diff --git a/.gitignore b/.gitignore index 493296158..01d4592b2 100644 --- a/.gitignore +++ b/.gitignore @@ -83,3 +83,6 @@ integration-tests/terminal-capture/scenarios/screenshots/ # storybook *storybook.log storybook-static + +# Dev symlink: qc-helper bundled skill docs (created by scripts/dev.js) +packages/core/src/skills/bundled/qc-helper/docs diff --git a/.qwen/skills/qwen-code-claw/SKILL.md b/.qwen/skills/qwen-code-claw/SKILL.md index f9a7b6a17..3a4b6e467 100644 --- a/.qwen/skills/qwen-code-claw/SKILL.md +++ b/.qwen/skills/qwen-code-claw/SKILL.md @@ -150,6 +150,59 @@ If every permission request is denied/cancelled and none are approved, `acpx` ex 4. Use `--format json` for automation and script integration 5. Use `--cwd` to manage context across multiple projects +## QwenCode Reference + +### CLI Commands + +| Command | Description | +| ----------- | ------------------------------- | +| `/help` | Show available commands | +| `/clear` | Clear conversation history | +| `/compress` | Compress history to save tokens | +| `/stats` | Show session info | +| `/auth` | Configure authentication | +| `/exit` | Exit Qwen Code | + +Full reference: https://raw.githubusercontent.com/QwenLM/qwen-code/refs/heads/main/docs/users/features/commands.md + +### Configuration + +Config files (highest priority first): CLI args > env vars > system > project (`.qwen/settings.json`) > user (`~/.qwen/settings.json`) > defaults. Format: JSONC with env var interpolation. + +Key settings: + +| Setting | Description | +| ---------------------------- | ----------------------------------------- | +| `model.name` | Model to use (e.g. `qwen-max`) | +| `tools.approvalMode` | `plan` / `default` / `auto_edit` / `yolo` | +| `permissions.allow/ask/deny` | Tool permission rules | +| `mcpServers.*` | MCP server configurations | + +Full reference: https://raw.githubusercontent.com/QwenLM/qwen-code/refs/heads/main/docs/users/configuration/settings.md + +### Authentication + +Supports Qwen OAuth (browser-based, 1000 free requests/day) and OpenAI-compatible API keys. + +Full reference: https://raw.githubusercontent.com/QwenLM/qwen-code/refs/heads/main/docs/users/configuration/auth.md + +### Model Providers + +Configure custom model providers via `modelProviders` in settings or environment variables (`OPENAI_API_KEY`, `OPENAI_BASE_URL`, `OPENAI_MODEL`). + +Full reference: https://raw.githubusercontent.com/QwenLM/qwen-code/refs/heads/main/docs/users/configuration/model-providers.md + +### Key Features + +| Feature | Description | Docs | +| ------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------- | +| Approval Mode | Control tool execution permissions | https://raw.githubusercontent.com/QwenLM/qwen-code/refs/heads/main/docs/users/features/approval-mode.md | +| MCP | Model Context Protocol server integration | https://raw.githubusercontent.com/QwenLM/qwen-code/refs/heads/main/docs/users/features/mcp.md | +| Skills | Reusable skill system via `/skill` | https://raw.githubusercontent.com/QwenLM/qwen-code/refs/heads/main/docs/users/features/skills.md | +| Sub-agents | Delegate tasks to specialized agents | https://raw.githubusercontent.com/QwenLM/qwen-code/refs/heads/main/docs/users/features/sub-agents.md | +| Sandbox | Secure code execution environment | https://raw.githubusercontent.com/QwenLM/qwen-code/refs/heads/main/docs/users/features/sandbox.md | +| Headless | Non-interactive / CI mode | https://raw.githubusercontent.com/QwenLM/qwen-code/refs/heads/main/docs/users/features/headless.md | + ## ACPX Reference ### Built-in Agent Registry diff --git a/README.md b/README.md index 7658b7ef0..5c0d83ab8 100644 --- a/README.md +++ b/README.md @@ -98,12 +98,22 @@ Your browser does not support the video tag. +## 🦞 Use Qwen Code for Coding Tasks in Claw + +Copy the prompt below and paste it into your agent: + +``` +Use Qwen Code as a coding agent. First, fetch and read this skill reference: +https://raw.githubusercontent.com/QwenLM/qwen-code/refs/heads/main/.qwen/skills/qwen-code-claw/SKILL.md +Then follow the instructions inside to install, authenticate, and use Qwen Code via acpx for all coding tasks. +``` + ## Authentication Qwen Code supports two authentication methods: - **Qwen OAuth (recommended & free)**: sign in with your `qwen.ai` account in a browser. -- **API-KEY**: use an API key to connect to any supported provider (OpenAI, Anthropic, Google GenAI, Alibaba Cloud Bailian, and other compatible endpoints). +- **API-KEY**: use an API key to connect to any supported provider (OpenAI, Anthropic, Google GenAI, Alibaba Cloud ModelStudio, and other compatible endpoints). #### Qwen OAuth (recommended) @@ -121,7 +131,7 @@ Choose **Qwen OAuth** and complete the browser flow. Your credentials are cached Use this if you want more flexibility over which provider and model to use. Supports multiple protocols: -- **OpenAI-compatible**: Alibaba Cloud Bailian, ModelScope, OpenAI, OpenRouter, and other OpenAI-compatible providers +- **OpenAI-compatible**: Alibaba Cloud ModelStudio, ModelScope, OpenAI, OpenRouter, and other OpenAI-compatible providers - **Anthropic**: Claude models - **Google GenAI**: Gemini models @@ -183,7 +193,7 @@ Use the `/model` command at any time to switch between all configured models. ##### More Examples
-Coding Plan (Alibaba Cloud Bailian) — fixed monthly fee, higher quotas +Coding Plan (Alibaba Cloud ModelStudio) — fixed monthly fee, higher quotas ```json { @@ -193,7 +203,7 @@ Use the `/model` command at any time to switch between all configured models. "id": "qwen3.5-plus", "name": "qwen3.5-plus (Coding Plan)", "baseUrl": "https://coding.dashscope.aliyuncs.com/v1", - "description": "qwen3.5-plus with thinking enabled from Bailian Coding Plan", + "description": "qwen3.5-plus with thinking enabled from ModelStudio Coding Plan", "envKey": "BAILIAN_CODING_PLAN_API_KEY", "generationConfig": { "extra_body": { @@ -205,14 +215,14 @@ Use the `/model` command at any time to switch between all configured models. "id": "qwen3-coder-plus", "name": "qwen3-coder-plus (Coding Plan)", "baseUrl": "https://coding.dashscope.aliyuncs.com/v1", - "description": "qwen3-coder-plus from Bailian Coding Plan", + "description": "qwen3-coder-plus from ModelStudio Coding Plan", "envKey": "BAILIAN_CODING_PLAN_API_KEY" }, { "id": "qwen3-coder-next", "name": "qwen3-coder-next (Coding Plan)", "baseUrl": "https://coding.dashscope.aliyuncs.com/v1", - "description": "qwen3-coder-next with thinking enabled from Bailian Coding Plan", + "description": "qwen3-coder-next with thinking enabled from ModelStudio Coding Plan", "envKey": "BAILIAN_CODING_PLAN_API_KEY", "generationConfig": { "extra_body": { @@ -224,7 +234,7 @@ Use the `/model` command at any time to switch between all configured models. "id": "glm-4.7", "name": "glm-4.7 (Coding Plan)", "baseUrl": "https://coding.dashscope.aliyuncs.com/v1", - "description": "glm-4.7 with thinking enabled from Bailian Coding Plan", + "description": "glm-4.7 with thinking enabled from ModelStudio Coding Plan", "envKey": "BAILIAN_CODING_PLAN_API_KEY", "generationConfig": { "extra_body": { @@ -236,7 +246,7 @@ Use the `/model` command at any time to switch between all configured models. "id": "kimi-k2.5", "name": "kimi-k2.5 (Coding Plan)", "baseUrl": "https://coding.dashscope.aliyuncs.com/v1", - "description": "kimi-k2.5 with thinking enabled from Bailian Coding Plan", + "description": "kimi-k2.5 with thinking enabled from ModelStudio Coding Plan", "envKey": "BAILIAN_CODING_PLAN_API_KEY", "generationConfig": { "extra_body": { @@ -260,7 +270,7 @@ Use the `/model` command at any time to switch between all configured models. } ``` -> Subscribe to the Coding Plan and get your API key at [Alibaba Cloud Bailian](https://modelstudio.console.aliyun.com/?tab=dashboard#/efm/coding_plan). +> Subscribe to the Coding Plan and get your API key at [Alibaba Cloud ModelStudio(Beijing)](https://bailian.console.aliyun.com/cn-beijing?tab=coding-plan#/efm/coding-plan-index) or [Alibaba Cloud ModelStudio(intl)](https://modelstudio.console.alibabacloud.com/?tab=coding-plan#/efm/coding-plan-index).
diff --git a/docs/users/configuration/auth.md b/docs/users/configuration/auth.md index 445e42bc5..8f43729cb 100644 --- a/docs/users/configuration/auth.md +++ b/docs/users/configuration/auth.md @@ -37,16 +37,16 @@ qwen auth qwen-oauth Use this if you want predictable costs with diverse model options and higher usage quotas. - **How it works**: Subscribe to the Coding Plan with a fixed monthly fee, then configure Qwen Code to use the dedicated endpoint and your subscription API key. -- **Requirements**: Obtain an active Coding Plan subscription from [Aliyun Bailian](https://bailian.console.aliyun.com/?tab=model#/efm/coding_plan) or [Alibaba Cloud](https://bailian.console.alibabacloud.com/?tab=model#/efm/coding_plan), depending on the region of your account. +- **Requirements**: Obtain an active Coding Plan subscription from [Alibaba Cloud ModelStudio(Beijing)](https://bailian.console.aliyun.com/cn-beijing?tab=coding-plan#/efm/coding-plan-index) or [Alibaba Cloud ModelStudio(intl)](https://modelstudio.console.alibabacloud.com/?tab=coding-plan#/efm/coding-plan-index), depending on the region of your account. - **Benefits**: Diverse model options, higher usage quotas, predictable monthly costs, access to a wide range of models (Qwen, GLM, Kimi, Minimax and more). -- **Cost & quota**: View [Aliyun Bailian Coding Plan documentation](https://bailian.console.aliyun.com/cn-beijing/?tab=doc#/doc/?type=model&url=3005961). +- **Cost & quota**: View Aliyun ModelStudio Coding Plan documentation[Beijing](https://bailian.console.aliyun.com/cn-beijing/?tab=doc#/doc/?type=model&url=3005961)[intl](https://modelstudio.console.alibabacloud.com/?tab=doc#/doc/?type=model&url=2840914). Alibaba Cloud Coding Plan is available in two regions: -| Region | Console URL | -| -------------------------------- | ---------------------------------------------------------------------------- | -| Aliyun Bailian (aliyun.com) | [bailian.console.aliyun.com](https://bailian.console.aliyun.com) | -| Alibaba Cloud (alibabacloud.com) | [bailian.console.alibabacloud.com](https://bailian.console.alibabacloud.com) | +| Region | Console URL | +| ---------------------------- | ---------------------------------------------------------------------------- | +| Aliyun ModelStudio (Beijing) | [bailian.console.aliyun.com](https://bailian.console.aliyun.com) | +| Alibaba Cloud (intl) | [bailian.console.alibabacloud.com](https://bailian.console.alibabacloud.com) | ### Interactive setup diff --git a/docs/users/configuration/model-providers.md b/docs/users/configuration/model-providers.md index bcfc2cc75..83a66e8de 100644 --- a/docs/users/configuration/model-providers.md +++ b/docs/users/configuration/model-providers.md @@ -51,6 +51,10 @@ This auth type supports not only OpenAI's official API but also any OpenAI-compa ```json { + "env": { + "OPENAI_API_KEY": "sk-your-actual-openai-key-here", + "OPENROUTER_API_KEY": "sk-or-your-actual-openrouter-key-here" + }, "modelProviders": { "openai": [ { @@ -117,6 +121,9 @@ This auth type supports not only OpenAI's official API but also any OpenAI-compa ```json { + "env": { + "ANTHROPIC_API_KEY": "sk-ant-your-actual-anthropic-key-here" + }, "modelProviders": { "anthropic": [ { @@ -157,6 +164,9 @@ This auth type supports not only OpenAI's official API but also any OpenAI-compa ```json { + "env": { + "GEMINI_API_KEY": "AIza-your-actual-gemini-key-here" + }, "modelProviders": { "gemini": [ { @@ -191,6 +201,11 @@ Most local inference servers (vLLM, Ollama, LM Studio, etc.) provide an OpenAI-c ```json { + "env": { + "OLLAMA_API_KEY": "ollama", + "VLLM_API_KEY": "not-needed", + "LMSTUDIO_API_KEY": "lm-studio" + }, "modelProviders": { "openai": [ { @@ -255,6 +270,27 @@ export VLLM_API_KEY="not-needed" > > The `extra_body` parameter is **only supported for OpenAI-compatible providers** (`openai`, `qwen-oauth`). It is ignored for Anthropic, and Gemini providers. +> [!note] +> +> **About `envKey`**: The `envKey` field specifies the **name of an environment variable**, not the actual API key value. For the configuration to work, you need to ensure the corresponding environment variable is set with your real API key. There are two ways to do this: +> +> - **Option 1: Using a `.env` file** (recommended for security): +> ```bash +> # ~/.qwen/.env (or project root) +> OPENAI_API_KEY=sk-your-actual-key-here +> ``` +> Be sure to add `.env` to your `.gitignore` to prevent accidentally committing secrets. +> - **Option 2: Using the `env` field in `settings.json`** (as shown in the examples above): +> ```json +> { +> "env": { +> "OPENAI_API_KEY": "sk-your-actual-key-here" +> } +> } +> ``` +> +> Each provider example includes an `env` field to illustrate how the API key should be configured. + ## Alibaba Cloud Coding Plan Alibaba Cloud Coding Plan provides a pre-configured set of Qwen models optimized for coding tasks. This feature is available for users with Alibaba Cloud Coding Plan API access and offers a simplified setup experience with automatic model configuration updates. diff --git a/docs/users/features/_meta.ts b/docs/users/features/_meta.ts index 9cf6d403f..cb083c35a 100644 --- a/docs/users/features/_meta.ts +++ b/docs/users/features/_meta.ts @@ -13,4 +13,5 @@ export default { 'token-caching': 'Token Caching', sandbox: 'Sandboxing', language: 'i18n', + hooks: 'Hooks', }; diff --git a/docs/users/features/hooks.md b/docs/users/features/hooks.md new file mode 100644 index 000000000..5d32118c3 --- /dev/null +++ b/docs/users/features/hooks.md @@ -0,0 +1,715 @@ +# Qwen Code Hooks Documentation + +## Overview + +Qwen Code hooks provide a powerful mechanism for extending and customizing the behavior of the Qwen Code application. Hooks allow users to execute custom scripts or programs at specific points in the application lifecycle, such as before tool execution, after tool execution, at session start/end, and during other key events. + +> **⚠️ EXPERIMENTAL FEATURE** +> +> Hooks are currently in an experimental stage. To enable hooks, start Qwen Code with the `--experimental-hooks` flag: +> +> ```bash +> qwen --experimental-hooks +> ``` + +## What are Hooks? + +Hooks are user-defined scripts or programs that are automatically executed by Qwen Code at predefined points in the application flow. They allow users to: + +- Monitor and audit tool usage +- Enforce security policies +- Inject additional context into conversations +- Customize application behavior based on events +- Integrate with external systems and services +- Modify tool inputs or responses programmatically + +## Hook Architecture + +The Qwen Code hook system consists of several key components: + +1. **Hook Registry**: Stores and manages all configured hooks +2. **Hook Planner**: Determines which hooks should run for each event +3. **Hook Runner**: Executes individual hooks with proper context +4. **Hook Aggregator**: Combines results from multiple hooks +5. **Hook Event Handler**: Coordinates the firing of hooks for events + +## Hook Events + +Hooks fire at specific points during a Qwen Code session. When an event fires and a matcher matches, Qwen Code passes JSON context about the event to your hook handler. For command hooks, input arrives on stdin. Your handler can inspect the input, take action, and optionally return a decision. Some events fire once per session, while others fire repeatedly inside the agentic loop. + +
+Hook Lifecycle Diagram +
+ +The following table lists all available hook events in Qwen Code: + +| Event Name | Description | Use Case | +| -------------------- | ------------------------------------------- | ----------------------------------------------- | +| `PreToolUse` | Fired before tool execution | Permission checking, input validation, logging | +| `PostToolUse` | Fired after successful tool execution | Logging, output processing, monitoring | +| `PostToolUseFailure` | Fired when tool execution fails | Error handling, alerting, remediation | +| `Notification` | Fired when notifications are sent | Notification customization, logging | +| `UserPromptSubmit` | Fired when user submits a prompt | Input processing, validation, context injection | +| `SessionStart` | Fired when a new session starts | Initialization, context setup | +| `Stop` | Fired before Qwen concludes its response | Finalization, cleanup | +| `SubagentStart` | Fired when a subagent starts | Subagent initialization | +| `SubagentStop` | Fired when a subagent stops | Subagent finalization | +| `PreCompact` | Fired before conversation compaction | Pre-compaction processing | +| `SessionEnd` | Fired when a session ends | Cleanup, reporting | +| `PermissionRequest` | Fired when permission dialogs are displayed | Permission automation, policy enforcement | + +## Input/Output Rules + +### Hook Input Structure + +All hooks receive standardized input in JSON format through stdin. Common fields included in every hook event: + +```json +{ + "session_id": "string", + "transcript_path": "string", + "cwd": "string", + "hook_event_name": "string", + "timestamp": "string" +} +``` + +Event-specific fields are added based on the hook type. Below are the event-specific fields for each hook event: + +### Individual Hook Event Details + +#### PreToolUse + +**Purpose**: Executed before a tool is used to allow for permission checks, input validation, or context injection. + +**Event-specific fields**: + +```json +{ + "permission_mode": "default | plan | auto_edit | yolo", + "tool_name": "name of the tool being executed", + "tool_input": "object containing the tool's input parameters", + "tool_use_id": "unique identifier for this tool use instance" +} +``` + +**Output Options**: + +- `hookSpecificOutput.permissionDecision`: "allow", "deny", or "ask" (REQUIRED) +- `hookSpecificOutput.permissionDecisionReason`: explanation for the decision (REQUIRED) +- `hookSpecificOutput.updatedInput`: modified tool input parameters to use instead of original +- `hookSpecificOutput.additionalContext`: additional context information + +**Note**: While standard hook output fields like `decision` and `reason` are technically supported by the underlying class, the official interface expects the `hookSpecificOutput` with `permissionDecision` and `permissionDecisionReason`. + +**Example Output**: + +```json +{ + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "allow", + "permissionDecisionReason": "My reason here", + "updatedInput": { + "field_to_modify": "new value" + }, + "additionalContext": "Current environment: production. Proceed with caution." + } +} +``` + +#### PostToolUse + +**Purpose**: Executed after a tool completes successfully to process results, log outcomes, or inject additional context. + +**Event-specific fields**: + +```json +{ + "permission_mode": "default | plan | auto_edit | yolo", + "tool_name": "name of the tool that was executed", + "tool_input": "object containing the tool's input parameters", + "tool_response": "object containing the tool's response", + "tool_use_id": "unique identifier for this tool use instance" +} +``` + +**Output Options**: + +- `decision`: "allow", "deny", "block" (defaults to "allow" if not specified) +- `reason`: reason for the decision +- `hookSpecificOutput.additionalContext`: additional information to be included + +**Example Output**: + +```json +{ + "decision": "allow", + "reason": "Tool executed successfully", + "hookSpecificOutput": { + "additionalContext": "File modification recorded in audit log" + } +} +``` + +#### PostToolUseFailure + +**Purpose**: Executed when a tool execution fails to handle errors, send alerts, or record failures. + +**Event-specific fields**: + +```json +{ + "permission_mode": "default | plan | auto_edit | yolo", + "tool_use_id": "unique identifier for the tool use", + "tool_name": "name of the tool that failed", + "tool_input": "object containing the tool's input parameters", + "error": "error message describing the failure", + "is_interrupt": "boolean indicating if failure was due to user interruption (optional)" +} +``` + +**Output Options**: + +- `hookSpecificOutput.additionalContext`: error handling information +- Standard hook output fields + +**Example Output**: + +```json +{ + "hookSpecificOutput": { + "additionalContext": "Error: File not found. Failure logged in monitoring system." + } +} +``` + +#### UserPromptSubmit + +**Purpose**: Executed when the user submits a prompt to modify, validate, or enrich the input. + +**Event-specific fields**: + +```json +{ + "prompt": "the user's submitted prompt text" +} +``` + +**Output Options**: + +- `decision`: "allow", "deny", "block", or "ask" +- `reason`: human-readable explanation for the decision +- `hookSpecificOutput.additionalContext`: additional context to append to the prompt (optional) + +**Note**: Since UserPromptSubmitOutput extends HookOutput, all standard fields are available but only additionalContext in hookSpecificOutput is specifically defined for this event. + +**Example Output**: + +```json +{ + "decision": "allow", + "reason": "Prompt reviewed and approved", + "hookSpecificOutput": { + "additionalContext": "Remember to follow company coding standards." + } +} +``` + +#### SessionStart + +**Purpose**: Executed when a new session starts to perform initialization tasks. + +**Event-specific fields**: + +```json +{ + "permission_mode": "default | plan | auto_edit | yolo", + "source": "startup | resume | clear | compact", + "model": "the model being used", + "agent_type": "the type of agent if applicable (optional)" +} +``` + +**Output Options**: + +- `hookSpecificOutput.additionalContext`: context to be available in the session +- Standard hook output fields + +**Example Output**: + +```json +{ + "hookSpecificOutput": { + "additionalContext": "Session started with security policies enabled." + } +} +``` + +#### SessionEnd + +**Purpose**: Executed when a session ends to perform cleanup tasks. + +**Event-specific fields**: + +```json +{ + "reason": "clear | logout | prompt_input_exit | bypass_permissions_disabled | other" +} +``` + +**Output Options**: + +- Standard hook output fields (typically not used for blocking) + +#### Stop + +**Purpose**: Executed before Qwen concludes its response to provide final feedback or summaries. + +**Event-specific fields**: + +```json +{ + "stop_hook_active": "boolean indicating if stop hook is active", + "last_assistant_message": "the last message from the assistant" +} +``` + +**Output Options**: + +- `decision`: "allow", "deny", "block", or "ask" +- `reason`: human-readable explanation for the decision +- `stopReason`: feedback to include in the stop response +- `continue`: set to false to stop execution +- `hookSpecificOutput.additionalContext`: additional context information + +**Note**: Since StopOutput extends HookOutput, all standard fields are available but the stopReason field is particularly relevant for this event. + +**Example Output**: + +```json +{ + "decision": "block", + "reason": "Must be provided when Qwen Code is blocked from stopping" +} +``` + +#### SubagentStart + +**Purpose**: Executed when a subagent (like the Task tool) is started to set up context or permissions. + +**Event-specific fields**: + +```json +{ + "permission_mode": "default | plan | auto_edit | yolo", + "agent_id": "identifier for the subagent", + "agent_type": "type of agent (Bash, Explorer, Plan, Custom, etc.)" +} +``` + +**Output Options**: + +- `hookSpecificOutput.additionalContext`: initial context for the subagent +- Standard hook output fields + +**Example Output**: + +```json +{ + "hookSpecificOutput": { + "additionalContext": "Subagent initialized with restricted permissions." + } +} +``` + +#### SubagentStop + +**Purpose**: Executed when a subagent finishes to perform finalization tasks. + +**Event-specific fields**: + +```json +{ + "permission_mode": "default | plan | auto_edit | yolo", + "stop_hook_active": "boolean indicating if stop hook is active", + "agent_id": "identifier for the subagent", + "agent_type": "type of agent", + "agent_transcript_path": "path to the subagent's transcript", + "last_assistant_message": "the last message from the subagent" +} +``` + +**Output Options**: + +- `decision`: "allow", "deny", "block", or "ask" +- `reason`: human-readable explanation for the decision + +**Example Output**: + +```json +{ + "decision": "block", + "reason": "Must be provided when Qwen Code is blocked from stopping" +} +``` + +#### PreCompact + +**Purpose**: Executed before conversation compaction to prepare or log the compaction. + +**Event-specific fields**: + +```json +{ + "trigger": "manual | auto", + "custom_instructions": "custom instructions currently set" +} +``` + +**Output Options**: + +- `hookSpecificOutput.additionalContext`: context to include before compaction +- Standard hook output fields + +**Example Output**: + +```json +{ + "hookSpecificOutput": { + "additionalContext": "Compacting conversation to maintain optimal context window." + } +} +``` + +#### Notification + +**Purpose**: Executed when notifications are sent to customize or intercept them. + +**Event-specific fields**: + +```json +{ + "message": "notification message content", + "title": "notification title (optional)", + "notification_type": "permission_prompt | idle_prompt | auth_success" +} +``` + +> **Note**: `elicitation_dialog` type is defined but not currently implemented. + +**Output Options**: + +- `hookSpecificOutput.additionalContext`: additional information to include +- Standard hook output fields + +**Example Output**: + +```json +{ + "hookSpecificOutput": { + "additionalContext": "Notification processed by monitoring system." + } +} +``` + +#### PermissionRequest + +**Purpose**: Executed when permission dialogs are displayed to automate decisions or update permissions. + +**Event-specific fields**: + +```json +{ + "permission_mode": "default | plan | auto_edit | yolo", + "tool_name": "name of the tool requesting permission", + "tool_input": "object containing the tool's input parameters", + "permission_suggestions": "array of suggested permissions (optional)" +} +``` + +**Output Options**: + +- `hookSpecificOutput.decision`: structured object with permission decision details: + - `behavior`: "allow" or "deny" + - `updatedInput`: modified tool input (optional) + - `updatedPermissions`: modified permissions (optional) + - `message`: message to show to user (optional) + - `interrupt`: whether to interrupt the workflow (optional) + +**Example Output**: + +```json +{ + "hookSpecificOutput": { + "decision": { + "behavior": "allow", + "message": "Permission granted based on security policy", + "interrupt": false + } + } +} +``` + +## Hook Configuration + +Hooks are configured in Qwen Code settings, typically in `.qwen/settings.json` or user configuration files: + +```json +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "^bash$", // Regex to match tool names + "sequential": false, // Whether to run hooks sequentially + "hooks": [ + { + "type": "command", + "command": "/path/to/script.sh", + "name": "security-check", + "description": "Run security checks before tool execution", + "timeout": 30000 + } + ] + } + ], + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "echo 'Session started'", + "name": "session-init" + } + ] + } + ] + } +} +``` + +### Matcher Patterns + +Matchers allow filtering hooks based on context. Not all hook events support matchers: + +| Event Type | Events | Matcher Support | Matcher Target (Values) | +| ------------------- | ---------------------------------------------------------------------- | --------------- | -------------------------------------------------------------------------------------- | +| Tool Events | `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | ✅ Yes (regex) | Tool name: `bash`, `read_file`, `write_file`, `edit`, `glob`, `grep_search`, etc. | +| Subagent Events | `SubagentStart`, `SubagentStop` | ✅ Yes (regex) | Agent type: `Bash`, `Explorer`, etc. | +| Session Events | `SessionStart` | ✅ Yes (regex) | Source: `startup`, `resume`, `clear`, `compact` | +| Session Events | `SessionEnd` | ✅ Yes (regex) | Reason: `clear`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` | +| Notification Events | `Notification` | ✅ Yes (exact) | Type: `permission_prompt`, `idle_prompt`, `auth_success` | +| Compact Events | `PreCompact` | ✅ Yes (exact) | Trigger: `manual`, `auto` | +| Prompt Events | `UserPromptSubmit` | ❌ No | N/A | +| Stop Events | `Stop` | ❌ No | N/A | + +**Matcher Syntax**: + +- Regex pattern matched against the target field +- Empty string `""` or `"*"` matches all events of that type +- Standard regex syntax supported (e.g., `^bash$`, `read.*`, `(bash|run_shell_command)`) + +**Examples**: + +```json +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "^bash$", // Only match bash tool + "hooks": [...] + }, + { + "matcher": "read.*", // Match read_file, read_multiple_files, etc. + "hooks": [...] + }, + { + "matcher": "", // Match all tools (same as "*" or omitting matcher) + "hooks": [...] + } + ], + "SubagentStart": [ + { + "matcher": "^(Bash|Explorer)$", // Only match Bash and Explorer agents + "hooks": [...] + } + ], + "SessionStart": [ + { + "matcher": "^(startup|resume)$", // Only match startup and resume sources + "hooks": [...] + } + ] + } +} +``` + +## Hook Execution + +### Parallel vs Sequential Execution + +- By default, hooks execute in parallel for better performance +- Use `sequential: true` in hook definition to enforce order-dependent execution +- Sequential hooks can modify input for subsequent hooks in the chain + +### Security Model + +- Hooks run in the user's environment with user privileges +- Project-level hooks require trusted folder status +- Timeouts prevent hanging hooks (default: 60 seconds) + +### Exit Codes + +Hook scripts communicate their result through exit codes: + +| Exit Code | Meaning | Behavior | +| --------- | ------------------ | ----------------------------------------------- | +| `0` | Success | stdout/stderr not shown | +| `2` | Blocking error | Show stderr to model and block tool call | +| Other | Non-blocking error | Show stderr to user only but continue tool call | + +**Examples**: + +```bash +#!/bin/bash + +# Success (exit 0 is default, can be omitted) +echo '{"decision": "allow"}' +exit 0 + +# Blocking error - prevents operation +echo "Dangerous operation blocked by security policy" >&2 +exit 2 +``` + +> **Note**: If no exit code is specified, the script defaults to `0` (success). + +## Best Practices + +### Example 1: Security Validation Hook + +A PreToolUse hook that logs and potentially blocks dangerous commands: + +**security_check.sh** + +```bash +#!/bin/bash + +# Read input from stdin +INPUT=$(cat) + +# Parse the input to extract tool info +TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name') +TOOL_INPUT=$(echo "$INPUT" | jq -r '.tool_input') + +# Check for potentially dangerous operations +if echo "$TOOL_INPUT" | grep -qiE "(rm.*-rf|mv.*\/|chmod.*777)"; then + echo '{ + "decision": "deny", + "reason": "Potentially dangerous operation detected", + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "deny", + "permissionDecisionReason": "Dangerous command blocked by security policy" + } + }' + exit 2 # Blocking error +fi + +# Allow the operation with a log +echo "INFO: Tool $TOOL_NAME executed safely at $(date)" >> /var/log/qwen-security.log + +# Allow with additional context +echo '{ + "decision": "allow", + "reason": "Operation approved by security checker", + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "allow", + "permissionDecisionReason": "Security check passed", + "additionalContext": "Command approved by security policy" + } +}' +exit 0 +``` + +Configure in `.qwen/settings.json`: + +```json +{ + "hooks": { + "PreToolUse": [ + { + "hooks": [ + { + "type": "command", + "command": "${SECURITY_CHECK_SCRIPT}", + "name": "security-checker", + "description": "Security validation for bash commands", + "timeout": 10000 + } + ] + } + ] + } +} +``` + +### Example 2: User Prompt Validation Hook + +A UserPromptSubmit hook that validates user prompts for sensitive information and provides context for long prompts: + +**prompt_validator.py** + +```python +import json +import sys +import re + +# Load input from stdin +try: + input_data = json.load(sys.stdin) +except json.JSONDecodeError as e: + print(f"Error: Invalid JSON input: {e}", file=sys.stderr) + exit(1) + +user_prompt = input_data.get("prompt", "") + +# Sensitive words list +sensitive_words = ["password", "secret", "token", "api_key"] + +# Check for sensitive information +for word in sensitive_words: + if re.search(rf"\b{word}\b", user_prompt.lower()): + # Block prompts containing sensitive information + output = { + "decision": "block", + "reason": f"Prompt contains sensitive information '{word}'. Please remove sensitive content and resubmit.", + "hookSpecificOutput": { + "hookEventName": "UserPromptSubmit" + } + } + print(json.dumps(output)) + exit(0) + +# Check prompt length and add warning context if too long +if len(user_prompt) > 1000: + output = { + "hookSpecificOutput": { + "hookEventName": "UserPromptSubmit", + "additionalContext": "Note: User submitted a long prompt. Please read carefully and ensure all requirements are understood." + } + } + print(json.dumps(output)) + exit(0) + +# No processing needed for normal cases +exit(0) +``` + +## Troubleshooting + +- Check application logs for hook execution details +- Verify hook script permissions and executability +- Ensure proper JSON formatting in hook outputs +- Use specific matcher patterns to avoid unintended hook execution diff --git a/docs/users/features/lsp.md b/docs/users/features/lsp.md index c0ed7da9a..2af14ed01 100644 --- a/docs/users/features/lsp.md +++ b/docs/users/features/lsp.md @@ -4,7 +4,7 @@ Qwen Code provides native Language Server Protocol (LSP) support, enabling advan ## Overview -LSP support in Qwen Code works by connecting to language servers that understand your code. When you work with TypeScript, Python, Go, or other supported languages, Qwen Code can automatically start the appropriate language server and use it to: +LSP support in Qwen Code works by connecting to language servers that understand your code. Once you configure servers via `.lsp.json` (or extensions), Qwen Code can start them and use them to: - Navigate to symbol definitions - Find all references to a symbol @@ -21,7 +21,7 @@ LSP is an experimental feature in Qwen Code. To enable it, use the `--experiment qwen --experimental-lsp ``` -For most common languages, Qwen Code will automatically detect and start the appropriate language server if it's installed on your system. +LSP servers are configuration-driven. You must define them in `.lsp.json` (or via extensions) for Qwen Code to start them. ### Prerequisites @@ -33,6 +33,8 @@ You need to have the language server for your programming language installed: | Python | pylsp | `pip install python-lsp-server` | | Go | gopls | `go install golang.org/x/tools/gopls@latest` | | Rust | rust-analyzer | [Installation guide](https://rust-analyzer.github.io/manual.html#installation) | +| C/C++ | clangd | Install LLVM/clangd via your package manager | +| Java | jdtls | Install JDTLS and a JDK | ## Configuration @@ -57,30 +59,71 @@ You can configure language servers using a `.lsp.json` file in your project root } ``` +### C/C++ (clangd) configuration + +Dependencies: + +- clangd (LLVM) must be installed and available in PATH. +- A compile database (`compile_commands.json`) or `compile_flags.txt` is required for accurate results. + +Example: + +```json +{ + "cpp": { + "command": "clangd", + "args": [ + "--background-index", + "--clang-tidy", + "--header-insertion=iwyu", + "--completion-style=detailed" + ] + } +} +``` + +### Java (jdtls) configuration + +Dependencies: + +- JDK installed and available in PATH (`java`). +- JDTLS installed and available in PATH (`jdtls`). + +Example: + +```json +{ + "java": { + "command": "jdtls", + "args": ["-configuration", ".jdtls-config", "-data", ".jdtls-workspace"] + } +} +``` + ### Configuration Options #### Required Fields -| Option | Type | Description | -| --------------------- | ------ | ------------------------------------------------- | -| `command` | string | Command to start the LSP server (must be in PATH) | -| `extensionToLanguage` | object | Maps file extensions to language identifiers | +| Option | Type | Description | +| --------- | ------ | ------------------------------------------------- | +| `command` | string | Command to start the LSP server (must be in PATH) | #### Optional Fields -| Option | Type | Default | Description | -| ----------------------- | -------- | --------- | ------------------------------------------------------ | -| `args` | string[] | `[]` | Command line arguments | -| `transport` | string | `"stdio"` | Transport type: `stdio` or `socket` | -| `env` | object | - | Environment variables | -| `initializationOptions` | object | - | LSP initialization options | -| `settings` | object | - | Server settings via `workspace/didChangeConfiguration` | -| `workspaceFolder` | string | - | Override workspace folder | -| `startupTimeout` | number | `10000` | Startup timeout in milliseconds | -| `shutdownTimeout` | number | `5000` | Shutdown timeout in milliseconds | -| `restartOnCrash` | boolean | `false` | Auto-restart on crash | -| `maxRestarts` | number | `3` | Maximum restart attempts | -| `trustRequired` | boolean | `true` | Require trusted workspace | +| Option | Type | Default | Description | +| ----------------------- | -------- | --------- | ------------------------------------------------------- | +| `args` | string[] | `[]` | Command line arguments | +| `transport` | string | `"stdio"` | Transport type: `stdio`, `tcp`, or `socket` | +| `env` | object | - | Environment variables | +| `initializationOptions` | object | - | LSP initialization options | +| `settings` | object | - | Server settings via `workspace/didChangeConfiguration` | +| `extensionToLanguage` | object | - | Maps file extensions to language identifiers | +| `workspaceFolder` | string | - | Override workspace folder (must be within project root) | +| `startupTimeout` | number | `10000` | Startup timeout in milliseconds | +| `shutdownTimeout` | number | `5000` | Shutdown timeout in milliseconds | +| `restartOnCrash` | boolean | `false` | Auto-restart on crash | +| `maxRestarts` | number | `3` | Maximum restart attempts | +| `trustRequired` | boolean | `true` | Require trusted workspace | ### TCP/Socket Transport @@ -269,7 +312,7 @@ LSP servers are only started in trusted workspaces by default. This is because l ### Trust Controls -- **Trusted Workspace**: LSP servers start automatically +- **Trusted Workspace**: LSP servers start if configured - **Untrusted Workspace**: LSP servers won't start unless `trustRequired: false` is set in the server configuration To mark a workspace as trusted, use the `/trust` command or configure trusted folders in settings. diff --git a/integration-tests/hooks-command.test.ts b/integration-tests/hooks-command.test.ts new file mode 100644 index 000000000..0fb67f00f --- /dev/null +++ b/integration-tests/hooks-command.test.ts @@ -0,0 +1,71 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { TestRig } from './test-helper.js'; + +describe('/hooks command', () => { + let rig: TestRig; + + beforeEach(async () => { + rig = new TestRig(); + await rig.setup('/hooks command test'); + }); + + afterEach(async () => { + await rig.cleanup(); + }); + + it('should display hooks dialog when /hooks command is entered', async () => { + const { ptyProcess } = rig.runInteractive(); + + let output = ''; + ptyProcess.onData((data) => { + output += data; + }); + + // Wait for CLI to be ready + const isReady = await rig.waitForText('Type your message', 15000); + expect(isReady, 'CLI did not start up in interactive mode correctly').toBe( + true, + ); + + // Type /hooks command + ptyProcess.write('/hooks'); + + // Wait a bit for the command to be typed + await new Promise((resolve) => setTimeout(resolve, 500)); + + // Press Enter to execute the command + ptyProcess.write('\r'); + + // Wait for hooks dialog to appear + const showedHooksDialog = await rig.poll( + () => output.includes('Hooks') || output.includes('hooks'), + 5000, + 200, + ); + + // Print output for debugging + console.log('Output after /hooks command:'); + console.log(output); + + expect(showedHooksDialog, `Hooks dialog not shown. Output: ${output}`).toBe( + true, + ); + + // Close the dialog with Escape + ptyProcess.write('\x1b'); + + // Wait a bit + await new Promise((resolve) => setTimeout(resolve, 500)); + + // Exit with Ctrl+C twice + ptyProcess.write('\x03'); + await new Promise((resolve) => setTimeout(resolve, 300)); + ptyProcess.write('\x03'); + }); +}); diff --git a/integration-tests/list_directory.test.ts b/integration-tests/list_directory.test.ts index 6d3cc37ad..a60945ba4 100644 --- a/integration-tests/list_directory.test.ts +++ b/integration-tests/list_directory.test.ts @@ -29,7 +29,7 @@ describe('list_directory', () => { 50, // check every 50ms ); - const prompt = `Can you list the files in the current directory.`; + const prompt = `Use the list_directory tool to list the files in the current directory.`; const result = await rig.run(prompt); diff --git a/integration-tests/sdk-typescript/abort-and-lifecycle.test.ts b/integration-tests/sdk-typescript/abort-and-lifecycle.test.ts index f9bd77963..566f63c21 100644 --- a/integration-tests/sdk-typescript/abort-and-lifecycle.test.ts +++ b/integration-tests/sdk-typescript/abort-and-lifecycle.test.ts @@ -11,6 +11,7 @@ import { AbortError, isAbortError, isSDKAssistantMessage, + isSDKPartialAssistantMessage, isSDKResultMessage, type TextBlock, type SDKUserMessage, @@ -38,11 +39,8 @@ describe('AbortController and Process Lifecycle (E2E)', () => { describe('Basic AbortController Usage', () => { it('should support AbortController cancellation', async () => { const controller = new AbortController(); - - // Abort after 5 seconds - setTimeout(() => { - controller.abort(); - }, 5000); + const TARGET_CHARS = 50; + let accumulatedText = ''; const q = query({ prompt: 'Write a very long story about TypeScript programming', @@ -50,23 +48,38 @@ describe('AbortController and Process Lifecycle (E2E)', () => { ...SHARED_TEST_OPTIONS, cwd: testDir, abortController: controller, + includePartialMessages: true, debug: false, }, }); try { for await (const message of q) { - if (isSDKAssistantMessage(message)) { + if (isSDKPartialAssistantMessage(message)) { + // Handle partial messages from streaming + if ( + message.event.type === 'content_block_delta' && + message.event.delta.type === 'text_delta' + ) { + accumulatedText += message.event.delta.text; + + // Abort when we have enough content to verify + if (accumulatedText.length >= TARGET_CHARS) { + controller.abort(); + } + } + } else if (isSDKAssistantMessage(message)) { + // Handle complete assistant messages const textBlocks = message.message.content.filter( (block): block is TextBlock => block.type === 'text', ); - const text = textBlocks - .map((b) => b.text) - .join('') - .slice(0, 100); + const chunkText = textBlocks.map((b) => b.text).join(''); + accumulatedText += chunkText; - // Should receive some content before abort - expect(text.length).toBeGreaterThan(0); + // Abort when we have enough content to verify + if (accumulatedText.length >= TARGET_CHARS) { + controller.abort(); + } } } @@ -74,6 +87,8 @@ describe('AbortController and Process Lifecycle (E2E)', () => { expect(false).toBe(true); } catch (error) { expect(isAbortError(error)).toBe(true); + // Should have accumulated at least TARGET_CHARS before abort + expect(accumulatedText.length).toBeGreaterThanOrEqual(TARGET_CHARS); } finally { await q.close(); } @@ -347,7 +362,8 @@ describe('AbortController and Process Lifecycle (E2E)', () => { session_id: sessionId, message: { role: 'user', - content: 'Write "updated" to test.txt.', + content: + 'Write "updated" to test.txt. Stop if any exception occurs.', }, parent_tool_use_id: null, }; diff --git a/integration-tests/sdk-typescript/test-helper.ts b/integration-tests/sdk-typescript/test-helper.ts index c426f6725..8274398cb 100644 --- a/integration-tests/sdk-typescript/test-helper.ts +++ b/integration-tests/sdk-typescript/test-helper.ts @@ -11,7 +11,7 @@ */ import { mkdir, writeFile, readFile, rm, chmod } from 'node:fs/promises'; -import { join } from 'node:path'; +import { dirname, join } from 'node:path'; import { existsSync } from 'node:fs'; import type { SDKMessage, @@ -121,6 +121,9 @@ export class SDKTestHelper { throw new Error('Test directory not initialized. Call setup() first.'); } const filePath = join(this.testDir, fileName); + // Ensure parent directories exist before writing the file + const parentDir = dirname(filePath); + await mkdir(parentDir, { recursive: true }); await writeFile(filePath, content, 'utf-8'); return filePath; } diff --git a/integration-tests/sdk-typescript/tool-control.test.ts b/integration-tests/sdk-typescript/tool-control.test.ts index aecb98ae6..c4b48fc82 100644 --- a/integration-tests/sdk-typescript/tool-control.test.ts +++ b/integration-tests/sdk-typescript/tool-control.test.ts @@ -173,7 +173,9 @@ describe('Tool Control Parameters (E2E)', () => { if (writeFileResults.length > 0) { // Tool was called but should have permission declined message for (const result of writeFileResults) { - expect(result.content).toMatch(/permission.*declined/i); + expect(result.content).toMatch( + /permission.*(?:declined|denied)|denied.*permission/i, + ); } } @@ -221,14 +223,18 @@ describe('Tool Control Parameters (E2E)', () => { const listDirResults = findToolResults(messages, 'list_directory'); if (listDirResults.length > 0) { for (const result of listDirResults) { - expect(result.content).toMatch(/permission.*declined/i); + expect(result.content).toMatch( + /permission.*(?:declined|denied)|denied.*permission/i, + ); } } const shellResults = findToolResults(messages, 'run_shell_command'); if (shellResults.length > 0) { for (const result of shellResults) { - expect(result.content).toMatch(/permission.*declined/i); + expect(result.content).toMatch( + /permission.*(?:declined|denied)|denied.*permission/i, + ); } } } finally { @@ -263,7 +269,9 @@ describe('Tool Control Parameters (E2E)', () => { // All shell commands should have permission declined const shellResults = findToolResults(messages, 'run_shell_command'); for (const result of shellResults) { - expect(result.content).toMatch(/permission.*declined/i); + expect(result.content).toMatch( + /permission.*(?:declined|denied)|denied.*permission/i, + ); } } finally { await q.close(); @@ -303,7 +311,9 @@ describe('Tool Control Parameters (E2E)', () => { if (writeFileResults.length > 0) { // Tool was called but should have permission declined message (exclude takes priority) for (const result of writeFileResults) { - expect(result.content).toMatch(/permission.*declined/i); + expect(result.content).toMatch( + /permission.*(?:declined|denied)|denied.*permission/i, + ); } } @@ -316,6 +326,176 @@ describe('Tool Control Parameters (E2E)', () => { }, TEST_TIMEOUT, ); + + it( + 'should block read operations on specific path patterns with excludeTools', + async () => { + await helper.createFile('.env', 'SECRET=password'); + await helper.createFile('config.json', '{"key": "value"}'); + await helper.createFile('data.txt', 'public data'); + + const q = query({ + prompt: + 'Read .env file, read config.json, and read data.txt. Tell me about their contents.', + options: { + ...SHARED_TEST_OPTIONS, + cwd: testDir, + permissionMode: 'yolo', + // Block reading .env files + excludeTools: ['Read(.env)'], + debug: false, + }, + }); + + const messages: SDKMessage[] = []; + + try { + for await (const message of q) { + messages.push(message); + } + + const toolCalls = findToolCalls(messages); + const readCalls = toolCalls.filter( + (tc) => tc.toolUse.name === 'read_file', + ); + + // Should have attempted to read files + expect(readCalls.length).toBeGreaterThan(0); + + // Check that .env read was blocked + const envReadResults = findToolResults(messages, 'read_file').filter( + (result) => { + return result.content.includes('.env'); + }, + ); + if (envReadResults.length > 0) { + for (const result of envReadResults) { + expect(result.content).toMatch( + /permission.*(?:declined|denied)|denied.*permission/i, + ); + } + } + } finally { + await q.close(); + } + }, + TEST_TIMEOUT, + ); + + it( + 'should block edit operations on specific path patterns with excludeTools', + async () => { + await helper.createFile('src/app.ts', 'const app = "original";'); + await helper.createFile('test/spec.ts', 'describe("test", () => {});'); + await helper.createFile('readme.md', '# Readme'); + + const q = query({ + prompt: + 'Edit src/app.ts to add a semicolon, edit test/spec.ts to add a test, and edit readme.md.', + options: { + ...SHARED_TEST_OPTIONS, + cwd: testDir, + permissionMode: 'yolo', + coreTools: ['read_file', 'edit', 'write_file', 'list_directory'], + // Block editing files in /src/** directory + excludeTools: ['Edit(/src/**)'], + debug: false, + }, + }); + + const messages: SDKMessage[] = []; + + try { + for await (const message of q) { + messages.push(message); + } + + const toolCalls = findToolCalls(messages); + const editCalls = toolCalls.filter( + (tc) => tc.toolUse.name === 'edit', + ); + + // Should have attempted edits + expect(editCalls.length).toBeGreaterThan(0); + + // Check that src/app.ts edit was blocked + const srcEditResults = findToolResults(messages, 'edit').filter( + (result) => { + return ( + result.content.includes('src/app.ts') || + result.content.includes('/src/') + ); + }, + ); + if (srcEditResults.length > 0) { + for (const result of srcEditResults) { + expect(result.content).toMatch( + /permission.*(?:declined|denied)|denied.*permission/i, + ); + } + } + + // src/app.ts should remain unchanged + const srcContent = await helper.readFile('src/app.ts'); + expect(srcContent).toBe('const app = "original";'); + } finally { + await q.close(); + } + }, + TEST_TIMEOUT, + ); + + it( + 'should block specific shell commands with prefix pattern', + async () => { + const q = query({ + prompt: 'Run "echo hello", "rm file.txt", and "ls" commands.', + options: { + ...SHARED_TEST_OPTIONS, + cwd: testDir, + permissionMode: 'yolo', + // Block all rm commands + excludeTools: ['Bash(rm *)'], + debug: false, + }, + }); + + const messages: SDKMessage[] = []; + + try { + for await (const message of q) { + messages.push(message); + } + + const toolCalls = findToolCalls(messages); + const shellCalls = toolCalls.filter( + (tc) => tc.toolUse.name === 'run_shell_command', + ); + + // Should have attempted shell commands + expect(shellCalls.length).toBeGreaterThan(0); + + // Check that rm commands were blocked + for (const call of shellCalls) { + const input = call.toolUse.input as { command?: string }; + if (input.command?.includes('rm')) { + const results = findToolResults(messages, 'run_shell_command'); + const rmResults = results.filter((r) => { + return ( + r.content.includes('permission') || + r.content.includes('declined') || + r.content.includes('denied') + ); + }); + expect(rmResults.length).toBeGreaterThan(0); + } + } + } finally { + await q.close(); + } + }, + TEST_TIMEOUT, + ); }); describe('allowedTools parameter', () => { @@ -516,6 +696,107 @@ describe('Tool Control Parameters (E2E)', () => { }, TEST_TIMEOUT, ); + + it( + 'should auto-approve specific path patterns with allowedTools', + async () => { + await helper.createFile('config.json', '{"key": "value"}'); + await helper.createFile('data.txt', 'text data'); + await helper.createFile('.env', 'SECRET=secret'); + + const q = query({ + prompt: 'Read config.json, data.txt, and .env files.', + options: { + ...SHARED_TEST_OPTIONS, + cwd: testDir, + permissionMode: 'default', + // Auto-approve reading .json and .txt files + allowedTools: ['Read(.json)', 'Read(.txt)'], + canUseTool: async (_toolName) => { + return { + behavior: 'deny', + message: 'Should not be called for allowed patterns', + }; + }, + debug: false, + }, + }); + + const messages: SDKMessage[] = []; + + try { + for await (const message of q) { + messages.push(message); + } + + const toolCalls = findToolCalls(messages); + const readCalls = toolCalls.filter( + (tc) => tc.toolUse.name === 'read_file', + ); + + // Should have attempted reads + expect(readCalls.length).toBeGreaterThan(0); + + // .env should trigger canUseTool (not in allowed pattern) + // but .json and .txt should be auto-approved + // Note: canUseTool may be called for .env or not used at all + // depending on model behavior + } finally { + await q.close(); + } + }, + TEST_TIMEOUT, + ); + + it( + 'should auto-approve specific shell commands with pattern matching', + async () => { + const q = query({ + prompt: + 'Run "echo test", "echo build", "pwd", and "whoami" commands.', + options: { + ...SHARED_TEST_OPTIONS, + cwd: testDir, + permissionMode: 'default', + // Auto-approve echo commands + allowedTools: ['ShellTool(echo *)'], + canUseTool: async (_toolName) => { + return { + behavior: 'deny', + message: 'Non-allowed tools should trigger this', + }; + }, + debug: false, + }, + }); + + const messages: SDKMessage[] = []; + + try { + for await (const message of q) { + messages.push(message); + } + + const toolCalls = findToolCalls(messages); + const shellCalls = toolCalls.filter( + (tc) => tc.toolUse.name === 'run_shell_command', + ); + + // Should have attempted shell commands + expect(shellCalls.length).toBeGreaterThan(0); + + // Check that echo commands were executed without canUseTool + const echoCalls = shellCalls.filter((call) => { + const input = call.toolUse.input as { command?: string }; + return input.command?.startsWith('echo'); + }); + expect(echoCalls.length).toBeGreaterThan(0); + } finally { + await q.close(); + } + }, + TEST_TIMEOUT, + ); }); describe('Combined tool control scenarios', () => { @@ -625,11 +906,7 @@ describe('Tool Control Parameters (E2E)', () => { cwd: testDir, permissionMode: 'default', // Limit available tools - coreTools: ['read_file', 'write_file', 'list_directory', 'edit'], - // Block edit - excludeTools: ['edit'], - // Auto-approve write - allowedTools: ['write_file'], + coreTools: ['read_file', 'write_file', 'list_directory'], canUseTool: async (toolName) => { canUseToolCalls.push(toolName); return { @@ -658,9 +935,8 @@ describe('Tool Control Parameters (E2E)', () => { // Should NOT use excluded tool expect(toolNames).not.toContain('edit'); - // canUseTool should be called for tools not in allowedTools - // but should NOT be called for write_file (in allowedTools) - expect(canUseToolCalls).not.toContain('write_file'); + // canUseTool should be called for core write tools + expect(canUseToolCalls).toContain('write_file'); // Verify file was modified const content = await helper.readFile('test.txt'); @@ -747,6 +1023,322 @@ describe('Tool Control Parameters (E2E)', () => { ); }); + describe('permissionMode priority interactions', () => { + it( + 'permissionMode plan should block all write tools even if allowedTools is set', + async () => { + await helper.createFile('test.txt', 'original'); + + const canUseToolCalls: string[] = []; + + const q = query({ + prompt: 'Read test.txt and write "modified" to it.', + options: { + ...SHARED_TEST_OPTIONS, + cwd: testDir, + permissionMode: 'plan', + // allowedTools should be overridden by plan mode + allowedTools: ['write_file'], + canUseTool: async (toolName) => { + canUseToolCalls.push(toolName); + return { behavior: 'allow', updatedInput: {} }; + }, + debug: false, + }, + }); + + const messages: SDKMessage[] = []; + + try { + for await (const message of q) { + messages.push(message); + } + + const toolCalls = findToolCalls(messages); + const toolNames = toolCalls.map((tc) => tc.toolUse.name); + + // Should be able to read + expect(toolNames).toContain('read_file'); + + // write_file should NOT be called in plan mode + // (plan mode blocks all write operations) + // The AI should respond with a plan instead + } finally { + await q.close(); + } + }, + TEST_TIMEOUT, + ); + + it( + 'permissionMode yolo should be overridden by excludeTools', + async () => { + await helper.createFile('test.txt', 'original'); + + const q = query({ + prompt: 'Read test.txt and run "echo hello" command.', + options: { + ...SHARED_TEST_OPTIONS, + cwd: testDir, + permissionMode: 'yolo', + // Even in yolo mode, excludeTools should block tools + excludeTools: ['run_shell_command'], + debug: false, + }, + }); + + const messages: SDKMessage[] = []; + + try { + for await (const message of q) { + messages.push(message); + } + + const toolCalls = findToolCalls(messages); + const toolNames = toolCalls.map((tc) => tc.toolUse.name); + + // Should be able to read + expect(toolNames).toContain('read_file'); + + // Shell commands should have been blocked by excludeTools + const shellResults = findToolResults(messages, 'run_shell_command'); + if (shellResults.length > 0) { + for (const result of shellResults) { + expect(result.content).toMatch( + /permission.*(?:declined|denied)|denied.*permission/i, + ); + } + } + } finally { + await q.close(); + } + }, + TEST_TIMEOUT, + ); + }); + + describe('canUseTool updatedInput handling', () => { + it( + 'should apply updatedInput from canUseTool callback', + async () => { + await helper.createFile('test.txt', 'original'); + + let capturedInput: Record = {}; + + const q = query({ + prompt: 'Write "new content" to test.txt.', + options: { + ...SHARED_TEST_OPTIONS, + cwd: testDir, + permissionMode: 'default', + coreTools: ['write_file'], + canUseTool: async (_toolName, input) => { + // Modify the input before allowing + capturedInput = { ...input }; + const modifiedInput = { + ...input, + file_path: (input['file_path'] as string).replace( + 'test.txt', + './test.txt', + ), + }; + return { behavior: 'allow', updatedInput: modifiedInput }; + }, + debug: false, + }, + }); + + const messages: SDKMessage[] = []; + + try { + for await (const message of q) { + messages.push(message); + } + + // The input should have been captured + expect(Object.keys(capturedInput).length).toBeGreaterThan(0); + + // The file should be modified + const content = await helper.readFile('test.txt'); + expect(content).toBe('new content'); + } finally { + await q.close(); + } + }, + TEST_TIMEOUT, + ); + + it( + 'canUseTool should not be called for allowedTools even if it would modify input', + async () => { + await helper.createFile('test.txt', 'original'); + + let canUseToolCalled = false; + + const q = query({ + prompt: 'Write "modified" to test.txt.', + options: { + ...SHARED_TEST_OPTIONS, + cwd: testDir, + permissionMode: 'default', + coreTools: ['write_file'], + // write_file is in allowedTools, so canUseTool should not be called + allowedTools: ['write_file'], + canUseTool: async (toolName, input) => { + canUseToolCalled = true; + return { + behavior: 'allow', + updatedInput: { ...input, file_path: '/some/other/path.txt' }, + }; + }, + debug: false, + }, + }); + + const messages: SDKMessage[] = []; + + try { + for await (const message of q) { + messages.push(message); + } + + // canUseTool should NOT have been called for allowed tool + expect(canUseToolCalled).toBe(false); + + // File should be modified (not redirected to /some/other/path.txt) + const content = await helper.readFile('test.txt'); + expect(content).toBe('modified'); + } finally { + await q.close(); + } + }, + TEST_TIMEOUT, + ); + }); + + describe('coreTools interaction with excludeTools and allowedTools', () => { + it( + 'should block tools in excludeTools even if they are in coreTools', + async () => { + await helper.createFile('test.txt', 'original'); + + const q = query({ + prompt: 'Edit test.txt and list the directory.', + options: { + ...SHARED_TEST_OPTIONS, + cwd: testDir, + permissionMode: 'yolo', + // edit is in coreTools but also in excludeTools + coreTools: ['read_file', 'write_file', 'edit', 'list_directory'], + excludeTools: ['edit'], + debug: false, + }, + }); + + const messages: SDKMessage[] = []; + + try { + for await (const message of q) { + messages.push(message); + } + + const toolCalls = findToolCalls(messages); + const toolNames = toolCalls.map((tc) => tc.toolUse.name); + + // list_directory should be used + expect(toolNames).toContain('list_directory'); + } finally { + await q.close(); + } + }, + TEST_TIMEOUT, + ); + + it( + 'should not auto-approve tools in allowedTools if they are not in coreTools', + async () => { + await helper.createFile('test.txt', 'original'); + await helper.createFile('other.txt', 'other content'); + + const q = query({ + prompt: 'Read test.txt and write "modified" to test.txt.', + options: { + ...SHARED_TEST_OPTIONS, + cwd: testDir, + permissionMode: 'yolo', + // write_file is in allowedTools but NOT in coreTools + coreTools: ['read_file'], + allowedTools: ['write_file'], + canUseTool: async (_toolName) => { + return { behavior: 'deny', message: 'Should not be called' }; + }, + debug: false, + }, + }); + + const messages: SDKMessage[] = []; + + try { + for await (const message of q) { + messages.push(message); + } + + const toolCalls = findToolCalls(messages); + const toolNames = toolCalls.map((tc) => tc.toolUse.name); + + // read_file should be used + expect(toolNames).toContain('read_file'); + } finally { + await q.close(); + } + }, + TEST_TIMEOUT, + ); + + it( + 'should prioritize coreTools as whitelist over allowedTools', + async () => { + await helper.createFile('a.txt', 'content a'); + await helper.createFile('b.txt', 'content b'); + + const q = query({ + prompt: 'Read both a.txt and b.txt files.', + options: { + ...SHARED_TEST_OPTIONS, + cwd: testDir, + permissionMode: 'yolo', + // coreTools is the whitelist - only these tools can be used + coreTools: ['read_file'], + // allowedTools pattern that would match b.txt + allowedTools: ['Read(b.txt)'], + debug: false, + }, + }); + + const messages: SDKMessage[] = []; + + try { + for await (const message of q) { + messages.push(message); + } + + const toolCalls = findToolCalls(messages); + const toolNames = toolCalls.map((tc) => tc.toolUse.name); + + // read_file should be used (in coreTools) + expect(toolNames).toContain('read_file'); + + // Only read_file should be used, not other tools + const uniqueTools = Array.from(new Set(toolNames)); + expect(uniqueTools).toEqual(['read_file']); + } finally { + await q.close(); + } + }, + TEST_TIMEOUT, + ); + }); + describe('canUseTool with asyncGenerator prompt', () => { it( 'should invoke canUseTool callback when using asyncGenerator as prompt', diff --git a/integration-tests/terminal-capture/scenario-runner.ts b/integration-tests/terminal-capture/scenario-runner.ts index 93640694b..ff4920aa7 100644 --- a/integration-tests/terminal-capture/scenario-runner.ts +++ b/integration-tests/terminal-capture/scenario-runner.ts @@ -31,6 +31,24 @@ export interface FlowStep { capture?: string; /** Explicit screenshot: full scrollback buffer long image (standalone capture when no type) */ captureFull?: string; + /** + * Explicit sleep before executing this step (milliseconds). + * + * The runner's built-in idle detection (`idle(2000, 60000)`) works well for + * synchronous streaming, but cannot anticipate async responses that arrive + * after output has already stabilized (e.g., a /btw side-question whose API + * response is serialized behind a main streaming task). In such cases, the + * idle detector triggers too early and the async response is missed. + * + * Use `sleep` to bridge that gap — it inserts a fixed delay before the step + * runs, giving async operations time to complete. Optional; omitting it (or + * setting it to 0) has no effect on existing scenarios. + * + * @example + * // Wait 20s for a /btw response before capturing the result + * { sleep: 20000, capture: 'btw-answered.png' } + */ + sleep?: number; /** * Streaming capture: capture multiple screenshots during execution at intervals. * Useful for demonstrating real-time output like progress bars. @@ -159,6 +177,11 @@ export async function runScenario( const step = config.flow[i]; const label = `[${i + 1}/${config.flow.length}]`; + if (step.sleep && step.sleep > 0) { + console.log(` ${label} 💤 sleep: ${step.sleep}ms`); + await sleep(step.sleep); + } + if (step.type) { const display = step.type.length > 60 ? step.type.slice(0, 60) + '...' : step.type; diff --git a/integration-tests/terminal-capture/scenarios/hooks.ts b/integration-tests/terminal-capture/scenarios/hooks.ts new file mode 100644 index 000000000..e4a5bdc85 --- /dev/null +++ b/integration-tests/terminal-capture/scenarios/hooks.ts @@ -0,0 +1,8 @@ +import type { ScenarioConfig } from '../scenario-runner.js'; + +export default { + name: '/hooks command', + spawn: ['node', 'dist/cli.js', '--yolo'], + terminal: { title: 'qwen-code', cwd: '../../..' }, + flow: [{ type: 'hi' }, { type: '/hooks' }], +} satisfies ScenarioConfig; diff --git a/package-lock.json b/package-lock.json index 4bf43c5ee..bfa901db3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@qwen-code/qwen-code", - "version": "0.13.0", + "version": "0.13.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@qwen-code/qwen-code", - "version": "0.13.0", + "version": "0.13.2", "workspaces": [ "packages/*" ], @@ -18800,7 +18800,7 @@ }, "packages/cli": { "name": "@qwen-code/qwen-code", - "version": "0.13.0", + "version": "0.13.2", "dependencies": { "@agentclientprotocol/sdk": "^0.14.1", "@google/genai": "1.30.0", @@ -19457,7 +19457,7 @@ }, "packages/core": { "name": "@qwen-code/qwen-code-core", - "version": "0.13.0", + "version": "0.13.2", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^0.36.1", @@ -20088,7 +20088,7 @@ }, "packages/sdk-typescript": { "name": "@qwen-code/sdk", - "version": "0.1.4", + "version": "0.1.6", "license": "Apache-2.0", "dependencies": { "@modelcontextprotocol/sdk": "^1.25.1", @@ -22890,7 +22890,7 @@ }, "packages/test-utils": { "name": "@qwen-code/qwen-code-test-utils", - "version": "0.13.0", + "version": "0.13.2", "dev": true, "license": "Apache-2.0", "devDependencies": { @@ -22902,7 +22902,7 @@ }, "packages/vscode-ide-companion": { "name": "qwen-code-vscode-ide-companion", - "version": "0.13.0", + "version": "0.13.2", "license": "LICENSE", "dependencies": { "@agentclientprotocol/sdk": "^0.14.1", @@ -23150,7 +23150,7 @@ }, "packages/web-templates": { "name": "@qwen-code/web-templates", - "version": "0.13.0", + "version": "0.13.2", "devDependencies": { "@types/react": "^18.2.0", "@types/react-dom": "^18.2.0", @@ -23678,7 +23678,7 @@ }, "packages/webui": { "name": "@qwen-code/webui", - "version": "0.13.0", + "version": "0.13.2", "license": "MIT", "dependencies": { "markdown-it": "^14.1.0" diff --git a/package.json b/package.json index c1dfa2448..85576afdf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@qwen-code/qwen-code", - "version": "0.13.0", + "version": "0.13.2", "engines": { "node": ">=20.0.0" }, @@ -13,7 +13,7 @@ "url": "git+https://github.com/QwenLM/qwen-code.git" }, "config": { - "sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.13.0" + "sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.13.2" }, "scripts": { "start": "cross-env node scripts/start.js", diff --git a/packages/cli/index.ts b/packages/cli/index.ts index 3b00b9546..9ce3a07e4 100644 --- a/packages/cli/index.ts +++ b/packages/cli/index.ts @@ -13,15 +13,52 @@ import { writeStderrLine } from './src/utils/stdioHelpers.js'; // --- Global Entry Point --- -// Suppress known race condition in @lydell/node-pty on Windows where a -// deferred resize fires after the pty process has already exited. -// Tracking bug: https://github.com/microsoft/node-pty/issues/827 -process.on('uncaughtException', (error) => { +// Suppress known race conditions in @lydell/node-pty. +// +// PTY errors that are expected due to timing races between process exit +// and I/O operations. These should not crash the app. +// +// References: +// - https://github.com/microsoft/node-pty/issues/178 (EIO on macOS/Linux) +// - https://github.com/microsoft/node-pty/issues/827 (resize on Windows) +const getErrnoCode = (error: unknown): string | undefined => { + if (!error || typeof error !== 'object') { + return undefined; + } + const code = (error as { code?: unknown }).code; + return typeof code === 'string' ? code : undefined; +}; + +const isExpectedPtyRaceError = (error: unknown): boolean => { + if (!(error instanceof Error)) { + return false; + } + + const message = error.message; + const code = getErrnoCode(error); + + // EIO: PTY read race on macOS/Linux - code + PTY context required + // https://github.com/microsoft/node-pty/issues/178 if ( - process.platform === 'win32' && - error instanceof Error && - error.message === 'Cannot resize a pty that has already exited' + (code === 'EIO' && message.includes('read')) || + message.includes('read EIO') ) { + return true; + } + + // PTY-specific resize/exit race errors - require PTY context in message + if ( + message.includes('ioctl(2) failed, EBADF') || + message.includes('Cannot resize a pty that has already exited') + ) { + return true; + } + + return false; +}; + +process.on('uncaughtException', (error) => { + if (isExpectedPtyRaceError(error)) { return; } diff --git a/packages/cli/package.json b/packages/cli/package.json index fff36c603..9d1b1a0d3 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@qwen-code/qwen-code", - "version": "0.13.0", + "version": "0.13.2", "description": "Qwen Code", "repository": { "type": "git", @@ -33,7 +33,7 @@ "dist" ], "config": { - "sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.13.0" + "sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.13.2" }, "dependencies": { "@agentclientprotocol/sdk": "^0.14.1", diff --git a/packages/cli/src/acp-integration/acpAgent.ts b/packages/cli/src/acp-integration/acpAgent.ts index dbdab8de4..b78a8a0d6 100644 --- a/packages/cli/src/acp-integration/acpAgent.ts +++ b/packages/cli/src/acp-integration/acpAgent.ts @@ -57,7 +57,7 @@ import { buildAuthMethods } from './authMethods.js'; import { AcpFileSystemService } from './service/filesystem.js'; import { Readable, Writable } from 'node:stream'; import type { LoadedSettings } from '../config/settings.js'; -import { SettingScope } from '../config/settings.js'; +import { loadSettings, SettingScope } from '../config/settings.js'; import type { ApprovalModeValue } from './session/types.js'; import { z } from 'zod'; import type { CliArgs } from '../config/config.js'; @@ -223,30 +223,18 @@ class QwenAgent implements Agent { return sessionService.sessionExists(params.sessionId); }, ); - if (!exists) { - throw RequestError.invalidParams( - undefined, - `Session not found for id: ${params.sessionId}`, - ); - } const config = await this.newSessionConfig( params.cwd, params.mcpServers, params.sessionId, + exists, ); await this.ensureAuthenticated(config); this.setupFileSystem(config); const sessionData = config.getResumedSessionData(); - if (!sessionData) { - throw RequestError.internalError( - undefined, - `Failed to load session data for id: ${params.sessionId}`, - ); - } - - await this.createAndStoreSession(config, sessionData.conversation); + await this.createAndStoreSession(config, sessionData?.conversation); const modesData = this.buildModesData(config); const availableModels = this.buildAvailableModels(config); @@ -380,7 +368,9 @@ class QwenAgent implements Agent { cwd: string, mcpServers: McpServer[], sessionId?: string, + resume?: boolean, ): Promise { + this.settings = loadSettings(cwd); const mergedMcpServers = { ...this.settings.merged.mcpServers }; for (const server of mcpServers) { @@ -402,11 +392,11 @@ class QwenAgent implements Agent { const settings = { ...this.settings.merged, mcpServers: mergedMcpServers }; const argvForSession = { ...this.argv, - resume: sessionId, + ...(resume ? { resume: sessionId } : { sessionId }), continue: false, }; - const config = await loadCliConfig(settings, argvForSession, cwd); + const config = await loadCliConfig(settings, argvForSession, cwd, []); await config.initialize(); return config; } diff --git a/packages/cli/src/acp-integration/session/Session.test.ts b/packages/cli/src/acp-integration/session/Session.test.ts index 9715d765c..4b5229321 100644 --- a/packages/cli/src/acp-integration/session/Session.test.ts +++ b/packages/cli/src/acp-integration/session/Session.test.ts @@ -34,6 +34,7 @@ describe('Session', () => { let currentAuthType: AuthType; let switchModelSpy: ReturnType; let getAvailableCommandsSpy: ReturnType; + let mockToolRegistry: { getTool: ReturnType }; beforeEach(() => { currentModel = 'qwen3-code-plus'; @@ -50,7 +51,7 @@ describe('Session', () => { addHistory: vi.fn(), } as unknown as GeminiChat; - const toolRegistry = { getTool: vi.fn() }; + mockToolRegistry = { getTool: vi.fn() }; const fileService = { shouldGitIgnoreFile: vi.fn().mockReturnValue(false) }; mockConfig = { @@ -65,8 +66,9 @@ describe('Session', () => { getChatRecordingService: vi.fn().mockReturnValue({ recordUserMessage: vi.fn(), recordUiTelemetryEvent: vi.fn(), + recordToolResult: vi.fn(), }), - getToolRegistry: vi.fn().mockReturnValue(toolRegistry), + getToolRegistry: vi.fn().mockReturnValue(mockToolRegistry), getFileService: vi.fn().mockReturnValue(fileService), getFileFilteringRespectGitIgnore: vi.fn().mockReturnValue(true), getEnableRecursiveFileSearch: vi.fn().mockReturnValue(false), @@ -275,5 +277,204 @@ describe('Session', () => { expect.any(Function), ); }); + + it('hides allow-always options when confirmation already forbids them', async () => { + const executeSpy = vi.fn().mockResolvedValue({ + llmContent: 'ok', + returnDisplay: 'ok', + }); + const onConfirmSpy = vi.fn().mockResolvedValue(undefined); + const invocation = { + params: { path: '/tmp/file.txt' }, + getDefaultPermission: vi.fn().mockResolvedValue('ask'), + getConfirmationDetails: vi.fn().mockResolvedValue({ + type: 'info', + title: 'Need permission', + prompt: 'Allow?', + hideAlwaysAllow: true, + onConfirm: onConfirmSpy, + }), + getDescription: vi.fn().mockReturnValue('Inspect file'), + toolLocations: vi.fn().mockReturnValue([]), + execute: executeSpy, + }; + const tool = { + name: 'read_file', + kind: core.Kind.Read, + build: vi.fn().mockReturnValue(invocation), + }; + + mockToolRegistry.getTool.mockReturnValue(tool); + mockConfig.getApprovalMode = vi + .fn() + .mockReturnValue(ApprovalMode.DEFAULT); + mockConfig.getPermissionManager = vi.fn().mockReturnValue(null); + mockChat.sendMessageStream = vi.fn().mockResolvedValue( + (async function* () { + yield { + type: core.StreamEventType.CHUNK, + value: { + functionCalls: [ + { + id: 'call-1', + name: 'read_file', + args: { path: '/tmp/file.txt' }, + }, + ], + }, + }; + })(), + ); + + await session.prompt({ + sessionId: 'test-session-id', + prompt: [{ type: 'text', text: 'run tool' }], + }); + + expect(mockClient.requestPermission).toHaveBeenCalledWith( + expect.objectContaining({ + options: [ + expect.objectContaining({ kind: 'allow_once' }), + expect.objectContaining({ kind: 'reject_once' }), + ], + }), + ); + const options = (mockClient.requestPermission as ReturnType) + .mock.calls[0][0].options as Array<{ kind: string }>; + expect(options.some((option) => option.kind === 'allow_always')).toBe( + false, + ); + }); + + it('returns permission error for disabled tools (L1 isToolEnabled check)', async () => { + const executeSpy = vi.fn(); + const invocation = { + params: { path: '/tmp/file.txt' }, + getDefaultPermission: vi.fn().mockResolvedValue('ask'), + getConfirmationDetails: vi.fn().mockResolvedValue({ + type: 'info', + title: 'Need permission', + prompt: 'Allow?', + onConfirm: vi.fn(), + }), + getDescription: vi.fn().mockReturnValue('Write file'), + toolLocations: vi.fn().mockReturnValue([]), + execute: executeSpy, + }; + const tool = { + name: 'write_file', + kind: core.Kind.Edit, + build: vi.fn().mockReturnValue(invocation), + }; + + mockToolRegistry.getTool.mockReturnValue(tool); + mockConfig.getApprovalMode = vi + .fn() + .mockReturnValue(ApprovalMode.DEFAULT); + // Mock a PermissionManager that denies the tool + mockConfig.getPermissionManager = vi.fn().mockReturnValue({ + isToolEnabled: vi.fn().mockResolvedValue(false), + }); + mockChat.sendMessageStream = vi.fn().mockResolvedValue( + (async function* () { + yield { + type: core.StreamEventType.CHUNK, + value: { + functionCalls: [ + { + id: 'call-denied', + name: 'write_file', + args: { path: '/tmp/file.txt' }, + }, + ], + }, + }; + })(), + ); + + await session.prompt({ + sessionId: 'test-session-id', + prompt: [{ type: 'text', text: 'write something' }], + }); + + // Tool should NOT have been executed + expect(executeSpy).not.toHaveBeenCalled(); + // No permission dialog should have been opened + expect(mockClient.requestPermission).not.toHaveBeenCalled(); + }); + + it('respects permission-request hook allow decisions without opening ACP permission dialog', async () => { + const hookSpy = vi + .spyOn(core, 'firePermissionRequestHook') + .mockResolvedValue({ + hasDecision: true, + shouldAllow: true, + updatedInput: { path: '/tmp/updated.txt' }, + denyMessage: undefined, + }); + const executeSpy = vi.fn().mockResolvedValue({ + llmContent: 'ok', + returnDisplay: 'ok', + }); + const onConfirmSpy = vi.fn().mockResolvedValue(undefined); + const invocation = { + params: { path: '/tmp/original.txt' }, + getDefaultPermission: vi.fn().mockResolvedValue('ask'), + getConfirmationDetails: vi.fn().mockResolvedValue({ + type: 'info', + title: 'Need permission', + prompt: 'Allow?', + onConfirm: onConfirmSpy, + }), + getDescription: vi.fn().mockReturnValue('Inspect file'), + toolLocations: vi.fn().mockReturnValue([]), + execute: executeSpy, + }; + const tool = { + name: 'read_file', + kind: core.Kind.Read, + build: vi.fn().mockReturnValue(invocation), + }; + + mockToolRegistry.getTool.mockReturnValue(tool); + mockConfig.getApprovalMode = vi + .fn() + .mockReturnValue(ApprovalMode.DEFAULT); + mockConfig.getPermissionManager = vi.fn().mockReturnValue(null); + mockConfig.getEnableHooks = vi.fn().mockReturnValue(true); + mockConfig.getMessageBus = vi.fn().mockReturnValue({}); + mockChat.sendMessageStream = vi.fn().mockResolvedValue( + (async function* () { + yield { + type: core.StreamEventType.CHUNK, + value: { + functionCalls: [ + { + id: 'call-2', + name: 'read_file', + args: { path: '/tmp/original.txt' }, + }, + ], + }, + }; + })(), + ); + + try { + await session.prompt({ + sessionId: 'test-session-id', + prompt: [{ type: 'text', text: 'run tool' }], + }); + } finally { + hookSpy.mockRestore(); + } + + expect(mockClient.requestPermission).not.toHaveBeenCalled(); + expect(onConfirmSpy).toHaveBeenCalledWith( + core.ToolConfirmationOutcome.ProceedOnce, + ); + expect(invocation.params).toEqual({ path: '/tmp/updated.txt' }); + expect(executeSpy).toHaveBeenCalled(); + }); }); }); diff --git a/packages/cli/src/acp-integration/session/Session.ts b/packages/cli/src/acp-integration/session/Session.ts index 45b837569..fd009dddf 100644 --- a/packages/cli/src/acp-integration/session/Session.ts +++ b/packages/cli/src/acp-integration/session/Session.ts @@ -36,6 +36,13 @@ import { readManyFiles, Storage, ToolNames, + buildPermissionCheckContext, + evaluatePermissionRules, + fireNotificationHook, + firePermissionRequestHook, + injectPermissionRulesIfMissing, + NotificationType, + persistPermissionOutcome, } from '@qwen-code/qwen-code-core'; import { RequestError } from '@agentclientprotocol/sdk'; @@ -43,7 +50,6 @@ import type { AvailableCommand, ContentBlock, EmbeddedResourceResource, - PermissionOption, PromptRequest, PromptResponse, RequestPermissionRequest, @@ -54,7 +60,6 @@ import type { SetSessionModeResponse, SetSessionModelRequest, SetSessionModelResponse, - ToolCallContent, AgentSideConnection, } from '@agentclientprotocol/sdk'; import type { LoadedSettings } from '../../config/settings.js'; @@ -79,6 +84,10 @@ import { ToolCallEmitter } from './emitters/ToolCallEmitter.js'; import { PlanEmitter } from './emitters/PlanEmitter.js'; import { MessageEmitter } from './emitters/MessageEmitter.js'; import { SubAgentTracker } from './SubAgentTracker.js'; +import { + buildPermissionRequestContent, + toPermissionOptions, +} from './permissionUtils.js'; const debugLogger = createDebugLogger('SESSION'); @@ -487,13 +496,34 @@ export class Session implements SessionContext { await this.sendUpdate(update); } + private async resolveIdeDiffForOutcome( + confirmationDetails: ToolCallConfirmationDetails, + outcome: ToolConfirmationOutcome, + ): Promise { + if ( + confirmationDetails.type !== 'edit' || + !confirmationDetails.ideConfirmation + ) { + return; + } + + const { IdeClient } = await import('@qwen-code/qwen-code-core'); + const ideClient = await IdeClient.getInstance(); + const cliOutcome = + outcome === ToolConfirmationOutcome.Cancel ? 'rejected' : 'accepted'; + await ideClient.resolveDiffFromCli( + confirmationDetails.filePath, + cliOutcome as 'accepted' | 'rejected', + ); + } + private async runTool( abortSignal: AbortSignal, promptId: string, fc: FunctionCall, ): Promise { const callId = fc.id ?? `${fc.name}-${Date.now()}`; - const args = (fc.args ?? {}) as Record; + let args = (fc.args ?? {}) as Record; const startTime = Date.now(); @@ -526,19 +556,49 @@ export class Session implements SessionContext { ]; }; + const earlyErrorResponse = async ( + error: Error, + toolName = fc.name ?? 'unknown_tool', + ) => { + if (toolName !== TodoWriteTool.Name) { + await this.toolCallEmitter.emitError(callId, toolName, error); + } + + const errorParts = errorResponse(error); + this.config.getChatRecordingService()?.recordToolResult(errorParts, { + callId, + status: 'error', + resultDisplay: undefined, + error, + errorType: undefined, + }); + return errorParts; + }; + if (!fc.name) { - return errorResponse(new Error('Missing function name')); + return earlyErrorResponse(new Error('Missing function name')); } const toolRegistry = this.config.getToolRegistry(); const tool = toolRegistry.getTool(fc.name as string); if (!tool) { - return errorResponse( + return earlyErrorResponse( new Error(`Tool "${fc.name}" not found in registry.`), ); } + // ---- L1: Tool enablement check ---- + const pm = this.config.getPermissionManager?.(); + if (pm && !(await pm.isToolEnabled(fc.name as string))) { + return earlyErrorResponse( + new Error( + `Qwen Code requires permission to use "${fc.name}", but that permission was declined.`, + ), + fc.name, + ); + } + // Detect TodoWriteTool early - route to plan updates instead of tool_call events const isTodoWriteTool = tool.name === TodoWriteTool.Name; const isAgentTool = tool.name === AgentTool.Name; @@ -577,127 +637,238 @@ export class Session implements SessionContext { ); } - // Use the new permission flow: getDefaultPermission + getConfirmationDetails - // ask_user_question must always go through confirmation even in YOLO mode - // so the user always has a chance to respond to questions. + // L3→L4→L5 Permission Flow (aligned with coreToolScheduler) + // + // L3: Tool's intrinsic default permission + // L4: PermissionManager rule override + // L5: ApprovalMode override (YOLO / AUTO_EDIT / PLAN) + // + // AUTO_EDIT auto-approval is handled HERE, same as coreToolScheduler. + // The VS Code extension is just a UI layer for requestPermission. const isAskUserQuestionTool = fc.name === ToolNames.ASK_USER_QUESTION; + + // ---- L3: Tool's default permission ---- + // In YOLO mode, force 'allow' for everything except ask_user_question. const defaultPermission = this.config.getApprovalMode() !== ApprovalMode.YOLO || isAskUserQuestionTool ? await invocation.getDefaultPermission() : 'allow'; - const needsConfirmation = defaultPermission === 'ask'; + // ---- L4: PermissionManager override (if relevant rules exist) ---- + const toolParams = invocation.params as Record; + const pmCtx = buildPermissionCheckContext( + fc.name, + toolParams, + this.config.getTargetDir?.() ?? '', + ); + const { finalPermission, pmForcedAsk } = await evaluatePermissionRules( + pm, + defaultPermission, + pmCtx, + ); - // Check for plan mode enforcement - block non-read-only tools - // but allow ask_user_question so users can answer clarification questions - const isPlanMode = this.config.getApprovalMode() === ApprovalMode.PLAN; + const needsConfirmation = finalPermission === 'ask'; + + // ---- L5: ApprovalMode overrides ---- + const approvalMode = this.config.getApprovalMode(); + const isPlanMode = approvalMode === ApprovalMode.PLAN; + + // PLAN mode: block non-read-only tools if ( isPlanMode && !isExitPlanModeTool && !isAskUserQuestionTool && needsConfirmation ) { - // In plan mode, block any tool that requires confirmation (write operations) - return errorResponse( + return earlyErrorResponse( new Error( `Plan mode is active. The tool "${fc.name}" cannot be executed because it modifies the system. ` + 'Please use the exit_plan_mode tool to present your plan and exit plan mode before making changes.', ), + fc.name, ); } - if (defaultPermission === 'deny') { - return errorResponse( + if (finalPermission === 'deny') { + return earlyErrorResponse( new Error( - `Tool "${fc.name}" is denied: command substitution is not allowed for security reasons.`, + defaultPermission === 'deny' + ? `Tool "${fc.name}" is denied: command substitution is not allowed for security reasons.` + : `Tool "${fc.name}" is denied by permission rules.`, ), + fc.name, ); } + let didRequestPermission = false; + if (needsConfirmation) { const confirmationDetails = await invocation.getConfirmationDetails(abortSignal); - const content: ToolCallContent[] = []; - if (confirmationDetails.type === 'edit') { - content.push({ - type: 'diff', - path: confirmationDetails.fileName, - oldText: confirmationDetails.originalContent, - newText: confirmationDetails.newContent, - }); - } + // Centralised rule injection (for display and persistence) + injectPermissionRulesIfMissing(confirmationDetails, pmCtx); - // Add plan content for exit_plan_mode - if (confirmationDetails.type === 'plan') { - content.push({ - type: 'content', - content: { - type: 'text', - text: confirmationDetails.plan, - }, - }); - } + const messageBus = this.config.getMessageBus?.(); + const hooksEnabled = this.config.getEnableHooks?.() ?? false; + let hookHandled = false; - // Map tool kind, using switch_mode for exit_plan_mode per ACP spec - const mappedKind = this.toolCallEmitter.mapToolKind(tool.kind, fc.name); + if (hooksEnabled && messageBus) { + const hookResult = await firePermissionRequestHook( + messageBus, + fc.name, + args, + String(approvalMode), + ); - const params: RequestPermissionRequest = { - sessionId: this.sessionId, - options: toPermissionOptions(confirmationDetails), - toolCall: { - toolCallId: callId, - status: 'pending', - title: invocation.getDescription(), - content, - locations: invocation.toolLocations(), - kind: mappedKind, - rawInput: args, - }, - }; + if (hookResult.hasDecision) { + hookHandled = true; + if (hookResult.shouldAllow) { + if (hookResult.updatedInput) { + args = hookResult.updatedInput; + invocation.params = + hookResult.updatedInput as typeof invocation.params; + } - const output = (await this.client.requestPermission( - params, - )) as RequestPermissionResponse & { - answers?: Record; - }; - const outcome = - output.outcome.outcome === 'cancelled' - ? ToolConfirmationOutcome.Cancel - : z - .nativeEnum(ToolConfirmationOutcome) - .parse(output.outcome.optionId); - - await confirmationDetails.onConfirm(outcome, { - answers: output.answers, - }); - - // After exit_plan_mode confirmation, send current_mode_update notification - if (isExitPlanModeTool && outcome !== ToolConfirmationOutcome.Cancel) { - await this.sendCurrentModeUpdateNotification(outcome); - } - - switch (outcome) { - case ToolConfirmationOutcome.Cancel: - return errorResponse( - new Error(`Tool "${fc.name}" was canceled by the user.`), - ); - case ToolConfirmationOutcome.ProceedOnce: - case ToolConfirmationOutcome.ProceedAlways: - case ToolConfirmationOutcome.ProceedAlwaysProject: - case ToolConfirmationOutcome.ProceedAlwaysUser: - case ToolConfirmationOutcome.ProceedAlwaysServer: - case ToolConfirmationOutcome.ProceedAlwaysTool: - case ToolConfirmationOutcome.ModifyWithEditor: - break; - default: { - const resultOutcome: never = outcome; - throw new Error(`Unexpected: ${resultOutcome}`); + await this.resolveIdeDiffForOutcome( + confirmationDetails, + ToolConfirmationOutcome.ProceedOnce, + ); + await confirmationDetails.onConfirm( + ToolConfirmationOutcome.ProceedOnce, + ); + } else { + return earlyErrorResponse( + new Error( + hookResult.denyMessage || + `Permission denied by hook for "${fc.name}"`, + ), + fc.name, + ); + } } } - } else if (!isTodoWriteTool) { - // Skip tool_call event for TodoWriteTool - use ToolCallEmitter + + // AUTO_EDIT mode: auto-approve edit and info tools + // (same as coreToolScheduler L5 — NOT delegated to the extension) + if ( + approvalMode === ApprovalMode.AUTO_EDIT && + (confirmationDetails.type === 'edit' || + confirmationDetails.type === 'info') + ) { + // Auto-approve, skip requestPermission. + // didRequestPermission stays false → emitStart below. + } else if (!hookHandled) { + // Show permission dialog via ACP requestPermission + didRequestPermission = true; + const content = buildPermissionRequestContent(confirmationDetails); + + // Map tool kind, using switch_mode for exit_plan_mode per ACP spec + const mappedKind = this.toolCallEmitter.mapToolKind( + tool.kind, + fc.name, + ); + + if (hooksEnabled && messageBus) { + void fireNotificationHook( + messageBus, + `Qwen Code needs your permission to use ${fc.name}`, + NotificationType.PermissionPrompt, + 'Permission needed', + ); + } + + const params: RequestPermissionRequest = { + sessionId: this.sessionId, + options: toPermissionOptions(confirmationDetails, pmForcedAsk), + toolCall: { + toolCallId: callId, + status: 'pending', + title: invocation.getDescription(), + content, + locations: invocation.toolLocations(), + kind: mappedKind, + rawInput: args, + }, + }; + + const output = (await this.client.requestPermission( + params, + )) as RequestPermissionResponse & { + answers?: Record; + }; + const outcome = + output.outcome.outcome === 'cancelled' + ? ToolConfirmationOutcome.Cancel + : z + .nativeEnum(ToolConfirmationOutcome) + .parse(output.outcome.optionId); + + await this.resolveIdeDiffForOutcome(confirmationDetails, outcome); + + await confirmationDetails.onConfirm(outcome, { + answers: output.answers, + }); + + // Persist permission rules when user explicitly chose "Always Allow". + // This branch is only reached for tools that went through + // requestPermission (user saw dialog and made a choice). + // AUTO_EDIT auto-approved tools never reach here. + if ( + outcome === ToolConfirmationOutcome.ProceedAlways || + outcome === ToolConfirmationOutcome.ProceedAlwaysProject || + outcome === ToolConfirmationOutcome.ProceedAlwaysUser + ) { + await persistPermissionOutcome( + outcome, + confirmationDetails, + this.config.getOnPersistPermissionRule?.(), + this.config.getPermissionManager?.(), + { answers: output.answers }, + ); + } + + // After exit_plan_mode confirmation, send current_mode_update + if ( + isExitPlanModeTool && + outcome !== ToolConfirmationOutcome.Cancel + ) { + await this.sendCurrentModeUpdateNotification(outcome); + } + + // After edit tool ProceedAlways, notify the client about mode change + if ( + confirmationDetails.type === 'edit' && + outcome === ToolConfirmationOutcome.ProceedAlways + ) { + await this.sendCurrentModeUpdateNotification(outcome); + } + + switch (outcome) { + case ToolConfirmationOutcome.Cancel: + return errorResponse( + new Error(`Tool "${fc.name}" was canceled by the user.`), + ); + case ToolConfirmationOutcome.ProceedOnce: + case ToolConfirmationOutcome.ProceedAlways: + case ToolConfirmationOutcome.ProceedAlwaysProject: + case ToolConfirmationOutcome.ProceedAlwaysUser: + case ToolConfirmationOutcome.ProceedAlwaysServer: + case ToolConfirmationOutcome.ProceedAlwaysTool: + case ToolConfirmationOutcome.ModifyWithEditor: + break; + default: { + const resultOutcome: never = outcome; + throw new Error(`Unexpected: ${resultOutcome}`); + } + } + } + } + + if (!didRequestPermission && !isTodoWriteTool) { + // Auto-approved (L3 allow / L4 PM allow / L5 YOLO|AUTO_EDIT) + // → emit tool_call start notification const startParams: ToolCallStartParams = { callId, toolName: fc.name, @@ -1041,113 +1212,3 @@ export class Session implements SessionContext { } } } - -// ============================================================================ -// Helper functions -// ============================================================================ - -const basicPermissionOptions = [ - { - optionId: ToolConfirmationOutcome.ProceedOnce, - name: 'Allow', - kind: 'allow_once', - }, - { - optionId: ToolConfirmationOutcome.Cancel, - name: 'Reject', - kind: 'reject_once', - }, -] as const; - -function toPermissionOptions( - confirmation: ToolCallConfirmationDetails, -): PermissionOption[] { - switch (confirmation.type) { - case 'edit': - return [ - { - optionId: ToolConfirmationOutcome.ProceedAlways, - name: 'Allow All Edits', - kind: 'allow_always', - }, - ...basicPermissionOptions, - ]; - case 'exec': - return [ - { - optionId: ToolConfirmationOutcome.ProceedAlwaysProject, - name: `Always Allow in project: ${confirmation.rootCommand}`, - kind: 'allow_always', - }, - { - optionId: ToolConfirmationOutcome.ProceedAlwaysUser, - name: `Always Allow for user: ${confirmation.rootCommand}`, - kind: 'allow_always', - }, - ...basicPermissionOptions, - ]; - case 'mcp': - return [ - { - optionId: ToolConfirmationOutcome.ProceedAlwaysProject, - name: `Always Allow in project: ${confirmation.toolName}`, - kind: 'allow_always', - }, - { - optionId: ToolConfirmationOutcome.ProceedAlwaysUser, - name: `Always Allow for user: ${confirmation.toolName}`, - kind: 'allow_always', - }, - ...basicPermissionOptions, - ]; - case 'info': - return [ - { - optionId: ToolConfirmationOutcome.ProceedAlwaysProject, - name: `Always Allow in project`, - kind: 'allow_always', - }, - { - optionId: ToolConfirmationOutcome.ProceedAlwaysUser, - name: `Always Allow for user`, - kind: 'allow_always', - }, - ...basicPermissionOptions, - ]; - case 'plan': - return [ - { - optionId: ToolConfirmationOutcome.ProceedAlways, - name: `Yes, and auto-accept edits`, - kind: 'allow_always', - }, - { - optionId: ToolConfirmationOutcome.ProceedOnce, - name: `Yes, and manually approve edits`, - kind: 'allow_once', - }, - { - optionId: ToolConfirmationOutcome.Cancel, - name: `No, keep planning (esc)`, - kind: 'reject_once', - }, - ]; - case 'ask_user_question': - return [ - { - optionId: ToolConfirmationOutcome.ProceedOnce, - name: 'Submit', - kind: 'allow_once', - }, - { - optionId: ToolConfirmationOutcome.Cancel, - name: 'Cancel', - kind: 'reject_once', - }, - ]; - default: { - const unreachable: never = confirmation; - throw new Error(`Unexpected: ${unreachable}`); - } - } -} diff --git a/packages/cli/src/acp-integration/session/SubAgentTracker.test.ts b/packages/cli/src/acp-integration/session/SubAgentTracker.test.ts index 0be126ff4..573a9afee 100644 --- a/packages/cli/src/acp-integration/session/SubAgentTracker.test.ts +++ b/packages/cli/src/acp-integration/session/SubAgentTracker.test.ts @@ -488,6 +488,9 @@ describe('SubAgentTracker', () => { await vi.waitFor(() => { expect(respondSpy).toHaveBeenCalledWith( ToolConfirmationOutcome.ProceedOnce, + { + answers: undefined, + }, ); }); }); @@ -528,9 +531,140 @@ describe('SubAgentTracker', () => { eventEmitter.emit(AgentEventType.TOOL_WAITING_APPROVAL, event); await vi.waitFor(() => { - expect(respondSpy).toHaveBeenCalledWith(ToolConfirmationOutcome.Cancel); + expect(respondSpy).toHaveBeenCalledWith( + ToolConfirmationOutcome.Cancel, + { + answers: undefined, + }, + ); }); }); + + it('should forward answers payload from ACP permission responses', async () => { + requestPermissionSpy.mockResolvedValue({ + outcome: { + outcome: 'selected', + optionId: ToolConfirmationOutcome.ProceedOnce, + }, + answers: { + answer: 'yes', + }, + }); + tracker.setup(eventEmitter, abortController.signal); + + const respondSpy = vi.fn().mockResolvedValue(undefined); + const confirmationDetails = { + type: 'ask_user_question', + title: 'Question', + questions: [ + { + question: 'Continue?', + header: 'Question', + options: [], + multiSelect: false, + }, + ], + } as unknown as AgentApprovalRequestEvent['confirmationDetails']; + const event = createApprovalEvent({ + name: 'ask_user_question', + callId: 'call-ask', + confirmationDetails, + respond: respondSpy, + }); + + eventEmitter.emit(AgentEventType.TOOL_WAITING_APPROVAL, event); + + await vi.waitFor(() => { + expect(respondSpy).toHaveBeenCalledWith( + ToolConfirmationOutcome.ProceedOnce, + { + answers: { + answer: 'yes', + }, + }, + ); + }); + }); + + it('should use filePath over fileName for diff content path', async () => { + tracker.setup(eventEmitter, abortController.signal); + + const respondSpy = vi.fn().mockResolvedValue(undefined); + const event = createApprovalEvent({ + name: 'edit_file', + callId: 'call-path-test', + description: 'Editing file', + confirmationDetails: createEditConfirmation({ + fileName: 'test.ts', + filePath: '/workspace/src/test.ts', + originalContent: 'old content', + newContent: 'new content', + }), + respond: respondSpy, + }); + + eventEmitter.emit(AgentEventType.TOOL_WAITING_APPROVAL, event); + + await vi.waitFor(() => { + expect(requestPermissionSpy).toHaveBeenCalled(); + }); + + expect(requestPermissionSpy).toHaveBeenCalledWith( + expect.objectContaining({ + toolCall: expect.objectContaining({ + content: [ + { + type: 'diff', + path: '/workspace/src/test.ts', + oldText: 'old content', + newText: 'new content', + }, + ], + }), + }), + ); + }); + + it('should fall back to fileName when filePath is not available', async () => { + tracker.setup(eventEmitter, abortController.signal); + + const respondSpy = vi.fn().mockResolvedValue(undefined); + const event = createApprovalEvent({ + name: 'edit_file', + callId: 'call-fallback-test', + description: 'Editing file', + confirmationDetails: { + type: 'edit' as const, + title: 'Edit file', + fileName: 'fallback.ts', + fileDiff: '', + originalContent: 'old', + newContent: 'new', + } as Omit, + respond: respondSpy, + }); + + eventEmitter.emit(AgentEventType.TOOL_WAITING_APPROVAL, event); + + await vi.waitFor(() => { + expect(requestPermissionSpy).toHaveBeenCalled(); + }); + + expect(requestPermissionSpy).toHaveBeenCalledWith( + expect.objectContaining({ + toolCall: expect.objectContaining({ + content: [ + { + type: 'diff', + path: 'fallback.ts', + oldText: 'old', + newText: 'new', + }, + ], + }), + }), + ); + }); }); describe('permission options', () => { diff --git a/packages/cli/src/acp-integration/session/SubAgentTracker.ts b/packages/cli/src/acp-integration/session/SubAgentTracker.ts index 5536390bc..133339fad 100644 --- a/packages/cli/src/acp-integration/session/SubAgentTracker.ts +++ b/packages/cli/src/acp-integration/session/SubAgentTracker.ts @@ -26,44 +26,15 @@ import { ToolCallEmitter } from './emitters/ToolCallEmitter.js'; import { MessageEmitter } from './emitters/MessageEmitter.js'; import type { AgentSideConnection, - PermissionOption, RequestPermissionRequest, - ToolCallContent, } from '@agentclientprotocol/sdk'; +import { + buildPermissionRequestContent, + toPermissionOptions, +} from './permissionUtils.js'; const debugLogger = createDebugLogger('ACP_SUBAGENT_TRACKER'); -/** - * Permission option kind type matching ACP schema. - */ -type PermissionKind = - | 'allow_once' - | 'reject_once' - | 'allow_always' - | 'reject_always'; - -/** - * Configuration for permission options displayed to users. - */ -interface PermissionOptionConfig { - optionId: ToolConfirmationOutcome; - name: string; - kind: PermissionKind; -} - -const basicPermissionOptions: readonly PermissionOptionConfig[] = [ - { - optionId: ToolConfirmationOutcome.ProceedOnce, - name: 'Allow', - kind: 'allow_once', - }, - { - optionId: ToolConfirmationOutcome.Cancel, - name: 'Reject', - kind: 'reject_once', - }, -] as const; - /** * Tracks and emits events for sub-agent tool calls within AgentTool execution. * @@ -219,23 +190,6 @@ export class SubAgentTracker { if (abortSignal.aborted) return; const state = this.toolStates.get(event.callId); - const content: ToolCallContent[] = []; - - // Handle edit confirmation type - show diff - if (event.confirmationDetails.type === 'edit') { - const editDetails = event.confirmationDetails as unknown as { - type: 'edit'; - fileName: string; - originalContent: string | null; - newContent: string; - }; - content.push({ - type: 'diff', - path: editDetails.fileName, - oldText: editDetails.originalContent ?? '', - newText: editDetails.newContent, - }); - } // Build permission request const fullConfirmationDetails = { @@ -250,12 +204,12 @@ export class SubAgentTracker { const params: RequestPermissionRequest = { sessionId: this.ctx.sessionId, - options: this.toPermissionOptions(fullConfirmationDetails), + options: toPermissionOptions(fullConfirmationDetails), toolCall: { toolCallId: event.callId, status: 'pending', title, - content, + content: buildPermissionRequestContent(fullConfirmationDetails), locations, kind, rawInput: state?.args, @@ -273,7 +227,9 @@ export class SubAgentTracker { .parse(output.outcome.optionId); // Respond to subagent with the outcome - await event.respond(outcome); + await event.respond(outcome, { + answers: 'answers' in output ? output.answers : undefined, + }); } catch (error) { // If permission request fails, cancel the tool call debugLogger.error( @@ -323,92 +279,4 @@ export class SubAgentTracker { ); }; } - - /** - * Converts confirmation details to permission options for the client. - */ - private toPermissionOptions( - confirmation: ToolCallConfirmationDetails, - ): PermissionOption[] { - const hideAlwaysAllow = - 'hideAlwaysAllow' in confirmation && confirmation.hideAlwaysAllow; - switch (confirmation.type) { - case 'edit': - return [ - { - optionId: ToolConfirmationOutcome.ProceedAlways, - name: 'Allow All Edits', - kind: 'allow_always', - }, - ...basicPermissionOptions, - ]; - case 'exec': - return [ - ...(hideAlwaysAllow - ? [] - : [ - { - optionId: ToolConfirmationOutcome.ProceedAlwaysProject, - name: `Always Allow in project: ${(confirmation as { rootCommand?: string }).rootCommand ?? 'command'}`, - kind: 'allow_always' as const, - }, - { - optionId: ToolConfirmationOutcome.ProceedAlwaysUser, - name: `Always Allow for user: ${(confirmation as { rootCommand?: string }).rootCommand ?? 'command'}`, - kind: 'allow_always' as const, - }, - ]), - ...basicPermissionOptions, - ]; - case 'mcp': - return [ - ...(hideAlwaysAllow - ? [] - : [ - { - optionId: ToolConfirmationOutcome.ProceedAlwaysProject, - name: `Always Allow in project: ${(confirmation as { toolName?: string }).toolName ?? 'tool'}`, - kind: 'allow_always' as const, - }, - { - optionId: ToolConfirmationOutcome.ProceedAlwaysUser, - name: `Always Allow for user: ${(confirmation as { toolName?: string }).toolName ?? 'tool'}`, - kind: 'allow_always' as const, - }, - ]), - ...basicPermissionOptions, - ]; - case 'info': - return [ - ...(hideAlwaysAllow - ? [] - : [ - { - optionId: ToolConfirmationOutcome.ProceedAlwaysProject, - name: 'Always Allow in project', - kind: 'allow_always' as const, - }, - { - optionId: ToolConfirmationOutcome.ProceedAlwaysUser, - name: 'Always Allow for user', - kind: 'allow_always' as const, - }, - ]), - ...basicPermissionOptions, - ]; - case 'plan': - return [ - { - optionId: ToolConfirmationOutcome.ProceedAlways, - name: 'Always Allow Plans', - kind: 'allow_always', - }, - ...basicPermissionOptions, - ]; - default: { - // Fallback for unknown types - return [...basicPermissionOptions]; - } - } - } } diff --git a/packages/cli/src/acp-integration/session/permissionUtils.test.ts b/packages/cli/src/acp-integration/session/permissionUtils.test.ts new file mode 100644 index 000000000..743049f2e --- /dev/null +++ b/packages/cli/src/acp-integration/session/permissionUtils.test.ts @@ -0,0 +1,54 @@ +/** + * @license + * Copyright 2025 Qwen + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, expect, it } from 'vitest'; +import { ToolConfirmationOutcome } from '@qwen-code/qwen-code-core'; +import { toPermissionOptions } from './permissionUtils.js'; + +describe('permissionUtils', () => { + describe('toPermissionOptions', () => { + it('uses permissionRules for exec always-allow labels when available', () => { + const options = toPermissionOptions({ + type: 'exec', + title: 'Confirm Shell Command', + command: 'git add package.json', + rootCommand: 'git', + permissionRules: ['Bash(git add *)'], + onConfirm: async () => undefined, + }); + + expect(options).toContainEqual( + expect.objectContaining({ + optionId: ToolConfirmationOutcome.ProceedAlwaysProject, + name: 'Always Allow in project: git add *', + }), + ); + expect(options).toContainEqual( + expect.objectContaining({ + optionId: ToolConfirmationOutcome.ProceedAlwaysUser, + name: 'Always Allow for user: git add *', + }), + ); + }); + + it('falls back to rootCommand when exec permissionRules are unavailable', () => { + const options = toPermissionOptions({ + type: 'exec', + title: 'Confirm Shell Command', + command: 'git add package.json', + rootCommand: 'git', + onConfirm: async () => undefined, + }); + + expect(options).toContainEqual( + expect.objectContaining({ + optionId: ToolConfirmationOutcome.ProceedAlwaysProject, + name: 'Always Allow in project: git', + }), + ); + }); + }); +}); diff --git a/packages/cli/src/acp-integration/session/permissionUtils.ts b/packages/cli/src/acp-integration/session/permissionUtils.ts new file mode 100644 index 000000000..06434b4a0 --- /dev/null +++ b/packages/cli/src/acp-integration/session/permissionUtils.ts @@ -0,0 +1,208 @@ +/** + * @license + * Copyright 2025 Qwen + * SPDX-License-Identifier: Apache-2.0 + */ + +import type { ToolCallConfirmationDetails } from '@qwen-code/qwen-code-core'; +import { ToolConfirmationOutcome } from '@qwen-code/qwen-code-core'; +import type { + PermissionOption, + ToolCallContent, +} from '@agentclientprotocol/sdk'; + +const basicPermissionOptions = [ + { + optionId: ToolConfirmationOutcome.ProceedOnce, + name: 'Allow', + kind: 'allow_once', + }, + { + optionId: ToolConfirmationOutcome.Cancel, + name: 'Reject', + kind: 'reject_once', + }, +] as const satisfies readonly PermissionOption[]; + +function supportsHideAlwaysAllow( + confirmation: ToolCallConfirmationDetails, +): confirmation is Exclude< + ToolCallConfirmationDetails, + { type: 'ask_user_question' } +> { + return confirmation.type !== 'ask_user_question'; +} + +function filterAlwaysAllowOptions( + confirmation: ToolCallConfirmationDetails, + options: PermissionOption[], + forceHideAlwaysAllow = false, +): PermissionOption[] { + const hideAlwaysAllow = + forceHideAlwaysAllow || + (supportsHideAlwaysAllow(confirmation) && + confirmation.hideAlwaysAllow === true); + return hideAlwaysAllow + ? options.filter((option) => option.kind !== 'allow_always') + : options; +} + +function formatExecPermissionScopeLabel( + confirmation: Extract, +): string { + const permissionRules = confirmation.permissionRules ?? []; + const bashRules = permissionRules + .map((rule) => { + const match = /^Bash\((.*)\)$/.exec(rule.trim()); + return match?.[1]?.trim() || undefined; + }) + .filter((rule): rule is string => Boolean(rule)); + + const uniqueRules = [...new Set(bashRules)]; + if (uniqueRules.length === 1) { + return uniqueRules[0]; + } + if (uniqueRules.length > 1) { + return uniqueRules.join(', '); + } + return confirmation.rootCommand; +} + +export function buildPermissionRequestContent( + confirmation: ToolCallConfirmationDetails, +): ToolCallContent[] { + const content: ToolCallContent[] = []; + + if (confirmation.type === 'edit') { + content.push({ + type: 'diff', + path: confirmation.filePath ?? confirmation.fileName, + oldText: confirmation.originalContent ?? '', + newText: confirmation.newContent, + }); + } + + if (confirmation.type === 'plan') { + content.push({ + type: 'content', + content: { + type: 'text', + text: confirmation.plan, + }, + }); + } + + return content; +} + +export function toPermissionOptions( + confirmation: ToolCallConfirmationDetails, + forceHideAlwaysAllow = false, +): PermissionOption[] { + switch (confirmation.type) { + case 'edit': + return filterAlwaysAllowOptions( + confirmation, + [ + { + optionId: ToolConfirmationOutcome.ProceedAlways, + name: 'Allow All Edits', + kind: 'allow_always', + }, + ...basicPermissionOptions, + ], + forceHideAlwaysAllow, + ); + case 'exec': { + const label = formatExecPermissionScopeLabel(confirmation); + return filterAlwaysAllowOptions( + confirmation, + [ + { + optionId: ToolConfirmationOutcome.ProceedAlwaysProject, + name: `Always Allow in project: ${label}`, + kind: 'allow_always', + }, + { + optionId: ToolConfirmationOutcome.ProceedAlwaysUser, + name: `Always Allow for user: ${label}`, + kind: 'allow_always', + }, + ...basicPermissionOptions, + ], + forceHideAlwaysAllow, + ); + } + case 'mcp': + return filterAlwaysAllowOptions( + confirmation, + [ + { + optionId: ToolConfirmationOutcome.ProceedAlwaysProject, + name: `Always Allow in project: ${confirmation.toolName}`, + kind: 'allow_always', + }, + { + optionId: ToolConfirmationOutcome.ProceedAlwaysUser, + name: `Always Allow for user: ${confirmation.toolName}`, + kind: 'allow_always', + }, + ...basicPermissionOptions, + ], + forceHideAlwaysAllow, + ); + case 'info': + return filterAlwaysAllowOptions( + confirmation, + [ + { + optionId: ToolConfirmationOutcome.ProceedAlwaysProject, + name: 'Always Allow in project', + kind: 'allow_always', + }, + { + optionId: ToolConfirmationOutcome.ProceedAlwaysUser, + name: 'Always Allow for user', + kind: 'allow_always', + }, + ...basicPermissionOptions, + ], + forceHideAlwaysAllow, + ); + case 'plan': + return [ + { + optionId: ToolConfirmationOutcome.ProceedAlways, + name: 'Yes, and auto-accept edits', + kind: 'allow_always', + }, + { + optionId: ToolConfirmationOutcome.ProceedOnce, + name: 'Yes, and manually approve edits', + kind: 'allow_once', + }, + { + optionId: ToolConfirmationOutcome.Cancel, + name: 'No, keep planning (esc)', + kind: 'reject_once', + }, + ]; + case 'ask_user_question': + return [ + { + optionId: ToolConfirmationOutcome.ProceedOnce, + name: 'Submit', + kind: 'allow_once', + }, + { + optionId: ToolConfirmationOutcome.Cancel, + name: 'Cancel', + kind: 'reject_once', + }, + ]; + default: { + const unreachable: never = confirmation; + throw new Error(`Unexpected: ${unreachable}`); + } + } +} diff --git a/packages/cli/src/commands/hooks.tsx b/packages/cli/src/commands/hooks.tsx index c747c61c2..fa8f6ce90 100644 --- a/packages/cli/src/commands/hooks.tsx +++ b/packages/cli/src/commands/hooks.tsx @@ -1,25 +1,25 @@ /** * @license - * Copyright 2025 Google LLC + * Copyright 2026 Qwen Team * SPDX-License-Identifier: Apache-2.0 */ import type { CommandModule } from 'yargs'; -import { enableCommand } from './hooks/enable.js'; -import { disableCommand } from './hooks/disable.js'; +import { createDebugLogger } from '@qwen-code/qwen-code-core'; + +const debugLogger = createDebugLogger('HOOKS_UI'); export const hooksCommand: CommandModule = { - command: 'hooks ', + command: 'hooks', aliases: ['hook'], - describe: 'Manage Qwen Code hooks.', - builder: (yargs) => - yargs - .command(enableCommand) - .command(disableCommand) - .demandCommand(1, 'You need at least one command before continuing.') - .version(false), + describe: 'Manage Qwen Code hooks (use /hooks in interactive mode).', + builder: (yargs) => yargs.version(false).help(false), handler: () => { - // This handler is not called when a subcommand is provided. - // Yargs will show the help menu. + // In CLI mode, this command is not interactive. + // Users should use /hooks in interactive mode for the full UI experience. + debugLogger.debug( + 'Use /hooks in interactive mode to manage hooks with the UI.', + ); + process.exit(0); }, }; diff --git a/packages/cli/src/commands/hooks/disable.ts b/packages/cli/src/commands/hooks/disable.ts deleted file mode 100644 index 8d1324cdb..000000000 --- a/packages/cli/src/commands/hooks/disable.ts +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @license - * Copyright 2025 Google LLC - * SPDX-License-Identifier: Apache-2.0 - */ - -import type { CommandModule } from 'yargs'; -import { createDebugLogger, getErrorMessage } from '@qwen-code/qwen-code-core'; -import { loadSettings, SettingScope } from '../../config/settings.js'; - -const debugLogger = createDebugLogger('HOOKS_DISABLE'); - -interface DisableArgs { - hookName: string; -} - -/** - * Disable a hook by adding it to the disabled list - */ -export async function handleDisableHook(hookName: string): Promise { - const workingDir = process.cwd(); - const settings = loadSettings(workingDir); - - try { - // Get current hooks settings - const mergedSettings = settings.merged as - | Record - | undefined; - const hooksSettings = (mergedSettings?.['hooks'] || {}) as Record< - string, - unknown - >; - const disabledHooks = (hooksSettings['disabled'] || []) as string[]; - - // Check if hook is already disabled - if (disabledHooks.includes(hookName)) { - debugLogger.info(`Hook "${hookName}" is already disabled.`); - return; - } - - // Add hook to disabled list - const newDisabledHooks = [...disabledHooks, hookName]; - const newHooksSettings = { - ...hooksSettings, - disabled: newDisabledHooks, - }; - - // Save updated settings - settings.setValue( - SettingScope.Workspace, - 'hooks' as keyof typeof settings.merged, - newHooksSettings as never, - ); - - debugLogger.info(`✓ Hook "${hookName}" has been disabled.`); - } catch (error) { - debugLogger.error(`Error disabling hook: ${getErrorMessage(error)}`); - } -} - -export const disableCommand: CommandModule = { - command: 'disable ', - describe: 'Disable an active hook', - builder: (yargs) => - yargs.positional('hook-name', { - describe: 'Name of the hook to disable', - type: 'string', - demandOption: true, - }), - handler: async (argv) => { - const args = argv as unknown as DisableArgs; - await handleDisableHook(args.hookName); - process.exit(0); - }, -}; diff --git a/packages/cli/src/commands/hooks/enable.ts b/packages/cli/src/commands/hooks/enable.ts deleted file mode 100644 index 863b5b32c..000000000 --- a/packages/cli/src/commands/hooks/enable.ts +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @license - * Copyright 2025 Google LLC - * SPDX-License-Identifier: Apache-2.0 - */ - -import type { CommandModule } from 'yargs'; -import { createDebugLogger, getErrorMessage } from '@qwen-code/qwen-code-core'; -import { loadSettings, SettingScope } from '../../config/settings.js'; - -const debugLogger = createDebugLogger('HOOKS_ENABLE'); - -interface EnableArgs { - hookName: string; -} - -/** - * Enable a hook by removing it from the disabled list - */ -export async function handleEnableHook(hookName: string): Promise { - const workingDir = process.cwd(); - const settings = loadSettings(workingDir); - - try { - // Get current hooks settings - const mergedSettings = settings.merged as - | Record - | undefined; - const hooksSettings = (mergedSettings?.['hooks'] || {}) as Record< - string, - unknown - >; - const disabledHooks = (hooksSettings['disabled'] || []) as string[]; - - // Check if hook is in disabled list - if (!disabledHooks.includes(hookName)) { - debugLogger.info(`Hook "${hookName}" is not disabled.`); - return; - } - - // Remove hook from disabled list - const newDisabledHooks = disabledHooks.filter((h) => h !== hookName); - const newHooksSettings = { - ...hooksSettings, - disabled: newDisabledHooks, - }; - - // Save updated settings - settings.setValue( - SettingScope.Workspace, - 'hooks' as keyof typeof settings.merged, - newHooksSettings as never, - ); - - debugLogger.info(`✓ Hook "${hookName}" has been enabled.`); - } catch (error) { - debugLogger.error(`Error enabling hook: ${getErrorMessage(error)}`); - } -} - -export const enableCommand: CommandModule = { - command: 'enable ', - describe: 'Enable a disabled hook', - builder: (yargs) => - yargs.positional('hook-name', { - describe: 'Name of the hook to enable', - type: 'string', - demandOption: true, - }), - handler: async (argv) => { - const args = argv as unknown as EnableArgs; - await handleEnableHook(args.hookName); - process.exit(0); - }, -}; diff --git a/packages/cli/src/config/config.ts b/packages/cli/src/config/config.ts index 78ef3dde0..fcc33f76a 100755 --- a/packages/cli/src/config/config.ts +++ b/packages/cli/src/config/config.ts @@ -33,8 +33,8 @@ import { } from '@qwen-code/qwen-code-core'; import { extensionsCommand } from '../commands/extensions.js'; import { hooksCommand } from '../commands/hooks.js'; -import type { Settings, LoadedSettings } from './settings.js'; -import { SettingScope } from './settings.js'; +import type { Settings } from './settings.js'; +import { loadSettings, SettingScope } from './settings.js'; import { authCommand } from '../commands/auth.js'; import { resolveCliGenerationConfig, @@ -704,7 +704,6 @@ export async function loadCliConfig( argv: CliArgs, cwd: string = process.cwd(), overrideExtensions?: string[], - loadedSettings?: LoadedSettings, ): Promise { const debugMode = isDebugMode(argv); @@ -1042,20 +1041,19 @@ export async function loadCliConfig( deny: mergedDeny.length > 0 ? mergedDeny : undefined, }, // Permission rule persistence callback (writes to settings files). - onPersistPermissionRule: loadedSettings - ? async (scope, ruleType, rule) => { - const settingScope = - scope === 'project' ? SettingScope.Workspace : SettingScope.User; - const key = `permissions.${ruleType}`; - const currentRules: string[] = - loadedSettings.forScope(settingScope).settings.permissions?.[ - ruleType - ] ?? []; - if (!currentRules.includes(rule)) { - loadedSettings.setValue(settingScope, key, [...currentRules, rule]); - } - } - : undefined, + onPersistPermissionRule: async (scope, ruleType, rule) => { + const currentSettings = loadSettings(cwd); + const settingScope = + scope === 'project' ? SettingScope.Workspace : SettingScope.User; + const key = `permissions.${ruleType}`; + const currentRules: string[] = + currentSettings.forScope(settingScope).settings.permissions?.[ + ruleType + ] ?? []; + if (!currentRules.includes(rule)) { + currentSettings.setValue(settingScope, key, [...currentRules, rule]); + } + }, toolDiscoveryCommand: settings.tools?.discoveryCommand, toolCallCommand: settings.tools?.callCommand, mcpServerCommand: settings.mcp?.serverCommand, diff --git a/packages/cli/src/config/settingsSchema.ts b/packages/cli/src/config/settingsSchema.ts index 379ea2168..d2cf5081c 100644 --- a/packages/cli/src/config/settingsSchema.ts +++ b/packages/cli/src/config/settingsSchema.ts @@ -107,7 +107,7 @@ export interface SettingsSchema { /** * Common items schema for hook definitions. - * Used by both UserPromptSubmit and Stop hooks. + * Used by all hook event types in the hooks configuration. */ const HOOK_DEFINITION_ITEMS: SettingItemDefinition = { type: 'object', @@ -1481,6 +1481,7 @@ const SETTINGS_SCHEMA = { description: 'Hooks that execute when notifications are sent.', showInDialog: false, mergeStrategy: MergeStrategy.CONCAT, + items: HOOK_DEFINITION_ITEMS, }, PreToolUse: { type: 'array', @@ -1491,6 +1492,7 @@ const SETTINGS_SCHEMA = { description: 'Hooks that execute before tool execution.', showInDialog: false, mergeStrategy: MergeStrategy.CONCAT, + items: HOOK_DEFINITION_ITEMS, }, PostToolUse: { type: 'array', @@ -1501,6 +1503,7 @@ const SETTINGS_SCHEMA = { description: 'Hooks that execute after successful tool execution.', showInDialog: false, mergeStrategy: MergeStrategy.CONCAT, + items: HOOK_DEFINITION_ITEMS, }, PostToolUseFailure: { type: 'array', @@ -1511,6 +1514,7 @@ const SETTINGS_SCHEMA = { description: 'Hooks that execute when tool execution fails. ', showInDialog: false, mergeStrategy: MergeStrategy.CONCAT, + items: HOOK_DEFINITION_ITEMS, }, SessionStart: { type: 'array', @@ -1521,6 +1525,7 @@ const SETTINGS_SCHEMA = { description: 'Hooks that execute when a new session starts or resumes.', showInDialog: false, mergeStrategy: MergeStrategy.CONCAT, + items: HOOK_DEFINITION_ITEMS, }, SessionEnd: { type: 'array', @@ -1531,6 +1536,7 @@ const SETTINGS_SCHEMA = { description: 'Hooks that execute when a session ends.', showInDialog: false, mergeStrategy: MergeStrategy.CONCAT, + items: HOOK_DEFINITION_ITEMS, }, PreCompact: { type: 'array', @@ -1541,6 +1547,7 @@ const SETTINGS_SCHEMA = { description: 'Hooks that execute before conversation compaction.', showInDialog: false, mergeStrategy: MergeStrategy.CONCAT, + items: HOOK_DEFINITION_ITEMS, }, SubagentStart: { type: 'array', @@ -1552,6 +1559,7 @@ const SETTINGS_SCHEMA = { 'Hooks that execute when a subagent (Task tool call) is started.', showInDialog: false, mergeStrategy: MergeStrategy.CONCAT, + items: HOOK_DEFINITION_ITEMS, }, SubagentStop: { type: 'array', @@ -1563,6 +1571,7 @@ const SETTINGS_SCHEMA = { 'Hooks that execute right before a subagent (Task tool call) concludes its response.', showInDialog: false, mergeStrategy: MergeStrategy.CONCAT, + items: HOOK_DEFINITION_ITEMS, }, PermissionRequest: { type: 'array', @@ -1574,6 +1583,7 @@ const SETTINGS_SCHEMA = { 'Hooks that execute when a permission dialog is displayed.', showInDialog: false, mergeStrategy: MergeStrategy.CONCAT, + items: HOOK_DEFINITION_ITEMS, }, }, }, diff --git a/packages/cli/src/constants/alibabaStandardApiKey.ts b/packages/cli/src/constants/alibabaStandardApiKey.ts new file mode 100644 index 000000000..cb1c6170c --- /dev/null +++ b/packages/cli/src/constants/alibabaStandardApiKey.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +export type AlibabaStandardRegion = + | 'cn-beijing' + | 'sg-singapore' + | 'us-virginia' + | 'cn-hongkong'; + +export const DASHSCOPE_STANDARD_API_KEY_ENV_KEY = 'DASHSCOPE_API_KEY'; + +export const ALIBABA_STANDARD_API_KEY_ENDPOINTS: Record< + AlibabaStandardRegion, + string +> = { + 'cn-beijing': 'https://dashscope.aliyuncs.com/compatible-mode/v1', + 'sg-singapore': 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1', + 'us-virginia': 'https://dashscope-us.aliyuncs.com/compatible-mode/v1', + 'cn-hongkong': + 'https://cn-hongkong.dashscope.aliyuncs.com/compatible-mode/v1', +}; diff --git a/packages/cli/src/constants/codingPlan.ts b/packages/cli/src/constants/codingPlan.ts index 87be46542..8e7621861 100644 --- a/packages/cli/src/constants/codingPlan.ts +++ b/packages/cli/src/constants/codingPlan.ts @@ -54,7 +54,7 @@ export function generateCodingPlanTemplate( return [ { id: 'qwen3.5-plus', - name: '[Bailian Coding Plan] qwen3.5-plus', + name: '[ModelStudio Coding Plan] qwen3.5-plus', baseUrl: 'https://coding.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { @@ -66,7 +66,7 @@ export function generateCodingPlanTemplate( }, { id: 'glm-5', - name: '[Bailian Coding Plan] glm-5', + name: '[ModelStudio Coding Plan] glm-5', baseUrl: 'https://coding.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { @@ -78,7 +78,7 @@ export function generateCodingPlanTemplate( }, { id: 'kimi-k2.5', - name: '[Bailian Coding Plan] kimi-k2.5', + name: '[ModelStudio Coding Plan] kimi-k2.5', baseUrl: 'https://coding.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { @@ -90,7 +90,7 @@ export function generateCodingPlanTemplate( }, { id: 'MiniMax-M2.5', - name: '[Bailian Coding Plan] MiniMax-M2.5', + name: '[ModelStudio Coding Plan] MiniMax-M2.5', baseUrl: 'https://coding.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { @@ -102,7 +102,7 @@ export function generateCodingPlanTemplate( }, { id: 'qwen3-coder-plus', - name: '[Bailian Coding Plan] qwen3-coder-plus', + name: '[ModelStudio Coding Plan] qwen3-coder-plus', baseUrl: 'https://coding.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { @@ -111,7 +111,7 @@ export function generateCodingPlanTemplate( }, { id: 'qwen3-coder-next', - name: '[Bailian Coding Plan] qwen3-coder-next', + name: '[ModelStudio Coding Plan] qwen3-coder-next', baseUrl: 'https://coding.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { @@ -120,7 +120,7 @@ export function generateCodingPlanTemplate( }, { id: 'qwen3-max-2026-01-23', - name: '[Bailian Coding Plan] qwen3-max-2026-01-23', + name: '[ModelStudio Coding Plan] qwen3-max-2026-01-23', baseUrl: 'https://coding.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { @@ -132,7 +132,7 @@ export function generateCodingPlanTemplate( }, { id: 'glm-4.7', - name: '[Bailian Coding Plan] glm-4.7', + name: '[ModelStudio Coding Plan] glm-4.7', baseUrl: 'https://coding.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { @@ -145,11 +145,11 @@ export function generateCodingPlanTemplate( ]; } - // Global region uses Bailian Coding Plan branding for Global/Intl + // Global region uses ModelStudio Coding Plan branding for Global/Intl return [ { id: 'qwen3.5-plus', - name: '[Bailian Coding Plan for Global/Intl] qwen3.5-plus', + name: '[ModelStudio Coding Plan for Global/Intl] qwen3.5-plus', baseUrl: 'https://coding-intl.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { @@ -161,7 +161,7 @@ export function generateCodingPlanTemplate( }, { id: 'qwen3-coder-plus', - name: '[Bailian Coding Plan for Global/Intl] qwen3-coder-plus', + name: '[ModelStudio Coding Plan for Global/Intl] qwen3-coder-plus', baseUrl: 'https://coding-intl.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { @@ -170,7 +170,7 @@ export function generateCodingPlanTemplate( }, { id: 'qwen3-coder-next', - name: '[Bailian Coding Plan for Global/Intl] qwen3-coder-next', + name: '[ModelStudio Coding Plan for Global/Intl] qwen3-coder-next', baseUrl: 'https://coding-intl.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { @@ -179,7 +179,7 @@ export function generateCodingPlanTemplate( }, { id: 'qwen3-max-2026-01-23', - name: '[Bailian Coding Plan for Global/Intl] qwen3-max-2026-01-23', + name: '[ModelStudio Coding Plan for Global/Intl] qwen3-max-2026-01-23', baseUrl: 'https://coding-intl.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { @@ -191,7 +191,7 @@ export function generateCodingPlanTemplate( }, { id: 'glm-4.7', - name: '[Bailian Coding Plan for Global/Intl] glm-4.7', + name: '[ModelStudio Coding Plan for Global/Intl] glm-4.7', baseUrl: 'https://coding-intl.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { @@ -203,7 +203,7 @@ export function generateCodingPlanTemplate( }, { id: 'glm-5', - name: '[Bailian Coding Plan for Global/Intl] glm-5', + name: '[ModelStudio Coding Plan for Global/Intl] glm-5', baseUrl: 'https://coding-intl.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { @@ -215,7 +215,7 @@ export function generateCodingPlanTemplate( }, { id: 'MiniMax-M2.5', - name: '[Bailian Coding Plan for Global/Intl] MiniMax-M2.5', + name: '[ModelStudio Coding Plan for Global/Intl] MiniMax-M2.5', baseUrl: 'https://coding-intl.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { @@ -227,7 +227,7 @@ export function generateCodingPlanTemplate( }, { id: 'kimi-k2.5', - name: '[Bailian Coding Plan for Global/Intl] kimi-k2.5', + name: '[ModelStudio Coding Plan for Global/Intl] kimi-k2.5', baseUrl: 'https://coding-intl.dashscope.aliyuncs.com/v1', envKey: CODING_PLAN_ENV_KEY, generationConfig: { diff --git a/packages/cli/src/core/initializer.test.ts b/packages/cli/src/core/initializer.test.ts new file mode 100644 index 000000000..7b1b92696 --- /dev/null +++ b/packages/cli/src/core/initializer.test.ts @@ -0,0 +1,109 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { AuthType } from '@qwen-code/qwen-code-core'; +import type { LoadedSettings } from '../config/settings.js'; +import type { Config } from '@qwen-code/qwen-code-core'; +import { initializeApp } from './initializer.js'; +import { performInitialAuth } from './auth.js'; +import { validateTheme } from './theme.js'; +import { initializeI18n } from '../i18n/index.js'; + +vi.mock('./auth.js', () => ({ + performInitialAuth: vi.fn(), +})); + +vi.mock('./theme.js', () => ({ + validateTheme: vi.fn(), +})); + +vi.mock('../i18n/index.js', () => ({ + initializeI18n: vi.fn(), +})); + +describe('initializeApp', () => { + beforeEach(() => { + vi.clearAllMocks(); + delete process.env['QWEN_CODE_LANG']; + + vi.mocked(initializeI18n).mockResolvedValue(undefined); + vi.mocked(validateTheme).mockReturnValue(null); + }); + + function createMockConfig( + options: { + authType?: AuthType; + wasAuthTypeExplicitlyProvided?: boolean; + geminiMdFileCount?: number; + ideMode?: boolean; + } = {}, + ): Config { + const { + authType = AuthType.USE_OPENAI, + wasAuthTypeExplicitlyProvided = true, + geminiMdFileCount = 0, + ideMode = false, + } = options; + + return { + getModelsConfig: vi.fn().mockReturnValue({ + getCurrentAuthType: vi.fn().mockReturnValue(authType), + wasAuthTypeExplicitlyProvided: vi + .fn() + .mockReturnValue(wasAuthTypeExplicitlyProvided), + }), + getIdeMode: vi.fn().mockReturnValue(ideMode), + getGeminiMdFileCount: vi.fn().mockReturnValue(geminiMdFileCount), + } as unknown as Config; + } + + function createMockSettings(): LoadedSettings { + return { + merged: { + general: { + language: 'en', + }, + }, + setValue: vi.fn(), + } as unknown as LoadedSettings; + } + + it('should not clear selected auth type when initial auth fails', async () => { + vi.mocked(performInitialAuth).mockResolvedValue( + 'Failed to login. Message: missing OLLAMA_API_KEY', + ); + + const config = createMockConfig({ + authType: AuthType.USE_OPENAI, + wasAuthTypeExplicitlyProvided: true, + }); + const settings = createMockSettings(); + + const result = await initializeApp(config, settings); + + expect(result.authError).toBe( + 'Failed to login. Message: missing OLLAMA_API_KEY', + ); + expect(result.shouldOpenAuthDialog).toBe(true); + expect(settings.setValue).not.toHaveBeenCalled(); + }); + + it('should not open auth dialog when auth is explicit and succeeds', async () => { + vi.mocked(performInitialAuth).mockResolvedValue(null); + + const config = createMockConfig({ + authType: AuthType.USE_OPENAI, + wasAuthTypeExplicitlyProvided: true, + }); + const settings = createMockSettings(); + + const result = await initializeApp(config, settings); + + expect(result.authError).toBeNull(); + expect(result.shouldOpenAuthDialog).toBe(false); + }); +}); diff --git a/packages/cli/src/core/initializer.ts b/packages/cli/src/core/initializer.ts index 25825ce6d..ce16d1941 100644 --- a/packages/cli/src/core/initializer.ts +++ b/packages/cli/src/core/initializer.ts @@ -11,7 +11,7 @@ import { logIdeConnection, type Config, } from '@qwen-code/qwen-code-core'; -import { type LoadedSettings, SettingScope } from '../config/settings.js'; +import { type LoadedSettings } from '../config/settings.js'; import { performInitialAuth } from './auth.js'; import { validateTheme } from './theme.js'; import { initializeI18n, type SupportedLanguage } from '../i18n/index.js'; @@ -46,14 +46,6 @@ export async function initializeApp( const authType = config.getModelsConfig().getCurrentAuthType(); const authError = await performInitialAuth(config, authType); - // Fallback to user select when initial authentication fails - if (authError) { - settings.setValue( - SettingScope.User, - 'security.auth.selectedType', - undefined, - ); - } const themeError = validateTheme(settings); const shouldOpenAuthDialog = diff --git a/packages/cli/src/gemini.tsx b/packages/cli/src/gemini.tsx index b28ed2591..aebb67993 100644 --- a/packages/cli/src/gemini.tsx +++ b/packages/cli/src/gemini.tsx @@ -358,7 +358,6 @@ export async function main() { argv, process.cwd(), argv.extensions, - settings, ); // Register cleanup for MCP clients as early as possible diff --git a/packages/cli/src/i18n/locales/de.js b/packages/cli/src/i18n/locales/de.js index aa4a6d552..cb3229a2b 100644 --- a/packages/cli/src/i18n/locales/de.js +++ b/packages/cli/src/i18n/locales/de.js @@ -594,6 +594,121 @@ export default { 'List all configured hooks': 'Alle konfigurierten Hooks auflisten', 'Enable a disabled hook': 'Einen deaktivierten Hook aktivieren', 'Disable an active hook': 'Einen aktiven Hook deaktivieren', + // Hooks - Dialog + Hooks: 'Hooks', + 'Loading hooks...': 'Hooks werden geladen...', + 'Error loading hooks:': 'Fehler beim Laden der Hooks:', + 'Press Escape to close': 'Escape zum Schließen drücken', + 'No hook selected': 'Kein Hook ausgewählt', + // Hooks - List Step + 'No hook events found.': 'Keine Hook-Ereignisse gefunden.', + '{{count}} hook configured': '{{count}} Hook konfiguriert', + '{{count}} hooks configured': '{{count}} Hooks konfiguriert', + 'This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.': + 'Dieses Menü ist schreibgeschützt. Um Hooks hinzuzufügen oder zu ändern, bearbeiten Sie settings.json direkt oder fragen Sie Qwen Code.', + 'Enter to select · Esc to cancel': 'Enter zum Auswählen · Esc zum Abbrechen', + // Hooks - Detail Step + 'Exit codes:': 'Exit-Codes:', + 'Configured hooks:': 'Konfigurierte Hooks:', + 'No hooks configured for this event.': + 'Für dieses Ereignis sind keine Hooks konfiguriert.', + 'To add hooks, edit settings.json directly or ask Qwen.': + 'Um Hooks hinzuzufügen, bearbeiten Sie settings.json direkt oder fragen Sie Qwen.', + 'Enter to select · Esc to go back': 'Enter zum Auswählen · Esc zum Zurück', + // Hooks - Config Detail Step + 'Hook details': 'Hook-Details', + 'Event:': 'Ereignis:', + 'Extension:': 'Erweiterung:', + 'Desc:': 'Beschreibung:', + 'No hook config selected': 'Keine Hook-Konfiguration ausgewählt', + 'To modify or remove this hook, edit settings.json directly or ask Qwen to help.': + 'Um diesen Hook zu ändern oder zu entfernen, bearbeiten Sie settings.json direkt oder fragen Sie Qwen.', + // Hooks - Source + Project: 'Projekt', + User: 'Benutzer', + System: 'System', + Extension: 'Erweiterung', + 'Local Settings': 'Lokale Einstellungen', + 'User Settings': 'Benutzereinstellungen', + 'System Settings': 'Systemeinstellungen', + Extensions: 'Erweiterungen', + // Hooks - Status + '✓ Enabled': '✓ Aktiviert', + '✗ Disabled': '✗ Deaktiviert', + // Hooks - Event Descriptions (short) + 'Before tool execution': 'Vor der Tool-Ausführung', + 'After tool execution': 'Nach der Tool-Ausführung', + 'After tool execution fails': 'Wenn die Tool-Ausführung fehlschlägt', + 'When notifications are sent': 'Wenn Benachrichtigungen gesendet werden', + 'When the user submits a prompt': 'Wenn der Benutzer einen Prompt absendet', + 'When a new session is started': 'Wenn eine neue Sitzung gestartet wird', + 'Right before Qwen Code concludes its response': + 'Direkt bevor Qwen Code seine Antwort abschließt', + 'When a subagent (Agent tool call) is started': + 'Wenn ein Subagent (Agent-Tool-Aufruf) gestartet wird', + 'Right before a subagent concludes its response': + 'Direkt bevor ein Subagent seine Antwort abschließt', + 'Before conversation compaction': 'Vor der Gesprächskomprimierung', + 'When a session is ending': 'Wenn eine Sitzung endet', + 'When a permission dialog is displayed': + 'Wenn ein Berechtigungsdialog angezeigt wird', + // Hooks - Event Descriptions (detailed) + 'Input to command is JSON of tool call arguments.': + 'Die Eingabe an den Befehl ist JSON der Tool-Aufruf-Argumente.', + 'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).': + 'Die Eingabe an den Befehl ist JSON mit den Feldern "inputs" (Tool-Aufruf-Argumente) und "response" (Tool-Aufruf-Antwort).', + 'Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.': + 'Die Eingabe an den Befehl ist JSON mit tool_name, tool_input, tool_use_id, error, error_type, is_interrupt und is_timeout.', + 'Input to command is JSON with notification message and type.': + 'Die Eingabe an den Befehl ist JSON mit Benachrichtigungsnachricht und -typ.', + 'Input to command is JSON with original user prompt text.': + 'Die Eingabe an den Befehl ist JSON mit dem ursprünglichen Benutzer-Prompt-Text.', + 'Input to command is JSON with session start source.': + 'Die Eingabe an den Befehl ist JSON mit der Sitzungsstart-Quelle.', + 'Input to command is JSON with session end reason.': + 'Die Eingabe an den Befehl ist JSON mit dem Sitzungsende-Grund.', + 'Input to command is JSON with agent_id and agent_type.': + 'Die Eingabe an den Befehl ist JSON mit agent_id und agent_type.', + 'Input to command is JSON with agent_id, agent_type, and agent_transcript_path.': + 'Die Eingabe an den Befehl ist JSON mit agent_id, agent_type und agent_transcript_path.', + 'Input to command is JSON with compaction details.': + 'Die Eingabe an den Befehl ist JSON mit Komprimierungsdetails.', + 'Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.': + 'Die Eingabe an den Befehl ist JSON mit tool_name, tool_input und tool_use_id. Ausgabe ist JSON mit hookSpecificOutput, das die Entscheidung zum Zulassen oder Ablehnen enthält.', + // Hooks - Exit Code Descriptions + 'stdout/stderr not shown': 'stdout/stderr nicht angezeigt', + 'show stderr to model and continue conversation': + 'stderr dem Modell anzeigen und Konversation fortsetzen', + 'show stderr to user only': 'stderr nur dem Benutzer anzeigen', + 'stdout shown in transcript mode (ctrl+o)': + 'stdout im Transkriptmodus angezeigt (ctrl+o)', + 'show stderr to model immediately': 'stderr sofort dem Modell anzeigen', + 'show stderr to user only but continue with tool call': + 'stderr nur dem Benutzer anzeigen, aber mit Tool-Aufruf fortfahren', + 'block processing, erase original prompt, and show stderr to user only': + 'Verarbeitung blockieren, ursprünglichen Prompt löschen und stderr nur dem Benutzer anzeigen', + 'stdout shown to Qwen': 'stdout dem Qwen anzeigen', + 'show stderr to user only (blocking errors ignored)': + 'stderr nur dem Benutzer anzeigen (Blockierungsfehler ignoriert)', + 'command completes successfully': 'Befehl erfolgreich abgeschlossen', + 'stdout shown to subagent': 'stdout dem Subagenten anzeigen', + 'show stderr to subagent and continue having it run': + 'stderr dem Subagenten anzeigen und ihn weiterlaufen lassen', + 'stdout appended as custom compact instructions': + 'stdout als benutzerdefinierte Komprimierungsanweisungen angehängt', + 'block compaction': 'Komprimierung blockieren', + 'show stderr to user only but continue with compaction': + 'stderr nur dem Benutzer anzeigen, aber mit Komprimierung fortfahren', + 'use hook decision if provided': + 'Hook-Entscheidung verwenden, falls bereitgestellt', + // Hooks - Messages + 'Config not loaded.': 'Konfiguration nicht geladen.', + 'Hooks are not enabled. Enable hooks in settings to use this feature.': + 'Hooks sind nicht aktiviert. Aktivieren Sie Hooks in den Einstellungen, um diese Funktion zu nutzen.', + 'No hooks configured. Add hooks in your settings.json file.': + 'Keine Hooks konfiguriert. Fügen Sie Hooks in Ihrer settings.json-Datei hinzu.', + 'Configured Hooks ({{count}} total)': + 'Konfigurierte Hooks ({{count}} insgesamt)', // ============================================================================ // Commands - Session Export @@ -708,7 +823,6 @@ export default { 'Workspace approval mode exists and takes priority. User-level change will have no effect.': 'Arbeitsbereich-Genehmigungsmodus existiert und hat Vorrang. Benutzerebene-Änderung hat keine Wirkung.', 'Apply To': 'Anwenden auf', - 'User Settings': 'Benutzereinstellungen', 'Workspace Settings': 'Arbeitsbereich-Einstellungen', // ============================================================================ @@ -763,7 +877,6 @@ export default { 'List configured MCP servers and tools': 'Konfigurierte MCP-Server und Werkzeuge auflisten', 'Restarts MCP servers.': 'MCP-Server neu starten.', - 'Config not loaded.': 'Konfiguration nicht geladen.', 'Could not retrieve tool registry.': 'Werkzeugregister konnte nicht abgerufen werden.', 'No MCP servers configured with OAuth authentication.': @@ -972,7 +1085,6 @@ export default { 'No server selected': 'Kein Server ausgewählt', '(disabled)': '(deaktiviert)', 'Error:': 'Fehler:', - Extension: 'Erweiterung', tool: 'Werkzeug', tools: 'Werkzeuge', connected: 'verbunden', @@ -1047,7 +1159,11 @@ export default { "Ausführung erlauben von: '{{command}}'?", 'Yes, allow always ...': 'Ja, immer erlauben ...', 'Always allow in this project': 'In diesem Projekt immer erlauben', + 'Always allow {{action}} in this project': + '{{action}} in diesem Projekt immer erlauben', 'Always allow for this user': 'Für diesen Benutzer immer erlauben', + 'Always allow {{action}} for this user': + '{{action}} für diesen Benutzer immer erlauben', 'Yes, and auto-accept edits': 'Ja, und Änderungen automatisch akzeptieren', 'Yes, and manually approve edits': 'Ja, und Änderungen manuell genehmigen', 'No, keep planning (esc)': 'Nein, weiter planen (Esc)', @@ -1668,8 +1784,8 @@ export default { // Auth Dialog - View Titles and Labels // ============================================================================ 'Coding Plan': 'Coding Plan', - "Paste your api key of Bailian Coding Plan and you're all set!": - 'Fügen Sie Ihren Bailian Coding Plan API-Schlüssel ein und Sie sind bereit!', + "Paste your api key of ModelStudio Coding Plan and you're all set!": + 'Fügen Sie Ihren ModelStudio Coding Plan API-Schlüssel ein und Sie sind bereit!', Custom: 'Benutzerdefiniert', 'More instructions about configuring `modelProviders` manually.': 'Weitere Anweisungen zur manuellen Konfiguration von `modelProviders`.', diff --git a/packages/cli/src/i18n/locales/en.js b/packages/cli/src/i18n/locales/en.js index fb4433b2a..3178ea533 100644 --- a/packages/cli/src/i18n/locales/en.js +++ b/packages/cli/src/i18n/locales/en.js @@ -668,6 +668,118 @@ export default { 'List all configured hooks': 'List all configured hooks', 'Enable a disabled hook': 'Enable a disabled hook', 'Disable an active hook': 'Disable an active hook', + // Hooks - Dialog + Hooks: 'Hooks', + 'Loading hooks...': 'Loading hooks...', + 'Error loading hooks:': 'Error loading hooks:', + 'Press Escape to close': 'Press Escape to close', + 'No hook selected': 'No hook selected', + // Hooks - List Step + 'No hook events found.': 'No hook events found.', + '{{count}} hook configured': '{{count}} hook configured', + '{{count}} hooks configured': '{{count}} hooks configured', + 'This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.': + 'This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.', + 'Enter to select · Esc to cancel': 'Enter to select · Esc to cancel', + // Hooks - Detail Step + 'Exit codes:': 'Exit codes:', + 'Configured hooks:': 'Configured hooks:', + 'No hooks configured for this event.': 'No hooks configured for this event.', + 'To add hooks, edit settings.json directly or ask Qwen.': + 'To add hooks, edit settings.json directly or ask Qwen.', + 'Enter to select · Esc to go back': 'Enter to select · Esc to go back', + // Hooks - Config Detail Step + 'Hook details': 'Hook details', + 'Event:': 'Event:', + 'Extension:': 'Extension:', + 'Desc:': 'Desc:', + 'No hook config selected': 'No hook config selected', + 'To modify or remove this hook, edit settings.json directly or ask Qwen to help.': + 'To modify or remove this hook, edit settings.json directly or ask Qwen to help.', + // Hooks - Source + Project: 'Project', + User: 'User', + System: 'System', + Extension: 'Extension', + 'Local Settings': 'Local Settings', + 'User Settings': 'User Settings', + 'System Settings': 'System Settings', + Extensions: 'Extensions', + // Hooks - Status + '✓ Enabled': '✓ Enabled', + '✗ Disabled': '✗ Disabled', + // Hooks - Event Descriptions (short) + 'Before tool execution': 'Before tool execution', + 'After tool execution': 'After tool execution', + 'After tool execution fails': 'After tool execution fails', + 'When notifications are sent': 'When notifications are sent', + 'When the user submits a prompt': 'When the user submits a prompt', + 'When a new session is started': 'When a new session is started', + 'Right before Qwen Code concludes its response': + 'Right before Qwen Code concludes its response', + 'When a subagent (Agent tool call) is started': + 'When a subagent (Agent tool call) is started', + 'Right before a subagent concludes its response': + 'Right before a subagent concludes its response', + 'Before conversation compaction': 'Before conversation compaction', + 'When a session is ending': 'When a session is ending', + 'When a permission dialog is displayed': + 'When a permission dialog is displayed', + // Hooks - Event Descriptions (detailed) + 'Input to command is JSON of tool call arguments.': + 'Input to command is JSON of tool call arguments.', + 'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).': + 'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).', + 'Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.': + 'Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.', + 'Input to command is JSON with notification message and type.': + 'Input to command is JSON with notification message and type.', + 'Input to command is JSON with original user prompt text.': + 'Input to command is JSON with original user prompt text.', + 'Input to command is JSON with session start source.': + 'Input to command is JSON with session start source.', + 'Input to command is JSON with session end reason.': + 'Input to command is JSON with session end reason.', + 'Input to command is JSON with agent_id and agent_type.': + 'Input to command is JSON with agent_id and agent_type.', + 'Input to command is JSON with agent_id, agent_type, and agent_transcript_path.': + 'Input to command is JSON with agent_id, agent_type, and agent_transcript_path.', + 'Input to command is JSON with compaction details.': + 'Input to command is JSON with compaction details.', + 'Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.': + 'Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.', + // Hooks - Exit Code Descriptions + 'stdout/stderr not shown': 'stdout/stderr not shown', + 'show stderr to model and continue conversation': + 'show stderr to model and continue conversation', + 'show stderr to user only': 'show stderr to user only', + 'stdout shown in transcript mode (ctrl+o)': + 'stdout shown in transcript mode (ctrl+o)', + 'show stderr to model immediately': 'show stderr to model immediately', + 'show stderr to user only but continue with tool call': + 'show stderr to user only but continue with tool call', + 'block processing, erase original prompt, and show stderr to user only': + 'block processing, erase original prompt, and show stderr to user only', + 'stdout shown to Qwen': 'stdout shown to Qwen', + 'show stderr to user only (blocking errors ignored)': + 'show stderr to user only (blocking errors ignored)', + 'command completes successfully': 'command completes successfully', + 'stdout shown to subagent': 'stdout shown to subagent', + 'show stderr to subagent and continue having it run': + 'show stderr to subagent and continue having it run', + 'stdout appended as custom compact instructions': + 'stdout appended as custom compact instructions', + 'block compaction': 'block compaction', + 'show stderr to user only but continue with compaction': + 'show stderr to user only but continue with compaction', + 'use hook decision if provided': 'use hook decision if provided', + // Hooks - Messages + 'Config not loaded.': 'Config not loaded.', + 'Hooks are not enabled. Enable hooks in settings to use this feature.': + 'Hooks are not enabled. Enable hooks in settings to use this feature.', + 'No hooks configured. Add hooks in your settings.json file.': + 'No hooks configured. Add hooks in your settings.json file.', + 'Configured Hooks ({{count}} total)': 'Configured Hooks ({{count}} total)', // ============================================================================ // Commands - Session Export @@ -775,7 +887,6 @@ export default { 'Workspace approval mode exists and takes priority. User-level change will have no effect.': 'Workspace approval mode exists and takes priority. User-level change will have no effect.', 'Apply To': 'Apply To', - 'User Settings': 'User Settings', 'Workspace Settings': 'Workspace Settings', // ============================================================================ @@ -829,7 +940,6 @@ export default { 'List configured MCP servers and tools', 'Restarts MCP servers.': 'Restarts MCP servers.', 'Open MCP management dialog': 'Open MCP management dialog', - 'Config not loaded.': 'Config not loaded.', 'Could not retrieve tool registry.': 'Could not retrieve tool registry.', 'No MCP servers configured with OAuth authentication.': 'No MCP servers configured with OAuth authentication.', @@ -895,7 +1005,6 @@ export default { prompts: 'prompts', '(disabled)': '(disabled)', 'Error:': 'Error:', - Extension: 'Extension', tool: 'tool', tools: 'tools', connected: 'connected', @@ -1103,7 +1212,11 @@ export default { "Allow execution of: '{{command}}'?": "Allow execution of: '{{command}}'?", 'Yes, allow always ...': 'Yes, allow always ...', 'Always allow in this project': 'Always allow in this project', + 'Always allow {{action}} in this project': + 'Always allow {{action}} in this project', 'Always allow for this user': 'Always allow for this user', + 'Always allow {{action}} for this user': + 'Always allow {{action}} for this user', 'Yes, and auto-accept edits': 'Yes, and auto-accept edits', 'Yes, and manually approve edits': 'Yes, and manually approve edits', 'No, keep planning (esc)': 'No, keep planning (esc)', @@ -1720,8 +1833,8 @@ export default { // Auth Dialog - View Titles and Labels // ============================================================================ 'Coding Plan': 'Coding Plan', - "Paste your api key of Bailian Coding Plan and you're all set!": - "Paste your api key of Bailian Coding Plan and you're all set!", + "Paste your api key of ModelStudio Coding Plan and you're all set!": + "Paste your api key of ModelStudio Coding Plan and you're all set!", Custom: 'Custom', 'More instructions about configuring `modelProviders` manually.': 'More instructions about configuring `modelProviders` manually.', diff --git a/packages/cli/src/i18n/locales/ja.js b/packages/cli/src/i18n/locales/ja.js index b06a6fdef..ac5f59111 100644 --- a/packages/cli/src/i18n/locales/ja.js +++ b/packages/cli/src/i18n/locales/ja.js @@ -380,6 +380,118 @@ export default { 'List all configured hooks': '設定済みのフックをすべて表示する', 'Enable a disabled hook': '無効なフックを有効にする', 'Disable an active hook': '有効なフックを無効にする', + // Hooks - Dialog + Hooks: 'フック', + 'Loading hooks...': 'フックを読み込んでいます...', + 'Error loading hooks:': 'フックの読み込みエラー:', + 'Press Escape to close': 'Escape キーで閉じる', + 'No hook selected': 'フックが選択されていません', + // Hooks - List Step + 'No hook events found.': 'フックイベントが見つかりません。', + '{{count}} hook configured': '{{count}} 件のフックが設定されています', + '{{count}} hooks configured': '{{count}} 件のフックが設定されています', + 'This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.': + 'このメニューは読み取り専用です。フックを追加または変更するには、settings.json を直接編集するか、Qwen Code に尋ねてください。', + 'Enter to select · Esc to cancel': 'Enter で選択 · Esc でキャンセル', + // Hooks - Detail Step + 'Exit codes:': '終了コード:', + 'Configured hooks:': '設定済みのフック:', + 'No hooks configured for this event.': + 'このイベントにはフックが設定されていません。', + 'To add hooks, edit settings.json directly or ask Qwen.': + 'フックを追加するには、settings.json を直接編集するか、Qwen に尋ねてください。', + 'Enter to select · Esc to go back': 'Enter で選択 · Esc で戻る', + // Hooks - Config Detail Step + 'Hook details': 'フック詳細', + 'Event:': 'イベント:', + 'Extension:': '拡張機能:', + 'Desc:': '説明:', + 'No hook config selected': 'フック設定が選択されていません', + 'To modify or remove this hook, edit settings.json directly or ask Qwen to help.': + 'このフックを変更または削除するには、settings.json を直接編集するか、Qwen に尋ねてください。', + // Hooks - Source + Project: 'プロジェクト', + User: 'ユーザー', + System: 'システム', + Extension: '拡張機能', + 'Local Settings': 'ローカル設定', + 'User Settings': 'ユーザー設定', + 'System Settings': 'システム設定', + Extensions: '拡張機能', + // Hooks - Status + '✓ Enabled': '✓ 有効', + '✗ Disabled': '✗ 無効', + // Hooks - Event Descriptions (short) + 'Before tool execution': 'ツール実行前', + 'After tool execution': 'ツール実行後', + 'After tool execution fails': 'ツール実行失敗時', + 'When notifications are sent': '通知送信時', + 'When the user submits a prompt': 'ユーザーがプロンプトを送信した時', + 'When a new session is started': '新しいセッションが開始された時', + 'Right before Qwen Code concludes its response': + 'Qwen Code が応答を終了する直前', + 'When a subagent (Agent tool call) is started': + 'サブエージェント(Agent ツール呼び出し)が開始された時', + 'Right before a subagent concludes its response': + 'サブエージェントが応答を終了する直前', + 'Before conversation compaction': '会話圧縮前', + 'When a session is ending': 'セッション終了時', + 'When a permission dialog is displayed': '権限ダイアログ表示時', + // Hooks - Event Descriptions (detailed) + 'Input to command is JSON of tool call arguments.': + 'コマンドへの入力はツール呼び出し引数の JSON です。', + 'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).': + 'コマンドへの入力は "inputs"(ツール呼び出し引数)と "response"(ツール呼び出し応答)フィールドを持つ JSON です。', + 'Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.': + 'コマンドへの入力は tool_name、tool_input、tool_use_id、error、error_type、is_interrupt、is_timeout を持つ JSON です。', + 'Input to command is JSON with notification message and type.': + 'コマンドへの入力は通知メッセージとタイプを持つ JSON です。', + 'Input to command is JSON with original user prompt text.': + 'コマンドへの入力は元のユーザープロンプトテキストを持つ JSON です。', + 'Input to command is JSON with session start source.': + 'コマンドへの入力はセッション開始ソースを持つ JSON です。', + 'Input to command is JSON with session end reason.': + 'コマンドへの入力はセッション終了理由を持つ JSON です。', + 'Input to command is JSON with agent_id and agent_type.': + 'コマンドへの入力は agent_id と agent_type を持つ JSON です。', + 'Input to command is JSON with agent_id, agent_type, and agent_transcript_path.': + 'コマンドへの入力は agent_id、agent_type、agent_transcript_path を持つ JSON です。', + 'Input to command is JSON with compaction details.': + 'コマンドへの入力は圧縮詳細を持つ JSON です。', + 'Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.': + 'コマンドへの入力は tool_name、tool_input、tool_use_id を持つ JSON です。許可または拒否の決定を含む hookSpecificOutput を持つ JSON を出力します。', + // Hooks - Exit Code Descriptions + 'stdout/stderr not shown': 'stdout/stderr は表示されません', + 'show stderr to model and continue conversation': + 'stderr をモデルに表示し、会話を続ける', + 'show stderr to user only': 'stderr をユーザーのみに表示', + 'stdout shown in transcript mode (ctrl+o)': + 'stdout はトランスクリプトモードで表示 (ctrl+o)', + 'show stderr to model immediately': 'stderr をモデルに即座に表示', + 'show stderr to user only but continue with tool call': + 'stderr をユーザーのみに表示し、ツール呼び出しを続ける', + 'block processing, erase original prompt, and show stderr to user only': + '処理をブロックし、元のプロンプトを消去し、stderr をユーザーのみに表示', + 'stdout shown to Qwen': 'stdout をモデルに表示', + 'show stderr to user only (blocking errors ignored)': + 'stderr をユーザーのみに表示(ブロッキングエラーは無視)', + 'command completes successfully': 'コマンドが正常に完了', + 'stdout shown to subagent': 'stdout をサブエージェントに表示', + 'show stderr to subagent and continue having it run': + 'stderr をサブエージェントに表示し、実行を続ける', + 'stdout appended as custom compact instructions': + 'stdout をカスタム圧縮指示として追加', + 'block compaction': '圧縮をブロック', + 'show stderr to user only but continue with compaction': + 'stderr をユーザーのみに表示し、圧縮を続ける', + 'use hook decision if provided': '提供されている場合はフックの決定を使用', + // Hooks - Messages + 'Config not loaded.': '設定が読み込まれていません。', + 'Hooks are not enabled. Enable hooks in settings to use this feature.': + 'フックが有効になっていません。この機能を使用するには設定でフックを有効にしてください。', + 'No hooks configured. Add hooks in your settings.json file.': + 'フックが設定されていません。settings.json ファイルにフックを追加してください。', + 'Configured Hooks ({{count}} total)': '設定済みのフック(合計 {{count}} 件)', // ============================================================================ // Commands - Session Export @@ -480,7 +592,6 @@ export default { '(Use Enter to select, Tab to change focus)': '(Enter で選択、Tab でフォーカス変更)', 'Apply To': '適用先', - 'User Settings': 'ユーザー設定', 'Workspace Settings': 'ワークスペース設定', // Memory 'Commands for interacting with memory.': 'メモリ操作のコマンド', @@ -527,7 +638,6 @@ export default { '設定済みのMCPサーバーとツールを一覧表示', 'No MCP servers configured.': 'MCPサーバーが設定されていません', 'Restarts MCP servers.': 'MCPサーバーを再起動します', - 'Config not loaded.': '設定が読み込まれていません', 'Could not retrieve tool registry.': 'ツールレジストリを取得できませんでした', 'No MCP servers configured with OAuth authentication.': 'OAuth認証が設定されたMCPサーバーはありません', @@ -712,7 +822,6 @@ export default { 'No server selected': 'サーバーが選択されていません', '(disabled)': '(無効)', 'Error:': 'エラー:', - Extension: '拡張機能', tool: 'ツール', tools: 'ツール', connected: '接続済み', @@ -786,7 +895,10 @@ export default { "Allow execution of: '{{command}}'?": "'{{command}}' の実行を許可しますか?", 'Yes, allow always ...': 'はい、常に許可...', 'Always allow in this project': 'このプロジェクトで常に許可', + 'Always allow {{action}} in this project': + 'このプロジェクトで{{action}}を常に許可', 'Always allow for this user': 'このユーザーに常に許可', + 'Always allow {{action}} for this user': 'このユーザーに{{action}}を常に許可', 'Yes, and auto-accept edits': 'はい、編集を自動承認', 'Yes, and manually approve edits': 'はい、編集を手動承認', 'No, keep planning (esc)': 'いいえ、計画を続ける (Esc)', @@ -1173,8 +1285,8 @@ export default { // Auth Dialog - View Titles and Labels // ============================================================================ 'Coding Plan': 'Coding Plan', - "Paste your api key of Bailian Coding Plan and you're all set!": - 'Bailian Coding PlanのAPIキーを貼り付けるだけで準備完了です!', + "Paste your api key of ModelStudio Coding Plan and you're all set!": + 'ModelStudio Coding PlanのAPIキーを貼り付けるだけで準備完了です!', Custom: 'カスタム', 'More instructions about configuring `modelProviders` manually.': '`modelProviders`を手動で設定する方法の詳細はこちら。', diff --git a/packages/cli/src/i18n/locales/pt.js b/packages/cli/src/i18n/locales/pt.js index b2240877b..993cd8d8c 100644 --- a/packages/cli/src/i18n/locales/pt.js +++ b/packages/cli/src/i18n/locales/pt.js @@ -599,6 +599,120 @@ export default { 'List all configured hooks': 'Listar todos os hooks configurados', 'Enable a disabled hook': 'Ativar um hook desativado', 'Disable an active hook': 'Desativar um hook ativo', + // Hooks - Dialog + Hooks: 'Hooks', + 'Loading hooks...': 'Carregando hooks...', + 'Error loading hooks:': 'Erro ao carregar hooks:', + 'Press Escape to close': 'Pressione Escape para fechar', + 'No hook selected': 'Nenhum hook selecionado', + // Hooks - List Step + 'No hook events found.': 'Nenhum evento de hook encontrado.', + '{{count}} hook configured': '{{count}} hook configurado', + '{{count}} hooks configured': '{{count}} hooks configurados', + 'This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.': + 'Este menu é somente leitura. Para adicionar ou modificar hooks, edite settings.json diretamente ou pergunte ao Qwen Code.', + 'Enter to select · Esc to cancel': + 'Enter para selecionar · Esc para cancelar', + // Hooks - Detail Step + 'Exit codes:': 'Códigos de saída:', + 'Configured hooks:': 'Hooks configurados:', + 'No hooks configured for this event.': + 'Nenhum hook configurado para este evento.', + 'To add hooks, edit settings.json directly or ask Qwen.': + 'Para adicionar hooks, edite settings.json diretamente ou pergunte ao Qwen.', + 'Enter to select · Esc to go back': 'Enter para selecionar · Esc para voltar', + // Hooks - Config Detail Step + 'Hook details': 'Detalhes do Hook', + 'Event:': 'Evento:', + 'Extension:': 'Extensão:', + 'Desc:': 'Descrição:', + 'No hook config selected': 'Nenhuma configuração de hook selecionada', + 'To modify or remove this hook, edit settings.json directly or ask Qwen to help.': + 'Para modificar ou remover este hook, edite settings.json diretamente ou pergunte ao Qwen.', + // Hooks - Source + Project: 'Projeto', + User: 'Usuário', + System: 'Sistema', + Extension: 'Extensão', + 'Local Settings': 'Configurações Locais', + 'User Settings': 'Configurações do Usuário', + 'System Settings': 'Configurações do Sistema', + Extensions: 'Extensões', + // Hooks - Status + '✓ Enabled': '✓ Ativado', + '✗ Disabled': '✗ Desativado', + // Hooks - Event Descriptions (short) + 'Before tool execution': 'Antes da execução da ferramenta', + 'After tool execution': 'Após a execução da ferramenta', + 'After tool execution fails': 'Após a falha da execução da ferramenta', + 'When notifications are sent': 'Quando notificações são enviadas', + 'When the user submits a prompt': 'Quando o usuário envia um prompt', + 'When a new session is started': 'Quando uma nova sessão é iniciada', + 'Right before Qwen Code concludes its response': + 'Logo antes do Qwen Code concluir sua resposta', + 'When a subagent (Agent tool call) is started': + 'Quando um subagente (chamada de ferramenta Agent) é iniciado', + 'Right before a subagent concludes its response': + 'Logo antes de um subagente concluir sua resposta', + 'Before conversation compaction': 'Antes da compactação da conversa', + 'When a session is ending': 'Quando uma sessão está terminando', + 'When a permission dialog is displayed': + 'Quando um diálogo de permissão é exibido', + // Hooks - Event Descriptions (detailed) + 'Input to command is JSON of tool call arguments.': + 'A entrada para o comando é JSON dos argumentos da chamada da ferramenta.', + 'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).': + 'A entrada para o comando é JSON com campos "inputs" (argumentos da chamada da ferramenta) e "response" (resposta da chamada da ferramenta).', + 'Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.': + 'A entrada para o comando é JSON com tool_name, tool_input, tool_use_id, error, error_type, is_interrupt e is_timeout.', + 'Input to command is JSON with notification message and type.': + 'A entrada para o comando é JSON com mensagem e tipo de notificação.', + 'Input to command is JSON with original user prompt text.': + 'A entrada para o comando é JSON com o texto original do prompt do usuário.', + 'Input to command is JSON with session start source.': + 'A entrada para o comando é JSON com a fonte de início da sessão.', + 'Input to command is JSON with session end reason.': + 'A entrada para o comando é JSON com o motivo do fim da sessão.', + 'Input to command is JSON with agent_id and agent_type.': + 'A entrada para o comando é JSON com agent_id e agent_type.', + 'Input to command is JSON with agent_id, agent_type, and agent_transcript_path.': + 'A entrada para o comando é JSON com agent_id, agent_type e agent_transcript_path.', + 'Input to command is JSON with compaction details.': + 'A entrada para o comando é JSON com detalhes da compactação.', + 'Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.': + 'A entrada para o comando é JSON com tool_name, tool_input e tool_use_id. Saída é JSON com hookSpecificOutput contendo decisão de permitir ou negar.', + // Hooks - Exit Code Descriptions + 'stdout/stderr not shown': 'stdout/stderr não exibido', + 'show stderr to model and continue conversation': + 'mostrar stderr ao modelo e continuar conversa', + 'show stderr to user only': 'mostrar stderr apenas ao usuário', + 'stdout shown in transcript mode (ctrl+o)': + 'stdout exibido no modo transcrição (ctrl+o)', + 'show stderr to model immediately': 'mostrar stderr ao modelo imediatamente', + 'show stderr to user only but continue with tool call': + 'mostrar stderr apenas ao usuário mas continuar com chamada de ferramenta', + 'block processing, erase original prompt, and show stderr to user only': + 'bloquear processamento, apagar prompt original e mostrar stderr apenas ao usuário', + 'stdout shown to Qwen': 'stdout mostrado ao Qwen', + 'show stderr to user only (blocking errors ignored)': + 'mostrar stderr apenas ao usuário (erros de bloqueio ignorados)', + 'command completes successfully': 'comando concluído com sucesso', + 'stdout shown to subagent': 'stdout mostrado ao subagente', + 'show stderr to subagent and continue having it run': + 'mostrar stderr ao subagente e continuar executando', + 'stdout appended as custom compact instructions': + 'stdout anexado como instruções de compactação personalizadas', + 'block compaction': 'bloquear compactação', + 'show stderr to user only but continue with compaction': + 'mostrar stderr apenas ao usuário mas continuar com compactação', + 'use hook decision if provided': 'usar decisão do hook se fornecida', + // Hooks - Messages + 'Config not loaded.': 'Configuração não carregada.', + 'Hooks are not enabled. Enable hooks in settings to use this feature.': + 'Hooks não estão ativados. Ative hooks nas configurações para usar este recurso.', + 'No hooks configured. Add hooks in your settings.json file.': + 'Nenhum hook configurado. Adicione hooks no seu arquivo settings.json.', + 'Configured Hooks ({{count}} total)': 'Hooks Configurados ({{count}} total)', // ============================================================================ // Commands - Session Export @@ -712,7 +826,6 @@ export default { 'Workspace approval mode exists and takes priority. User-level change will have no effect.': 'O modo de aprovação do workspace existe e tem prioridade. A alteração no nível do usuário não terá efeito.', 'Apply To': 'Aplicar A', - 'User Settings': 'Configurações do Usuário', 'Workspace Settings': 'Configurações do Workspace', // ============================================================================ @@ -769,7 +882,6 @@ export default { 'List configured MCP servers and tools': 'Listar servidores e ferramentas MCP configurados', 'Restarts MCP servers.': 'Reinicia os servidores MCP.', - 'Config not loaded.': 'Configuração não carregada.', 'Could not retrieve tool registry.': 'Não foi possível recuperar o registro de ferramentas.', 'No MCP servers configured with OAuth authentication.': @@ -979,7 +1091,6 @@ export default { 'No server selected': 'Nenhum servidor selecionado', '(disabled)': '(desativado)', 'Error:': 'Erro:', - Extension: 'Extensão', tool: 'ferramenta', tools: 'ferramentas', connected: 'conectado', @@ -1054,7 +1165,11 @@ export default { "Permitir a execução de: '{{command}}'?", 'Yes, allow always ...': 'Sim, permitir sempre ...', 'Always allow in this project': 'Sempre permitir neste projeto', + 'Always allow {{action}} in this project': + 'Sempre permitir {{action}} neste projeto', 'Always allow for this user': 'Sempre permitir para este usuário', + 'Always allow {{action}} for this user': + 'Sempre permitir {{action}} para este usuário', 'Yes, and auto-accept edits': 'Sim, e aceitar edições automaticamente', 'Yes, and manually approve edits': 'Sim, e aprovar edições manualmente', 'No, keep planning (esc)': 'Não, continuar planejando (esc)', @@ -1662,8 +1777,8 @@ export default { // Auth Dialog - View Titles and Labels // ============================================================================ 'Coding Plan': 'Coding Plan', - "Paste your api key of Bailian Coding Plan and you're all set!": - 'Cole sua chave de API do Bailian Coding Plan e pronto!', + "Paste your api key of ModelStudio Coding Plan and you're all set!": + 'Cole sua chave de API do ModelStudio Coding Plan e pronto!', Custom: 'Personalizado', 'More instructions about configuring `modelProviders` manually.': 'Mais instruções sobre como configurar `modelProviders` manualmente.', diff --git a/packages/cli/src/i18n/locales/ru.js b/packages/cli/src/i18n/locales/ru.js index c3ae5953a..bb7e8968f 100644 --- a/packages/cli/src/i18n/locales/ru.js +++ b/packages/cli/src/i18n/locales/ru.js @@ -605,6 +605,119 @@ export default { 'List all configured hooks': 'Показать все настроенные хуки', 'Enable a disabled hook': 'Включить отключенный хук', 'Disable an active hook': 'Отключить активный хук', + // Hooks - Dialog + Hooks: 'Хуки', + 'Loading hooks...': 'Загрузка хуков...', + 'Error loading hooks:': 'Ошибка загрузки хуков:', + 'Press Escape to close': 'Нажмите Escape для закрытия', + 'No hook selected': 'Хук не выбран', + // Hooks - List Step + 'No hook events found.': 'События хуков не найдены.', + '{{count}} hook configured': '{{count}} хук настроен', + '{{count}} hooks configured': '{{count}} хуков настроено', + 'This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.': + 'Это меню только для чтения. Чтобы добавить или изменить хуки, отредактируйте settings.json напрямую или спросите Qwen Code.', + 'Enter to select · Esc to cancel': 'Enter для выбора · Esc для отмены', + // Hooks - Detail Step + 'Exit codes:': 'Коды выхода:', + 'Configured hooks:': 'Настроенные хуки:', + 'No hooks configured for this event.': + 'Для этого события нет настроенных хуков.', + 'To add hooks, edit settings.json directly or ask Qwen.': + 'Чтобы добавить хуки, отредактируйте settings.json напрямую или спросите Qwen.', + 'Enter to select · Esc to go back': 'Enter для выбора · Esc для возврата', + // Hooks - Config Detail Step + 'Hook details': 'Детали хука', + 'Event:': 'Событие:', + 'Extension:': 'Расширение:', + 'Desc:': 'Описание:', + 'No hook config selected': 'Конфигурация хука не выбрана', + 'To modify or remove this hook, edit settings.json directly or ask Qwen to help.': + 'Чтобы изменить или удалить этот хук, отредактируйте settings.json напрямую или спросите Qwen.', + // Hooks - Source + Project: 'Проект', + User: 'Пользователь', + System: 'Система', + Extension: 'Расширение', + 'Local Settings': 'Локальные настройки', + 'User Settings': 'Пользовательские настройки', + 'System Settings': 'Системные настройки', + Extensions: 'Расширения', + // Hooks - Status + '✓ Enabled': '✓ Включен', + '✗ Disabled': '✗ Отключен', + // Hooks - Event Descriptions (short) + 'Before tool execution': 'Перед выполнением инструмента', + 'After tool execution': 'После выполнения инструмента', + 'After tool execution fails': 'При неудачном выполнении инструмента', + 'When notifications are sent': 'При отправке уведомлений', + 'When the user submits a prompt': 'Когда пользователь отправляет промпт', + 'When a new session is started': 'При запуске новой сессии', + 'Right before Qwen Code concludes its response': + 'Непосредственно перед завершением ответа Qwen Code', + 'When a subagent (Agent tool call) is started': + 'При запуске субагента (вызов инструмента Agent)', + 'Right before a subagent concludes its response': + 'Непосредственно перед завершением ответа субагента', + 'Before conversation compaction': 'Перед сжатием разговора', + 'When a session is ending': 'При завершении сессии', + 'When a permission dialog is displayed': 'При отображении диалога разрешений', + // Hooks - Event Descriptions (detailed) + 'Input to command is JSON of tool call arguments.': + 'Ввод в команду — это JSON аргументов вызова инструмента.', + 'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).': + 'Ввод в команду — это JSON с полями "inputs" (аргументы вызова инструмента) и "response" (ответ вызова инструмента).', + 'Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.': + 'Ввод в команду — это JSON с tool_name, tool_input, tool_use_id, error, error_type, is_interrupt и is_timeout.', + 'Input to command is JSON with notification message and type.': + 'Ввод в команду — это JSON с сообщением уведомления и типом.', + 'Input to command is JSON with original user prompt text.': + 'Ввод в команду — это JSON с исходным текстом промпта пользователя.', + 'Input to command is JSON with session start source.': + 'Ввод в команду — это JSON с источником запуска сессии.', + 'Input to command is JSON with session end reason.': + 'Ввод в команду — это JSON с причиной завершения сессии.', + 'Input to command is JSON with agent_id and agent_type.': + 'Ввод в команду — это JSON с agent_id и agent_type.', + 'Input to command is JSON with agent_id, agent_type, and agent_transcript_path.': + 'Ввод в команду — это JSON с agent_id, agent_type и agent_transcript_path.', + 'Input to command is JSON with compaction details.': + 'Ввод в команду — это JSON с деталями сжатия.', + 'Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.': + 'Ввод в команду — это JSON с tool_name, tool_input и tool_use_id. Вывод — JSON с hookSpecificOutput, содержащим решение о разрешении или отказе.', + // Hooks - Exit Code Descriptions + 'stdout/stderr not shown': 'stdout/stderr не отображаются', + 'show stderr to model and continue conversation': + 'показать stderr модели и продолжить разговор', + 'show stderr to user only': 'показать stderr только пользователю', + 'stdout shown in transcript mode (ctrl+o)': + 'stdout отображается в режиме транскрипции (ctrl+o)', + 'show stderr to model immediately': 'показать stderr модели немедленно', + 'show stderr to user only but continue with tool call': + 'показать stderr только пользователю, но продолжить вызов инструмента', + 'block processing, erase original prompt, and show stderr to user only': + 'заблокировать обработку, стереть исходный промпт и показать stderr только пользователю', + 'stdout shown to Qwen': 'stdout показан Qwen', + 'show stderr to user only (blocking errors ignored)': + 'показать stderr только пользователю (блокирующие ошибки игнорируются)', + 'command completes successfully': 'команда успешно завершена', + 'stdout shown to subagent': 'stdout показан субагенту', + 'show stderr to subagent and continue having it run': + 'показать stderr субагенту и продолжить его выполнение', + 'stdout appended as custom compact instructions': + 'stdout добавлен как пользовательские инструкции сжатия', + 'block compaction': 'заблокировать сжатие', + 'show stderr to user only but continue with compaction': + 'показать stderr только пользователю, но продолжить сжатие', + 'use hook decision if provided': + 'использовать решение хука, если предоставлено', + // Hooks - Messages + 'Config not loaded.': 'Конфигурация не загружена.', + 'Hooks are not enabled. Enable hooks in settings to use this feature.': + 'Хуки не включены. Включите хуки в настройках, чтобы использовать эту функцию.', + 'No hooks configured. Add hooks in your settings.json file.': + 'Хуки не настроены. Добавьте хуки в файл settings.json.', + 'Configured Hooks ({{count}} total)': 'Настроенные хуки (всего {{count}})', // ============================================================================ // Commands - Session Export @@ -718,7 +831,6 @@ export default { 'Workspace approval mode exists and takes priority. User-level change will have no effect.': 'Режим подтверждения рабочего пространства существует и имеет приоритет. Изменение на уровне пользователя не будет иметь эффекта.', 'Apply To': 'Применить к', - 'User Settings': 'Настройки пользователя', 'Workspace Settings': 'Настройки рабочего пространства', // ============================================================================ @@ -773,7 +885,6 @@ export default { 'List configured MCP servers and tools': 'Просмотр настроенных MCP-серверов и инструментов', 'Restarts MCP servers.': 'Перезапустить MCP-серверы.', - 'Config not loaded.': 'Конфигурация не загружена.', 'Could not retrieve tool registry.': 'Не удалось получить реестр инструментов.', 'No MCP servers configured with OAuth authentication.': @@ -951,7 +1062,6 @@ export default { 'View tools': 'Просмотреть инструменты', '(disabled)': '(отключен)', 'Error:': 'Ошибка:', - Extension: 'Расширение', tool: 'инструмент', connected: 'подключен', connecting: 'подключение', @@ -979,7 +1089,11 @@ export default { "Allow execution of: '{{command}}'?": "Разрешить выполнение: '{{command}}'?", 'Yes, allow always ...': 'Да, всегда разрешать ...', 'Always allow in this project': 'Всегда разрешать в этом проекте', + 'Always allow {{action}} in this project': + 'Всегда разрешать {{action}} в этом проекте', 'Always allow for this user': 'Всегда разрешать для этого пользователя', + 'Always allow {{action}} for this user': + 'Всегда разрешать {{action}} для этого пользователя', 'Yes, and auto-accept edits': 'Да, и автоматически принимать правки', 'Yes, and manually approve edits': 'Да, и вручную подтверждать правки', 'No, keep planning (esc)': 'Нет, продолжить планирование (esc)', @@ -1597,8 +1711,8 @@ export default { // Auth Dialog - View Titles and Labels // ============================================================================ 'Coding Plan': 'Coding Plan', - "Paste your api key of Bailian Coding Plan and you're all set!": - 'Вставьте ваш API-ключ Bailian Coding Plan и всё готово!', + "Paste your api key of ModelStudio Coding Plan and you're all set!": + 'Вставьте ваш API-ключ ModelStudio Coding Plan и всё готово!', Custom: 'Пользовательский', 'More instructions about configuring `modelProviders` manually.': 'Дополнительные инструкции по ручной настройке `modelProviders`.', diff --git a/packages/cli/src/i18n/locales/zh.js b/packages/cli/src/i18n/locales/zh.js index d22fe9b26..ad755b721 100644 --- a/packages/cli/src/i18n/locales/zh.js +++ b/packages/cli/src/i18n/locales/zh.js @@ -632,6 +632,114 @@ export default { 'List all configured hooks': '列出所有已配置的 Hook', 'Enable a disabled hook': '启用已禁用的 Hook', 'Disable an active hook': '禁用已启用的 Hook', + // Hooks - Dialog + Hooks: 'Hook', + 'Loading hooks...': '正在加载 Hook...', + 'Error loading hooks:': '加载 Hook 出错:', + 'Press Escape to close': '按 Escape 关闭', + 'No hook selected': '未选择 Hook', + // Hooks - List Step + 'No hook events found.': '未找到 Hook 事件。', + '{{count}} hook configured': '{{count}} 个 Hook 已配置', + '{{count}} hooks configured': '{{count}} 个 Hook 已配置', + 'This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.': + '此菜单为只读。要添加或修改 Hook,请直接编辑 settings.json 或询问 Qwen Code。', + 'Enter to select · Esc to cancel': 'Enter 选择 · Esc 取消', + // Hooks - Detail Step + 'Exit codes:': '退出码:', + 'Configured hooks:': '已配置的 Hook:', + 'No hooks configured for this event.': '此事件未配置 Hook。', + 'To add hooks, edit settings.json directly or ask Qwen.': + '要添加 Hook,请直接编辑 settings.json 或询问 Qwen。', + 'Enter to select · Esc to go back': 'Enter 选择 · Esc 返回', + // Hooks - Config Detail Step + 'Hook details': 'Hook 详情', + 'Event:': '事件:', + 'Extension:': '扩展:', + 'Desc:': '描述:', + 'No hook config selected': '未选择 Hook 配置', + 'To modify or remove this hook, edit settings.json directly or ask Qwen to help.': + '要修改或删除此 Hook,请直接编辑 settings.json 或询问 Qwen。', + // Hooks - Source + Project: '项目', + User: '用户', + System: '系统', + Extension: '扩展', + 'Local Settings': '本地设置', + 'User Settings': '用户设置', + 'System Settings': '系统设置', + Extensions: '扩展', + // Hooks - Status + '✓ Enabled': '✓ 已启用', + '✗ Disabled': '✗ 已禁用', + // Hooks - Event Descriptions (short) + 'Before tool execution': '工具执行前', + 'After tool execution': '工具执行后', + 'After tool execution fails': '工具执行失败后', + 'When notifications are sent': '发送通知时', + 'When the user submits a prompt': '用户提交提示时', + 'When a new session is started': '新会话开始时', + 'Right before Qwen Code concludes its response': 'Qwen Code 结束响应之前', + 'When a subagent (Agent tool call) is started': + '子智能体(Agent 工具调用)启动时', + 'Right before a subagent concludes its response': '子智能体结束响应之前', + 'Before conversation compaction': '对话压缩前', + 'When a session is ending': '会话结束时', + 'When a permission dialog is displayed': '显示权限对话框时', + // Hooks - Event Descriptions (detailed) + 'Input to command is JSON of tool call arguments.': + '命令输入为工具调用参数的 JSON。', + 'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).': + '命令输入为包含 "inputs"(工具调用参数)和 "response"(工具调用响应)字段的 JSON。', + 'Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.': + '命令输入为包含 tool_name、tool_input、tool_use_id、error、error_type、is_interrupt 和 is_timeout 的 JSON。', + 'Input to command is JSON with notification message and type.': + '命令输入为包含通知消息和类型的 JSON。', + 'Input to command is JSON with original user prompt text.': + '命令输入为包含原始用户提示文本的 JSON。', + 'Input to command is JSON with session start source.': + '命令输入为包含会话启动来源的 JSON。', + 'Input to command is JSON with session end reason.': + '命令输入为包含会话结束原因的 JSON。', + 'Input to command is JSON with agent_id and agent_type.': + '命令输入为包含 agent_id 和 agent_type 的 JSON。', + 'Input to command is JSON with agent_id, agent_type, and agent_transcript_path.': + '命令输入为包含 agent_id、agent_type 和 agent_transcript_path 的 JSON。', + 'Input to command is JSON with compaction details.': + '命令输入为包含压缩详情的 JSON。', + 'Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.': + '命令输入为包含 tool_name、tool_input 和 tool_use_id 的 JSON。输出包含 hookSpecificOutput 的 JSON,其中包含允许或拒绝的决定。', + // Hooks - Exit Code Descriptions + 'stdout/stderr not shown': 'stdout/stderr 不显示', + 'show stderr to model and continue conversation': + '向模型显示 stderr 并继续对话', + 'show stderr to user only': '仅向用户显示 stderr', + 'stdout shown in transcript mode (ctrl+o)': 'stdout 以转录模式显示 (ctrl+o)', + 'show stderr to model immediately': '立即向模型显示 stderr', + 'show stderr to user only but continue with tool call': + '仅向用户显示 stderr 但继续工具调用', + 'block processing, erase original prompt, and show stderr to user only': + '阻止处理,擦除原始提示,仅向用户显示 stderr', + 'stdout shown to Qwen': '向 Qwen 显示 stdout', + 'show stderr to user only (blocking errors ignored)': + '仅向用户显示 stderr(忽略阻塞错误)', + 'command completes successfully': '命令成功完成', + 'stdout shown to subagent': '向子智能体显示 stdout', + 'show stderr to subagent and continue having it run': + '向子智能体显示 stderr 并继续运行', + 'stdout appended as custom compact instructions': + 'stdout 作为自定义压缩指令追加', + 'block compaction': '阻止压缩', + 'show stderr to user only but continue with compaction': + '仅向用户显示 stderr 但继续压缩', + 'use hook decision if provided': '如果提供则使用 Hook 决定', + // Hooks - Messages + 'Config not loaded.': '配置未加载。', + 'Hooks are not enabled. Enable hooks in settings to use this feature.': + 'Hook 未启用。请在设置中启用 Hook 以使用此功能。', + 'No hooks configured. Add hooks in your settings.json file.': + '未配置 Hook。请在 settings.json 文件中添加 Hook。', + 'Configured Hooks ({{count}} total)': '已配置的 Hook(共 {{count}} 个)', // ============================================================================ // Commands - Session Export @@ -732,7 +840,6 @@ export default { 'Workspace approval mode exists and takes priority. User-level change will have no effect.': '工作区审批模式已存在并具有优先级。用户级别的更改将无效。', 'Apply To': '应用于', - 'User Settings': '用户设置', 'Workspace Settings': '工作区设置', // ============================================================================ @@ -782,7 +889,6 @@ export default { 'List configured MCP servers and tools': '列出已配置的 MCP 服务器和工具', 'Restarts MCP servers.': '重启 MCP 服务器', 'Open MCP management dialog': '打开 MCP 管理对话框', - 'Config not loaded.': '配置未加载', 'Could not retrieve tool registry.': '无法检索工具注册表', 'No MCP servers configured with OAuth authentication.': '未配置支持 OAuth 认证的 MCP 服务器', @@ -841,7 +947,6 @@ export default { 'Server:': '服务器:', '(disabled)': '(已禁用)', 'Error:': '错误:', - Extension: '扩展', tool: '工具', tools: '个工具', connected: '已连接', @@ -1044,7 +1149,9 @@ export default { "Allow execution of: '{{command}}'?": "允许执行:'{{command}}'?", 'Yes, allow always ...': '是,总是允许 ...', 'Always allow in this project': '在本项目中总是允许', + 'Always allow {{action}} in this project': '在本项目中总是允许{{action}}', 'Always allow for this user': '对该用户总是允许', + 'Always allow {{action}} for this user': '对该用户总是允许{{action}}', 'Yes, and auto-accept edits': '是,并自动接受编辑', 'Yes, and manually approve edits': '是,并手动批准编辑', 'No, keep planning (esc)': '否,继续规划 (esc)', @@ -1543,7 +1650,7 @@ export default { // ============================================================================ 'API-KEY': 'API-KEY', 'Coding Plan': 'Coding Plan', - "Paste your api key of Bailian Coding Plan and you're all set!": + "Paste your api key of ModelStudio Coding Plan and you're all set!": '粘贴您的百炼 Coding Plan API Key,即可完成设置!', Custom: '自定义', 'More instructions about configuring `modelProviders` manually.': diff --git a/packages/cli/src/nonInteractiveCliCommands.test.ts b/packages/cli/src/nonInteractiveCliCommands.test.ts index 76b29f3e0..c1c47c678 100644 --- a/packages/cli/src/nonInteractiveCliCommands.test.ts +++ b/packages/cli/src/nonInteractiveCliCommands.test.ts @@ -149,6 +149,33 @@ describe('handleSlashCommand', () => { } }); + it('should execute /btw when using the default allowed list', async () => { + const mockBtwCommand = { + name: 'btw', + description: 'Ask a side question', + kind: CommandKind.BUILT_IN, + action: vi.fn().mockResolvedValue({ + type: 'message', + messageType: 'info', + content: 'btw> question\nanswer', + }), + }; + mockGetCommands.mockReturnValue([mockBtwCommand]); + + const result = await handleSlashCommand( + '/btw question', + abortController, + mockConfig, + mockSettings, + ); + + expect(mockBtwCommand.action).toHaveBeenCalled(); + expect(result.type).toBe('message'); + if (result.type === 'message') { + expect(result.content).toBe('btw> question\nanswer'); + } + }); + it('should execute file commands regardless of allowed list', async () => { const mockFileCommand = { name: 'custom', diff --git a/packages/cli/src/nonInteractiveCliCommands.ts b/packages/cli/src/nonInteractiveCliCommands.ts index b089fa6c2..e6344f5d0 100644 --- a/packages/cli/src/nonInteractiveCliCommands.ts +++ b/packages/cli/src/nonInteractiveCliCommands.ts @@ -42,6 +42,7 @@ export const ALLOWED_BUILTIN_COMMANDS_NON_INTERACTIVE = [ 'init', 'summary', 'compress', + 'btw', 'bug', ] as const; diff --git a/packages/cli/src/services/BuiltinCommandLoader.ts b/packages/cli/src/services/BuiltinCommandLoader.ts index 73c233209..f379a39de 100644 --- a/packages/cli/src/services/BuiltinCommandLoader.ts +++ b/packages/cli/src/services/BuiltinCommandLoader.ts @@ -12,6 +12,7 @@ import { agentsCommand } from '../ui/commands/agentsCommand.js'; import { arenaCommand } from '../ui/commands/arenaCommand.js'; import { approvalModeCommand } from '../ui/commands/approvalModeCommand.js'; import { authCommand } from '../ui/commands/authCommand.js'; +import { btwCommand } from '../ui/commands/btwCommand.js'; import { bugCommand } from '../ui/commands/bugCommand.js'; import { clearCommand } from '../ui/commands/clearCommand.js'; import { compressCommand } from '../ui/commands/compressCommand.js'; @@ -67,6 +68,7 @@ export class BuiltinCommandLoader implements ICommandLoader { arenaCommand, approvalModeCommand, authCommand, + btwCommand, bugCommand, clearCommand, compressCommand, diff --git a/packages/cli/src/services/prompt-processors/shellProcessor.test.ts b/packages/cli/src/services/prompt-processors/shellProcessor.test.ts index fa2afe4fd..c47758574 100644 --- a/packages/cli/src/services/prompt-processors/shellProcessor.test.ts +++ b/packages/cli/src/services/prompt-processors/shellProcessor.test.ts @@ -19,6 +19,19 @@ import type { PromptPipelineContent } from './types.js'; // mirroring the logic in the actual `escapeShellArg` implementation. function getExpectedEscapedArgForPlatform(arg: string): string { if (os.platform() === 'win32') { + // Detect Git Bash / MSYS2 / MinTTY environments (same logic as getShellConfiguration) + const msystem = process.env['MSYSTEM']; + const term = process.env['TERM'] || ''; + const isGitBash = + msystem?.startsWith('MINGW') || + msystem?.startsWith('MSYS') || + term.includes('msys') || + term.includes('cygwin'); + + if (isGitBash) { + return quote([arg]); + } + const comSpec = (process.env['ComSpec'] || 'cmd.exe').toLowerCase(); const isPowerShell = comSpec.endsWith('powershell.exe') || comSpec.endsWith('pwsh.exe'); diff --git a/packages/cli/src/services/prompt-processors/shellProcessor.ts b/packages/cli/src/services/prompt-processors/shellProcessor.ts index f499c2713..679e1d0c6 100644 --- a/packages/cli/src/services/prompt-processors/shellProcessor.ts +++ b/packages/cli/src/services/prompt-processors/shellProcessor.ts @@ -133,12 +133,12 @@ export class ShellProcessor implements IPromptProcessor { // Security check on the final, escaped command string. const { allAllowed, disallowedCommands, blockReason, isHardDenial } = - checkCommandPermissions(command, config, sessionShellAllowlist); + await checkCommandPermissions(command, config, sessionShellAllowlist); // Determine if this command is explicitly auto-approved via PermissionManager const pm = config.getPermissionManager?.(); const isAllowedBySettings = pm - ? pm.isCommandAllowed(command) === 'allow' + ? (await pm.isCommandAllowed(command)) === 'allow' : false; if (!allAllowed) { diff --git a/packages/cli/src/test-utils/mockCommandContext.ts b/packages/cli/src/test-utils/mockCommandContext.ts index fd825b9df..d6a6c3e6d 100644 --- a/packages/cli/src/test-utils/mockCommandContext.ts +++ b/packages/cli/src/test-utils/mockCommandContext.ts @@ -55,6 +55,10 @@ export const createMockCommandContext = ( setDebugMessage: vi.fn(), pendingItem: null, setPendingItem: vi.fn(), + btwItem: null, + setBtwItem: vi.fn(), + cancelBtw: vi.fn(), + btwAbortControllerRef: { current: null }, loadHistory: vi.fn(), toggleVimEnabled: vi.fn(), extensionsUpdateState: new Map(), diff --git a/packages/cli/src/ui/AppContainer.test.tsx b/packages/cli/src/ui/AppContainer.test.tsx index 91b8ae644..07397989a 100644 --- a/packages/cli/src/ui/AppContainer.test.tsx +++ b/packages/cli/src/ui/AppContainer.test.tsx @@ -190,6 +190,8 @@ describe('AppContainer State Management', () => { isAuthDialogOpen: false, isAuthenticating: false, handleAuthSelect: vi.fn(), + handleCodingPlanSubmit: vi.fn(), + handleAlibabaStandardSubmit: vi.fn(), openAuthDialog: vi.fn(), cancelAuthentication: vi.fn(), }); @@ -434,6 +436,41 @@ describe('AppContainer State Management', () => { ); }).not.toThrow(); }); + + it('submits /btw immediately instead of queueing while responding', () => { + const mockSubmitQuery = vi.fn(); + const mockQueueMessage = vi.fn(); + + mockedUseGeminiStream.mockReturnValue({ + streamingState: 'responding', + submitQuery: mockSubmitQuery, + initError: null, + pendingHistoryItems: [], + thought: null, + cancelOngoingRequest: vi.fn(), + retryLastPrompt: vi.fn(), + }); + mockedUseMessageQueue.mockReturnValue({ + messageQueue: [], + addMessage: mockQueueMessage, + clearQueue: vi.fn(), + getQueuedMessagesText: vi.fn().mockReturnValue(''), + }); + + render( + , + ); + + capturedUIActions.handleFinalSubmit('/btw quick side question'); + + expect(mockSubmitQuery).toHaveBeenCalledWith('/btw quick side question'); + expect(mockQueueMessage).not.toHaveBeenCalled(); + }); }); describe('Settings Integration', () => { diff --git a/packages/cli/src/ui/AppContainer.tsx b/packages/cli/src/ui/AppContainer.tsx index 2574f5bf0..37dc32518 100644 --- a/packages/cli/src/ui/AppContainer.tsx +++ b/packages/cli/src/ui/AppContainer.tsx @@ -41,6 +41,7 @@ import { Storage, SessionEndReason, SessionStartSource, + type PermissionMode, } from '@qwen-code/qwen-code-core'; import { buildResumedHistoryItems } from './utils/resumeHistoryUtils.js'; import { validateAuthMethod } from '../config/auth.js'; @@ -71,6 +72,7 @@ import { useTextBuffer } from './components/shared/text-buffer.js'; import { useLogger } from './hooks/useLogger.js'; import { useGeminiStream } from './hooks/useGeminiStream.js'; import { useVim } from './hooks/vim.js'; +import { isBtwCommand } from './utils/commandUtils.js'; import { type LoadedSettings, SettingScope } from '../config/settings.js'; import { type InitializationResult } from '../core/initializer.js'; import { useFocus } from './hooks/useFocus.js'; @@ -108,6 +110,7 @@ import { useSubagentCreateDialog } from './hooks/useSubagentCreateDialog.js'; import { useAgentsManagerDialog } from './hooks/useAgentsManagerDialog.js'; import { useExtensionsManagerDialog } from './hooks/useExtensionsManagerDialog.js'; import { useMcpDialog } from './hooks/useMcpDialog.js'; +import { useHooksDialog } from './hooks/useHooksDialog.js'; import { useAttentionNotifications } from './hooks/useAttentionNotifications.js'; import { requestConsentInteractive, @@ -307,7 +310,11 @@ export const AppContainer = (props: AppContainerProps) => { if (hookSystem) { hookSystem - .fireSessionStartEvent(sessionStartSource, config.getModel() ?? '') + .fireSessionStartEvent( + sessionStartSource, + config.getModel() ?? '', + String(config.getApprovalMode()) as PermissionMode, + ) .then(() => { debugLogger.debug('SessionStart event completed successfully'); }) @@ -450,6 +457,7 @@ export const AppContainer = (props: AppContainerProps) => { qwenAuthState, handleAuthSelect, handleCodingPlanSubmit, + handleAlibabaStandardSubmit, openAuthDialog, cancelAuthentication, } = useAuthCommand(settings, config, historyManager.addItem, refreshStatic); @@ -546,6 +554,8 @@ export const AppContainer = (props: AppContainerProps) => { closeExtensionsManagerDialog, } = useExtensionsManagerDialog(); const { isMcpDialogOpen, openMcpDialog, closeMcpDialog } = useMcpDialog(); + const { isHooksDialogOpen, openHooksDialog, closeHooksDialog } = + useHooksDialog(); const slashCommandActions = useMemo( () => ({ @@ -572,6 +582,7 @@ export const AppContainer = (props: AppContainerProps) => { openAgentsManagerDialog, openExtensionsManagerDialog, openMcpDialog, + openHooksDialog, openResumeDialog, }), [ @@ -591,6 +602,7 @@ export const AppContainer = (props: AppContainerProps) => { openAgentsManagerDialog, openExtensionsManagerDialog, openMcpDialog, + openHooksDialog, openResumeDialog, ], ); @@ -599,6 +611,9 @@ export const AppContainer = (props: AppContainerProps) => { handleSlashCommand, slashCommands, pendingHistoryItems: pendingSlashCommandHistoryItems, + btwItem, + setBtwItem, + cancelBtw, commandContext, shellConfirmationRequest, confirmationRequest, @@ -747,9 +762,16 @@ export const AppContainer = (props: AppContainerProps) => { return; } } + if ( + streamingState === StreamingState.Responding && + isBtwCommand(submittedValue) + ) { + void submitQuery(submittedValue); + return; + } addMessage(submittedValue); }, - [addMessage, agentViewState], + [addMessage, agentViewState, streamingState, submitQuery], ); const handleArenaModelsSelected = useCallback( @@ -947,6 +969,7 @@ export const AppContainer = (props: AppContainerProps) => { const ctrlDTimerRef = useRef(null); const [escapePressedOnce, setEscapePressedOnce] = useState(false); const escapeTimerRef = useRef(null); + const dialogsVisibleRef = useRef(false); const [constrainHeight, setConstrainHeight] = useState(true); const [ideContextState, setIdeContextState] = useState< IdeContext | undefined @@ -1233,7 +1256,13 @@ export const AppContainer = (props: AppContainerProps) => { handleExit(ctrlDPressedOnce, setCtrlDPressedOnce, ctrlDTimerRef); return; } else if (keyMatchers[Command.ESCAPE](key)) { - // Escape key handling + // Dismiss or cancel btw side-question on Escape, + // but only when btw is actually visible (not hidden behind a dialog). + if (btwItem && !dialogsVisibleRef.current) { + cancelBtw(); + return; + } + // Skip if shell is focused (to allow shell's own escape handling) if (embeddedShellFocused) { return; @@ -1275,6 +1304,20 @@ export const AppContainer = (props: AppContainerProps) => { return; } + // Dismiss completed btw side-question on Space or Enter, + // but only when btw is visible and the input buffer is empty. + if ( + btwItem && + !btwItem.btw.isPending && + !dialogsVisibleRef.current && + buffer.text.length === 0 + ) { + if (key.name === 'return' || key.sequence === ' ') { + setBtwItem(null); + return; + } + } + let enteringConstrainHeightMode = false; if (!constrainHeight) { enteringConstrainHeightMode = true; @@ -1329,6 +1372,9 @@ export const AppContainer = (props: AppContainerProps) => { handleSlashCommand, activePtyId, embeddedShellFocused, + btwItem, + setBtwItem, + cancelBtw, settings.merged.general?.debugKeystrokeLogging, isAuthenticating, ], @@ -1399,9 +1445,11 @@ export const AppContainer = (props: AppContainerProps) => { isSubagentCreateDialogOpen || isAgentsManagerDialogOpen || isMcpDialogOpen || + isHooksDialogOpen || isApprovalModeDialogOpen || isResumeDialogOpen || isExtensionsManagerDialogOpen; + dialogsVisibleRef.current = dialogsVisible; const { isFeedbackDialogOpen, @@ -1492,6 +1540,9 @@ export const AppContainer = (props: AppContainerProps) => { staticExtraHeight, dialogsVisible, pendingHistoryItems, + btwItem, + setBtwItem, + cancelBtw, nightly, branchName, sessionStats, @@ -1517,6 +1568,8 @@ export const AppContainer = (props: AppContainerProps) => { isExtensionsManagerDialogOpen, // MCP dialog isMcpDialogOpen, + // Hooks dialog + isHooksDialogOpen, // Feedback dialog isFeedbackDialogOpen, // Per-task token tracking @@ -1588,6 +1641,9 @@ export const AppContainer = (props: AppContainerProps) => { staticExtraHeight, dialogsVisible, pendingHistoryItems, + btwItem, + setBtwItem, + cancelBtw, nightly, branchName, sessionStats, @@ -1615,6 +1671,8 @@ export const AppContainer = (props: AppContainerProps) => { isExtensionsManagerDialogOpen, // MCP dialog isMcpDialogOpen, + // Hooks dialog + isHooksDialogOpen, // Feedback dialog isFeedbackDialogOpen, // Per-task token tracking @@ -1634,6 +1692,7 @@ export const AppContainer = (props: AppContainerProps) => { onAuthError, cancelAuthentication, handleCodingPlanSubmit, + handleAlibabaStandardSubmit, handleEditorSelect, exitEditorDialog, closeSettingsDialog, @@ -1666,6 +1725,10 @@ export const AppContainer = (props: AppContainerProps) => { closeExtensionsManagerDialog, // MCP dialog closeMcpDialog, + // Hooks dialog + openHooksDialog, + // Hooks dialog + closeHooksDialog, // Resume session dialog openResumeDialog, closeResumeDialog, @@ -1687,6 +1750,7 @@ export const AppContainer = (props: AppContainerProps) => { onAuthError, cancelAuthentication, handleCodingPlanSubmit, + handleAlibabaStandardSubmit, handleEditorSelect, exitEditorDialog, closeSettingsDialog, @@ -1717,6 +1781,10 @@ export const AppContainer = (props: AppContainerProps) => { closeExtensionsManagerDialog, // MCP dialog closeMcpDialog, + // Hooks dialog + openHooksDialog, + // Hooks dialog + closeHooksDialog, // Resume session dialog openResumeDialog, closeResumeDialog, diff --git a/packages/cli/src/ui/auth/AuthDialog.test.tsx b/packages/cli/src/ui/auth/AuthDialog.test.tsx index 90b15c968..561d5b0b2 100644 --- a/packages/cli/src/ui/auth/AuthDialog.test.tsx +++ b/packages/cli/src/ui/auth/AuthDialog.test.tsx @@ -32,6 +32,9 @@ const createMockUIActions = (overrides: Partial = {}): UIActions => { // AuthDialog only uses handleAuthSelect const baseActions = { handleAuthSelect: vi.fn(), + handleCodingPlanSubmit: vi.fn(), + handleAlibabaStandardSubmit: vi.fn(), + onAuthError: vi.fn(), handleRetryLastPrompt: vi.fn(), } as Partial; diff --git a/packages/cli/src/ui/auth/AuthDialog.tsx b/packages/cli/src/ui/auth/AuthDialog.tsx index 4469a0759..c82524011 100644 --- a/packages/cli/src/ui/auth/AuthDialog.tsx +++ b/packages/cli/src/ui/auth/AuthDialog.tsx @@ -13,6 +13,7 @@ import { theme } from '../semantic-colors.js'; import { useKeypress } from '../hooks/useKeypress.js'; import { DescriptiveRadioButtonSelect } from '../components/shared/DescriptiveRadioButtonSelect.js'; import { ApiKeyInput } from '../components/ApiKeyInput.js'; +import { TextInput } from '../components/shared/TextInput.js'; import { useUIState } from '../contexts/UIStateContext.js'; import { useUIActions } from '../contexts/UIActionsContext.js'; import { useConfig } from '../contexts/ConfigContext.js'; @@ -21,6 +22,10 @@ import { CodingPlanRegion, isCodingPlanConfig, } from '../../constants/codingPlan.js'; +import { + ALIBABA_STANDARD_API_KEY_ENDPOINTS, + type AlibabaStandardRegion, +} from '../../constants/alibabaStandardApiKey.js'; const MODEL_PROVIDERS_DOCUMENTATION_URL = 'https://qwenlm.github.io/qwen-code-docs/en/users/configuration/model-providers/'; @@ -39,15 +44,39 @@ function parseDefaultAuthType( // Main menu option type type MainOption = typeof AuthType.QWEN_OAUTH | 'CODING_PLAN' | 'API_KEY'; +type ApiKeyOption = 'ALIBABA_STANDARD_API_KEY' | 'CUSTOM_API_KEY'; // View level for navigation -type ViewLevel = 'main' | 'region-select' | 'api-key-input' | 'custom-info'; +type ViewLevel = + | 'main' + | 'region-select' + | 'api-key-input' + | 'api-key-type-select' + | 'alibaba-standard-region-select' + | 'alibaba-standard-api-key-input' + | 'alibaba-standard-model-id-input' + | 'custom-info'; + +const ALIBABA_STANDARD_MODEL_IDS_PLACEHOLDER = 'qwen3.5-plus,glm-5,kimi-k2.5'; +const ALIBABA_STANDARD_API_DOCUMENTATION_URLS: Record< + AlibabaStandardRegion, + string +> = { + 'cn-beijing': 'https://bailian.console.aliyun.com/cn-beijing?tab=api#/api', + 'sg-singapore': + 'https://modelstudio.console.alibabacloud.com/ap-southeast-1?tab=api#/api/?type=model&url=2712195', + 'us-virginia': + 'https://modelstudio.console.alibabacloud.com/us-east-1?tab=api#/api/?type=model&url=2712195', + 'cn-hongkong': + 'https://modelstudio.console.alibabacloud.com/cn-hongkong?tab=api#/api/?type=model&url=2712195', +}; export function AuthDialog(): React.JSX.Element { const { pendingAuthType, authError } = useUIState(); const { handleAuthSelect: onAuthSelect, handleCodingPlanSubmit, + handleAlibabaStandardSubmit, onAuthError, } = useUIActions(); const config = useConfig(); @@ -58,6 +87,18 @@ export function AuthDialog(): React.JSX.Element { const [region, setRegion] = useState( CodingPlanRegion.CHINA, ); + const [alibabaStandardRegionIndex, setAlibabaStandardRegionIndex] = + useState(0); + const [apiKeyTypeIndex, setApiKeyTypeIndex] = useState(0); + const [alibabaStandardRegion, setAlibabaStandardRegion] = + useState('cn-beijing'); + const [alibabaStandardApiKey, setAlibabaStandardApiKey] = useState(''); + const [alibabaStandardApiKeyError, setAlibabaStandardApiKeyError] = useState< + string | null + >(null); + const [alibabaStandardModelId, setAlibabaStandardModelId] = useState(''); + const [alibabaStandardModelIdError, setAlibabaStandardModelIdError] = + useState(null); // Main authentication entries (flat three-option layout) const mainItems = [ @@ -124,21 +165,87 @@ export function AuthDialog(): React.JSX.Element { }, ]; + const alibabaStandardRegionItems = [ + { + key: 'cn-beijing', + title: t('China (Beijing)'), + label: t('China (Beijing)'), + description: ( + + Endpoint: {ALIBABA_STANDARD_API_KEY_ENDPOINTS['cn-beijing']} + + ), + value: 'cn-beijing' as AlibabaStandardRegion, + }, + { + key: 'sg-singapore', + title: t('Singapore'), + label: t('Singapore'), + description: ( + + Endpoint: {ALIBABA_STANDARD_API_KEY_ENDPOINTS['sg-singapore']} + + ), + value: 'sg-singapore' as AlibabaStandardRegion, + }, + { + key: 'us-virginia', + title: t('US (Virginia)'), + label: t('US (Virginia)'), + description: ( + + Endpoint: {ALIBABA_STANDARD_API_KEY_ENDPOINTS['us-virginia']} + + ), + value: 'us-virginia' as AlibabaStandardRegion, + }, + { + key: 'cn-hongkong', + title: t('China (Hong Kong)'), + label: t('China (Hong Kong)'), + description: ( + + Endpoint: {ALIBABA_STANDARD_API_KEY_ENDPOINTS['cn-hongkong']} + + ), + value: 'cn-hongkong' as AlibabaStandardRegion, + }, + ]; + + const apiKeyTypeItems = [ + { + key: 'ALIBABA_STANDARD_API_KEY', + title: t('Alibaba Cloud ModelStudio Standard API Key'), + label: t('Alibaba Cloud ModelStudio Standard API Key'), + description: t('Quick setup for Model Studio (China/International)'), + value: 'ALIBABA_STANDARD_API_KEY' as ApiKeyOption, + }, + { + key: 'CUSTOM_API_KEY', + title: t('Custom API Key'), + label: t('Custom API Key'), + description: t( + 'For other OpenAI / Anthropic / Gemini-compatible providers', + ), + value: 'CUSTOM_API_KEY' as ApiKeyOption, + }, + ]; + // Map an AuthType to the corresponding main menu option. - // QWEN_OAUTH maps directly; any other auth type maps to CODING_PLAN only - // if the current config actually uses a Coding Plan baseUrl+envKey, - // otherwise it maps to API_KEY. + // QWEN_OAUTH maps directly; USE_OPENAI maps to: + // - CODING_PLAN when current config matches coding plan + // - API_KEY for other OpenAI / Anthropic / Gemini-compatible configs const contentGenConfig = config.getContentGeneratorConfig(); const isCurrentlyCodingPlan = isCodingPlanConfig( contentGenConfig?.baseUrl, contentGenConfig?.apiKeyEnvKey, ) !== false; - const authTypeToMainOption = (authType: AuthType): MainOption => { if (authType === AuthType.QWEN_OAUTH) return AuthType.QWEN_OAUTH; - if (authType === AuthType.USE_OPENAI && isCurrentlyCodingPlan) + if (authType === AuthType.USE_OPENAI && isCurrentlyCodingPlan) { return 'CODING_PLAN'; + } return 'API_KEY'; }; @@ -180,8 +287,7 @@ export function AuthDialog(): React.JSX.Element { } if (value === 'API_KEY') { - // Navigate directly to custom API key info - setViewLevel('custom-info'); + setViewLevel('api-key-type-select'); return; } @@ -189,6 +295,20 @@ export function AuthDialog(): React.JSX.Element { await onAuthSelect(value); }; + const handleApiKeyTypeSelect = async (value: ApiKeyOption) => { + setErrorMessage(null); + onAuthError(null); + + if (value === 'ALIBABA_STANDARD_API_KEY') { + setAlibabaStandardModelIdError(null); + setAlibabaStandardApiKeyError(null); + setViewLevel('alibaba-standard-region-select'); + return; + } + + setViewLevel('custom-info'); + }; + const handleRegionSelect = async (selectedRegion: CodingPlanRegion) => { setErrorMessage(null); onAuthError(null); @@ -196,6 +316,17 @@ export function AuthDialog(): React.JSX.Element { setViewLevel('api-key-input'); }; + const handleAlibabaStandardRegionSelect = async ( + selectedRegion: AlibabaStandardRegion, + ) => { + setErrorMessage(null); + onAuthError(null); + setAlibabaStandardApiKeyError(null); + setAlibabaStandardModelIdError(null); + setAlibabaStandardRegion(selectedRegion); + setViewLevel('alibaba-standard-api-key-input'); + }; + const handleApiKeyInputSubmit = async (apiKey: string) => { setErrorMessage(null); @@ -208,14 +339,59 @@ export function AuthDialog(): React.JSX.Element { await handleCodingPlanSubmit(apiKey, region); }; + const handleAlibabaStandardApiKeySubmit = () => { + const trimmedKey = alibabaStandardApiKey.trim(); + if (!trimmedKey) { + setAlibabaStandardApiKeyError(t('API key cannot be empty.')); + return; + } + + setAlibabaStandardApiKeyError(null); + if (!alibabaStandardModelId.trim()) { + setAlibabaStandardModelId(ALIBABA_STANDARD_MODEL_IDS_PLACEHOLDER); + } + setViewLevel('alibaba-standard-model-id-input'); + }; + + const handleAlibabaStandardModelSubmit = () => { + const trimmedApiKey = alibabaStandardApiKey.trim(); + const trimmedModelIds = alibabaStandardModelId.trim(); + if (!trimmedApiKey) { + setAlibabaStandardApiKeyError(t('API key cannot be empty.')); + setViewLevel('alibaba-standard-api-key-input'); + return; + } + if (!trimmedModelIds) { + setAlibabaStandardModelIdError(t('Model IDs cannot be empty.')); + return; + } + + setAlibabaStandardModelIdError(null); + void handleAlibabaStandardSubmit( + trimmedApiKey, + alibabaStandardRegion, + trimmedModelIds, + ); + }; + const handleGoBack = () => { setErrorMessage(null); onAuthError(null); - if (viewLevel === 'region-select' || viewLevel === 'custom-info') { + if (viewLevel === 'region-select') { setViewLevel('main'); } else if (viewLevel === 'api-key-input') { setViewLevel('region-select'); + } else if (viewLevel === 'api-key-type-select') { + setViewLevel('main'); + } else if (viewLevel === 'custom-info') { + setViewLevel('api-key-type-select'); + } else if (viewLevel === 'alibaba-standard-region-select') { + setViewLevel('api-key-type-select'); + } else if (viewLevel === 'alibaba-standard-api-key-input') { + setViewLevel('alibaba-standard-region-select'); + } else if (viewLevel === 'alibaba-standard-model-id-input') { + setViewLevel('alibaba-standard-api-key-input'); } }; @@ -232,6 +408,15 @@ export function AuthDialog(): React.JSX.Element { handleGoBack(); return; } + if ( + viewLevel === 'api-key-type-select' || + viewLevel === 'alibaba-standard-region-select' || + viewLevel === 'alibaba-standard-api-key-input' || + viewLevel === 'alibaba-standard-model-id-input' + ) { + handleGoBack(); + return; + } // For main view, use existing logic if (errorMessage) { @@ -304,6 +489,135 @@ export function AuthDialog(): React.JSX.Element { ); + const renderApiKeyTypeSelectView = () => ( + <> + + { + const index = apiKeyTypeItems.findIndex( + (item) => item.value === value, + ); + setApiKeyTypeIndex(index); + }} + itemGap={1} + /> + + + + {t('Enter to select, ↑↓ to navigate, Esc to go back')} + + + + ); + + const renderAlibabaStandardRegionSelectView = () => ( + <> + + { + const index = alibabaStandardRegionItems.findIndex( + (item) => item.value === value, + ); + setAlibabaStandardRegionIndex(index); + }} + itemGap={1} + /> + + + + {t('Enter to select, ↑↓ to navigate, Esc to go back')} + + + + ); + + const renderAlibabaStandardApiKeyInputView = () => ( + + + + Endpoint: {ALIBABA_STANDARD_API_KEY_ENDPOINTS[alibabaStandardRegion]} + + + + {t('Documentation')}: + + + + + {ALIBABA_STANDARD_API_DOCUMENTATION_URLS[alibabaStandardRegion]} + + + + + { + setAlibabaStandardApiKey(value); + if (alibabaStandardApiKeyError) { + setAlibabaStandardApiKeyError(null); + } + }} + onSubmit={handleAlibabaStandardApiKeySubmit} + placeholder="sk-..." + /> + + {alibabaStandardApiKeyError && ( + + {alibabaStandardApiKeyError} + + )} + + + {t('Enter to submit, Esc to go back')} + + + + ); + + const renderAlibabaStandardModelIdInputView = () => ( + + + + {t( + 'You can enter multiple model IDs, separated by commas. Examples: qwen3.5-plus,glm-5,kimi-k2.5', + )} + + + + { + setAlibabaStandardModelId(value); + if (alibabaStandardModelIdError) { + setAlibabaStandardModelIdError(null); + } + }} + onSubmit={handleAlibabaStandardModelSubmit} + placeholder={ALIBABA_STANDARD_MODEL_IDS_PLACEHOLDER} + /> + + {alibabaStandardModelIdError && ( + + {alibabaStandardModelIdError} + + )} + + + {t('Enter to submit, Esc to go back')} + + + + ); + // Render custom mode info const renderCustomInfoView = () => ( <> @@ -336,8 +650,18 @@ export function AuthDialog(): React.JSX.Element { return t('Select Region for Coding Plan'); case 'api-key-input': return t('Enter Coding Plan API Key'); + case 'api-key-type-select': + return t('Select API Key Type'); case 'custom-info': return t('Custom Configuration'); + case 'alibaba-standard-region-select': + return t( + 'Select Region for Alibaba Cloud ModelStudio Standard API Key', + ); + case 'alibaba-standard-api-key-input': + return t('Enter Alibaba Cloud ModelStudio Standard API Key'); + case 'alibaba-standard-model-id-input': + return t('Enter Model IDs'); default: return t('Select Authentication Method'); } @@ -356,6 +680,13 @@ export function AuthDialog(): React.JSX.Element { {viewLevel === 'main' && renderMainView()} {viewLevel === 'region-select' && renderRegionSelectView()} {viewLevel === 'api-key-input' && renderApiKeyInputView()} + {viewLevel === 'api-key-type-select' && renderApiKeyTypeSelectView()} + {viewLevel === 'alibaba-standard-region-select' && + renderAlibabaStandardRegionSelectView()} + {viewLevel === 'alibaba-standard-api-key-input' && + renderAlibabaStandardApiKeyInputView()} + {viewLevel === 'alibaba-standard-model-id-input' && + renderAlibabaStandardModelIdInputView()} {viewLevel === 'custom-info' && renderCustomInfoView()} {(authError || errorMessage) && ( diff --git a/packages/cli/src/ui/auth/useAuth.ts b/packages/cli/src/ui/auth/useAuth.ts index 283a0d155..86c3857aa 100644 --- a/packages/cli/src/ui/auth/useAuth.ts +++ b/packages/cli/src/ui/auth/useAuth.ts @@ -36,6 +36,11 @@ import { CODING_PLAN_ENV_KEY, } from '../../constants/codingPlan.js'; import { backupSettingsFile } from '../../utils/settingsUtils.js'; +import { + ALIBABA_STANDARD_API_KEY_ENDPOINTS, + DASHSCOPE_STANDARD_API_KEY_ENV_KEY, + type AlibabaStandardRegion, +} from '../../constants/alibabaStandardApiKey.js'; export type { QwenAuthState } from '../hooks/useQwenAuth.js'; @@ -421,6 +426,134 @@ export const useAuthCommand = ( [settings, config, handleAuthFailure, addItem, onAuthChange], ); + /** + * Handle Alibaba Cloud standard API key flow. + * Persists key to env.DASHSCOPE_API_KEY and creates a modelProviders.openai entry. + */ + const handleAlibabaStandardSubmit = useCallback( + async ( + apiKey: string, + region: AlibabaStandardRegion, + modelIdsInput: string, + ) => { + try { + setIsAuthenticating(true); + setAuthError(null); + + const trimmedApiKey = apiKey.trim(); + const modelIds = modelIdsInput + .split(',') + .map((id) => id.trim()) + .filter( + (id, index, array) => id.length > 0 && array.indexOf(id) === index, + ); + if (!trimmedApiKey) { + throw new Error(t('API key cannot be empty.')); + } + if (modelIds.length === 0) { + throw new Error(t('Model IDs cannot be empty.')); + } + + const baseUrl = ALIBABA_STANDARD_API_KEY_ENDPOINTS[region]; + const persistScope = getPersistScopeForModelSelection(settings); + + const settingsFile = settings.forScope(persistScope); + backupSettingsFile(settingsFile.path); + + settings.setValue( + persistScope, + `env.${DASHSCOPE_STANDARD_API_KEY_ENV_KEY}`, + trimmedApiKey, + ); + process.env[DASHSCOPE_STANDARD_API_KEY_ENV_KEY] = trimmedApiKey; + + const newConfigs: ProviderModelConfig[] = modelIds.map((modelId) => ({ + id: modelId, + name: `[ModelStudio Standard] ${modelId}`, + baseUrl, + envKey: DASHSCOPE_STANDARD_API_KEY_ENV_KEY, + })); + + const existingConfigs = + ( + settings.merged.modelProviders as ModelProvidersConfig | undefined + )?.[AuthType.USE_OPENAI] || []; + + const nonAlibabaStandardConfigs = existingConfigs.filter( + (existing) => + !( + existing.envKey === DASHSCOPE_STANDARD_API_KEY_ENV_KEY && + typeof existing.baseUrl === 'string' && + Object.values(ALIBABA_STANDARD_API_KEY_ENDPOINTS).includes( + existing.baseUrl, + ) + ), + ); + + const updatedConfigs = [...newConfigs, ...nonAlibabaStandardConfigs]; + + settings.setValue( + persistScope, + `modelProviders.${AuthType.USE_OPENAI}`, + updatedConfigs, + ); + settings.setValue( + persistScope, + 'security.auth.selectedType', + AuthType.USE_OPENAI, + ); + settings.setValue(persistScope, 'model.name', modelIds[0]); + + const updatedModelProviders: ModelProvidersConfig = { + ...(settings.merged.modelProviders as + | ModelProvidersConfig + | undefined), + [AuthType.USE_OPENAI]: updatedConfigs, + }; + config.reloadModelProvidersConfig(updatedModelProviders); + await config.refreshAuth(AuthType.USE_OPENAI); + + setAuthError(null); + setAuthState(AuthState.Authenticated); + setPendingAuthType(undefined); + setIsAuthDialogOpen(false); + setIsAuthenticating(false); + onAuthChange?.(); + + addItem( + { + type: MessageType.INFO, + text: t( + 'Alibaba Cloud ModelStudio Standard API Key successfully entered. Settings updated with env.DASHSCOPE_API_KEY and {{modelCount}} model(s).', + { modelCount: String(modelIds.length) }, + ), + }, + Date.now(), + ); + + addItem( + { + type: MessageType.INFO, + text: t( + 'You can use /model to see new ModelStudio Standard models and switch between them.', + ), + }, + Date.now(), + ); + + const authEvent = new AuthEvent( + AuthType.USE_OPENAI, + 'manual', + 'success', + ); + logAuth(config, authEvent); + } catch (error) { + handleAuthFailure(error); + } + }, + [settings, config, handleAuthFailure, addItem, onAuthChange], + ); + /** /** * We previously used a useEffect to trigger authentication automatically when @@ -472,6 +605,7 @@ export const useAuthCommand = ( qwenAuthState, handleAuthSelect, handleCodingPlanSubmit, + handleAlibabaStandardSubmit, openAuthDialog, cancelAuthentication, }; diff --git a/packages/cli/src/ui/commands/btwCommand.test.ts b/packages/cli/src/ui/commands/btwCommand.test.ts new file mode 100644 index 000000000..99dfa40d3 --- /dev/null +++ b/packages/cli/src/ui/commands/btwCommand.test.ts @@ -0,0 +1,464 @@ +/** + * @license + * Copyright 2025 Qwen Code + * SPDX-License-Identifier: Apache-2.0 + */ + +import { vi, describe, it, expect, beforeEach } from 'vitest'; +import { btwCommand } from './btwCommand.js'; +import { type CommandContext } from './types.js'; +import { createMockCommandContext } from '../../test-utils/mockCommandContext.js'; +import { CommandKind } from './types.js'; +import { MessageType } from '../types.js'; + +vi.mock('../../i18n/index.js', () => ({ + t: (key: string, params?: Record) => { + if (params) { + return Object.entries(params).reduce( + (str, [k, v]) => str.replace(`{{${k}}}`, v), + key, + ); + } + return key; + }, +})); + +describe('btwCommand', () => { + let mockContext: CommandContext; + let mockGenerateContent: ReturnType; + let mockGetHistory: ReturnType; + const createConfig = (overrides: Record = {}) => ({ + getGeminiClient: () => ({ + getHistory: mockGetHistory, + generateContent: mockGenerateContent, + }), + getModel: () => 'test-model', + getSessionId: () => 'test-session-id', + ...overrides, + }); + + beforeEach(() => { + vi.clearAllMocks(); + + mockGenerateContent = vi.fn(); + mockGetHistory = vi.fn().mockReturnValue([]); + + mockContext = createMockCommandContext({ + services: { + config: createConfig(), + }, + }); + }); + + it('should have correct metadata', () => { + expect(btwCommand.name).toBe('btw'); + expect(btwCommand.kind).toBe(CommandKind.BUILT_IN); + expect(btwCommand.description).toBeTruthy(); + }); + + it('should return error when no question is provided', async () => { + const result = await btwCommand.action!(mockContext, ''); + + expect(result).toEqual({ + type: 'message', + messageType: 'error', + content: 'Please provide a question. Usage: /btw ', + }); + }); + + it('should return error when only whitespace is provided', async () => { + const result = await btwCommand.action!(mockContext, ' '); + + expect(result).toEqual({ + type: 'message', + messageType: 'error', + content: 'Please provide a question. Usage: /btw ', + }); + }); + + it('should return error when config is not loaded', async () => { + const noConfigContext = createMockCommandContext({ + services: { config: null }, + }); + + const result = await btwCommand.action!(noConfigContext, 'test question'); + + expect(result).toEqual({ + type: 'message', + messageType: 'error', + content: 'Config not loaded.', + }); + }); + + it('should return error when model is not configured', async () => { + const noModelContext = createMockCommandContext({ + services: { + config: createConfig({ + getModel: () => '', + }), + }, + }); + + const result = await btwCommand.action!(noModelContext, 'test question'); + + expect(result).toEqual({ + type: 'message', + messageType: 'error', + content: 'No model configured.', + }); + }); + + describe('interactive mode', () => { + const flushPromises = () => + new Promise((resolve) => setTimeout(resolve, 0)); + + it('should set btwItem and update it on success', async () => { + mockGenerateContent.mockResolvedValue({ + candidates: [ + { + content: { + parts: [{ text: 'The answer is 42.' }], + }, + }, + ], + }); + + await btwCommand.action!(mockContext, 'what is the meaning of life?'); + + // Action returns immediately; btwItem is set synchronously + expect(mockContext.ui.setBtwItem).toHaveBeenCalledWith({ + type: MessageType.BTW, + btw: { + question: 'what is the meaning of life?', + answer: '', + isPending: true, + }, + }); + + // pendingItem should NOT be used + expect(mockContext.ui.setPendingItem).not.toHaveBeenCalled(); + + await flushPromises(); + + // On success, setBtwItem is called with the completed answer + expect(mockContext.ui.setBtwItem).toHaveBeenCalledWith({ + type: MessageType.BTW, + btw: { + question: 'what is the meaning of life?', + answer: 'The answer is 42.', + isPending: false, + }, + }); + + // addItem should NOT be called (btw stays in fixed area, not in history) + expect(mockContext.ui.addItem).not.toHaveBeenCalled(); + }); + + it('should pass conversation history to generateContent', async () => { + const history = [ + { role: 'user', parts: [{ text: 'Hello' }] }, + { role: 'model', parts: [{ text: 'Hi!' }] }, + ]; + mockGetHistory.mockReturnValue(history); + mockGenerateContent.mockResolvedValue({ + candidates: [{ content: { parts: [{ text: 'answer' }] } }], + }); + + await btwCommand.action!(mockContext, 'my question'); + await flushPromises(); + + expect(mockGenerateContent).toHaveBeenCalledWith( + [ + ...history, + { + role: 'user', + parts: [ + { + text: expect.stringContaining('my question'), + }, + ], + }, + ], + {}, + expect.any(AbortSignal), + 'test-model', + expect.stringMatching(/^test-session-id########btw-/), + ); + }); + + it('should add error item on failure and clear btwItem', async () => { + mockGenerateContent.mockRejectedValue(new Error('API error')); + + await btwCommand.action!(mockContext, 'test question'); + await flushPromises(); + + // btwItem should be cleared on error + expect(mockContext.ui.setBtwItem).toHaveBeenCalledWith(null); + + // Error goes to history + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.ERROR, + text: 'Failed to answer btw question: API error', + }, + expect.any(Number), + ); + }); + + it('should handle non-Error exceptions', async () => { + mockGenerateContent.mockRejectedValue('string error'); + + await btwCommand.action!(mockContext, 'test question'); + await flushPromises(); + + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.ERROR, + text: 'Failed to answer btw question: string error', + }, + expect.any(Number), + ); + }); + + it('should not block when another pendingItem exists', async () => { + const busyContext = createMockCommandContext({ + services: { + config: createConfig(), + }, + ui: { + pendingItem: { type: 'info' }, + }, + }); + + mockGenerateContent.mockResolvedValue({ + candidates: [{ content: { parts: [{ text: 'answer' }] } }], + }); + + // btw should NOT be blocked by pendingItem anymore + const result = await btwCommand.action!(busyContext, 'test question'); + expect(result).toBeUndefined(); + expect(busyContext.ui.setBtwItem).toHaveBeenCalled(); + }); + + it('should not update btwItem when cancelled via btwAbortControllerRef', async () => { + mockGenerateContent.mockImplementation( + () => + new Promise((resolve) => + setTimeout( + () => + resolve({ + candidates: [ + { content: { parts: [{ text: 'late answer' }] } }, + ], + }), + 50, + ), + ), + ); + + await btwCommand.action!(mockContext, 'test question'); + + // The btw command should have registered its AbortController + expect(mockContext.ui.btwAbortControllerRef.current).toBeInstanceOf( + AbortController, + ); + + // Simulate user pressing ESC: cancel the in-flight btw + mockContext.ui.btwAbortControllerRef.current!.abort(); + + await flushPromises(); + + // setBtwItem should only have the initial pending call (no completion) + expect(mockContext.ui.setBtwItem).toHaveBeenCalledTimes(1); + expect(mockContext.ui.addItem).not.toHaveBeenCalled(); + }); + + it('should clear btwAbortControllerRef after successful completion', async () => { + mockGenerateContent.mockResolvedValue({ + candidates: [{ content: { parts: [{ text: 'answer' }] } }], + }); + + await btwCommand.action!(mockContext, 'test question'); + + // Ref is set during the call + expect(mockContext.ui.btwAbortControllerRef.current).toBeInstanceOf( + AbortController, + ); + + await flushPromises(); + + // After completion, ref should be cleaned up + expect(mockContext.ui.btwAbortControllerRef.current).toBeNull(); + }); + + it('should clear btwAbortControllerRef after error', async () => { + mockGenerateContent.mockRejectedValue(new Error('API error')); + + await btwCommand.action!(mockContext, 'test question'); + + expect(mockContext.ui.btwAbortControllerRef.current).toBeInstanceOf( + AbortController, + ); + + await flushPromises(); + + expect(mockContext.ui.btwAbortControllerRef.current).toBeNull(); + }); + + it('should cancel previous btw when starting a new one', async () => { + mockGenerateContent.mockResolvedValue({ + candidates: [{ content: { parts: [{ text: 'answer' }] } }], + }); + + await btwCommand.action!(mockContext, 'first question'); + + // cancelBtw should have been called to clean up any previous btw + expect(mockContext.ui.cancelBtw).toHaveBeenCalledTimes(1); + + // Second btw call + await btwCommand.action!(mockContext, 'second question'); + + // cancelBtw called again for the second invocation + expect(mockContext.ui.cancelBtw).toHaveBeenCalledTimes(2); + }); + + it('should return fallback text when response has no parts', async () => { + mockGenerateContent.mockResolvedValue({ + candidates: [{ content: { parts: [] } }], + }); + + await btwCommand.action!(mockContext, 'test question'); + await flushPromises(); + + expect(mockContext.ui.setBtwItem).toHaveBeenCalledWith({ + type: MessageType.BTW, + btw: { + question: 'test question', + answer: 'No response received.', + isPending: false, + }, + }); + }); + + it('should return void immediately without blocking', async () => { + mockGenerateContent.mockResolvedValue({ + candidates: [{ content: { parts: [{ text: 'answer' }] } }], + }); + + const result = await btwCommand.action!(mockContext, 'test question'); + + expect(result).toBeUndefined(); + + // Only the pending setBtwItem called so far + expect(mockContext.ui.setBtwItem).toHaveBeenCalledTimes(1); + + await flushPromises(); + + // Now the completed setBtwItem has been called + expect(mockContext.ui.setBtwItem).toHaveBeenCalledTimes(2); + }); + }); + + describe('non-interactive mode', () => { + let nonInteractiveContext: CommandContext; + + beforeEach(() => { + nonInteractiveContext = createMockCommandContext({ + executionMode: 'non_interactive', + services: { + config: createConfig(), + }, + }); + }); + + it('should return info message on success', async () => { + mockGenerateContent.mockResolvedValue({ + candidates: [{ content: { parts: [{ text: 'the answer' }] } }], + }); + + const result = await btwCommand.action!( + nonInteractiveContext, + 'my question', + ); + + expect(result).toEqual({ + type: 'message', + messageType: 'info', + content: 'btw> my question\nthe answer', + }); + }); + + it('should return error message on failure', async () => { + mockGenerateContent.mockRejectedValue(new Error('network error')); + + const result = await btwCommand.action!( + nonInteractiveContext, + 'my question', + ); + + expect(result).toEqual({ + type: 'message', + messageType: 'error', + content: 'Failed to answer btw question: network error', + }); + }); + }); + + describe('acp mode', () => { + let acpContext: CommandContext; + + beforeEach(() => { + acpContext = createMockCommandContext({ + executionMode: 'acp', + services: { + config: createConfig(), + }, + }); + }); + + it('should return stream_messages generator on success', async () => { + mockGenerateContent.mockResolvedValue({ + candidates: [{ content: { parts: [{ text: 'streamed answer' }] } }], + }); + + const result = (await btwCommand.action!(acpContext, 'my question')) as { + type: string; + messages: AsyncGenerator; + }; + + expect(result.type).toBe('stream_messages'); + + const messages = []; + for await (const msg of result.messages) { + messages.push(msg); + } + + expect(messages).toEqual([ + { messageType: 'info', content: 'Thinking...' }, + { messageType: 'info', content: 'btw> my question\nstreamed answer' }, + ]); + }); + + it('should yield error message on failure', async () => { + mockGenerateContent.mockRejectedValue(new Error('api failure')); + + const result = (await btwCommand.action!(acpContext, 'my question')) as { + type: string; + messages: AsyncGenerator; + }; + + const messages = []; + for await (const msg of result.messages) { + messages.push(msg); + } + + expect(messages).toEqual([ + { messageType: 'info', content: 'Thinking...' }, + { + messageType: 'error', + content: 'Failed to answer btw question: api failure', + }, + ]); + }); + }); +}); diff --git a/packages/cli/src/ui/commands/btwCommand.ts b/packages/cli/src/ui/commands/btwCommand.ts new file mode 100644 index 000000000..60a3ab8dd --- /dev/null +++ b/packages/cli/src/ui/commands/btwCommand.ts @@ -0,0 +1,226 @@ +/** + * @license + * Copyright 2025 Qwen Code + * SPDX-License-Identifier: Apache-2.0 + */ + +import type { + CommandContext, + SlashCommand, + SlashCommandActionReturn, +} from './types.js'; +import { CommandKind } from './types.js'; +import { MessageType } from '../types.js'; +import type { HistoryItemBtw } from '../types.js'; +import { t } from '../../i18n/index.js'; +import type { GeminiClient } from '@qwen-code/qwen-code-core'; + +function makeBtwPromptId(sessionId: string): string { + return `${sessionId}########btw-${Date.now()}`; +} + +function formatBtwError(error: unknown): string { + return t('Failed to answer btw question: {{error}}', { + error: + error instanceof Error ? error.message : String(error || 'Unknown error'), + }); +} + +/** + * Helper to make the ephemeral generateContent call and extract the answer. + * Uses a snapshot of the current conversation history as context. + */ +async function askBtw( + geminiClient: GeminiClient, + model: string, + question: string, + abortSignal: AbortSignal, + promptId: string, +): Promise { + const history = geminiClient.getHistory(); + + const response = await geminiClient.generateContent( + [ + ...history, + { + role: 'user', + parts: [ + { + text: `[Side question - answer briefly and concisely, this is a "by the way" question that doesn't need to be part of our main conversation]\n\n${question}`, + }, + ], + }, + ], + {}, + abortSignal, + model, + promptId, + ); + + const parts = response.candidates?.[0]?.content?.parts; + return ( + parts + ?.map((part) => part.text) + .filter((text): text is string => typeof text === 'string') + .join('') || t('No response received.') + ); +} + +export const btwCommand: SlashCommand = { + name: 'btw', + get description() { + return t( + 'Ask a quick side question without affecting the main conversation', + ); + }, + kind: CommandKind.BUILT_IN, + action: async ( + context: CommandContext, + args: string, + ): Promise => { + const question = args.trim(); + const executionMode = context.executionMode ?? 'interactive'; + const abortSignal = context.abortSignal ?? new AbortController().signal; + + if (!question) { + return { + type: 'message', + messageType: 'error', + content: t('Please provide a question. Usage: /btw '), + }; + } + + const { config } = context.services; + const { ui } = context; + + if (!config) { + return { + type: 'message', + messageType: 'error', + content: t('Config not loaded.'), + }; + } + + const geminiClient = config.getGeminiClient(); + const model = config.getModel(); + const sessionId = config.getSessionId(); + + if (!model) { + return { + type: 'message', + messageType: 'error', + content: t('No model configured.'), + }; + } + + // ACP mode: return a stream_messages async generator + if (executionMode === 'acp') { + const btwPromptId = makeBtwPromptId(sessionId); + const messages = async function* () { + try { + yield { + messageType: 'info' as const, + content: t('Thinking...'), + }; + + const answer = await askBtw( + geminiClient, + model, + question, + abortSignal, + btwPromptId, + ); + + yield { + messageType: 'info' as const, + content: `btw> ${question}\n${answer}`, + }; + } catch (error) { + yield { + messageType: 'error' as const, + content: formatBtwError(error), + }; + } + }; + + return { type: 'stream_messages', messages: messages() }; + } + + // Non-interactive mode: return a simple message result + if (executionMode === 'non_interactive') { + try { + const btwPromptId = makeBtwPromptId(sessionId); + const answer = await askBtw( + geminiClient, + model, + question, + abortSignal, + btwPromptId, + ); + return { + type: 'message', + messageType: 'info', + content: `btw> ${question}\n${answer}`, + }; + } catch (error) { + return { + type: 'message', + messageType: 'error', + content: formatBtwError(error), + }; + } + } + + // Interactive mode: use dedicated btwItem state for the fixed bottom area. + // This does NOT occupy pendingItem, so the main conversation is never blocked. + + // Cancel any previous in-flight btw before starting a new one. + ui.cancelBtw(); + + const btwAbortController = new AbortController(); + const btwSignal = btwAbortController.signal; + ui.btwAbortControllerRef.current = btwAbortController; + + const pendingItem: HistoryItemBtw = { + type: MessageType.BTW, + btw: { + question, + answer: '', + isPending: true, + }, + }; + ui.setBtwItem(pendingItem); + + // Fire-and-forget: run the API call in the background so the main + // conversation is not blocked while waiting for the btw answer. + const btwPromptId = makeBtwPromptId(sessionId); + void askBtw(geminiClient, model, question, btwSignal, btwPromptId) + .then((answer) => { + if (btwSignal.aborted) return; + + ui.btwAbortControllerRef.current = null; + const completedItem: HistoryItemBtw = { + type: MessageType.BTW, + btw: { + question, + answer, + isPending: false, + }, + }; + ui.setBtwItem(completedItem); + }) + .catch((error) => { + if (btwSignal.aborted) return; + + ui.btwAbortControllerRef.current = null; + ui.setBtwItem(null); + ui.addItem( + { + type: MessageType.ERROR, + text: formatBtwError(error), + }, + Date.now(), + ); + }); + }, +}; diff --git a/packages/cli/src/ui/commands/clearCommand.test.ts b/packages/cli/src/ui/commands/clearCommand.test.ts index 5887a8012..61e66b53e 100644 --- a/packages/cli/src/ui/commands/clearCommand.test.ts +++ b/packages/cli/src/ui/commands/clearCommand.test.ts @@ -59,6 +59,7 @@ describe('clearCommand', () => { }), getModel: () => 'test-model', getToolRegistry: () => undefined, + getApprovalMode: () => 'default', }, }, session: { @@ -108,6 +109,7 @@ describe('clearCommand', () => { expect(mockFireSessionStartEvent).toHaveBeenCalledWith( SessionStartSource.Clear, 'test-model', + expect.any(String), // permissionMode ); // SessionEnd should be called before SessionStart @@ -138,6 +140,71 @@ describe('clearCommand', () => { expect(mockContext.ui.clear).toHaveBeenCalledTimes(1); }); + it('should clear UI before resetChat for immediate responsiveness', async () => { + if (!clearCommand.action) { + throw new Error('clearCommand must have an action.'); + } + + const callOrder: string[] = []; + (mockContext.ui.clear as ReturnType).mockImplementation( + () => { + callOrder.push('ui.clear'); + }, + ); + mockResetChat.mockImplementation(async () => { + callOrder.push('resetChat'); + }); + + await clearCommand.action(mockContext, ''); + + // ui.clear should be called before resetChat for immediate UI feedback + const clearIndex = callOrder.indexOf('ui.clear'); + const resetIndex = callOrder.indexOf('resetChat'); + expect(clearIndex).toBeGreaterThanOrEqual(0); + expect(resetIndex).toBeGreaterThanOrEqual(0); + expect(clearIndex).toBeLessThan(resetIndex); + }); + + it('should not await hook events (fire-and-forget)', async () => { + if (!clearCommand.action) { + throw new Error('clearCommand must have an action.'); + } + + // Make hooks take a long time - they should not block + let sessionEndResolved = false; + let sessionStartResolved = false; + mockFireSessionEndEvent.mockImplementation( + () => + new Promise((resolve) => { + setTimeout(() => { + sessionEndResolved = true; + resolve(undefined); + }, 5000); + }), + ); + mockFireSessionStartEvent.mockImplementation( + () => + new Promise((resolve) => { + setTimeout(() => { + sessionStartResolved = true; + resolve(undefined); + }, 5000); + }), + ); + + await clearCommand.action(mockContext, ''); + + // The action should complete immediately without waiting for hooks + expect(mockContext.ui.clear).toHaveBeenCalledTimes(1); + expect(mockResetChat).toHaveBeenCalledTimes(1); + // Hooks should have been called but not necessarily resolved + expect(mockFireSessionEndEvent).toHaveBeenCalled(); + expect(mockFireSessionStartEvent).toHaveBeenCalled(); + // Hooks should NOT have resolved yet since they have 5s timeouts + expect(sessionEndResolved).toBe(false); + expect(sessionStartResolved).toBe(false); + }); + it('should not attempt to reset chat if config service is not available', async () => { if (!clearCommand.action) { throw new Error('clearCommand must have an action.'); diff --git a/packages/cli/src/ui/commands/clearCommand.ts b/packages/cli/src/ui/commands/clearCommand.ts index 7de8192e2..571ee5c6c 100644 --- a/packages/cli/src/ui/commands/clearCommand.ts +++ b/packages/cli/src/ui/commands/clearCommand.ts @@ -13,6 +13,7 @@ import { SessionStartSource, ToolNames, SkillTool, + type PermissionMode, } from '@qwen-code/qwen-code-core'; export const clearCommand: SlashCommand = { @@ -26,14 +27,13 @@ export const clearCommand: SlashCommand = { const { config } = context.services; if (config) { - // Fire SessionEnd event before clearing (current session ends) - try { - await config - .getHookSystem() - ?.fireSessionEndEvent(SessionEndReason.Clear); - } catch (err) { - config.getDebugLogger().warn(`SessionEnd hook failed: ${err}`); - } + // Fire SessionEnd event (non-blocking to avoid UI lag) + config + .getHookSystem() + ?.fireSessionEndEvent(SessionEndReason.Clear) + .catch((err) => { + config.getDebugLogger().warn(`SessionEnd hook failed: ${err}`); + }); const newSessionId = config.startNewSession(); @@ -53,6 +53,9 @@ export const clearCommand: SlashCommand = { context.session.startNewSession(newSessionId); } + // Clear UI first for immediate responsiveness + context.ui.clear(); + const geminiClient = config.getGeminiClient(); if (geminiClient) { context.ui.setDebugMessage( @@ -65,21 +68,20 @@ export const clearCommand: SlashCommand = { context.ui.setDebugMessage(t('Starting a new session and clearing.')); } - // Fire SessionStart event after clearing (new session starts) - try { - await config - .getHookSystem() - ?.fireSessionStartEvent( - SessionStartSource.Clear, - config.getModel() ?? '', - ); - } catch (err) { - config.getDebugLogger().warn(`SessionStart hook failed: ${err}`); - } + // Fire SessionStart event (non-blocking to avoid UI lag) + config + .getHookSystem() + ?.fireSessionStartEvent( + SessionStartSource.Clear, + config.getModel() ?? '', + String(config.getApprovalMode()) as PermissionMode, + ) + .catch((err) => { + config.getDebugLogger().warn(`SessionStart hook failed: ${err}`); + }); } else { context.ui.setDebugMessage(t('Starting a new session and clearing.')); + context.ui.clear(); } - - context.ui.clear(); }, }; diff --git a/packages/cli/src/ui/commands/hooksCommand.test.ts b/packages/cli/src/ui/commands/hooksCommand.test.ts new file mode 100644 index 000000000..2da70b0d0 --- /dev/null +++ b/packages/cli/src/ui/commands/hooksCommand.test.ts @@ -0,0 +1,88 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { vi, describe, it, expect, beforeEach } from 'vitest'; +import { hooksCommand } from './hooksCommand.js'; +import { createMockCommandContext } from '../../test-utils/mockCommandContext.js'; + +describe('hooksCommand', () => { + let mockContext: ReturnType; + let mockConfig: { + getHookSystem: ReturnType; + }; + + beforeEach(() => { + vi.clearAllMocks(); + + // Create mock config with hook system + mockConfig = { + getHookSystem: vi.fn().mockReturnValue({ + getRegistry: vi.fn().mockReturnValue({ + getAllHooks: vi.fn().mockReturnValue([]), + }), + }), + }; + + mockContext = createMockCommandContext({ + services: { + config: mockConfig, + }, + }); + }); + + describe('basic functionality', () => { + it('should open hooks management dialog in interactive mode', async () => { + const result = await hooksCommand.action!(mockContext, ''); + + expect(result).toEqual({ + type: 'dialog', + dialog: 'hooks', + }); + }); + + it('should open hooks management dialog even if config is not available', async () => { + const contextWithoutConfig = createMockCommandContext({ + services: { + config: null, + }, + }); + + const result = await hooksCommand.action!(contextWithoutConfig, ''); + + expect(result).toEqual({ + type: 'dialog', + dialog: 'hooks', + }); + }); + + it('should open hooks management dialog even if hook system is not available', async () => { + mockConfig.getHookSystem = vi.fn().mockReturnValue(null); + + const result = await hooksCommand.action!(mockContext, ''); + + expect(result).toEqual({ + type: 'dialog', + dialog: 'hooks', + }); + }); + }); + + describe('non-interactive mode', () => { + it('should list hooks in non-interactive mode', async () => { + const nonInteractiveContext = createMockCommandContext({ + services: { + config: mockConfig, + }, + executionMode: 'non_interactive', + }); + + const result = await hooksCommand.action!(nonInteractiveContext, ''); + + // In non-interactive mode, it should return a message + expect(result).toHaveProperty('type', 'message'); + }); + }); +}); diff --git a/packages/cli/src/ui/commands/hooksCommand.ts b/packages/cli/src/ui/commands/hooksCommand.ts index 04951db7a..2a007dfeb 100644 --- a/packages/cli/src/ui/commands/hooksCommand.ts +++ b/packages/cli/src/ui/commands/hooksCommand.ts @@ -1,6 +1,6 @@ /** * @license - * Copyright 2025 Google LLC + * Copyright 2026 Qwen Team * SPDX-License-Identifier: Apache-2.0 */ @@ -20,13 +20,13 @@ import type { HookRegistryEntry } from '@qwen-code/qwen-code-core'; function formatHookSource(source: string): string { switch (source) { case 'project': - return 'Project'; + return t('Project'); case 'user': - return 'User'; + return t('User'); case 'system': - return 'System'; + return t('System'); case 'extensions': - return 'Extension'; + return t('Extension'); default: return source; } @@ -36,7 +36,7 @@ function formatHookSource(source: string): string { * Format hook status for display */ function formatHookStatus(enabled: boolean): string { - return enabled ? '✓ Enabled' : '✗ Disabled'; + return enabled ? t('✓ Enabled') : t('✗ Disabled'); } const listCommand: SlashCommand = { @@ -114,209 +114,27 @@ const listCommand: SlashCommand = { }, }; -const enableCommand: SlashCommand = { - name: 'enable', - get description() { - return t('Enable a disabled hook'); - }, - kind: CommandKind.BUILT_IN, - action: async ( - context: CommandContext, - args: string, - ): Promise => { - const hookName = args.trim(); - if (!hookName) { - return { - type: 'message', - messageType: 'error', - content: t( - 'Please specify a hook name. Usage: /hooks enable ', - ), - }; - } - - const { config } = context.services; - if (!config) { - return { - type: 'message', - messageType: 'error', - content: t('Config not loaded.'), - }; - } - - const hookSystem = config.getHookSystem(); - if (!hookSystem) { - return { - type: 'message', - messageType: 'error', - content: t('Hooks are not enabled.'), - }; - } - - const registry = hookSystem.getRegistry(); - registry.setHookEnabled(hookName, true); - - return { - type: 'message', - messageType: 'info', - content: t('Hook "{{name}}" has been enabled for this session.', { - name: hookName, - }), - }; - }, - completion: async (context: CommandContext, partialArg: string) => { - const { config } = context.services; - if (!config) return []; - - const hookSystem = config.getHookSystem(); - if (!hookSystem) return []; - - const registry = hookSystem.getRegistry(); - const allHooks = registry.getAllHooks(); - - // Return disabled hooks for enable command (deduplicated by name) - const disabledHookNames = allHooks - .filter((hook) => !hook.enabled) - .map((hook) => hook.config.name || hook.config.command || '') - .filter((name) => name && name.startsWith(partialArg)); - return [...new Set(disabledHookNames)]; - }, -}; - -const disableCommand: SlashCommand = { - name: 'disable', - get description() { - return t('Disable an active hook'); - }, - kind: CommandKind.BUILT_IN, - action: async ( - context: CommandContext, - args: string, - ): Promise => { - const hookName = args.trim(); - if (!hookName) { - return { - type: 'message', - messageType: 'error', - content: t( - 'Please specify a hook name. Usage: /hooks disable ', - ), - }; - } - - const { config } = context.services; - if (!config) { - return { - type: 'message', - messageType: 'error', - content: t('Config not loaded.'), - }; - } - - const hookSystem = config.getHookSystem(); - if (!hookSystem) { - return { - type: 'message', - messageType: 'error', - content: t('Hooks are not enabled.'), - }; - } - - const registry = hookSystem.getRegistry(); - registry.setHookEnabled(hookName, false); - - return { - type: 'message', - messageType: 'info', - content: t('Hook "{{name}}" has been disabled for this session.', { - name: hookName, - }), - }; - }, - completion: async (context: CommandContext, partialArg: string) => { - const { config } = context.services; - if (!config) return []; - - const hookSystem = config.getHookSystem(); - if (!hookSystem) return []; - - const registry = hookSystem.getRegistry(); - const allHooks = registry.getAllHooks(); - - // Return enabled hooks for disable command (deduplicated by name) - const enabledHookNames = allHooks - .filter((hook) => hook.enabled) - .map((hook) => hook.config.name || hook.config.command || '') - .filter((name) => name && name.startsWith(partialArg)); - return [...new Set(enabledHookNames)]; - }, -}; - export const hooksCommand: SlashCommand = { name: 'hooks', get description() { return t('Manage Qwen Code hooks'); }, kind: CommandKind.BUILT_IN, - subCommands: [listCommand, enableCommand, disableCommand], action: async ( context: CommandContext, args: string, ): Promise => { - // If no subcommand provided, show list - if (!args.trim()) { - const result = await listCommand.action?.(context, ''); - return result ?? { type: 'message', messageType: 'info', content: '' }; + // In interactive mode, open the hooks dialog + const executionMode = context.executionMode ?? 'interactive'; + if (executionMode === 'interactive') { + return { + type: 'dialog', + dialog: 'hooks', + }; } - const [subcommand, ...rest] = args.trim().split(/\s+/); - const subArgs = rest.join(' '); - - let result: SlashCommandActionReturn | void; - switch (subcommand.toLowerCase()) { - case 'list': - result = await listCommand.action?.(context, subArgs); - break; - case 'enable': - result = await enableCommand.action?.(context, subArgs); - break; - case 'disable': - result = await disableCommand.action?.(context, subArgs); - break; - default: - return { - type: 'message', - messageType: 'error', - content: t( - 'Unknown subcommand: {{cmd}}. Available: list, enable, disable', - { - cmd: subcommand, - }, - ), - }; - } + // In non-interactive mode, list hooks + const result = await listCommand.action?.(context, args); return result ?? { type: 'message', messageType: 'info', content: '' }; }, - completion: async (context: CommandContext, partialArg: string) => { - const subcommands = ['list', 'enable', 'disable']; - const parts = partialArg.split(/\s+/); - - if (parts.length <= 1) { - // Complete subcommand - return subcommands.filter((cmd) => cmd.startsWith(partialArg)); - } - - // Complete subcommand arguments - const [subcommand, ...rest] = parts; - const subArgs = rest.join(' '); - - switch (subcommand.toLowerCase()) { - case 'enable': - return enableCommand.completion?.(context, subArgs) ?? []; - case 'disable': - return disableCommand.completion?.(context, subArgs) ?? []; - default: - return []; - } - }, }; diff --git a/packages/cli/src/ui/commands/memoryCommand.test.ts b/packages/cli/src/ui/commands/memoryCommand.test.ts index ce25c5158..2634a7b23 100644 --- a/packages/cli/src/ui/commands/memoryCommand.test.ts +++ b/packages/cli/src/ui/commands/memoryCommand.test.ts @@ -168,6 +168,116 @@ describe('memoryCommand', () => { expect.any(Number), ); }); + + it('should fall back to AGENTS.md when QWEN.md does not exist for --project', async () => { + const projectCommand = showCommand.subCommands?.find( + (cmd) => cmd.name === '--project', + ); + if (!projectCommand?.action) throw new Error('Command has no action'); + + setGeminiMdFilename(['QWEN.md', 'AGENTS.md']); + vi.spyOn(process, 'cwd').mockReturnValue('/test/project'); + mockReadFile.mockImplementation(async (filePath: string) => { + if (filePath.endsWith('AGENTS.md')) return 'agents memory content'; + throw new Error('ENOENT'); + }); + + await projectCommand.action(mockContext, ''); + + const expectedPath = path.join('/test/project', 'AGENTS.md'); + expect(mockReadFile).toHaveBeenCalledWith(expectedPath, 'utf-8'); + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.INFO, + text: expect.stringContaining('agents memory content'), + }, + expect.any(Number), + ); + }); + + it('should fall back to AGENTS.md when QWEN.md does not exist for --global', async () => { + const globalCommand = showCommand.subCommands?.find( + (cmd) => cmd.name === '--global', + ); + if (!globalCommand?.action) throw new Error('Command has no action'); + + setGeminiMdFilename(['QWEN.md', 'AGENTS.md']); + vi.spyOn(os, 'homedir').mockReturnValue('/home/user'); + mockReadFile.mockImplementation(async (filePath: string) => { + if (filePath.endsWith('AGENTS.md')) return 'global agents memory'; + throw new Error('ENOENT'); + }); + + await globalCommand.action(mockContext, ''); + + const expectedPath = path.join('/home/user', QWEN_DIR, 'AGENTS.md'); + expect(mockReadFile).toHaveBeenCalledWith(expectedPath, 'utf-8'); + expect(mockContext.ui.addItem).toHaveBeenCalledWith( + { + type: MessageType.INFO, + text: expect.stringContaining('global agents memory'), + }, + expect.any(Number), + ); + }); + + it('should show content from both QWEN.md and AGENTS.md for --project when both exist', async () => { + const projectCommand = showCommand.subCommands?.find( + (cmd) => cmd.name === '--project', + ); + if (!projectCommand?.action) throw new Error('Command has no action'); + + setGeminiMdFilename(['QWEN.md', 'AGENTS.md']); + vi.spyOn(process, 'cwd').mockReturnValue('/test/project'); + mockReadFile.mockImplementation(async (filePath: string) => { + if (filePath.endsWith('QWEN.md')) return 'qwen memory'; + if (filePath.endsWith('AGENTS.md')) return 'agents memory'; + throw new Error('ENOENT'); + }); + + await projectCommand.action(mockContext, ''); + + expect(mockReadFile).toHaveBeenCalledWith( + path.join('/test/project', 'QWEN.md'), + 'utf-8', + ); + expect(mockReadFile).toHaveBeenCalledWith( + path.join('/test/project', 'AGENTS.md'), + 'utf-8', + ); + const addItemCall = (mockContext.ui.addItem as Mock).mock.calls[0][0]; + expect(addItemCall.text).toContain('qwen memory'); + expect(addItemCall.text).toContain('agents memory'); + }); + + it('should show content from both files for --global when both exist', async () => { + const globalCommand = showCommand.subCommands?.find( + (cmd) => cmd.name === '--global', + ); + if (!globalCommand?.action) throw new Error('Command has no action'); + + setGeminiMdFilename(['QWEN.md', 'AGENTS.md']); + vi.spyOn(os, 'homedir').mockReturnValue('/home/user'); + mockReadFile.mockImplementation(async (filePath: string) => { + if (filePath.endsWith('QWEN.md')) return 'global qwen memory'; + if (filePath.endsWith('AGENTS.md')) return 'global agents memory'; + throw new Error('ENOENT'); + }); + + await globalCommand.action(mockContext, ''); + + expect(mockReadFile).toHaveBeenCalledWith( + path.join('/home/user', QWEN_DIR, 'QWEN.md'), + 'utf-8', + ); + expect(mockReadFile).toHaveBeenCalledWith( + path.join('/home/user', QWEN_DIR, 'AGENTS.md'), + 'utf-8', + ); + const addItemCall = (mockContext.ui.addItem as Mock).mock.calls[0][0]; + expect(addItemCall.text).toContain('global qwen memory'); + expect(addItemCall.text).toContain('global agents memory'); + }); }); describe('/memory add', () => { diff --git a/packages/cli/src/ui/commands/memoryCommand.ts b/packages/cli/src/ui/commands/memoryCommand.ts index 507444e5a..709c00cd0 100644 --- a/packages/cli/src/ui/commands/memoryCommand.ts +++ b/packages/cli/src/ui/commands/memoryCommand.ts @@ -6,7 +6,7 @@ import { getErrorMessage, - getCurrentGeminiMdFilename, + getAllGeminiMdFilenames, loadServerHierarchicalMemory, QWEN_DIR, } from '@qwen-code/qwen-code-core'; @@ -18,6 +18,28 @@ import type { SlashCommand, SlashCommandActionReturn } from './types.js'; import { CommandKind } from './types.js'; import { t } from '../../i18n/index.js'; +/** + * Read all existing memory files from the configured filenames in a directory. + * Returns an array of found files with their paths and contents. + */ +async function findAllExistingMemoryFiles( + dir: string, +): Promise> { + const results: Array<{ filePath: string; content: string }> = []; + for (const filename of getAllGeminiMdFilenames()) { + const filePath = path.join(dir, filename); + try { + const content = await fs.readFile(filePath, 'utf-8'); + if (content.trim().length > 0) { + results.push({ filePath, content }); + } + } catch { + // File doesn't exist, try next + } + } + return results; +} + export const memoryCommand: SlashCommand = { name: 'memory', get description() { @@ -56,37 +78,27 @@ export const memoryCommand: SlashCommand = { }, kind: CommandKind.BUILT_IN, action: async (context) => { - try { - const workingDir = - context.services.config?.getWorkingDir?.() ?? process.cwd(); - const projectMemoryPath = path.join( - workingDir, - getCurrentGeminiMdFilename(), - ); - const memoryContent = await fs.readFile( - projectMemoryPath, - 'utf-8', - ); - - const messageContent = - memoryContent.trim().length > 0 - ? t( - 'Project memory content from {{path}}:\n\n---\n{{content}}\n---', - { - path: projectMemoryPath, - content: memoryContent, - }, - ) - : t('Project memory is currently empty.'); + const workingDir = + context.services.config?.getWorkingDir?.() ?? process.cwd(); + const results = await findAllExistingMemoryFiles(workingDir); + if (results.length > 0) { + const combined = results + .map((r) => + t( + 'Project memory content from {{path}}:\n\n---\n{{content}}\n---', + { path: r.filePath, content: r.content }, + ), + ) + .join('\n\n'); context.ui.addItem( { type: MessageType.INFO, - text: messageContent, + text: combined, }, Date.now(), ); - } catch (_error) { + } else { context.ui.addItem( { type: MessageType.INFO, @@ -106,32 +118,25 @@ export const memoryCommand: SlashCommand = { }, kind: CommandKind.BUILT_IN, action: async (context) => { - try { - const globalMemoryPath = path.join( - os.homedir(), - QWEN_DIR, - getCurrentGeminiMdFilename(), - ); - const globalMemoryContent = await fs.readFile( - globalMemoryPath, - 'utf-8', - ); - - const messageContent = - globalMemoryContent.trim().length > 0 - ? t('Global memory content:\n\n---\n{{content}}\n---', { - content: globalMemoryContent, - }) - : t('Global memory is currently empty.'); + const globalDir = path.join(os.homedir(), QWEN_DIR); + const results = await findAllExistingMemoryFiles(globalDir); + if (results.length > 0) { + const combined = results + .map((r) => + t('Global memory content:\n\n---\n{{content}}\n---', { + content: r.content, + }), + ) + .join('\n\n'); context.ui.addItem( { type: MessageType.INFO, - text: messageContent, + text: combined, }, Date.now(), ); - } catch (_error) { + } else { context.ui.addItem( { type: MessageType.INFO, diff --git a/packages/cli/src/ui/commands/types.ts b/packages/cli/src/ui/commands/types.ts index 49f937027..2bd798054 100644 --- a/packages/cli/src/ui/commands/types.ts +++ b/packages/cli/src/ui/commands/types.ts @@ -4,12 +4,13 @@ * SPDX-License-Identifier: Apache-2.0 */ -import type { ReactNode } from 'react'; +import type { MutableRefObject, ReactNode } from 'react'; import type { Content, PartListUnion } from '@google/genai'; import type { Config, GitService, Logger } from '@qwen-code/qwen-code-core'; import type { HistoryItemWithoutId, HistoryItem, + HistoryItemBtw, ConfirmationRequest, } from '../types.js'; import type { LoadedSettings } from '../../config/settings.js'; @@ -66,6 +67,14 @@ export interface CommandContext { * @param item The history item to display as pending, or `null` to clear. */ setPendingItem: (item: HistoryItemWithoutId | null) => void; + /** The current btw side-question item rendered in the fixed bottom area. */ + btwItem: HistoryItemBtw | null; + /** Sets the btw item independently of the main pendingItem. */ + setBtwItem: (item: HistoryItemBtw | null) => void; + /** Cancels a pending btw (aborts the in-flight API call and clears the btw area). */ + cancelBtw: () => void; + /** Ref to the btw AbortController, set by btwCommand so cancelBtw can abort it. */ + btwAbortControllerRef: MutableRefObject; /** * Loads a new set of history items, replacing the current history. * @@ -155,6 +164,7 @@ export interface OpenDialogActionReturn { | 'approval-mode' | 'resume' | 'extensions_manage' + | 'hooks' | 'mcp'; } diff --git a/packages/cli/src/ui/components/DialogManager.tsx b/packages/cli/src/ui/components/DialogManager.tsx index 2e5fae0c8..e2f1256ff 100644 --- a/packages/cli/src/ui/components/DialogManager.tsx +++ b/packages/cli/src/ui/components/DialogManager.tsx @@ -41,6 +41,7 @@ import { AgentCreationWizard } from './subagents/create/AgentCreationWizard.js'; import { AgentsManagerDialog } from './subagents/manage/AgentsManagerDialog.js'; import { ExtensionsManagerDialog } from './extensions/ExtensionsManagerDialog.js'; import { MCPManagementDialog } from './mcp/MCPManagementDialog.js'; +import { HooksManagementDialog } from './hooks/HooksManagementDialog.js'; import { SessionPicker } from './SessionPicker.js'; interface DialogManagerProps { @@ -351,6 +352,9 @@ export const DialogManager = ({ /> ); } + if (uiState.isHooksDialogOpen) { + return ; + } if (uiState.isMcpDialogOpen) { return ; } diff --git a/packages/cli/src/ui/components/HistoryItemDisplay.tsx b/packages/cli/src/ui/components/HistoryItemDisplay.tsx index b52a2b9bf..12a46380e 100644 --- a/packages/cli/src/ui/components/HistoryItemDisplay.tsx +++ b/packages/cli/src/ui/components/HistoryItemDisplay.tsx @@ -42,6 +42,7 @@ import { McpStatus } from './views/McpStatus.js'; import { ContextUsage } from './views/ContextUsage.js'; import { ArenaAgentCard, ArenaSessionCard } from './arena/ArenaCards.js'; import { InsightProgressMessage } from './messages/InsightProgressMessage.js'; +import { BtwMessage } from './messages/BtwMessage.js'; interface HistoryItemDisplayProps { item: HistoryItem; @@ -226,6 +227,9 @@ const HistoryItemDisplayComponent: React.FC = ({ {itemForDisplay.type === 'insight_progress' && ( )} + {itemForDisplay.type === 'btw' && itemForDisplay.btw && ( + + )} ); }; diff --git a/packages/cli/src/ui/components/hooks/HookConfigDetailStep.test.tsx b/packages/cli/src/ui/components/hooks/HookConfigDetailStep.test.tsx new file mode 100644 index 000000000..1f2728965 --- /dev/null +++ b/packages/cli/src/ui/components/hooks/HookConfigDetailStep.test.tsx @@ -0,0 +1,280 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render } from 'ink-testing-library'; +import { + HookEventName, + HooksConfigSource, + HookType, +} from '@qwen-code/qwen-code-core'; +import { HookConfigDetailStep } from './HookConfigDetailStep.js'; +import type { HookEventDisplayInfo, HookConfigDisplayInfo } from './types.js'; + +// Mock i18n module +vi.mock('../../../i18n/index.js', () => ({ + t: vi.fn((key: string) => key), +})); + +// Mock useTerminalSize +vi.mock('../../hooks/useTerminalSize.js', () => ({ + useTerminalSize: vi.fn(() => ({ columns: 100, rows: 24 })), +})); + +// Mock semantic-colors +vi.mock('../../semantic-colors.js', () => ({ + theme: { + text: { + primary: 'white', + secondary: 'gray', + accent: 'cyan', + }, + border: { + default: 'gray', + }, + }, +})); + +describe('HookConfigDetailStep', () => { + const createMockHookEvent = (): HookEventDisplayInfo => ({ + event: HookEventName.Stop, + shortDescription: 'Right before Qwen Code concludes its response', + description: '', + exitCodes: [ + { code: 0, description: 'stdout/stderr not shown' }, + { + code: 2, + description: 'show stderr to model and continue conversation', + }, + { code: 'Other', description: 'show stderr to user only' }, + ], + configs: [], + }); + + const createMockHookConfig = ( + source: HooksConfigSource = HooksConfigSource.User, + sourceDisplay = 'User Settings', + sourcePath?: string, + ): HookConfigDisplayInfo => ({ + config: { + type: HookType.Command, + command: '/path/to/hook.sh', + }, + source, + sourceDisplay, + sourcePath, + enabled: true, + }); + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('should render hook details title', () => { + const hookEvent = createMockHookEvent(); + const hookConfig = createMockHookConfig(); + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('Hook details'); + }); + + it('should render event name', () => { + const hookEvent = createMockHookEvent(); + const hookConfig = createMockHookConfig(); + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('Event:'); + expect(lastFrame()).toContain(HookEventName.Stop); + }); + + it('should render hook type', () => { + const hookEvent = createMockHookEvent(); + const hookConfig = createMockHookConfig(); + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('Type:'); + expect(lastFrame()).toContain('command'); + }); + + it('should render source for User Settings', () => { + const hookEvent = createMockHookEvent(); + const hookConfig = createMockHookConfig(HooksConfigSource.User); + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('Source:'); + expect(lastFrame()).toContain('User Settings'); + }); + + it('should render source for Local Settings', () => { + const hookEvent = createMockHookEvent(); + const hookConfig = createMockHookConfig(HooksConfigSource.Project); + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('Local Settings'); + }); + + it('should render source for Extensions with path', () => { + const hookEvent = createMockHookEvent(); + const hookConfig = createMockHookConfig( + HooksConfigSource.Extensions, + 'ralph-wiggum', + '/Users/test/.qwen/extensions/ralph-wiggum', + ); + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('Extensions'); + expect(lastFrame()).toContain('/Users/test/.qwen/extensions/ralph-wiggum'); + }); + + it('should render Extension field for extensions', () => { + const hookEvent = createMockHookEvent(); + const hookConfig = createMockHookConfig( + HooksConfigSource.Extensions, + 'ralph-wiggum', + ); + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('Extension:'); + expect(lastFrame()).toContain('ralph-wiggum'); + }); + + it('should not render Extension field for non-extensions', () => { + const hookEvent = createMockHookEvent(); + const hookConfig = createMockHookConfig(HooksConfigSource.User); + + const { lastFrame } = render( + , + ); + + // Should not have Extension label for User Settings + const output = lastFrame(); + const extensionMatch = output?.match(/Extension:/g); + expect(extensionMatch).toBeNull(); + }); + + it('should render command', () => { + const hookEvent = createMockHookEvent(); + const hookConfig = createMockHookConfig(); + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('Command:'); + expect(lastFrame()).toContain('/path/to/hook.sh'); + }); + + it('should render hook name if present', () => { + const hookEvent = createMockHookEvent(); + const hookConfig: HookConfigDisplayInfo = { + config: { + type: HookType.Command, + command: '/path/to/hook.sh', + name: 'My Hook', + }, + source: HooksConfigSource.User, + sourceDisplay: 'User Settings', + enabled: true, + }; + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('Name:'); + expect(lastFrame()).toContain('My Hook'); + }); + + it('should render hook description if present', () => { + const hookEvent = createMockHookEvent(); + const hookConfig: HookConfigDisplayInfo = { + config: { + type: HookType.Command, + command: '/path/to/hook.sh', + description: 'A test hook', + }, + source: HooksConfigSource.User, + sourceDisplay: 'User Settings', + enabled: true, + }; + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('Desc:'); + expect(lastFrame()).toContain('A test hook'); + }); + + it('should render help text', () => { + const hookEvent = createMockHookEvent(); + const hookConfig = createMockHookConfig(); + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('To modify or remove this hook'); + }); + + it('should render Esc hint', () => { + const hookEvent = createMockHookEvent(); + const hookConfig = createMockHookConfig(); + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('Esc to go back'); + }); + + it('should handle different event types', () => { + const events = [ + HookEventName.PreToolUse, + HookEventName.PostToolUse, + HookEventName.UserPromptSubmit, + HookEventName.SessionStart, + ]; + + for (const event of events) { + const hookEvent: HookEventDisplayInfo = { + event, + shortDescription: 'Test', + description: '', + exitCodes: [], + configs: [], + }; + const hookConfig = createMockHookConfig(); + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain(event); + } + }); +}); diff --git a/packages/cli/src/ui/components/hooks/HookConfigDetailStep.tsx b/packages/cli/src/ui/components/hooks/HookConfigDetailStep.tsx new file mode 100644 index 000000000..27f3016a1 --- /dev/null +++ b/packages/cli/src/ui/components/hooks/HookConfigDetailStep.tsx @@ -0,0 +1,167 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { Box, Text } from 'ink'; +import { theme } from '../../semantic-colors.js'; +import { useTerminalSize } from '../../hooks/useTerminalSize.js'; +import type { HookConfigDisplayInfo, HookEventDisplayInfo } from './types.js'; +import { HooksConfigSource } from '@qwen-code/qwen-code-core'; +import { t } from '../../../i18n/index.js'; + +interface HookConfigDetailStepProps { + hookEvent: HookEventDisplayInfo; + hookConfig: HookConfigDisplayInfo; +} + +export function HookConfigDetailStep({ + hookEvent, + hookConfig, +}: HookConfigDetailStepProps): React.JSX.Element { + const { columns: terminalWidth } = useTerminalSize(); + + // Get source display + const getSourceDisplay = (): string => { + switch (hookConfig.source) { + case HooksConfigSource.Project: + return t('Local Settings'); + case HooksConfigSource.User: + return t('User Settings'); + case HooksConfigSource.System: + return t('System Settings'); + case HooksConfigSource.Extensions: + return t('Extensions'); + default: + return hookConfig.source; + } + }; + + // Check if this is from an extension + const isFromExtension = hookConfig.source === HooksConfigSource.Extensions; + + // Get hook type display + const getHookTypeDisplay = (): string => { + switch (hookConfig.config.type) { + case 'command': + return 'command'; + default: + return hookConfig.config.type; + } + }; + + // Get command to display + const getCommand = (): string => { + if (hookConfig.config.type === 'command') { + return hookConfig.config.command; + } + return ''; + }; + + // Calculate box width for command display + const commandBoxWidth = Math.min(terminalWidth - 6, 80); + + // Label width for alignment (Extension: is the longest label) + const labelWidth = 12; + + return ( + + {/* Title */} + + + {t('Hook details')} + + + + {/* Event */} + + + {t('Event:')} + + {hookEvent.event} + + + {/* Type */} + + + {t('Type:')} + + {getHookTypeDisplay()} + + + {/* Source */} + + + {t('Source:')} + + {getSourceDisplay()} + {hookConfig.sourcePath && ( + ({hookConfig.sourcePath}) + )} + + + {/* Extension name (only for extensions) */} + {isFromExtension && hookConfig.sourceDisplay && ( + + + {t('Extension:')} + + {hookConfig.sourceDisplay} + + )} + + {/* Name (if exists) */} + {hookConfig.config.name && ( + + + {t('Name:')} + + {hookConfig.config.name} + + )} + + {/* Description (if exists) */} + {hookConfig.config.description && ( + + + {t('Desc:')} + + + {hookConfig.config.description} + + + )} + + {/* Command */} + + {t('Command:')} + + + {/* Command box */} + + {getCommand()} + + + {/* Help text */} + + + {t( + 'To modify or remove this hook, edit settings.json directly or ask Qwen to help.', + )} + + + + {/* Footer hint */} + + {t('Esc to go back')} + + + ); +} diff --git a/packages/cli/src/ui/components/hooks/HookDetailStep.test.tsx b/packages/cli/src/ui/components/hooks/HookDetailStep.test.tsx new file mode 100644 index 000000000..0b5f1c6b7 --- /dev/null +++ b/packages/cli/src/ui/components/hooks/HookDetailStep.test.tsx @@ -0,0 +1,228 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render } from 'ink-testing-library'; +import { + HookEventName, + HooksConfigSource, + HookType, +} from '@qwen-code/qwen-code-core'; +import { HookDetailStep } from './HookDetailStep.js'; +import type { HookEventDisplayInfo } from './types.js'; + +// Mock i18n module +vi.mock('../../../i18n/index.js', () => ({ + t: vi.fn((key: string) => key), +})); + +// Mock useTerminalSize +vi.mock('../../hooks/useTerminalSize.js', () => ({ + useTerminalSize: vi.fn(() => ({ columns: 100, rows: 24 })), +})); + +// Mock semantic-colors +vi.mock('../../semantic-colors.js', () => ({ + theme: { + text: { + primary: 'white', + secondary: 'gray', + accent: 'cyan', + }, + status: { + success: 'green', + error: 'red', + }, + }, +})); + +describe('HookDetailStep', () => { + const createMockHookInfo = ( + event: HookEventName, + configCount = 0, + hasDescription = true, + ): HookEventDisplayInfo => ({ + event, + shortDescription: `Short description for ${event}`, + description: hasDescription ? `Detailed description for ${event}` : '', + exitCodes: [ + { code: 0, description: 'Success' }, + { code: 2, description: 'Block' }, + ], + configs: Array(configCount) + .fill(null) + .map((_, i) => ({ + config: { command: `hook-command-${i}`, type: HookType.Command }, + source: + i % 2 === 0 ? HooksConfigSource.User : HooksConfigSource.Project, + sourceDisplay: i % 2 === 0 ? 'User Settings' : 'Local Settings', + enabled: true, + })), + }); + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('should render hook event name as title', () => { + const hook = createMockHookInfo(HookEventName.PreToolUse); + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain(HookEventName.PreToolUse); + }); + + it('should render description when present', () => { + const hook = createMockHookInfo(HookEventName.PreToolUse, 0, true); + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('Detailed description for PreToolUse'); + }); + + it('should not render description section when empty', () => { + const hook = createMockHookInfo(HookEventName.Stop, 0, false); + + const { lastFrame } = render( + , + ); + + // Stop event has empty description + const output = lastFrame(); + expect(output).toContain(HookEventName.Stop); + }); + + it('should render exit codes', () => { + const hook = createMockHookInfo(HookEventName.PreToolUse); + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + expect(output).toContain('Exit codes'); + expect(output).toContain('0'); + expect(output).toContain('Success'); + expect(output).toContain('2'); + expect(output).toContain('Block'); + }); + + it('should show empty state when no configs', () => { + const hook = createMockHookInfo(HookEventName.PreToolUse, 0); + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + expect(output).toContain('No hooks configured for this event'); + expect(output).toContain('To add hooks, edit settings.json'); + }); + + it('should show configured hooks list when configs exist', () => { + const hook = createMockHookInfo(HookEventName.PreToolUse, 2); + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + expect(output).toContain('Configured hooks'); + expect(output).toContain('[command]'); + expect(output).toContain('hook-command-0'); + expect(output).toContain('hook-command-1'); + }); + + it('should show source display for each config', () => { + const hook = createMockHookInfo(HookEventName.PreToolUse, 2); + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + expect(output).toContain('User Settings'); + expect(output).toContain('Local Settings'); + }); + + it('should show selection indicator for first config', () => { + const hook = createMockHookInfo(HookEventName.PreToolUse, 3); + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + expect(output).toContain('❯'); + }); + + it('should show keyboard hint for going back', () => { + const hook = createMockHookInfo(HookEventName.PreToolUse); + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('Esc to go back'); + }); + + it('should render with multiple configs', () => { + const hook = createMockHookInfo(HookEventName.PostToolUse, 5); + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + expect(output).toContain('1.'); + expect(output).toContain('2.'); + expect(output).toContain('3.'); + expect(output).toContain('4.'); + expect(output).toContain('5.'); + }); + + it('should handle hook with no exit codes', () => { + const hook: HookEventDisplayInfo = { + event: HookEventName.PreToolUse, + shortDescription: 'Test', + description: 'Test description', + exitCodes: [], + configs: [], + }; + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + expect(output).not.toContain('Exit codes'); + }); + + it('should handle different hook event types', () => { + const events = [ + HookEventName.Stop, + HookEventName.PreToolUse, + HookEventName.PostToolUse, + HookEventName.UserPromptSubmit, + HookEventName.SessionStart, + HookEventName.SessionEnd, + ]; + + for (const event of events) { + const hook = createMockHookInfo(event, 1); + + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain(event); + } + }); +}); diff --git a/packages/cli/src/ui/components/hooks/HookDetailStep.tsx b/packages/cli/src/ui/components/hooks/HookDetailStep.tsx new file mode 100644 index 000000000..69c5d24e3 --- /dev/null +++ b/packages/cli/src/ui/components/hooks/HookDetailStep.tsx @@ -0,0 +1,150 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { Box, Text } from 'ink'; +import { theme } from '../../semantic-colors.js'; +import { useTerminalSize } from '../../hooks/useTerminalSize.js'; +import type { HookEventDisplayInfo } from './types.js'; +import { HooksConfigSource } from '@qwen-code/qwen-code-core'; +import { getTranslatedSourceDisplayMap } from './constants.js'; +import { t } from '../../../i18n/index.js'; + +interface HookDetailStepProps { + hook: HookEventDisplayInfo; + selectedIndex: number; +} + +export function HookDetailStep({ + hook, + selectedIndex, +}: HookDetailStepProps): React.JSX.Element { + const hasConfigs = hook.configs.length > 0; + const { columns: terminalWidth } = useTerminalSize(); + + // Get translated source display map + const sourceDisplayMap = getTranslatedSourceDisplayMap(); + + // Calculate column widths (command: 70%, source: 30%) + const commandWidth = Math.floor(terminalWidth * 0.65); + const sourceWidth = Math.floor(terminalWidth * 0.3); + + // Get source display for config list + const getConfigSourceDisplay = (config: { + source: HooksConfigSource; + sourceDisplay: string; + }): string => { + if (config.source === HooksConfigSource.Extensions) { + // For extensions, sourceDisplay is the extension name + return `${sourceDisplayMap[HooksConfigSource.Extensions]} (${config.sourceDisplay})`; + } + return sourceDisplayMap[config.source] || config.source; + }; + + return ( + + {/* Title */} + + + {hook.event} + + + + {/* Description */} + {hook.description && ( + + {hook.description} + + )} + + {/* Exit codes */} + {hook.exitCodes.length > 0 && ( + + + {t('Exit codes:')} + + {hook.exitCodes.map((ec, index) => ( + + + {` ${ec.code}: ${ec.description}`} + + + ))} + + )} + + + + {/* Configs or empty state */} + {hasConfigs ? ( + <> + + {t('Configured hooks:')} + + {hook.configs.map((config, index) => { + const isSelected = index === selectedIndex; + const sourceDisplay = getConfigSourceDisplay(config); + const command = + config.config.type === 'command' ? config.config.command : ''; + const hookType = config.config.type; + + return ( + + {/* Left column: selector + command */} + + + + {isSelected ? '❯' : ' '} + + + + {`${index + 1}. [${hookType}] ${command}`} + + + {/* Spacer between columns */} + + {/* Right column: source */} + + + {sourceDisplay} + + + + ); + })} + + + {t('Enter to select · Esc to go back')} + + + + ) : ( + <> + + + {t('No hooks configured for this event.')} + + + + + {t('To add hooks, edit settings.json directly or ask Qwen.')} + + + + {t('Esc to go back')} + + + )} + + ); +} diff --git a/packages/cli/src/ui/components/hooks/HooksListStep.test.tsx b/packages/cli/src/ui/components/hooks/HooksListStep.test.tsx new file mode 100644 index 000000000..a328ca66a --- /dev/null +++ b/packages/cli/src/ui/components/hooks/HooksListStep.test.tsx @@ -0,0 +1,197 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render } from 'ink-testing-library'; +import { + HookEventName, + HookType, + HooksConfigSource, +} from '@qwen-code/qwen-code-core'; +import { HooksListStep } from './HooksListStep.js'; +import type { HookEventDisplayInfo } from './types.js'; + +// Mock i18n module +vi.mock('../../../i18n/index.js', () => ({ + t: vi.fn((key: string, options?: { count?: string }) => { + // Handle pluralization + if (key === '{{count}} hook configured' && options?.count) { + return `${options.count} hook configured`; + } + if (key === '{{count}} hooks configured' && options?.count) { + return `${options.count} hooks configured`; + } + return key; + }), +})); + +// Mock useTerminalSize +vi.mock('../../hooks/useTerminalSize.js', () => ({ + useTerminalSize: vi.fn(() => ({ columns: 120, rows: 24 })), +})); + +// Mock semantic-colors +vi.mock('../../semantic-colors.js', () => ({ + theme: { + text: { + primary: 'white', + secondary: 'gray', + accent: 'cyan', + }, + status: { + success: 'green', + error: 'red', + }, + }, +})); + +describe('HooksListStep', () => { + const createMockHookInfo = ( + event: HookEventName, + configCount = 0, + ): HookEventDisplayInfo => ({ + event, + shortDescription: `Description for ${event}`, + description: `Detailed description for ${event}`, + exitCodes: [ + { code: 0, description: 'Success' }, + { code: 2, description: 'Block' }, + ], + configs: Array(configCount) + .fill(null) + .map((_, i) => ({ + config: { command: `hook-${i}`, type: HookType.Command }, + source: HooksConfigSource.User, + sourceDisplay: 'User Settings', + enabled: true, + })), + }); + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('should render empty state when no hooks', () => { + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain('No hook events found'); + }); + + it('should render list of hooks', () => { + const hooks: HookEventDisplayInfo[] = [ + createMockHookInfo(HookEventName.PreToolUse), + createMockHookInfo(HookEventName.PostToolUse), + ]; + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + expect(output).toContain('Hooks'); + expect(output).toContain(HookEventName.PreToolUse); + expect(output).toContain(HookEventName.PostToolUse); + }); + + it('should show config count for hooks with configs', () => { + const hooks: HookEventDisplayInfo[] = [ + createMockHookInfo(HookEventName.PreToolUse, 3), + createMockHookInfo(HookEventName.PostToolUse, 0), + ]; + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + expect(output).toContain('(3)'); + expect(output).not.toContain('(0)'); + }); + + it('should show singular form for single hook', () => { + const hooks: HookEventDisplayInfo[] = [ + createMockHookInfo(HookEventName.PreToolUse, 1), + ]; + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + expect(output).toContain('1 hook configured'); + }); + + it('should show read-only message', () => { + const hooks: HookEventDisplayInfo[] = [ + createMockHookInfo(HookEventName.PreToolUse), + ]; + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + expect(output).toContain('read-only'); + expect(output).toContain('settings.json'); + }); + + it('should show keyboard hints', () => { + const hooks: HookEventDisplayInfo[] = [ + createMockHookInfo(HookEventName.PreToolUse), + ]; + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + expect(output).toContain('Enter to select'); + expect(output).toContain('Esc to cancel'); + }); + + it('should show selection indicator for first item', () => { + const hooks: HookEventDisplayInfo[] = [ + createMockHookInfo(HookEventName.PreToolUse), + createMockHookInfo(HookEventName.PostToolUse), + ]; + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + expect(output).toContain('❯'); + }); + + it('should display hook short descriptions', () => { + const hooks: HookEventDisplayInfo[] = [ + createMockHookInfo(HookEventName.PreToolUse), + ]; + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + expect(output).toContain('Description for PreToolUse'); + }); + + it('should pad index numbers based on total count', () => { + const hooks: HookEventDisplayInfo[] = Array(10) + .fill(null) + .map((_, i) => createMockHookInfo(`${i}` as HookEventName)); + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + expect(output).toContain(' 1.'); + expect(output).toContain('10.'); + }); +}); diff --git a/packages/cli/src/ui/components/hooks/HooksListStep.tsx b/packages/cli/src/ui/components/hooks/HooksListStep.tsx new file mode 100644 index 000000000..5b3da41f5 --- /dev/null +++ b/packages/cli/src/ui/components/hooks/HooksListStep.tsx @@ -0,0 +1,103 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { Box, Text } from 'ink'; +import { theme } from '../../semantic-colors.js'; +import { useTerminalSize } from '../../hooks/useTerminalSize.js'; +import type { HookEventDisplayInfo } from './types.js'; +import { t } from '../../../i18n/index.js'; + +interface HooksListStepProps { + hooks: HookEventDisplayInfo[]; + selectedIndex: number; +} + +export function HooksListStep({ + hooks, + selectedIndex, +}: HooksListStepProps): React.JSX.Element { + const { columns: terminalWidth } = useTerminalSize(); + + // Calculate responsive width for hook name column (min 20, max 35) + const hookNameWidth = Math.min( + 35, + Math.max(20, Math.floor(terminalWidth * 0.25)), + ); + + if (hooks.length === 0) { + return ( + + {t('No hook events found.')} + + ); + } + + // Calculate total configured hooks + const totalConfigured = hooks.reduce( + (sum, hook) => sum + hook.configs.length, + 0, + ); + + // Get the correct plural/singular form + const hooksConfiguredText = + totalConfigured === 1 + ? t('{{count}} hook configured', { count: String(totalConfigured) }) + : t('{{count}} hooks configured', { count: String(totalConfigured) }); + + return ( + + + + {t('Hooks')} + + {` · ${hooksConfiguredText}`} + + + + + {t( + 'This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.', + )} + + + + {hooks.map((hook, index) => { + const isSelected = index === selectedIndex; + const configCount = hook.configs.length; + const maxDigits = String(hooks.length).length; + const paddedIndex = String(index + 1).padStart(maxDigits); + + return ( + + + + {isSelected ? '❯' : ' '} + + + + + {paddedIndex}. {hook.event} + {configCount > 0 && ( + ({configCount}) + )} + + + {hook.shortDescription} + + ); + })} + + + + {t('Enter to select · Esc to cancel')} + + + + ); +} diff --git a/packages/cli/src/ui/components/hooks/HooksManagementDialog.test.tsx b/packages/cli/src/ui/components/hooks/HooksManagementDialog.test.tsx new file mode 100644 index 000000000..08189ff49 --- /dev/null +++ b/packages/cli/src/ui/components/hooks/HooksManagementDialog.test.tsx @@ -0,0 +1,127 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { HooksManagementDialog } from './HooksManagementDialog.js'; +import { renderWithProviders } from '../../../test-utils/render.js'; + +// Mock i18n module +vi.mock('../../../i18n/index.js', () => ({ + t: vi.fn((key: string, options?: { count?: string }) => { + // Handle pluralization + if (key === '{{count}} hook configured' && options?.count) { + return `${options.count} hook configured`; + } + if (key === '{{count}} hooks configured' && options?.count) { + return `${options.count} hooks configured`; + } + return key; + }), +})); + +// Mock useTerminalSize +vi.mock('../../hooks/useTerminalSize.js', () => ({ + useTerminalSize: vi.fn(() => ({ columns: 120, rows: 24 })), +})); + +// Mock useConfig +vi.mock('../../contexts/ConfigContext.js', async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + useConfig: vi.fn(() => ({ + getExtensions: vi.fn(() => []), + })), + }; +}); + +// Mock loadSettings +vi.mock('../../../config/settings.js', async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + loadSettings: vi.fn(() => ({ + forScope: vi.fn(() => ({ settings: {} })), + })), + }; +}); + +// Mock semantic-colors +vi.mock('../../semantic-colors.js', () => ({ + theme: { + text: { + primary: 'white', + secondary: 'gray', + accent: 'cyan', + }, + status: { + success: 'green', + error: 'red', + }, + border: { + default: 'gray', + }, + }, +})); + +// Mock createDebugLogger +vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + createDebugLogger: vi.fn(() => ({ + log: vi.fn(), + error: vi.fn(), + })), + }; +}); + +describe('HooksManagementDialog', () => { + const mockOnClose = vi.fn(); + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('should render loading state initially', () => { + const { lastFrame } = renderWithProviders( + , + ); + + expect(lastFrame()).toContain('Loading hooks'); + }); + + it('should render with border', async () => { + const { lastFrame, unmount } = renderWithProviders( + , + ); + + await new Promise((resolve) => setTimeout(resolve, 100)); + + // The dialog should have a border (rendered as box-drawing characters) + const output = lastFrame(); + expect(output).toBeTruthy(); + + unmount(); + }); + + it('should handle empty hooks list gracefully', async () => { + const { lastFrame, unmount } = renderWithProviders( + , + ); + + await new Promise((resolve) => setTimeout(resolve, 100)); + + const output = lastFrame(); + // Should show 0 hooks configured when no hooks are configured + expect(output).toContain('0 hooks configured'); + + unmount(); + }); +}); diff --git a/packages/cli/src/ui/components/hooks/HooksManagementDialog.tsx b/packages/cli/src/ui/components/hooks/HooksManagementDialog.tsx new file mode 100644 index 000000000..fd18da36b --- /dev/null +++ b/packages/cli/src/ui/components/hooks/HooksManagementDialog.tsx @@ -0,0 +1,421 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { useState, useCallback, useEffect, useMemo } from 'react'; +import { Box, Text } from 'ink'; +import { theme } from '../../semantic-colors.js'; +import { useTerminalSize } from '../../hooks/useTerminalSize.js'; +import { useKeypress } from '../../hooks/useKeypress.js'; +import { useConfig } from '../../contexts/ConfigContext.js'; +import { loadSettings, SettingScope } from '../../../config/settings.js'; +import { + HooksConfigSource, + type HookDefinition, + type HookConfig, + createDebugLogger, + HOOKS_CONFIG_FIELDS, +} from '@qwen-code/qwen-code-core'; +import type { + HooksManagementDialogProps, + HookEventDisplayInfo, +} from './types.js'; +import { HOOKS_MANAGEMENT_STEPS } from './types.js'; +import { HooksListStep } from './HooksListStep.js'; +import { HookDetailStep } from './HookDetailStep.js'; +import { HookConfigDetailStep } from './HookConfigDetailStep.js'; +import { + DISPLAY_HOOK_EVENTS, + getTranslatedSourceDisplayMap, + createEmptyHookEventInfo, +} from './constants.js'; +import { t } from '../../../i18n/index.js'; + +const debugLogger = createDebugLogger('HOOKS_DIALOG'); + +/** + * Type guard to check if a value is a valid HookConfig + */ +function isValidHookConfig(config: unknown): config is HookConfig { + return ( + typeof config === 'object' && + config !== null && + 'type' in config && + 'command' in config && + typeof (config as HookConfig).command === 'string' + ); +} + +/** + * Type guard to check if a value is a valid HookDefinition + */ +function isValidHookDefinition(def: unknown): def is HookDefinition { + if (typeof def !== 'object' || def === null) { + return false; + } + const obj = def as Record; + // hooks array is required + if (!('hooks' in obj) || !Array.isArray(obj['hooks'])) { + return false; + } + // Validate each hook config in the array + for (const hook of obj['hooks']) { + if (!isValidHookConfig(hook)) { + return false; + } + } + // matcher is optional but must be a string if present + if ('matcher' in obj && typeof obj['matcher'] !== 'string') { + return false; + } + // sequential is optional but must be a boolean if present + if ('sequential' in obj && typeof obj['sequential'] !== 'boolean') { + return false; + } + return true; +} + +/** + * Type guard to check if a value is a valid hooks record + */ +function isValidHooksRecord( + hooks: unknown, +): hooks is Record { + if (typeof hooks !== 'object' || hooks === null) { + return false; + } + const record = hooks as Record; + for (const [key, value] of Object.entries(record)) { + // Skip non-event configuration fields + if (HOOKS_CONFIG_FIELDS.includes(key)) { + continue; + } + if (!Array.isArray(value)) { + return false; + } + for (const def of value) { + if (!isValidHookDefinition(def)) { + return false; + } + } + } + return true; +} + +export function HooksManagementDialog({ + onClose, +}: HooksManagementDialogProps): React.JSX.Element { + const config = useConfig(); + const { columns: width } = useTerminalSize(); + const boxWidth = width - 4; + + const [navigationStack, setNavigationStack] = useState([ + HOOKS_MANAGEMENT_STEPS.HOOKS_LIST, + ]); + const [selectedHookIndex, setSelectedHookIndex] = useState(-1); + const [selectedConfigIndex, setSelectedConfigIndex] = useState(-1); + // Track selected index within each step for keyboard navigation + const [listSelectedIndex, setListSelectedIndex] = useState(0); + const [detailSelectedIndex, setDetailSelectedIndex] = useState(0); + const [hooks, setHooks] = useState([]); + const [isLoading, setIsLoading] = useState(true); + const [loadError, setLoadError] = useState(null); + + // Current step + const currentStep = + navigationStack[navigationStack.length - 1] || + HOOKS_MANAGEMENT_STEPS.HOOKS_LIST; + + // Selected hook event + const selectedHook = useMemo(() => { + if (selectedHookIndex >= 0 && selectedHookIndex < hooks.length) { + return hooks[selectedHookIndex]; + } + return null; + }, [hooks, selectedHookIndex]); + + // Centralized keyboard handler + useKeypress( + (key) => { + if (isLoading || loadError) { + // Allow Escape to close even during loading/error states + if (key.name === 'escape') { + onClose(); + } + return; + } + + switch (currentStep) { + case HOOKS_MANAGEMENT_STEPS.HOOKS_LIST: + if (key.name === 'up') { + setListSelectedIndex((prev) => Math.max(0, prev - 1)); + } else if (key.name === 'down') { + setListSelectedIndex((prev) => + Math.min(hooks.length - 1, prev + 1), + ); + } else if (key.name === 'return') { + if (hooks.length > 0 && listSelectedIndex >= 0) { + setSelectedHookIndex(listSelectedIndex); + setSelectedConfigIndex(-1); + setDetailSelectedIndex(0); + setNavigationStack((prev) => [ + ...prev, + HOOKS_MANAGEMENT_STEPS.HOOK_DETAIL, + ]); + } + } else if (key.name === 'escape') { + onClose(); + } + break; + + case HOOKS_MANAGEMENT_STEPS.HOOK_DETAIL: + if (key.name === 'escape') { + handleNavigateBack(); + } else if (selectedHook && selectedHook.configs.length > 0) { + if (key.name === 'up') { + setDetailSelectedIndex((prev) => Math.max(0, prev - 1)); + } else if (key.name === 'down') { + setDetailSelectedIndex((prev) => + Math.min(selectedHook.configs.length - 1, prev + 1), + ); + } else if (key.name === 'return') { + setSelectedConfigIndex(detailSelectedIndex); + setNavigationStack((prev) => [ + ...prev, + HOOKS_MANAGEMENT_STEPS.HOOK_CONFIG_DETAIL, + ]); + } + } + break; + + case HOOKS_MANAGEMENT_STEPS.HOOK_CONFIG_DETAIL: + if (key.name === 'escape') { + handleNavigateBack(); + } + break; + + default: + // No action for unknown steps + break; + } + }, + { isActive: true }, + ); + + // Load hooks data + const fetchHooksData = useCallback((): HookEventDisplayInfo[] => { + if (!config) return []; + + const settings = loadSettings(); + const userSettings = settings.forScope(SettingScope.User).settings; + const workspaceSettings = settings.forScope( + SettingScope.Workspace, + ).settings; + + // Get translated source display map + const sourceDisplayMap = getTranslatedSourceDisplayMap(); + + const result: HookEventDisplayInfo[] = []; + + for (const eventName of DISPLAY_HOOK_EVENTS) { + const hookInfo = createEmptyHookEventInfo(eventName); + + // Get hooks from user settings (with type validation) + const userSettingsRecord = userSettings as Record; + const userHooksRaw = userSettingsRecord?.['hooks']; + if (isValidHooksRecord(userHooksRaw) && userHooksRaw[eventName]) { + for (const def of userHooksRaw[eventName]) { + for (const hookConfig of def.hooks) { + hookInfo.configs.push({ + config: hookConfig, + source: HooksConfigSource.User, + sourceDisplay: sourceDisplayMap[HooksConfigSource.User], + enabled: true, + }); + } + } + } + + // Get hooks from workspace settings (with type validation) + const workspaceSettingsRecord = workspaceSettings as Record< + string, + unknown + >; + const workspaceHooksRaw = workspaceSettingsRecord?.['hooks']; + if ( + isValidHooksRecord(workspaceHooksRaw) && + workspaceHooksRaw[eventName] + ) { + for (const def of workspaceHooksRaw[eventName]) { + for (const hookConfig of def.hooks) { + hookInfo.configs.push({ + config: hookConfig, + source: HooksConfigSource.Project, + sourceDisplay: sourceDisplayMap[HooksConfigSource.Project], + enabled: true, + }); + } + } + } + + // Get hooks from extensions (with type validation) + const extensions = config.getExtensions() || []; + for (const extension of extensions) { + if (extension.isActive && extension.hooks?.[eventName]) { + const extensionHooks = extension.hooks[eventName]; + if (Array.isArray(extensionHooks)) { + for (const def of extensionHooks) { + if (isValidHookDefinition(def)) { + for (const hookConfig of def.hooks) { + hookInfo.configs.push({ + config: hookConfig, + source: HooksConfigSource.Extensions, + sourceDisplay: extension.name, + sourcePath: extension.path, + enabled: true, + }); + } + } + } + } + } + } + + result.push(hookInfo); + } + + return result; + }, [config]); + + // Load hooks data on initial render + useEffect(() => { + let cancelled = false; + setIsLoading(true); + setLoadError(null); + try { + const hooksData = fetchHooksData(); + if (!cancelled) { + setHooks(hooksData); + } + } catch (error) { + if (!cancelled) { + debugLogger.error('Error loading hooks:', error); + setLoadError( + error instanceof Error ? error.message : 'Failed to load hooks', + ); + } + } finally { + if (!cancelled) { + setIsLoading(false); + } + } + return () => { + cancelled = true; + }; + }, [fetchHooksData]); + + // Navigation handler for going back + const handleNavigateBack = useCallback(() => { + setNavigationStack((prev) => { + if (prev.length <= 1) { + onClose(); + return prev; + } + return prev.slice(0, -1); + }); + }, [onClose]); + + // Selected hook config + const selectedConfig = useMemo(() => { + if ( + selectedHook && + selectedConfigIndex >= 0 && + selectedConfigIndex < selectedHook.configs.length + ) { + return selectedHook.configs[selectedConfigIndex]; + } + return null; + }, [selectedHook, selectedConfigIndex]); + + // Render based on current step + const renderContent = () => { + if (isLoading) { + return ( + + {t('Loading hooks...')} + + ); + } + + if (loadError) { + return ( + + {t('Error loading hooks:')} + {loadError} + + + {t('Press Escape to close')} + + + + ); + } + + switch (currentStep) { + case HOOKS_MANAGEMENT_STEPS.HOOKS_LIST: + return ( + + ); + + case HOOKS_MANAGEMENT_STEPS.HOOK_DETAIL: + if (selectedHook) { + return ( + + ); + } + return ( + + {t('No hook selected')} + + ); + + case HOOKS_MANAGEMENT_STEPS.HOOK_CONFIG_DETAIL: + if (selectedHook && selectedConfig) { + return ( + + ); + } + return ( + + + {t('No hook config selected')} + + + ); + + default: + return null; + } + }; + + return ( + + {renderContent()} + + ); +} diff --git a/packages/cli/src/ui/components/hooks/constants.test.ts b/packages/cli/src/ui/components/hooks/constants.test.ts new file mode 100644 index 000000000..e9bbc705a --- /dev/null +++ b/packages/cli/src/ui/components/hooks/constants.test.ts @@ -0,0 +1,219 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { HookEventName, HooksConfigSource } from '@qwen-code/qwen-code-core'; + +// Mock i18n module +vi.mock('../../../i18n/index.js', () => ({ + t: vi.fn((key: string) => key), +})); + +// Import after mocking +import { + getHookExitCodes, + getHookShortDescription, + getHookDescription, + getTranslatedSourceDisplayMap, + createEmptyHookEventInfo, + DISPLAY_HOOK_EVENTS, +} from './constants.js'; + +describe('hooks constants', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe('getHookExitCodes', () => { + it('should return exit codes for Stop event', () => { + const exitCodes = getHookExitCodes(HookEventName.Stop); + expect(exitCodes).toHaveLength(3); + expect(exitCodes[0]).toEqual({ + code: 0, + description: expect.any(String), + }); + expect(exitCodes[1]).toEqual({ + code: 2, + description: expect.any(String), + }); + expect(exitCodes[2]).toEqual({ + code: 'Other', + description: expect.any(String), + }); + }); + + it('should return exit codes for PreToolUse event', () => { + const exitCodes = getHookExitCodes(HookEventName.PreToolUse); + expect(exitCodes).toHaveLength(3); + expect(exitCodes[0].code).toBe(0); + expect(exitCodes[1].code).toBe(2); + expect(exitCodes[2].code).toBe('Other'); + }); + + it('should return exit codes for PostToolUse event', () => { + const exitCodes = getHookExitCodes(HookEventName.PostToolUse); + expect(exitCodes).toHaveLength(3); + }); + + it('should return exit codes for UserPromptSubmit event', () => { + const exitCodes = getHookExitCodes(HookEventName.UserPromptSubmit); + expect(exitCodes).toHaveLength(3); + }); + + it('should return exit codes for Notification event', () => { + const exitCodes = getHookExitCodes(HookEventName.Notification); + expect(exitCodes).toHaveLength(2); + }); + + it('should return exit codes for SessionStart event', () => { + const exitCodes = getHookExitCodes(HookEventName.SessionStart); + expect(exitCodes).toHaveLength(2); + }); + + it('should return exit codes for SessionEnd event', () => { + const exitCodes = getHookExitCodes(HookEventName.SessionEnd); + expect(exitCodes).toHaveLength(2); + }); + + it('should return exit codes for PreCompact event', () => { + const exitCodes = getHookExitCodes(HookEventName.PreCompact); + expect(exitCodes).toHaveLength(3); + }); + + it('should return empty array for unknown event', () => { + const exitCodes = getHookExitCodes('unknown_event' as HookEventName); + expect(exitCodes).toEqual([]); + }); + }); + + describe('getHookShortDescription', () => { + it('should return description for PreToolUse', () => { + const desc = getHookShortDescription(HookEventName.PreToolUse); + expect(desc).toBe('Before tool execution'); + }); + + it('should return description for PostToolUse', () => { + const desc = getHookShortDescription(HookEventName.PostToolUse); + expect(desc).toBe('After tool execution'); + }); + + it('should return description for UserPromptSubmit', () => { + const desc = getHookShortDescription(HookEventName.UserPromptSubmit); + expect(desc).toBe('When the user submits a prompt'); + }); + + it('should return description for SessionStart', () => { + const desc = getHookShortDescription(HookEventName.SessionStart); + expect(desc).toBe('When a new session is started'); + }); + + it('should return empty string for unknown event', () => { + const desc = getHookShortDescription('unknown_event' as HookEventName); + expect(desc).toBe(''); + }); + }); + + describe('getHookDescription', () => { + it('should return description for PreToolUse', () => { + const desc = getHookDescription(HookEventName.PreToolUse); + expect(desc).toBe('Input to command is JSON of tool call arguments.'); + }); + + it('should return description for PostToolUse', () => { + const desc = getHookDescription(HookEventName.PostToolUse); + expect(desc).toContain('inputs'); + expect(desc).toContain('response'); + }); + + it('should return empty string for Stop event', () => { + const desc = getHookDescription(HookEventName.Stop); + expect(desc).toBe(''); + }); + + it('should return empty string for unknown event', () => { + const desc = getHookDescription('unknown_event' as HookEventName); + expect(desc).toBe(''); + }); + }); + + describe('getTranslatedSourceDisplayMap', () => { + it('should return mapping for all sources', () => { + const map = getTranslatedSourceDisplayMap(); + + expect(map[HooksConfigSource.Project]).toBe('Local Settings'); + expect(map[HooksConfigSource.User]).toBe('User Settings'); + expect(map[HooksConfigSource.System]).toBe('System Settings'); + expect(map[HooksConfigSource.Extensions]).toBe('Extensions'); + }); + + it('should return translated strings', () => { + const map = getTranslatedSourceDisplayMap(); + + // All values should be strings (translated) + Object.values(map).forEach((value) => { + expect(typeof value).toBe('string'); + expect(value.length).toBeGreaterThan(0); + }); + }); + }); + + describe('DISPLAY_HOOK_EVENTS', () => { + it('should contain all expected hook events', () => { + expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.Stop); + expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.PreToolUse); + expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.PostToolUse); + expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.PostToolUseFailure); + expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.Notification); + expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.UserPromptSubmit); + expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.SessionStart); + expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.SessionEnd); + expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.SubagentStart); + expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.SubagentStop); + expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.PreCompact); + expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.PermissionRequest); + }); + + it('should have 12 events', () => { + expect(DISPLAY_HOOK_EVENTS).toHaveLength(12); + }); + }); + + describe('createEmptyHookEventInfo', () => { + it('should create empty info for PreToolUse', () => { + const info = createEmptyHookEventInfo(HookEventName.PreToolUse); + + expect(info.event).toBe(HookEventName.PreToolUse); + expect(info.shortDescription).toBe('Before tool execution'); + expect(info.description).toBe( + 'Input to command is JSON of tool call arguments.', + ); + expect(info.exitCodes).toHaveLength(3); + expect(info.configs).toEqual([]); + }); + + it('should create empty info for Stop', () => { + const info = createEmptyHookEventInfo(HookEventName.Stop); + + expect(info.event).toBe(HookEventName.Stop); + expect(info.shortDescription).toBe( + 'Right before Qwen Code concludes its response', + ); + expect(info.description).toBe(''); + expect(info.exitCodes).toHaveLength(3); + expect(info.configs).toEqual([]); + }); + + it('should create empty info for unknown event', () => { + const info = createEmptyHookEventInfo('unknown_event' as HookEventName); + + expect(info.event).toBe('unknown_event'); + expect(info.shortDescription).toBe(''); + expect(info.description).toBe(''); + expect(info.exitCodes).toEqual([]); + expect(info.configs).toEqual([]); + }); + }); +}); diff --git a/packages/cli/src/ui/components/hooks/constants.ts b/packages/cli/src/ui/components/hooks/constants.ts new file mode 100644 index 000000000..e18bf569a --- /dev/null +++ b/packages/cli/src/ui/components/hooks/constants.ts @@ -0,0 +1,217 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { HooksConfigSource, HookEventName } from '@qwen-code/qwen-code-core'; +import type { HookExitCode, HookEventDisplayInfo } from './types.js'; +import { t } from '../../../i18n/index.js'; + +/** + * Exit code descriptions for different hook types + */ +export function getHookExitCodes(eventName: string): HookExitCode[] { + const exitCodesMap: Record = { + [HookEventName.Stop]: [ + { code: 0, description: t('stdout/stderr not shown') }, + { + code: 2, + description: t('show stderr to model and continue conversation'), + }, + { code: 'Other', description: t('show stderr to user only') }, + ], + [HookEventName.PreToolUse]: [ + { code: 0, description: t('stdout/stderr not shown') }, + { code: 2, description: t('show stderr to model and block tool call') }, + { + code: 'Other', + description: t('show stderr to user only but continue with tool call'), + }, + ], + [HookEventName.PostToolUse]: [ + { code: 0, description: t('stdout shown in transcript mode (ctrl+o)') }, + { code: 2, description: t('show stderr to model immediately') }, + { code: 'Other', description: t('show stderr to user only') }, + ], + [HookEventName.PostToolUseFailure]: [ + { code: 0, description: t('stdout shown in transcript mode (ctrl+o)') }, + { code: 2, description: t('show stderr to model immediately') }, + { code: 'Other', description: t('show stderr to user only') }, + ], + [HookEventName.Notification]: [ + { code: 0, description: t('stdout/stderr not shown') }, + { code: 'Other', description: t('show stderr to user only') }, + ], + [HookEventName.UserPromptSubmit]: [ + { code: 0, description: t('stdout shown to Qwen') }, + { + code: 2, + description: t( + 'block processing, erase original prompt, and show stderr to user only', + ), + }, + { code: 'Other', description: t('show stderr to user only') }, + ], + [HookEventName.SessionStart]: [ + { code: 0, description: t('stdout shown to Qwen') }, + { + code: 'Other', + description: t('show stderr to user only (blocking errors ignored)'), + }, + ], + [HookEventName.SessionEnd]: [ + { code: 0, description: t('command completes successfully') }, + { code: 'Other', description: t('show stderr to user only') }, + ], + [HookEventName.SubagentStart]: [ + { code: 0, description: t('stdout shown to subagent') }, + { + code: 'Other', + description: t('show stderr to user only (blocking errors ignored)'), + }, + ], + [HookEventName.SubagentStop]: [ + { code: 0, description: t('stdout/stderr not shown') }, + { + code: 2, + description: t('show stderr to subagent and continue having it run'), + }, + { code: 'Other', description: t('show stderr to user only') }, + ], + [HookEventName.PreCompact]: [ + { + code: 0, + description: t('stdout appended as custom compact instructions'), + }, + { code: 2, description: t('block compaction') }, + { + code: 'Other', + description: t('show stderr to user only but continue with compaction'), + }, + ], + [HookEventName.PermissionRequest]: [ + { code: 0, description: t('use hook decision if provided') }, + { code: 'Other', description: t('show stderr to user only') }, + ], + }; + return exitCodesMap[eventName] || []; +} + +/** + * Short one-line description for hooks list view + */ +export function getHookShortDescription(eventName: string): string { + const descriptions: Record = { + [HookEventName.PreToolUse]: t('Before tool execution'), + [HookEventName.PostToolUse]: t('After tool execution'), + [HookEventName.PostToolUseFailure]: t('After tool execution fails'), + [HookEventName.Notification]: t('When notifications are sent'), + [HookEventName.UserPromptSubmit]: t('When the user submits a prompt'), + [HookEventName.SessionStart]: t('When a new session is started'), + [HookEventName.Stop]: t('Right before Qwen Code concludes its response'), + [HookEventName.SubagentStart]: t( + 'When a subagent (Agent tool call) is started', + ), + [HookEventName.SubagentStop]: t( + 'Right before a subagent concludes its response', + ), + [HookEventName.PreCompact]: t('Before conversation compaction'), + [HookEventName.SessionEnd]: t('When a session is ending'), + [HookEventName.PermissionRequest]: t( + 'When a permission dialog is displayed', + ), + }; + return descriptions[eventName] || ''; +} + +/** + * Detailed description for each hook event type (shown in detail view) + */ +export function getHookDescription(eventName: string): string { + const descriptions: Record = { + [HookEventName.Stop]: '', + [HookEventName.PreToolUse]: t( + 'Input to command is JSON of tool call arguments.', + ), + [HookEventName.PostToolUse]: t( + 'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).', + ), + [HookEventName.PostToolUseFailure]: t( + 'Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.', + ), + [HookEventName.Notification]: t( + 'Input to command is JSON with notification message and type.', + ), + [HookEventName.UserPromptSubmit]: t( + 'Input to command is JSON with original user prompt text.', + ), + [HookEventName.SessionStart]: t( + 'Input to command is JSON with session start source.', + ), + [HookEventName.SessionEnd]: t( + 'Input to command is JSON with session end reason.', + ), + [HookEventName.SubagentStart]: t( + 'Input to command is JSON with agent_id and agent_type.', + ), + [HookEventName.SubagentStop]: t( + 'Input to command is JSON with agent_id, agent_type, and agent_transcript_path.', + ), + [HookEventName.PreCompact]: t( + 'Input to command is JSON with compaction details.', + ), + [HookEventName.PermissionRequest]: t( + 'Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.', + ), + }; + return descriptions[eventName] || ''; +} + +/** + * Source display mapping (translated) + */ +export function getTranslatedSourceDisplayMap(): Record< + HooksConfigSource, + string +> { + return { + [HooksConfigSource.Project]: t('Local Settings'), + [HooksConfigSource.User]: t('User Settings'), + [HooksConfigSource.System]: t('System Settings'), + [HooksConfigSource.Extensions]: t('Extensions'), + }; +} + +/** + * List of hook events to display in the UI + */ +export const DISPLAY_HOOK_EVENTS: HookEventName[] = [ + HookEventName.Stop, + HookEventName.PreToolUse, + HookEventName.PostToolUse, + HookEventName.PostToolUseFailure, + HookEventName.Notification, + HookEventName.UserPromptSubmit, + HookEventName.SessionStart, + HookEventName.SessionEnd, + HookEventName.SubagentStart, + HookEventName.SubagentStop, + HookEventName.PreCompact, + HookEventName.PermissionRequest, +]; + +/** + * Create empty hook event display info + */ +export function createEmptyHookEventInfo( + eventName: HookEventName, +): HookEventDisplayInfo { + return { + event: eventName, + shortDescription: getHookShortDescription(eventName), + description: getHookDescription(eventName), + exitCodes: getHookExitCodes(eventName), + configs: [], + }; +} diff --git a/packages/cli/src/ui/components/hooks/index.ts b/packages/cli/src/ui/components/hooks/index.ts new file mode 100644 index 000000000..d2bcdb933 --- /dev/null +++ b/packages/cli/src/ui/components/hooks/index.ts @@ -0,0 +1,11 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +export { HooksManagementDialog } from './HooksManagementDialog.js'; +export { HooksListStep } from './HooksListStep.js'; +export { HookDetailStep } from './HookDetailStep.js'; +export * from './types.js'; +export * from './constants.js'; diff --git a/packages/cli/src/ui/components/hooks/types.ts b/packages/cli/src/ui/components/hooks/types.ts new file mode 100644 index 000000000..c4d3d92ee --- /dev/null +++ b/packages/cli/src/ui/components/hooks/types.ts @@ -0,0 +1,60 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import type { + HookConfig, + HooksConfigSource, + HookEventName, +} from '@qwen-code/qwen-code-core'; + +/** + * Exit code description for hooks + */ +export interface HookExitCode { + code: number | string; + description: string; +} + +/** + * UI display information for a hook event + */ +export interface HookEventDisplayInfo { + event: HookEventName; + shortDescription: string; + description: string; + exitCodes: HookExitCode[]; + configs: HookConfigDisplayInfo[]; +} + +/** + * UI display information for a hook configuration + */ +export interface HookConfigDisplayInfo { + config: HookConfig; + source: HooksConfigSource; + sourceDisplay: string; + sourcePath?: string; + enabled: boolean; +} + +/** + * Hook management dialog step names + */ +export const HOOKS_MANAGEMENT_STEPS = { + HOOKS_LIST: 'hooks_list', + HOOK_DETAIL: 'hook_detail', + HOOK_CONFIG_DETAIL: 'hook_config_detail', +} as const; + +export type HooksManagementStep = + (typeof HOOKS_MANAGEMENT_STEPS)[keyof typeof HOOKS_MANAGEMENT_STEPS]; + +/** + * Props for HooksManagementDialog + */ +export interface HooksManagementDialogProps { + onClose: () => void; +} diff --git a/packages/cli/src/ui/components/messages/BtwMessage.test.tsx b/packages/cli/src/ui/components/messages/BtwMessage.test.tsx new file mode 100644 index 000000000..da784dc0d --- /dev/null +++ b/packages/cli/src/ui/components/messages/BtwMessage.test.tsx @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2025 Qwen Code + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, expect, it } from 'vitest'; +import { render } from 'ink-testing-library'; +import { BtwMessage } from './BtwMessage.js'; + +describe('BtwMessage', () => { + it('is wrapped in React.memo to avoid unnecessary layout rerenders', () => { + expect((BtwMessage as unknown as { $$typeof?: symbol }).$$typeof).toBe( + Symbol.for('react.memo'), + ); + }); + + it('renders the side question and answer', () => { + const { lastFrame } = render( + , + ); + + const output = lastFrame() ?? ''; + expect(output).toContain('/btw'); + expect(output).toContain('side question'); + expect(output).toContain('side answer'); + }); +}); diff --git a/packages/cli/src/ui/components/messages/BtwMessage.tsx b/packages/cli/src/ui/components/messages/BtwMessage.tsx new file mode 100644 index 000000000..9b28ecc49 --- /dev/null +++ b/packages/cli/src/ui/components/messages/BtwMessage.tsx @@ -0,0 +1,54 @@ +/** + * @license + * Copyright 2025 Qwen Code + * SPDX-License-Identifier: Apache-2.0 + */ + +import React from 'react'; +import { Box, Text } from 'ink'; +import type { BtwProps } from '../../types.js'; +import { Colors } from '../../colors.js'; +import { t } from '../../../i18n/index.js'; + +export interface BtwDisplayProps { + btw: BtwProps; +} + +const BtwMessageInternal: React.FC = ({ btw }) => ( + + + + {'/btw '} + + + {btw.question} + + + {btw.isPending ? ( + + + {'+ '} + {t('Answering...')} + + + {t('Press Escape to cancel')} + + + ) : ( + + {btw.answer} + + {t('Press Space, Enter, or Escape to dismiss')} + + + )} + +); + +export const BtwMessage = React.memo(BtwMessageInternal); diff --git a/packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx b/packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx index 3946b0b05..cc70a8809 100644 --- a/packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx +++ b/packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx @@ -17,7 +17,11 @@ import type { Config, EditorType, } from '@qwen-code/qwen-code-core'; -import { IdeClient, ToolConfirmationOutcome } from '@qwen-code/qwen-code-core'; +import { + IdeClient, + ToolConfirmationOutcome, + buildHumanReadableRuleLabel, +} from '@qwen-code/qwen-code-core'; import type { RadioSelectItem } from '../shared/RadioButtonSelect.js'; import { RadioButtonSelect } from '../shared/RadioButtonSelect.js'; import { MaxSizedBox } from '../shared/MaxSizedBox.js'; @@ -74,6 +78,12 @@ export const ToolConfirmationMessage: React.FC< }, [config]); const handleConfirm = async (outcome: ToolConfirmationOutcome) => { + // Call onConfirm before resolving the IDE diff so that the CLI outcome + // (e.g. ProceedAlways) is processed first. resolveDiffFromCli would + // otherwise trigger the scheduler's ideConfirmation .then() handler + // with ProceedOnce, racing with the intended CLI outcome. + onConfirm(outcome); + if (confirmationDetails.type === 'edit') { if (config.getIdeMode() && isDiffingEnabled) { const cliOutcome = @@ -84,7 +94,6 @@ export const ToolConfirmationMessage: React.FC< ); } } - onConfirm(outcome); }; const isTrustedFolder = config.isTrustedFolder(); @@ -243,16 +252,24 @@ export const ToolConfirmationMessage: React.FC< key: 'Yes, allow once', }); if (isTrustedFolder && !confirmationDetails.hideAlwaysAllow) { - const rulesLabel = executionProps.permissionRules?.length - ? ` [${executionProps.permissionRules.join(', ')}]` + const friendlyLabel = executionProps.permissionRules?.length + ? ` ${buildHumanReadableRuleLabel(executionProps.permissionRules)}` : ''; options.push({ - label: t('Always allow in this project') + rulesLabel, + label: friendlyLabel + ? t('Always allow {{action}} in this project', { + action: friendlyLabel.trim(), + }) + : t('Always allow in this project'), value: ToolConfirmationOutcome.ProceedAlwaysProject, key: 'Always allow in this project', }); options.push({ - label: t('Always allow for this user') + rulesLabel, + label: friendlyLabel + ? t('Always allow {{action}} for this user', { + action: friendlyLabel.trim(), + }) + : t('Always allow for this user'), value: ToolConfirmationOutcome.ProceedAlwaysUser, key: 'Always allow for this user', }); @@ -324,18 +341,26 @@ export const ToolConfirmationMessage: React.FC< key: 'Yes, allow once', }); if (isTrustedFolder && !confirmationDetails.hideAlwaysAllow) { - const rulesLabel = + const friendlyLabel = 'permissionRules' in infoProps && (infoProps as { permissionRules?: string[] }).permissionRules?.length - ? ` [${(infoProps as { permissionRules?: string[] }).permissionRules!.join(', ')}]` + ? ` ${buildHumanReadableRuleLabel((infoProps as { permissionRules?: string[] }).permissionRules!)}` : ''; options.push({ - label: t('Always allow in this project') + rulesLabel, + label: friendlyLabel + ? t('Always allow {{action}} in this project', { + action: friendlyLabel.trim(), + }) + : t('Always allow in this project'), value: ToolConfirmationOutcome.ProceedAlwaysProject, key: 'Always allow in this project', }); options.push({ - label: t('Always allow for this user') + rulesLabel, + label: friendlyLabel + ? t('Always allow {{action}} for this user', { + action: friendlyLabel.trim(), + }) + : t('Always allow for this user'), value: ToolConfirmationOutcome.ProceedAlwaysUser, key: 'Always allow for this user', }); @@ -401,16 +426,24 @@ export const ToolConfirmationMessage: React.FC< key: 'Yes, allow once', }); if (isTrustedFolder && !confirmationDetails.hideAlwaysAllow) { - const rulesLabel = mcpProps.permissionRules?.length - ? ` [${mcpProps.permissionRules.join(', ')}]` + const friendlyLabel = mcpProps.permissionRules?.length + ? ` ${buildHumanReadableRuleLabel(mcpProps.permissionRules)}` : ''; options.push({ - label: t('Always allow in this project') + rulesLabel, + label: friendlyLabel + ? t('Always allow {{action}} in this project', { + action: friendlyLabel.trim(), + }) + : t('Always allow in this project'), value: ToolConfirmationOutcome.ProceedAlwaysProject, key: 'Always allow in this project', }); options.push({ - label: t('Always allow for this user') + rulesLabel, + label: friendlyLabel + ? t('Always allow {{action}} for this user', { + action: friendlyLabel.trim(), + }) + : t('Always allow for this user'), value: ToolConfirmationOutcome.ProceedAlwaysUser, key: 'Always allow for this user', }); diff --git a/packages/cli/src/ui/contexts/KeypressContext.tsx b/packages/cli/src/ui/contexts/KeypressContext.tsx index 78207673c..142a0c63c 100644 --- a/packages/cli/src/ui/contexts/KeypressContext.tsx +++ b/packages/cli/src/ui/contexts/KeypressContext.tsx @@ -577,7 +577,16 @@ export function KeypressProvider({ } }; + // Matches terminal query responses (DA1, DA2, Kitty protocol query) + // that may arrive late from startup detection in kittyProtocolDetector. + // These are never valid user input. + // eslint-disable-next-line no-control-regex + const TERMINAL_RESPONSE_RE = /^\x1b\[[?>][\d;]*[uc]$/; + const handleKeypress = async (_: unknown, key: Key) => { + if (TERMINAL_RESPONSE_RE.test(key.sequence)) { + return; + } if (key.sequence === FOCUS_IN || key.sequence === FOCUS_OUT) { return; } diff --git a/packages/cli/src/ui/contexts/UIActionsContext.tsx b/packages/cli/src/ui/contexts/UIActionsContext.tsx index 8604e6744..e1a1010b9 100644 --- a/packages/cli/src/ui/contexts/UIActionsContext.tsx +++ b/packages/cli/src/ui/contexts/UIActionsContext.tsx @@ -16,6 +16,7 @@ import { } from '@qwen-code/qwen-code-core'; import { type SettingScope } from '../../config/settings.js'; import { type CodingPlanRegion } from '../../constants/codingPlan.js'; +import { type AlibabaStandardRegion } from '../../constants/alibabaStandardApiKey.js'; import type { AuthState } from '../types.js'; import { type ArenaDialogType } from '../hooks/useArenaCommand.js'; // OpenAICredentials type (previously imported from OpenAIKeyPrompt) @@ -45,6 +46,11 @@ export interface UIActions { apiKey: string, region?: CodingPlanRegion, ) => Promise; + handleAlibabaStandardSubmit: ( + apiKey: string, + region: AlibabaStandardRegion, + modelIdsInput: string, + ) => Promise; setAuthState: (state: AuthState) => void; onAuthError: (error: string | null) => void; cancelAuthentication: () => void; @@ -83,6 +89,10 @@ export interface UIActions { closeExtensionsManagerDialog: () => void; // MCP dialog closeMcpDialog: () => void; + // Hooks dialog + openHooksDialog: () => void; + // Hooks dialog + closeHooksDialog: () => void; // Resume session dialog openResumeDialog: () => void; closeResumeDialog: () => void; diff --git a/packages/cli/src/ui/contexts/UIStateContext.tsx b/packages/cli/src/ui/contexts/UIStateContext.tsx index 986b07899..9c8446368 100644 --- a/packages/cli/src/ui/contexts/UIStateContext.tsx +++ b/packages/cli/src/ui/contexts/UIStateContext.tsx @@ -7,6 +7,7 @@ import { createContext, useContext } from 'react'; import type { HistoryItem, + HistoryItemBtw, ThoughtSummary, ShellConfirmationRequest, ConfirmationRequest, @@ -104,6 +105,9 @@ export interface UIState { staticExtraHeight: number; dialogsVisible: boolean; pendingHistoryItems: HistoryItemWithoutId[]; + btwItem: HistoryItemBtw | null; + setBtwItem: (item: HistoryItemBtw | null) => void; + cancelBtw: () => void; nightly: boolean; branchName: string | undefined; sessionStats: SessionStatsState; @@ -132,6 +136,8 @@ export interface UIState { isExtensionsManagerDialogOpen: boolean; // MCP dialog isMcpDialogOpen: boolean; + // Hooks dialog + isHooksDialogOpen: boolean; // Feedback dialog isFeedbackDialogOpen: boolean; // Per-task token tracking diff --git a/packages/cli/src/ui/hooks/slashCommandProcessor.ts b/packages/cli/src/ui/hooks/slashCommandProcessor.ts index d799a402d..c0c3fac07 100644 --- a/packages/cli/src/ui/hooks/slashCommandProcessor.ts +++ b/packages/cli/src/ui/hooks/slashCommandProcessor.ts @@ -23,6 +23,7 @@ import { useSessionStats } from '../contexts/SessionContext.js'; import type { Message, HistoryItemWithoutId, + HistoryItemBtw, SlashCommandProcessorResult, HistoryItem, ConfirmationRequest, @@ -36,6 +37,7 @@ import { BundledSkillLoader } from '../../services/BundledSkillLoader.js'; import { FileCommandLoader } from '../../services/FileCommandLoader.js'; import { McpPromptLoader } from '../../services/McpPromptLoader.js'; import { parseSlashCommand } from '../../utils/commands.js'; +import { isBtwCommand } from '../utils/commandUtils.js'; import { clearScreen } from '../../utils/stdioHelpers.js'; import { useKeypress } from './useKeypress.js'; import { @@ -63,6 +65,7 @@ const SLASH_COMMANDS_SKIP_RECORDING = new Set([ 'reset', 'new', 'resume', + 'btw', ]); interface SlashCommandProcessorActions { @@ -84,6 +87,7 @@ interface SlashCommandProcessorActions { openAgentsManagerDialog: () => void; openExtensionsManagerDialog: () => void; openMcpDialog: () => void; + openHooksDialog: () => void; } /** @@ -139,10 +143,20 @@ export const useSlashCommandProcessor = ( null, ); + const [btwItem, setBtwItem] = useState(null); + const btwAbortControllerRef = useRef(null); + + const cancelBtw = useCallback(() => { + btwAbortControllerRef.current?.abort(); + btwAbortControllerRef.current = null; + setBtwItem(null); + }, []); + // AbortController for cancelling async slash commands via ESC const abortControllerRef = useRef(null); const cancelSlashCommand = useCallback(() => { + cancelBtw(); if (!abortControllerRef.current) { return; } @@ -156,7 +170,7 @@ export const useSlashCommandProcessor = ( ); setPendingItem(null); setIsProcessing(false); - }, [addItem, setIsProcessing]); + }, [addItem, setIsProcessing, cancelBtw]); useKeypress( (key) => { @@ -251,6 +265,10 @@ export const useSlashCommandProcessor = ( setDebugMessage: actions.setDebugMessage, pendingItem, setPendingItem, + btwItem, + setBtwItem, + cancelBtw, + btwAbortControllerRef, toggleVimEnabled, setGeminiMdFileCount, reloadCommands, @@ -279,6 +297,9 @@ export const useSlashCommandProcessor = ( actions, pendingItem, setPendingItem, + btwItem, + setBtwItem, + cancelBtw, toggleVimEnabled, sessionShellAllowlist, setGeminiMdFileCount, @@ -366,10 +387,12 @@ export const useSlashCommandProcessor = ( abortControllerRef.current = abortController; const userMessageTimestamp = Date.now(); - addItemWithRecording( - { type: MessageType.USER, text: trimmed }, - userMessageTimestamp, - ); + if (!isBtwCommand(trimmed)) { + addItemWithRecording( + { type: MessageType.USER, text: trimmed }, + userMessageTimestamp, + ); + } let hasError = false; const { @@ -501,6 +524,9 @@ export const useSlashCommandProcessor = ( case 'mcp': actions.openMcpDialog(); return { type: 'handled' }; + case 'hooks': + actions.openHooksDialog(); + return { type: 'handled' }; case 'approval-mode': actions.openApprovalModeDialog(); return { type: 'handled' }; @@ -727,6 +753,9 @@ export const useSlashCommandProcessor = ( handleSlashCommand, slashCommands: commands, pendingHistoryItems, + btwItem, + setBtwItem, + cancelBtw, commandContext, shellConfirmationRequest, confirmationRequest, diff --git a/packages/cli/src/ui/hooks/useCommandCompletion.test.ts b/packages/cli/src/ui/hooks/useCommandCompletion.test.ts index 659b99db0..fed160343 100644 --- a/packages/cli/src/ui/hooks/useCommandCompletion.test.ts +++ b/packages/cli/src/ui/hooks/useCommandCompletion.test.ts @@ -417,6 +417,95 @@ describe('useCommandCompletion', () => { }); }); + describe('Completion mode detection', () => { + it('should switch to AT mode when typing @ after a slash command (#2518)', async () => { + setupMocks({ + atSuggestions: [{ label: 'src/file.txt', value: 'src/file.txt' }], + }); + + const text = '/qc:create-issue @file'; + renderHook(() => + useCommandCompletion( + useTextBufferForTest(text), + testDirs, + testRootDir, + [], + mockCommandContext, + false, + mockConfig, + ), + ); + + await waitFor(() => { + expect(useAtCompletion).toHaveBeenLastCalledWith( + expect.objectContaining({ + enabled: true, + pattern: 'file', + }), + ); + }); + }); + + it('should remain in SLASH mode when no @ is typed after slash command', async () => { + setupMocks({ + slashSuggestions: [{ label: 'help', value: 'help' }], + }); + + const text = '/help'; + renderHook(() => + useCommandCompletion( + useTextBufferForTest(text), + testDirs, + testRootDir, + [], + mockCommandContext, + false, + mockConfig, + ), + ); + + await waitFor(() => { + expect(useSlashCompletion).toHaveBeenLastCalledWith( + expect.objectContaining({ + enabled: true, + query: '/help', + }), + ); + }); + }); + + it('should complete a file path when @ appears after a slash command', async () => { + setupMocks({ + atSuggestions: [{ label: 'src/index.ts', value: 'src/index.ts' }], + }); + + const text = '/review @src/ind'; + const { result } = renderHook(() => { + const textBuffer = useTextBufferForTest(text); + const completion = useCommandCompletion( + textBuffer, + testDirs, + testRootDir, + [], + mockCommandContext, + false, + mockConfig, + ); + return { ...completion, textBuffer }; + }); + + await waitFor(() => { + expect(result.current.suggestions.length).toBe(1); + }); + + act(() => { + result.current.handleAutocomplete(0); + }); + + expect(result.current.textBuffer.text).toBe('/review @src/index.ts '); + }); + }); + describe('handleAutocomplete', () => { it('should complete a partial command', async () => { setupMocks({ diff --git a/packages/cli/src/ui/hooks/useCommandCompletion.tsx b/packages/cli/src/ui/hooks/useCommandCompletion.tsx index cb5d9f276..c78e9e46e 100644 --- a/packages/cli/src/ui/hooks/useCommandCompletion.tsx +++ b/packages/cli/src/ui/hooks/useCommandCompletion.tsx @@ -74,15 +74,9 @@ export function useCommandCompletion( const { completionMode, query, completionStart, completionEnd } = useMemo(() => { const currentLine = buffer.lines[cursorRow] || ''; - if (cursorRow === 0 && isSlashCommand(currentLine.trim())) { - return { - completionMode: CompletionMode.SLASH, - query: currentLine, - completionStart: 0, - completionEnd: currentLine.length, - }; - } + // Check for @ completion first, so that typing @ after a slash command + // still triggers file search (see #2518). const codePoints = toCodePoints(currentLine); for (let i = cursorCol - 1; i >= 0; i--) { const char = codePoints[i]; @@ -121,6 +115,15 @@ export function useCommandCompletion( } } + if (cursorRow === 0 && isSlashCommand(currentLine.trim())) { + return { + completionMode: CompletionMode.SLASH, + query: currentLine, + completionStart: 0, + completionEnd: currentLine.length, + }; + } + return { completionMode: CompletionMode.IDLE, query: null, diff --git a/packages/cli/src/ui/hooks/useGeminiStream.test.tsx b/packages/cli/src/ui/hooks/useGeminiStream.test.tsx index 4330ba7a5..2234db6bd 100644 --- a/packages/cli/src/ui/hooks/useGeminiStream.test.tsx +++ b/packages/cli/src/ui/hooks/useGeminiStream.test.tsx @@ -834,7 +834,7 @@ describe('useGeminiStream', () => { // Wait for the first part of the response await waitFor(() => { - expect(result.current.streamingState).toBe(StreamingState.Responding); + expect(mockSendMessageStream).toHaveBeenCalledTimes(1); }); // Call cancelOngoingRequest directly @@ -983,7 +983,7 @@ describe('useGeminiStream', () => { }); await waitFor(() => { - expect(result.current.streamingState).toBe(StreamingState.Responding); + expect(mockSendMessageStream).toHaveBeenCalledTimes(1); }); // Cancel the request @@ -2709,6 +2709,109 @@ describe('useGeminiStream', () => { }); describe('Concurrent Execution Prevention', () => { + it('should allow /btw slash commands while a main response is in progress', async () => { + let resolveFirstCall!: () => void; + + const firstCallPromise = new Promise((resolve) => { + resolveFirstCall = resolve; + }); + + const firstStream = (async function* () { + yield { + type: ServerGeminiEventType.Content, + value: 'First call content', + }; + await firstCallPromise; + })(); + + mockSendMessageStream.mockImplementation(() => firstStream); + mockHandleSlashCommand.mockImplementation(async (command) => { + if (command === '/btw quick side question') { + return { type: 'handled' }; + } + return false; + }); + + const { result } = renderTestHook(); + + let mainRequest!: Promise; + await act(async () => { + mainRequest = result.current.submitQuery('First query'); + }); + + try { + await waitFor(() => { + expect(mockSendMessageStream).toHaveBeenCalledTimes(1); + expect(result.current.streamingState).toBe(StreamingState.Responding); + }); + + await act(async () => { + await result.current.submitQuery('/btw quick side question'); + }); + + expect(mockHandleSlashCommand).toHaveBeenCalledWith( + '/btw quick side question', + ); + expect(mockSendMessageStream).toHaveBeenCalledTimes(1); + } finally { + resolveFirstCall(); + await mainRequest; + } + }); + + it('should keep the main request cancellable after submitting /btw in parallel', async () => { + let resolveFirstCall!: () => void; + let mainAbortSignal: AbortSignal | undefined; + + const firstCallPromise = new Promise((resolve) => { + resolveFirstCall = resolve; + }); + + mockSendMessageStream.mockImplementation((_query, signal) => { + mainAbortSignal = signal; + return (async function* () { + yield { + type: ServerGeminiEventType.Content, + value: 'First call content', + }; + await firstCallPromise; + })(); + }); + mockHandleSlashCommand.mockImplementation(async (command) => { + if (command === '/btw quick side question') { + return { type: 'handled' }; + } + return false; + }); + + const { result } = renderTestHook(); + + let mainRequest!: Promise; + await act(async () => { + mainRequest = result.current.submitQuery('First query'); + }); + + try { + await waitFor(() => { + expect(mainAbortSignal).toBeDefined(); + expect(result.current.streamingState).toBe(StreamingState.Responding); + }); + + await act(async () => { + await result.current.submitQuery('/btw quick side question'); + }); + + act(() => { + result.current.cancelOngoingRequest(); + }); + + expect(mainAbortSignal?.aborted).toBe(true); + } finally { + resolveFirstCall(); + await mainRequest; + } + }); + it('should prevent concurrent submitQuery calls', async () => { let resolveFirstCall!: () => void; let resolveSecondCall!: () => void; diff --git a/packages/cli/src/ui/hooks/useGeminiStream.ts b/packages/cli/src/ui/hooks/useGeminiStream.ts index 108b2fe83..5d39654b1 100644 --- a/packages/cli/src/ui/hooks/useGeminiStream.ts +++ b/packages/cli/src/ui/hooks/useGeminiStream.ts @@ -49,7 +49,11 @@ import type { SlashCommandProcessorResult, } from '../types.js'; import { StreamingState, MessageType, ToolCallStatus } from '../types.js'; -import { isAtCommand, isSlashCommand } from '../utils/commandUtils.js'; +import { + isAtCommand, + isBtwCommand, + isSlashCommand, +} from '../utils/commandUtils.js'; import { useShellCommandProcessor } from './shellCommandProcessor.js'; import { handleAtCommand } from './atCommandProcessor.js'; import { findLastSafeSplitPoint } from '../utils/markdownUtilities.js'; @@ -1094,11 +1098,18 @@ export const useGeminiStream = ( submitType: SendMessageType = SendMessageType.UserQuery, prompt_id?: string, ) => { + const allowConcurrentBtwDuringResponse = + submitType === SendMessageType.UserQuery && + streamingState === StreamingState.Responding && + typeof query === 'string' && + isBtwCommand(query); + // Prevent concurrent executions of submitQuery, but allow continuations // which are part of the same logical flow (tool responses) if ( isSubmittingQueryRef.current && - submitType !== SendMessageType.ToolResult + submitType !== SendMessageType.ToolResult && + !allowConcurrentBtwDuringResponse ) { return; } @@ -1106,7 +1117,8 @@ export const useGeminiStream = ( if ( (streamingState === StreamingState.Responding || streamingState === StreamingState.WaitingForConfirmation) && - submitType !== SendMessageType.ToolResult + submitType !== SendMessageType.ToolResult && + !allowConcurrentBtwDuringResponse ) return; @@ -1116,7 +1128,10 @@ export const useGeminiStream = ( const userMessageTimestamp = Date.now(); // Reset quota error flag when starting a new query (not a continuation) - if (submitType !== SendMessageType.ToolResult) { + if ( + submitType !== SendMessageType.ToolResult && + !allowConcurrentBtwDuringResponse + ) { setModelSwitchedFromQuotaError(false); // Commit any pending retry error to history (without hint) since the // user is starting a new conversation turn. @@ -1130,9 +1145,15 @@ export const useGeminiStream = ( } } - abortControllerRef.current = new AbortController(); - const abortSignal = abortControllerRef.current.signal; - turnCancelledRef.current = false; + const abortController = new AbortController(); + const abortSignal = abortController.signal; + + // Keep the main stream's cancellation state intact while /btw is handled + // in parallel. The side-question can use its own local abort signal. + if (!allowConcurrentBtwDuringResponse) { + abortControllerRef.current = abortController; + turnCancelledRef.current = false; + } if (!prompt_id) { prompt_id = config.getSessionId() + '########' + getPromptCount(); diff --git a/packages/cli/src/ui/hooks/useHooksDialog.ts b/packages/cli/src/ui/hooks/useHooksDialog.ts new file mode 100644 index 000000000..5f4bcea09 --- /dev/null +++ b/packages/cli/src/ui/hooks/useHooksDialog.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { useState, useCallback } from 'react'; + +export interface UseHooksDialogReturn { + isHooksDialogOpen: boolean; + openHooksDialog: () => void; + closeHooksDialog: () => void; +} + +export const useHooksDialog = (): UseHooksDialogReturn => { + const [isHooksDialogOpen, setIsHooksDialogOpen] = useState(false); + + const openHooksDialog = useCallback(() => { + setIsHooksDialogOpen(true); + }, []); + + const closeHooksDialog = useCallback(() => { + setIsHooksDialogOpen(false); + }, []); + + return { + isHooksDialogOpen, + openHooksDialog, + closeHooksDialog, + }; +}; diff --git a/packages/cli/src/ui/hooks/useResumeCommand.ts b/packages/cli/src/ui/hooks/useResumeCommand.ts index 6a77ffdeb..04edc21ea 100644 --- a/packages/cli/src/ui/hooks/useResumeCommand.ts +++ b/packages/cli/src/ui/hooks/useResumeCommand.ts @@ -9,6 +9,7 @@ import { SessionService, type Config, SessionStartSource, + type PermissionMode, } from '@qwen-code/qwen-code-core'; import { buildResumedHistoryItems } from '../utils/resumeHistoryUtils.js'; import type { UseHistoryManagerReturn } from './useHistoryManager.js'; @@ -78,6 +79,7 @@ export function useResumeCommand( ?.fireSessionStartEvent( SessionStartSource.Resume, config.getModel() ?? '', + String(config.getApprovalMode()) as PermissionMode, ); } catch (err) { config.getDebugLogger().warn(`SessionStart hook failed: ${err}`); diff --git a/packages/cli/src/ui/layouts/DefaultAppLayout.tsx b/packages/cli/src/ui/layouts/DefaultAppLayout.tsx index ddb3f2df0..479730cb4 100644 --- a/packages/cli/src/ui/layouts/DefaultAppLayout.tsx +++ b/packages/cli/src/ui/layouts/DefaultAppLayout.tsx @@ -11,6 +11,7 @@ import { MainContent } from '../components/MainContent.js'; import { DialogManager } from '../components/DialogManager.js'; import { Composer } from '../components/Composer.js'; import { ExitWarning } from '../components/ExitWarning.js'; +import { BtwMessage } from '../components/messages/BtwMessage.js'; import { AgentTabBar } from '../components/agent-view/AgentTabBar.js'; import { AgentChatView } from '../components/agent-view/AgentChatView.js'; import { AgentComposer } from '../components/agent-view/AgentComposer.js'; @@ -66,6 +67,10 @@ export const DefaultAppLayout: React.FC = () => { addItem={uiState.historyManager.addItem} /> + ) : uiState.btwItem ? ( + + + ) : ( )} diff --git a/packages/cli/src/ui/layouts/ScreenReaderAppLayout.tsx b/packages/cli/src/ui/layouts/ScreenReaderAppLayout.tsx index b4967a5f4..f9e876a48 100644 --- a/packages/cli/src/ui/layouts/ScreenReaderAppLayout.tsx +++ b/packages/cli/src/ui/layouts/ScreenReaderAppLayout.tsx @@ -12,6 +12,7 @@ import { DialogManager } from '../components/DialogManager.js'; import { Composer } from '../components/Composer.js'; import { Footer } from '../components/Footer.js'; import { ExitWarning } from '../components/ExitWarning.js'; +import { BtwMessage } from '../components/messages/BtwMessage.js'; import { useUIState } from '../contexts/UIStateContext.js'; export const ScreenReaderAppLayout: React.FC = () => { @@ -24,6 +25,7 @@ export const ScreenReaderAppLayout: React.FC = () => { + {uiState.dialogsVisible ? ( { addItem={uiState.historyManager.addItem} /> + ) : uiState.btwItem ? ( + + + ) : ( )} diff --git a/packages/cli/src/ui/noninteractive/nonInteractiveUi.ts b/packages/cli/src/ui/noninteractive/nonInteractiveUi.ts index 779293330..dbdf4e2e3 100644 --- a/packages/cli/src/ui/noninteractive/nonInteractiveUi.ts +++ b/packages/cli/src/ui/noninteractive/nonInteractiveUi.ts @@ -20,6 +20,10 @@ export function createNonInteractiveUI(): CommandContext['ui'] { loadHistory: (_newHistory) => {}, pendingItem: null, setPendingItem: (_item) => {}, + btwItem: null, + setBtwItem: (_item) => {}, + cancelBtw: () => {}, + btwAbortControllerRef: { current: null }, toggleVimEnabled: async () => false, setGeminiMdFileCount: (_count) => {}, reloadCommands: () => {}, diff --git a/packages/cli/src/ui/types.ts b/packages/cli/src/ui/types.ts index 64353066e..7f9b4c176 100644 --- a/packages/cli/src/ui/types.ts +++ b/packages/cli/src/ui/types.ts @@ -350,6 +350,17 @@ export type HistoryItemInsightProgress = HistoryItemBase & { progress: InsightProgressProps; }; +export interface BtwProps { + question: string; + answer: string; + isPending: boolean; +} + +export type HistoryItemBtw = HistoryItemBase & { + type: 'btw'; + btw: BtwProps; +}; + // Using Omit seems to have some issues with typescript's // type inference e.g. historyItem.type === 'tool_group' isn't auto-inferring that // 'tools' in historyItem. @@ -383,7 +394,8 @@ export type HistoryItemWithoutId = | HistoryItemContextUsage | HistoryItemArenaAgentComplete | HistoryItemArenaSessionComplete - | HistoryItemInsightProgress; + | HistoryItemInsightProgress + | HistoryItemBtw; export type HistoryItem = HistoryItemWithoutId & { id: number }; @@ -411,6 +423,7 @@ export enum MessageType { ARENA_AGENT_COMPLETE = 'arena_agent_complete', ARENA_SESSION_COMPLETE = 'arena_session_complete', INSIGHT_PROGRESS = 'insight_progress', + BTW = 'btw', } export interface InsightProgressProps { diff --git a/packages/cli/src/ui/utils/commandUtils.ts b/packages/cli/src/ui/utils/commandUtils.ts index 802107f6b..9436447f7 100644 --- a/packages/cli/src/ui/utils/commandUtils.ts +++ b/packages/cli/src/ui/utils/commandUtils.ts @@ -62,6 +62,17 @@ export const isSlashCommand = (query: string): boolean => { return true; }; +const BTW_COMMAND_RE = /^[/?]btw(?:\s|$)/; + +/** + * Checks if a query is a /btw side-question invocation. + * Accepts both "/btw" and "?btw" prefixes. + */ +export const isBtwCommand = (query: string): boolean => { + const trimmed = query.trim(); + return trimmed.length > 0 && BTW_COMMAND_RE.test(trimmed); +}; + const debugLogger = createDebugLogger('COMMAND_UTILS'); // Copies a string snippet to the clipboard for different platforms diff --git a/packages/cli/src/ui/utils/kittyProtocolDetector.ts b/packages/cli/src/ui/utils/kittyProtocolDetector.ts index 3355330a6..a46390603 100644 --- a/packages/cli/src/ui/utils/kittyProtocolDetector.ts +++ b/packages/cli/src/ui/utils/kittyProtocolDetector.ts @@ -37,11 +37,20 @@ export async function detectAndEnableKittyProtocol(): Promise { const onTimeout = () => { timeoutId = undefined; process.stdin.removeListener('data', handleData); - if (!originalRawMode) { - process.stdin.setRawMode(false); - } - detectionComplete = true; - resolve(false); + + // Keep a drain handler briefly to consume any late-arriving terminal + // responses that would otherwise leak into the application input. + const drainHandler = () => {}; + process.stdin.on('data', drainHandler); + + setTimeout(() => { + process.stdin.removeListener('data', drainHandler); + if (!originalRawMode) { + process.stdin.setRawMode(false); + } + detectionComplete = true; + resolve(false); + }, 100); }; const handleData = (data: Buffer) => { diff --git a/packages/cli/test-setup.ts b/packages/cli/test-setup.ts index cc0ac0023..c26e57fa5 100644 --- a/packages/cli/test-setup.ts +++ b/packages/cli/test-setup.ts @@ -9,4 +9,10 @@ if (process.env['NO_COLOR'] !== undefined) { delete process.env['NO_COLOR']; } +// Avoid writing per-session debug log files during CLI tests. +// Individual tests can still opt in by overriding this env var explicitly. +if (process.env['QWEN_DEBUG_LOG_FILE'] === undefined) { + process.env['QWEN_DEBUG_LOG_FILE'] = '0'; +} + import './src/test-utils/customMatchers.js'; diff --git a/packages/core/package.json b/packages/core/package.json index cca5ef21c..d42076816 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@qwen-code/qwen-code-core", - "version": "0.13.0", + "version": "0.13.2", "description": "Qwen Code Core", "repository": { "type": "git", diff --git a/packages/core/src/config/config.test.ts b/packages/core/src/config/config.test.ts index 5b1e62fb5..aefe25ea1 100644 --- a/packages/core/src/config/config.test.ts +++ b/packages/core/src/config/config.test.ts @@ -1582,4 +1582,37 @@ describe('Model Switching and Config Updates', () => { const updatedConfig = config.getContentGeneratorConfig(); expect(updatedConfig['contextWindowSize']).toBe(128_000); }); + + describe('hasHooksForEvent', () => { + it('should return false when hookSystem is not initialized', () => { + const config = new Config(baseParams); + expect(config.hasHooksForEvent('Stop')).toBe(false); + }); + + it('should delegate to hookSystem.hasHooksForEvent when hookSystem exists', () => { + const config = new Config(baseParams); + const mockHasHooksForEvent = vi.fn().mockReturnValue(true); + const mockHookSystem = { + hasHooksForEvent: mockHasHooksForEvent, + }; + // @ts-expect-error - accessing private for testing + config['hookSystem'] = mockHookSystem; + + expect(config.hasHooksForEvent('UserPromptSubmit')).toBe(true); + expect(mockHasHooksForEvent).toHaveBeenCalledWith('UserPromptSubmit'); + }); + + it('should return false when hookSystem has no hooks for the event', () => { + const config = new Config(baseParams); + const mockHasHooksForEvent = vi.fn().mockReturnValue(false); + const mockHookSystem = { + hasHooksForEvent: mockHasHooksForEvent, + }; + // @ts-expect-error - accessing private for testing + config['hookSystem'] = mockHookSystem; + + expect(config.hasHooksForEvent('Stop')).toBe(false); + expect(mockHasHooksForEvent).toHaveBeenCalledWith('Stop'); + }); + }); }); diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index 6ffd3ac3b..3589948e9 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -108,6 +108,7 @@ import { shouldDefaultToNodePty } from '../utils/shell-utils.js'; import { WorkspaceContext } from '../utils/workspaceContext.js'; import { type ToolName } from '../utils/tool-utils.js'; import { getErrorMessage } from '../utils/errors.js'; +import { normalizeProxyUrl } from '../utils/proxyUtils.js'; // Local config modules import type { FileFilteringOptions } from './constants.js'; @@ -747,8 +748,9 @@ export class Config { initializeTelemetry(this); } - if (this.getProxy()) { - setGlobalDispatcher(new ProxyAgent(this.getProxy() as string)); + const proxyUrl = this.getProxy(); + if (proxyUrl) { + setGlobalDispatcher(new ProxyAgent(proxyUrl)); } this.geminiClient = new GeminiClient(this); this.chatRecordingService = this.chatRecordingEnabled @@ -810,19 +812,33 @@ export class Config { return; } + // Check if request was aborted + if (request.signal?.aborted) { + this.messageBus?.publish({ + type: MessageBusType.HOOK_EXECUTION_RESPONSE, + correlationId: request.correlationId, + success: false, + error: new Error('Hook execution cancelled (aborted)'), + } as HookExecutionResponse); + return; + } + // Execute the appropriate hook based on eventName let result; const input = request.input || {}; + const signal = request.signal; switch (request.eventName) { case 'UserPromptSubmit': result = await hookSystem.fireUserPromptSubmitEvent( (input['prompt'] as string) || '', + signal, ); break; case 'Stop': result = await hookSystem.fireStopEvent( (input['stop_hook_active'] as boolean) || false, (input['last_assistant_message'] as string) || '', + signal, ); break; case 'PreToolUse': { @@ -832,6 +848,7 @@ export class Config { (input['tool_use_id'] as string) || '', (input['permission_mode'] as PermissionMode | undefined) ?? PermissionMode.Default, + signal, ); break; } @@ -842,6 +859,7 @@ export class Config { (input['tool_response'] as Record) || {}, (input['tool_use_id'] as string) || '', (input['permission_mode'] as PermissionMode) || 'default', + signal, ); break; case 'PostToolUseFailure': @@ -852,6 +870,7 @@ export class Config { (input['error'] as string) || '', input['is_interrupt'] as boolean | undefined, (input['permission_mode'] as PermissionMode) || 'default', + signal, ); break; case 'Notification': @@ -860,6 +879,7 @@ export class Config { (input['notification_type'] as NotificationType) || 'permission_prompt', (input['title'] as string) || undefined, + signal, ); break; case 'PermissionRequest': @@ -871,6 +891,7 @@ export class Config { (input['permission_suggestions'] as | PermissionSuggestion[] | undefined) || undefined, + signal, ); break; case 'SubagentStart': @@ -879,6 +900,7 @@ export class Config { (input['agent_type'] as string) || '', (input['permission_mode'] as PermissionMode) || PermissionMode.Default, + signal, ); break; case 'SubagentStop': @@ -890,6 +912,7 @@ export class Config { (input['stop_hook_active'] as boolean) || false, (input['permission_mode'] as PermissionMode) || PermissionMode.Default, + signal, ); break; default: @@ -1696,7 +1719,7 @@ export class Config { } getProxy(): string | undefined { - return this.proxy; + return normalizeProxyUrl(this.proxy); } getWorkingDir(): string { @@ -1748,6 +1771,15 @@ export class Config { return this.hookSystem; } + /** + * Fast-path check: returns true only when hooks are enabled AND there are + * registered hooks for the given event name. Callers can use this to skip + * expensive MessageBus round-trips when no hooks are configured. + */ + hasHooksForEvent(eventName: string): boolean { + return this.hookSystem?.hasHooksForEvent(eventName) ?? false; + } + /** * Check if hooks are enabled. */ @@ -2090,7 +2122,7 @@ export class Config { // Helper to create & register core tools that are enabled // eslint-disable-next-line @typescript-eslint/no-explicit-any - const registerCoreTool = (ToolClass: any, ...args: unknown[]) => { + const registerCoreTool = async (ToolClass: any, ...args: unknown[]) => { const toolName = ToolClass?.Name as ToolName | undefined; const className = ToolClass?.name ?? 'UnknownTool'; @@ -2106,7 +2138,7 @@ export class Config { // PermissionManager handles both the coreTools allowlist (registry-level) // and deny rules (runtime-level) in a single check. const pmEnabled = this.permissionManager - ? this.permissionManager.isToolEnabled(toolName) + ? await this.permissionManager.isToolEnabled(toolName) : true; // Should never reach here after initialize(), but safe default. if (pmEnabled) { @@ -2122,10 +2154,10 @@ export class Config { } }; - registerCoreTool(AgentTool, this); - registerCoreTool(SkillTool, this); - registerCoreTool(LSTool, this); - registerCoreTool(ReadFileTool, this); + await registerCoreTool(AgentTool, this); + await registerCoreTool(SkillTool, this); + await registerCoreTool(LSTool, this); + await registerCoreTool(ReadFileTool, this); if (this.getUseRipgrep()) { let useRipgrep = false; @@ -2136,7 +2168,7 @@ export class Config { errorString = getErrorMessage(error); } if (useRipgrep) { - registerCoreTool(RipGrepTool, this); + await registerCoreTool(RipGrepTool, this); } else { // Log for telemetry logRipgrepFallback( @@ -2147,30 +2179,30 @@ export class Config { errorString || 'ripgrep is not available', ), ); - registerCoreTool(GrepTool, this); + await registerCoreTool(GrepTool, this); } } else { - registerCoreTool(GrepTool, this); + await registerCoreTool(GrepTool, this); } - registerCoreTool(GlobTool, this); - registerCoreTool(EditTool, this); - registerCoreTool(WriteFileTool, this); - registerCoreTool(ShellTool, this); - registerCoreTool(MemoryTool); - registerCoreTool(TodoWriteTool, this); - registerCoreTool(AskUserQuestionTool, this); - !this.sdkMode && registerCoreTool(ExitPlanModeTool, this); - registerCoreTool(WebFetchTool, this); + await registerCoreTool(GlobTool, this); + await registerCoreTool(EditTool, this); + await registerCoreTool(WriteFileTool, this); + await registerCoreTool(ShellTool, this); + await registerCoreTool(MemoryTool); + await registerCoreTool(TodoWriteTool, this); + await registerCoreTool(AskUserQuestionTool, this); + !this.sdkMode && (await registerCoreTool(ExitPlanModeTool, this)); + await registerCoreTool(WebFetchTool, this); // Conditionally register web search tool if web search provider is configured // buildWebSearchConfig ensures qwen-oauth users get dashscope provider, so // if tool is registered, config must exist if (this.getWebSearchConfig()) { - registerCoreTool(WebSearchTool, this); + await registerCoreTool(WebSearchTool, this); } if (this.isLspEnabled() && this.getLspClient()) { // Register the unified LSP tool - registerCoreTool(LspTool, this); + await registerCoreTool(LspTool, this); } if (!options?.skipDiscovery) { diff --git a/packages/core/src/confirmation-bus/message-bus.ts b/packages/core/src/confirmation-bus/message-bus.ts index fcd2caab7..e8a737f82 100644 --- a/packages/core/src/confirmation-bus/message-bus.ts +++ b/packages/core/src/confirmation-bus/message-bus.ts @@ -90,10 +90,17 @@ export class MessageBus extends EventEmitter { request: Omit, responseType: TResponse['type'], timeoutMs: number = 60000, + signal?: AbortSignal, ): Promise { const correlationId = randomUUID(); return new Promise((resolve, reject) => { + // Check if already aborted + if (signal?.aborted) { + reject(new Error('Request aborted')); + return; + } + const timeoutId = setTimeout(() => { cleanup(); reject(new Error(`Request timed out waiting for ${responseType}`)); @@ -102,8 +109,20 @@ export class MessageBus extends EventEmitter { const cleanup = () => { clearTimeout(timeoutId); this.unsubscribe(responseType, responseHandler); + if (signal) { + signal.removeEventListener('abort', abortHandler); + } }; + const abortHandler = () => { + cleanup(); + reject(new Error('Request aborted')); + }; + + if (signal) { + signal.addEventListener('abort', abortHandler); + } + const responseHandler = (response: TResponse) => { // Check if this response matches our request if ( diff --git a/packages/core/src/confirmation-bus/types.ts b/packages/core/src/confirmation-bus/types.ts index 7a699bacb..819794b61 100644 --- a/packages/core/src/confirmation-bus/types.ts +++ b/packages/core/src/confirmation-bus/types.ts @@ -109,6 +109,8 @@ export interface HookExecutionRequest { eventName: string; input: Record; correlationId: string; + /** Optional AbortSignal to cancel hook execution */ + signal?: AbortSignal; } export interface HookExecutionResponse { diff --git a/packages/core/src/core/client.test.ts b/packages/core/src/core/client.test.ts index 01d97ffbd..3c181ba8f 100644 --- a/packages/core/src/core/client.test.ts +++ b/packages/core/src/core/client.test.ts @@ -34,6 +34,7 @@ import { import { getCoreSystemPrompt, getCustomSystemPrompt } from './prompts.js'; import { DEFAULT_QWEN_FLASH_MODEL } from '../config/models.js'; import { FileDiscoveryService } from '../services/fileDiscoveryService.js'; +import { promptIdContext } from '../utils/promptIdContext.js'; import { setSimulate429 } from '../utils/testUtils.js'; import { ideContextStore } from '../ide/ideContext.js'; import { uiTelemetryService } from '../telemetry/uiTelemetry.js'; @@ -362,6 +363,7 @@ describe('Gemini Client (client.ts)', () => { getEnableHooks: vi.fn().mockReturnValue(false), getArenaManager: vi.fn().mockReturnValue(null), getMessageBus: vi.fn().mockReturnValue(undefined), + hasHooksForEvent: vi.fn().mockReturnValue(false), getHookSystem: vi.fn().mockReturnValue(undefined), getDebugLogger: vi.fn().mockReturnValue({ debug: vi.fn(), @@ -2383,6 +2385,105 @@ Other open files: expect(client['sessionTurnCount']).toBe(turnCountBefore); }); }); + + describe('hooks fast-path optimization', () => { + let mockChat: Partial; + + beforeEach(() => { + vi.spyOn(client, 'tryCompressChat').mockResolvedValue({ + originalTokenCount: 0, + newTokenCount: 0, + compressionStatus: CompressionStatus.COMPRESSED, + }); + + const mockStream = (async function* () { + yield { type: 'content', value: 'Hello' }; + })(); + mockTurnRunFn.mockReturnValue(mockStream); + + mockChat = { + addHistory: vi.fn(), + getHistory: vi.fn().mockReturnValue([]), + stripThoughtsFromHistory: vi.fn(), + }; + client['chat'] = mockChat as GeminiChat; + }); + + it('should skip messageBus.request for UserPromptSubmit when hasHooksForEvent returns false', async () => { + // Enable hooks and provide messageBus + const mockMessageBus = { + request: vi.fn(), + response: vi.fn(), + }; + vi.spyOn(client['config'], 'getEnableHooks').mockReturnValue(true); + vi.spyOn(client['config'], 'getMessageBus').mockReturnValue( + mockMessageBus as unknown as ReturnType, + ); + vi.spyOn(client['config'], 'hasHooksForEvent').mockReturnValue(false); + + const stream = client.sendMessageStream( + [{ text: 'Hi' }], + new AbortController().signal, + 'prompt-hooks-1', + ); + for await (const _ of stream) { + // consume stream + } + + // messageBus.request should NOT be called because hasHooksForEvent returned false + expect(mockMessageBus.request).not.toHaveBeenCalled(); + }); + + it('should skip messageBus.request for Stop when hasHooksForEvent returns false', async () => { + const mockMessageBus = { + request: vi.fn(), + response: vi.fn(), + }; + vi.spyOn(client['config'], 'getEnableHooks').mockReturnValue(true); + vi.spyOn(client['config'], 'getMessageBus').mockReturnValue( + mockMessageBus as unknown as ReturnType, + ); + vi.spyOn(client['config'], 'hasHooksForEvent').mockReturnValue(false); + + const stream = client.sendMessageStream( + [{ text: 'Hi' }], + new AbortController().signal, + 'prompt-hooks-2', + ); + for await (const _ of stream) { + // consume stream + } + + // messageBus.request should NOT be called for Stop hook either + expect(mockMessageBus.request).not.toHaveBeenCalled(); + }); + + it('should not skip hooks when hasHooksForEvent returns true', async () => { + const mockMessageBus = { + request: vi.fn().mockResolvedValue({ modifiedPrompt: undefined }), + response: vi.fn(), + }; + vi.spyOn(client['config'], 'getEnableHooks').mockReturnValue(true); + vi.spyOn(client['config'], 'getMessageBus').mockReturnValue( + mockMessageBus as unknown as ReturnType, + ); + vi.spyOn(client['config'], 'hasHooksForEvent').mockImplementation( + (event: string) => event === 'UserPromptSubmit', + ); + + const stream = client.sendMessageStream( + [{ text: 'Hi' }], + new AbortController().signal, + 'prompt-hooks-3', + ); + for await (const _ of stream) { + // consume stream + } + + // messageBus.request SHOULD be called for UserPromptSubmit + expect(mockMessageBus.request).toHaveBeenCalled(); + }); + }); }); describe('generateContent', () => { @@ -2441,6 +2542,55 @@ Other open files: ); }); + it('should prefer the current prompt id context for stateless requests', async () => { + const contents = [{ role: 'user', parts: [{ text: 'hello' }] }]; + const abortSignal = new AbortController().signal; + + await promptIdContext.run('btw-prompt-id', async () => { + await client.generateContent( + contents, + {}, + abortSignal, + DEFAULT_QWEN_FLASH_MODEL, + ); + }); + + expect(mockContentGenerator.generateContent).toHaveBeenCalledWith( + expect.objectContaining({ + model: DEFAULT_QWEN_FLASH_MODEL, + contents, + }), + 'btw-prompt-id', + ); + }); + + it('should prefer an explicit prompt id override over the current context', async () => { + const contents = [{ role: 'user', parts: [{ text: 'hello' }] }]; + const abortSignal = new AbortController().signal; + + await promptIdContext.run('context-prompt-id', async () => { + await ( + client.generateContent as unknown as ( + ...args: unknown[] + ) => Promise + )( + contents, + {}, + abortSignal, + DEFAULT_QWEN_FLASH_MODEL, + 'override-prompt-id', + ); + }); + + expect(mockContentGenerator.generateContent).toHaveBeenCalledWith( + expect.objectContaining({ + model: DEFAULT_QWEN_FLASH_MODEL, + contents, + }), + 'override-prompt-id', + ); + }); + it('should use config system prompt override when provided', async () => { const contents = [{ role: 'user', parts: [{ text: 'hello' }] }]; const abortSignal = new AbortController().signal; diff --git a/packages/core/src/core/client.ts b/packages/core/src/core/client.ts index c7a04d2fe..43c6f556f 100644 --- a/packages/core/src/core/client.ts +++ b/packages/core/src/core/client.ts @@ -68,6 +68,7 @@ import { reportError } from '../utils/errorReporting.js'; import { getErrorMessage } from '../utils/errors.js'; import { checkNextSpeaker } from '../utils/nextSpeakerChecker.js'; import { flatMapTextParts } from '../utils/partUtils.js'; +import { promptIdContext } from '../utils/promptIdContext.js'; import { retryWithBackoff } from '../utils/retry.js'; // Hook types and utilities @@ -464,7 +465,12 @@ export class GeminiClient { // Fire UserPromptSubmit hook through MessageBus (only if hooks are enabled) const hooksEnabled = this.config.getEnableHooks(); const messageBus = this.config.getMessageBus(); - if (messageType !== SendMessageType.Retry && hooksEnabled && messageBus) { + if ( + messageType !== SendMessageType.Retry && + hooksEnabled && + messageBus && + this.config.hasHooksForEvent('UserPromptSubmit') + ) { const promptText = partToString(request); const response = await messageBus.request< HookExecutionRequest, @@ -534,7 +540,7 @@ export class GeminiClient { return new Turn(this.getChat(), prompt_id); } - const compressed = await this.tryCompressChat(prompt_id, false); + const compressed = await this.tryCompressChat(prompt_id, false, signal); if (compressed.compressionStatus === CompressionStatus.COMPRESSED) { yield { type: GeminiEventType.ChatCompressed, value: compressed }; @@ -674,9 +680,16 @@ export class GeminiClient { return turn; } } - // Fire Stop hook through MessageBus (only if hooks are enabled) + // Fire Stop hook through MessageBus (only if hooks are enabled and registered) // This must be done before any early returns to ensure hooks are always triggered - if (hooksEnabled && messageBus && !turn.pendingToolCalls.length) { + if ( + hooksEnabled && + messageBus && + !turn.pendingToolCalls.length && + signal && + !signal.aborted && + this.config.hasHooksForEvent('Stop') + ) { // Get response text from the chat history const history = this.getHistory(); const lastModelMessage = history @@ -699,26 +712,38 @@ export class GeminiClient { stop_hook_active: true, last_assistant_message: responseText, }, + signal, }, MessageBusType.HOOK_EXECUTION_RESPONSE, ); + + // Check if aborted after hook execution + if (signal.aborted) { + return turn; + } + const hookOutput = response.output ? createHookOutput('Stop', response.output) : undefined; const stopOutput = hookOutput as StopHookOutput | undefined; + // This should happen regardless of the hook's decision + if (stopOutput?.systemMessage) { + yield { + type: GeminiEventType.HookSystemMessage, + value: stopOutput.systemMessage, + }; + } + // For Stop hooks, blocking/stop execution should force continuation if ( stopOutput?.isBlockingDecision() || stopOutput?.shouldStopExecution() ) { - // Emit system message if provided (e.g., "🔄 Ralph iteration 5") - if (stopOutput.systemMessage) { - yield { - type: GeminiEventType.HookSystemMessage, - value: stopOutput.systemMessage, - }; + // Check if aborted before continuing + if (signal.aborted) { + return turn; } const continueReason = stopOutput.getEffectiveReason(); @@ -786,8 +811,11 @@ export class GeminiClient { generationConfig: GenerateContentConfig, abortSignal: AbortSignal, model: string, + promptIdOverride?: string, ): Promise { let currentAttemptModel: string = model; + const promptId = + promptIdOverride ?? promptIdContext.getStore() ?? this.lastPromptId!; try { const userMemory = this.config.getUserMemory(); @@ -810,7 +838,7 @@ export class GeminiClient { config: requestConfig, contents, }, - this.lastPromptId!, + promptId, ); }; const result = await retryWithBackoff(apiCall, { @@ -840,6 +868,7 @@ export class GeminiClient { async tryCompressChat( prompt_id: string, force: boolean = false, + signal?: AbortSignal, ): Promise { const compressionService = new ChatCompressionService(); @@ -850,6 +879,7 @@ export class GeminiClient { this.config.getModel(), this.config, this.hasFailedCompressionAttempt, + signal, ); // Handle compression result diff --git a/packages/core/src/core/coreToolScheduler.ts b/packages/core/src/core/coreToolScheduler.ts index 097120d08..959c86e99 100644 --- a/packages/core/src/core/coreToolScheduler.ts +++ b/packages/core/src/core/coreToolScheduler.ts @@ -49,7 +49,12 @@ import type { PartListUnion, } from '@google/genai'; import { ToolNames } from '../tools/tool-names.js'; -import { buildPermissionRules } from '../permissions/rule-parser.js'; +import { + buildPermissionCheckContext, + evaluatePermissionRules, + injectPermissionRulesIfMissing, + persistPermissionOutcome, +} from './permission-helpers.js'; import { getResponseTextFromParts } from '../utils/generateContentResponseUtilities.js'; import type { ModifyContext } from '../tools/modifiable-tool.js'; import { @@ -57,7 +62,6 @@ import { modifyWithEditor, } from '../tools/modifiable-tool.js'; import * as Diff from 'diff'; -import * as path from 'node:path'; import levenshtein from 'fast-levenshtein'; import { getPlanModeSystemReminder } from './prompts.js'; import { ShellToolInvocation } from '../tools/shell.js'; @@ -695,116 +699,125 @@ export class CoreToolScheduler { } const requestsToProcess = Array.isArray(request) ? request : [request]; - const newToolCalls: ToolCall[] = requestsToProcess.map( - (reqInfo): ToolCall => { - // Check if the tool is excluded due to permissions/environment restrictions - // This check should happen before registry lookup to provide a clear permission error - const pm = this.config.getPermissionManager?.(); - if (pm && !pm.isToolEnabled(reqInfo.name)) { - const permissionErrorMessage = `Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined.`; - return { - status: 'error', - request: reqInfo, - response: createErrorResponse( - reqInfo, - new Error(permissionErrorMessage), - ToolErrorType.EXECUTION_DENIED, - ), - durationMs: 0, - }; - } + const newToolCalls: ToolCall[] = []; + for (const reqInfo of requestsToProcess) { + // Check if the tool is excluded due to permissions/environment restrictions + // This check should happen before registry lookup to provide a clear permission error + const pm = this.config.getPermissionManager?.(); + if (pm && !(await pm.isToolEnabled(reqInfo.name))) { + const matchingRule = pm.findMatchingDenyRule({ + toolName: reqInfo.name, + }); + const ruleInfo = matchingRule + ? ` Matching deny rule: "${matchingRule}".` + : ''; + const permissionErrorMessage = `Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined.${ruleInfo}`; + newToolCalls.push({ + status: 'error', + request: reqInfo, + response: createErrorResponse( + reqInfo, + new Error(permissionErrorMessage), + ToolErrorType.EXECUTION_DENIED, + ), + durationMs: 0, + }); + continue; + } - // Legacy fallback: check getPermissionsDeny() when PM is not available - if (!pm) { - const excludeTools = - this.config.getPermissionsDeny?.() ?? undefined; - if (excludeTools && excludeTools.length > 0) { - const normalizedToolName = reqInfo.name.toLowerCase().trim(); - const excludedMatch = excludeTools.find( - (excludedTool) => - excludedTool.toLowerCase().trim() === normalizedToolName, - ); - if (excludedMatch) { - const permissionErrorMessage = `Qwen Code requires permission to use ${excludedMatch}, but that permission was declined.`; - return { - status: 'error', - request: reqInfo, - response: createErrorResponse( - reqInfo, - new Error(permissionErrorMessage), - ToolErrorType.EXECUTION_DENIED, - ), - durationMs: 0, - }; - } + // Legacy fallback: check getPermissionsDeny() when PM is not available + if (!pm) { + const excludeTools = this.config.getPermissionsDeny?.() ?? undefined; + if (excludeTools && excludeTools.length > 0) { + const normalizedToolName = reqInfo.name.toLowerCase().trim(); + const excludedMatch = excludeTools.find( + (excludedTool) => + excludedTool.toLowerCase().trim() === normalizedToolName, + ); + if (excludedMatch) { + const permissionErrorMessage = `Qwen Code requires permission to use ${excludedMatch}, but that permission was declined.`; + newToolCalls.push({ + status: 'error', + request: reqInfo, + response: createErrorResponse( + reqInfo, + new Error(permissionErrorMessage), + ToolErrorType.EXECUTION_DENIED, + ), + durationMs: 0, + }); + continue; } } + } - const toolInstance = this.toolRegistry.getTool(reqInfo.name); - if (!toolInstance) { - // Tool is not in registry and not excluded - likely hallucinated or typo - const errorMessage = this.getToolNotFoundMessage(reqInfo.name); - return { - status: 'error', - request: reqInfo, - response: createErrorResponse( - reqInfo, - new Error(errorMessage), - ToolErrorType.TOOL_NOT_REGISTERED, - ), - durationMs: 0, - }; - } + const toolInstance = this.toolRegistry.getTool(reqInfo.name); + if (!toolInstance) { + // Tool is not in registry and not excluded - likely hallucinated or typo + const errorMessage = this.getToolNotFoundMessage(reqInfo.name); + newToolCalls.push({ + status: 'error', + request: reqInfo, + response: createErrorResponse( + reqInfo, + new Error(errorMessage), + ToolErrorType.TOOL_NOT_REGISTERED, + ), + durationMs: 0, + }); + continue; + } - const invocationOrError = this.buildInvocation( - toolInstance, - reqInfo.args, - ); - if (invocationOrError instanceof Error) { - const error = reqInfo.wasOutputTruncated - ? new Error( - `${invocationOrError.message} ${TRUNCATION_PARAM_GUIDANCE}`, - ) - : invocationOrError; - return { - status: 'error', - request: reqInfo, - tool: toolInstance, - response: createErrorResponse( - reqInfo, - error, - ToolErrorType.INVALID_TOOL_PARAMS, - ), - durationMs: 0, - }; - } - - // Reject file-modifying calls when truncated to prevent - // writing incomplete content. - if (reqInfo.wasOutputTruncated && toolInstance.kind === Kind.Edit) { - const truncationError = new Error(TRUNCATION_EDIT_REJECTION); - return { - status: 'error', - request: reqInfo, - tool: toolInstance, - response: createErrorResponse( - reqInfo, - truncationError, - ToolErrorType.OUTPUT_TRUNCATED, - ), - durationMs: 0, - }; - } - - return { - status: 'validating', + const invocationOrError = this.buildInvocation( + toolInstance, + reqInfo.args, + ); + if (invocationOrError instanceof Error) { + const error = reqInfo.wasOutputTruncated + ? new Error( + `${invocationOrError.message} ${TRUNCATION_PARAM_GUIDANCE}`, + ) + : invocationOrError; + newToolCalls.push({ + status: 'error', request: reqInfo, tool: toolInstance, - invocation: invocationOrError, - startTime: Date.now(), - }; - }, - ); + response: createErrorResponse( + reqInfo, + error, + ToolErrorType.INVALID_TOOL_PARAMS, + ), + durationMs: 0, + }); + continue; + } + + // Reject file-modifying calls when truncated to prevent + // writing incomplete content. + if (reqInfo.wasOutputTruncated && toolInstance.kind === Kind.Edit) { + const truncationError = new Error(TRUNCATION_EDIT_REJECTION); + newToolCalls.push({ + status: 'error', + request: reqInfo, + tool: toolInstance, + response: createErrorResponse( + reqInfo, + truncationError, + ToolErrorType.OUTPUT_TRUNCATED, + ), + durationMs: 0, + }); + continue; + } + + newToolCalls.push({ + status: 'validating', + request: reqInfo, + tool: toolInstance, + invocation: invocationOrError, + startTime: Date.now(), + }); + } this.toolCalls = this.toolCalls.concat(newToolCalls); this.notifyToolCallsUpdate(); @@ -836,66 +849,14 @@ export class CoreToolScheduler { // ---- L4: PermissionManager override (if relevant rules exist) ---- const pm = this.config.getPermissionManager?.(); - let finalPermission = defaultPermission; - let pmForcedAsk = false; - - // Build invocation context from tool params. - // This is used both by the PM evaluation below and later by - // centralized permission-rule generation (Always Allow). const toolParams = invocation.params as Record; - const shellCommand = - 'command' in toolParams ? String(toolParams['command']) : undefined; - // Extract file path — tools use 'file_path' or 'path' - // (LS / grep / glob). - let invocationFilePath = - typeof toolParams['file_path'] === 'string' - ? toolParams['file_path'] - : undefined; - if ( - invocationFilePath === undefined && - typeof toolParams['path'] === 'string' - ) { - // LS uses absolute paths; grep/glob may be relative to targetDir. - invocationFilePath = path.isAbsolute(toolParams['path']) - ? toolParams['path'] - : path.resolve(this.config.getTargetDir(), toolParams['path']); - } - let invocationDomain: string | undefined; - if (typeof toolParams['url'] === 'string') { - try { - invocationDomain = new URL(toolParams['url']).hostname; - } catch { - // malformed URL — leave domain undefined - } - } - // Generic specifier for literal matching (Skill name, Task subagent type, etc.) - const literalSpecifier = - typeof toolParams['skill'] === 'string' - ? toolParams['skill'] - : typeof toolParams['subagent_type'] === 'string' - ? toolParams['subagent_type'] - : undefined; - const pmCtx = { - toolName: reqInfo.name, - command: shellCommand, - filePath: invocationFilePath, - domain: invocationDomain, - specifier: literalSpecifier, - }; - - if (pm && defaultPermission !== 'deny') { - if (pm.hasRelevantRules(pmCtx)) { - const pmDecision = pm.evaluate(pmCtx); - if (pmDecision !== 'default') { - finalPermission = pmDecision; - // If PM explicitly forces 'ask', adding allow rules won't help - // because ask has higher priority. Hide "Always allow" options. - if (pmDecision === 'ask') { - pmForcedAsk = true; - } - } - } - } + const pmCtx = buildPermissionCheckContext( + reqInfo.name, + toolParams, + this.config.getTargetDir?.() ?? '', + ); + const { finalPermission, pmForcedAsk } = + await evaluatePermissionRules(pm, defaultPermission, pmCtx); // ---- L5: Final decision based on permission + ApprovalMode ---- const approvalMode = this.config.getApprovalMode(); @@ -914,10 +875,16 @@ export class CoreToolScheduler { if (finalPermission === 'deny') { // Hard deny: security violation or PM explicit deny - const denyMessage = - defaultPermission === 'deny' - ? `Tool "${reqInfo.name}" is denied: command substitution is not allowed for security reasons.` - : `Tool "${reqInfo.name}" is denied by permission rules.`; + let denyMessage: string; + if (defaultPermission === 'deny') { + denyMessage = `Tool "${reqInfo.name}" is denied: command substitution is not allowed for security reasons.`; + } else { + const matchingRule = pm?.findMatchingDenyRule(pmCtx); + const ruleInfo = matchingRule + ? ` Matching deny rule: "${matchingRule}".` + : ''; + denyMessage = `Tool "${reqInfo.name}" is denied by permission rules.${ruleInfo}`; + } this.setStatusInternal( reqInfo.callId, 'error', @@ -965,19 +932,7 @@ export class CoreToolScheduler { await invocation.getConfirmationDetails(signal); // ── Centralised rule injection ────────────────────────────────── - // If the tool did not provide its own permissionRules (e.g. Shell - // and WebFetch already do), generate minimum-scope rules from - // the invocation context so that "Always Allow" persists a - // properly scoped rule rather than nothing. - // Only exec/mcp/info types support the permissionRules field. - if ( - (confirmationDetails.type === 'exec' || - confirmationDetails.type === 'mcp' || - confirmationDetails.type === 'info') && - !confirmationDetails.permissionRules - ) { - confirmationDetails.permissionRules = buildPermissionRules(pmCtx); - } + injectPermissionRulesIfMissing(confirmationDetails, pmCtx); // AUTO_EDIT mode: auto-approve edit-like and info tools if ( @@ -1002,7 +957,7 @@ export class CoreToolScheduler { this.config.getInputFormat() !== InputFormat.STREAM_JSON; if (shouldAutoDeny) { - const errorMessage = `Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined.`; + const errorMessage = `Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined (non-interactive mode cannot prompt for confirmation).`; this.setStatusInternal( reqInfo.callId, 'error', @@ -1021,6 +976,17 @@ export class CoreToolScheduler { confirmationDetails.ideConfirmation ) { confirmationDetails.ideConfirmation.then((resolution) => { + // Guard: skip if the tool was already handled (e.g. by CLI + // confirmation). Without this check, resolveDiffFromCli + // triggers this handler AND the CLI's onConfirm, causing a + // race where ProceedOnce overwrites ProceedAlways. + const still = this.toolCalls.find( + (c) => + c.request.callId === reqInfo.callId && + c.status === 'awaiting_approval', + ); + if (!still) return; + if (resolution.status === 'accepted') { this.handleConfirmationResponse( reqInfo.callId, @@ -1185,6 +1151,11 @@ export class CoreToolScheduler { (c) => c.request.callId === callId && c.status === 'awaiting_approval', ); + // Guard: if the tool is no longer awaiting approval (already handled by + // another confirmation path, e.g. IDE vs CLI race), skip to avoid double + // processing and potential re-execution. + if (!toolCall) return; + await originalOnConfirm(outcome, payload); if ( @@ -1193,37 +1164,13 @@ export class CoreToolScheduler { outcome === ToolConfirmationOutcome.ProceedAlwaysUser ) { // Persist permission rules for Project/User scope outcomes - if ( - outcome === ToolConfirmationOutcome.ProceedAlwaysProject || - outcome === ToolConfirmationOutcome.ProceedAlwaysUser - ) { - const scope = - outcome === ToolConfirmationOutcome.ProceedAlwaysProject - ? 'project' - : 'user'; - // Read permissionRules from the stored confirmation details first, - // falling back to payload for backward compatibility. - const details = (toolCall as WaitingToolCall | undefined) - ?.confirmationDetails; - const detailsRules = (details as Record | undefined)?.[ - 'permissionRules' - ] as string[] | undefined; - const payloadRules = payload?.permissionRules; - const rules = payloadRules ?? detailsRules ?? []; - const persistFn = this.config.getOnPersistPermissionRule?.(); - const pm = this.config.getPermissionManager?.(); - if (rules.length > 0) { - for (const rule of rules) { - // 1. Persist to disk (settings.json) - if (persistFn) { - await persistFn(scope, 'allow', rule); - } - // 2. Immediately update in-memory PermissionManager so the - // new rule takes effect without restart. - pm?.addPersistentRule(rule, 'allow'); - } - } - } + await persistPermissionOutcome( + outcome, + (toolCall as WaitingToolCall).confirmationDetails, + this.config.getOnPersistPermissionRule?.(), + this.config.getPermissionManager?.(), + payload, + ); await this.autoApproveCompatiblePendingTools(signal, callId); } @@ -1726,50 +1673,20 @@ export class CoreToolScheduler { // Re-run L3→L4 to see if the tool can now be auto-approved const defaultPermission = await pendingTool.invocation.getDefaultPermission(); - let finalPermission = defaultPermission; - - // L4: PM override - const pm = this.config.getPermissionManager?.(); - if (pm && defaultPermission !== 'deny') { - const params = pendingTool.invocation.params as Record< - string, - unknown - >; - const shellCommand = - 'command' in params ? String(params['command']) : undefined; - const filePath = - typeof params['file_path'] === 'string' - ? params['file_path'] - : undefined; - let domain: string | undefined; - if (typeof params['url'] === 'string') { - try { - domain = new URL(params['url']).hostname; - } catch { - // malformed URL - } - } - // Generic specifier for literal matching (Skill name, Task subagent type, etc.) - const literalSpecifier = - typeof params['skill'] === 'string' - ? params['skill'] - : typeof params['subagent_type'] === 'string' - ? params['subagent_type'] - : undefined; - const pmCtx = { - toolName: pendingTool.request.name, - command: shellCommand, - filePath, - domain, - specifier: literalSpecifier, - }; - if (pm.hasRelevantRules(pmCtx)) { - const pmDecision = pm.evaluate(pmCtx); - if (pmDecision !== 'default') { - finalPermission = pmDecision; - } - } - } + const toolParams = pendingTool.invocation.params as Record< + string, + unknown + >; + const pmCtx = buildPermissionCheckContext( + pendingTool.request.name, + toolParams, + this.config.getTargetDir?.() ?? '', + ); + const { finalPermission } = await evaluatePermissionRules( + this.config.getPermissionManager?.(), + defaultPermission, + pmCtx, + ); if (finalPermission === 'allow') { this.setToolCallOutcome( diff --git a/packages/core/src/core/loggingContentGenerator/loggingContentGenerator.test.ts b/packages/core/src/core/loggingContentGenerator/loggingContentGenerator.test.ts index 06be16ea5..b39e65357 100644 --- a/packages/core/src/core/loggingContentGenerator/loggingContentGenerator.test.ts +++ b/packages/core/src/core/loggingContentGenerator/loggingContentGenerator.test.ts @@ -66,6 +66,7 @@ const createConfig = (overrides: Record = {}): Config => { return { getContentGeneratorConfig: () => configContent, getAuthType: () => configContent.authType as AuthType | undefined, + getWorkingDir: () => process.cwd(), } as Config; }; diff --git a/packages/core/src/core/loggingContentGenerator/loggingContentGenerator.ts b/packages/core/src/core/loggingContentGenerator/loggingContentGenerator.ts index 61fc885e9..4f4b00138 100644 --- a/packages/core/src/core/loggingContentGenerator/loggingContentGenerator.ts +++ b/packages/core/src/core/loggingContentGenerator/loggingContentGenerator.ts @@ -62,7 +62,10 @@ export class LoggingContentGenerator implements ContentGenerator { // Extract fields needed for initialization from passed config // (config.getContentGeneratorConfig() may not be available yet during refreshAuth) if (generatorConfig.enableOpenAILogging) { - this.openaiLogger = new OpenAILogger(generatorConfig.openAILoggingDir); + this.openaiLogger = new OpenAILogger( + generatorConfig.openAILoggingDir, + config.getWorkingDir(), + ); this.schemaCompliance = generatorConfig.schemaCompliance; } } diff --git a/packages/core/src/core/permission-helpers.ts b/packages/core/src/core/permission-helpers.ts new file mode 100644 index 000000000..82d960bd6 --- /dev/null +++ b/packages/core/src/core/permission-helpers.ts @@ -0,0 +1,207 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * Shared permission-evaluation and persistence helpers. + * + * These are used by both `coreToolScheduler` (CLI mode) and the ACP + * `Session` (VS Code / webui mode) so that the L3→L4→L5 permission flow + * and the "Always Allow" persistence logic stay in sync. + */ + +import * as path from 'node:path'; +import type { PermissionCheckContext } from '../permissions/types.js'; +import type { PermissionManager } from '../permissions/permission-manager.js'; +import type { + ToolCallConfirmationDetails, + ToolConfirmationPayload, +} from '../tools/tools.js'; +import { ToolConfirmationOutcome } from '../tools/tools.js'; +import { buildPermissionRules } from '../permissions/rule-parser.js'; + +// ───────────────────────────────────────────────────────────────────────────── +// Context building +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Build a {@link PermissionCheckContext} from raw tool invocation parameters. + * + * Extracts `command`, `filePath`, `domain`, and `specifier` fields from the + * tool's params, resolving relative paths against `targetDir`. + */ +export function buildPermissionCheckContext( + toolName: string, + toolParams: Record, + targetDir: string, +): PermissionCheckContext { + const command = + 'command' in toolParams ? String(toolParams['command']) : undefined; + + // Extract file path — tools use 'file_path' or 'path' (LS / grep / glob). + let filePath = + typeof toolParams['file_path'] === 'string' + ? toolParams['file_path'] + : undefined; + if (filePath === undefined && typeof toolParams['path'] === 'string') { + // LS uses absolute paths; grep/glob may be relative to targetDir. + filePath = path.isAbsolute(toolParams['path']) + ? toolParams['path'] + : path.resolve(targetDir, toolParams['path']); + } + + let domain: string | undefined; + if (typeof toolParams['url'] === 'string') { + try { + domain = new URL(toolParams['url']).hostname; + } catch { + // malformed URL — leave domain undefined + } + } + + // Generic specifier for literal matching (Skill name, Task subagent type, etc.) + const specifier = + typeof toolParams['skill'] === 'string' + ? toolParams['skill'] + : typeof toolParams['subagent_type'] === 'string' + ? toolParams['subagent_type'] + : undefined; + + return { toolName, command, filePath, domain, specifier }; +} + +// ───────────────────────────────────────────────────────────────────────────── +// PM evaluation +// ───────────────────────────────────────────────────────────────────────────── + +/** Result of {@link evaluatePermissionRules}. */ +export interface PermissionEvalResult { + /** The final permission after PM override. */ + finalPermission: string; + /** + * `true` when PM explicitly forces `'ask'`. In that case "Always Allow" + * buttons should be hidden because allow rules can never override the + * higher-priority ask rule. + */ + pmForcedAsk: boolean; +} + +/** + * L4 — evaluate {@link PermissionManager} rules against the given context. + * + * Returns the final permission decision and whether PM forced 'ask'. + * When `defaultPermission` is already `'deny'`, PM evaluation is skipped. + */ +export async function evaluatePermissionRules( + pm: PermissionManager | null | undefined, + defaultPermission: string, + pmCtx: PermissionCheckContext, +): Promise { + let finalPermission = defaultPermission; + let pmForcedAsk = false; + + if (pm && defaultPermission !== 'deny') { + if (pm.hasRelevantRules(pmCtx)) { + const pmDecision = await pm.evaluate(pmCtx); + if (pmDecision !== 'default') { + finalPermission = pmDecision; + // If PM explicitly forces 'ask', adding allow rules won't help + // because ask has higher priority. Hide "Always allow" options. + if (pmDecision === 'ask' && pm.hasMatchingAskRule(pmCtx)) { + pmForcedAsk = true; + } + } + } + } + + return { finalPermission, pmForcedAsk }; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Centralised rule injection +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Inject centralized permission rules into confirmation details when the tool + * doesn't provide its own. This ensures "Always Allow" persists a properly + * scoped rule rather than nothing. + * + * Only `exec` / `mcp` / `info` types support the `permissionRules` field. + * Mutates `confirmationDetails` in place. + */ +export function injectPermissionRulesIfMissing( + confirmationDetails: ToolCallConfirmationDetails, + pmCtx: PermissionCheckContext, +): void { + if ( + (confirmationDetails.type === 'exec' || + confirmationDetails.type === 'mcp' || + confirmationDetails.type === 'info') && + !confirmationDetails.permissionRules + ) { + confirmationDetails.permissionRules = buildPermissionRules(pmCtx); + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// Permission persistence +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Persist permission rules for `ProceedAlwaysProject` / `ProceedAlwaysUser` + * outcomes. + * + * Reads rules from `confirmationDetails.permissionRules` (set by the tool or + * by {@link injectPermissionRulesIfMissing}), falling back to + * `payload.permissionRules` for backward compatibility. + * + * Writes to disk via `persistFn` and updates the in-memory + * {@link PermissionManager}. No-op for other outcomes. + */ +export async function persistPermissionOutcome( + outcome: ToolConfirmationOutcome, + confirmationDetails: ToolCallConfirmationDetails, + persistFn: + | (( + scope: 'project' | 'user', + ruleType: 'allow' | 'ask' | 'deny', + rule: string, + ) => Promise) + | undefined, + pm: PermissionManager | null | undefined, + payload?: ToolConfirmationPayload, +): Promise { + if ( + outcome !== ToolConfirmationOutcome.ProceedAlwaysProject && + outcome !== ToolConfirmationOutcome.ProceedAlwaysUser + ) { + return; + } + + const scope = + outcome === ToolConfirmationOutcome.ProceedAlwaysProject + ? 'project' + : 'user'; + + // Read permissionRules from the stored confirmation details first, + // falling back to payload for backward compatibility. + const detailsRules = ( + confirmationDetails as unknown as Record + )?.['permissionRules'] as string[] | undefined; + const payloadRules = payload?.permissionRules; + const rules = payloadRules ?? detailsRules ?? []; + + if (rules.length > 0) { + for (const rule of rules) { + // 1. Persist to disk (settings.json) + if (persistFn) { + await persistFn(scope, 'allow', rule); + } + // 2. Immediately update in-memory PermissionManager so the + // new rule takes effect without restart. + pm?.addPersistentRule(rule, 'allow'); + } + } +} diff --git a/packages/core/src/core/toolHookTriggers.ts b/packages/core/src/core/toolHookTriggers.ts index 1d62477e0..73423d77d 100644 --- a/packages/core/src/core/toolHookTriggers.ts +++ b/packages/core/src/core/toolHookTriggers.ts @@ -81,6 +81,7 @@ export async function firePreToolUseHook( toolInput: Record, toolUseId: string, permissionMode: string, + signal?: AbortSignal, ): Promise { if (!messageBus) { return { shouldProceed: true }; @@ -100,6 +101,7 @@ export async function firePreToolUseHook( tool_input: toolInput, tool_use_id: toolUseId, }, + signal, }, MessageBusType.HOOK_EXECUTION_RESPONSE, ); @@ -178,6 +180,7 @@ export async function firePostToolUseHook( toolResponse: Record, toolUseId: string, permissionMode: string, + signal?: AbortSignal, ): Promise { if (!messageBus) { return { shouldStop: false }; @@ -198,6 +201,7 @@ export async function firePostToolUseHook( tool_response: toolResponse, tool_use_id: toolUseId, }, + signal, }, MessageBusType.HOOK_EXECUTION_RESPONSE, ); @@ -255,6 +259,7 @@ export async function firePostToolUseFailureHook( errorMessage: string, isInterrupt?: boolean, permissionMode?: string, + signal?: AbortSignal, ): Promise { if (!messageBus) { return {}; @@ -276,6 +281,7 @@ export async function firePostToolUseFailureHook( error: errorMessage, is_interrupt: isInterrupt, }, + signal, }, MessageBusType.HOOK_EXECUTION_RESPONSE, ); @@ -319,6 +325,7 @@ export async function fireNotificationHook( message: string, notificationType: NotificationType, title?: string, + signal?: AbortSignal, ): Promise { if (!messageBus) { return {}; @@ -337,6 +344,7 @@ export async function fireNotificationHook( notification_type: notificationType, title, }, + signal, }, MessageBusType.HOOK_EXECUTION_RESPONSE, ); @@ -390,6 +398,7 @@ export async function firePermissionRequestHook( toolInput: Record, permissionMode: string, permissionSuggestions?: PermissionSuggestion[], + signal?: AbortSignal, ): Promise { if (!messageBus) { return { hasDecision: false }; @@ -409,6 +418,7 @@ export async function firePermissionRequestHook( permission_mode: permissionMode, permission_suggestions: permissionSuggestions, }, + signal, }, MessageBusType.HOOK_EXECUTION_RESPONSE, ); diff --git a/packages/core/src/extension/extensionManager.test.ts b/packages/core/src/extension/extensionManager.test.ts index 10a39dc5e..7b43eddc7 100644 --- a/packages/core/src/extension/extensionManager.test.ts +++ b/packages/core/src/extension/extensionManager.test.ts @@ -755,6 +755,20 @@ describe('extension tests', () => { const id = getExtensionId(config, metadata); expect(id).toBe(hashValue('https://github.com/owner/repo')); }); + + it('should use source as-is for non-GitHub git URLs (e.g., GitLab)', () => { + // For non-GitHub git servers, fall back to using the source URL directly + const config: ExtensionConfig = { name: 'test-ext', version: '1.0.0' }; + const metadata = { + type: 'git' as const, + source: 'https://gitlab.company.com/team/extension-repo', + }; + + const id = getExtensionId(config, metadata); + expect(id).toBe( + hashValue('https://gitlab.company.com/team/extension-repo'), + ); + }); }); }); diff --git a/packages/core/src/extension/extensionManager.ts b/packages/core/src/extension/extensionManager.ts index 15ead552d..e64527ced 100644 --- a/packages/core/src/extension/extensionManager.ts +++ b/packages/core/src/extension/extensionManager.ts @@ -1358,12 +1358,18 @@ export function getExtensionId( installMetadata?: ExtensionInstallMetadata, ): string { let idValue = config.name; - const githubUrlParts = + let githubUrlParts = null; + if ( installMetadata && (installMetadata.type === 'git' || installMetadata.type === 'github-release') - ? parseGitHubRepoForReleases(installMetadata.source) - : null; + ) { + try { + githubUrlParts = parseGitHubRepoForReleases(installMetadata.source); + } catch { + // Non-GitHub URL (GitLab, Bitbucket, etc.) - use source as-is + } + } if (githubUrlParts) { idValue = `https://github.com/${githubUrlParts.owner}/${githubUrlParts.repo}`; } else { diff --git a/packages/core/src/extension/variables.test.ts b/packages/core/src/extension/variables.test.ts index 685a70064..7f2366497 100644 --- a/packages/core/src/extension/variables.test.ts +++ b/packages/core/src/extension/variables.test.ts @@ -263,6 +263,34 @@ describe('performVariableReplacement', () => { expect(result).not.toContain('```!'); }); + it('should replace .claude with .qwen in markdown files', () => { + const extDir = path.join(testDir, 'ext'); + fs.mkdirSync(extDir, { recursive: true }); + + const mdContent = [ + '---', + 'description: "Cancel active loop"', + '---', + '', + '# Cancel', + '', + 'Check if `.claude/loop.local.md` exists.', + 'Remove the file: `rm .claude/loop.local.md`', + 'Path: `$HOME/.claude/cache`', + 'Local: `./.claude/local`', + ].join('\n'); + fs.writeFileSync(path.join(extDir, 'cancel.md'), mdContent, 'utf-8'); + + performVariableReplacement(extDir); + + const result = fs.readFileSync(path.join(extDir, 'cancel.md'), 'utf-8'); + expect(result).toContain('.qwen/loop.local.md'); + expect(result).toContain('rm .qwen/loop.local.md'); + expect(result).toContain('$HOME/.qwen/cache'); + expect(result).toContain('./.qwen/local'); + expect(result).not.toContain('.claude/'); + }); + it('should replace "role":"assistant" with "type":"assistant" in shell scripts', () => { const extDir = path.join(testDir, 'ext'); fs.mkdirSync(extDir, { recursive: true }); diff --git a/packages/core/src/extension/variables.ts b/packages/core/src/extension/variables.ts index ba3d9a439..63fe7e558 100644 --- a/packages/core/src/extension/variables.ts +++ b/packages/core/src/extension/variables.ts @@ -7,7 +7,8 @@ import { type VariableSchema, VARIABLE_SCHEMA } from './variableSchema.js'; import path from 'node:path'; import { QWEN_DIR } from '../config/storage.js'; -import type { HookEventName, HookDefinition } from '../hooks/types.js'; +import type { HookDefinition } from '../hooks/types.js'; +import type { HookEventName } from '../hooks/types.js'; import * as fs from 'node:fs'; import { glob } from 'glob'; import { createDebugLogger } from '../utils/debugLogger.js'; @@ -15,7 +16,7 @@ import { createDebugLogger } from '../utils/debugLogger.js'; const debugLogger = createDebugLogger('Extension:variables'); // Re-export types for substituteHookVariables -export type { HookEventName, HookDefinition }; +export type { HookDefinition }; export const EXTENSIONS_DIRECTORY_NAME = path.join(QWEN_DIR, 'extensions'); export const EXTENSIONS_CONFIG_FILENAME = 'qwen-extension.json'; @@ -147,16 +148,24 @@ export function performVariableReplacement(extensionPath: string): void { // Replace Markdown shell syntax ```! ... ``` with system-recognized !{...} syntax // This regex finds code blocks with ! language identifier and captures their content - const updatedMdContent = updatedContent.replace( + const syntaxUpdatedContent = updatedContent.replace( /```!(?:\s*\n)?([\s\S]*?)\n*```/g, '!{$1}', ); + // Replace references to ".claude" directory with ".qwen" in markdown files + // Only match path references (e.g., ~/.claude/, $HOME/.claude, ./.claude/) + // Avoid matching URLs, comments, or string literals containing .claude + const updatedMdContent = syntaxUpdatedContent.replace( + /(\$\{?HOME\}?\/|~\/)?\.claude(\/|$)/g, + '$1.qwen$2', + ); + // Only write if content was actually changed if (updatedMdContent !== content) { fs.writeFileSync(filePath, updatedMdContent, 'utf8'); debugLogger.debug( - `Updated variables and syntax in file: ${filePath}`, + `Updated variables, syntax, and .claude paths in file: ${filePath}`, ); } } catch (error) { diff --git a/packages/core/src/hooks/hookEventHandler.test.ts b/packages/core/src/hooks/hookEventHandler.test.ts index 9bffed8bb..bf22f4cc9 100644 --- a/packages/core/src/hooks/hookEventHandler.test.ts +++ b/packages/core/src/hooks/hookEventHandler.test.ts @@ -25,6 +25,13 @@ import type { AggregatedHookResult, } from './index.js'; import type { HookConfig, HookOutput, PermissionSuggestion } from './types.js'; +import type { HookExecutionResult } from './types.js'; +import { logHookCall } from '../telemetry/loggers.js'; + +// Mock the telemetry loggers module +vi.mock('../telemetry/loggers.js', () => ({ + logHookCall: vi.fn(), +})); describe('HookEventHandler', () => { let mockConfig: Config; @@ -712,6 +719,7 @@ describe('HookEventHandler', () => { expect.any(Object), // input object expect.any(Function), // onHookStart callback expect.any(Function), // onHookEnd callback + undefined, // signal ); }); @@ -2245,4 +2253,361 @@ describe('HookEventHandler', () => { expect(input.stop_hook_active).toBe(true); }); }); + + describe('telemetry', () => { + const createMockHookExecutionResult = ( + success: boolean, + hookConfig: HookConfig, + duration: number = 100, + output?: HookOutput, + error?: Error, + ): HookExecutionResult => ({ + hookConfig, + eventName: HookEventName.PreToolUse, + success, + output, + stdout: 'stdout', + stderr: success ? undefined : 'stderr', + exitCode: success ? 0 : 1, + duration, + error, + }); + + beforeEach(() => { + vi.mocked(logHookCall).mockClear(); + }); + + it('should call logHookCall for each hook execution', async () => { + const hookConfig1: HookConfig = { + type: HookType.Command, + command: 'hook1.sh', + name: 'first-hook', + source: HooksConfigSource.Project, + }; + const hookConfig2: HookConfig = { + type: HookType.Command, + command: 'hook2.sh', + name: 'second-hook', + source: HooksConfigSource.Project, + }; + + const mockPlan = createMockExecutionPlan([hookConfig1, hookConfig2]); + vi.mocked(mockHookPlanner.createExecutionPlan).mockReturnValue(mockPlan); + + const result1 = createMockHookExecutionResult(true, hookConfig1, 50); + const result2 = createMockHookExecutionResult(true, hookConfig2, 75); + vi.mocked(mockHookRunner.executeHooksParallel).mockResolvedValue([ + result1, + result2, + ]); + vi.mocked(mockHookAggregator.aggregateResults).mockReturnValue( + createMockAggregatedResult(true), + ); + + await hookEventHandler.fireUserPromptSubmitEvent('test prompt'); + + expect(logHookCall).toHaveBeenCalledTimes(2); + }); + + it('should log hook call with correct event name', async () => { + const hookConfig: HookConfig = { + type: HookType.Command, + command: 'test.sh', + source: HooksConfigSource.Project, + }; + + const mockPlan = createMockExecutionPlan([hookConfig]); + vi.mocked(mockHookPlanner.createExecutionPlan).mockReturnValue(mockPlan); + + const result = createMockHookExecutionResult(true, hookConfig); + vi.mocked(mockHookRunner.executeHooksParallel).mockResolvedValue([ + result, + ]); + vi.mocked(mockHookAggregator.aggregateResults).mockReturnValue( + createMockAggregatedResult(true), + ); + + await hookEventHandler.firePreToolUseEvent( + 'read_file', + { path: '/test' }, + 'tool-123', + PermissionMode.Default, + ); + + expect(logHookCall).toHaveBeenCalledWith( + mockConfig, + expect.objectContaining({ + hook_event_name: HookEventName.PreToolUse, + }), + ); + }); + + it('should log hook call with hook name from config', async () => { + const hookConfig: HookConfig = { + type: HookType.Command, + command: '/path/to/my-hook.sh', + name: 'my-custom-hook', + source: HooksConfigSource.Project, + }; + + const mockPlan = createMockExecutionPlan([hookConfig]); + vi.mocked(mockHookPlanner.createExecutionPlan).mockReturnValue(mockPlan); + + const result = createMockHookExecutionResult(true, hookConfig); + vi.mocked(mockHookRunner.executeHooksParallel).mockResolvedValue([ + result, + ]); + vi.mocked(mockHookAggregator.aggregateResults).mockReturnValue( + createMockAggregatedResult(true), + ); + + await hookEventHandler.fireUserPromptSubmitEvent('test'); + + expect(logHookCall).toHaveBeenCalledWith( + mockConfig, + expect.objectContaining({ + hook_name: 'my-custom-hook', + }), + ); + }); + + it('should log hook call with command as name when no name specified', async () => { + const hookConfig: HookConfig = { + type: HookType.Command, + command: '/path/to/hook-script.sh', + source: HooksConfigSource.Project, + }; + + const mockPlan = createMockExecutionPlan([hookConfig]); + vi.mocked(mockHookPlanner.createExecutionPlan).mockReturnValue(mockPlan); + + const result = createMockHookExecutionResult(true, hookConfig); + vi.mocked(mockHookRunner.executeHooksParallel).mockResolvedValue([ + result, + ]); + vi.mocked(mockHookAggregator.aggregateResults).mockReturnValue( + createMockAggregatedResult(true), + ); + + await hookEventHandler.fireUserPromptSubmitEvent('test'); + + expect(logHookCall).toHaveBeenCalledWith( + mockConfig, + expect.objectContaining({ + hook_name: '/path/to/hook-script.sh', + }), + ); + }); + + it('should log hook call with duration', async () => { + const hookConfig: HookConfig = { + type: HookType.Command, + command: 'test.sh', + source: HooksConfigSource.Project, + }; + + const mockPlan = createMockExecutionPlan([hookConfig]); + vi.mocked(mockHookPlanner.createExecutionPlan).mockReturnValue(mockPlan); + + const duration = 250; + const result = createMockHookExecutionResult(true, hookConfig, duration); + vi.mocked(mockHookRunner.executeHooksParallel).mockResolvedValue([ + result, + ]); + vi.mocked(mockHookAggregator.aggregateResults).mockReturnValue( + createMockAggregatedResult(true), + ); + + await hookEventHandler.fireUserPromptSubmitEvent('test'); + + expect(logHookCall).toHaveBeenCalledWith( + mockConfig, + expect.objectContaining({ + duration_ms: duration, + }), + ); + }); + + it('should log hook call with success status', async () => { + const hookConfig: HookConfig = { + type: HookType.Command, + command: 'test.sh', + source: HooksConfigSource.Project, + }; + + const mockPlan = createMockExecutionPlan([hookConfig]); + vi.mocked(mockHookPlanner.createExecutionPlan).mockReturnValue(mockPlan); + + const result = createMockHookExecutionResult(true, hookConfig); + vi.mocked(mockHookRunner.executeHooksParallel).mockResolvedValue([ + result, + ]); + vi.mocked(mockHookAggregator.aggregateResults).mockReturnValue( + createMockAggregatedResult(true), + ); + + await hookEventHandler.fireUserPromptSubmitEvent('test'); + + expect(logHookCall).toHaveBeenCalledWith( + mockConfig, + expect.objectContaining({ + success: true, + }), + ); + }); + + it('should log hook call with failure status', async () => { + const hookConfig: HookConfig = { + type: HookType.Command, + command: 'failing-hook.sh', + source: HooksConfigSource.Project, + }; + + const mockPlan = createMockExecutionPlan([hookConfig]); + vi.mocked(mockHookPlanner.createExecutionPlan).mockReturnValue(mockPlan); + + const result = createMockHookExecutionResult( + false, + hookConfig, + 100, + undefined, + new Error('Hook failed'), + ); + vi.mocked(mockHookRunner.executeHooksParallel).mockResolvedValue([ + result, + ]); + vi.mocked(mockHookAggregator.aggregateResults).mockReturnValue( + createMockAggregatedResult(false), + ); + + await hookEventHandler.fireUserPromptSubmitEvent('test'); + + expect(logHookCall).toHaveBeenCalledWith( + mockConfig, + expect.objectContaining({ + success: false, + error: 'Hook failed', + }), + ); + }); + + it('should log hook call with exit code', async () => { + const hookConfig: HookConfig = { + type: HookType.Command, + command: 'test.sh', + source: HooksConfigSource.Project, + }; + + const mockPlan = createMockExecutionPlan([hookConfig]); + vi.mocked(mockHookPlanner.createExecutionPlan).mockReturnValue(mockPlan); + + const result = createMockHookExecutionResult(true, hookConfig); + result.exitCode = 0; + vi.mocked(mockHookRunner.executeHooksParallel).mockResolvedValue([ + result, + ]); + vi.mocked(mockHookAggregator.aggregateResults).mockReturnValue( + createMockAggregatedResult(true), + ); + + await hookEventHandler.fireUserPromptSubmitEvent('test'); + + expect(logHookCall).toHaveBeenCalledWith( + mockConfig, + expect.objectContaining({ + exit_code: 0, + }), + ); + }); + + it('should log hook call with hook type', async () => { + const hookConfig: HookConfig = { + type: HookType.Command, + command: 'test.sh', + source: HooksConfigSource.Project, + }; + + const mockPlan = createMockExecutionPlan([hookConfig]); + vi.mocked(mockHookPlanner.createExecutionPlan).mockReturnValue(mockPlan); + + const result = createMockHookExecutionResult(true, hookConfig); + vi.mocked(mockHookRunner.executeHooksParallel).mockResolvedValue([ + result, + ]); + vi.mocked(mockHookAggregator.aggregateResults).mockReturnValue( + createMockAggregatedResult(true), + ); + + await hookEventHandler.fireUserPromptSubmitEvent('test'); + + expect(logHookCall).toHaveBeenCalledWith( + mockConfig, + expect.objectContaining({ + hook_type: 'command', + }), + ); + }); + + it('should not call logHookCall when no hooks are configured', async () => { + const mockPlan = createMockExecutionPlan([]); + vi.mocked(mockHookPlanner.createExecutionPlan).mockReturnValue(mockPlan); + + await hookEventHandler.fireUserPromptSubmitEvent('test'); + + expect(logHookCall).not.toHaveBeenCalled(); + }); + + it('should log telemetry for different event types', async () => { + const hookConfig: HookConfig = { + type: HookType.Command, + command: 'test.sh', + source: HooksConfigSource.Project, + }; + + const mockPlan = createMockExecutionPlan([hookConfig]); + vi.mocked(mockHookPlanner.createExecutionPlan).mockReturnValue(mockPlan); + + const result = createMockHookExecutionResult(true, hookConfig); + vi.mocked(mockHookRunner.executeHooksParallel).mockResolvedValue([ + result, + ]); + vi.mocked(mockHookAggregator.aggregateResults).mockReturnValue( + createMockAggregatedResult(true), + ); + + // Test SessionStart + await hookEventHandler.fireSessionStartEvent( + SessionStartSource.Startup, + 'test-model', + ); + expect(logHookCall).toHaveBeenCalledWith( + mockConfig, + expect.objectContaining({ + hook_event_name: HookEventName.SessionStart, + }), + ); + + vi.mocked(logHookCall).mockClear(); + + // Test SessionEnd + await hookEventHandler.fireSessionEndEvent(SessionEndReason.Clear); + expect(logHookCall).toHaveBeenCalledWith( + mockConfig, + expect.objectContaining({ + hook_event_name: HookEventName.SessionEnd, + }), + ); + + vi.mocked(logHookCall).mockClear(); + + // Test Stop + await hookEventHandler.fireStopEvent(true, 'last message'); + expect(logHookCall).toHaveBeenCalledWith( + mockConfig, + expect.objectContaining({ + hook_event_name: HookEventName.Stop, + }), + ); + }); + }); }); diff --git a/packages/core/src/hooks/hookEventHandler.ts b/packages/core/src/hooks/hookEventHandler.ts index 16bc92b4a..ae3602ab9 100644 --- a/packages/core/src/hooks/hookEventHandler.ts +++ b/packages/core/src/hooks/hookEventHandler.ts @@ -34,6 +34,8 @@ import type { } from './types.js'; import { PermissionMode } from './types.js'; import { createDebugLogger } from '../utils/debugLogger.js'; +import { logHookCall } from '../telemetry/loggers.js'; +import { HookCallEvent } from '../telemetry/types.js'; const debugLogger = createDebugLogger('TRUSTED_HOOKS'); @@ -64,13 +66,19 @@ export class HookEventHandler { */ async fireUserPromptSubmitEvent( prompt: string, + signal?: AbortSignal, ): Promise { const input: UserPromptSubmitInput = { ...this.createBaseInput(HookEventName.UserPromptSubmit), prompt, }; - return this.executeHooks(HookEventName.UserPromptSubmit, input); + return this.executeHooks( + HookEventName.UserPromptSubmit, + input, + undefined, + signal, + ); } /** @@ -80,6 +88,7 @@ export class HookEventHandler { async fireStopEvent( stopHookActive: boolean = false, lastAssistantMessage: string = '', + signal?: AbortSignal, ): Promise { const input: StopInput = { ...this.createBaseInput(HookEventName.Stop), @@ -87,7 +96,7 @@ export class HookEventHandler { last_assistant_message: lastAssistantMessage, }; - return this.executeHooks(HookEventName.Stop, input); + return this.executeHooks(HookEventName.Stop, input, undefined, signal); } /** @@ -99,6 +108,7 @@ export class HookEventHandler { model: string, permissionMode?: PermissionMode, agentType?: AgentType, + signal?: AbortSignal, ): Promise { const input: SessionStartInput = { ...this.createBaseInput(HookEventName.SessionStart), @@ -109,9 +119,14 @@ export class HookEventHandler { }; // Pass source as context for matcher filtering - return this.executeHooks(HookEventName.SessionStart, input, { - trigger: source, - }); + return this.executeHooks( + HookEventName.SessionStart, + input, + { + trigger: source, + }, + signal, + ); } /** @@ -120,6 +135,7 @@ export class HookEventHandler { */ async fireSessionEndEvent( reason: SessionEndReason, + signal?: AbortSignal, ): Promise { const input: SessionEndInput = { ...this.createBaseInput(HookEventName.SessionEnd), @@ -127,9 +143,14 @@ export class HookEventHandler { }; // Pass reason as context for matcher filtering - return this.executeHooks(HookEventName.SessionEnd, input, { - trigger: reason, - }); + return this.executeHooks( + HookEventName.SessionEnd, + input, + { + trigger: reason, + }, + signal, + ); } /** @@ -141,6 +162,7 @@ export class HookEventHandler { toolInput: Record, toolUseId: string, permissionMode: PermissionMode, + signal?: AbortSignal, ): Promise { const input: PreToolUseInput = { ...this.createBaseInput(HookEventName.PreToolUse), @@ -151,9 +173,14 @@ export class HookEventHandler { }; // Pass tool name as context for matcher filtering - return this.executeHooks(HookEventName.PreToolUse, input, { - toolName, - }); + return this.executeHooks( + HookEventName.PreToolUse, + input, + { + toolName, + }, + signal, + ); } /** @@ -166,6 +193,7 @@ export class HookEventHandler { toolResponse: Record, toolUseId: string, permissionMode: PermissionMode, + signal?: AbortSignal, ): Promise { const input: PostToolUseInput = { ...this.createBaseInput(HookEventName.PostToolUse), @@ -177,9 +205,14 @@ export class HookEventHandler { }; // Pass tool name as context for matcher filtering - return this.executeHooks(HookEventName.PostToolUse, input, { - toolName, - }); + return this.executeHooks( + HookEventName.PostToolUse, + input, + { + toolName, + }, + signal, + ); } /** @@ -193,6 +226,7 @@ export class HookEventHandler { errorMessage: string, isInterrupt?: boolean, permissionMode?: PermissionMode, + signal?: AbortSignal, ): Promise { const input: PostToolUseFailureInput = { ...this.createBaseInput(HookEventName.PostToolUseFailure), @@ -205,9 +239,14 @@ export class HookEventHandler { }; // Pass tool name as context for matcher filtering - return this.executeHooks(HookEventName.PostToolUseFailure, input, { - toolName, - }); + return this.executeHooks( + HookEventName.PostToolUseFailure, + input, + { + toolName, + }, + signal, + ); } /** @@ -217,6 +256,7 @@ export class HookEventHandler { async firePreCompactEvent( trigger: PreCompactTrigger, customInstructions: string = '', + signal?: AbortSignal, ): Promise { const input: PreCompactInput = { ...this.createBaseInput(HookEventName.PreCompact), @@ -225,9 +265,14 @@ export class HookEventHandler { }; // Pass trigger as context for matcher filtering - return this.executeHooks(HookEventName.PreCompact, input, { - trigger, - }); + return this.executeHooks( + HookEventName.PreCompact, + input, + { + trigger, + }, + signal, + ); } /** @@ -237,6 +282,7 @@ export class HookEventHandler { message: string, notificationType: NotificationType, title?: string, + signal?: AbortSignal, ): Promise { const input: NotificationInput = { ...this.createBaseInput(HookEventName.Notification), @@ -246,9 +292,14 @@ export class HookEventHandler { }; // Pass notification_type as context for matcher filtering - return this.executeHooks(HookEventName.Notification, input, { - notificationType, - }); + return this.executeHooks( + HookEventName.Notification, + input, + { + notificationType, + }, + signal, + ); } /** @@ -260,6 +311,7 @@ export class HookEventHandler { toolInput: Record, permissionMode: PermissionMode, permissionSuggestions?: PermissionSuggestion[], + signal?: AbortSignal, ): Promise { const input: PermissionRequestInput = { ...this.createBaseInput(HookEventName.PermissionRequest), @@ -270,9 +322,14 @@ export class HookEventHandler { }; // Pass tool name as context for matcher filtering - return this.executeHooks(HookEventName.PermissionRequest, input, { - toolName, - }); + return this.executeHooks( + HookEventName.PermissionRequest, + input, + { + toolName, + }, + signal, + ); } /** @@ -283,6 +340,7 @@ export class HookEventHandler { agentId: string, agentType: AgentType | string, permissionMode: PermissionMode, + signal?: AbortSignal, ): Promise { const input: SubagentStartInput = { ...this.createBaseInput(HookEventName.SubagentStart), @@ -292,9 +350,14 @@ export class HookEventHandler { }; // Pass agentType as context for matcher filtering - return this.executeHooks(HookEventName.SubagentStart, input, { - agentType: String(agentType), - }); + return this.executeHooks( + HookEventName.SubagentStart, + input, + { + agentType: String(agentType), + }, + signal, + ); } /** @@ -308,6 +371,7 @@ export class HookEventHandler { lastAssistantMessage: string, stopHookActive: boolean, permissionMode: PermissionMode, + signal?: AbortSignal, ): Promise { const input: SubagentStopInput = { ...this.createBaseInput(HookEventName.SubagentStop), @@ -320,9 +384,14 @@ export class HookEventHandler { }; // Pass agentType as context for matcher filtering - return this.executeHooks(HookEventName.SubagentStop, input, { - agentType: String(agentType), - }); + return this.executeHooks( + HookEventName.SubagentStop, + input, + { + agentType: String(agentType), + }, + signal, + ); } /** @@ -333,6 +402,7 @@ export class HookEventHandler { eventName: HookEventName, input: HookInput, context?: HookEventContext, + signal?: AbortSignal, ): Promise { try { // Create execution plan @@ -347,12 +417,18 @@ export class HookEventHandler { }; } - const onHookStart = (_config: HookConfig, _index: number) => { - // Hook start event (telemetry removed) + const onHookStart = (config: HookConfig, index: number) => { + const hookName = this.getHookName(config); + debugLogger.debug( + `Hook ${hookName} started for event ${eventName} (${index + 1}/${plan.hookConfigs.length})`, + ); }; - const onHookEnd = (_config: HookConfig, _result: HookExecutionResult) => { - // Hook end event (telemetry removed) + const onHookEnd = (config: HookConfig, result: HookExecutionResult) => { + const hookName = this.getHookName(config); + debugLogger.debug( + `Hook ${hookName} ended for event ${eventName}: ${result.success ? 'success' : 'failed'}`, + ); }; // Execute hooks according to the plan's strategy @@ -363,6 +439,7 @@ export class HookEventHandler { input, onHookStart, onHookEnd, + signal, ) : await this.hookRunner.executeHooksParallel( plan.hookConfigs, @@ -370,6 +447,7 @@ export class HookEventHandler { input, onHookStart, onHookEnd, + signal, ); // Aggregate results @@ -381,6 +459,9 @@ export class HookEventHandler { // Process common hook output fields centrally this.processCommonHookOutputFields(aggregated); + // Log hook execution for telemetry + this.logHookExecution(eventName, input, results, aggregated); + return aggregated; } catch (error) { debugLogger.error(`Hook event bus error for ${eventName}: ${error}`); @@ -426,8 +507,6 @@ export class HookEventHandler { debugLogger.warn(`Hook system message: ${systemMessage}`); } - // Handle suppressOutput - already handled by not logging above when true - // Handle continue=false - this should stop the entire agent execution if (aggregated.finalOutput.continue === false) { const stopReason = @@ -435,10 +514,84 @@ export class HookEventHandler { aggregated.finalOutput.reason || 'No reason provided'; debugLogger.debug(`Hook requested to stop execution: ${stopReason}`); - - // Note: The actual stopping of execution must be handled by integration points - // as they need to interpret this signal in the context of their specific workflow - // This is just logging the request centrally } } + + /** + * Log hook execution for observability + */ + private logHookExecution( + eventName: HookEventName, + input: HookInput, + results: HookExecutionResult[], + aggregated: AggregatedHookResult, + ): void { + const failedHooks = results.filter((r) => !r.success); + const successCount = results.length - failedHooks.length; + const errorCount = failedHooks.length; + + if (errorCount > 0) { + const failedNames = failedHooks + .map((r) => this.getHookNameFromResult(r)) + .join(', '); + + debugLogger.warn( + `Hook(s) [${failedNames}] failed for event ${eventName}. Check debug logs for more details.`, + ); + } else { + debugLogger.debug( + `Hook execution for ${eventName}: ${successCount} hooks executed successfully, ` + + `total duration: ${aggregated.totalDuration}ms`, + ); + } + + for (const result of results) { + const hookName = this.getHookNameFromResult(result); + const hookType = this.getHookTypeFromResult(result); + + const hookCallEvent = new HookCallEvent( + eventName, + hookType, + hookName, + { ...input }, + result.duration, + result.success, + result.output ? { ...result.output } : undefined, + result.exitCode, + result.stdout, + result.stderr, + result.error?.message, + ); + + logHookCall(this.config, hookCallEvent); + } + + for (const error of aggregated.errors) { + debugLogger.warn(`Hook execution error: ${error.message}`); + } + } + + /** + * Get hook name from config for display or telemetry + */ + private getHookName(config: HookConfig): string { + if (config.type === 'command') { + return config.name || config.command || 'unknown-command'; + } + return config.name || 'unknown-hook'; + } + + /** + * Get hook name from execution result for telemetry + */ + private getHookNameFromResult(result: HookExecutionResult): string { + return this.getHookName(result.hookConfig); + } + + /** + * Get hook type from execution result for telemetry + */ + private getHookTypeFromResult(result: HookExecutionResult): 'command' { + return result.hookConfig.type as 'command'; + } } diff --git a/packages/core/src/hooks/hookRunner.ts b/packages/core/src/hooks/hookRunner.ts index 26a09f350..d7d11f17d 100644 --- a/packages/core/src/hooks/hookRunner.ts +++ b/packages/core/src/hooks/hookRunner.ts @@ -46,20 +46,38 @@ const EXIT_CODE_NON_BLOCKING_ERROR = 1; export class HookRunner { /** * Execute a single hook + * @param hookConfig Hook configuration + * @param eventName Event name + * @param input Hook input + * @param signal Optional AbortSignal to cancel hook execution */ async executeHook( hookConfig: HookConfig, eventName: HookEventName, input: HookInput, + signal?: AbortSignal, ): Promise { const startTime = Date.now(); + // Check if already aborted before starting + if (signal?.aborted) { + const hookId = hookConfig.name || hookConfig.command || 'unknown'; + return { + hookConfig, + eventName, + success: false, + error: new Error(`Hook execution cancelled (aborted): ${hookId}`), + duration: 0, + }; + } + try { return await this.executeCommandHook( hookConfig, eventName, input, startTime, + signal, ); } catch (error) { const duration = Date.now() - startTime; @@ -79,6 +97,7 @@ export class HookRunner { /** * Execute multiple hooks in parallel + * @param signal Optional AbortSignal to cancel hook execution */ async executeHooksParallel( hookConfigs: HookConfig[], @@ -86,10 +105,11 @@ export class HookRunner { input: HookInput, onHookStart?: (config: HookConfig, index: number) => void, onHookEnd?: (config: HookConfig, result: HookExecutionResult) => void, + signal?: AbortSignal, ): Promise { const promises = hookConfigs.map(async (config, index) => { onHookStart?.(config, index); - const result = await this.executeHook(config, eventName, input); + const result = await this.executeHook(config, eventName, input, signal); onHookEnd?.(config, result); return result; }); @@ -99,6 +119,7 @@ export class HookRunner { /** * Execute multiple hooks sequentially + * @param signal Optional AbortSignal to cancel hook execution */ async executeHooksSequential( hookConfigs: HookConfig[], @@ -106,14 +127,24 @@ export class HookRunner { input: HookInput, onHookStart?: (config: HookConfig, index: number) => void, onHookEnd?: (config: HookConfig, result: HookExecutionResult) => void, + signal?: AbortSignal, ): Promise { const results: HookExecutionResult[] = []; let currentInput = input; for (let i = 0; i < hookConfigs.length; i++) { + // Check if aborted before each hook + if (signal?.aborted) { + break; + } const config = hookConfigs[i]; onHookStart?.(config, i); - const result = await this.executeHook(config, eventName, currentInput); + const result = await this.executeHook( + config, + eventName, + currentInput, + signal, + ); onHookEnd?.(config, result); results.push(result); @@ -184,12 +215,18 @@ export class HookRunner { /** * Execute a command hook + * @param hookConfig Hook configuration + * @param eventName Event name + * @param input Hook input + * @param startTime Start time for duration calculation + * @param signal Optional AbortSignal to cancel hook execution */ private async executeCommandHook( hookConfig: HookConfig, eventName: HookEventName, input: HookInput, startTime: number, + signal?: AbortSignal, ): Promise { const timeout = hookConfig.timeout ?? DEFAULT_HOOK_TIMEOUT; @@ -212,6 +249,7 @@ export class HookRunner { let stdout = ''; let stderr = ''; let timedOut = false; + let aborted = false; const shellConfig = getShellConfiguration(); const command = this.expandCommand( @@ -239,19 +277,36 @@ export class HookRunner { }, ); + // Helper to kill child process + const killChild = () => { + if (!child.killed) { + child.kill('SIGTERM'); + // Force kill after 2 seconds + setTimeout(() => { + if (!child.killed) { + child.kill('SIGKILL'); + } + }, 2000); + } + }; + // Set up timeout const timeoutHandle = setTimeout(() => { timedOut = true; - child.kill('SIGTERM'); - - // Force kill after 5 seconds - setTimeout(() => { - if (!child.killed) { - child.kill('SIGKILL'); - } - }, 5000); + killChild(); }, timeout); + // Set up abort handler + const abortHandler = () => { + aborted = true; + clearTimeout(timeoutHandle); + killChild(); + }; + + if (signal) { + signal.addEventListener('abort', abortHandler); + } + // Send input to stdin if (child.stdin) { child.stdin.on('error', (err: NodeJS.ErrnoException) => { @@ -303,8 +358,25 @@ export class HookRunner { // Handle process exit child.on('close', (exitCode) => { clearTimeout(timeoutHandle); + // Clean up abort listener + if (signal) { + signal.removeEventListener('abort', abortHandler); + } const duration = Date.now() - startTime; + if (aborted) { + resolve({ + hookConfig, + eventName, + success: false, + error: new Error('Hook execution cancelled (aborted)'), + stdout, + stderr, + duration, + }); + return; + } + if (timedOut) { resolve({ hookConfig, diff --git a/packages/core/src/hooks/hookSystem.test.ts b/packages/core/src/hooks/hookSystem.test.ts index b0741a829..0bdbbaf05 100644 --- a/packages/core/src/hooks/hookSystem.test.ts +++ b/packages/core/src/hooks/hookSystem.test.ts @@ -65,6 +65,7 @@ describe('HookSystem', () => { initialize: vi.fn().mockResolvedValue(undefined), setHookEnabled: vi.fn(), getAllHooks: vi.fn().mockReturnValue([]), + getHooksForEvent: vi.fn().mockReturnValue([]), } as unknown as HookRegistry; mockHookRunner = { @@ -186,6 +187,52 @@ describe('HookSystem', () => { }); }); + describe('hasHooksForEvent', () => { + it('should return false when no hooks are registered for the event', () => { + vi.mocked(mockHookRegistry.getHooksForEvent).mockReturnValue([]); + + expect(hookSystem.hasHooksForEvent('Stop')).toBe(false); + expect(mockHookRegistry.getHooksForEvent).toHaveBeenCalledWith('Stop'); + }); + + it('should return true when hooks are registered for the event', () => { + vi.mocked(mockHookRegistry.getHooksForEvent).mockReturnValue([ + { + config: { + type: HookType.Command, + command: 'echo test', + source: HooksConfigSource.Project, + }, + source: HooksConfigSource.Project, + eventName: HookEventName.Stop, + enabled: true, + }, + ]); + + expect(hookSystem.hasHooksForEvent('Stop')).toBe(true); + }); + + it('should check the correct event name for UserPromptSubmit', () => { + vi.mocked(mockHookRegistry.getHooksForEvent).mockReturnValue([]); + + hookSystem.hasHooksForEvent('UserPromptSubmit'); + + expect(mockHookRegistry.getHooksForEvent).toHaveBeenCalledWith( + 'UserPromptSubmit', + ); + }); + + it('should check the correct event name for SessionEnd', () => { + vi.mocked(mockHookRegistry.getHooksForEvent).mockReturnValue([]); + + hookSystem.hasHooksForEvent('SessionEnd'); + + expect(mockHookRegistry.getHooksForEvent).toHaveBeenCalledWith( + 'SessionEnd', + ); + }); + }); + describe('fireStopEvent', () => { it('should fire stop event and return output', async () => { const mockResult = { @@ -207,6 +254,7 @@ describe('HookSystem', () => { expect(mockHookEventHandler.fireStopEvent).toHaveBeenCalledWith( true, 'last message', + undefined, ); expect(result).toBeDefined(); }); @@ -228,6 +276,7 @@ describe('HookSystem', () => { expect(mockHookEventHandler.fireStopEvent).toHaveBeenCalledWith( false, '', + undefined, ); }); @@ -269,7 +318,7 @@ describe('HookSystem', () => { expect( mockHookEventHandler.fireUserPromptSubmitEvent, - ).toHaveBeenCalledWith('test prompt'); + ).toHaveBeenCalledWith('test prompt', undefined); expect(result).toBeDefined(); }); @@ -291,7 +340,7 @@ describe('HookSystem', () => { expect( mockHookEventHandler.fireUserPromptSubmitEvent, - ).toHaveBeenCalledWith('my custom prompt'); + ).toHaveBeenCalledWith('my custom prompt', undefined); }); it('should return undefined when no final output', async () => { @@ -382,6 +431,7 @@ describe('HookSystem', () => { 'gpt-4', undefined, undefined, + undefined, ); expect(result).toBeDefined(); }); @@ -412,6 +462,7 @@ describe('HookSystem', () => { 'claude-3', PermissionMode.AutoEdit, AgentType.Custom, + undefined, ); }); @@ -458,6 +509,7 @@ describe('HookSystem', () => { expect(mockHookEventHandler.fireSessionEndEvent).toHaveBeenCalledWith( SessionEndReason.Other, + undefined, ); expect(result).toBeDefined(); }); @@ -480,6 +532,7 @@ describe('HookSystem', () => { expect(mockHookEventHandler.fireSessionEndEvent).toHaveBeenCalledWith( SessionEndReason.Other, + undefined, ); }); @@ -531,6 +584,7 @@ describe('HookSystem', () => { { command: 'ls' }, 'toolu_test123', PermissionMode.AutoEdit, + undefined, ); expect(result).toBeDefined(); }); @@ -561,6 +615,7 @@ describe('HookSystem', () => { { path: '/test.txt', content: 'test' }, 'toolu_test456', PermissionMode.Yolo, + undefined, ); }); @@ -674,6 +729,7 @@ describe('HookSystem', () => { { output: 'file1.txt\nfile2.txt' }, 'toolu_test123', PermissionMode.AutoEdit, + undefined, ); expect(result).toBeDefined(); }); @@ -706,6 +762,7 @@ describe('HookSystem', () => { { content: 'file content' }, 'toolu_test456', PermissionMode.Plan, + undefined, ); }); @@ -794,6 +851,7 @@ describe('HookSystem', () => { 'Command not found', false, PermissionMode.AutoEdit, + undefined, ); expect(result).toBeDefined(); }); @@ -830,6 +888,7 @@ describe('HookSystem', () => { 'Permission denied', true, PermissionMode.Yolo, + undefined, ); }); @@ -861,6 +920,7 @@ describe('HookSystem', () => { 'Error occurred', undefined, undefined, + undefined, ); }); @@ -941,6 +1001,7 @@ describe('HookSystem', () => { expect(mockHookEventHandler.firePreCompactEvent).toHaveBeenCalledWith( PreCompactTrigger.Auto, '', + undefined, ); expect(result).toBeDefined(); }); @@ -964,6 +1025,7 @@ describe('HookSystem', () => { expect(mockHookEventHandler.firePreCompactEvent).toHaveBeenCalledWith( PreCompactTrigger.Manual, '', + undefined, ); }); @@ -989,6 +1051,7 @@ describe('HookSystem', () => { expect(mockHookEventHandler.firePreCompactEvent).toHaveBeenCalledWith( PreCompactTrigger.Auto, 'Custom compression instructions', + undefined, ); }); @@ -1065,6 +1128,7 @@ describe('HookSystem', () => { 'Test notification message', NotificationType.PermissionPrompt, 'Permission needed', + undefined, ); expect(result).toBeDefined(); }); @@ -1093,6 +1157,7 @@ describe('HookSystem', () => { 'Qwen Code is waiting for your input', NotificationType.IdlePrompt, 'Waiting for input', + undefined, ); }); @@ -1119,6 +1184,7 @@ describe('HookSystem', () => { 'Authentication successful', NotificationType.AuthSuccess, undefined, + undefined, ); }); @@ -1194,6 +1260,7 @@ describe('HookSystem', () => { 'Dialog shown to user', NotificationType.ElicitationDialog, 'Dialog', + undefined, ); }); }); @@ -1226,6 +1293,7 @@ describe('HookSystem', () => { { command: 'ls -la' }, PermissionMode.Default, undefined, + undefined, ); expect(result).toBeDefined(); // Type assertion needed because getPermissionDecision is specific to PermissionRequestHookOutput @@ -1259,6 +1327,7 @@ describe('HookSystem', () => { { command: 'npm test' }, PermissionMode.Default, suggestions, + undefined, ); }); @@ -1354,6 +1423,7 @@ describe('HookSystem', () => { 'agent-123', 'code-reviewer', PermissionMode.Default, + undefined, ); expect(result).toBeDefined(); }); @@ -1382,6 +1452,7 @@ describe('HookSystem', () => { 'agent-456', AgentType.Bash, PermissionMode.Yolo, + undefined, ); }); @@ -1468,6 +1539,7 @@ describe('HookSystem', () => { 'Final output from subagent', false, PermissionMode.Default, + undefined, ); expect(result).toBeDefined(); }); @@ -1502,6 +1574,7 @@ describe('HookSystem', () => { 'last message from agent', true, PermissionMode.Plan, + undefined, ); }); diff --git a/packages/core/src/hooks/hookSystem.ts b/packages/core/src/hooks/hookSystem.ts index 4716a0c84..03d6eebfc 100644 --- a/packages/core/src/hooks/hookSystem.ts +++ b/packages/core/src/hooks/hookSystem.ts @@ -22,6 +22,7 @@ import type { PreCompactTrigger, NotificationType, PermissionSuggestion, + HookEventName, } from './types.js'; const debugLogger = createDebugLogger('TRUSTED_HOOKS'); @@ -87,11 +88,25 @@ export class HookSystem { return this.hookRegistry.getAllHooks(); } + /** + * Check if there are any enabled hooks registered for a specific event. + * This is a fast-path check to avoid expensive MessageBus round-trips + * when no hooks are configured for a given event. + */ + hasHooksForEvent(eventName: string): boolean { + return ( + this.hookRegistry.getHooksForEvent(eventName as HookEventName).length > 0 + ); + } + async fireUserPromptSubmitEvent( prompt: string, + signal?: AbortSignal, ): Promise { - const result = - await this.hookEventHandler.fireUserPromptSubmitEvent(prompt); + const result = await this.hookEventHandler.fireUserPromptSubmitEvent( + prompt, + signal, + ); return result.finalOutput ? createHookOutput('UserPromptSubmit', result.finalOutput) : undefined; @@ -100,10 +115,12 @@ export class HookSystem { async fireStopEvent( stopHookActive: boolean = false, lastAssistantMessage: string = '', + signal?: AbortSignal, ): Promise { const result = await this.hookEventHandler.fireStopEvent( stopHookActive, lastAssistantMessage, + signal, ); return result.finalOutput ? createHookOutput('Stop', result.finalOutput) @@ -115,12 +132,14 @@ export class HookSystem { model: string, permissionMode?: PermissionMode, agentType?: AgentType, + signal?: AbortSignal, ): Promise { const result = await this.hookEventHandler.fireSessionStartEvent( source, model, permissionMode, agentType, + signal, ); return result.finalOutput ? createHookOutput('SessionStart', result.finalOutput) @@ -129,8 +148,12 @@ export class HookSystem { async fireSessionEndEvent( reason: SessionEndReason, + signal?: AbortSignal, ): Promise { - const result = await this.hookEventHandler.fireSessionEndEvent(reason); + const result = await this.hookEventHandler.fireSessionEndEvent( + reason, + signal, + ); return result.finalOutput ? createHookOutput('SessionEnd', result.finalOutput) : undefined; @@ -144,12 +167,14 @@ export class HookSystem { toolInput: Record, toolUseId: string, permissionMode: PermissionMode, + signal?: AbortSignal, ): Promise { const result = await this.hookEventHandler.firePreToolUseEvent( toolName, toolInput, toolUseId, permissionMode, + signal, ); return result.finalOutput ? createHookOutput('PreToolUse', result.finalOutput) @@ -165,6 +190,7 @@ export class HookSystem { toolResponse: Record, toolUseId: string, permissionMode: PermissionMode, + signal?: AbortSignal, ): Promise { const result = await this.hookEventHandler.firePostToolUseEvent( toolName, @@ -172,6 +198,7 @@ export class HookSystem { toolResponse, toolUseId, permissionMode, + signal, ); return result.finalOutput ? createHookOutput('PostToolUse', result.finalOutput) @@ -188,6 +215,7 @@ export class HookSystem { errorMessage: string, isInterrupt?: boolean, permissionMode?: PermissionMode, + signal?: AbortSignal, ): Promise { const result = await this.hookEventHandler.firePostToolUseFailureEvent( toolUseId, @@ -196,6 +224,7 @@ export class HookSystem { errorMessage, isInterrupt, permissionMode, + signal, ); return result.finalOutput ? createHookOutput('PostToolUseFailure', result.finalOutput) @@ -208,10 +237,12 @@ export class HookSystem { async firePreCompactEvent( trigger: PreCompactTrigger, customInstructions: string = '', + signal?: AbortSignal, ): Promise { const result = await this.hookEventHandler.firePreCompactEvent( trigger, customInstructions, + signal, ); return result.finalOutput ? createHookOutput('PreCompact', result.finalOutput) @@ -225,11 +256,13 @@ export class HookSystem { message: string, notificationType: NotificationType, title?: string, + signal?: AbortSignal, ): Promise { const result = await this.hookEventHandler.fireNotificationEvent( message, notificationType, title, + signal, ); return result.finalOutput ? createHookOutput('Notification', result.finalOutput) @@ -243,11 +276,13 @@ export class HookSystem { agentId: string, agentType: AgentType | string, permissionMode: PermissionMode, + signal?: AbortSignal, ): Promise { const result = await this.hookEventHandler.fireSubagentStartEvent( agentId, agentType, permissionMode, + signal, ); return result.finalOutput ? createHookOutput('SubagentStart', result.finalOutput) @@ -264,6 +299,7 @@ export class HookSystem { lastAssistantMessage: string, stopHookActive: boolean, permissionMode: PermissionMode, + signal?: AbortSignal, ): Promise { const result = await this.hookEventHandler.fireSubagentStopEvent( agentId, @@ -272,6 +308,7 @@ export class HookSystem { lastAssistantMessage, stopHookActive, permissionMode, + signal, ); return result.finalOutput ? createHookOutput('SubagentStop', result.finalOutput) @@ -286,12 +323,14 @@ export class HookSystem { toolInput: Record, permissionMode: PermissionMode, permissionSuggestions?: PermissionSuggestion[], + signal?: AbortSignal, ): Promise { const result = await this.hookEventHandler.firePermissionRequestEvent( toolName, toolInput, permissionMode, permissionSuggestions, + signal, ); return result.finalOutput ? createHookOutput('PermissionRequest', result.finalOutput) diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 2a97f731b..83ab203ca 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -55,6 +55,7 @@ export * from './output/types.js'; export * from './core/client.js'; export * from './core/contentGenerator.js'; export * from './core/coreToolScheduler.js'; +export * from './core/permission-helpers.js'; export * from './core/geminiChat.js'; export * from './core/geminiRequest.js'; export * from './core/logger.js'; @@ -127,7 +128,6 @@ export * from './ide/types.js'; export * from './lsp/constants.js'; export * from './lsp/LspConfigLoader.js'; export * from './lsp/LspConnectionFactory.js'; -export * from './lsp/LspLanguageDetector.js'; export * from './lsp/LspResponseNormalizer.js'; export * from './lsp/LspServerManager.js'; export * from './lsp/NativeLspClient.js'; @@ -217,6 +217,7 @@ export * from './utils/pathReader.js'; export * from './utils/paths.js'; export * from './utils/projectSummary.js'; export * from './utils/promptIdContext.js'; +export * from './utils/proxyUtils.js'; export * from './utils/quotaErrorDetection.js'; export * from './utils/readManyFiles.js'; export * from './utils/request-tokenizer/supportedImageFormats.js'; @@ -260,5 +261,6 @@ export type { HookRegistryEntry } from './hooks/index.js'; // Export hook triggers for notification hooks export { fireNotificationHook, + firePermissionRequestHook, type NotificationHookResult, } from './core/toolHookTriggers.js'; diff --git a/packages/core/src/lsp/LspConfigLoader.test.ts b/packages/core/src/lsp/LspConfigLoader.test.ts index 9f0ee8548..46b221878 100644 --- a/packages/core/src/lsp/LspConfigLoader.test.ts +++ b/packages/core/src/lsp/LspConfigLoader.test.ts @@ -9,6 +9,104 @@ import mock from 'mock-fs'; import { LspConfigLoader } from './LspConfigLoader.js'; import type { Extension } from '../extension/extensionManager.js'; +describe('LspConfigLoader config-driven behavior', () => { + const workspaceRoot = '/workspace'; + + it('does not generate any presets when no user or extension config provided', () => { + const loader = new LspConfigLoader(workspaceRoot); + // Even if languages are detected, no built-in presets should be generated + const configs = loader.mergeConfigs(['java', 'cpp', 'typescript'], [], []); + + expect(configs).toHaveLength(0); + }); + + it('respects user-provided configs via .lsp.json', () => { + const loader = new LspConfigLoader(workspaceRoot); + const userConfigs = [ + { + name: 'jdtls', + languages: ['java'], + command: 'jdtls', + args: [], + transport: 'stdio' as const, + initializationOptions: {}, + rootUri: 'file:///workspace', + workspaceFolder: workspaceRoot, + trustRequired: true, + }, + ]; + + const configs = loader.mergeConfigs(['java'], [], userConfigs); + + expect(configs).toHaveLength(1); + expect(configs[0]?.name).toBe('jdtls'); + expect(configs[0]?.languages).toEqual(['java']); + }); + + it('respects extension-provided configs', () => { + const loader = new LspConfigLoader(workspaceRoot); + const extensionConfigs = [ + { + name: 'clangd', + languages: ['cpp', 'c'], + command: 'clangd', + args: ['--background-index'], + transport: 'stdio' as const, + initializationOptions: {}, + rootUri: 'file:///workspace', + workspaceFolder: workspaceRoot, + trustRequired: true, + }, + ]; + + const configs = loader.mergeConfigs(['cpp'], extensionConfigs, []); + + expect(configs).toHaveLength(1); + expect(configs[0]?.name).toBe('clangd'); + expect(configs[0]?.command).toBe('clangd'); + }); + + it('user configs override extension configs with same name', () => { + const loader = new LspConfigLoader(workspaceRoot); + const extensionConfigs = [ + { + name: 'jdtls', + languages: ['java'], + command: 'jdtls', + args: [], + transport: 'stdio' as const, + initializationOptions: {}, + rootUri: 'file:///workspace', + workspaceFolder: workspaceRoot, + trustRequired: true, + }, + ]; + const userConfigs = [ + { + name: 'jdtls', + languages: ['java'], + command: '/custom/path/jdtls', + args: ['--custom-flag'], + transport: 'stdio' as const, + initializationOptions: {}, + rootUri: 'file:///workspace', + workspaceFolder: workspaceRoot, + trustRequired: true, + }, + ]; + + const configs = loader.mergeConfigs( + ['java'], + extensionConfigs, + userConfigs, + ); + + expect(configs).toHaveLength(1); + expect(configs[0]?.command).toBe('/custom/path/jdtls'); + expect(configs[0]?.args).toEqual(['--custom-flag']); + }); +}); + describe('LspConfigLoader extension configs', () => { const workspaceRoot = '/workspace'; const extensionPath = '/extensions/ts-plugin'; diff --git a/packages/core/src/lsp/LspConfigLoader.ts b/packages/core/src/lsp/LspConfigLoader.ts index 61ffad8b5..0a3b384c7 100644 --- a/packages/core/src/lsp/LspConfigLoader.ts +++ b/packages/core/src/lsp/LspConfigLoader.ts @@ -106,18 +106,17 @@ export class LspConfigLoader { } /** - * Merge configs: built-in presets + extension configs + user configs + * Merge configs: extension configs + user configs + * Note: Built-in presets are disabled. LSP servers must be explicitly configured + * by the user via .lsp.json or through extensions. */ mergeConfigs( - detectedLanguages: string[], + _detectedLanguages: string[], extensionConfigs: LspServerConfig[], userConfigs: LspServerConfig[], ): LspServerConfig[] { - // Built-in preset configurations - const presets = this.getBuiltInPresets(detectedLanguages); - // Merge configs, user configs take priority - const mergedConfigs = [...presets]; + const mergedConfigs: LspServerConfig[] = []; const applyConfigs = (configs: LspServerConfig[]) => { for (const config of configs) { @@ -161,71 +160,6 @@ export class LspConfigLoader { return overrides; } - /** - * Get built-in preset configurations - */ - private getBuiltInPresets(detectedLanguages: string[]): LspServerConfig[] { - const presets: LspServerConfig[] = []; - - // Convert directory path to file URI format - const rootUri = pathToFileURL(this.workspaceRoot).toString(); - - // Generate corresponding LSP server config based on detected languages - if ( - detectedLanguages.includes('typescript') || - detectedLanguages.includes('javascript') - ) { - presets.push({ - name: 'typescript-language-server', - languages: [ - 'typescript', - 'javascript', - 'typescriptreact', - 'javascriptreact', - ], - command: 'typescript-language-server', - args: ['--stdio'], - transport: 'stdio', - initializationOptions: {}, - rootUri, - workspaceFolder: this.workspaceRoot, - trustRequired: true, - }); - } - - if (detectedLanguages.includes('python')) { - presets.push({ - name: 'pylsp', - languages: ['python'], - command: 'pylsp', - args: [], - transport: 'stdio', - initializationOptions: {}, - rootUri, - workspaceFolder: this.workspaceRoot, - trustRequired: true, - }); - } - - if (detectedLanguages.includes('go')) { - presets.push({ - name: 'gopls', - languages: ['go'], - command: 'gopls', - args: [], - transport: 'stdio', - initializationOptions: {}, - rootUri, - workspaceFolder: this.workspaceRoot, - trustRequired: true, - }); - } - - // Additional language presets can be added as needed - - return presets; - } - /** * Parse configuration source and extract server configs. * Expects basic format keyed by language identifier. diff --git a/packages/core/src/lsp/LspLanguageDetector.ts b/packages/core/src/lsp/LspLanguageDetector.ts deleted file mode 100644 index 9c3f96e73..000000000 --- a/packages/core/src/lsp/LspLanguageDetector.ts +++ /dev/null @@ -1,226 +0,0 @@ -/** - * @license - * Copyright 2025 Qwen Team - * SPDX-License-Identifier: Apache-2.0 - */ - -/** - * LSP Language Detector - * - * Detects programming languages in a workspace by analyzing file extensions - * and root marker files (e.g., package.json, tsconfig.json). - */ - -import * as fs from 'node:fs'; -import * as path from 'path'; -import { globSync } from 'glob'; -import type { FileDiscoveryService } from '../services/fileDiscoveryService.js'; -import type { WorkspaceContext } from '../utils/workspaceContext.js'; - -/** - * Extension to language ID mapping - */ -const DEFAULT_EXTENSION_TO_LANGUAGE: Record = { - js: 'javascript', - ts: 'typescript', - jsx: 'javascriptreact', - tsx: 'typescriptreact', - py: 'python', - go: 'go', - rs: 'rust', - java: 'java', - cpp: 'cpp', - c: 'c', - php: 'php', - rb: 'ruby', - cs: 'csharp', - vue: 'vue', - svelte: 'svelte', - html: 'html', - css: 'css', - json: 'json', - yaml: 'yaml', - yml: 'yaml', -}; - -/** - * Root marker file to language ID mapping - */ -const MARKER_TO_LANGUAGE: Record = { - 'package.json': 'javascript', - 'tsconfig.json': 'typescript', - 'pyproject.toml': 'python', - 'go.mod': 'go', - 'Cargo.toml': 'rust', - 'pom.xml': 'java', - 'build.gradle': 'java', - 'composer.json': 'php', - Gemfile: 'ruby', - '*.sln': 'csharp', - 'mix.exs': 'elixir', - 'deno.json': 'deno', -}; - -/** - * Common root marker files to look for - */ -const COMMON_MARKERS = [ - 'package.json', - 'tsconfig.json', - 'pyproject.toml', - 'go.mod', - 'Cargo.toml', - 'pom.xml', - 'build.gradle', - 'composer.json', - 'Gemfile', - 'mix.exs', - 'deno.json', -]; - -/** - * Default exclude patterns for file search - */ -const DEFAULT_EXCLUDE_PATTERNS = [ - '**/node_modules/**', - '**/.git/**', - '**/dist/**', - '**/build/**', -]; - -/** - * Detects programming languages in a workspace. - */ -export class LspLanguageDetector { - constructor( - private readonly workspaceContext: WorkspaceContext, - private readonly fileDiscoveryService: FileDiscoveryService, - ) {} - - /** - * Detect programming languages in workspace by analyzing files and markers. - * Returns languages sorted by frequency (most common first). - * - * @param extensionOverrides - Custom extension to language mappings - * @returns Array of detected language IDs - */ - async detectLanguages( - extensionOverrides: Record = {}, - ): Promise { - const extensionMap = this.getExtensionToLanguageMap(extensionOverrides); - const extensions = Object.keys(extensionMap); - const patterns = - extensions.length > 0 ? [`**/*.{${extensions.join(',')}}`] : ['**/*']; - - const files = new Set(); - const searchRoots = this.workspaceContext.getDirectories(); - - for (const root of searchRoots) { - for (const pattern of patterns) { - try { - const matches = globSync(pattern, { - cwd: root, - ignore: DEFAULT_EXCLUDE_PATTERNS, - absolute: true, - nodir: true, - }); - - for (const match of matches) { - if (this.fileDiscoveryService.shouldIgnoreFile(match)) { - continue; - } - files.add(match); - } - } catch { - // Ignore glob errors for missing/invalid directories - } - } - } - - // Count files per language - const languageCounts = new Map(); - for (const file of Array.from(files)) { - const ext = path.extname(file).slice(1).toLowerCase(); - if (ext) { - const lang = this.mapExtensionToLanguage(ext, extensionMap); - if (lang) { - languageCounts.set(lang, (languageCounts.get(lang) || 0) + 1); - } - } - } - - // Also detect languages via root marker files - const rootMarkers = await this.detectRootMarkers(); - for (const marker of rootMarkers) { - const lang = this.mapMarkerToLanguage(marker); - if (lang) { - // Give higher weight to config files - const currentCount = languageCounts.get(lang) || 0; - languageCounts.set(lang, currentCount + 100); - } - } - - // Return languages sorted by count (descending) - return Array.from(languageCounts.entries()) - .sort((a, b) => b[1] - a[1]) - .map(([lang]) => lang); - } - - /** - * Detect root marker files in workspace directories - */ - private async detectRootMarkers(): Promise { - const markers = new Set(); - - for (const root of this.workspaceContext.getDirectories()) { - for (const marker of COMMON_MARKERS) { - try { - const fullPath = path.join(root, marker); - if (fs.existsSync(fullPath)) { - markers.add(marker); - } - } catch { - // ignore missing files - } - } - } - - return Array.from(markers); - } - - /** - * Map file extension to programming language ID - */ - private mapExtensionToLanguage( - ext: string, - extensionMap: Record, - ): string | null { - return extensionMap[ext] || null; - } - - /** - * Get extension to language mapping with overrides applied - */ - private getExtensionToLanguageMap( - extensionOverrides: Record = {}, - ): Record { - const extToLang = { ...DEFAULT_EXTENSION_TO_LANGUAGE }; - - for (const [key, value] of Object.entries(extensionOverrides)) { - const normalized = key.startsWith('.') ? key.slice(1) : key; - if (!normalized) { - continue; - } - extToLang[normalized.toLowerCase()] = value; - } - - return extToLang; - } - - /** - * Map root marker file to programming language ID - */ - private mapMarkerToLanguage(marker: string): string | null { - return MARKER_TO_LANGUAGE[marker] || null; - } -} diff --git a/packages/core/src/lsp/LspResponseNormalizer.ts b/packages/core/src/lsp/LspResponseNormalizer.ts index 9a9a478c0..a890c32bc 100644 --- a/packages/core/src/lsp/LspResponseNormalizer.ts +++ b/packages/core/src/lsp/LspResponseNormalizer.ts @@ -522,12 +522,21 @@ export class LspResponseNormalizer { itemObj['range'] ?? undefined) as { start?: unknown; end?: unknown } | undefined; - if (!locationObj['uri'] || !range?.start || !range?.end) { + // Only require uri; range is optional per LSP 3.17 WorkspaceSymbol spec + // where location may be { uri } without a range. + if (!locationObj['uri']) { return null; } - const start = range.start as { line?: number; character?: number }; - const end = range.end as { line?: number; character?: number }; + // LSP 3.17 WorkspaceSymbol format may have location with only uri (no range). + // Servers like jdtls use this format, requiring a workspaceSymbol/resolve call + // for the full range. Default to file start when range is absent. + const start = (range?.start as + | { line?: number; character?: number } + | undefined) ?? { line: 0, character: 0 }; + const end = (range?.end as + | { line?: number; character?: number } + | undefined) ?? { line: 0, character: 0 }; return { name: (itemObj['name'] ?? itemObj['label'] ?? 'symbol') as string, diff --git a/packages/core/src/lsp/LspServerManager.ts b/packages/core/src/lsp/LspServerManager.ts index d38b23851..544dcd6ef 100644 --- a/packages/core/src/lsp/LspServerManager.ts +++ b/packages/core/src/lsp/LspServerManager.ts @@ -94,20 +94,24 @@ export class LspServerManager { /** * Ensure tsserver has at least one file open so navto/navtree requests succeed. * Sets warmedUp flag only after successful warm-up to allow retry on failure. + * + * @param handle - The LSP server handle + * @param force - Force re-warmup even if already warmed up + * @returns The URI of the file opened during warmup, or undefined if no file was opened */ async warmupTypescriptServer( handle: LspServerHandle, force = false, - ): Promise { + ): Promise { if (!handle.connection || !this.isTypescriptServer(handle)) { - return; + return undefined; } if (handle.warmedUp && !force) { - return; + return undefined; } const tsFile = this.findFirstTypescriptFile(); if (!tsFile) { - return; + return undefined; } const uri = pathToFileURL(tsFile).toString(); @@ -138,9 +142,11 @@ export class LspServerManager { ); // Only mark as warmed up after successful completion handle.warmedUp = true; + return uri; } catch (error) { // Do not set warmedUp to true on failure, allowing retry debugLogger.warn('TypeScript server warm-up failed:', error); + return undefined; } } @@ -559,40 +565,22 @@ export class LspServerManager { }); } - // Warm up TypeScript server by opening a workspace file so it can create a project. - if ( - config.name.includes('typescript') || - (config.command?.includes('typescript') ?? false) - ) { - try { - const tsFile = this.findFirstTypescriptFile(); - if (tsFile) { - const uri = pathToFileURL(tsFile).toString(); - const languageId = tsFile.endsWith('.tsx') - ? 'typescriptreact' - : 'typescript'; - const text = fs.readFileSync(tsFile, 'utf-8'); - connection.connection.send({ - jsonrpc: '2.0', - method: 'textDocument/didOpen', - params: { - textDocument: { - uri, - languageId, - version: 1, - text, - }, - }, - }); - } - } catch (error) { - debugLogger.warn('TypeScript LSP warm-up failed:', error); - } - } + // Note: TypeScript server warm-up is handled by warmupTypescriptServer() + // which is called before every LSP request. This avoids duplicate + // textDocument/didOpen notifications that aren't tracked in openedDocuments. } /** - * Check if command exists + * Check if command exists by spawning it with --version. + * Only returns false when the spawn itself fails (e.g. ENOENT). + * A timeout means the process started successfully (command exists) + * but didn't exit in time — common for servers like jdtls that + * don't support --version and start their full runtime instead. + * + * @param command - The command to check + * @param env - Optional environment variables + * @param cwd - Optional working directory + * @returns true if the command can be spawned, false if not found */ private async commandExists( command: string, @@ -616,16 +604,20 @@ export class LspServerManager { if (settled) { return; } - // If command exists, it typically returns 0 or other non-error codes - // Some commands with --version may return non-0, but won't throw error - resolve(code !== 127); // 127 typically indicates command not found + settled = true; + // 127 typically indicates command not found in shell + resolve(code !== 127); }); - // Set timeout to avoid long waits + // If the process is still running after the timeout, it means the + // command was found and started — it just didn't finish in time. + // This is expected for servers like jdtls that don't support --version. setTimeout(() => { - settled = true; - child.kill(); - resolve(false); + if (!settled) { + settled = true; + child.kill(); + resolve(true); + } }, DEFAULT_LSP_COMMAND_CHECK_TIMEOUT_MS); }); } diff --git a/packages/core/src/lsp/NativeLspService.test.ts b/packages/core/src/lsp/NativeLspService.test.ts index 218f2e3c7..6daad8039 100644 --- a/packages/core/src/lsp/NativeLspService.test.ts +++ b/packages/core/src/lsp/NativeLspService.test.ts @@ -4,13 +4,17 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { describe, beforeEach, expect, test } from 'vitest'; +import { describe, beforeEach, expect, test, vi } from 'vitest'; import { NativeLspService } from './NativeLspService.js'; import { EventEmitter } from 'events'; import type { Config as CoreConfig } from '../config/config.js'; import type { FileDiscoveryService } from '../services/fileDiscoveryService.js'; import type { IdeContextStore } from '../ide/ideContext.js'; import type { WorkspaceContext } from '../utils/workspaceContext.js'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { pathToFileURL } from 'node:url'; // 模拟依赖项 class MockConfig { @@ -110,8 +114,29 @@ describe('NativeLspService', () => { expect(lspService).toBeDefined(); }); - test('should detect languages from workspace files', async () => { - // 这个测试需要修改,因为我们无法直接访问私有方法 + test('discoverAndPrepare should not invoke language detection', async () => { + const service = new NativeLspService( + mockConfig as unknown as CoreConfig, + mockWorkspace as unknown as WorkspaceContext, + eventEmitter, + mockFileDiscovery as unknown as FileDiscoveryService, + mockIdeStore as unknown as IdeContextStore, + ); + + const detectLanguages = vi.fn(async () => { + throw new Error('detectLanguages should not be called'); + }); + ( + service as unknown as { + languageDetector: { detectLanguages: () => Promise }; + } + ).languageDetector = { detectLanguages }; + + await expect(service.discoverAndPrepare()).resolves.toBeUndefined(); + expect(detectLanguages).not.toHaveBeenCalled(); + }); + + test('should prepare configs without language detection', async () => { await lspService.discoverAndPrepare(); const status = lspService.getStatus(); @@ -119,14 +144,959 @@ describe('NativeLspService', () => { expect(status).toBeDefined(); }); - test('should merge built-in presets with user configs', async () => { - await lspService.discoverAndPrepare(); + test('should open document before hover requests', async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lsp-test-')); + const filePath = path.join(tempDir, 'main.cpp'); + fs.writeFileSync(filePath, 'int main(){return 0;}\n', 'utf-8'); + const uri = pathToFileURL(filePath).toString(); - const status = lspService.getStatus(); - // 检查服务是否已准备就绪 - expect(status).toBeDefined(); + const events: string[] = []; + const connection = { + listen: vi.fn(), + send: vi.fn((message: { method?: string }) => { + events.push(`send:${message.method ?? 'unknown'}`); + }), + onNotification: vi.fn(), + onRequest: vi.fn(), + request: vi.fn(async (method: string) => { + events.push(`request:${method}`); + return null; + }), + initialize: vi.fn(async () => ({})), + shutdown: vi.fn(async () => {}), + end: vi.fn(), + }; + + const handle = { + config: { + name: 'clangd', + languages: ['cpp'], + command: 'clangd', + args: [], + transport: 'stdio', + }, + status: 'READY', + connection, + }; + + const serverManager = { + getHandles: () => new Map([['clangd', handle]]), + warmupTypescriptServer: vi.fn(), + }; + + (lspService as unknown as { serverManager: unknown }).serverManager = + serverManager; + + vi.useFakeTimers(); + try { + const promise1 = lspService.hover({ + uri, + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + }); + await vi.runAllTimersAsync(); + await promise1; + + expect(connection.send).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'textDocument/didOpen', + params: { + textDocument: expect.objectContaining({ + uri, + languageId: 'cpp', + }), + }, + }), + ); + expect(connection.request).toHaveBeenCalledWith( + 'textDocument/hover', + expect.any(Object), + ); + expect(events[0]).toBe('send:textDocument/didOpen'); + + const promise2 = lspService.hover({ + uri, + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + }); + await vi.runAllTimersAsync(); + await promise2; + + expect(connection.send).toHaveBeenCalledTimes(1); + } finally { + vi.useRealTimers(); + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + + test('should open a workspace file before workspace symbol search', async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lsp-symbol-')); + const workspaceFile = path.join(tempDir, 'src', 'main.cpp'); + fs.mkdirSync(path.dirname(workspaceFile), { recursive: true }); + fs.writeFileSync(workspaceFile, 'int main(){return 0;}\n', 'utf-8'); + const workspaceUri = pathToFileURL(workspaceFile).toString(); + + const events: string[] = []; + let opened = false; + const connection = { + listen: vi.fn(), + send: vi.fn((message: { method?: string }) => { + events.push(`send:${message.method ?? 'unknown'}`); + if (message.method === 'textDocument/didOpen') { + opened = true; + } + }), + onNotification: vi.fn(), + onRequest: vi.fn(), + request: vi.fn(async (method: string) => { + events.push(`request:${method}`); + if (method === 'workspace/symbol') { + return opened + ? [ + { + name: 'Calculator', + kind: 5, + location: { + uri: workspaceUri, + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 10 }, + }, + }, + }, + ] + : []; + } + return null; + }), + initialize: vi.fn(async () => ({})), + shutdown: vi.fn(async () => {}), + end: vi.fn(), + }; + + const handle = { + config: { + name: 'clangd', + languages: ['cpp'], + command: 'clangd', + args: [], + transport: 'stdio', + }, + status: 'READY', + connection, + }; + + const serverManager = { + getHandles: () => new Map([['clangd', handle]]), + warmupTypescriptServer: vi.fn(), + isTypescriptServer: () => false, + }; + + const tempConfig = new MockConfig(); + tempConfig.rootPath = tempDir; + const tempWorkspace = new MockWorkspaceContext(); + tempWorkspace.rootPath = tempDir; + const tempDiscovery = new MockFileDiscoveryService(); + const tempIdeStore = new MockIdeContextStore(); + const tempEmitter = new EventEmitter(); + + const tempService = new NativeLspService( + tempConfig as unknown as CoreConfig, + tempWorkspace as unknown as WorkspaceContext, + tempEmitter, + tempDiscovery as unknown as FileDiscoveryService, + tempIdeStore as unknown as IdeContextStore, + { workspaceRoot: tempDir }, + ); + + (tempService as unknown as { serverManager: unknown }).serverManager = + serverManager; + + vi.useFakeTimers(); + try { + const promise = tempService.workspaceSymbols('Calculator'); + await vi.runAllTimersAsync(); + const results = await promise; + + expect(connection.send).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'textDocument/didOpen', + }), + ); + expect(events[0]).toBe('send:textDocument/didOpen'); + expect(results.length).toBe(1); + } finally { + vi.useRealTimers(); + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + + test('should retry workspace symbols after warmup when initial result is empty', async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lsp-symbol-retry-')); + const workspaceFile = path.join(tempDir, 'src', 'main.cpp'); + fs.mkdirSync(path.dirname(workspaceFile), { recursive: true }); + fs.writeFileSync(workspaceFile, 'int main(){return 0;}\n', 'utf-8'); + const workspaceUri = pathToFileURL(workspaceFile).toString(); + + const events: string[] = []; + let opened = false; + let symbolCalls = 0; + const connection = { + listen: vi.fn(), + send: vi.fn((message: { method?: string }) => { + events.push(`send:${message.method ?? 'unknown'}`); + if (message.method === 'textDocument/didOpen') { + opened = true; + } + }), + onNotification: vi.fn(), + onRequest: vi.fn(), + request: vi.fn(async (method: string) => { + events.push(`request:${method}`); + if (method === 'workspace/symbol') { + symbolCalls += 1; + if (!opened) { + return []; + } + if (symbolCalls === 1) { + return []; + } + return [ + { + name: 'Calculator', + kind: 5, + location: { + uri: workspaceUri, + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 10 }, + }, + }, + }, + ]; + } + return null; + }), + initialize: vi.fn(async () => ({})), + shutdown: vi.fn(async () => {}), + end: vi.fn(), + }; + + const handle = { + config: { + name: 'clangd', + languages: ['cpp'], + command: 'clangd', + args: [], + transport: 'stdio', + }, + status: 'READY', + connection, + }; + + const serverManager = { + getHandles: () => new Map([['clangd', handle]]), + warmupTypescriptServer: vi.fn(), + isTypescriptServer: () => false, + }; + + const tempConfig = new MockConfig(); + tempConfig.rootPath = tempDir; + const tempWorkspace = new MockWorkspaceContext(); + tempWorkspace.rootPath = tempDir; + const tempDiscovery = new MockFileDiscoveryService(); + const tempIdeStore = new MockIdeContextStore(); + const tempEmitter = new EventEmitter(); + + const tempService = new NativeLspService( + tempConfig as unknown as CoreConfig, + tempWorkspace as unknown as WorkspaceContext, + tempEmitter, + tempDiscovery as unknown as FileDiscoveryService, + tempIdeStore as unknown as IdeContextStore, + { workspaceRoot: tempDir }, + ); + + (tempService as unknown as { serverManager: unknown }).serverManager = + serverManager; + + vi.useFakeTimers(); + try { + const promise = tempService.workspaceSymbols('Calculator'); + await vi.runAllTimersAsync(); + const results = await promise; + + expect(symbolCalls).toBe(2); + expect(results.length).toBe(1); + expect(events[0]).toBe('send:textDocument/didOpen'); + } finally { + vi.useRealTimers(); + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + + test('should not retry workspace symbols when no warmup file is available', async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lsp-symbol-empty-')); + + let symbolCalls = 0; + const connection = { + listen: vi.fn(), + send: vi.fn(), + onNotification: vi.fn(), + onRequest: vi.fn(), + request: vi.fn(async (method: string) => { + if (method === 'workspace/symbol') { + symbolCalls += 1; + return []; + } + return null; + }), + initialize: vi.fn(async () => ({})), + shutdown: vi.fn(async () => {}), + end: vi.fn(), + }; + + const handle = { + config: { + name: 'clangd', + languages: ['cpp'], + command: 'clangd', + args: [], + transport: 'stdio', + }, + status: 'READY', + connection, + }; + + const serverManager = { + getHandles: () => new Map([['clangd', handle]]), + warmupTypescriptServer: vi.fn(), + isTypescriptServer: () => false, + }; + + const tempConfig = new MockConfig(); + tempConfig.rootPath = tempDir; + const tempWorkspace = new MockWorkspaceContext(); + tempWorkspace.rootPath = tempDir; + const tempDiscovery = new MockFileDiscoveryService(); + const tempIdeStore = new MockIdeContextStore(); + const tempEmitter = new EventEmitter(); + + const tempService = new NativeLspService( + tempConfig as unknown as CoreConfig, + tempWorkspace as unknown as WorkspaceContext, + tempEmitter, + tempDiscovery as unknown as FileDiscoveryService, + tempIdeStore as unknown as IdeContextStore, + { workspaceRoot: tempDir }, + ); + + (tempService as unknown as { serverManager: unknown }).serverManager = + serverManager; + + vi.useFakeTimers(); + try { + const promise = tempService.workspaceSymbols('Calculator'); + await vi.runAllTimersAsync(); + await promise; + + expect(symbolCalls).toBe(1); + } finally { + vi.useRealTimers(); + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + + test('should reopen documents after connection changes', async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lsp-reopen-')); + const filePath = path.join(tempDir, 'main.cpp'); + fs.writeFileSync(filePath, 'int main(){return 0;}\n', 'utf-8'); + const uri = pathToFileURL(filePath).toString(); + + const connection1 = { + listen: vi.fn(), + send: vi.fn(), + onNotification: vi.fn(), + onRequest: vi.fn(), + request: vi.fn(async () => null), + initialize: vi.fn(async () => ({})), + shutdown: vi.fn(async () => {}), + end: vi.fn(), + }; + const connection2 = { + listen: vi.fn(), + send: vi.fn(), + onNotification: vi.fn(), + onRequest: vi.fn(), + request: vi.fn(async () => null), + initialize: vi.fn(async () => ({})), + shutdown: vi.fn(async () => {}), + end: vi.fn(), + }; + + const handle = { + config: { + name: 'clangd', + languages: ['cpp'], + command: 'clangd', + args: [], + transport: 'stdio', + }, + status: 'READY', + connection: connection1, + }; + + const serverManager = { + getHandles: () => new Map([['clangd', handle]]), + warmupTypescriptServer: vi.fn(), + }; + + const tempConfig = new MockConfig(); + tempConfig.rootPath = tempDir; + const tempWorkspace = new MockWorkspaceContext(); + tempWorkspace.rootPath = tempDir; + const tempDiscovery = new MockFileDiscoveryService(); + const tempIdeStore = new MockIdeContextStore(); + const tempEmitter = new EventEmitter(); + + const tempService = new NativeLspService( + tempConfig as unknown as CoreConfig, + tempWorkspace as unknown as WorkspaceContext, + tempEmitter, + tempDiscovery as unknown as FileDiscoveryService, + tempIdeStore as unknown as IdeContextStore, + { workspaceRoot: tempDir }, + ); + + (tempService as unknown as { serverManager: unknown }).serverManager = + serverManager; + + vi.useFakeTimers(); + try { + const promise1 = tempService.hover({ + uri, + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + }); + await vi.runAllTimersAsync(); + await promise1; + + expect(connection1.send).toHaveBeenCalledWith( + expect.objectContaining({ method: 'textDocument/didOpen' }), + ); + + handle.connection = connection2; + + const promise2 = tempService.hover({ + uri, + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + }); + await vi.runAllTimersAsync(); + await promise2; + + expect(connection2.send).toHaveBeenCalledWith( + expect.objectContaining({ method: 'textDocument/didOpen' }), + ); + } finally { + vi.useRealTimers(); + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + test('should delay after fresh document open then send request', async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lsp-delay-')); + const filePath = path.join(tempDir, 'main.cpp'); + fs.writeFileSync(filePath, 'int main(){return 0;}\n', 'utf-8'); + const uri = pathToFileURL(filePath).toString(); + + const timeline: Array<{ event: string; time: number }> = []; + const connection = { + listen: vi.fn(), + send: vi.fn((message: { method?: string }) => { + if (message.method === 'textDocument/didOpen') { + timeline.push({ event: 'didOpen', time: Date.now() }); + } + }), + onNotification: vi.fn(), + onRequest: vi.fn(), + request: vi.fn(async (method: string) => { + if (method === 'textDocument/definition') { + timeline.push({ event: 'definition', time: Date.now() }); + return [ + { + uri, + range: { + start: { line: 0, character: 4 }, + end: { line: 0, character: 8 }, + }, + }, + ]; + } + return null; + }), + initialize: vi.fn(async () => ({})), + shutdown: vi.fn(async () => {}), + end: vi.fn(), + }; + + const handle = { + config: { + name: 'clangd', + languages: ['cpp'], + command: 'clangd', + args: [], + transport: 'stdio', + }, + status: 'READY', + connection, + }; + + const serverManager = { + getHandles: () => new Map([['clangd', handle]]), + warmupTypescriptServer: vi.fn(), + }; + + (lspService as unknown as { serverManager: unknown }).serverManager = + serverManager; + + vi.useFakeTimers(); + try { + const promise = lspService.definitions({ + uri, + range: { + start: { line: 0, character: 4 }, + end: { line: 0, character: 4 }, + }, + }); + await vi.runAllTimersAsync(); + const results = await promise; + + // Verify didOpen fires before the definition request + expect(timeline.length).toBe(2); + expect(timeline[0]!.event).toBe('didOpen'); + expect(timeline[1]!.event).toBe('definition'); + // The delay should have elapsed between the two events (200ms) + expect(timeline[1]!.time - timeline[0]!.time).toBeGreaterThanOrEqual(200); + expect(results.length).toBe(1); + } finally { + vi.useRealTimers(); + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + + test('should skip delay when document is already open', async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lsp-nodelay-')); + const filePath = path.join(tempDir, 'main.cpp'); + fs.writeFileSync(filePath, 'int main(){return 0;}\n', 'utf-8'); + const uri = pathToFileURL(filePath).toString(); + + let didOpenCount = 0; + const connection = { + listen: vi.fn(), + send: vi.fn((message: { method?: string }) => { + if (message.method === 'textDocument/didOpen') { + didOpenCount += 1; + } + }), + onNotification: vi.fn(), + onRequest: vi.fn(), + request: vi.fn(async () => null), + initialize: vi.fn(async () => ({})), + shutdown: vi.fn(async () => {}), + end: vi.fn(), + }; + + const handle = { + config: { + name: 'clangd', + languages: ['cpp'], + command: 'clangd', + args: [], + transport: 'stdio', + }, + status: 'READY', + connection, + }; + + const serverManager = { + getHandles: () => new Map([['clangd', handle]]), + warmupTypescriptServer: vi.fn(), + }; + + (lspService as unknown as { serverManager: unknown }).serverManager = + serverManager; + + vi.useFakeTimers(); + try { + // First hover opens the document + const promise1 = lspService.hover({ + uri, + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + }); + await vi.runAllTimersAsync(); + await promise1; + expect(didOpenCount).toBe(1); + + // Second hover should not re-open or delay + const startTime = Date.now(); + const promise2 = lspService.hover({ + uri, + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + }); + await vi.runAllTimersAsync(); + await promise2; + const elapsed = Date.now() - startTime; + + expect(didOpenCount).toBe(1); + // No delay should have been triggered (well under 200ms with fake timers) + expect(elapsed).toBeLessThan(200); + } finally { + vi.useRealTimers(); + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + + test('should not send duplicate didOpen for warmup-opened URI on subsequent requests', async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lsp-warmup-track-')); + const queryFilePath = path.join(tempDir, 'main.cpp'); + const warmupFilePath = path.join(tempDir, 'index.ts'); + fs.writeFileSync(queryFilePath, 'int main(){return 0;}\n', 'utf-8'); + fs.writeFileSync(warmupFilePath, 'export const x = 1;\n', 'utf-8'); + const queryUri = pathToFileURL(queryFilePath).toString(); + const warmupUri = pathToFileURL(warmupFilePath).toString(); + + const didOpenUris: string[] = []; + const connection = { + listen: vi.fn(), + send: vi.fn( + (message: { + method?: string; + params?: { textDocument?: { uri?: string } }; + }) => { + if (message.method === 'textDocument/didOpen') { + didOpenUris.push(message.params?.textDocument?.uri ?? ''); + } + }, + ), + onNotification: vi.fn(), + onRequest: vi.fn(), + request: vi.fn(async () => null), + initialize: vi.fn(async () => ({})), + shutdown: vi.fn(async () => {}), + end: vi.fn(), + }; + + const handle = { + config: { + name: 'typescript', + languages: ['typescript'], + command: 'typescript-language-server', + args: ['--stdio'], + transport: 'stdio', + }, + status: 'READY', + connection, + }; + + // First call: warmup returns warmupUri (different from queryUri) + const serverManager = { + getHandles: () => new Map([['typescript', handle]]), + warmupTypescriptServer: vi.fn(async () => warmupUri), + }; + + (lspService as unknown as { serverManager: unknown }).serverManager = + serverManager; + + vi.useFakeTimers(); + try { + // First request: opens queryUri via ensureDocumentOpen, warmup returns warmupUri + const promise1 = lspService.hover({ + uri: queryUri, + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + }); + await vi.runAllTimersAsync(); + await promise1; + + // queryUri should have been opened via ensureDocumentOpen + expect(didOpenUris).toContain(queryUri); + const countAfterFirst = didOpenUris.length; + + // Second request: for warmupUri which was already tracked from warmup + const promise2 = lspService.hover({ + uri: warmupUri, + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + }); + await vi.runAllTimersAsync(); + await promise2; + + // warmupUri should NOT have been opened again via ensureDocumentOpen + // because it was tracked from the warmup in the first call + expect(didOpenUris.length).toBe(countAfterFirst); + } finally { + vi.useRealTimers(); + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + + test('should retry document operations for slow servers after fresh didOpen', async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lsp-retry-doc-')); + const filePath = path.join(tempDir, 'Main.java'); + fs.writeFileSync(filePath, 'public class Main { }\n', 'utf-8'); + const uri = pathToFileURL(filePath).toString(); + + let requestCount = 0; + const connection = { + listen: vi.fn(), + send: vi.fn(), + onNotification: vi.fn(), + onRequest: vi.fn(), + request: vi.fn(async (method: string) => { + if (method === 'textDocument/documentSymbol') { + requestCount += 1; + // First call returns empty (server still indexing), second returns data + if (requestCount === 1) { + return []; + } + return [ + { + name: 'Main', + kind: 5, + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 21 }, + }, + selectionRange: { + start: { line: 0, character: 13 }, + end: { line: 0, character: 17 }, + }, + }, + ]; + } + return null; + }), + initialize: vi.fn(async () => ({})), + shutdown: vi.fn(async () => {}), + end: vi.fn(), + }; + + const handle = { + config: { + name: 'jdtls', + languages: ['java'], + command: 'jdtls', + args: [], + transport: 'stdio', + }, + status: 'READY', + connection, + }; + + const serverManager = { + getHandles: () => new Map([['jdtls', handle]]), + warmupTypescriptServer: vi.fn(), + isTypescriptServer: () => false, + }; + + const tempConfig = new MockConfig(); + tempConfig.rootPath = tempDir; + const tempWorkspace = new MockWorkspaceContext(); + tempWorkspace.rootPath = tempDir; + + const tempService = new NativeLspService( + tempConfig as unknown as CoreConfig, + tempWorkspace as unknown as WorkspaceContext, + new EventEmitter(), + new MockFileDiscoveryService() as unknown as FileDiscoveryService, + new MockIdeContextStore() as unknown as IdeContextStore, + { workspaceRoot: tempDir }, + ); + + (tempService as unknown as { serverManager: unknown }).serverManager = + serverManager; + + vi.useFakeTimers(); + try { + const promise = tempService.documentSymbols(uri); + await vi.runAllTimersAsync(); + const results = await promise; + + // Should have retried: 2 requests total + expect(requestCount).toBe(2); + expect(results.length).toBe(1); + expect(results[0]?.name).toBe('Main'); + } finally { + vi.useRealTimers(); + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + + test('should NOT retry document operations for TypeScript servers', async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lsp-no-retry-ts-')); + const filePath = path.join(tempDir, 'index.ts'); + fs.writeFileSync(filePath, 'export const x = 1;\n', 'utf-8'); + const uri = pathToFileURL(filePath).toString(); + + let requestCount = 0; + const connection = { + listen: vi.fn(), + send: vi.fn(), + onNotification: vi.fn(), + onRequest: vi.fn(), + request: vi.fn(async (method: string) => { + if (method === 'textDocument/documentSymbol') { + requestCount += 1; + return []; + } + return null; + }), + initialize: vi.fn(async () => ({})), + shutdown: vi.fn(async () => {}), + end: vi.fn(), + }; + + const handle = { + config: { + name: 'typescript-language-server', + languages: ['typescript'], + command: 'typescript-language-server', + args: ['--stdio'], + transport: 'stdio', + }, + status: 'READY', + connection, + }; + + const serverManager = { + getHandles: () => new Map([['typescript', handle]]), + warmupTypescriptServer: vi.fn(), + isTypescriptServer: () => true, + }; + + (lspService as unknown as { serverManager: unknown }).serverManager = + serverManager; + + vi.useFakeTimers(); + try { + const promise = lspService.documentSymbols(uri); + await vi.runAllTimersAsync(); + await promise; + + // Should NOT have retried: only 1 request + expect(requestCount).toBe(1); + } finally { + vi.useRealTimers(); + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + + test('should NOT retry when document was already open', async () => { + const tempDir = fs.mkdtempSync( + path.join(os.tmpdir(), 'lsp-no-retry-open-'), + ); + const filePath = path.join(tempDir, 'Main.java'); + fs.writeFileSync(filePath, 'public class Main { }\n', 'utf-8'); + const uri = pathToFileURL(filePath).toString(); + + let requestCount = 0; + const connection = { + listen: vi.fn(), + send: vi.fn(), + onNotification: vi.fn(), + onRequest: vi.fn(), + request: vi.fn(async (method: string) => { + if ( + method === 'textDocument/hover' || + method === 'textDocument/documentSymbol' + ) { + requestCount += 1; + return null; + } + return null; + }), + initialize: vi.fn(async () => ({})), + shutdown: vi.fn(async () => {}), + end: vi.fn(), + }; + + const handle = { + config: { + name: 'jdtls', + languages: ['java'], + command: 'jdtls', + args: [], + transport: 'stdio', + }, + status: 'READY', + connection, + }; + + const serverManager = { + getHandles: () => new Map([['jdtls', handle]]), + warmupTypescriptServer: vi.fn(), + isTypescriptServer: () => false, + }; + + const tempConfig = new MockConfig(); + tempConfig.rootPath = tempDir; + const tempWorkspace = new MockWorkspaceContext(); + tempWorkspace.rootPath = tempDir; + + const tempService = new NativeLspService( + tempConfig as unknown as CoreConfig, + tempWorkspace as unknown as WorkspaceContext, + new EventEmitter(), + new MockFileDiscoveryService() as unknown as FileDiscoveryService, + new MockIdeContextStore() as unknown as IdeContextStore, + { workspaceRoot: tempDir }, + ); + + (tempService as unknown as { serverManager: unknown }).serverManager = + serverManager; + + vi.useFakeTimers(); + try { + // First call opens the document (retry is allowed on this call) + const promise1 = tempService.hover({ + uri, + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + }); + await vi.runAllTimersAsync(); + await promise1; + + requestCount = 0; + + // Second call - document already open, should NOT retry even though empty + const promise2 = tempService.documentSymbols(uri); + await vi.runAllTimersAsync(); + await promise2; + + expect(requestCount).toBe(1); + } finally { + vi.useRealTimers(); + fs.rmSync(tempDir, { recursive: true, force: true }); + } }); }); - -// 注意:实际的单元测试需要适当的测试框架配置 -// 这里只是一个结构示例 diff --git a/packages/core/src/lsp/NativeLspService.ts b/packages/core/src/lsp/NativeLspService.ts index df969cf2a..1ef901e77 100644 --- a/packages/core/src/lsp/NativeLspService.ts +++ b/packages/core/src/lsp/NativeLspService.ts @@ -27,8 +27,12 @@ import type { LspWorkspaceEdit, } from './types.js'; import type { EventEmitter } from 'events'; +import { + DEFAULT_LSP_DOCUMENT_OPEN_DELAY_MS, + DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS, + DEFAULT_LSP_WORKSPACE_SYMBOL_WARMUP_DELAY_MS, +} from './constants.js'; import { LspConfigLoader } from './LspConfigLoader.js'; -import { LspLanguageDetector } from './LspLanguageDetector.js'; import { LspResponseNormalizer } from './LspResponseNormalizer.js'; import { LspServerManager } from './LspServerManager.js'; import type { @@ -38,12 +42,36 @@ import type { NativeLspServiceOptions, } from './types.js'; import * as path from 'path'; -import { fileURLToPath } from 'url'; +import { fileURLToPath, pathToFileURL } from 'url'; import * as fs from 'node:fs'; import { createDebugLogger } from '../utils/debugLogger.js'; +import { globSync } from 'glob'; const debugLogger = createDebugLogger('LSP'); +/** + * Mapping from LSP language identifiers to file extensions, only for cases + * where the language ID does NOT match the file extension directly. + * Languages whose ID is already a valid extension (e.g. "cpp", "java", "go") + * are handled by the fallback in getWorkspaceSymbolExtensions(). + */ +const LANGUAGE_ID_TO_EXTENSIONS: Record = { + typescript: ['ts', 'tsx'], + typescriptreact: ['tsx'], + javascript: ['js', 'jsx'], + javascriptreact: ['jsx'], + python: ['py'], + csharp: ['cs'], + ruby: ['rb'], +}; + +const DEFAULT_EXCLUDE_PATTERNS = [ + '**/node_modules/**', + '**/.git/**', + '**/dist/**', + '**/build/**', +]; + export class NativeLspService { private config: CoreConfig; private workspaceContext: WorkspaceContext; @@ -52,8 +80,9 @@ export class NativeLspService { private workspaceRoot: string; private configLoader: LspConfigLoader; private serverManager: LspServerManager; - private languageDetector: LspLanguageDetector; private normalizer: LspResponseNormalizer; + private openedDocuments = new Map>(); + private lastConnections = new Map(); constructor( config: CoreConfig, @@ -71,10 +100,6 @@ export class NativeLspService { options.workspaceRoot ?? (config as { getProjectRoot: () => string }).getProjectRoot(); this.configLoader = new LspConfigLoader(this.workspaceRoot); - this.languageDetector = new LspLanguageDetector( - this.workspaceContext, - this.fileDiscoveryService, - ); this.normalizer = new LspResponseNormalizer(); this.serverManager = new LspServerManager( this.config, @@ -102,22 +127,14 @@ export class NativeLspService { return; } - // Detect languages in workspace + // Load LSP configs const userConfigs = await this.configLoader.loadUserConfigs(); const extensionConfigs = await this.configLoader.loadExtensionConfigs( this.getActiveExtensions(), ); - const extensionOverrides = - this.configLoader.collectExtensionToLanguageOverrides([ - ...extensionConfigs, - ...userConfigs, - ]); - const detectedLanguages = - await this.languageDetector.detectLanguages(extensionOverrides); - - // Merge configs: built-in presets + extension LSP configs + user .lsp.json + // Merge configs: extension LSP configs + user .lsp.json const serverConfigs = this.configLoader.mergeConfigs( - detectedLanguages, + [], extensionConfigs, userConfigs, ); @@ -177,6 +194,264 @@ export class NativeLspService { ); } + /** + * Ensure a document is open on the given LSP server. Sends textDocument/didOpen + * if not already tracked, then waits for the server to process the file before + * returning. This delay prevents empty results when the server hasn't analyzed + * the file yet. + * + * @param serverName - The name of the LSP server + * @param handle - The server handle with an active connection + * @param uri - The document URI to open + * @returns true if a new didOpen was sent; false if already open or failed + */ + private async ensureDocumentOpen( + serverName: string, + handle: LspServerHandle & { connection: LspConnectionInterface }, + uri: string, + ): Promise { + const lastConnection = this.lastConnections.get(serverName); + if (lastConnection && lastConnection !== handle.connection) { + this.openedDocuments.delete(serverName); + } + this.lastConnections.set(serverName, handle.connection); + + if (!uri.startsWith('file://')) { + return false; + } + const openedForServer = this.openedDocuments.get(serverName); + if (openedForServer?.has(uri)) { + return false; + } + + let filePath: string; + try { + filePath = fileURLToPath(uri); + } catch (error) { + debugLogger.warn(`Failed to resolve file path for ${uri}:`, error); + return false; + } + + let text: string; + try { + text = fs.readFileSync(filePath, 'utf-8'); + } catch (error) { + debugLogger.warn( + `Failed to read file for LSP didOpen: ${filePath}`, + error, + ); + return false; + } + + const languageId = this.resolveLanguageId(filePath, handle) ?? 'plaintext'; + + handle.connection.send({ + jsonrpc: '2.0', + method: 'textDocument/didOpen', + params: { + textDocument: { + uri, + languageId, + version: 1, + text, + }, + }, + }); + + const nextOpened = openedForServer ?? new Set(); + nextOpened.add(uri); + this.openedDocuments.set(serverName, nextOpened); + + // Wait for the LSP server to process the newly opened document. + // Without this delay, requests sent immediately after didOpen may return + // empty results because the server hasn't finished analyzing the file. + await this.delay(DEFAULT_LSP_DOCUMENT_OPEN_DELAY_MS); + + return true; + } + + /** + * Register a URI that was opened externally (e.g. by warmupTypescriptServer) + * so that ensureDocumentOpen does not send a duplicate textDocument/didOpen. + * + * @param serverName - The name of the LSP server + * @param uri - The document URI to track as already opened + */ + private trackExternallyOpenedDocument(serverName: string, uri: string): void { + const openedForServer = + this.openedDocuments.get(serverName) ?? new Set(); + openedForServer.add(uri); + this.openedDocuments.set(serverName, openedForServer); + } + + private resolveLanguageId( + filePath: string, + handle: LspServerHandle, + ): string | undefined { + const ext = path.extname(filePath).slice(1).toLowerCase(); + if (ext && handle.config.extensionToLanguage) { + const mapping = handle.config.extensionToLanguage; + return mapping[ext] ?? mapping['.' + ext]; + } + if (handle.config.languages && handle.config.languages.length > 0) { + return handle.config.languages[0]; + } + return ext || undefined; + } + + private async warmupWorkspaceSymbols( + serverName: string, + handle: LspServerHandle, + ): Promise { + if (!handle.connection) { + return false; + } + const openedForServer = this.openedDocuments.get(serverName); + if (openedForServer && openedForServer.size > 0) { + return true; + } + + const filePath = this.findWorkspaceFileForServer(handle); + if (!filePath) { + return false; + } + + const uri = pathToFileURL(filePath).toString(); + const didOpen = await this.ensureDocumentOpen( + serverName, + handle as LspServerHandle & { connection: LspConnectionInterface }, + uri, + ); + if (!didOpen) { + return false; + } + await this.delay(DEFAULT_LSP_WORKSPACE_SYMBOL_WARMUP_DELAY_MS); + return true; + } + + /** + * Find the first source file in the workspace that matches the server's + * language extensions. Used to open a file for workspace symbol warmup. + * + * @param handle - The LSP server handle to determine target extensions + * @returns Absolute path of the first matching file, or undefined + */ + private findWorkspaceFileForServer( + handle: LspServerHandle, + ): string | undefined { + const extensions = this.getWorkspaceSymbolExtensions(handle); + if (extensions.length === 0) { + return undefined; + } + // Brace expansion requires at least 2 items; use plain glob for a single ext + const extGlob = + extensions.length === 1 ? extensions[0]! : `{${extensions.join(',')}}`; + const pattern = `**/*.${extGlob}`; + const roots = this.workspaceContext.getDirectories(); + + for (const root of roots) { + try { + // Use maxDepth to avoid scanning deeply nested directories; + // we only need one file to trigger server indexing. + const matches = globSync(pattern, { + cwd: root, + ignore: DEFAULT_EXCLUDE_PATTERNS, + absolute: true, + nodir: true, + maxDepth: 5, + }); + for (const match of matches) { + if (this.fileDiscoveryService.shouldIgnoreFile(match)) { + continue; + } + return match; + } + } catch (_error) { + // ignore glob errors + } + } + + return undefined; + } + + /** + * Determine file extensions this server can handle, used to find a workspace + * file to open for warmup. Resolution order: + * 1. Keys from config.extensionToLanguage (explicit user/extension mapping) + * 2. Derived from config.languages via LANGUAGE_ID_TO_EXTENSIONS, falling + * back to treating the language ID itself as a file extension + */ + private getWorkspaceSymbolExtensions(handle: LspServerHandle): string[] { + const extensions = new Set(); + + // Prefer explicit extension-to-language mapping from server config + const extMapping = handle.config.extensionToLanguage; + if (extMapping) { + for (const key of Object.keys(extMapping)) { + const normalized = key.startsWith('.') ? key.slice(1) : key; + if (normalized) { + extensions.add(normalized.toLowerCase()); + } + } + } + + // Fall back to deriving extensions from language identifiers + if (extensions.size === 0) { + for (const language of handle.config.languages) { + const mapped = LANGUAGE_ID_TO_EXTENSIONS[language]; + if (mapped) { + for (const ext of mapped) { + extensions.add(ext); + } + } else { + // For languages like "cpp", "java", "go", "rust" etc., + // the language ID itself is a valid file extension + extensions.add(language.toLowerCase()); + } + } + } + + return Array.from(extensions); + } + + /** + * Run TypeScript server warmup and track the opened URI to prevent + * duplicate didOpen notifications. + * + * @param serverName - The name of the LSP server + * @param handle - The server handle + * @param force - Force re-warmup even if already warmed up + */ + private async warmupAndTrack( + serverName: string, + handle: LspServerHandle, + force = false, + ): Promise { + const warmupUri = await this.serverManager.warmupTypescriptServer( + handle, + force, + ); + if (warmupUri) { + this.trackExternallyOpenedDocument(serverName, warmupUri); + } + } + + /** + * Whether we should retry a document-level operation that returned empty + * results. We retry when a textDocument/didOpen was just sent (the server + * may still be indexing) AND the server is not a fast TypeScript server. + */ + private shouldRetryAfterOpen( + justOpened: boolean, + handle: LspServerHandle, + ): boolean { + return justOpened && !this.serverManager.isTypescriptServer(handle); + } + + private async delay(ms: number): Promise { + await new Promise((resolve) => setTimeout(resolve, ms)); + } + /** * Workspace symbol search across all ready LSP servers. */ @@ -193,15 +468,29 @@ export class NativeLspService { continue; } try { - await this.serverManager.warmupTypescriptServer(handle); + await this.warmupAndTrack(serverName, handle); + const warmedUp = this.serverManager.isTypescriptServer(handle) + ? false + : await this.warmupWorkspaceSymbols(serverName, handle); let response = await handle.connection.request('workspace/symbol', { query, }); + if ( + !this.serverManager.isTypescriptServer(handle) && + Array.isArray(response) && + response.length === 0 && + warmedUp + ) { + await this.delay(DEFAULT_LSP_WORKSPACE_SYMBOL_WARMUP_DELAY_MS); + response = await handle.connection.request('workspace/symbol', { + query, + }); + } if ( this.serverManager.isTypescriptServer(handle) && this.isNoProjectErrorResponse(response) ) { - await this.serverManager.warmupTypescriptServer(handle, true); + await this.warmupAndTrack(serverName, handle, true); response = await handle.connection.request('workspace/symbol', { query, }); @@ -241,17 +530,36 @@ export class NativeLspService { limit = 50, ): Promise { const handles = this.getReadyHandles(serverName); + const requestParams = { + textDocument: { uri: location.uri }, + position: location.range.start, + }; for (const [name, handle] of handles) { try { - await this.serverManager.warmupTypescriptServer(handle); - const response = await handle.connection.request( - 'textDocument/definition', - { - textDocument: { uri: location.uri }, - position: location.range.start, - }, + const justOpened = await this.ensureDocumentOpen( + name, + handle, + location.uri, ); + await this.warmupAndTrack(name, handle); + + let response = await handle.connection.request( + 'textDocument/definition', + requestParams, + ); + + if ( + this.isEmptyResponse(response) && + this.shouldRetryAfterOpen(justOpened, handle) + ) { + await this.delay(DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS); + response = await handle.connection.request( + 'textDocument/definition', + requestParams, + ); + } + const candidates = Array.isArray(response) ? response : response @@ -291,18 +599,37 @@ export class NativeLspService { limit = 200, ): Promise { const handles = this.getReadyHandles(serverName); + const requestParams = { + textDocument: { uri: location.uri }, + position: location.range.start, + context: { includeDeclaration }, + }; for (const [name, handle] of handles) { try { - await this.serverManager.warmupTypescriptServer(handle); - const response = await handle.connection.request( - 'textDocument/references', - { - textDocument: { uri: location.uri }, - position: location.range.start, - context: { includeDeclaration }, - }, + const justOpened = await this.ensureDocumentOpen( + name, + handle, + location.uri, ); + await this.warmupAndTrack(name, handle); + + let response = await handle.connection.request( + 'textDocument/references', + requestParams, + ); + + if ( + this.isEmptyResponse(response) && + this.shouldRetryAfterOpen(justOpened, handle) + ) { + await this.delay(DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS); + response = await handle.connection.request( + 'textDocument/references', + requestParams, + ); + } + if (!Array.isArray(response)) { continue; } @@ -338,14 +665,36 @@ export class NativeLspService { serverName?: string, ): Promise { const handles = this.getReadyHandles(serverName); + const requestParams = { + textDocument: { uri: location.uri }, + position: location.range.start, + }; for (const [name, handle] of handles) { try { - await this.serverManager.warmupTypescriptServer(handle); - const response = await handle.connection.request('textDocument/hover', { - textDocument: { uri: location.uri }, - position: location.range.start, - }); + const justOpened = await this.ensureDocumentOpen( + name, + handle, + location.uri, + ); + await this.warmupAndTrack(name, handle); + + let response = await handle.connection.request( + 'textDocument/hover', + requestParams, + ); + + if ( + this.isEmptyResponse(response) && + this.shouldRetryAfterOpen(justOpened, handle) + ) { + await this.delay(DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS); + response = await handle.connection.request( + 'textDocument/hover', + requestParams, + ); + } + const normalized = this.normalizer.normalizeHoverResult(response, name); if (normalized) { return normalized; @@ -367,16 +716,29 @@ export class NativeLspService { limit = 200, ): Promise { const handles = this.getReadyHandles(serverName); + const requestParams = { textDocument: { uri } }; for (const [name, handle] of handles) { try { - await this.serverManager.warmupTypescriptServer(handle); - const response = await handle.connection.request( + const justOpened = await this.ensureDocumentOpen(name, handle, uri); + await this.warmupAndTrack(name, handle); + + let response = await handle.connection.request( 'textDocument/documentSymbol', - { - textDocument: { uri }, - }, + requestParams, ); + + if ( + this.isEmptyResponse(response) && + this.shouldRetryAfterOpen(justOpened, handle) + ) { + await this.delay(DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS); + response = await handle.connection.request( + 'textDocument/documentSymbol', + requestParams, + ); + } + if (!Array.isArray(response)) { continue; } @@ -430,17 +792,36 @@ export class NativeLspService { limit = 50, ): Promise { const handles = this.getReadyHandles(serverName); + const requestParams = { + textDocument: { uri: location.uri }, + position: location.range.start, + }; for (const [name, handle] of handles) { try { - await this.serverManager.warmupTypescriptServer(handle); - const response = await handle.connection.request( - 'textDocument/implementation', - { - textDocument: { uri: location.uri }, - position: location.range.start, - }, + const justOpened = await this.ensureDocumentOpen( + name, + handle, + location.uri, ); + await this.warmupAndTrack(name, handle); + + let response = await handle.connection.request( + 'textDocument/implementation', + requestParams, + ); + + if ( + this.isEmptyResponse(response) && + this.shouldRetryAfterOpen(justOpened, handle) + ) { + await this.delay(DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS); + response = await handle.connection.request( + 'textDocument/implementation', + requestParams, + ); + } + const candidates = Array.isArray(response) ? response : response @@ -482,17 +863,36 @@ export class NativeLspService { limit = 50, ): Promise { const handles = this.getReadyHandles(serverName); + const requestParams = { + textDocument: { uri: location.uri }, + position: location.range.start, + }; for (const [name, handle] of handles) { try { - await this.serverManager.warmupTypescriptServer(handle); - const response = await handle.connection.request( - 'textDocument/prepareCallHierarchy', - { - textDocument: { uri: location.uri }, - position: location.range.start, - }, + const justOpened = await this.ensureDocumentOpen( + name, + handle, + location.uri, ); + await this.warmupAndTrack(name, handle); + + let response = await handle.connection.request( + 'textDocument/prepareCallHierarchy', + requestParams, + ); + + if ( + this.isEmptyResponse(response) && + this.shouldRetryAfterOpen(justOpened, handle) + ) { + await this.delay(DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS); + response = await handle.connection.request( + 'textDocument/prepareCallHierarchy', + requestParams, + ); + } + const candidates = Array.isArray(response) ? response : response @@ -538,7 +938,7 @@ export class NativeLspService { for (const [name, handle] of handles) { try { - await this.serverManager.warmupTypescriptServer(handle); + await this.warmupAndTrack(name, handle); const response = await handle.connection.request( 'callHierarchy/incomingCalls', { @@ -585,7 +985,7 @@ export class NativeLspService { for (const [name, handle] of handles) { try { - await this.serverManager.warmupTypescriptServer(handle); + await this.warmupAndTrack(name, handle); const response = await handle.connection.request( 'callHierarchy/outgoingCalls', { @@ -631,7 +1031,8 @@ export class NativeLspService { for (const [name, handle] of handles) { try { - await this.serverManager.warmupTypescriptServer(handle); + await this.ensureDocumentOpen(name, handle, uri); + await this.warmupAndTrack(name, handle); // Request pull diagnostics if the server supports it const response = await handle.connection.request( @@ -681,7 +1082,7 @@ export class NativeLspService { for (const [name, handle] of handles) { try { - await this.serverManager.warmupTypescriptServer(handle); + await this.warmupAndTrack(name, handle); // Request workspace diagnostics if supported const response = await handle.connection.request( @@ -735,7 +1136,8 @@ export class NativeLspService { for (const [name, handle] of handles) { try { - await this.serverManager.warmupTypescriptServer(handle); + await this.ensureDocumentOpen(name, handle, uri); + await this.warmupAndTrack(name, handle); // Convert context diagnostics to LSP format const lspDiagnostics = context.diagnostics.map((d: LspDiagnostic) => @@ -879,6 +1281,20 @@ export class NativeLspService { fs.writeFileSync(filePath, lines.join('\n'), 'utf-8'); } + /** + * Check if an LSP response represents an empty/null result, used to decide + * whether a retry is worthwhile after a freshly opened document. + */ + private isEmptyResponse(response: unknown): boolean { + if (response === null || response === undefined) { + return true; + } + if (Array.isArray(response) && response.length === 0) { + return true; + } + return false; + } + private isNoProjectErrorResponse(response: unknown): boolean { if (!response) { return false; diff --git a/packages/core/src/lsp/__e2e__/lsp-e2e-test.ts b/packages/core/src/lsp/__e2e__/lsp-e2e-test.ts new file mode 100644 index 000000000..5a4149c9e --- /dev/null +++ b/packages/core/src/lsp/__e2e__/lsp-e2e-test.ts @@ -0,0 +1,687 @@ +/** + * @license + * Copyright 2025 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +/* eslint-disable no-console, @typescript-eslint/no-explicit-any */ +/** + * LSP End-to-End Test Script + * + * Directly instantiates NativeLspService against real LSP servers + * (typescript-language-server, clangd, jdtls) to verify all 12 LSP methods + * return correct results after the ensureDocumentOpen delay fix. + * + * Key design decisions: + * - Uses per-method cursor positions (different LSP methods need different + * positions, e.g. implementations requires an interface, call hierarchy + * requires a function with both callers and callees). + * - Warms up the server by calling documentSymbols first (opens the file), + * then waits for the server to index before testing timing-sensitive + * methods like hover and definitions. + * + * Usage: npx tsx packages/core/src/lsp/__e2e__/lsp-e2e-test.ts + */ + +import { NativeLspService } from '../NativeLspService.js'; +import { EventEmitter } from 'events'; +import { pathToFileURL } from 'url'; +import * as path from 'path'; + +/* ------------------------------------------------------------------ */ +/* Helpers */ +/* ------------------------------------------------------------------ */ +const green = (s: string) => `\x1b[32m${s}\x1b[0m`; +const red = (s: string) => `\x1b[31m${s}\x1b[0m`; +const yellow = (s: string) => `\x1b[33m${s}\x1b[0m`; +const bold = (s: string) => `\x1b[1m${s}\x1b[0m`; + +interface TestResult { + method: string; + language: string; + passed: boolean; + detail: string; +} + +const results: TestResult[] = []; + +function record( + method: string, + language: string, + passed: boolean, + detail: string, +): void { + results.push({ method, language, passed, detail }); + const icon = passed ? green('PASS') : red('FAIL'); + console.log(` [${icon}] ${language}/${method}: ${detail}`); +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** Build an LSP location object from file path + 0-indexed line/char. */ +function loc(filePath: string, line: number, char: number) { + return { + uri: pathToFileURL(filePath).toString(), + range: { + start: { line, character: char }, + end: { line, character: char }, + }, + }; +} + +/* ------------------------------------------------------------------ */ +/* Per-method cursor position config */ +/* ------------------------------------------------------------------ */ +interface MethodPositions { + /** File + position for hover (on a type name or variable) */ + hover: { file: string; line: number; char: number }; + /** File + position for go-to-definition (on a function/method call) */ + definitions: { file: string; line: number; char: number }; + /** File + position for find-references (on a function/method name) */ + references: { file: string; line: number; char: number }; + /** File for documentSymbols (any file with multiple symbols) */ + documentSymbolsFile: string; + /** Query string for workspaceSymbols */ + symbolQuery: string; + /** File + position for implementations (on an interface/base class) */ + implementations: { file: string; line: number; char: number }; + /** File + position for call hierarchy (on a function that has callers AND callees) */ + callHierarchy: { file: string; line: number; char: number }; + /** File for diagnostics / codeActions */ + diagnosticsFile: string; +} + +interface LanguageTestConfig { + langName: string; + workspaceRoot: string; + positions: MethodPositions; + /** Extra wait time (ms) after opening a file for server to index. */ + indexWaitMs: number; + /** + * Methods where empty results are acceptable due to known server + * limitations (e.g. clangd doesn't implement callHierarchy/outgoingCalls). + * These methods will pass with a "Server limitation" note instead of failing. + */ + serverLimitedMethods?: Set; +} + +/* ------------------------------------------------------------------ */ +/* Service factory (lightweight mocks for config/workspace) */ +/* ------------------------------------------------------------------ */ +function createService(workspaceRoot: string): NativeLspService { + const config = { + isTrustedFolder: () => true, + getProjectRoot: () => workspaceRoot, + get: () => undefined, + getActiveExtensions: () => [], + }; + const workspaceContext = { + getDirectories: () => [workspaceRoot], + isPathWithinWorkspace: () => true, + fileExists: async () => false, + readFile: async () => '{}', + resolvePath: (p: string) => path.resolve(workspaceRoot, p), + }; + const fileDiscovery = { + discoverFiles: async () => [], + shouldIgnoreFile: () => false, + }; + + return new NativeLspService( + config as any, + workspaceContext as any, + new EventEmitter(), + fileDiscovery as any, + {} as any, + { workspaceRoot, requireTrustedWorkspace: false }, + ); +} + +/* ------------------------------------------------------------------ */ +/* Per-language test runner */ +/* ------------------------------------------------------------------ */ +async function testLanguage(cfg: LanguageTestConfig): Promise { + const { + langName, + workspaceRoot, + positions, + indexWaitMs, + serverLimitedMethods, + } = cfg; + const isServerLimited = (method: string) => + serverLimitedMethods?.has(method) ?? false; + + console.log(bold(`\n=============== ${langName} ===============`)); + console.log(` workspace : ${workspaceRoot}`); + + const service = createService(workspaceRoot); + + try { + /* ---------- startup ---------- */ + console.log(` Discovering and starting LSP server...`); + await service.discoverAndPrepare(); + await service.start(); + + const status = service.getStatus(); + const serverStatuses = Array.from(status.entries()); + if (serverStatuses.length === 0) { + record('startup', langName, false, 'No servers discovered'); + return; + } + let anyReady = false; + for (const [name, s] of serverStatuses) { + console.log(` Server "${name}": ${s}`); + if (s === 'READY') anyReady = true; + } + if (!anyReady) { + record('startup', langName, false, 'No server reached READY'); + return; + } + record('startup', langName, true, 'Server ready'); + + /* ---------- warmup: open main files via documentSymbols ---------- */ + // This triggers ensureDocumentOpen for each file, so the server starts + // indexing. We then wait for full indexing before timing-sensitive tests. + const filesToWarmUp = new Set(); + filesToWarmUp.add(positions.hover.file); + filesToWarmUp.add(positions.definitions.file); + filesToWarmUp.add(positions.references.file); + filesToWarmUp.add(positions.documentSymbolsFile); + filesToWarmUp.add(positions.implementations.file); + filesToWarmUp.add(positions.callHierarchy.file); + filesToWarmUp.add(positions.diagnosticsFile); + + console.log(` Warming up ${filesToWarmUp.size} file(s)...`); + for (const file of filesToWarmUp) { + const fileUri = pathToFileURL(file).toString(); + try { + await service.documentSymbols(fileUri); + } catch { + // Ignore errors during warmup; files will be retried in actual tests + } + } + + console.log(` Waiting ${indexWaitMs}ms for server to index...`); + await sleep(indexWaitMs); + + /* ---------- 1. hover ---------- */ + try { + const hoverLoc = loc( + positions.hover.file, + positions.hover.line, + positions.hover.char, + ); + const hover = await service.hover(hoverLoc); + if (hover?.contents) { + record( + 'hover', + langName, + true, + `"${hover.contents.substring(0, 100)}"`, + ); + } else { + record('hover', langName, false, 'Empty/null result'); + } + } catch (e: any) { + record('hover', langName, false, `Error: ${e.message}`); + } + + /* ---------- 2. definitions ---------- */ + try { + const defLoc = loc( + positions.definitions.file, + positions.definitions.line, + positions.definitions.char, + ); + const defs = await service.definitions(defLoc); + record( + 'definitions', + langName, + defs.length > 0, + defs.length > 0 ? `${defs.length} def(s)` : 'Empty result', + ); + } catch (e: any) { + record('definitions', langName, false, `Error: ${e.message}`); + } + + /* ---------- 3. references ---------- */ + try { + const refLoc = loc( + positions.references.file, + positions.references.line, + positions.references.char, + ); + const refs = await service.references(refLoc, undefined, true); + record( + 'references', + langName, + refs.length > 0, + refs.length > 0 ? `${refs.length} ref(s)` : 'Empty result', + ); + } catch (e: any) { + record('references', langName, false, `Error: ${e.message}`); + } + + /* ---------- 4. documentSymbols ---------- */ + try { + const docSymUri = pathToFileURL(positions.documentSymbolsFile).toString(); + const symbols = await service.documentSymbols(docSymUri); + if (symbols.length > 0) { + const names = symbols + .slice(0, 5) + .map((s) => s.name) + .join(', '); + record( + 'documentSymbols', + langName, + true, + `${symbols.length} symbol(s): ${names}`, + ); + } else { + record('documentSymbols', langName, false, 'Empty result'); + } + } catch (e: any) { + record('documentSymbols', langName, false, `Error: ${e.message}`); + } + + /* ---------- 5. workspaceSymbols ---------- */ + try { + const wsSymbols = await service.workspaceSymbols(positions.symbolQuery); + if (wsSymbols.length > 0) { + const names = wsSymbols + .slice(0, 5) + .map((s) => s.name) + .join(', '); + record( + 'workspaceSymbols', + langName, + true, + `${wsSymbols.length} symbol(s): ${names}`, + ); + } else { + record('workspaceSymbols', langName, false, 'Empty result'); + } + } catch (e: any) { + record('workspaceSymbols', langName, false, `Error: ${e.message}`); + } + + /* ---------- 6. implementations ---------- */ + try { + const implLoc = loc( + positions.implementations.file, + positions.implementations.line, + positions.implementations.char, + ); + const impls = await service.implementations(implLoc); + record( + 'implementations', + langName, + impls.length > 0, + impls.length > 0 ? `${impls.length} impl(s)` : 'Empty result', + ); + } catch (e: any) { + record('implementations', langName, false, `Error: ${e.message}`); + } + + /* ---------- 7/8/9. call hierarchy ---------- */ + try { + const callLoc = loc( + positions.callHierarchy.file, + positions.callHierarchy.line, + positions.callHierarchy.char, + ); + const callItems = await service.prepareCallHierarchy(callLoc); + if (callItems.length > 0) { + record( + 'prepareCallHierarchy', + langName, + true, + `${callItems.length} item(s): ${callItems[0]!.name}`, + ); + + try { + const incoming = await service.incomingCalls(callItems[0]!); + record( + 'incomingCalls', + langName, + incoming.length > 0, + incoming.length > 0 + ? `${incoming.length} caller(s)` + : 'Empty (no callers found)', + ); + } catch (e: any) { + record('incomingCalls', langName, false, `Error: ${e.message}`); + } + + try { + const outgoing = await service.outgoingCalls(callItems[0]!); + if (outgoing.length > 0) { + record( + 'outgoingCalls', + langName, + true, + `${outgoing.length} callee(s)`, + ); + } else if (isServerLimited('outgoingCalls')) { + record( + 'outgoingCalls', + langName, + true, + 'Empty (server does not implement this method)', + ); + } else { + record( + 'outgoingCalls', + langName, + false, + 'Empty (no callees found)', + ); + } + } catch (e: any) { + record('outgoingCalls', langName, false, `Error: ${e.message}`); + } + } else { + record('prepareCallHierarchy', langName, false, 'Empty result'); + record('incomingCalls', langName, false, 'Skipped'); + record('outgoingCalls', langName, false, 'Skipped'); + } + } catch (e: any) { + record('prepareCallHierarchy', langName, false, `Error: ${e.message}`); + record('incomingCalls', langName, false, 'Skipped'); + record('outgoingCalls', langName, false, 'Skipped'); + } + + /* ---------- 10. diagnostics ---------- */ + try { + const diagUri = pathToFileURL(positions.diagnosticsFile).toString(); + const diags = await service.diagnostics(diagUri); + // 0 diagnostics is fine for clean code + record('diagnostics', langName, true, `${diags.length} diagnostic(s)`); + } catch (e: any) { + record('diagnostics', langName, false, `Error: ${e.message}`); + } + + /* ---------- 11. codeActions ---------- */ + try { + const caUri = pathToFileURL(positions.diagnosticsFile).toString(); + const actions = await service.codeActions( + caUri, + { start: { line: 0, character: 0 }, end: { line: 0, character: 10 } }, + { diagnostics: [], triggerKind: 'invoked' as const }, + ); + // 0 actions is fine when there are no diagnostics + record('codeActions', langName, true, `${actions.length} action(s)`); + } catch (e: any) { + record('codeActions', langName, false, `Error: ${e.message}`); + } + + /* ---------- 12. workspaceDiagnostics ---------- */ + try { + const wsDiags = await service.workspaceDiagnostics(); + record( + 'workspaceDiagnostics', + langName, + true, + `${wsDiags.length} file(s) with diagnostics`, + ); + } catch (e: any) { + record('workspaceDiagnostics', langName, false, `Error: ${e.message}`); + } + + await service.stop(); + } catch (e: any) { + console.log(red(` Fatal error: ${e.message}`)); + console.log(e.stack); + try { + await service.stop(); + } catch { + // Best-effort cleanup; ignore errors during shutdown + } + } +} + +/* ------------------------------------------------------------------ */ +/* Language configs */ +/* ------------------------------------------------------------------ */ + +const TS_ROOT = '/tmp/lsp-e2e-test/ts-project'; +const CPP_ROOT = '/tmp/lsp-e2e-test/cpp-project'; +const JAVA_ROOT = '/tmp/lsp-e2e-test/java-project'; + +/** + * TypeScript positions (all in index.ts / math.ts): + * + * index.ts: + * L0: import { createCalculator, Calculator } from './math.js'; + * L1: (empty) + * L2: const calc: Calculator = createCalculator(); + * L3: console.log(calc.add(1, 2)); + * L4: console.log(calc.subtract(5, 3)); + * + * math.ts: + * L0: export interface Calculator { + * L5: export class SimpleCalculator implements Calculator { + * L15: export function createCalculator(): Calculator { + */ +const tsConfig: LanguageTestConfig = { + langName: 'TypeScript', + workspaceRoot: TS_ROOT, + indexWaitMs: 3000, + positions: { + // hover on `createCalculator` call: L2 char 27 + hover: { file: `${TS_ROOT}/src/index.ts`, line: 2, char: 27 }, + // definitions on `createCalculator` call → math.ts definition + definitions: { file: `${TS_ROOT}/src/index.ts`, line: 2, char: 27 }, + // references on `Calculator` → found in both files + references: { file: `${TS_ROOT}/src/index.ts`, line: 2, char: 12 }, + // documentSymbols on math.ts (has interface, class, function) + documentSymbolsFile: `${TS_ROOT}/src/math.ts`, + symbolQuery: 'Calculator', + // implementations on `Calculator` interface → SimpleCalculator + implementations: { file: `${TS_ROOT}/src/math.ts`, line: 0, char: 17 }, + // call hierarchy on `createCalculator` (called by index.ts, calls SimpleCalculator) + callHierarchy: { file: `${TS_ROOT}/src/math.ts`, line: 15, char: 16 }, + diagnosticsFile: `${TS_ROOT}/src/index.ts`, + }, +}; + +/** + * C++ positions (main.cpp / calculator.h / calculator.cpp): + * + * main.cpp: + * L0: #include "calculator.h" + * L1: #include + * L2: (empty) + * L3: int addValues(Calculator& calc, int a, int b) { + * L4: return calc.add(a, b); + * L5: } + * ... + * L11: int computeSum(Calculator& calc) { + * L12: return addValues(calc, 1, 2) + subtractValues(calc, 5, 3); + * L13: } + * ... + * L15: int main() { + * L16: Calculator calc; + * L17: int result = computeSum(calc); + * L18: std::cout << result << std::endl; + * ... + * + * calculator.h: + * L0: #pragma once + * L1: (empty) + * L2: class Calculator { + * L3: public: + * L4: int add(int a, int b); + * L5: int subtract(int a, int b); + * ... + * L9: class AdvancedCalculator : public Calculator { + * + * calculator.cpp: + * L0: #include "calculator.h" + * L1: (empty) + * L2: int Calculator::add(int a, int b) { + */ +const cppConfig: LanguageTestConfig = { + langName: 'C++', + workspaceRoot: CPP_ROOT, + indexWaitMs: 5000, + // clangd v19.x does not implement callHierarchy/outgoingCalls (returns -32601) + serverLimitedMethods: new Set(['outgoingCalls']), + positions: { + // hover on `Calculator` type at main.cpp L16:4 → class info + hover: { file: `${CPP_ROOT}/src/main.cpp`, line: 16, char: 4 }, + // definitions on `computeSum` call at main.cpp L17:17 → L11 definition + definitions: { file: `${CPP_ROOT}/src/main.cpp`, line: 17, char: 17 }, + // references on `add` method at calculator.h L4:8 → all usages + references: { file: `${CPP_ROOT}/src/calculator.h`, line: 4, char: 8 }, + // documentSymbols on main.cpp → addValues, subtractValues, computeSum, main + documentSymbolsFile: `${CPP_ROOT}/src/main.cpp`, + symbolQuery: 'Calculator', + // implementations on `Calculator` class at calculator.h L2:6 + // → should find AdvancedCalculator (derived class) + implementations: { file: `${CPP_ROOT}/src/calculator.h`, line: 2, char: 6 }, + // call hierarchy on `computeSum` at main.cpp L11:4 + // → incomingCalls: main; outgoingCalls: addValues, subtractValues + callHierarchy: { file: `${CPP_ROOT}/src/main.cpp`, line: 11, char: 4 }, + diagnosticsFile: `${CPP_ROOT}/src/main.cpp`, + }, +}; + +/** + * Java positions (Main.java / Calculator.java / SimpleCalculator.java): + * + * Main.java: + * L0: package com.test; + * L1: (empty) + * L2: public class Main { + * L3: public static int computeSum(Calculator calc) { + * L4: return calc.add(1, 2) + calc.subtract(5, 3); + * L5: } + * L6: (empty) + * L7: public static void main(String[] args) { + * L8: Calculator calc = new SimpleCalculator(); + * L9: int result = computeSum(calc); + * L10: System.out.println(result); + * L11: } + * L12: } + * + * Calculator.java: + * L0: package com.test; + * L1: (empty) + * L2: public interface Calculator { + * L3: int add(int a, int b); + * + * SimpleCalculator.java: + * L2: public class SimpleCalculator implements Calculator { + * L4: public int add(int a, int b) { + */ +const javaConfig: LanguageTestConfig = { + langName: 'Java', + workspaceRoot: JAVA_ROOT, + indexWaitMs: 20000, + positions: { + // hover on `Calculator` type at Main.java L8:8 → interface info + hover: { + file: `${JAVA_ROOT}/src/main/java/com/test/Main.java`, + line: 8, + char: 8, + }, + // definitions on `computeSum` call at Main.java L9:21 → L3 definition + definitions: { + file: `${JAVA_ROOT}/src/main/java/com/test/Main.java`, + line: 9, + char: 21, + }, + // references on `add` at Calculator.java L3:8 → all usages + references: { + file: `${JAVA_ROOT}/src/main/java/com/test/Calculator.java`, + line: 3, + char: 8, + }, + // documentSymbols on Main.java → Main class, computeSum, main + documentSymbolsFile: `${JAVA_ROOT}/src/main/java/com/test/Main.java`, + symbolQuery: 'Calculator', + // implementations on `Calculator` interface at Calculator.java L2:17 + implementations: { + file: `${JAVA_ROOT}/src/main/java/com/test/Calculator.java`, + line: 2, + char: 17, + }, + // call hierarchy on `computeSum` at Main.java L3:22 + // → incomingCalls: main; outgoingCalls: add, subtract + callHierarchy: { + file: `${JAVA_ROOT}/src/main/java/com/test/Main.java`, + line: 3, + char: 22, + }, + diagnosticsFile: `${JAVA_ROOT}/src/main/java/com/test/Main.java`, + }, +}; + +/* ------------------------------------------------------------------ */ +/* Main */ +/* ------------------------------------------------------------------ */ +async function main(): Promise { + console.log(bold('LSP End-to-End Test Suite')); + console.log( + 'Verifying all 12 LSP methods with real servers (TS / C++ / Java)\n', + ); + + await testLanguage(tsConfig); + await testLanguage(cppConfig); + await testLanguage(javaConfig); + + /* ---------- Summary ---------- */ + console.log(bold('\n================== Summary ==================')); + const passed = results.filter((r) => r.passed).length; + const failed = results.filter((r) => !r.passed).length; + console.log( + `Total: ${results.length} | ${green(`Passed: ${passed}`)} | ${red(`Failed: ${failed}`)}`, + ); + + console.log(bold('\nPer Language:')); + for (const lang of ['TypeScript', 'C++', 'Java']) { + const lr = results.filter((r) => r.language === lang); + const lp = lr.filter((r) => r.passed).length; + const icon = + lp === lr.length ? green('ALL PASS') : yellow(`${lp}/${lr.length}`); + console.log(` ${lang}: ${icon}`); + } + + console.log(bold('\nPer Method:')); + const methods = [ + 'startup', + 'hover', + 'definitions', + 'references', + 'documentSymbols', + 'workspaceSymbols', + 'implementations', + 'prepareCallHierarchy', + 'incomingCalls', + 'outgoingCalls', + 'diagnostics', + 'codeActions', + 'workspaceDiagnostics', + ]; + for (const m of methods) { + const mr = results.filter((r) => r.method === m); + const langs = mr + .map((r) => (r.passed ? green(r.language) : red(r.language))) + .join(' | '); + console.log(` ${m}: ${langs}`); + } + + if (failed > 0) { + console.log(yellow('\nFailed tests:')); + for (const r of results.filter((rr) => !rr.passed)) { + console.log(red(` ${r.language}/${r.method}: ${r.detail}`)); + } + } + + process.exit(failed > 0 ? 1 : 0); +} + +main(); diff --git a/packages/core/src/lsp/constants.ts b/packages/core/src/lsp/constants.ts index 04fa4bb31..aa70435a0 100644 --- a/packages/core/src/lsp/constants.ts +++ b/packages/core/src/lsp/constants.ts @@ -19,9 +19,25 @@ export const DEFAULT_LSP_REQUEST_TIMEOUT_MS = 15000; /** Default delay for TypeScript server warm-up in milliseconds */ export const DEFAULT_LSP_WARMUP_DELAY_MS = 150; +/** Default delay after opening a document to allow the LSP server to process it */ +export const DEFAULT_LSP_DOCUMENT_OPEN_DELAY_MS = 200; + /** Default timeout for command existence check in milliseconds */ export const DEFAULT_LSP_COMMAND_CHECK_TIMEOUT_MS = 2000; +/** Default delay for workspace symbol warmup after opening a file, in milliseconds */ +export const DEFAULT_LSP_WORKSPACE_SYMBOL_WARMUP_DELAY_MS = 1500; + +/** + * Default delay before retrying a document-level operation (definitions, + * references, hover, documentSymbols, etc.) when the first attempt returns + * empty results right after we sent textDocument/didOpen. + * + * Slow servers like jdtls (Java) and clangd (C++) need significantly more + * time than the initial 200ms didOpen delay to build their AST / index. + */ +export const DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS = 2000; + // ============================================================================ // Retry Constants // ============================================================================ diff --git a/packages/core/src/permissions/permission-manager.test.ts b/packages/core/src/permissions/permission-manager.test.ts index d15f36b25..5b1048d5c 100644 --- a/packages/core/src/permissions/permission-manager.test.ts +++ b/packages/core/src/permissions/permission-manager.test.ts @@ -20,6 +20,7 @@ import { splitCompoundCommand, buildPermissionRules, getRuleDisplayName, + buildHumanReadableRuleLabel, } from './rule-parser.js'; import { PermissionManager } from './permission-manager.js'; import type { PermissionManagerConfig } from './permission-manager.js'; @@ -27,12 +28,12 @@ import type { PermissionManagerConfig } from './permission-manager.js'; // ─── resolveToolName ───────────────────────────────────────────────────────── describe('resolveToolName', () => { - it('resolves canonical names', () => { + it('resolves canonical names', async () => { expect(resolveToolName('run_shell_command')).toBe('run_shell_command'); expect(resolveToolName('read_file')).toBe('read_file'); }); - it('resolves display-name aliases', () => { + it('resolves display-name aliases', async () => { expect(resolveToolName('Shell')).toBe('run_shell_command'); expect(resolveToolName('ShellTool')).toBe('run_shell_command'); expect(resolveToolName('Bash')).toBe('run_shell_command'); @@ -42,25 +43,25 @@ describe('resolveToolName', () => { expect(resolveToolName('WriteFileTool')).toBe('write_file'); }); - it('resolves "Read" and "Edit" meta-categories', () => { + it('resolves "Read" and "Edit" meta-categories', async () => { expect(resolveToolName('Read')).toBe('read_file'); expect(resolveToolName('Edit')).toBe('edit'); expect(resolveToolName('Write')).toBe('write_file'); }); - it('resolves Agent category', () => { + it('resolves Agent category', async () => { expect(resolveToolName('Agent')).toBe('agent'); expect(resolveToolName('agent')).toBe('agent'); expect(resolveToolName('AgentTool')).toBe('agent'); }); - it('resolves legacy task aliases to agent', () => { + it('resolves legacy task aliases to agent', async () => { expect(resolveToolName('task')).toBe('agent'); expect(resolveToolName('Task')).toBe('agent'); expect(resolveToolName('TaskTool')).toBe('agent'); }); - it('returns unknown names unchanged', () => { + it('returns unknown names unchanged', async () => { expect(resolveToolName('my_mcp_tool')).toBe('my_mcp_tool'); expect(resolveToolName('mcp__server__tool')).toBe('mcp__server__tool'); }); @@ -69,11 +70,11 @@ describe('resolveToolName', () => { // ─── getSpecifierKind ──────────────────────────────────────────────────────── describe('getSpecifierKind', () => { - it('returns "command" for shell tools', () => { + it('returns "command" for shell tools', async () => { expect(getSpecifierKind('run_shell_command')).toBe('command'); }); - it('returns "path" for file read/edit tools', () => { + it('returns "path" for file read/edit tools', async () => { expect(getSpecifierKind('read_file')).toBe('path'); expect(getSpecifierKind('edit')).toBe('path'); expect(getSpecifierKind('write_file')).toBe('path'); @@ -82,11 +83,11 @@ describe('getSpecifierKind', () => { expect(getSpecifierKind('list_directory')).toBe('path'); }); - it('returns "domain" for web fetch tools', () => { + it('returns "domain" for web fetch tools', async () => { expect(getSpecifierKind('web_fetch')).toBe('domain'); }); - it('returns "literal" for other tools', () => { + it('returns "literal" for other tools', async () => { expect(getSpecifierKind('Agent')).toBe('literal'); expect(getSpecifierKind('task')).toBe('literal'); expect(getSpecifierKind('mcp__server')).toBe('literal'); @@ -96,22 +97,22 @@ describe('getSpecifierKind', () => { // ─── toolMatchesRuleToolName ───────────────────────────────────────────────── describe('toolMatchesRuleToolName', () => { - it('exact match', () => { + it('exact match', async () => { expect(toolMatchesRuleToolName('read_file', 'read_file')).toBe(true); expect(toolMatchesRuleToolName('edit', 'edit')).toBe(true); }); - it('"Read" (read_file) covers grep_search, glob, list_directory', () => { + it('"Read" (read_file) covers grep_search, glob, list_directory', async () => { expect(toolMatchesRuleToolName('read_file', 'grep_search')).toBe(true); expect(toolMatchesRuleToolName('read_file', 'glob')).toBe(true); expect(toolMatchesRuleToolName('read_file', 'list_directory')).toBe(true); }); - it('"Edit" (edit) covers write_file', () => { + it('"Edit" (edit) covers write_file', async () => { expect(toolMatchesRuleToolName('edit', 'write_file')).toBe(true); }); - it('does not cross categories', () => { + it('does not cross categories', async () => { expect(toolMatchesRuleToolName('read_file', 'edit')).toBe(false); expect(toolMatchesRuleToolName('edit', 'read_file')).toBe(false); expect(toolMatchesRuleToolName('read_file', 'run_shell_command')).toBe( @@ -123,7 +124,7 @@ describe('toolMatchesRuleToolName', () => { // ─── parseRule ─────────────────────────────────────────────────────────────── describe('parseRule', () => { - it('parses a simple tool name', () => { + it('parses a simple tool name', async () => { const r = parseRule('ShellTool'); expect(r.raw).toBe('ShellTool'); expect(r.toolName).toBe('run_shell_command'); @@ -131,59 +132,59 @@ describe('parseRule', () => { expect(r.specifierKind).toBeUndefined(); }); - it('parses Bash alias (Claude Code compat)', () => { + it('parses Bash alias (Claude Code compat)', async () => { const r = parseRule('Bash'); expect(r.toolName).toBe('run_shell_command'); }); - it('parses a shell tool with a specifier', () => { + it('parses a shell tool with a specifier', async () => { const r = parseRule('Bash(git *)'); expect(r.toolName).toBe('run_shell_command'); expect(r.specifier).toBe('git *'); expect(r.specifierKind).toBe('command'); }); - it('parses Read with path specifier', () => { + it('parses Read with path specifier', async () => { const r = parseRule('Read(./secrets/**)'); expect(r.toolName).toBe('read_file'); expect(r.specifier).toBe('./secrets/**'); expect(r.specifierKind).toBe('path'); }); - it('parses Edit with path specifier', () => { + it('parses Edit with path specifier', async () => { const r = parseRule('Edit(/src/**/*.ts)'); expect(r.toolName).toBe('edit'); expect(r.specifier).toBe('/src/**/*.ts'); expect(r.specifierKind).toBe('path'); }); - it('parses WebFetch with domain specifier', () => { + it('parses WebFetch with domain specifier', async () => { const r = parseRule('WebFetch(domain:example.com)'); expect(r.toolName).toBe('web_fetch'); expect(r.specifier).toBe('domain:example.com'); expect(r.specifierKind).toBe('domain'); }); - it('parses Agent with literal specifier', () => { + it('parses Agent with literal specifier', async () => { const r = parseRule('Agent(Explore)'); expect(r.toolName).toBe('agent'); expect(r.specifier).toBe('Explore'); expect(r.specifierKind).toBe('literal'); }); - it('handles unknown tools without specifier', () => { + it('handles unknown tools without specifier', async () => { const r = parseRule('mcp__my_server__my_tool'); expect(r.toolName).toBe('mcp__my_server__my_tool'); expect(r.specifier).toBeUndefined(); }); - it('handles legacy :* suffix (deprecated)', () => { + it('handles legacy :* suffix (deprecated)', async () => { const r = parseRule('Bash(git:*)'); expect(r.toolName).toBe('run_shell_command'); expect(r.specifier).toBe('git *'); }); - it('handles malformed pattern (no closing paren)', () => { + it('handles malformed pattern (no closing paren)', async () => { const r = parseRule('Bash(git status'); expect(r.specifier).toBeUndefined(); }); @@ -192,7 +193,7 @@ describe('parseRule', () => { // ─── parseRules ────────────────────────────────────────────────────────────── describe('parseRules', () => { - it('filters empty strings', () => { + it('filters empty strings', async () => { const rules = parseRules(['ShellTool', '', ' ', 'ReadFileTool']); expect(rules).toHaveLength(2); }); @@ -203,48 +204,48 @@ describe('parseRules', () => { describe('matchesCommandPattern', () => { // Basic prefix matching (no wildcards) describe('prefix matching without glob', () => { - it('exact match', () => { + it('exact match', async () => { expect(matchesCommandPattern('git', 'git')).toBe(true); }); - it('prefix + space', () => { + it('prefix + space', async () => { expect(matchesCommandPattern('git', 'git status')).toBe(true); expect(matchesCommandPattern('git commit', 'git commit -m "test"')).toBe( true, ); }); - it('does not match as substring', () => { + it('does not match as substring', async () => { expect(matchesCommandPattern('git', 'gitcommit')).toBe(false); }); }); // Wildcard at tail describe('wildcard at tail', () => { - it('matches any arguments', () => { + it('matches any arguments', async () => { expect(matchesCommandPattern('git *', 'git status')).toBe(true); expect(matchesCommandPattern('git *', 'git commit -m "test"')).toBe(true); expect(matchesCommandPattern('npm run *', 'npm run build')).toBe(true); }); - it('space-star requires word boundary (ls * does not match lsof)', () => { + it('space-star requires word boundary (ls * does not match lsof)', async () => { expect(matchesCommandPattern('ls *', 'ls -la')).toBe(true); expect(matchesCommandPattern('ls *', 'lsof')).toBe(false); }); - it('no-space-star allows prefix matching (ls* matches lsof)', () => { + it('no-space-star allows prefix matching (ls* matches lsof)', async () => { expect(matchesCommandPattern('ls*', 'ls -la')).toBe(true); expect(matchesCommandPattern('ls*', 'lsof')).toBe(true); }); - it('does not match different command', () => { + it('does not match different command', async () => { expect(matchesCommandPattern('git *', 'echo hello')).toBe(false); }); }); // Wildcard at head describe('wildcard at head', () => { - it('matches any command ending with pattern', () => { + it('matches any command ending with pattern', async () => { expect(matchesCommandPattern('* --version', 'node --version')).toBe(true); expect(matchesCommandPattern('* --version', 'npm --version')).toBe(true); expect(matchesCommandPattern('* --help *', 'npm --help install')).toBe( @@ -252,21 +253,21 @@ describe('matchesCommandPattern', () => { ); }); - it('does not match non-matching suffix', () => { + it('does not match non-matching suffix', async () => { expect(matchesCommandPattern('* --version', 'node --help')).toBe(false); }); }); // Wildcard in middle describe('wildcard in middle', () => { - it('matches middle segments', () => { + it('matches middle segments', async () => { expect(matchesCommandPattern('git * main', 'git checkout main')).toBe( true, ); expect(matchesCommandPattern('git * main', 'git merge main')).toBe(true); }); - it('does not match different suffix', () => { + it('does not match different suffix', async () => { expect(matchesCommandPattern('git * main', 'git checkout dev')).toBe( false, ); @@ -275,19 +276,19 @@ describe('matchesCommandPattern', () => { // Word boundary rule: space before * matters describe('word boundary rule (space before *)', () => { - it('Bash(ls *): matches "ls -la" but NOT "lsof"', () => { + it('Bash(ls *): matches "ls -la" but NOT "lsof"', async () => { expect(matchesCommandPattern('ls *', 'ls -la')).toBe(true); expect(matchesCommandPattern('ls *', 'ls')).toBe(true); // "ls" alone expect(matchesCommandPattern('ls *', 'lsof')).toBe(false); }); - it('Bash(ls*): matches both "ls -la" and "lsof"', () => { + it('Bash(ls*): matches both "ls -la" and "lsof"', async () => { expect(matchesCommandPattern('ls*', 'ls -la')).toBe(true); expect(matchesCommandPattern('ls*', 'lsof')).toBe(true); expect(matchesCommandPattern('ls*', 'ls')).toBe(true); }); - it('Bash(npm *): matches "npm run" but NOT "npmx"', () => { + it('Bash(npm *): matches "npm run" but NOT "npmx"', async () => { expect(matchesCommandPattern('npm *', 'npm run build')).toBe(true); expect(matchesCommandPattern('npm *', 'npmx install')).toBe(false); }); @@ -306,13 +307,13 @@ describe('matchesCommandPattern', () => { // These tests verify that matchesCommandPattern works correctly on // individual simple commands (the sub-commands after splitting). describe('simple command matching (no operators)', () => { - it('matches when no operators are present', () => { + it('matches when no operators are present', async () => { expect( matchesCommandPattern('git *', 'git commit -m "hello world"'), ).toBe(true); }); - it('operators inside quotes are not boundaries for splitCompoundCommand', () => { + it('operators inside quotes are not boundaries for splitCompoundCommand', async () => { // "echo 'a && b'" → the && is inside quotes, not an operator expect(matchesCommandPattern('echo *', "echo 'a && b'")).toBe(true); }); @@ -320,24 +321,24 @@ describe('matchesCommandPattern', () => { // Special: lone * matches any command describe('lone wildcard', () => { - it('* matches any single command', () => { + it('* matches any single command', async () => { expect(matchesCommandPattern('*', 'anything here')).toBe(true); }); }); // Exact command match with specifier describe('exact command specifier', () => { - it('Bash(npm run build) matches exact command', () => { + it('Bash(npm run build) matches exact command', async () => { expect(matchesCommandPattern('npm run build', 'npm run build')).toBe( true, ); }); - it('Bash(npm run build) also matches with trailing args (prefix)', () => { + it('Bash(npm run build) also matches with trailing args (prefix)', async () => { expect( matchesCommandPattern('npm run build', 'npm run build --verbose'), ).toBe(true); }); - it('Bash(npm run build) does not match different command', () => { + it('Bash(npm run build) does not match different command', async () => { expect(matchesCommandPattern('npm run build', 'npm run test')).toBe( false, ); @@ -348,59 +349,59 @@ describe('matchesCommandPattern', () => { // ─── splitCompoundCommand ──────────────────────────────────────────────────── describe('splitCompoundCommand', () => { - it('simple command returns single-element array', () => { + it('simple command returns single-element array', async () => { expect(splitCompoundCommand('git status')).toEqual(['git status']); }); - it('splits on &&', () => { + it('splits on &&', async () => { expect(splitCompoundCommand('git status && rm -rf /')).toEqual([ 'git status', 'rm -rf /', ]); }); - it('splits on ||', () => { + it('splits on ||', async () => { expect(splitCompoundCommand('git push || echo failed')).toEqual([ 'git push', 'echo failed', ]); }); - it('splits on ;', () => { + it('splits on ;', async () => { expect(splitCompoundCommand('echo hello; echo world')).toEqual([ 'echo hello', 'echo world', ]); }); - it('splits on |', () => { + it('splits on |', async () => { expect(splitCompoundCommand('git log | grep fix')).toEqual([ 'git log', 'grep fix', ]); }); - it('handles three-part compound', () => { + it('handles three-part compound', async () => { expect(splitCompoundCommand('a && b && c')).toEqual(['a', 'b', 'c']); }); - it('handles mixed operators', () => { + it('handles mixed operators', async () => { expect(splitCompoundCommand('a && b | c; d')).toEqual(['a', 'b', 'c', 'd']); }); - it('does not split on operators inside single quotes', () => { + it('does not split on operators inside single quotes', async () => { expect(splitCompoundCommand("echo 'a && b'")).toEqual(["echo 'a && b'"]); }); - it('does not split on operators inside double quotes', () => { + it('does not split on operators inside double quotes', async () => { expect(splitCompoundCommand('echo "a && b"')).toEqual(['echo "a && b"']); }); - it('handles escaped characters', () => { + it('handles escaped characters', async () => { expect(splitCompoundCommand('echo a \\&& b')).toEqual(['echo a \\&& b']); }); - it('trims whitespace around sub-commands', () => { + it('trims whitespace around sub-commands', async () => { expect(splitCompoundCommand(' git status && rm -rf / ')).toEqual([ 'git status', 'rm -rf /', @@ -414,13 +415,13 @@ describe('resolvePathPattern', () => { const projectRoot = '/project'; const cwd = '/project/subdir'; - it('// prefix → absolute from filesystem root', () => { + it('// prefix → absolute from filesystem root', async () => { expect( resolvePathPattern('//Users/alice/secrets/**', projectRoot, cwd), ).toBe('/Users/alice/secrets/**'); }); - it('~/ prefix → relative to home directory', () => { + it('~/ prefix → relative to home directory', async () => { const result = resolvePathPattern('~/Documents/*.pdf', projectRoot, cwd); expect(result).toContain('Documents/*.pdf'); // On POSIX systems the home dir starts with '/'; on Windows it may look like @@ -430,25 +431,25 @@ describe('resolvePathPattern', () => { expect(result.startsWith(normalizedHome)).toBe(true); }); - it('/ prefix → relative to project root (NOT absolute)', () => { + it('/ prefix → relative to project root (NOT absolute)', async () => { expect(resolvePathPattern('/src/**/*.ts', projectRoot, cwd)).toBe( '/project/src/**/*.ts', ); }); - it('./ prefix → relative to cwd', () => { + it('./ prefix → relative to cwd', async () => { expect(resolvePathPattern('./secrets/**', projectRoot, cwd)).toBe( '/project/subdir/secrets/**', ); }); - it('no prefix → relative to cwd', () => { + it('no prefix → relative to cwd', async () => { expect(resolvePathPattern('*.env', projectRoot, cwd)).toBe( '/project/subdir/*.env', ); }); - it('/Users/alice/file is relative to project root, NOT absolute', () => { + it('/Users/alice/file is relative to project root, NOT absolute', async () => { // This is a gotcha from the Claude Code docs expect(resolvePathPattern('/Users/alice/file', projectRoot, cwd)).toBe( '/project/Users/alice/file', @@ -462,7 +463,7 @@ describe('matchesPathPattern', () => { const projectRoot = '/project'; const cwd = '/project'; - it('matches dotfiles (e.g. .env)', () => { + it('matches dotfiles (e.g. .env)', async () => { expect(matchesPathPattern('.env', '/project/.env', projectRoot, cwd)).toBe( true, ); @@ -471,7 +472,7 @@ describe('matchesPathPattern', () => { ); }); - it('** matches recursively across directories', () => { + it('** matches recursively across directories', async () => { expect( matchesPathPattern( './secrets/**', @@ -482,7 +483,7 @@ describe('matchesPathPattern', () => { ).toBe(true); }); - it('* matches single directory only', () => { + it('* matches single directory only', async () => { expect( matchesPathPattern( '/src/*.ts', @@ -501,7 +502,7 @@ describe('matchesPathPattern', () => { ).toBe(false); }); - it('/docs/** matches under project root docs', () => { + it('/docs/** matches under project root docs', async () => { expect( matchesPathPattern( '/docs/**', @@ -520,7 +521,7 @@ describe('matchesPathPattern', () => { ).toBe(false); }); - it('//tmp/scratch.txt matches absolute path', () => { + it('//tmp/scratch.txt matches absolute path', async () => { expect( matchesPathPattern( '//tmp/scratch.txt', @@ -531,7 +532,7 @@ describe('matchesPathPattern', () => { ).toBe(true); }); - it('does not match unrelated paths', () => { + it('does not match unrelated paths', async () => { expect( matchesPathPattern( './secrets/**', @@ -546,13 +547,13 @@ describe('matchesPathPattern', () => { // ─── matchesDomainPattern ──────────────────────────────────────────────────── describe('matchesDomainPattern', () => { - it('matches exact domain', () => { + it('matches exact domain', async () => { expect(matchesDomainPattern('domain:example.com', 'example.com')).toBe( true, ); }); - it('matches subdomain', () => { + it('matches subdomain', async () => { expect(matchesDomainPattern('domain:example.com', 'sub.example.com')).toBe( true, ); @@ -561,19 +562,19 @@ describe('matchesDomainPattern', () => { ).toBe(true); }); - it('does not match different domain', () => { + it('does not match different domain', async () => { expect(matchesDomainPattern('domain:example.com', 'notexample.com')).toBe( false, ); }); - it('is case-insensitive', () => { + it('is case-insensitive', async () => { expect(matchesDomainPattern('domain:Example.COM', 'example.com')).toBe( true, ); }); - it('handles missing prefix', () => { + it('handles missing prefix', async () => { expect(matchesDomainPattern('example.com', 'example.com')).toBe(true); }); }); @@ -582,26 +583,26 @@ describe('matchesDomainPattern', () => { describe('matchesRule', () => { // Basic tool name matching - it('simple tool-name rule matches any invocation', () => { + it('simple tool-name rule matches any invocation', async () => { const rule = parseRule('ShellTool'); expect(matchesRule(rule, 'run_shell_command')).toBe(true); expect(matchesRule(rule, 'run_shell_command', 'git status')).toBe(true); }); - it('does not match a different tool', () => { + it('does not match a different tool', async () => { const rule = parseRule('ShellTool'); expect(matchesRule(rule, 'read_file')).toBe(false); }); // Shell command specifier - it('specifier rule requires a command for shell tools', () => { + it('specifier rule requires a command for shell tools', async () => { const rule = parseRule('Bash(git *)'); expect(matchesRule(rule, 'run_shell_command')).toBe(false); // no command expect(matchesRule(rule, 'run_shell_command', 'git status')).toBe(true); expect(matchesRule(rule, 'run_shell_command', 'echo hello')).toBe(false); }); - it('matchesRule checks individual simple commands (compound splitting is at PM level)', () => { + it('matchesRule checks individual simple commands (compound splitting is at PM level)', async () => { const rule = parseRule('Bash(git *)'); // matchesRule receives a simple command (already split by PM) expect(matchesRule(rule, 'run_shell_command', 'git status')).toBe(true); @@ -609,7 +610,7 @@ describe('matchesRule', () => { }); // Meta-category matching: Read - it('Read rule matches grep_search, glob, list_directory', () => { + it('Read rule matches grep_search, glob, list_directory', async () => { const rule = parseRule('Read'); expect(matchesRule(rule, 'read_file')).toBe(true); expect(matchesRule(rule, 'grep_search')).toBe(true); @@ -619,7 +620,7 @@ describe('matchesRule', () => { }); // Meta-category matching: Edit - it('Edit rule matches edit and write_file', () => { + it('Edit rule matches edit and write_file', async () => { const rule = parseRule('Edit'); expect(matchesRule(rule, 'edit')).toBe(true); expect(matchesRule(rule, 'write_file')).toBe(true); @@ -627,7 +628,7 @@ describe('matchesRule', () => { }); // File path matching - it('Read with path specifier requires filePath', () => { + it('Read with path specifier requires filePath', async () => { const rule = parseRule('Read(.env)'); const pathCtx = { projectRoot: '/project', cwd: '/project' }; // No filePath → no match @@ -655,7 +656,7 @@ describe('matchesRule', () => { ).toBe(false); }); - it('Edit path specifier matches write_file too', () => { + it('Edit path specifier matches write_file too', async () => { const rule = parseRule('Edit(/src/**/*.ts)'); const pathCtx = { projectRoot: '/project', cwd: '/project' }; expect( @@ -681,7 +682,7 @@ describe('matchesRule', () => { }); // WebFetch domain matching - it('WebFetch domain specifier', () => { + it('WebFetch domain specifier', async () => { const rule = parseRule('WebFetch(domain:example.com)'); expect( matchesRule(rule, 'web_fetch', undefined, undefined, 'example.com'), @@ -697,7 +698,7 @@ describe('matchesRule', () => { }); // Agent literal matching - it('Agent literal specifier', () => { + it('Agent literal specifier', async () => { const rule = parseRule('Agent(Explore)'); // Agent is an alias for 'task'; specifier matches via the specifier field expect( @@ -726,26 +727,26 @@ describe('matchesRule', () => { }); // MCP tool matching - it('MCP tool exact match', () => { + it('MCP tool exact match', async () => { const rule = parseRule('mcp__puppeteer__puppeteer_navigate'); expect(matchesRule(rule, 'mcp__puppeteer__puppeteer_navigate')).toBe(true); expect(matchesRule(rule, 'mcp__puppeteer__puppeteer_click')).toBe(false); }); - it('MCP server-level match (2-part pattern)', () => { + it('MCP server-level match (2-part pattern)', async () => { const rule = parseRule('mcp__puppeteer'); expect(matchesRule(rule, 'mcp__puppeteer__puppeteer_navigate')).toBe(true); expect(matchesRule(rule, 'mcp__puppeteer__puppeteer_click')).toBe(true); expect(matchesRule(rule, 'mcp__other__tool')).toBe(false); }); - it('MCP wildcard match', () => { + it('MCP wildcard match', async () => { const rule = parseRule('mcp__puppeteer__*'); expect(matchesRule(rule, 'mcp__puppeteer__puppeteer_navigate')).toBe(true); expect(matchesRule(rule, 'mcp__other__tool')).toBe(false); }); - it('MCP intra-segment wildcard match (e.g. mcp__chrome__use_*)', () => { + it('MCP intra-segment wildcard match (e.g. mcp__chrome__use_*)', async () => { const rule = parseRule('mcp__chrome__use_*'); expect(matchesRule(rule, 'mcp__chrome__use_browser')).toBe(true); expect(matchesRule(rule, 'mcp__chrome__use_context')).toBe(true); @@ -791,25 +792,25 @@ describe('PermissionManager', () => { pm.initialize(); }); - it('returns deny for a denied tool', () => { - expect(pm.evaluate({ toolName: 'run_shell_command' })).toBe('deny'); + it('returns deny for a denied tool', async () => { + expect(await pm.evaluate({ toolName: 'run_shell_command' })).toBe('deny'); }); - it('returns ask for an ask-rule tool', () => { - expect(pm.evaluate({ toolName: 'write_file' })).toBe('ask'); + it('returns ask for an ask-rule tool', async () => { + expect(await pm.evaluate({ toolName: 'write_file' })).toBe('ask'); }); - it('returns allow for an allow-rule tool', () => { - expect(pm.evaluate({ toolName: 'read_file' })).toBe('allow'); + it('returns allow for an allow-rule tool', async () => { + expect(await pm.evaluate({ toolName: 'read_file' })).toBe('allow'); }); - it('returns default for unmatched tool', () => { + it('returns default for unmatched tool', async () => { // Note: 'glob' is covered by ReadFileTool via Read meta-category, // so use a tool not in any rule or meta-category - expect(pm.evaluate({ toolName: 'agent' })).toBe('default'); + expect(await pm.evaluate({ toolName: 'agent' })).toBe('default'); }); - it('deny takes precedence over ask and allow', () => { + it('deny takes precedence over ask and allow', async () => { const pm2 = new PermissionManager( makeConfig({ permissionsAllow: ['run_shell_command'], @@ -818,10 +819,12 @@ describe('PermissionManager', () => { }), ); pm2.initialize(); - expect(pm2.evaluate({ toolName: 'run_shell_command' })).toBe('deny'); + expect(await pm2.evaluate({ toolName: 'run_shell_command' })).toBe( + 'deny', + ); }); - it('ask takes precedence over allow', () => { + it('ask takes precedence over allow', async () => { const pm2 = new PermissionManager( makeConfig({ permissionsAllow: ['write_file'], @@ -829,7 +832,7 @@ describe('PermissionManager', () => { }), ); pm2.initialize(); - expect(pm2.evaluate({ toolName: 'write_file' })).toBe('ask'); + expect(await pm2.evaluate({ toolName: 'write_file' })).toBe('ask'); }); }); @@ -844,33 +847,51 @@ describe('PermissionManager', () => { pm.initialize(); }); - it('allows a matching allowed command', () => { + it('allows a matching allowed command', async () => { expect( - pm.evaluate({ toolName: 'run_shell_command', command: 'git status' }), + await pm.evaluate({ + toolName: 'run_shell_command', + command: 'git status', + }), ).toBe('allow'); }); - it('denies a matching denied command', () => { + it('denies a matching denied command', async () => { expect( - pm.evaluate({ toolName: 'run_shell_command', command: 'rm -rf /' }), + await pm.evaluate({ + toolName: 'run_shell_command', + command: 'rm -rf /', + }), ).toBe('deny'); }); - it('returns default for an unmatched command', () => { + it('resolves default to allow for readonly commands, ask for others', async () => { + // 'echo' is a readonly command, so it resolves to 'allow' expect( - pm.evaluate({ toolName: 'run_shell_command', command: 'echo hello' }), - ).toBe('default'); + await pm.evaluate({ + toolName: 'run_shell_command', + command: 'echo hello', + }), + ).toBe('allow'); + // 'npm install' is not readonly, so it resolves to 'ask' + expect( + await pm.evaluate({ + toolName: 'run_shell_command', + command: 'npm install', + }), + ).toBe('ask'); }); - it('isCommandAllowed delegates to evaluate', () => { - expect(pm.isCommandAllowed('git commit')).toBe('allow'); - expect(pm.isCommandAllowed('rm -rf /')).toBe('deny'); - expect(pm.isCommandAllowed('ls')).toBe('default'); + it('isCommandAllowed delegates to evaluate', async () => { + expect(await pm.isCommandAllowed('git commit')).toBe('allow'); + expect(await pm.isCommandAllowed('rm -rf /')).toBe('deny'); + // 'ls' is readonly, resolves to 'allow' when no rule matches + expect(await pm.isCommandAllowed('ls')).toBe('allow'); }); }); describe('compound command evaluation', () => { - it('all sub-commands allowed → allow', () => { + it('all sub-commands allowed → allow', async () => { pm = new PermissionManager( makeConfig({ permissionsAllow: ['Bash(safe-cmd *)', 'Bash(one-cmd *)'], @@ -878,29 +899,30 @@ describe('PermissionManager', () => { ); pm.initialize(); expect( - pm.evaluate({ + await pm.evaluate({ toolName: 'run_shell_command', command: 'safe-cmd arg1 && one-cmd arg2', }), ).toBe('allow'); }); - it('one sub-command unmatched → default (most restrictive)', () => { + it('one sub-command unmatched (non-readonly) → ask (resolved from default)', async () => { pm = new PermissionManager( makeConfig({ permissionsAllow: ['Bash(safe-cmd *)'], }), ); pm.initialize(); + // 'two-cmd' is unknown/non-readonly, so its default permission is 'ask' expect( - pm.evaluate({ + await pm.evaluate({ toolName: 'run_shell_command', command: 'safe-cmd && two-cmd', }), - ).toBe('default'); + ).toBe('ask'); }); - it('one sub-command denied → deny', () => { + it('one sub-command denied → deny', async () => { pm = new PermissionManager( makeConfig({ permissionsAllow: ['Bash(safe-cmd *)'], @@ -909,14 +931,14 @@ describe('PermissionManager', () => { ); pm.initialize(); expect( - pm.evaluate({ + await pm.evaluate({ toolName: 'run_shell_command', command: 'safe-cmd && evil-cmd rm-all', }), ).toBe('deny'); }); - it('one sub-command ask + one allow → ask', () => { + it('one sub-command ask + one allow → ask', async () => { pm = new PermissionManager( makeConfig({ permissionsAllow: ['Bash(git *)'], @@ -925,14 +947,14 @@ describe('PermissionManager', () => { ); pm.initialize(); expect( - pm.evaluate({ + await pm.evaluate({ toolName: 'run_shell_command', command: 'git status && npm publish', }), ).toBe('ask'); }); - it('pipe compound: all matched → allow', () => { + it('pipe compound: all matched → allow', async () => { pm = new PermissionManager( makeConfig({ permissionsAllow: ['Bash(git *)', 'Bash(grep *)'], @@ -940,29 +962,30 @@ describe('PermissionManager', () => { ); pm.initialize(); expect( - pm.evaluate({ + await pm.evaluate({ toolName: 'run_shell_command', command: 'git log | grep fix', }), ).toBe('allow'); }); - it('pipe compound: second unmatched → default', () => { + it('pipe compound: second unmatched but readonly → allow (resolved from default)', async () => { pm = new PermissionManager( makeConfig({ permissionsAllow: ['Bash(git *)'], }), ); pm.initialize(); + // 'grep' is a readonly command, so its default permission is 'allow' expect( - pm.evaluate({ + await pm.evaluate({ toolName: 'run_shell_command', command: 'git log | grep fix', }), - ).toBe('default'); + ).toBe('allow'); }); - it('semicolon compound: deny in second → deny', () => { + it('semicolon compound: deny in second → deny', async () => { pm = new PermissionManager( makeConfig({ permissionsAllow: ['Bash(echo *)'], @@ -971,14 +994,14 @@ describe('PermissionManager', () => { ); pm.initialize(); expect( - pm.evaluate({ + await pm.evaluate({ toolName: 'run_shell_command', command: 'echo hello; rm -rf /', }), ).toBe('deny'); }); - it('|| compound: all allowed → allow', () => { + it('|| compound: all allowed → allow', async () => { pm = new PermissionManager( makeConfig({ permissionsAllow: ['Bash(git *)', 'Bash(echo *)'], @@ -986,14 +1009,14 @@ describe('PermissionManager', () => { ); pm.initialize(); expect( - pm.evaluate({ + await pm.evaluate({ toolName: 'run_shell_command', command: 'git push || echo failed', }), ).toBe('allow'); }); - it('operators inside quotes: treated as single command', () => { + it('operators inside quotes: treated as single command', async () => { pm = new PermissionManager( makeConfig({ permissionsAllow: ['Bash(echo *)'], @@ -1001,14 +1024,14 @@ describe('PermissionManager', () => { ); pm.initialize(); expect( - pm.evaluate({ + await pm.evaluate({ toolName: 'run_shell_command', command: "echo 'a && b'", }), ).toBe('allow'); }); - it('three-part compound: all must pass', () => { + it('three-part compound: all must pass', async () => { pm = new PermissionManager( makeConfig({ permissionsAllow: ['Bash(git *)', 'Bash(npm *)', 'Bash(echo *)'], @@ -1016,29 +1039,30 @@ describe('PermissionManager', () => { ); pm.initialize(); expect( - pm.evaluate({ + await pm.evaluate({ toolName: 'run_shell_command', command: 'git add . && npm test && echo done', }), ).toBe('allow'); }); - it('three-part compound: one unmatched → default', () => { + it('three-part compound: one unmatched (non-readonly) → ask (resolved from default)', async () => { pm = new PermissionManager( makeConfig({ permissionsAllow: ['Bash(git *)', 'Bash(echo *)'], }), ); pm.initialize(); + // 'npm test' is not readonly, so its default permission is 'ask' expect( - pm.evaluate({ + await pm.evaluate({ toolName: 'run_shell_command', command: 'git add . && npm test && echo done', }), - ).toBe('default'); + ).toBe('ask'); }); - it('isCommandAllowed also handles compound commands', () => { + it('isCommandAllowed also handles compound commands', async () => { pm = new PermissionManager( makeConfig({ permissionsAllow: ['Bash(safe-cmd *)', 'Bash(one-cmd *)'], @@ -1046,9 +1070,16 @@ describe('PermissionManager', () => { }), ); pm.initialize(); - expect(pm.isCommandAllowed('safe-cmd a && one-cmd b')).toBe('allow'); - expect(pm.isCommandAllowed('safe-cmd a && unknown-cmd')).toBe('default'); - expect(pm.isCommandAllowed('safe-cmd a && evil-cmd b')).toBe('deny'); + expect(await pm.isCommandAllowed('safe-cmd a && one-cmd b')).toBe( + 'allow', + ); + // 'unknown-cmd' is not readonly, resolves to 'ask' + expect(await pm.isCommandAllowed('safe-cmd a && unknown-cmd')).toBe( + 'ask', + ); + expect(await pm.isCommandAllowed('safe-cmd a && evil-cmd b')).toBe( + 'deny', + ); }); }); @@ -1065,39 +1096,42 @@ describe('PermissionManager', () => { pm.initialize(); }); - it('denies reading a denied file', () => { + it('denies reading a denied file', async () => { expect( - pm.evaluate({ toolName: 'read_file', filePath: '/project/.env' }), + await pm.evaluate({ toolName: 'read_file', filePath: '/project/.env' }), ).toBe('deny'); }); - it('denies editing in a denied directory', () => { + it('denies editing in a denied directory', async () => { expect( - pm.evaluate({ + await pm.evaluate({ toolName: 'edit', filePath: '/project/src/generated/code.ts', }), ).toBe('deny'); }); - it('allows reading in an allowed directory', () => { + it('allows reading in an allowed directory', async () => { expect( - pm.evaluate({ + await pm.evaluate({ toolName: 'read_file', filePath: '/project/docs/readme.md', }), ).toBe('allow'); }); - it('Read deny applies to grep_search too (meta-category)', () => { + it('Read deny applies to grep_search too (meta-category)', async () => { expect( - pm.evaluate({ toolName: 'grep_search', filePath: '/project/.env' }), + await pm.evaluate({ + toolName: 'grep_search', + filePath: '/project/.env', + }), ).toBe('deny'); }); - it('returns default for unmatched path', () => { + it('returns default for unmatched path', async () => { expect( - pm.evaluate({ + await pm.evaluate({ toolName: 'read_file', filePath: '/project/src/index.ts', }), @@ -1116,89 +1150,89 @@ describe('PermissionManager', () => { pm.initialize(); }); - it('allows fetch to allowed domain', () => { - expect(pm.evaluate({ toolName: 'web_fetch', domain: 'github.com' })).toBe( - 'allow', - ); - }); - - it('allows fetch to subdomain of allowed domain', () => { + it('allows fetch to allowed domain', async () => { expect( - pm.evaluate({ toolName: 'web_fetch', domain: 'api.github.com' }), + await pm.evaluate({ toolName: 'web_fetch', domain: 'github.com' }), ).toBe('allow'); }); - it('denies fetch to denied domain', () => { - expect(pm.evaluate({ toolName: 'web_fetch', domain: 'evil.com' })).toBe( - 'deny', - ); + it('allows fetch to subdomain of allowed domain', async () => { + expect( + await pm.evaluate({ toolName: 'web_fetch', domain: 'api.github.com' }), + ).toBe('allow'); }); - it('returns default for unmatched domain', () => { + it('denies fetch to denied domain', async () => { expect( - pm.evaluate({ toolName: 'web_fetch', domain: 'example.com' }), + await pm.evaluate({ toolName: 'web_fetch', domain: 'evil.com' }), + ).toBe('deny'); + }); + + it('returns default for unmatched domain', async () => { + expect( + await pm.evaluate({ toolName: 'web_fetch', domain: 'example.com' }), ).toBe('default'); }); }); describe('isToolEnabled', () => { - it('returns false for deny-ruled tools', () => { + it('returns false for deny-ruled tools', async () => { pm = new PermissionManager( makeConfig({ permissionsDeny: ['ShellTool'] }), ); pm.initialize(); - expect(pm.isToolEnabled('run_shell_command')).toBe(false); + expect(await pm.isToolEnabled('run_shell_command')).toBe(false); }); - it('returns true for tools with only specifier deny rules', () => { + it('returns true for tools with only specifier deny rules', async () => { pm = new PermissionManager( makeConfig({ permissionsDeny: ['Bash(rm *)'] }), ); pm.initialize(); - expect(pm.isToolEnabled('run_shell_command')).toBe(true); + expect(await pm.isToolEnabled('run_shell_command')).toBe(true); }); - it('excludeTools passed via permissionsDeny disables the tool', () => { + it('excludeTools passed via permissionsDeny disables the tool', async () => { pm = new PermissionManager( makeConfig({ permissionsDeny: ['run_shell_command'] }), ); pm.initialize(); - expect(pm.isToolEnabled('run_shell_command')).toBe(false); + expect(await pm.isToolEnabled('run_shell_command')).toBe(false); }); - it('coreTools allowlist: listed tool is enabled', () => { + it('coreTools allowlist: listed tool is enabled', async () => { pm = new PermissionManager( makeConfig({ coreTools: ['read_file', 'Bash'] }), ); pm.initialize(); - expect(pm.isToolEnabled('read_file')).toBe(true); - expect(pm.isToolEnabled('run_shell_command')).toBe(true); // Bash resolves to run_shell_command + expect(await pm.isToolEnabled('read_file')).toBe(true); + expect(await pm.isToolEnabled('run_shell_command')).toBe(true); // Bash resolves to run_shell_command }); - it('coreTools allowlist: unlisted tool is disabled', () => { + it('coreTools allowlist: unlisted tool is disabled', async () => { pm = new PermissionManager(makeConfig({ coreTools: ['read_file'] })); pm.initialize(); - expect(pm.isToolEnabled('read_file')).toBe(true); - expect(pm.isToolEnabled('run_shell_command')).toBe(false); - expect(pm.isToolEnabled('edit')).toBe(false); + expect(await pm.isToolEnabled('read_file')).toBe(true); + expect(await pm.isToolEnabled('run_shell_command')).toBe(false); + expect(await pm.isToolEnabled('edit')).toBe(false); }); - it('coreTools with specifier: tool-level check strips specifier', () => { + it('coreTools with specifier: tool-level check strips specifier', async () => { // "Bash(ls -l)" should register run_shell_command (specifier only affects runtime) pm = new PermissionManager(makeConfig({ coreTools: ['Bash(ls -l)'] })); pm.initialize(); - expect(pm.isToolEnabled('run_shell_command')).toBe(true); - expect(pm.isToolEnabled('read_file')).toBe(false); + expect(await pm.isToolEnabled('run_shell_command')).toBe(true); + expect(await pm.isToolEnabled('read_file')).toBe(false); }); - it('empty coreTools: all tools enabled (no whitelist restriction)', () => { + it('empty coreTools: all tools enabled (no whitelist restriction)', async () => { pm = new PermissionManager(makeConfig({ coreTools: [] })); pm.initialize(); - expect(pm.isToolEnabled('read_file')).toBe(true); - expect(pm.isToolEnabled('run_shell_command')).toBe(true); + expect(await pm.isToolEnabled('read_file')).toBe(true); + expect(await pm.isToolEnabled('run_shell_command')).toBe(true); }); - it('coreTools allowlist + deny rule: deny takes precedence for listed tools', () => { + it('coreTools allowlist + deny rule: deny takes precedence for listed tools', async () => { pm = new PermissionManager( makeConfig({ coreTools: ['read_file', 'Bash'], @@ -1206,19 +1240,19 @@ describe('PermissionManager', () => { }), ); pm.initialize(); - expect(pm.isToolEnabled('read_file')).toBe(true); - expect(pm.isToolEnabled('run_shell_command')).toBe(false); // in list but denied + expect(await pm.isToolEnabled('read_file')).toBe(true); + expect(await pm.isToolEnabled('run_shell_command')).toBe(false); // in list but denied }); - it('permissionsAllow alone does NOT restrict unlisted tools (not a whitelist)', () => { + it('permissionsAllow alone does NOT restrict unlisted tools (not a whitelist)', async () => { // This verifies the previous incorrect behavior is gone: permissionsAllow // only means "auto-approve", it does NOT block unlisted tools. pm = new PermissionManager( makeConfig({ permissionsAllow: ['read_file'] }), ); pm.initialize(); - expect(pm.isToolEnabled('read_file')).toBe(true); - expect(pm.isToolEnabled('run_shell_command')).toBe(true); // not denied, just unreviewed + expect(await pm.isToolEnabled('read_file')).toBe(true); + expect(await pm.isToolEnabled('run_shell_command')).toBe(true); // not denied, just unreviewed }); }); @@ -1228,38 +1262,48 @@ describe('PermissionManager', () => { pm.initialize(); }); - it('addSessionAllowRule enables auto-approval for that pattern', () => { + it('addSessionAllowRule enables auto-approval for that pattern', async () => { + // Use 'git commit' which is not readonly, so it resolves to 'ask' by default expect( - pm.evaluate({ toolName: 'run_shell_command', command: 'git status' }), - ).toBe('default'); + await pm.evaluate({ + toolName: 'run_shell_command', + command: 'git commit', + }), + ).toBe('ask'); pm.addSessionAllowRule('Bash(git *)'); expect( - pm.evaluate({ toolName: 'run_shell_command', command: 'git status' }), + await pm.evaluate({ + toolName: 'run_shell_command', + command: 'git commit', + }), ).toBe('allow'); }); - it('session deny rules override allow rules', () => { + it('session deny rules override allow rules', async () => { pm.addSessionAllowRule('run_shell_command'); pm.addSessionDenyRule('run_shell_command'); - expect(pm.evaluate({ toolName: 'run_shell_command' })).toBe('deny'); + expect(await pm.evaluate({ toolName: 'run_shell_command' })).toBe('deny'); }); }); describe('allowedTools via permissionsAllow', () => { - it('allow rule auto-approves matching tools/commands', () => { + it('allow rule auto-approves matching tools/commands', async () => { pm = new PermissionManager( makeConfig({ permissionsAllow: ['ReadFileTool', 'Bash(git *)'] }), ); pm.initialize(); - expect(pm.evaluate({ toolName: 'read_file' })).toBe('allow'); + expect(await pm.evaluate({ toolName: 'read_file' })).toBe('allow'); expect( - pm.evaluate({ toolName: 'run_shell_command', command: 'git status' }), + await pm.evaluate({ + toolName: 'run_shell_command', + command: 'git status', + }), ).toBe('allow'); }); }); describe('listRules', () => { - it('returns all rules with type and scope', () => { + it('returns all rules with type and scope', async () => { pm = new PermissionManager( makeConfig({ permissionsAllow: ['ReadFileTool'], @@ -1277,37 +1321,67 @@ describe('PermissionManager', () => { expect(sessionAllow?.rule.toolName).toBe('run_shell_command'); }); }); + + describe('hasMatchingAskRule', () => { + it('returns false when shell ask comes only from default permission fallback', async () => { + pm = new PermissionManager( + makeConfig({ permissionsAllow: ['Bash(git add *)'] }), + ); + pm.initialize(); + + expect( + pm.hasMatchingAskRule({ + toolName: 'run_shell_command', + command: 'git add file && git commit -m "msg"', + }), + ).toBe(false); + }); + + it('returns true when an explicit ask rule matches a shell sub-command', async () => { + pm = new PermissionManager( + makeConfig({ permissionsAsk: ['Bash(git commit *)'] }), + ); + pm.initialize(); + + expect( + pm.hasMatchingAskRule({ + toolName: 'run_shell_command', + command: 'git add file && git commit -m "msg"', + }), + ).toBe(true); + }); + }); }); // ─── getRuleDisplayName ────────────────────────────────────────────────────── describe('getRuleDisplayName', () => { - it('maps read tools to "Read" meta-category', () => { + it('maps read tools to "Read" meta-category', async () => { expect(getRuleDisplayName('read_file')).toBe('Read'); expect(getRuleDisplayName('grep_search')).toBe('Read'); expect(getRuleDisplayName('glob')).toBe('Read'); expect(getRuleDisplayName('list_directory')).toBe('Read'); }); - it('maps edit tools to "Edit" meta-category', () => { + it('maps edit tools to "Edit" meta-category', async () => { expect(getRuleDisplayName('edit')).toBe('Edit'); expect(getRuleDisplayName('write_file')).toBe('Edit'); }); - it('maps shell to "Bash"', () => { + it('maps shell to "Bash"', async () => { expect(getRuleDisplayName('run_shell_command')).toBe('Bash'); }); - it('maps web_fetch to "WebFetch"', () => { + it('maps web_fetch to "WebFetch"', async () => { expect(getRuleDisplayName('web_fetch')).toBe('WebFetch'); }); - it('maps agent to "Agent" and skill to "Skill"', () => { + it('maps agent to "Agent" and skill to "Skill"', async () => { expect(getRuleDisplayName('agent')).toBe('Agent'); expect(getRuleDisplayName('skill')).toBe('Skill'); }); - it('returns the canonical name for unknown tools (e.g. MCP)', () => { + it('returns the canonical name for unknown tools (e.g. MCP)', async () => { expect(getRuleDisplayName('mcp__server__tool')).toBe('mcp__server__tool'); }); }); @@ -1316,7 +1390,7 @@ describe('getRuleDisplayName', () => { describe('buildPermissionRules', () => { describe('path-based tools (Read/Edit)', () => { - it('generates Read rule scoped to parent directory for read_file', () => { + it('generates Read rule scoped to parent directory for read_file', async () => { const rules = buildPermissionRules({ toolName: 'read_file', filePath: '/Users/alice/.secrets', @@ -1325,7 +1399,7 @@ describe('buildPermissionRules', () => { expect(rules).toEqual(['Read(//Users/alice/**)']); }); - it('generates Read rule with directory as-is for grep_search', () => { + it('generates Read rule with directory as-is for grep_search', async () => { const rules = buildPermissionRules({ toolName: 'grep_search', filePath: '/external/dir', @@ -1334,7 +1408,7 @@ describe('buildPermissionRules', () => { expect(rules).toEqual(['Read(//external/dir/**)']); }); - it('generates Read rule with directory as-is for glob', () => { + it('generates Read rule with directory as-is for glob', async () => { const rules = buildPermissionRules({ toolName: 'glob', filePath: '/tmp/data', @@ -1342,7 +1416,7 @@ describe('buildPermissionRules', () => { expect(rules).toEqual(['Read(//tmp/data/**)']); }); - it('generates Read rule with directory as-is for list_directory', () => { + it('generates Read rule with directory as-is for list_directory', async () => { const rules = buildPermissionRules({ toolName: 'list_directory', filePath: '/home/user/docs', @@ -1350,7 +1424,7 @@ describe('buildPermissionRules', () => { expect(rules).toEqual(['Read(//home/user/docs/**)']); }); - it('generates Edit rule scoped to parent directory for edit', () => { + it('generates Edit rule scoped to parent directory for edit', async () => { const rules = buildPermissionRules({ toolName: 'edit', filePath: '/external/file.ts', @@ -1359,7 +1433,7 @@ describe('buildPermissionRules', () => { expect(rules).toEqual(['Edit(//external/**)']); }); - it('generates Edit rule scoped to parent directory for write_file', () => { + it('generates Edit rule scoped to parent directory for write_file', async () => { const rules = buildPermissionRules({ toolName: 'write_file', filePath: '/tmp/output.txt', @@ -1367,14 +1441,14 @@ describe('buildPermissionRules', () => { expect(rules).toEqual(['Edit(//tmp/**)']); }); - it('falls back to bare display name when no filePath', () => { + it('falls back to bare display name when no filePath', async () => { const rules = buildPermissionRules({ toolName: 'read_file' }); expect(rules).toEqual(['Read']); }); }); describe('generated rules round-trip through parseRule and matchesRule', () => { - it('Read rule for external file covers the containing directory', () => { + it('Read rule for external file covers the containing directory', async () => { const rules = buildPermissionRules({ toolName: 'read_file', filePath: '/Users/alice/.secrets', @@ -1424,7 +1498,7 @@ describe('buildPermissionRules', () => { ).toBe(false); }); - it('Read rule also matches other read-family tools on the same path', () => { + it('Read rule also matches other read-family tools on the same path', async () => { const rules = buildPermissionRules({ toolName: 'grep_search', filePath: '/external/dir', @@ -1458,7 +1532,7 @@ describe('buildPermissionRules', () => { }); describe('domain-based tools', () => { - it('generates WebFetch rule with domain specifier', () => { + it('generates WebFetch rule with domain specifier', async () => { const rules = buildPermissionRules({ toolName: 'web_fetch', domain: 'example.com', @@ -1466,14 +1540,14 @@ describe('buildPermissionRules', () => { expect(rules).toEqual(['WebFetch(example.com)']); }); - it('falls back to bare display name when no domain', () => { + it('falls back to bare display name when no domain', async () => { const rules = buildPermissionRules({ toolName: 'web_fetch' }); expect(rules).toEqual(['WebFetch']); }); }); describe('command-based tools', () => { - it('generates Bash rule with command specifier', () => { + it('generates Bash rule with command specifier', async () => { const rules = buildPermissionRules({ toolName: 'run_shell_command', command: 'git status', @@ -1481,14 +1555,14 @@ describe('buildPermissionRules', () => { expect(rules).toEqual(['Bash(git status)']); }); - it('falls back to bare display name when no command', () => { + it('falls back to bare display name when no command', async () => { const rules = buildPermissionRules({ toolName: 'run_shell_command' }); expect(rules).toEqual(['Bash']); }); }); describe('literal-specifier tools', () => { - it('generates Skill rule with specifier', () => { + it('generates Skill rule with specifier', async () => { const rules = buildPermissionRules({ toolName: 'skill', specifier: 'Explore', @@ -1496,7 +1570,7 @@ describe('buildPermissionRules', () => { expect(rules).toEqual(['Skill(Explore)']); }); - it('generates Agent rule with specifier', () => { + it('generates Agent rule with specifier', async () => { const rules = buildPermissionRules({ toolName: 'agent', specifier: 'research', @@ -1504,14 +1578,14 @@ describe('buildPermissionRules', () => { expect(rules).toEqual(['Agent(research)']); }); - it('falls back to bare display name when no specifier', () => { + it('falls back to bare display name when no specifier', async () => { const rules = buildPermissionRules({ toolName: 'skill' }); expect(rules).toEqual(['Skill']); }); }); describe('unknown / MCP tools', () => { - it('uses the canonical name as display for MCP tools', () => { + it('uses the canonical name as display for MCP tools', async () => { const rules = buildPermissionRules({ toolName: 'mcp__puppeteer__navigate', }); @@ -1519,3 +1593,174 @@ describe('buildPermissionRules', () => { }); }); }); + +// ─── buildHumanReadableRuleLabel ───────────────────────────────────────────── + +describe('buildHumanReadableRuleLabel', () => { + it('returns empty string for empty rules array', () => { + expect(buildHumanReadableRuleLabel([])).toBe(''); + }); + + it('converts bare Read rule to "read files"', () => { + expect(buildHumanReadableRuleLabel(['Read'])).toBe('read files'); + }); + + it('converts bare Bash rule to "run commands"', () => { + expect(buildHumanReadableRuleLabel(['Bash'])).toBe('run commands'); + }); + + it('converts bare WebSearch rule to "search the web"', () => { + expect(buildHumanReadableRuleLabel(['WebSearch'])).toBe('search the web'); + }); + + it('converts Read with absolute path specifier', () => { + const label = buildHumanReadableRuleLabel(['Read(//Users/mochi/.qwen/**)']); + expect(label).toBe('read files in /Users/mochi/.qwen/'); + }); + + it('converts Read with relative path specifier', () => { + const label = buildHumanReadableRuleLabel(['Read(/src/**)']); + expect(label).toBe('read files in /src/'); + }); + + it('converts Edit with path specifier', () => { + const label = buildHumanReadableRuleLabel(['Edit(//tmp/**)']); + expect(label).toBe('edit files in /tmp/'); + }); + + it('converts Bash with command specifier', () => { + const label = buildHumanReadableRuleLabel(['Bash(git *)']); + expect(label).toBe("run 'git *' commands"); + }); + + it('converts WebFetch with domain specifier', () => { + const label = buildHumanReadableRuleLabel(['WebFetch(github.com)']); + expect(label).toBe('fetch from github.com'); + }); + + it('converts Skill with literal specifier', () => { + const label = buildHumanReadableRuleLabel(['Skill(Explore)']); + expect(label).toBe('use skill "Explore"'); + }); + + it('converts Agent with literal specifier', () => { + const label = buildHumanReadableRuleLabel(['Agent(research)']); + expect(label).toBe('use agent "research"'); + }); + + it('joins multiple rules with commas', () => { + const label = buildHumanReadableRuleLabel([ + 'Read(//Users/alice/**)', + 'Bash(npm *)', + ]); + expect(label).toBe("read files in /Users/alice/, run 'npm *' commands"); + }); + + it('handles unknown display names gracefully', () => { + const label = buildHumanReadableRuleLabel(['mcp__server__tool']); + expect(label).toBe('mcp__server__tool'); + }); + + it('handles unknown display name with specifier', () => { + const label = buildHumanReadableRuleLabel(['UnknownCategory(someValue)']); + expect(label).toBe('unknowncategory "someValue"'); + }); + + it('cleans path with /* suffix', () => { + const label = buildHumanReadableRuleLabel(['Read(//home/user/docs/*)']); + expect(label).toBe('read files in /home/user/docs/'); + }); + + it('round-trips from buildPermissionRules for file tool', () => { + const rules = buildPermissionRules({ + toolName: 'read_file', + filePath: '/Users/alice/.secrets', + }); + const label = buildHumanReadableRuleLabel(rules); + expect(label).toBe('read files in /Users/alice/'); + }); + + it('round-trips from buildPermissionRules for shell command', () => { + const rules = buildPermissionRules({ + toolName: 'run_shell_command', + command: 'git status', + }); + const label = buildHumanReadableRuleLabel(rules); + expect(label).toBe("run 'git status' commands"); + }); + + it('round-trips from buildPermissionRules for web fetch', () => { + const rules = buildPermissionRules({ + toolName: 'web_fetch', + domain: 'example.com', + }); + const label = buildHumanReadableRuleLabel(rules); + expect(label).toBe('fetch from example.com'); + }); +}); + +// ─── PermissionManager.findMatchingDenyRule ────────────────────────────────── + +describe('PermissionManager.findMatchingDenyRule', () => { + it('returns the raw deny rule string when context matches', () => { + const pm = new PermissionManager( + makeConfig({ permissionsDeny: ['Bash(rm *)'] }), + ); + pm.initialize(); + + const result = pm.findMatchingDenyRule({ + toolName: 'run_shell_command', + command: 'rm -rf /tmp/foo', + }); + expect(result).toBe('Bash(rm *)'); + }); + + it('returns undefined when no deny rule matches', () => { + const pm = new PermissionManager( + makeConfig({ permissionsDeny: ['Bash(rm *)'] }), + ); + pm.initialize(); + + const result = pm.findMatchingDenyRule({ + toolName: 'run_shell_command', + command: 'git status', + }); + expect(result).toBeUndefined(); + }); + + it('matches session deny rules', () => { + const pm = new PermissionManager(makeConfig()); + pm.initialize(); + pm.addSessionDenyRule('Read(//secret/**)'); + + const result = pm.findMatchingDenyRule({ + toolName: 'read_file', + filePath: '/secret/key.pem', + }); + expect(result).toBe('Read(//secret/**)'); + }); + + it('returns undefined for non-denied tool', () => { + const pm = new PermissionManager( + makeConfig({ permissionsDeny: ['ShellTool'] }), + ); + pm.initialize(); + + const result = pm.findMatchingDenyRule({ toolName: 'read_file' }); + expect(result).toBeUndefined(); + }); + + it('matches bare tool deny rule', () => { + const pm = new PermissionManager( + makeConfig({ permissionsDeny: ['ShellTool'] }), + ); + pm.initialize(); + + const result = pm.findMatchingDenyRule({ + toolName: 'run_shell_command', + command: 'echo hello', + }); + // rule.raw preserves the original rule string as written in config + expect(result).toBe('ShellTool'); + }); +}); diff --git a/packages/core/src/permissions/permission-manager.ts b/packages/core/src/permissions/permission-manager.ts index 06f0548b0..e17fac881 100644 --- a/packages/core/src/permissions/permission-manager.ts +++ b/packages/core/src/permissions/permission-manager.ts @@ -14,6 +14,8 @@ import { import type { PathMatchContext } from './rule-parser.js'; import { extractShellOperations } from './shell-semantics.js'; import type { ShellOperation } from './shell-semantics.js'; +import { isShellCommandReadOnlyAST } from '../utils/shellAstParser.js'; +import { detectCommandSubstitution } from '../utils/shell-utils.js'; import type { PermissionCheckContext, PermissionDecision, @@ -153,12 +155,12 @@ export class PermissionManager { * @param ctx - The context containing the tool name and optional command. * @returns A PermissionDecision indicating how to handle this tool call. */ - evaluate(ctx: PermissionCheckContext): PermissionDecision { - const { command } = ctx; + async evaluate(ctx: PermissionCheckContext): Promise { + const { command, toolName } = ctx; // For shell commands, split compound commands and evaluate each // sub-command independently, then return the most restrictive result. - // Priority order (most to least restrictive): deny > ask > default > allow + // Priority order (most to least restrictive): deny > ask > allow if (command !== undefined) { const subCommands = splitCompoundCommand(command); if (subCommands.length > 1) { @@ -166,7 +168,20 @@ export class PermissionManager { } } - return this.evaluateSingle(ctx); + const decision = this.evaluateSingle(ctx); + + // For shell commands, resolve 'default' to actual permission using AST analysis + // This ensures 'default' is never returned for shell commands - they always get + // a concrete permission (deny/ask/allow) based on the command's readonly status. + if ( + decision === 'default' && + toolName === 'run_shell_command' && + command !== undefined + ) { + return this.resolveDefaultPermission(command); + } + + return decision; } /** @@ -295,32 +310,46 @@ export class PermissionManager { * Evaluate a compound command by splitting it into sub-commands, * evaluating each independently, and returning the most restrictive result. * - * Restriction order: deny > ask > default > allow + * Restriction order: deny > ask > allow * - * Example: with rules `allow: [safe-cmd *, one-cmd *]` - * - "safe-cmd && one-cmd" → both allow → allow - * - "safe-cmd && two-cmd" → allow + default → default - * - "safe-cmd && evil-cmd" (deny: [evil-cmd]) → allow + deny → deny + * When a sub-command returns 'default' (no rule matches), it is resolved to + * the actual default permission using AST analysis: + * - Command substitution detected → 'deny' + * - Read-only command (cd, ls, git status, etc.) → 'allow' + * - Otherwise → 'ask' + * + * Example: with rules `allow: [git checkout *]` + * - "cd /path && git checkout -b feature" → allow (cd) + allow (rule) → allow + * - "rm /path && git checkout -b feature" → ask (rm) + allow (rule) → ask + * - "evil-cmd && git checkout" (deny: [evil-cmd]) → deny + allow → deny */ - private evaluateCompoundCommand( + private async evaluateCompoundCommand( ctx: PermissionCheckContext, subCommands: string[], - ): PermissionDecision { - const PRIORITY: Record = { + ): Promise { + // Type for resolved decisions (excludes 'default' since it's resolved) + type ResolvedDecision = 'allow' | 'ask' | 'deny'; + const PRIORITY: Record = { deny: 3, ask: 2, - default: 1, allow: 0, }; - let mostRestrictive: PermissionDecision = 'allow'; + let mostRestrictive: ResolvedDecision = 'allow'; for (const subCmd of subCommands) { const subCtx: PermissionCheckContext = { ...ctx, command: subCmd, }; - const decision = this.evaluateSingle(subCtx); + const rawDecision = this.evaluateSingle(subCtx); + + // Resolve 'default' to actual permission using AST analysis + // (same logic as ShellToolInvocation.getDefaultPermission) + const decision: ResolvedDecision = + rawDecision === 'default' + ? await this.resolveDefaultPermission(subCmd) + : (rawDecision as ResolvedDecision); if (PRIORITY[decision] > PRIORITY[mostRestrictive]) { mostRestrictive = decision; @@ -335,6 +364,34 @@ export class PermissionManager { return mostRestrictive; } + /** + * Resolve 'default' permission to actual permission using AST analysis. + * This mirrors the logic in ShellToolInvocation.getDefaultPermission(). + * + * @param command - The shell command to analyze. + * @returns 'deny' for command substitution, 'allow' for read-only, 'ask' otherwise. + */ + private async resolveDefaultPermission( + command: string, + ): Promise<'allow' | 'ask' | 'deny'> { + // Security: command substitution ($(), ``, <(), >()) → deny + if (detectCommandSubstitution(command)) { + return 'deny'; + } + + // AST-based read-only detection + try { + const isReadOnly = await isShellCommandReadOnlyAST(command); + if (isReadOnly) { + return 'allow'; + } + } catch { + // AST check failed, fall back to 'ask' + } + + return 'ask'; + } + // --------------------------------------------------------------------------- // Registry-level helper // --------------------------------------------------------------------------- @@ -347,7 +404,7 @@ export class PermissionManager { * `"Bash(rm -rf *)"` do NOT remove the tool from the registry – they only * deny specific invocations at runtime. */ - isToolEnabled(toolName: string): boolean { + async isToolEnabled(toolName: string): Promise { const canonicalName = resolveToolName(toolName); // If a coreTools allowlist is active, only explicitly listed tools are @@ -361,10 +418,47 @@ export class PermissionManager { // evaluate({ toolName }) without a command will only match rules that have // no specifier, which is the correct registry-level check. - const decision = this.evaluate({ toolName: canonicalName }); + const decision = await this.evaluate({ toolName: canonicalName }); return decision !== 'deny'; } + /** + * Find the first deny rule that matches the given context. + * Returns the raw rule string if found, or undefined if no deny rule matches. + * + * Useful for providing user-visible feedback about which rule caused a denial. + */ + findMatchingDenyRule(ctx: PermissionCheckContext): string | undefined { + const { toolName, command, filePath, domain, specifier } = ctx; + + const pathCtx: PathMatchContext | undefined = + this.config.getProjectRoot && this.config.getCwd + ? { + projectRoot: this.config.getProjectRoot(), + cwd: this.config.getCwd(), + } + : undefined; + + const matchArgs = [ + toolName, + command, + filePath, + domain, + pathCtx, + specifier, + ] as const; + + for (const rule of [ + ...this.sessionRules.deny, + ...this.persistentRules.deny, + ]) { + if (matchesRule(rule, ...matchArgs)) { + return rule.raw; + } + } + return undefined; + } + // --------------------------------------------------------------------------- // Shell command helper // --------------------------------------------------------------------------- @@ -375,7 +469,7 @@ export class PermissionManager { * @param command - The shell command to evaluate. * @returns The PermissionDecision for this command. */ - isCommandAllowed(command: string): PermissionDecision { + async isCommandAllowed(command: string): Promise { return this.evaluate({ toolName: 'run_shell_command', command, @@ -410,6 +504,15 @@ export class PermissionManager { hasRelevantRules(ctx: PermissionCheckContext): boolean { const { toolName, command, filePath, domain, specifier } = ctx; + if (ctx.toolName === 'run_shell_command' && command !== undefined) { + const subCommands = splitCompoundCommand(command); + if (subCommands.length > 1) { + return subCommands.some((subCmd) => + this.hasRelevantRules({ ...ctx, command: subCmd }), + ); + } + } + const pathCtx: PathMatchContext | undefined = this.config.getProjectRoot && this.config.getCwd ? { @@ -465,6 +568,69 @@ export class PermissionManager { return false; } + /** + * Returns true when the invocation is matched by an explicit `ask` rule. + * + * This is intentionally narrower than `evaluate(ctx) === 'ask'`. Shell + * commands can resolve to `ask` simply because they are non-read-only and no + * explicit allow/deny rule matched. That fallback should still allow users to + * create new allow rules, so callers must only hide "Always allow" when a + * real ask rule matched. + */ + hasMatchingAskRule(ctx: PermissionCheckContext): boolean { + const { toolName, command, filePath, domain, specifier } = ctx; + + if (ctx.toolName === 'run_shell_command' && command !== undefined) { + const subCommands = splitCompoundCommand(command); + if (subCommands.length > 1) { + return subCommands.some((subCmd) => + this.hasMatchingAskRule({ ...ctx, command: subCmd }), + ); + } + } + + const pathCtx: PathMatchContext | undefined = + this.config.getProjectRoot && this.config.getCwd + ? { + projectRoot: this.config.getProjectRoot(), + cwd: this.config.getCwd(), + } + : undefined; + + const matchArgs = [ + toolName, + command, + filePath, + domain, + pathCtx, + specifier, + ] as const; + + const askRules = [...this.sessionRules.ask, ...this.persistentRules.ask]; + + if (askRules.some((rule) => matchesRule(rule, ...matchArgs))) { + return true; + } + + if (ctx.toolName === 'run_shell_command' && ctx.command !== undefined) { + const cwd = pathCtx?.cwd ?? process.cwd(); + const ops = extractShellOperations(ctx.command, cwd); + return ops.some((op) => { + const opMatchArgs = [ + op.virtualTool, + undefined, + op.filePath, + op.domain, + pathCtx, + undefined, + ] as const; + return askRules.some((rule) => matchesRule(rule, ...opMatchArgs)); + }); + } + + return false; + } + // --------------------------------------------------------------------------- // Session rule management // --------------------------------------------------------------------------- diff --git a/packages/core/src/permissions/rule-parser.ts b/packages/core/src/permissions/rule-parser.ts index 32c413081..6ca9e8363 100644 --- a/packages/core/src/permissions/rule-parser.ts +++ b/packages/core/src/permissions/rule-parser.ts @@ -405,6 +405,106 @@ export function buildPermissionRules(ctx: PermissionCheckContext): string[] { } } +/** + * Human-readable display names for permission rule categories. + * Maps display name → verb phrase for use in "Always allow [verb phrase] in this project". + */ +const DISPLAY_NAME_TO_VERB: Readonly> = { + Read: 'read files', + Edit: 'edit files', + Bash: 'run commands', + WebFetch: 'fetch from', + WebSearch: 'search the web', + Agent: 'use agent', + Skill: 'use skill', + SaveMemory: 'save memory', + TodoWrite: 'write todos', + Lsp: 'use LSP', + ExitPlanMode: 'exit plan mode', +}; + +/** + * Strip the glob suffix (e.g. `/**`) and the leading `//` from an absolute + * path specifier so it reads cleanly in a UI label. + * + * `//Users/mochi/.qwen/**` → `/Users/mochi/.qwen/` + * `/src/**` → `src/` + */ +function cleanPathSpecifier(specifier: string): string { + let cleaned = specifier; + // Remove trailing glob patterns like /** or /* + cleaned = cleaned.replace(/\/\*\*$/, '/').replace(/\/\*$/, '/'); + // Convert rule grammar `//absolute` → `/absolute` + if (cleaned.startsWith('//')) { + cleaned = cleaned.substring(1); + } + // Ensure trailing slash for directories + if (!cleaned.endsWith('/')) { + cleaned += '/'; + } + return cleaned; +} + +/** + * Build a human-readable label describing what a set of permission rules allow. + * + * Used in "Always Allow" UI options to give users a clear, natural-language + * description instead of raw rule syntax. + * + * Examples: + * `["Read(//Users/mochi/.qwen/**)"]` → `"read files in /Users/mochi/.qwen/"` + * `["Bash(git *)"]` → `"run 'git *' commands"` + * `["WebFetch(github.com)"]` → `"fetch from github.com"` + * `["Read"]` → `"read files"` + * + * @param rules - Array of rule strings from buildPermissionRules() + * @returns A human-readable description string + */ +export function buildHumanReadableRuleLabel(rules: string[]): string { + if (!rules.length) return ''; + + const parts: string[] = []; + for (const rule of rules) { + // Parse "DisplayName(specifier)" or bare "DisplayName" + const parenIdx = rule.indexOf('('); + if (parenIdx === -1) { + // Bare rule like "Read" or "Bash" + const verb = DISPLAY_NAME_TO_VERB[rule] ?? rule.toLowerCase(); + parts.push(verb); + continue; + } + + const displayName = rule.substring(0, parenIdx); + const specifier = rule.substring(parenIdx + 1, rule.length - 1); // strip parens + const verb = DISPLAY_NAME_TO_VERB[displayName] ?? displayName.toLowerCase(); + + const canonicalName = Object.entries(CANONICAL_TO_RULE_DISPLAY).find( + ([, v]) => v === displayName, + )?.[0]; + const kind = canonicalName ? getSpecifierKind(canonicalName) : 'literal'; + + switch (kind) { + case 'path': { + const cleanPath = cleanPathSpecifier(specifier); + parts.push(`${verb} in ${cleanPath}`); + break; + } + case 'command': + parts.push(`run '${specifier}' commands`); + break; + case 'domain': + parts.push(`${verb} ${specifier}`); + break; + case 'literal': + default: + parts.push(`${verb} "${specifier}"`); + break; + } + } + + return parts.join(', '); +} + // ───────────────────────────────────────────────────────────────────────────── // Shell command matching // ───────────────────────────────────────────────────────────────────────────── diff --git a/packages/core/src/services/chatCompressionService.test.ts b/packages/core/src/services/chatCompressionService.test.ts index 074f46461..f3f490214 100644 --- a/packages/core/src/services/chatCompressionService.test.ts +++ b/packages/core/src/services/chatCompressionService.test.ts @@ -126,6 +126,7 @@ describe('ChatCompressionService', () => { getContentGeneratorConfig: vi.fn().mockReturnValue({}), getHookSystem: mockGetHookSystem, getModel: () => 'test-model', + getApprovalMode: () => 'default', getDebugLogger: () => ({ warn: vi.fn(), }), @@ -290,6 +291,9 @@ describe('ChatCompressionService', () => { expect(mockFireSessionStartEvent).toHaveBeenCalledWith( SessionStartSource.Compact, mockModel, + 'default', + undefined, + undefined, ); }); @@ -337,6 +341,9 @@ describe('ChatCompressionService', () => { expect(mockFireSessionStartEvent).toHaveBeenCalledWith( SessionStartSource.Compact, mockModel, + 'default', + undefined, + undefined, ); }); @@ -650,6 +657,7 @@ describe('ChatCompressionService', () => { expect(mockFirePreCompactEvent).toHaveBeenCalledWith( PreCompactTrigger.Manual, '', + undefined, ); }); @@ -699,6 +707,7 @@ describe('ChatCompressionService', () => { expect(mockFirePreCompactEvent).toHaveBeenCalledWith( PreCompactTrigger.Auto, '', + undefined, ); }); diff --git a/packages/core/src/services/chatCompressionService.ts b/packages/core/src/services/chatCompressionService.ts index 082971671..610445fb4 100644 --- a/packages/core/src/services/chatCompressionService.ts +++ b/packages/core/src/services/chatCompressionService.ts @@ -14,6 +14,7 @@ import { getCompressionPrompt } from '../core/prompts.js'; import { getResponseText } from '../utils/partUtils.js'; import { logChatCompression } from '../telemetry/loggers.js'; import { makeChatCompressionEvent } from '../telemetry/types.js'; +import type { PermissionMode } from '../hooks/types.js'; import { SessionStartSource, PreCompactTrigger } from '../hooks/types.js'; /** @@ -84,6 +85,7 @@ export class ChatCompressionService { model: string, config: Config, hasFailedCompressionAttempt: boolean, + signal?: AbortSignal, ): Promise<{ newHistory: Content[] | null; info: ChatCompressionInfo }> { const curatedHistory = chat.getHistory(true); const threshold = @@ -130,7 +132,7 @@ export class ChatCompressionService { if (hookSystem) { const trigger = force ? PreCompactTrigger.Manual : PreCompactTrigger.Auto; try { - await hookSystem.firePreCompactEvent(trigger, ''); + await hookSystem.firePreCompactEvent(trigger, '', signal); } catch (err) { config.getDebugLogger().warn(`PreCompact hook failed: ${err}`); } @@ -276,9 +278,18 @@ export class ChatCompressionService { // Fire SessionStart event after successful compression try { + const permissionMode = String( + config.getApprovalMode(), + ) as PermissionMode; await config .getHookSystem() - ?.fireSessionStartEvent(SessionStartSource.Compact, model ?? ''); + ?.fireSessionStartEvent( + SessionStartSource.Compact, + model ?? '', + permissionMode, + undefined, + signal, + ); } catch (err) { config.getDebugLogger().warn(`SessionStart hook failed: ${err}`); } diff --git a/packages/core/src/services/fileSystemService.test.ts b/packages/core/src/services/fileSystemService.test.ts index 7811a96ed..04d4293e8 100644 --- a/packages/core/src/services/fileSystemService.test.ts +++ b/packages/core/src/services/fileSystemService.test.ts @@ -10,6 +10,8 @@ import { StandardFileSystemService, needsUtf8Bom, resetUtf8BomCache, + detectLineEnding, + ensureCrlfLineEndings, } from './fileSystemService.js'; const mockPlatform = vi.hoisted(() => vi.fn().mockReturnValue('linux')); @@ -448,4 +450,144 @@ describe('StandardFileSystemService', () => { expect(needsUtf8Bom('/test/script.ps1')).toBe(true); }); }); + + describe('detectLineEnding', () => { + it('should detect CRLF line endings', () => { + expect(detectLineEnding('line1\r\nline2\r\n')).toBe('crlf'); + }); + + it('should detect LF line endings', () => { + expect(detectLineEnding('line1\nline2\n')).toBe('lf'); + }); + + it('should return lf for content with no line endings', () => { + expect(detectLineEnding('single line')).toBe('lf'); + }); + + it('should return lf for empty content', () => { + expect(detectLineEnding('')).toBe('lf'); + }); + + it('should detect CRLF even in mixed content', () => { + expect(detectLineEnding('line1\r\nline2\nline3')).toBe('crlf'); + }); + }); + + describe('ensureCrlfLineEndings', () => { + it('should convert LF to CRLF', () => { + expect(ensureCrlfLineEndings('line1\nline2\n')).toBe( + 'line1\r\nline2\r\n', + ); + }); + + it('should not double-convert existing CRLF', () => { + expect(ensureCrlfLineEndings('line1\r\nline2\r\n')).toBe( + 'line1\r\nline2\r\n', + ); + }); + + it('should handle mixed line endings', () => { + expect(ensureCrlfLineEndings('line1\r\nline2\nline3\r\n')).toBe( + 'line1\r\nline2\r\nline3\r\n', + ); + }); + + it('should handle content with no line endings', () => { + expect(ensureCrlfLineEndings('single line')).toBe('single line'); + }); + }); + + describe('writeTextFile with lineEnding preservation', () => { + it('should convert LF to CRLF when lineEnding is crlf', async () => { + vi.mocked(fs.writeFile).mockResolvedValue(); + + await fileSystem.writeTextFile({ + path: '/test/file.txt', + content: 'line1\nline2\n', + _meta: { lineEnding: 'crlf' }, + }); + + expect(fs.writeFile).toHaveBeenCalledWith( + '/test/file.txt', + 'line1\r\nline2\r\n', + 'utf-8', + ); + }); + + it('should not convert line endings when lineEnding is lf', async () => { + vi.mocked(fs.writeFile).mockResolvedValue(); + + await fileSystem.writeTextFile({ + path: '/test/file.txt', + content: 'line1\nline2\n', + _meta: { lineEnding: 'lf' }, + }); + + expect(fs.writeFile).toHaveBeenCalledWith( + '/test/file.txt', + 'line1\nline2\n', + 'utf-8', + ); + }); + + it('should not convert line endings when lineEnding is not specified', async () => { + vi.mocked(fs.writeFile).mockResolvedValue(); + + await fileSystem.writeTextFile({ + path: '/test/file.txt', + content: 'line1\nline2\n', + }); + + expect(fs.writeFile).toHaveBeenCalledWith( + '/test/file.txt', + 'line1\nline2\n', + 'utf-8', + ); + }); + + it('should preserve CRLF for non-bat files on non-Windows when lineEnding is crlf', async () => { + mockPlatform.mockReturnValue('linux'); + vi.mocked(fs.writeFile).mockResolvedValue(); + + await fileSystem.writeTextFile({ + path: '/test/file.cs', + content: 'using System;\nclass Foo {}\n', + _meta: { lineEnding: 'crlf' }, + }); + + expect(fs.writeFile).toHaveBeenCalledWith( + '/test/file.cs', + 'using System;\r\nclass Foo {}\r\n', + 'utf-8', + ); + }); + }); + + describe('readTextFile with lineEnding detection', () => { + it('should detect CRLF line ending in file content', async () => { + vi.mocked(readFileWithLineAndLimit).mockResolvedValue({ + content: 'line1\r\nline2\r\n', + bom: false, + encoding: 'utf-8', + originalLineCount: 3, + }); + + const result = await fileSystem.readTextFile({ path: '/test/file.txt' }); + + expect(result._meta?.lineEnding).toBe('crlf'); + }); + + it('should detect LF line ending in file content', async () => { + vi.mocked(readFileWithLineAndLimit).mockResolvedValue({ + content: 'line1\nline2\n', + bom: false, + encoding: 'utf-8', + originalLineCount: 3, + }); + + const result = await fileSystem.readTextFile({ path: '/test/file.txt' }); + + expect(result._meta?.lineEnding).toBe('lf'); + }); + }); }); diff --git a/packages/core/src/services/fileSystemService.ts b/packages/core/src/services/fileSystemService.ts index 6d2022c75..e17d9288b 100644 --- a/packages/core/src/services/fileSystemService.ts +++ b/packages/core/src/services/fileSystemService.ts @@ -21,12 +21,15 @@ import type { WriteTextFileResponse, } from '@agentclientprotocol/sdk'; +export type LineEnding = 'crlf' | 'lf'; + export type ReadTextFileResponse = { content: string; _meta?: { bom?: boolean; encoding?: string; originalLineCount?: number; + lineEnding?: LineEnding; }; }; @@ -148,10 +151,20 @@ function needsCrlfLineEndings(filePath: string): boolean { /** * Ensures content uses CRLF line endings. First normalizes any existing - * \r\n to \n to avoid double-conversion, then converts all \n to \r\n. + * CRLF to LF to avoid double-conversion, then converts all LF to CRLF. */ -function ensureCrlfLineEndings(content: string): string { - return content.replace(/\r\n/g, '\n').replace(/\n/g, '\r\n'); +export function ensureCrlfLineEndings(content: string): string { + // First normalize CRLF to LF to avoid double-conversion, then convert all LF to CRLF + return content.split('\r\n').join('\n').split('\n').join('\r\n'); +} + +/** + * Detects whether the content uses CRLF or LF line endings. + * Returns 'crlf' if the content contains at least one CRLF sequence, + * 'lf' otherwise (including for content with no line endings). + */ +export function detectLineEnding(content: string): LineEnding { + return content.includes('\r\n') ? 'crlf' : 'lf'; } /** @@ -194,15 +207,21 @@ export class StandardFileSystemService implements FileSystemService { limit: limit ?? Number.POSITIVE_INFINITY, line: line || 0, }); - return { content, _meta: { bom, encoding, originalLineCount } }; + const lineEnding = detectLineEnding(content); + return { content, _meta: { bom, encoding, originalLineCount, lineEnding } }; } async writeTextFile( params: Omit, ): Promise { const { path: filePath, _meta } = params; - // Convert LF to CRLF for file types that require it (e.g. .bat, .cmd) - const content = needsCrlfLineEndings(filePath) + const lineEnding = _meta?.['lineEnding'] as string | undefined; + // Convert LF to CRLF when: + // 1. The file type requires it (e.g. .bat, .cmd on Windows), OR + // 2. The original file used CRLF line endings (preserve original style) + const shouldUseCrlf = + needsCrlfLineEndings(filePath) || lineEnding === 'crlf'; + const content = shouldUseCrlf ? ensureCrlfLineEndings(params.content) : params.content; const bom = _meta?.['bom'] ?? (false as boolean); diff --git a/packages/core/src/services/shellExecutionService.test.ts b/packages/core/src/services/shellExecutionService.test.ts index 5dae23a2a..1b30b2f37 100644 --- a/packages/core/src/services/shellExecutionService.test.ts +++ b/packages/core/src/services/shellExecutionService.test.ts @@ -413,6 +413,67 @@ describe('ShellExecutionService', () => { expect(mockHeadlessTerminal.resize).toHaveBeenCalledWith(100, 40); }); + it('should ignore expected PTY read EIO errors on process exit', async () => { + const { result } = await simulateExecution('ls -l', (pty) => { + const eioError = Object.assign(new Error('read EIO'), { code: 'EIO' }); + pty.emit('error', eioError); + pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null }); + }); + + expect(result.exitCode).toBe(0); + }); + + it('should throw unexpected PTY errors from error event', async () => { + const abortController = new AbortController(); + const handle = await ShellExecutionService.execute( + 'ls -l', + '/test/dir', + onOutputEventMock, + abortController.signal, + true, + shellExecutionConfig, + ); + await new Promise((resolve) => process.nextTick(resolve)); + + const unexpectedError = Object.assign(new Error('unexpected pty error'), { + code: 'EPIPE', + }); + expect(() => mockPtyProcess.emit('error', unexpectedError)).toThrow( + 'unexpected pty error', + ); + + mockPtyProcess.onExit.mock.calls[0][0]({ exitCode: 0, signal: null }); + await handle.result; + }); + + it('should ignore ioctl EBADF message-only resize race errors', async () => { + mockPtyProcess.resize.mockImplementationOnce(() => { + throw new Error('ioctl(2) failed, EBADF'); + }); + + await simulateExecution('ls -l', (pty) => { + pty.onData.mock.calls[0][0]('file1.txt\n'); + expect(() => + ShellExecutionService.resizePty(pty.pid!, 100, 40), + ).not.toThrow(); + pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null }); + }); + }); + + it('should ignore exited-pty message-only resize race errors', async () => { + mockPtyProcess.resize.mockImplementationOnce(() => { + throw new Error('Cannot resize a pty that has already exited'); + }); + + await simulateExecution('ls -l', (pty) => { + pty.onData.mock.calls[0][0]('file1.txt\n'); + expect(() => + ShellExecutionService.resizePty(pty.pid!, 100, 40), + ).not.toThrow(); + pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null }); + }); + }); + it('should scroll the headless terminal', async () => { await simulateExecution('ls -l', (pty) => { pty.onData.mock.calls[0][0]('file1.txt\n'); diff --git a/packages/core/src/services/shellExecutionService.ts b/packages/core/src/services/shellExecutionService.ts index e943275bd..88b42d4bb 100644 --- a/packages/core/src/services/shellExecutionService.ts +++ b/packages/core/src/services/shellExecutionService.ts @@ -185,6 +185,40 @@ interface ActivePty { headlessTerminal: pkg.Terminal; } +const getErrnoCode = (error: unknown): string | undefined => { + if (!error || typeof error !== 'object' || !('code' in error)) { + return undefined; + } + const code = (error as { code?: unknown }).code; + return typeof code === 'string' ? code : undefined; +}; + +const getErrorMessage = (error: unknown): string => + error instanceof Error ? error.message : String(error); + +const isExpectedPtyReadExitError = (error: unknown): boolean => { + const code = getErrnoCode(error); + if (code === 'EIO') { + return true; + } + + const message = getErrorMessage(error); + return message.includes('read EIO'); +}; + +const isExpectedPtyExitRaceError = (error: unknown): boolean => { + const code = getErrnoCode(error); + if (code === 'ESRCH' || code === 'EBADF') { + return true; + } + + const message = getErrorMessage(error); + return ( + message.includes('ioctl(2) failed, EBADF') || + message.includes('Cannot resize a pty that has already exited') + ); +}; + const getFullBufferText = (terminal: pkg.Terminal): string => { const buffer = terminal.buffer.active; const lines: string[] = []; @@ -768,6 +802,20 @@ export class ShellExecutionService { handleOutput(bufferData); }); + // Handle PTY errors - EIO is expected when the PTY process exits + // due to race conditions between the exit event and read operations. + // This is a normal behavior on macOS/Linux and should not crash the app. + // See: https://github.com/microsoft/node-pty/issues/178 + ptyProcess.on('error', (err: NodeJS.ErrnoException) => { + if (isExpectedPtyReadExitError(err)) { + // EIO is expected when the PTY process exits - ignore it + return; + } + + // Surface unexpected PTY errors to preserve existing crash behavior. + throw err; + }); + ptyProcess.onExit( ({ exitCode, signal }: { exitCode: number; signal?: number }) => { exited = true; @@ -938,7 +986,9 @@ export class ShellExecutionService { } catch (e) { // Ignore errors if the pty has already exited, which can happen // due to a race condition between the exit event and this call. - if (e instanceof Error && 'code' in e && e.code === 'ESRCH') { + // - ESRCH: No such process (process no longer exists) + // - EBADF: Bad file descriptor (PTY fd closed, e.g., "ioctl(2) failed, EBADF") + if (isExpectedPtyExitRaceError(e)) { // ignore } else { throw e; @@ -968,7 +1018,9 @@ export class ShellExecutionService { } catch (e) { // Ignore errors if the pty has already exited, which can happen // due to a race condition between the exit event and this call. - if (e instanceof Error && 'code' in e && e.code === 'ESRCH') { + // - ESRCH: No such process (process no longer exists) + // - EBADF: Bad file descriptor (PTY fd closed, e.g., "ioctl(2) failed, EBADF") + if (isExpectedPtyExitRaceError(e)) { // ignore } else { throw e; diff --git a/packages/core/src/skills/bundled/qc-helper/SKILL.md b/packages/core/src/skills/bundled/qc-helper/SKILL.md new file mode 100644 index 000000000..14fbaa152 --- /dev/null +++ b/packages/core/src/skills/bundled/qc-helper/SKILL.md @@ -0,0 +1,151 @@ +--- +name: qc-helper +description: Answer any question about Qwen Code usage, features, configuration, and troubleshooting by referencing the official user documentation. Also helps users view or modify their settings.json. Invoke with `/qc-helper` followed by a question, e.g. `/qc-helper how do I configure MCP servers?` or `/qc-helper change approval mode to yolo`. +allowedTools: + - read_file + - edit_file + - grep_search + - glob + - read_many_files +--- + +# Qwen Code Helper + +You are a helpful assistant for **Qwen Code** — an AI coding agent for the terminal. Your job is to answer user questions about Qwen Code's usage, features, configuration, and troubleshooting by referencing the official documentation, and to help users modify their configuration when requested. + +## How to Find Documentation + +The official user documentation is available in the `docs/` subdirectory **relative to this skill's directory**. Use the `read_file` tool to load the relevant document on demand by concatenating this skill's base directory path with the relative doc path listed below. + +> **Example**: If the user asks about MCP servers, read `docs/features/mcp.md` (relative to this skill's directory). + +--- + +## Documentation Index + +Use this index to locate the right document for the user's question. Load only the docs that are relevant — do not read everything at once. + +### Getting Started + +| Topic | Doc Path | +| ----------------- | ------------------------- | +| Product overview | `docs/overview.md` | +| Quick start guide | `docs/quickstart.md` | +| Common workflows | `docs/common-workflow.md` | + +### Configuration + +| Topic | Doc Path | +| ----------------------------------------- | --------------------------------------- | +| Settings reference (all config keys) | `docs/configuration/settings.md` | +| Authentication setup | `docs/configuration/auth.md` | +| Model providers (OpenAI-compatible, etc.) | `docs/configuration/model-providers.md` | +| .qwenignore file | `docs/configuration/qwen-ignore.md` | +| Themes | `docs/configuration/themes.md` | +| Memory | `docs/configuration/memory.md` | +| Trusted folders | `docs/configuration/trusted-folders.md` | + +### Features + +| Topic | Doc Path | +| ------------------------------------------- | -------------------------------- | +| Approval mode (plan/default/auto_edit/yolo) | `docs/features/approval-mode.md` | +| MCP (Model Context Protocol) | `docs/features/mcp.md` | +| Skills system | `docs/features/skills.md` | +| Sub-agents | `docs/features/sub-agents.md` | +| Sandbox / security | `docs/features/sandbox.md` | +| Slash commands | `docs/features/commands.md` | +| Headless / non-interactive mode | `docs/features/headless.md` | +| LSP integration | `docs/features/lsp.md` | +| Checkpointing | `docs/features/checkpointing.md` | +| Token caching | `docs/features/token-caching.md` | +| Language / i18n | `docs/features/language.md` | +| Arena mode | `docs/features/arena.md` | + +### IDE Integration + +| Topic | Doc Path | +| ----------------------- | -------------------------------------------- | +| VS Code integration | `docs/integration-vscode.md` | +| Zed IDE integration | `docs/integration-zed.md` | +| JetBrains integration | `docs/integration-jetbrains.md` | +| GitHub Actions | `docs/integration-github-action.md` | +| IDE companion spec | `docs/ide-integration/ide-companion-spec.md` | +| IDE integration details | `docs/ide-integration/ide-integration.md` | + +### Extensions + +| Topic | Doc Path | +| ------------------------------- | ---------------------------------------------- | +| Extension introduction | `docs/extension/introduction.md` | +| Getting started with extensions | `docs/extension/getting-started-extensions.md` | +| Releasing extensions | `docs/extension/extension-releasing.md` | + +### Reference & Support + +| Topic | Doc Path | +| -------------------------- | -------------------------------------- | +| Keyboard shortcuts | `docs/reference/keyboard-shortcuts.md` | +| Troubleshooting | `docs/support/troubleshooting.md` | +| Uninstall guide | `docs/support/Uninstall.md` | +| Terms of service & privacy | `docs/support/tos-privacy.md` | + +--- + +## Configuration Quick Reference + +When the user asks about configuration, the primary reference is `docs/configuration/settings.md`. Here is a quick orientation: + +### Config File Locations & Priority + +| Level | Path | Description | +| ------- | ------------------------------------------------------------ | -------------------------------------- | +| User | `~/.qwen/settings.json` | Personal global config | +| Project | `/.qwen/settings.json` | Project-specific, overrides user level | +| System | macOS: `/Library/Application Support/QwenCode/settings.json` | Admin-level config | + +**Priority** (highest to lowest): CLI args > env vars > system settings > project settings > user settings > defaults + +**Format**: JSON with Comments (supports `//` and `/* */`), with environment variable interpolation (`$VAR` or `${VAR}`) + +### Common Config Categories + +| Category | Key Config Keys | Reference | +| ------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| Permissions | `permissions.allow/ask/deny` | `docs/configuration/settings.md`, `docs/features/approval-mode.md` | +| MCP Servers | `mcpServers.*`, `mcp.*` | `docs/configuration/settings.md`, `docs/features/mcp.md` | +| Tool Approval | `tools.approvalMode` | `docs/configuration/settings.md`, `docs/features/approval-mode.md` | +| Model | `model.name`, `modelProviders` | `docs/configuration/settings.md`, `docs/configuration/model-providers.md` | +| General/UI | `general.*`, `ui.*`, `ide.*`, `output.*` | `docs/configuration/settings.md` | +| Context | `context.*` | `docs/configuration/settings.md` | +| Advanced | `hooks`, `env`, `webSearch`, `security`, `privacy`, `telemetry`, `advanced.*` | `docs/configuration/settings.md` | + +--- + +## Workflow + +### Answering Questions + +1. **Identify the topic** from the user's question using the Documentation Index above +2. **Use `read_file`** to load the relevant doc(s) — only load what you need +3. **Provide a clear, concise answer** grounded in the documentation content +4. If the docs don't cover the question, say so honestly and suggest where to look + +### Helping with Configuration Changes + +When the user wants to modify their configuration: + +1. **Read the relevant doc** to understand the config key, its type, allowed values, and defaults +2. **Ask which config level** to modify if not specified: user (`~/.qwen/settings.json`) or project (`.qwen/settings.json`) +3. **Use `read_file`** to check the current content of the target settings file +4. **Use `edit_file`** to apply the change with correct JSON syntax +5. **After every configuration change**, you MUST remind the user: + +> **Note: Most configuration changes require restarting Qwen Code (`/exit` then re-launch) to take effect.** Only a few settings (like `permissions`) are picked up dynamically. + +### Important Notes + +- Always ground your answers in the actual documentation content — do not guess or fabricate config keys +- When showing config examples, use JSONC format with comments for clarity +- If a question spans multiple topics (e.g., "How do I set up MCP with sandbox?"), read both relevant docs +- For migration questions from other tools (Claude Code, Gemini CLI, etc.), check `docs/configuration/settings.md` for equivalent config keys diff --git a/packages/core/src/telemetry/index.ts b/packages/core/src/telemetry/index.ts index 596db3fa1..bab3e15a8 100644 --- a/packages/core/src/telemetry/index.ts +++ b/packages/core/src/telemetry/index.ts @@ -125,3 +125,4 @@ export { FileOperation, } from './metrics.js'; export { QwenLogger } from './qwen-logger/qwen-logger.js'; +export { sanitizeHookName } from './sanitize.js'; diff --git a/packages/core/src/telemetry/loggers.test.ts b/packages/core/src/telemetry/loggers.test.ts index 34d142c4f..288e02f03 100644 --- a/packages/core/src/telemetry/loggers.test.ts +++ b/packages/core/src/telemetry/loggers.test.ts @@ -54,6 +54,7 @@ import { logExtensionDisable, logExtensionInstallEvent, logExtensionUninstall, + logHookCall, } from './loggers.js'; import * as metrics from './metrics.js'; import { QwenLogger } from './qwen-logger/qwen-logger.js'; @@ -75,6 +76,7 @@ import { ExtensionDisableEvent, ExtensionInstallEvent, ExtensionUninstallEvent, + HookCallEvent, } from './types.js'; import { FileOperation } from './metrics.js'; import type { @@ -1281,4 +1283,230 @@ describe('loggers', () => { }); }); }); + + describe('logHookCall', () => { + const mockConfig = { + getSessionId: () => 'test-session-id', + getTargetDir: () => 'target-dir', + getUsageStatisticsEnabled: () => true, + getTelemetryEnabled: () => true, + getTelemetryLogPromptsEnabled: () => true, + } as unknown as Config; + + const mockQwenLogger = { + logHookCallEvent: vi.fn(), + }; + + beforeEach(() => { + vi.spyOn(QwenLogger, 'getInstance').mockReturnValue( + mockQwenLogger as unknown as QwenLogger, + ); + mockQwenLogger.logHookCallEvent.mockClear(); + }); + + it('should log a successful hook call to QwenLogger', () => { + const event = new HookCallEvent( + 'UserPromptSubmit', + 'command', + 'check-secrets.sh', + { prompt: 'test prompt' }, + 150, + true, + { output: 'success' }, + 0, + 'stdout message', + 'stderr message', + undefined, + ); + + logHookCall(mockConfig, event); + + // Should call QwenLogger + expect(mockQwenLogger.logHookCallEvent).toHaveBeenCalledWith(event); + }); + + it('should log a failed hook call with error', () => { + const event = new HookCallEvent( + 'Stop', + 'command', + 'cleanup.sh', + { last_assistant_message: 'final message' }, + 200, + false, + undefined, + 1, + 'stdout message', + 'stderr message', + 'Error occurred', + ); + + logHookCall(mockConfig, event); + + // Should call QwenLogger + expect(mockQwenLogger.logHookCallEvent).toHaveBeenCalledWith(event); + }); + + it('should handle when QwenLogger is not available', () => { + vi.spyOn(QwenLogger, 'getInstance').mockReturnValue(undefined); + + const event = new HookCallEvent( + 'UserPromptSubmit', + 'command', + 'test-hook.sh', + { prompt: 'test' }, + 100, + true, + ); + + // Should not throw when QwenLogger is not available + expect(() => logHookCall(mockConfig, event)).not.toThrow(); + }); + + it('should log hook call with all optional fields', () => { + const event = new HookCallEvent( + 'PreToolUse', + 'command', + 'validator.sh', + { tool_name: 'read_file', path: '/test/file.txt' }, + 250, + true, + { decision: 'allow', reason: 'validated' }, + 0, + 'validation passed', + '', + undefined, + ); + + logHookCall(mockConfig, event); + + expect(mockQwenLogger.logHookCallEvent).toHaveBeenCalledWith(event); + }); + + it('should log hook call with minimal fields', () => { + const event = new HookCallEvent( + 'SessionStart', + 'command', + 'init.sh', + {}, + 10, + true, + ); + + logHookCall(mockConfig, event); + + expect(mockQwenLogger.logHookCallEvent).toHaveBeenCalledWith(event); + }); + + it('should log hook call with exit code', () => { + const event = new HookCallEvent( + 'PostToolUseFailure', + 'command', + 'error-handler.sh', + { tool_name: 'shell' }, + 50, + false, + undefined, + 1, + '', + 'error output', + 'Command failed with exit code 1', + ); + + logHookCall(mockConfig, event); + + expect(mockQwenLogger.logHookCallEvent).toHaveBeenCalledWith(event); + }); + + it('should log hook call with zero exit code on success', () => { + const event = new HookCallEvent( + 'PostToolUse', + 'command', + 'success-handler.sh', + { tool_name: 'write_file' }, + 100, + true, + { result: 'ok' }, + 0, + 'done', + '', + undefined, + ); + + logHookCall(mockConfig, event); + + expect(mockQwenLogger.logHookCallEvent).toHaveBeenCalledWith(event); + }); + + it('should log hook call with non-zero exit code on failure', () => { + const event = new HookCallEvent( + 'PostToolUseFailure', + 'command', + 'failure-handler.sh', + { tool_name: 'shell' }, + 75, + false, + undefined, + 127, + '', + 'command not found', + 'Hook command not found', + ); + + logHookCall(mockConfig, event); + + expect(mockQwenLogger.logHookCallEvent).toHaveBeenCalledWith(event); + }); + + it('should log all hook event types', () => { + const eventTypes = [ + 'PreToolUse', + 'PostToolUse', + 'PostToolUseFailure', + 'Notification', + 'UserPromptSubmit', + 'SessionStart', + 'SessionEnd', + 'Stop', + 'SubagentStart', + 'SubagentStop', + 'PreCompact', + 'PermissionRequest', + ]; + + for (const eventType of eventTypes) { + mockQwenLogger.logHookCallEvent.mockClear(); + + const event = new HookCallEvent( + eventType, + 'command', + 'test-hook.sh', + {}, + 100, + true, + ); + + logHookCall(mockConfig, event); + + expect(mockQwenLogger.logHookCallEvent).toHaveBeenCalledWith(event); + } + }); + + it('should pass the exact event object to QwenLogger', () => { + const event = new HookCallEvent( + 'PreToolUse', + 'command', + 'test-hook.sh', + { tool_name: 'read_file' }, + 100, + true, + ); + + logHookCall(mockConfig, event); + + // Verify the exact event object is passed + expect(mockQwenLogger.logHookCallEvent).toHaveBeenCalledTimes(1); + const passedEvent = mockQwenLogger.logHookCallEvent.mock.calls[0][0]; + expect(passedEvent).toBe(event); + }); + }); }); diff --git a/packages/core/src/telemetry/loggers.ts b/packages/core/src/telemetry/loggers.ts index 0a7842f38..da2499008 100644 --- a/packages/core/src/telemetry/loggers.ts +++ b/packages/core/src/telemetry/loggers.ts @@ -102,6 +102,7 @@ import type { ArenaAgentCompletedEvent, ArenaSessionEndedEvent, } from './types.js'; +import type { HookCallEvent } from './types.js'; import type { UiEvent } from './uiTelemetry.js'; import { uiTelemetryService } from './uiTelemetry.js'; @@ -114,6 +115,8 @@ function getCommonAttributes(config: Config): LogAttributes { }; } +export { getCommonAttributes }; + export function logStartSession( config: Config, event: StartSessionEvent, @@ -787,6 +790,11 @@ export function logModelSlashCommand( recordModelSlashCommand(config, event); } +export function logHookCall(config: Config, event: HookCallEvent): void { + // Log to QwenLogger for RUM telemetry only + QwenLogger.getInstance(config)?.logHookCallEvent(event); +} + export function logExtensionInstallEvent( config: Config, event: ExtensionInstallEvent, diff --git a/packages/core/src/telemetry/qwen-logger/qwen-logger.test.ts b/packages/core/src/telemetry/qwen-logger/qwen-logger.test.ts index 352d90e12..61ca8014a 100644 --- a/packages/core/src/telemetry/qwen-logger/qwen-logger.test.ts +++ b/packages/core/src/telemetry/qwen-logger/qwen-logger.test.ts @@ -23,6 +23,7 @@ import { IdeConnectionEvent, KittySequenceOverflowEvent, IdeConnectionType, + HookCallEvent, } from '../types.js'; import type { RumEvent, RumPayload } from './event-types.js'; @@ -517,4 +518,312 @@ describe('QwenLogger', () => { expect(TEST_ONLY.FLUSH_INTERVAL_MS).toBe(60000); }); }); + + describe('logHookCallEvent', () => { + it('should log a successful hook call event', () => { + const logger = QwenLogger.getInstance(mockConfig)!; + const enqueueSpy = vi.spyOn(logger, 'enqueueLogEvent'); + + const event = new HookCallEvent( + 'PreToolUse', + 'command', + 'check-secrets.sh', + { tool_name: 'read_file' }, + 150, + true, + { result: 'valid' }, + 0, + 'stdout', + 'stderr', + undefined, + ); + + logger.logHookCallEvent(event); + + expect(enqueueSpy).toHaveBeenCalledWith( + expect.objectContaining({ + event_type: 'action', + type: 'hook', + name: 'hook_call#PreToolUse', + properties: expect.objectContaining({ + hook_event_name: 'PreToolUse', + hook_type: 'command', + hook_name: 'check-secrets.sh', + duration_ms: 150, + success: 1, + exit_code: 0, + }), + }), + ); + }); + + it('should log a failed hook call event with error when telemetry log prompts enabled', () => { + const configWithLogPrompts = makeFakeConfig({ + getTelemetryLogPromptsEnabled: () => true, + }); + const logger = QwenLogger.getInstance(configWithLogPrompts)!; + const enqueueSpy = vi.spyOn(logger, 'enqueueLogEvent'); + + const event = new HookCallEvent( + 'PostToolUse', + 'command', + 'cleanup.sh', + { tool_name: 'shell' }, + 200, + false, + undefined, + 1, + '', + 'error output', + 'Command failed', + ); + + logger.logHookCallEvent(event); + + expect(enqueueSpy).toHaveBeenCalledWith( + expect.objectContaining({ + event_type: 'action', + type: 'hook', + name: 'hook_call#PostToolUse', + properties: expect.objectContaining({ + hook_event_name: 'PostToolUse', + hook_type: 'command', + hook_name: 'cleanup.sh', + duration_ms: 200, + success: 0, + exit_code: 1, + error: 'Command failed', + }), + }), + ); + }); + + it('should not include error when telemetry log prompts disabled', () => { + const configWithoutLogPrompts = makeFakeConfig({ + getTelemetryLogPromptsEnabled: () => false, + }); + // Clear singleton to create new instance with different config + (QwenLogger as unknown as { instance: undefined }).instance = undefined; + const logger = QwenLogger.getInstance(configWithoutLogPrompts)!; + const enqueueSpy = vi.spyOn(logger, 'enqueueLogEvent'); + + const event = new HookCallEvent( + 'PostToolUse', + 'command', + 'cleanup.sh', + { tool_name: 'shell' }, + 200, + false, + undefined, + 1, + '', + 'error output', + 'Command failed with sensitive data', + ); + + logger.logHookCallEvent(event); + + expect(enqueueSpy).toHaveBeenCalledWith( + expect.objectContaining({ + properties: expect.objectContaining({ + hook_event_name: 'PostToolUse', + hook_type: 'command', + hook_name: 'cleanup.sh', + duration_ms: 200, + success: 0, + exit_code: 1, + }), + }), + ); + + // Error should NOT be in properties + const callArgs = enqueueSpy.mock.calls[0][0]; + expect(callArgs.properties).not.toHaveProperty('error'); + }); + + it('should sanitize hook name to remove sensitive information', () => { + const logger = QwenLogger.getInstance(mockConfig)!; + const enqueueSpy = vi.spyOn(logger, 'enqueueLogEvent'); + + // Hook name with full path and sensitive arguments + const event = new HookCallEvent( + 'PreToolUse', + 'command', + '/home/user/.qwen/hooks/check-secrets.sh --api-key=secret123', + { tool_name: 'read_file' }, + 100, + true, + ); + + logger.logHookCallEvent(event); + + expect(enqueueSpy).toHaveBeenCalledWith( + expect.objectContaining({ + properties: expect.objectContaining({ + // Should be sanitized to just the basename without arguments + hook_name: 'check-secrets.sh', + }), + }), + ); + }); + + it('should sanitize hook name with Windows path', () => { + const logger = QwenLogger.getInstance(mockConfig)!; + const enqueueSpy = vi.spyOn(logger, 'enqueueLogEvent'); + + const event = new HookCallEvent( + 'Stop', + 'command', + 'C:\\Users\\user\\hooks\\cleanup.bat --token=xyz', + {}, + 50, + true, + ); + + logger.logHookCallEvent(event); + + expect(enqueueSpy).toHaveBeenCalledWith( + expect.objectContaining({ + properties: expect.objectContaining({ + hook_name: 'cleanup.bat', + }), + }), + ); + }); + + it('should handle empty hook name', () => { + const logger = QwenLogger.getInstance(mockConfig)!; + const enqueueSpy = vi.spyOn(logger, 'enqueueLogEvent'); + + const event = new HookCallEvent( + 'SessionStart', + 'command', + '', + {}, + 10, + true, + ); + + logger.logHookCallEvent(event); + + expect(enqueueSpy).toHaveBeenCalledWith( + expect.objectContaining({ + properties: expect.objectContaining({ + hook_name: 'unknown-command', + }), + }), + ); + }); + + it('should handle hook name with only whitespace', () => { + const logger = QwenLogger.getInstance(mockConfig)!; + const enqueueSpy = vi.spyOn(logger, 'enqueueLogEvent'); + + const event = new HookCallEvent( + 'SessionEnd', + 'command', + ' ', + {}, + 10, + true, + ); + + logger.logHookCallEvent(event); + + expect(enqueueSpy).toHaveBeenCalledWith( + expect.objectContaining({ + properties: expect.objectContaining({ + hook_name: 'unknown-command', + }), + }), + ); + }); + + it('should handle hook name that is just a command without path', () => { + const logger = QwenLogger.getInstance(mockConfig)!; + const enqueueSpy = vi.spyOn(logger, 'enqueueLogEvent'); + + const event = new HookCallEvent( + 'Notification', + 'command', + 'python --arg=value', + {}, + 100, + true, + ); + + logger.logHookCallEvent(event); + + expect(enqueueSpy).toHaveBeenCalledWith( + expect.objectContaining({ + properties: expect.objectContaining({ + // Should be sanitized to just the command name + hook_name: 'python', + }), + }), + ); + }); + + it('should call flushIfNeeded after logging', () => { + const logger = QwenLogger.getInstance(mockConfig)!; + const flushSpy = vi.spyOn(logger, 'flushIfNeeded'); + + const event = new HookCallEvent( + 'PreToolUse', + 'command', + 'test-hook.sh', + {}, + 100, + true, + ); + + logger.logHookCallEvent(event); + + expect(flushSpy).toHaveBeenCalled(); + }); + + it('should handle all hook event types', () => { + const logger = QwenLogger.getInstance(mockConfig)!; + const enqueueSpy = vi.spyOn(logger, 'enqueueLogEvent'); + + const eventTypes = [ + 'PreToolUse', + 'PostToolUse', + 'PostToolUseFailure', + 'Notification', + 'UserPromptSubmit', + 'SessionStart', + 'SessionEnd', + 'Stop', + 'SubagentStart', + 'SubagentStop', + 'PreCompact', + 'PermissionRequest', + ]; + + for (const eventType of eventTypes) { + enqueueSpy.mockClear(); + + const event = new HookCallEvent( + eventType, + 'command', + 'test-hook.sh', + {}, + 100, + true, + ); + + logger.logHookCallEvent(event); + + expect(enqueueSpy).toHaveBeenCalledWith( + expect.objectContaining({ + name: `hook_call#${eventType}`, + properties: expect.objectContaining({ + hook_event_name: eventType, + }), + }), + ); + } + }); + }); }); diff --git a/packages/core/src/telemetry/qwen-logger/qwen-logger.ts b/packages/core/src/telemetry/qwen-logger/qwen-logger.ts index b0bb22bb0..f22582f05 100644 --- a/packages/core/src/telemetry/qwen-logger/qwen-logger.ts +++ b/packages/core/src/telemetry/qwen-logger/qwen-logger.ts @@ -49,6 +49,7 @@ import type { ArenaSessionStartedEvent, ArenaAgentCompletedEvent, ArenaSessionEndedEvent, + HookCallEvent, } from '../types.js'; import type { RumEvent, @@ -65,6 +66,7 @@ import { type DebugLogger, } from '../../utils/debugLogger.js'; import { safeJsonStringify } from '../../utils/safeJsonStringify.js'; +import { sanitizeHookName } from '../sanitize.js'; import { InstallationManager } from '../../utils/installationManager.js'; import { FixedDeque } from 'mnemonist'; import { AuthType } from '../../core/contentGenerator.js'; @@ -995,6 +997,37 @@ export class QwenLogger { this.flushIfNeeded(); } + /** + * Log a hook call event + * Records hook execution telemetry for observability + */ + logHookCallEvent(event: HookCallEvent): void { + // Sanitize hook name to remove potentially sensitive information + const sanitizedHookName = sanitizeHookName(event.hook_name); + + const properties: Record = { + hook_event_name: event.hook_event_name, + hook_type: event.hook_type, + hook_name: sanitizedHookName, + duration_ms: event.duration_ms, + success: event.success ? 1 : 0, + exit_code: event.exit_code, + }; + + if (event.error && this.config?.getTelemetryLogPromptsEnabled()) { + properties['error'] = event.error; + } + + const rumEvent = this.createActionEvent( + 'hook', + `hook_call#${event.hook_event_name}`, + { properties }, + ); + + this.enqueueLogEvent(rumEvent); + this.flushIfNeeded(); + } + getProxyAgent() { const proxyUrl = this.config?.getProxy(); if (!proxyUrl) return undefined; diff --git a/packages/core/src/telemetry/sanitize.test.ts b/packages/core/src/telemetry/sanitize.test.ts new file mode 100644 index 000000000..da90fef46 --- /dev/null +++ b/packages/core/src/telemetry/sanitize.test.ts @@ -0,0 +1,75 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, expect, it } from 'vitest'; +import { sanitizeHookName } from './sanitize.js'; + +describe('sanitizeHookName', () => { + it('should return "unknown-command" for empty string', () => { + expect(sanitizeHookName('')).toBe('unknown-command'); + }); + + it('should return "unknown-command" for whitespace-only string', () => { + expect(sanitizeHookName(' ')).toBe('unknown-command'); + expect(sanitizeHookName('\t\n\r')).toBe('unknown-command'); + }); + + it('should return "unknown-command" for null/undefined values', () => { + // Testing the function behavior with falsy inputs + expect(sanitizeHookName('')).toBe('unknown-command'); + }); + + it('should extract command name from full path on Unix systems', () => { + expect(sanitizeHookName('/usr/bin/git')).toBe('git'); + expect(sanitizeHookName('/path/to/.gemini/hooks/check-secrets.sh')).toBe( + 'check-secrets.sh', + ); + expect(sanitizeHookName('/home/user/script.py --arg=value')).toBe( + 'script.py', + ); + }); + + it('should extract command name from full path on Windows systems', () => { + expect(sanitizeHookName('C:\\Windows\\System32\\cmd.exe')).toBe('cmd.exe'); + expect(sanitizeHookName('C:\\Users\\User\\Documents\\test.bat /c')).toBe( + 'test.bat', + ); + }); + + it('should return the command name without arguments for simple commands', () => { + expect(sanitizeHookName('git status')).toBe('git'); + expect(sanitizeHookName('node index.js')).toBe('node'); + expect(sanitizeHookName('python script.py --api-key=abc123')).toBe( + 'python', + ); + }); + + it('should handle relative paths correctly', () => { + expect(sanitizeHookName('./my-script.sh')).toBe('my-script.sh'); + expect(sanitizeHookName('../tools/tool.exe')).toBe('tool.exe'); + }); + + it('should handle complex command lines', () => { + expect( + sanitizeHookName( + '/path/to/.gemini/hooks/check-secrets.sh --api-key=abc123', + ), + ).toBe('check-secrets.sh'); + expect( + sanitizeHookName('python /home/user/script.py --token=xyz --verbose'), + ).toBe('python'); + }); + + it('should handle edge cases', () => { + expect(sanitizeHookName('simple-command')).toBe('simple-command'); + expect(sanitizeHookName('one-word')).toBe('one-word'); + }); + + it('should return "unknown-command" for malformed paths', () => { + expect(sanitizeHookName('/')).toBe('unknown-command'); + expect(sanitizeHookName('\\')).toBe('unknown-command'); + }); +}); diff --git a/packages/core/src/telemetry/sanitize.ts b/packages/core/src/telemetry/sanitize.ts new file mode 100644 index 000000000..44376d104 --- /dev/null +++ b/packages/core/src/telemetry/sanitize.ts @@ -0,0 +1,52 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * Sanitize hook name to remove potentially sensitive information. + * Extracts the base command name without arguments or full paths. + * + * This function protects PII by removing: + * - Full file paths that may contain usernames + * - Command arguments that may contain credentials, API keys, tokens + * - Environment variables with sensitive values + * + * Examples: + * - "/path/to/.gemini/hooks/check-secrets.sh --api-key=abc123" -> "check-secrets.sh" + * - "python /home/user/script.py --token=xyz" -> "python" + * - "node index.js" -> "node" + * - "C:\\Windows\\System32\\cmd.exe /c secret.bat" -> "cmd.exe" + * - "" or " " -> "unknown-command" + * + * @param hookName Full command string. + * @returns Sanitized command name. + */ +export function sanitizeHookName(hookName: string): string { + // Handle empty or whitespace-only strings + if (!hookName || !hookName.trim()) { + return 'unknown-command'; + } + + // Split by spaces to get command parts + const parts = hookName.trim().split(/\s+/); + if (parts.length === 0) { + return 'unknown-command'; + } + + // Get the first part (the command) + const command = parts[0]; + if (!command) { + return 'unknown-command'; + } + + // If it's a path, extract just the basename + if (command.includes('/') || command.includes('\\')) { + const pathParts = command.split(/[/\\]/); + const basename = pathParts[pathParts.length - 1]; + return basename || 'unknown-command'; + } + + return command; +} diff --git a/packages/core/src/telemetry/types.ts b/packages/core/src/telemetry/types.ts index e67879886..a44f20ef9 100644 --- a/packages/core/src/telemetry/types.ts +++ b/packages/core/src/telemetry/types.ts @@ -802,6 +802,53 @@ export class AuthEvent implements BaseTelemetryEvent { } } +/** + * Hook call telemetry event + */ +export class HookCallEvent implements BaseTelemetryEvent { + 'event.name': string; + 'event.timestamp': string; + hook_event_name: string; + hook_type: 'command'; + hook_name: string; + hook_input: Record; + hook_output?: Record; + exit_code?: number; + stdout?: string; + stderr?: string; + duration_ms: number; + success: boolean; + error?: string; + + constructor( + hookEventName: string, + hookType: 'command', + hookName: string, + hookInput: Record, + durationMs: number, + success: boolean, + hookOutput?: Record, + exitCode?: number, + stdout?: string, + stderr?: string, + error?: string, + ) { + this['event.name'] = 'hook_call'; + this['event.timestamp'] = new Date().toISOString(); + this.hook_event_name = hookEventName; + this.hook_type = hookType; + this.hook_name = hookName; + this.hook_input = hookInput; + this.hook_output = hookOutput; + this.exit_code = exitCode; + this.stdout = stdout; + this.stderr = stderr; + this.duration_ms = durationMs; + this.success = success; + this.error = error; + } +} + export class SkillLaunchEvent implements BaseTelemetryEvent { 'event.name': 'skill_launch'; 'event.timestamp': string; @@ -877,6 +924,7 @@ export type TelemetryEvent = | ToolOutputTruncatedEvent | ModelSlashCommandEvent | AuthEvent + | HookCallEvent | SkillLaunchEvent | UserFeedbackEvent | ArenaSessionStartedEvent diff --git a/packages/core/src/tools/agent.test.ts b/packages/core/src/tools/agent.test.ts index aae2f6373..505b434a0 100644 --- a/packages/core/src/tools/agent.test.ts +++ b/packages/core/src/tools/agent.test.ts @@ -8,6 +8,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { AgentTool, type AgentParams } from './agent.js'; import type { PartListUnion } from '@google/genai'; import type { ToolResultDisplay, AgentResultDisplay } from './tools.js'; +import { ToolConfirmationOutcome } from './tools.js'; import type { Config } from '../config/config.js'; import { SubagentManager } from '../subagents/subagent-manager.js'; import type { SubagentConfig } from '../subagents/types.js'; @@ -16,22 +17,32 @@ import { type AgentHeadless, ContextState, } from '../agents/runtime/agent-headless.js'; +import { AgentEventType } from '../agents/runtime/agent-events.js'; +import type { + AgentToolCallEvent, + AgentToolResultEvent, + AgentApprovalRequestEvent, + AgentEventEmitter, +} from '../agents/runtime/agent-events.js'; import { partToString } from '../utils/partUtils.js'; import type { HookSystem } from '../hooks/hookSystem.js'; import { PermissionMode } from '../hooks/types.js'; // Type for accessing protected methods in tests +type AgentToolInvocation = { + execute: ( + signal?: AbortSignal, + updateOutput?: (output: ToolResultDisplay) => void, + ) => Promise<{ + llmContent: PartListUnion; + returnDisplay: ToolResultDisplay; + }>; + getDescription: () => string; + eventEmitter: AgentEventEmitter; +}; + type AgentToolWithProtectedMethods = AgentTool & { - createInvocation: (params: AgentParams) => { - execute: ( - signal?: AbortSignal, - liveOutputCallback?: (chunk: string) => void, - ) => Promise<{ - llmContent: PartListUnion; - returnDisplay: ToolResultDisplay; - }>; - getDescription: () => string; - }; + createInvocation: (params: AgentParams) => AgentToolInvocation; }; // Mock dependencies @@ -617,6 +628,7 @@ describe('AgentTool', () => { expect.stringContaining('file-search-'), 'file-search', PermissionMode.Default, + undefined, ); }); @@ -798,6 +810,7 @@ describe('AgentTool', () => { 'Task completed successfully', false, PermissionMode.Default, + undefined, ); }); @@ -842,6 +855,7 @@ describe('AgentTool', () => { 'Task completed successfully', true, PermissionMode.Default, + undefined, ); }); @@ -998,4 +1012,295 @@ describe('AgentTool', () => { expect(startAgentId).toMatch(/^file-search-\d+$/); }); }); + + describe('IDE diff-tab confirmation clears pendingConfirmation', () => { + let mockAgent: AgentHeadless; + let mockContextState: ContextState; + + // We capture the eventEmitter from the invocation so we can simulate + // events during subagent execution. + let capturedInvocation: AgentToolInvocation; + + beforeEach(() => { + mockContextState = { + set: vi.fn(), + } as unknown as ContextState; + + MockedContextState.mockImplementation(() => mockContextState); + + vi.mocked(mockSubagentManager.loadSubagent).mockResolvedValue( + mockSubagents[0], + ); + }); + + function createInvocationWithEventDrivenAgent( + emitDuringExecute: (emitter: AgentEventEmitter) => void, + ) { + // Create a mock agent whose execute() emits events on the invocation's + // eventEmitter, simulating a real subagent lifecycle. + mockAgent = { + execute: vi.fn(), + result: 'Done', + terminateMode: AgentTerminateMode.GOAL, + getFinalText: vi.fn().mockReturnValue('Done'), + formatCompactResult: vi.fn().mockReturnValue('✅ Success'), + getExecutionSummary: vi.fn().mockReturnValue({ + rounds: 1, + totalDurationMs: 100, + totalToolCalls: 1, + successfulToolCalls: 1, + failedToolCalls: 0, + successRate: 100, + inputTokens: 10, + outputTokens: 5, + totalTokens: 15, + toolUsage: [], + }), + getStatistics: vi.fn().mockReturnValue({ + rounds: 1, + totalDurationMs: 100, + totalToolCalls: 1, + successfulToolCalls: 1, + failedToolCalls: 0, + }), + getTerminateMode: vi.fn().mockReturnValue(AgentTerminateMode.GOAL), + } as unknown as AgentHeadless; + + vi.mocked(mockAgent.execute).mockImplementation(async () => { + emitDuringExecute(capturedInvocation.eventEmitter); + }); + + vi.mocked(mockSubagentManager.createAgentHeadless).mockResolvedValue( + mockAgent, + ); + + const params: AgentParams = { + description: 'Edit files', + prompt: 'Fix the bug', + subagent_type: 'file-search', + }; + + capturedInvocation = ( + agentTool as AgentToolWithProtectedMethods + ).createInvocation(params); + + return capturedInvocation; + } + + it('should clear pendingConfirmation when TOOL_RESULT arrives for the pending tool (IDE accept path)', async () => { + // Track whether pendingConfirmation was set then cleared, using + // snapshots that safely handle function properties (structuredClone + // can't serialize functions). + const snapshots: Array<{ + hasPendingConfirmation: boolean; + toolStatuses: Array<{ callId: string; status: string }>; + }> = []; + + const invocation = createInvocationWithEventDrivenAgent((emitter) => { + emitter.emit(AgentEventType.TOOL_CALL, { + subagentId: 'sub-1', + round: 1, + callId: 'call-edit-1', + name: 'edit_file', + args: { path: '/test.ts' }, + description: 'Editing test.ts', + timestamp: Date.now(), + } satisfies AgentToolCallEvent); + + // Tool needs approval → pendingConfirmation is set + emitter.emit(AgentEventType.TOOL_WAITING_APPROVAL, { + subagentId: 'sub-1', + round: 1, + callId: 'call-edit-1', + name: 'edit_file', + description: 'Editing test.ts', + timestamp: Date.now(), + confirmationDetails: { + type: 'edit' as const, + title: 'Edit file', + fileName: 'test.ts', + filePath: '/test.ts', + fileDiff: '', + originalContent: 'old', + newContent: 'new', + }, + respond: vi.fn(), + } as unknown as AgentApprovalRequestEvent); + + // IDE diff-tab accepted → TOOL_RESULT arrives without onConfirm + emitter.emit(AgentEventType.TOOL_RESULT, { + subagentId: 'sub-1', + round: 1, + callId: 'call-edit-1', + name: 'edit_file', + success: true, + timestamp: Date.now(), + } satisfies AgentToolResultEvent); + }); + + await invocation.execute(undefined, (output) => { + const display = output as AgentResultDisplay; + snapshots.push({ + hasPendingConfirmation: display.pendingConfirmation !== undefined, + toolStatuses: (display.toolCalls ?? []).map((tc) => ({ + callId: tc.callId, + status: tc.status, + })), + }); + }); + + // Should have at least one snapshot with pendingConfirmation set + const hasApproval = snapshots.some((s) => s.hasPendingConfirmation); + expect(hasApproval).toBe(true); + + // The final snapshot after TOOL_RESULT should have cleared it + const resultSnapshot = snapshots.find( + (s) => + !s.hasPendingConfirmation && + s.toolStatuses.some( + (tc) => tc.callId === 'call-edit-1' && tc.status === 'success', + ), + ); + expect(resultSnapshot).toBeDefined(); + }); + + it('should NOT clear pendingConfirmation when TOOL_RESULT is for a different tool', async () => { + const snapshots: Array<{ + hasPendingConfirmation: boolean; + toolStatuses: Array<{ callId: string; status: string }>; + }> = []; + + const invocation = createInvocationWithEventDrivenAgent((emitter) => { + // Tool A starts + emitter.emit(AgentEventType.TOOL_CALL, { + subagentId: 'sub-1', + round: 1, + callId: 'call-read-1', + name: 'read_file', + args: {}, + description: 'Reading', + timestamp: Date.now(), + } satisfies AgentToolCallEvent); + + // Tool B starts + emitter.emit(AgentEventType.TOOL_CALL, { + subagentId: 'sub-1', + round: 1, + callId: 'call-edit-1', + name: 'edit_file', + args: {}, + description: 'Editing', + timestamp: Date.now(), + } satisfies AgentToolCallEvent); + + // Tool B needs approval + emitter.emit(AgentEventType.TOOL_WAITING_APPROVAL, { + subagentId: 'sub-1', + round: 1, + callId: 'call-edit-1', + name: 'edit_file', + description: 'Editing', + timestamp: Date.now(), + confirmationDetails: { + type: 'edit' as const, + title: 'Edit', + fileName: 'test.ts', + filePath: '/test.ts', + fileDiff: '', + originalContent: '', + newContent: 'new', + }, + respond: vi.fn(), + } as unknown as AgentApprovalRequestEvent); + + // Tool A finishes (different callId) + emitter.emit(AgentEventType.TOOL_RESULT, { + subagentId: 'sub-1', + round: 1, + callId: 'call-read-1', + name: 'read_file', + success: true, + timestamp: Date.now(), + } satisfies AgentToolResultEvent); + }); + + await invocation.execute(undefined, (output) => { + const display = output as AgentResultDisplay; + snapshots.push({ + hasPendingConfirmation: display.pendingConfirmation !== undefined, + toolStatuses: (display.toolCalls ?? []).map((tc) => ({ + callId: tc.callId, + status: tc.status, + })), + }); + }); + + // The snapshot for read_file's TOOL_RESULT should still have + // pendingConfirmation because the result was for a different tool. + const readResultSnapshot = snapshots.find((s) => + s.toolStatuses.some( + (tc) => tc.callId === 'call-read-1' && tc.status === 'success', + ), + ); + expect(readResultSnapshot).toBeDefined(); + expect(readResultSnapshot!.hasPendingConfirmation).toBe(true); + }); + + it('should clear pendingConfirmation via onConfirm callback (terminal UI path)', async () => { + let capturedOnConfirm: + | ((outcome: ToolConfirmationOutcome) => Promise) + | undefined; + const snapshots: Array<{ hasPendingConfirmation: boolean }> = []; + + const invocation = createInvocationWithEventDrivenAgent((emitter) => { + emitter.emit(AgentEventType.TOOL_CALL, { + subagentId: 'sub-1', + round: 1, + callId: 'call-edit-1', + name: 'edit_file', + args: {}, + description: 'Editing', + timestamp: Date.now(), + } satisfies AgentToolCallEvent); + + emitter.emit(AgentEventType.TOOL_WAITING_APPROVAL, { + subagentId: 'sub-1', + round: 1, + callId: 'call-edit-1', + name: 'edit_file', + description: 'Editing', + timestamp: Date.now(), + confirmationDetails: { + type: 'edit' as const, + title: 'Edit', + fileName: 'test.ts', + filePath: '/test.ts', + fileDiff: '', + originalContent: '', + newContent: 'new', + }, + respond: vi.fn(), + } as unknown as AgentApprovalRequestEvent); + }); + + await invocation.execute(undefined, (output) => { + const display = output as AgentResultDisplay; + snapshots.push({ + hasPendingConfirmation: display.pendingConfirmation !== undefined, + }); + if (display.pendingConfirmation?.onConfirm) { + capturedOnConfirm = display.pendingConfirmation.onConfirm; + } + }); + + expect(capturedOnConfirm).toBeDefined(); + + // Call onConfirm as if the user pressed "accept" in the terminal UI + snapshots.length = 0; + await capturedOnConfirm!(ToolConfirmationOutcome.ProceedOnce); + + // The onConfirm callback should have cleared pendingConfirmation + expect(snapshots.some((s) => !s.hasPendingConfirmation)).toBe(true); + }); + }); }); diff --git a/packages/core/src/tools/agent.ts b/packages/core/src/tools/agent.ts index 1b0c1c924..c8599badc 100644 --- a/packages/core/src/tools/agent.ts +++ b/packages/core/src/tools/agent.ts @@ -308,6 +308,8 @@ class AgentToolInvocation extends BaseToolInvocation { private setupEventListeners( updateOutput?: (output: ToolResultDisplay) => void, ): void { + let pendingConfirmationCallId: string | undefined; + this.eventEmitter.on(AgentEventType.START, () => { this.updateDisplay({ status: 'running' }, updateOutput); }); @@ -344,9 +346,22 @@ class AgentToolInvocation extends BaseToolInvocation { responseParts: event.responseParts, }; + // When a tool result arrives for the tool that had a pending + // confirmation, clear the stale prompt. This handles the case where + // the IDE diff-tab accept resolved the tool via CoreToolScheduler's + // ideConfirmation.then path, which bypasses the UI's onConfirm wrapper. + const clearPending = + pendingConfirmationCallId === event.callId + ? { pendingConfirmation: undefined } + : {}; + if (pendingConfirmationCallId === event.callId) { + pendingConfirmationCallId = undefined; + } + this.updateDisplay( { toolCalls: [...this.currentToolCalls!], + ...clearPending, }, updateOutput, ); @@ -398,6 +413,7 @@ class AgentToolInvocation extends BaseToolInvocation { } // Bridge scheduler confirmation details to UI inline prompt + pendingConfirmationCallId = event.callId; const details: ToolCallConfirmationDetails = { ...(event.confirmationDetails as Omit< ToolCallConfirmationDetails, @@ -409,6 +425,7 @@ class AgentToolInvocation extends BaseToolInvocation { ) => { // Clear the inline prompt immediately // and optimistically mark the tool as executing for proceed outcomes. + pendingConfirmationCallId = undefined; const proceedOutcomes = new Set([ ToolConfirmationOutcome.ProceedOnce, ToolConfirmationOutcome.ProceedAlways, @@ -525,6 +542,7 @@ class AgentToolInvocation extends BaseToolInvocation { agentId, agentType, PermissionMode.Default, + signal, ); // Inject additional context from hook output into subagent context @@ -572,6 +590,7 @@ class AgentToolInvocation extends BaseToolInvocation { subagent.getFinalText(), stopHookActive, PermissionMode.Default, + signal, ); const typedStopOutput = stopHookOutput as diff --git a/packages/core/src/tools/edit.test.ts b/packages/core/src/tools/edit.test.ts index c67520385..71ff12209 100644 --- a/packages/core/src/tools/edit.test.ts +++ b/packages/core/src/tools/edit.test.ts @@ -922,5 +922,48 @@ describe('EditTool', () => { expect(params.old_string).toBe(initialContent); expect(params.new_string).toBe(modifiedContent); }); + + it('should not call ideClient.openDiff in AUTO_EDIT mode', async () => { + const initialContent = 'some old content here'; + fs.writeFileSync(filePath, initialContent); + const params: EditToolParams = { + file_path: filePath, + old_string: 'old', + new_string: 'new', + }; + (mockConfig.getApprovalMode as Mock).mockReturnValueOnce( + ApprovalMode.AUTO_EDIT, + ); + + const invocation = tool.build(params); + const confirmation = await invocation.getConfirmationDetails( + new AbortController().signal, + ); + + expect(ideClient.openDiff).not.toHaveBeenCalled(); + expect(confirmation).toBeDefined(); + expect((confirmation as any).ideConfirmation).toBeUndefined(); + }); + + it('should not call ideClient.openDiff in YOLO mode', async () => { + const initialContent = 'some old content here'; + fs.writeFileSync(filePath, initialContent); + const params: EditToolParams = { + file_path: filePath, + old_string: 'old', + new_string: 'new', + }; + (mockConfig.getApprovalMode as Mock).mockReturnValueOnce( + ApprovalMode.YOLO, + ); + + const invocation = tool.build(params); + const confirmation = await invocation.getConfirmationDetails( + new AbortController().signal, + ); + + expect(ideClient.openDiff).not.toHaveBeenCalled(); + expect((confirmation as any).ideConfirmation).toBeUndefined(); + }); }); }); diff --git a/packages/core/src/tools/edit.ts b/packages/core/src/tools/edit.ts index e5b1480b9..e41ec3a55 100644 --- a/packages/core/src/tools/edit.ts +++ b/packages/core/src/tools/edit.ts @@ -21,7 +21,12 @@ import { makeRelative, shortenPath } from '../utils/paths.js'; import { isNodeError } from '../utils/errors.js'; import type { Config } from '../config/config.js'; import { ApprovalMode } from '../config/config.js'; -import { FileEncoding, needsUtf8Bom } from '../services/fileSystemService.js'; +import { + FileEncoding, + needsUtf8Bom, + detectLineEnding, +} from '../services/fileSystemService.js'; +import type { LineEnding } from '../services/fileSystemService.js'; import { DEFAULT_DIFF_OPTIONS, getDiffStat } from './diffOptions.js'; import { ReadFileTool } from './read-file.js'; import { ToolNames, ToolDisplayNames } from './tool-names.js'; @@ -113,6 +118,8 @@ interface CalculatedEdit { encoding: string; /** Whether the existing file has a UTF-8 BOM */ bom: boolean; + /** Original line ending style of the existing file */ + lineEnding: LineEnding; } class EditToolInvocation implements ToolInvocation { @@ -144,6 +151,7 @@ class EditToolInvocation implements ToolInvocation { | undefined = undefined; let useBOM = false; let detectedEncoding = 'utf-8'; + let detectedLineEnding: LineEnding = 'lf'; if (fileExists) { try { const fileInfo = await this.config @@ -157,6 +165,8 @@ class EditToolInvocation implements ToolInvocation { fileInfo.content.codePointAt(0) === 0xfeff; } detectedEncoding = fileInfo._meta?.encoding || 'utf-8'; + // Detect original line ending style before normalizing + detectedLineEnding = detectLineEnding(fileInfo.content); // Normalize line endings to LF for consistent processing. currentContent = fileInfo.content.replace(/\r\n/g, '\n'); fileExists = true; @@ -257,6 +267,7 @@ class EditToolInvocation implements ToolInvocation { isNewFile, bom: useBOM, encoding: detectedEncoding, + lineEnding: detectedLineEnding, }; } @@ -297,9 +308,13 @@ class EditToolInvocation implements ToolInvocation { 'Proposed', DEFAULT_DIFF_OPTIONS, ); + const approvalMode = this.config.getApprovalMode(); const ideClient = await IdeClient.getInstance(); const ideConfirmation = - this.config.getIdeMode() && ideClient.isDiffingEnabled() + this.config.getIdeMode() && + ideClient.isDiffingEnabled() && + approvalMode !== ApprovalMode.AUTO_EDIT && + approvalMode !== ApprovalMode.YOLO ? ideClient.openDiff(this.params.file_path, editData.newContent) : undefined; @@ -414,6 +429,7 @@ class EditToolInvocation implements ToolInvocation { _meta: { bom: editData.bom, encoding: editData.encoding, + lineEnding: editData.lineEnding, }, }); } diff --git a/packages/core/src/tools/glob.test.ts b/packages/core/src/tools/glob.test.ts index dc1537930..67769a6e9 100644 --- a/packages/core/src/tools/glob.test.ts +++ b/packages/core/src/tools/glob.test.ts @@ -366,6 +366,87 @@ describe('GlobTool', () => { }); }); + describe('multi-directory workspace', () => { + it('should search across all workspace directories when no path is specified', async () => { + // Create a second workspace directory + const secondDir = await fs.mkdtemp( + path.join(os.tmpdir(), 'glob-tool-second-'), + ); + await fs.writeFile(path.join(secondDir, '.git'), ''); // Fake git repo + await fs.writeFile(path.join(secondDir, 'extra.txt'), 'extra content'); + await fs.writeFile(path.join(secondDir, 'bonus.txt'), 'bonus content'); + + const multiDirConfig = { + ...mockConfig, + getWorkspaceContext: () => + createMockWorkspaceContext(tempRootDir, [secondDir]), + } as unknown as Config; + + const multiDirGlobTool = new GlobTool(multiDirConfig); + const params: GlobToolParams = { pattern: '*.txt' }; + const invocation = multiDirGlobTool.build(params); + const result = await invocation.execute(abortSignal); + + // Should find files from both directories + expect(result.llmContent).toContain(path.join(tempRootDir, 'fileA.txt')); + expect(result.llmContent).toContain(path.join(secondDir, 'extra.txt')); + expect(result.llmContent).toContain(path.join(secondDir, 'bonus.txt')); + expect(result.llmContent).toContain('across 2 workspace directories'); + + await fs.rm(secondDir, { recursive: true, force: true }); + }); + + it('should deduplicate entries across overlapping directories', async () => { + // Use the same directory twice to test deduplication + const multiDirConfig = { + ...mockConfig, + getWorkspaceContext: () => + createMockWorkspaceContext(tempRootDir, [tempRootDir]), + } as unknown as Config; + + const multiDirGlobTool = new GlobTool(multiDirConfig); + const params: GlobToolParams = { pattern: '*.txt' }; + const invocation = multiDirGlobTool.build(params); + const result = await invocation.execute(abortSignal); + + // Should still only have 2 txt files (fileA.txt, FileB.TXT), not doubled + expect(result.llmContent).toContain('Found 2 file(s)'); + }); + + it('should use single directory description when only one workspace dir', async () => { + const params: GlobToolParams = { pattern: '*.txt' }; + const invocation = globTool.build(params); + const result = await invocation.execute(abortSignal); + + expect(result.llmContent).toContain('in the workspace directory'); + expect(result.llmContent).not.toContain('across'); + }); + + it('should search only the specified path when path is provided (ignoring multi-dir)', async () => { + const secondDir = await fs.mkdtemp( + path.join(os.tmpdir(), 'glob-tool-second-'), + ); + await fs.writeFile(path.join(secondDir, '.git'), ''); + await fs.writeFile(path.join(secondDir, 'other.txt'), 'other'); + + const multiDirConfig = { + ...mockConfig, + getWorkspaceContext: () => + createMockWorkspaceContext(tempRootDir, [secondDir]), + } as unknown as Config; + + const multiDirGlobTool = new GlobTool(multiDirConfig); + const params: GlobToolParams = { pattern: '*.txt', path: 'sub' }; + const invocation = multiDirGlobTool.build(params); + const result = await invocation.execute(abortSignal); + + // Should NOT find files from secondDir + expect(result.llmContent).not.toContain('other.txt'); + + await fs.rm(secondDir, { recursive: true, force: true }); + }); + }); + describe('ignore file handling', () => { it('should respect .gitignore files by default', async () => { await fs.writeFile(path.join(tempRootDir, '.gitignore'), '*.ignored.txt'); @@ -410,6 +491,44 @@ describe('GlobTool', () => { expect(result.llmContent).toContain('Found 3 file(s)'); // fileA.txt, FileB.TXT, b.notignored.txt expect(result.llmContent).not.toContain('a.qwenignored.txt'); }); + + it('should respect .gitignore when searching a subdirectory (path option)', async () => { + // This tests the regression fix: relativePaths must be computed relative + // to projectRoot, not to searchDir, so that gitignore rules rooted at + // projectRoot are evaluated against the correct paths. + await fs.writeFile(path.join(tempRootDir, '.gitignore'), '*.secret'); + await fs.writeFile(path.join(tempRootDir, 'sub', 'visible.txt'), 'ok'); + await fs.writeFile( + path.join(tempRootDir, 'sub', 'hidden.secret'), + 'should be ignored', + ); + + const subDirTool = new GlobTool(mockConfig); + const params: GlobToolParams = { pattern: '*', path: 'sub' }; + const invocation = subDirTool.build(params); + const result = await invocation.execute(abortSignal); + + expect(result.llmContent).toContain('visible.txt'); + expect(result.llmContent).not.toContain('hidden.secret'); + }); + + it('should respect .qwenignore when searching a subdirectory (path option)', async () => { + await fs.writeFile(path.join(tempRootDir, '.qwenignore'), '*.secret'); + await fs.writeFile(path.join(tempRootDir, 'sub', 'visible.txt'), 'ok'); + await fs.writeFile( + path.join(tempRootDir, 'sub', 'hidden.secret'), + 'should be ignored', + ); + + // Recreate to pick up .qwenignore + const subDirTool = new GlobTool(mockConfig); + const params: GlobToolParams = { pattern: '*', path: 'sub' }; + const invocation = subDirTool.build(params); + const result = await invocation.execute(abortSignal); + + expect(result.llmContent).toContain('visible.txt'); + expect(result.llmContent).not.toContain('hidden.secret'); + }); }); describe('file count truncation', () => { diff --git a/packages/core/src/tools/glob.ts b/packages/core/src/tools/glob.ts index 12a29922a..ab6b6d80a 100644 --- a/packages/core/src/tools/glob.ts +++ b/packages/core/src/tools/glob.ts @@ -119,61 +119,106 @@ class GlobToolInvocation extends BaseToolInvocation< return 'ask'; } + /** + * Runs glob search in a single directory and returns filtered entries. + */ + private async globInDirectory( + searchDir: string, + pattern: string, + signal: AbortSignal, + ): Promise { + let effectivePattern = pattern; + const fullPath = path.join(searchDir, effectivePattern); + if (fs.existsSync(fullPath)) { + effectivePattern = escape(effectivePattern); + } + + const entries = (await glob(effectivePattern, { + cwd: searchDir, + withFileTypes: true, + nodir: true, + stat: true, + nocase: true, + dot: true, + follow: false, + signal, + })) as GlobPath[]; + + // Filter using paths relative to the project root (the base that + // FileDiscoveryService uses for .gitignore / .qwenignore evaluation). + // Using searchDir-relative paths would cause ignore rules to be + // evaluated against incorrect paths when searchDir != projectRoot. + const projectRoot = this.config.getTargetDir(); + const relativePaths = entries.map((p) => + path.relative(projectRoot, p.fullpath()), + ); + + const { filteredPaths } = this.fileService.filterFilesWithReport( + relativePaths, + this.getFileFilteringOptions(), + ); + + const normalizePathForComparison = (p: string) => + process.platform === 'win32' || process.platform === 'darwin' + ? p.toLowerCase() + : p; + + const filteredAbsolutePaths = new Set( + filteredPaths.map((p) => + normalizePathForComparison(path.resolve(projectRoot, p)), + ), + ); + + return entries.filter((entry) => + filteredAbsolutePaths.has(normalizePathForComparison(entry.fullpath())), + ); + } + async execute(signal: AbortSignal): Promise { try { - // Default to target directory if no path is provided - const searchDirAbs = resolveAndValidatePath( - this.config, - this.params.path, - { allowExternalPaths: true }, - ); - const searchLocationDescription = this.params.path - ? `within ${searchDirAbs}` - : `in the workspace directory`; + // Determine which directories to search + const searchDirs: string[] = []; + let searchLocationDescription: string; - // Collect entries from the search directory - let pattern = this.params.pattern; - const fullPath = path.join(searchDirAbs, pattern); - if (fs.existsSync(fullPath)) { - pattern = escape(pattern); + if (this.params.path) { + // User specified a path — search only that directory + const searchDirAbs = resolveAndValidatePath( + this.config, + this.params.path, + { allowExternalPaths: true }, + ); + searchDirs.push(searchDirAbs); + searchLocationDescription = `within ${searchDirAbs}`; + } else { + // No path specified — search all workspace directories + const workspaceDirs = this.config + .getWorkspaceContext() + .getDirectories(); + searchDirs.push(...workspaceDirs); + searchLocationDescription = + workspaceDirs.length > 1 + ? `across ${workspaceDirs.length} workspace directories` + : `in the workspace directory`; } - const allEntries = (await glob(pattern, { - cwd: searchDirAbs, - withFileTypes: true, - nodir: true, - stat: true, - nocase: true, - dot: true, - follow: false, - signal, - })) as GlobPath[]; + // Collect entries from all search directories + const pattern = this.params.pattern; + const allFilteredEntries: GlobPath[] = []; + const seenPaths = new Set(); - const relativePaths = allEntries.map((p) => - path.relative(this.config.getTargetDir(), p.fullpath()), - ); + for (const searchDir of searchDirs) { + const entries = await this.globInDirectory(searchDir, pattern, signal); + for (const entry of entries) { + // Deduplicate entries that might appear in overlapping directories + const normalized = entry.fullpath(); + if (!seenPaths.has(normalized)) { + seenPaths.add(normalized); + allFilteredEntries.push(entry); + } + } + } - const { filteredPaths } = this.fileService.filterFilesWithReport( - relativePaths, - this.getFileFilteringOptions(), - ); - - const normalizePathForComparison = (p: string) => - process.platform === 'win32' || process.platform === 'darwin' - ? p.toLowerCase() - : p; - - const filteredAbsolutePaths = new Set( - filteredPaths.map((p) => - normalizePathForComparison( - path.resolve(this.config.getTargetDir(), p), - ), - ), - ); - - const filteredEntries = allEntries.filter((entry) => - filteredAbsolutePaths.has(normalizePathForComparison(entry.fullpath())), - ); + const filteredEntries = allFilteredEntries; if (!filteredEntries || filteredEntries.length === 0) { return { diff --git a/packages/core/src/tools/grep.test.ts b/packages/core/src/tools/grep.test.ts index 5a07dcada..4af6d8d7c 100644 --- a/packages/core/src/tools/grep.test.ts +++ b/packages/core/src/tools/grep.test.ts @@ -357,6 +357,75 @@ describe('GrepTool', () => { // Clean up await fs.rm(secondDir, { recursive: true, force: true }); }); + + it('should convert relative paths to absolute when searching multiple directories', async () => { + const secondDir = await fs.mkdtemp( + path.join(os.tmpdir(), 'grep-tool-second-'), + ); + await fs.writeFile( + path.join(secondDir, 'extra.txt'), + 'world content in second dir', + ); + + const multiDirConfig = { + getTargetDir: () => tempRootDir, + getWorkspaceContext: () => + createMockWorkspaceContext(tempRootDir, [secondDir]), + getFileExclusions: () => ({ + getGlobExcludes: () => [], + }), + getTruncateToolOutputThreshold: () => 25000, + getTruncateToolOutputLines: () => 1000, + } as unknown as Config; + + const multiDirGrepTool = new GrepTool(multiDirConfig); + + const params: GrepToolParams = { pattern: 'world' }; + const invocation = multiDirGrepTool.build(params); + const result = await invocation.execute(abortSignal); + + // Should show "across N workspace directories" + expect(result.llmContent).toContain('across 2 workspace directories'); + + // File paths from the second directory should be absolute + expect(result.llmContent).toContain( + `File: ${path.resolve(secondDir, 'extra.txt')}`, + ); + + // File paths from the first directory should also be absolute + expect(result.llmContent).toContain( + `File: ${path.resolve(tempRootDir, 'fileA.txt')}`, + ); + + await fs.rm(secondDir, { recursive: true, force: true }); + }); + + it('should deduplicate matches from overlapping workspace directories', async () => { + // This tests the fix: when workspace dirs overlap (parent + child), + // the same file should appear only once in the results. + const subDir = path.join(tempRootDir, 'sub'); + + const multiDirConfig = { + getTargetDir: () => tempRootDir, + getWorkspaceContext: () => + createMockWorkspaceContext(tempRootDir, [subDir]), + getFileExclusions: () => ({ + getGlobExcludes: () => [], + }), + getTruncateToolOutputThreshold: () => 25000, + getTruncateToolOutputLines: () => 1000, + } as unknown as Config; + + const multiDirGrepTool = new GrepTool(multiDirConfig); + // 'sub dir' exists only in sub/fileC.txt — a file that lives under both + // tempRootDir and subDir, so without deduplication it would appear twice. + const params: GrepToolParams = { pattern: 'sub dir' }; + const invocation = multiDirGrepTool.build(params); + const result = await invocation.execute(abortSignal); + + // sub/fileC.txt (or its absolute path equivalent) should appear only once + expect(result.llmContent).toContain('Found 1 match'); + }); }); describe('getDescription', () => { diff --git a/packages/core/src/tools/grep.ts b/packages/core/src/tools/grep.ts index e0df29140..4f927a167 100644 --- a/packages/core/src/tools/grep.ts +++ b/packages/core/src/tools/grep.ts @@ -95,26 +95,64 @@ class GrepToolInvocation extends BaseToolInvocation< async execute(signal: AbortSignal): Promise { try { - // Default to target directory if no path is provided - const searchDirAbs = resolveAndValidatePath( - this.config, - this.params.path, - { allowExternalPaths: true }, - ); - const searchDirDisplay = this.params.path || '.'; + // Determine which directories to search + const searchDirs: string[] = []; + let searchLocationDescription: string; - // Perform grep search - const rawMatches = await this.performGrepSearch({ - pattern: this.params.pattern, - path: searchDirAbs, - glob: this.params.glob, - signal, - }); + if (this.params.path) { + // User specified a path — search only that directory + const searchDirAbs = resolveAndValidatePath( + this.config, + this.params.path, + { allowExternalPaths: true }, + ); + searchDirs.push(searchDirAbs); + searchLocationDescription = `in path "${this.params.path}"`; + } else { + // No path specified — search all workspace directories + const workspaceDirs = this.config + .getWorkspaceContext() + .getDirectories(); + searchDirs.push(...workspaceDirs); + searchLocationDescription = + workspaceDirs.length > 1 + ? `across ${workspaceDirs.length} workspace directories` + : `in the workspace directory`; + } - // Build search description - const searchLocationDescription = this.params.path - ? `in path "${searchDirDisplay}"` - : `in the workspace directory`; + // Perform grep search across all directories + let rawMatches: GrepMatch[] = []; + for (const searchDir of searchDirs) { + const matches = await this.performGrepSearch({ + pattern: this.params.pattern, + path: searchDir, + glob: this.params.glob, + signal, + }); + // When searching multiple directories, convert relative file paths + // to absolute paths so results from different directories are + // unambiguous. + if (searchDirs.length > 1) { + for (const match of matches) { + if (!path.isAbsolute(match.filePath)) { + match.filePath = path.resolve(searchDir, match.filePath); + } + } + } + rawMatches.push(...matches); + } + + // Deduplicate matches that might appear from overlapping workspace + // directories (e.g. parent + child both in workspace dirs). + if (searchDirs.length > 1) { + const seen = new Set(); + rawMatches = rawMatches.filter((match) => { + const key = `${match.filePath}:${match.lineNumber}`; + if (seen.has(key)) return false; + seen.add(key); + return true; + }); + } const filterDescription = this.params.glob ? ` (filter: "${this.params.glob}")` diff --git a/packages/core/src/tools/mcp-tool.test.ts b/packages/core/src/tools/mcp-tool.test.ts index 9d850ad68..b78a4dd52 100644 --- a/packages/core/src/tools/mcp-tool.test.ts +++ b/packages/core/src/tools/mcp-tool.test.ts @@ -736,7 +736,7 @@ describe('DiscoveredMCPTool', () => { }); describe('getDefaultPermission and getConfirmationDetails', () => { - it('should return ask even if trust is true and folder is trusted (trust logic moved to PM)', async () => { + it('should return allow when trust is true', async () => { const trustedTool = new DiscoveredMCPTool( mockCallableToolInstance, serverName, @@ -748,7 +748,7 @@ describe('DiscoveredMCPTool', () => { { isTrustedFolder: () => true } as any, ); const invocation = trustedTool.build({ param: 'mock' }); - expect(await invocation.getDefaultPermission()).toBe('ask'); + expect(await invocation.getDefaultPermission()).toBe('allow'); }); it('should return ask if not trusted', async () => { @@ -808,7 +808,7 @@ describe('DiscoveredMCPTool', () => { isTrustedFolder: () => isTrusted, }); - it('should return ask even if trust is true and folder is trusted (trust logic moved to PM)', async () => { + it('should return allow when trust is true and folder is trusted', async () => { const trustedTool = new DiscoveredMCPTool( mockCallableToolInstance, serverName, @@ -820,7 +820,7 @@ describe('DiscoveredMCPTool', () => { mockConfig(true) as any, // isTrustedFolder = true ); const invocation = trustedTool.build({ param: 'mock' }); - expect(await invocation.getDefaultPermission()).toBe('ask'); + expect(await invocation.getDefaultPermission()).toBe('allow'); }); it('should return ask if trust is true but folder is not trusted', async () => { diff --git a/packages/core/src/tools/mcp-tool.ts b/packages/core/src/tools/mcp-tool.ts index 44b937633..05ffe7fc2 100644 --- a/packages/core/src/tools/mcp-tool.ts +++ b/packages/core/src/tools/mcp-tool.ts @@ -124,14 +124,17 @@ class DiscoveredMCPToolInvocation extends BaseToolInvocation< } /** - * MCP tool default permission based on annotations: + * MCP tool default permission based on trust and annotations: + * - trust: true in a trusted folder → 'allow' (server explicitly trusted by user config) * - readOnlyHint → 'allow' * - All other MCP tools → 'ask' - * - * Note: trust/isTrustedFolder logic is now handled by PM rules, - * not by getDefaultPermission(). */ override async getDefaultPermission(): Promise { + // MCP servers explicitly marked as trusted bypass confirmation, + // but only when the workspace folder is also trusted (security gate). + if (this.trust === true && this.cliConfig?.isTrustedFolder()) { + return 'allow'; + } // MCP tools annotated with readOnlyHint: true are safe if (this.annotations?.readOnlyHint === true) { return 'allow'; diff --git a/packages/core/src/tools/ripGrep.test.ts b/packages/core/src/tools/ripGrep.test.ts index 05730a7e9..118ed9791 100644 --- a/packages/core/src/tools/ripGrep.test.ts +++ b/packages/core/src/tools/ripGrep.test.ts @@ -436,6 +436,146 @@ describe('RipGrepTool', () => { }); }); + describe('multi-directory workspace', () => { + it('should search across all workspace directories when no path is specified', async () => { + const secondDir = await fs.mkdtemp( + path.join(os.tmpdir(), 'grep-tool-second-'), + ); + await fs.writeFile( + path.join(secondDir, 'extra.txt'), + 'hello from second dir', + ); + + const multiDirConfig = { + ...mockConfig, + getWorkspaceContext: () => + createMockWorkspaceContext(tempRootDir, [secondDir]), + } as unknown as Config; + + const multiDirGrepTool = new RipGrepTool(multiDirConfig); + + (runRipgrep as Mock).mockResolvedValue({ + stdout: `fileA.txt:1:hello world${EOL}${secondDir}/extra.txt:1:hello from second dir${EOL}`, + truncated: false, + error: undefined, + }); + + const params: RipGrepToolParams = { pattern: 'hello' }; + const invocation = multiDirGrepTool.build(params); + const result = await invocation.execute(abortSignal); + + expect(result.llmContent).toContain('across 2 workspace directories'); + expect(result.llmContent).toContain('Found 2 matches'); + + // Verify both paths were passed to runRipgrep + expect(runRipgrep).toHaveBeenCalledWith( + expect.arrayContaining([tempRootDir, secondDir]), + expect.anything(), + ); + + await fs.rm(secondDir, { recursive: true, force: true }); + }); + + it('should search only specified path when path is given (ignoring multi-dir)', async () => { + const secondDir = await fs.mkdtemp( + path.join(os.tmpdir(), 'grep-tool-second-'), + ); + await fs.writeFile(path.join(secondDir, 'other.txt'), 'other content'); + + const multiDirConfig = { + ...mockConfig, + getWorkspaceContext: () => + createMockWorkspaceContext(tempRootDir, [secondDir]), + } as unknown as Config; + + const multiDirGrepTool = new RipGrepTool(multiDirConfig); + + (runRipgrep as Mock).mockResolvedValue({ + stdout: `fileC.txt:1:another world in sub dir${EOL}`, + truncated: false, + error: undefined, + }); + + const params: RipGrepToolParams = { pattern: 'world', path: 'sub' }; + const invocation = multiDirGrepTool.build(params); + const result = await invocation.execute(abortSignal); + + expect(result.llmContent).toContain('in path "sub"'); + expect(result.llmContent).not.toContain('across'); + + await fs.rm(secondDir, { recursive: true, force: true }); + }); + + it('should load .qwenignore from each workspace directory', async () => { + const secondDir = await fs.mkdtemp( + path.join(os.tmpdir(), 'grep-tool-second-'), + ); + await fs.writeFile(path.join(secondDir, '.qwenignore'), 'ignored.txt\n'); + await fs.writeFile( + path.join(tempRootDir, '.qwenignore'), + 'other-ignored.txt\n', + ); + + const multiDirConfig = { + ...mockConfig, + getWorkspaceContext: () => + createMockWorkspaceContext(tempRootDir, [secondDir]), + } as unknown as Config; + + const multiDirGrepTool = new RipGrepTool(multiDirConfig); + + (runRipgrep as Mock).mockResolvedValue({ + stdout: '', + truncated: false, + error: undefined, + }); + + const params: RipGrepToolParams = { pattern: 'test' }; + const invocation = multiDirGrepTool.build(params); + await invocation.execute(abortSignal); + + // Verify both .qwenignore files were passed + const rgArgs = (runRipgrep as Mock).mock.calls[0][0] as string[]; + const ignoreFileArgs = rgArgs.filter( + (a: string, i: number) => i > 0 && rgArgs[i - 1] === '--ignore-file', + ); + expect(ignoreFileArgs).toContain(path.join(tempRootDir, '.qwenignore')); + expect(ignoreFileArgs).toContain(path.join(secondDir, '.qwenignore')); + + await fs.rm(secondDir, { recursive: true, force: true }); + }); + + it('should deduplicate matches from overlapping workspace directories', async () => { + // This tests the fix: when ripgrep receives overlapping search paths + // (e.g. /parent and /parent/sub), it may report the same file twice. + // The deduplication layer must remove duplicates. + const subDir = path.join(tempRootDir, 'sub'); + + const multiDirConfig = { + ...mockConfig, + getWorkspaceContext: () => + createMockWorkspaceContext(tempRootDir, [subDir]), + } as unknown as Config; + + const multiDirGrepTool = new RipGrepTool(multiDirConfig); + + // Simulate ripgrep returning the same file:line twice (once from each search root) + const dupLine = `${path.join(subDir, 'fileC.txt')}:1:hello world`; + (runRipgrep as Mock).mockResolvedValue({ + stdout: `${dupLine}${EOL}${dupLine}${EOL}`, + truncated: false, + error: undefined, + }); + + const params: RipGrepToolParams = { pattern: 'hello' }; + const invocation = multiDirGrepTool.build(params); + const result = await invocation.execute(abortSignal); + + // Despite two identical lines in the raw output, only 1 match should be reported. + expect(result.llmContent).toContain('Found 1 match'); + }); + }); + describe('abort signal handling', () => { it('should handle AbortSignal during search', async () => { const controller = new AbortController(); diff --git a/packages/core/src/tools/ripGrep.ts b/packages/core/src/tools/ripGrep.ts index 4419e0796..a023d9d61 100644 --- a/packages/core/src/tools/ripGrep.ts +++ b/packages/core/src/tools/ripGrep.ts @@ -58,17 +58,32 @@ class GrepToolInvocation extends BaseToolInvocation< async execute(signal: AbortSignal): Promise { try { - const searchDirAbs = resolveAndValidatePath( - this.config, - this.params.path, - { allowFiles: true }, - ); - const searchDirDisplay = this.params.path || '.'; + // Determine which paths to search + const searchPaths: string[] = []; + let searchDirDisplay: string; + + if (this.params.path) { + // User specified a path — search only that path + const searchDirAbs = resolveAndValidatePath( + this.config, + this.params.path, + { allowFiles: true }, + ); + searchPaths.push(searchDirAbs); + searchDirDisplay = this.params.path; + } else { + // No path specified — search all workspace directories + const workspaceDirs = this.config + .getWorkspaceContext() + .getDirectories(); + searchPaths.push(...workspaceDirs); + searchDirDisplay = '.'; + } // Get raw ripgrep output const rawOutput = await this.performRipgrepSearch({ pattern: this.params.pattern, - path: searchDirAbs, + paths: searchPaths, glob: this.params.glob, signal, }); @@ -76,7 +91,9 @@ class GrepToolInvocation extends BaseToolInvocation< // Build search description const searchLocationDescription = this.params.path ? `in path "${searchDirDisplay}"` - : `in the workspace directory`; + : searchPaths.length > 1 + ? `across ${searchPaths.length} workspace directories` + : `in the workspace directory`; const filterDescription = this.params.glob ? ` (filter: "${this.params.glob}")` @@ -89,7 +106,27 @@ class GrepToolInvocation extends BaseToolInvocation< } // Split into lines and count total matches - const allLines = rawOutput.split('\n').filter((line) => line.trim()); + let allLines = rawOutput.split('\n').filter((line) => line.trim()); + + // Deduplicate lines from potentially overlapping workspace directories. + // ripgrep reports the same file twice when given paths like /a and /a/sub. + if (searchPaths.length > 1) { + const seen = new Set(); + allLines = allLines.filter((line) => { + // ripgrep output format: filepath:linenum:content + const firstColon = line.indexOf(':'); + if (firstColon !== -1) { + const secondColon = line.indexOf(':', firstColon + 1); + if (secondColon !== -1) { + const key = line.substring(0, secondColon); + if (seen.has(key)) return false; + seen.add(key); + } + } + return true; + }); + } + const totalMatches = allLines.length; const matchTerm = totalMatches === 1 ? 'match' : 'matches'; @@ -171,11 +208,11 @@ class GrepToolInvocation extends BaseToolInvocation< private async performRipgrepSearch(options: { pattern: string; - path: string; // Can be a file or directory + paths: string[]; // Can be files or directories glob?: string; signal: AbortSignal; }): Promise { - const { pattern, path: absolutePath, glob } = options; + const { pattern, paths, glob } = options; const rgArgs: string[] = [ '--line-number', @@ -193,12 +230,21 @@ class GrepToolInvocation extends BaseToolInvocation< } if (filteringOptions.respectQwenIgnore) { - const qwenIgnorePath = path.join( - this.config.getTargetDir(), - '.qwenignore', - ); - if (fs.existsSync(qwenIgnorePath)) { - rgArgs.push('--ignore-file', qwenIgnorePath); + // Load .qwenignore from each workspace directory, not just the primary one + const seenIgnoreFiles = new Set(); + for (const searchPath of paths) { + const dir = + fs.existsSync(searchPath) && fs.statSync(searchPath).isDirectory() + ? searchPath + : path.dirname(searchPath); + const qwenIgnorePath = path.join(dir, '.qwenignore'); + if ( + !seenIgnoreFiles.has(qwenIgnorePath) && + fs.existsSync(qwenIgnorePath) + ) { + rgArgs.push('--ignore-file', qwenIgnorePath); + seenIgnoreFiles.add(qwenIgnorePath); + } } } @@ -208,7 +254,8 @@ class GrepToolInvocation extends BaseToolInvocation< } rgArgs.push('--threads', '4'); - rgArgs.push(absolutePath); + // Pass all search paths to ripgrep (it supports multiple paths natively) + rgArgs.push(...paths); const result = await runRipgrep(rgArgs, options.signal); if (result.error && !result.stdout) { diff --git a/packages/core/src/tools/shell.test.ts b/packages/core/src/tools/shell.test.ts index 693b03ec1..a8748e375 100644 --- a/packages/core/src/tools/shell.test.ts +++ b/packages/core/src/tools/shell.test.ts @@ -37,6 +37,7 @@ import * as crypto from 'node:crypto'; import { ToolErrorType } from './tool-error.js'; import { OUTPUT_UPDATE_INTERVAL_MS } from './shell.js'; import { createMockWorkspaceContext } from '../test-utils/mockWorkspaceContext.js'; +import { PermissionManager } from '../permissions/permission-manager.js'; describe('ShellTool', () => { let shellTool: ShellTool; @@ -49,6 +50,8 @@ describe('ShellTool', () => { mockConfig = { getCoreTools: vi.fn().mockReturnValue([]), + getPermissionsAllow: vi.fn().mockReturnValue([]), + getPermissionsAsk: vi.fn().mockReturnValue([]), getPermissionsDeny: vi.fn().mockReturnValue([]), getDebugMode: vi.fn().mockReturnValue(false), getTargetDir: vi.fn().mockReturnValue('/test/dir'), @@ -61,6 +64,7 @@ describe('ShellTool', () => { }, getTruncateToolOutputThreshold: vi.fn().mockReturnValue(0), getTruncateToolOutputLines: vi.fn().mockReturnValue(0), + getPermissionManager: vi.fn().mockReturnValue(undefined), getGeminiClient: vi.fn(), getGitCoAuthor: vi.fn().mockReturnValue({ enabled: true, @@ -91,21 +95,21 @@ describe('ShellTool', () => { }); describe('isCommandAllowed', () => { - it('should allow a command if no restrictions are provided', () => { + it('should allow a command if no restrictions are provided', async () => { (mockConfig.getCoreTools as Mock).mockReturnValue(undefined); (mockConfig.getPermissionsDeny as Mock).mockReturnValue(undefined); - expect(isCommandAllowed('ls -l', mockConfig).allowed).toBe(true); + expect((await isCommandAllowed('ls -l', mockConfig)).allowed).toBe(true); }); - it('should block a command with command substitution using $()', () => { - expect(isCommandAllowed('echo $(rm -rf /)', mockConfig).allowed).toBe( - false, - ); + it('should block a command with command substitution using $()', async () => { + expect( + (await isCommandAllowed('echo $(rm -rf /)', mockConfig)).allowed, + ).toBe(false); }); }); describe('build', () => { - it('should return an invocation for a valid command', () => { + it('should return an invocation for a valid command', async () => { const invocation = shellTool.build({ command: 'ls -l', is_background: false, @@ -113,13 +117,13 @@ describe('ShellTool', () => { expect(invocation).toBeDefined(); }); - it('should throw an error for an empty command', () => { + it('should throw an error for an empty command', async () => { expect(() => shellTool.build({ command: ' ', is_background: false }), ).toThrow('Command cannot be empty.'); }); - it('should throw an error for a relative directory path', () => { + it('should throw an error for a relative directory path', async () => { expect(() => shellTool.build({ command: 'ls', @@ -129,7 +133,7 @@ describe('ShellTool', () => { ).toThrow('Directory must be an absolute path.'); }); - it('should throw an error for a directory outside the workspace', () => { + it('should throw an error for a directory outside the workspace', async () => { (mockConfig.getWorkspaceContext as Mock).mockReturnValue( createMockWorkspaceContext('/test/dir', ['/another/workspace']), ); @@ -144,7 +148,7 @@ describe('ShellTool', () => { ); }); - it('should throw an error for a directory within the user skills directory', () => { + it('should throw an error for a directory within the user skills directory', async () => { expect(() => shellTool.build({ command: 'ls', @@ -156,7 +160,7 @@ describe('ShellTool', () => { ); }); - it('should throw an error for the user skills directory itself', () => { + it('should throw an error for the user skills directory itself', async () => { expect(() => shellTool.build({ command: 'ls', @@ -168,7 +172,7 @@ describe('ShellTool', () => { ); }); - it('should resolve directory path before checking user skills directory', () => { + it('should resolve directory path before checking user skills directory', async () => { expect(() => shellTool.build({ command: 'ls', @@ -180,7 +184,7 @@ describe('ShellTool', () => { ); }); - it('should return an invocation for a valid absolute directory path', () => { + it('should return an invocation for a valid absolute directory path', async () => { (mockConfig.getWorkspaceContext as Mock).mockReturnValue( createMockWorkspaceContext('/test/dir', ['/another/workspace']), ); @@ -192,7 +196,7 @@ describe('ShellTool', () => { expect(invocation).toBeDefined(); }); - it('should include background indicator in description when is_background is true', () => { + it('should include background indicator in description when is_background is true', async () => { const invocation = shellTool.build({ command: 'npm start', is_background: true, @@ -200,7 +204,7 @@ describe('ShellTool', () => { expect(invocation.getDescription()).toContain('[background]'); }); - it('should not include background indicator in description when is_background is false', () => { + it('should not include background indicator in description when is_background is false', async () => { const invocation = shellTool.build({ command: 'npm test', is_background: false, @@ -209,7 +213,7 @@ describe('ShellTool', () => { }); describe('is_background parameter coercion', () => { - it('should accept string "true" as boolean true', () => { + it('should accept string "true" as boolean true', async () => { const invocation = shellTool.build({ command: 'npm run dev', is_background: 'true' as unknown as boolean, @@ -218,7 +222,7 @@ describe('ShellTool', () => { expect(invocation.getDescription()).toContain('[background]'); }); - it('should accept string "false" as boolean false', () => { + it('should accept string "false" as boolean false', async () => { const invocation = shellTool.build({ command: 'npm run build', is_background: 'false' as unknown as boolean, @@ -227,7 +231,7 @@ describe('ShellTool', () => { expect(invocation.getDescription()).not.toContain('[background]'); }); - it('should accept string "True" as boolean true', () => { + it('should accept string "True" as boolean true', async () => { const invocation = shellTool.build({ command: 'npm run dev', is_background: 'True' as unknown as boolean, @@ -236,7 +240,7 @@ describe('ShellTool', () => { expect(invocation.getDescription()).toContain('[background]'); }); - it('should accept string "False" as boolean false', () => { + it('should accept string "False" as boolean false', async () => { const invocation = shellTool.build({ command: 'npm run build', is_background: 'False' as unknown as boolean, @@ -459,13 +463,13 @@ describe('ShellTool', () => { expect(result.error?.message).toBe('command failed'); }); - it('should throw an error for invalid parameters', () => { + it('should throw an error for invalid parameters', async () => { expect(() => shellTool.build({ command: '', is_background: false }), ).toThrow('Command cannot be empty.'); }); - it('should throw an error for invalid directory', () => { + it('should throw an error for invalid directory', async () => { expect(() => shellTool.build({ command: 'ls', @@ -949,7 +953,49 @@ describe('ShellTool', () => { ); }); - it('should throw an error if validation fails', () => { + it('should not surface file descriptor redirects as standalone commands in confirmation details', async () => { + const params = { + command: 'npm run build 2>&1 | head -100', + is_background: false, + }; + const invocation = shellTool.build(params); + + const permission = await invocation.getDefaultPermission(); + expect(permission).toBe('ask'); + + const details = (await invocation.getConfirmationDetails( + new AbortController().signal, + )) as { rootCommand: string; permissionRules: string[] }; + + expect(details.rootCommand).toBe('npm'); + expect(details.permissionRules).toEqual(['Bash(npm run *)']); + }); + + it('should exclude already-allowed sub-commands from confirmation details in compound commands', async () => { + const pm = new PermissionManager({ + getPermissionsAllow: () => ['Bash(git add *)'], + getPermissionsAsk: () => [], + getPermissionsDeny: () => [], + getProjectRoot: () => '/test/dir', + getCwd: () => '/test/dir', + }); + pm.initialize(); + (mockConfig.getPermissionManager as Mock).mockReturnValue(pm); + + const invocation = shellTool.build({ + command: 'git add /tmp/file && git commit -m "msg"', + is_background: false, + }); + + const details = (await invocation.getConfirmationDetails( + new AbortController().signal, + )) as { rootCommand: string; permissionRules: string[] }; + + expect(details.rootCommand).toBe('git'); + expect(details.permissionRules).toEqual(['Bash(git commit *)']); + }); + + it('should throw an error if validation fails', async () => { expect(() => shellTool.build({ command: '', is_background: false }), ).toThrow(); @@ -957,13 +1003,13 @@ describe('ShellTool', () => { }); describe('getDescription', () => { - it('should return the windows description when on windows', () => { + it('should return the windows description when on windows', async () => { vi.mocked(os.platform).mockReturnValue('win32'); const shellTool = new ShellTool(mockConfig); expect(shellTool.description).toMatchSnapshot(); }); - it('should return the non-windows description when not on windows', () => { + it('should return the non-windows description when not on windows', async () => { vi.mocked(os.platform).mockReturnValue('linux'); const shellTool = new ShellTool(mockConfig); expect(shellTool.description).toMatchSnapshot(); @@ -1008,7 +1054,7 @@ describe('ShellTool', () => { }); describe('timeout parameter', () => { - it('should validate timeout parameter correctly', () => { + it('should validate timeout parameter correctly', async () => { // Valid timeout expect(() => { shellTool.build({ @@ -1073,7 +1119,7 @@ describe('ShellTool', () => { }).toThrow('params/timeout must be number'); }); - it('should include timeout in description for foreground commands', () => { + it('should include timeout in description for foreground commands', async () => { const invocation = shellTool.build({ command: 'npm test', is_background: false, @@ -1083,7 +1129,7 @@ describe('ShellTool', () => { expect(invocation.getDescription()).toBe('npm test [timeout: 30000ms]'); }); - it('should not include timeout in description for background commands', () => { + it('should not include timeout in description for background commands', async () => { const invocation = shellTool.build({ command: 'npm start', is_background: true, diff --git a/packages/core/src/tools/shell.ts b/packages/core/src/tools/shell.ts index 3d38eaf4b..0300f7bec 100644 --- a/packages/core/src/tools/shell.ts +++ b/packages/core/src/tools/shell.ts @@ -37,7 +37,6 @@ import { getCommandRoots, splitCommands, stripShellWrapper, - detectCommandSubstitution, } from '../utils/shell-utils.js'; import { createDebugLogger } from '../utils/debugLogger.js'; import { @@ -92,18 +91,12 @@ export class ShellToolInvocation extends BaseToolInvocation< /** * AST-based permission check for the shell command. - * - Command substitution → 'deny' (security) * - Read-only commands (via AST analysis) → 'allow' * - All other commands → 'ask' */ override async getDefaultPermission(): Promise { const command = stripShellWrapper(this.params.command); - // Security: command substitution ($(), ``, <(), >()) → deny - if (detectCommandSubstitution(command)) { - return 'deny'; - } - // AST-based read-only detection try { const isReadOnly = await isShellCommandReadOnlyAST(command); @@ -127,25 +120,40 @@ export class ShellToolInvocation extends BaseToolInvocation< _abortSignal: AbortSignal, ): Promise { const command = stripShellWrapper(this.params.command); + const pm = this.config.getPermissionManager?.(); // Split compound command and filter out already-allowed (read-only) sub-commands const subCommands = splitCommands(command); - const nonReadOnlySubCommands: string[] = []; + const confirmableSubCommands: string[] = []; for (const sub of subCommands) { + let isReadOnly = false; try { - const isReadOnly = await isShellCommandReadOnlyAST(sub); - if (!isReadOnly) { - nonReadOnlySubCommands.push(sub); - } + isReadOnly = await isShellCommandReadOnlyAST(sub); } catch { - nonReadOnlySubCommands.push(sub); // conservative: include if check fails + // conservative: treat unknown commands as requiring confirmation } + + if (isReadOnly) { + continue; + } + + if (pm) { + try { + if ((await pm.isCommandAllowed(sub)) === 'allow') { + continue; + } + } catch (e) { + debugLogger.warn('PermissionManager command check failed:', e); + } + } + + confirmableSubCommands.push(sub); } // Fallback to all sub-commands if everything was filtered out (shouldn't // normally happen since getDefaultPermission already returned 'ask'). const effectiveSubCommands = - nonReadOnlySubCommands.length > 0 ? nonReadOnlySubCommands : subCommands; + confirmableSubCommands.length > 0 ? confirmableSubCommands : subCommands; const rootCommands = [ ...new Set( @@ -583,18 +591,10 @@ ${processGroupNote} } function getCommandDescription(): string { - const cmd_substitution_warning = - '\n*** WARNING: Command substitution using $(), `` ` ``, <(), or >() is not allowed for security reasons.'; if (os.platform() === 'win32') { - return ( - 'Exact command to execute as `cmd.exe /c `' + - cmd_substitution_warning - ); + return 'Exact command to execute as `cmd.exe /c `'; } else { - return ( - 'Exact bash command to execute as `bash -c `' + - cmd_substitution_warning - ); + return 'Exact bash command to execute as `bash -c `'; } } @@ -647,9 +647,9 @@ export class ShellTool extends BaseDeclarativeTool< protected override validateToolParamValues( params: ShellToolParams, ): string | null { - // NOTE: Permission checks (command substitution, read-only detection, PM rules) - // are now handled at L3 (getDefaultPermission) and L4 (PM override) in - // coreToolScheduler. This method only performs pure parameter validation. + // NOTE: Permission checks (read-only detection, PM rules) are handled at + // L3 (getDefaultPermission) and L4 (PM override) in coreToolScheduler. + // This method only performs pure parameter validation. if (!params.command.trim()) { return 'Command cannot be empty.'; } diff --git a/packages/core/src/tools/web-fetch.ts b/packages/core/src/tools/web-fetch.ts index c0d04aed6..927d716f5 100644 --- a/packages/core/src/tools/web-fetch.ts +++ b/packages/core/src/tools/web-fetch.ts @@ -111,7 +111,11 @@ ${textContent} const result = await geminiClient.generateContent( [{ role: 'user', parts: [{ text: fallbackPrompt }] }], - {}, + { + systemInstruction: + 'Extract and summarize the requested information from the provided web content. ' + + 'Be concise and accurate. Respond only with the requested information.', + }, signal, this.config.getModel() || DEFAULT_QWEN_MODEL, ); diff --git a/packages/core/src/tools/write-file.test.ts b/packages/core/src/tools/write-file.test.ts index f4808cdc0..407d187b1 100644 --- a/packages/core/src/tools/write-file.test.ts +++ b/packages/core/src/tools/write-file.test.ts @@ -321,6 +321,36 @@ describe('WriteFileTool', () => { expect(mockIdeClient.openDiff).not.toHaveBeenCalled(); }); + it('should not call openDiff in AUTO_EDIT mode', async () => { + mockConfigInternal.getApprovalMode.mockReturnValue( + ApprovalMode.AUTO_EDIT, + ); + const filePath = path.join(rootDir, 'ide_auto_edit_file.txt'); + const params = { file_path: filePath, content: 'test' }; + const invocation = tool.build(params); + + const confirmation = (await invocation.getConfirmationDetails( + abortSignal, + )) as ToolEditConfirmationDetails; + + expect(mockIdeClient.openDiff).not.toHaveBeenCalled(); + expect(confirmation.ideConfirmation).toBeUndefined(); + }); + + it('should not call openDiff in YOLO mode', async () => { + mockConfigInternal.getApprovalMode.mockReturnValue(ApprovalMode.YOLO); + const filePath = path.join(rootDir, 'ide_yolo_file.txt'); + const params = { file_path: filePath, content: 'test' }; + const invocation = tool.build(params); + + const confirmation = (await invocation.getConfirmationDetails( + abortSignal, + )) as ToolEditConfirmationDetails; + + expect(mockIdeClient.openDiff).not.toHaveBeenCalled(); + expect(confirmation.ideConfirmation).toBeUndefined(); + }); + it('should update params.content with IDE content when onConfirm is called', async () => { const filePath = path.join(rootDir, 'ide_onconfirm_file.txt'); const params = { file_path: filePath, content: 'original-content' }; @@ -740,7 +770,7 @@ describe('WriteFileTool', () => { expect(writeSpy).toHaveBeenCalledWith({ path: filePath, content: newContent, - _meta: { bom: true, encoding: 'utf-8' }, + _meta: { bom: true, encoding: 'utf-8', lineEnding: 'lf' }, }); // Cleanup @@ -768,7 +798,7 @@ describe('WriteFileTool', () => { expect(writeSpy).toHaveBeenCalledWith({ path: filePath, content: newContent, - _meta: { bom: false, encoding: 'utf-8' }, + _meta: { bom: false, encoding: 'utf-8', lineEnding: 'lf' }, }); // Cleanup diff --git a/packages/core/src/tools/write-file.ts b/packages/core/src/tools/write-file.ts index 1f1a30cdd..caaa3aaa4 100644 --- a/packages/core/src/tools/write-file.ts +++ b/packages/core/src/tools/write-file.ts @@ -25,7 +25,12 @@ import { ToolConfirmationOutcome, } from './tools.js'; import { ToolErrorType } from './tool-error.js'; -import { FileEncoding, needsUtf8Bom } from '../services/fileSystemService.js'; +import { + FileEncoding, + needsUtf8Bom, + detectLineEnding, +} from '../services/fileSystemService.js'; +import type { LineEnding } from '../services/fileSystemService.js'; import { makeRelative, shortenPath } from '../utils/paths.js'; import { getErrorMessage, isNodeError } from '../utils/errors.js'; import { DEFAULT_DIFF_OPTIONS, getDiffStat } from './diffOptions.js'; @@ -138,9 +143,13 @@ class WriteFileToolInvocation extends BaseToolInvocation< DEFAULT_DIFF_OPTIONS, ); + const approvalMode = this.config.getApprovalMode(); const ideClient = await IdeClient.getInstance(); const ideConfirmation = - this.config.getIdeMode() && ideClient.isDiffingEnabled() + this.config.getIdeMode() && + ideClient.isDiffingEnabled() && + approvalMode !== ApprovalMode.AUTO_EDIT && + approvalMode !== ApprovalMode.YOLO ? ideClient.openDiff(this.params.file_path, this.params.content) : undefined; @@ -177,6 +186,7 @@ class WriteFileToolInvocation extends BaseToolInvocation< let originalContent = ''; let useBOM = false; let detectedEncoding: string | undefined; + let detectedLineEnding: LineEnding | undefined; const dirName = path.dirname(file_path); if (fileExists) { try { @@ -191,6 +201,7 @@ class WriteFileToolInvocation extends BaseToolInvocation< fileInfo.content.codePointAt(0) === 0xfeff; } detectedEncoding = fileInfo._meta?.encoding || 'utf-8'; + detectedLineEnding = detectLineEnding(fileInfo.content); originalContent = fileInfo.content; fileExists = true; // File exists and was read } catch (err) { @@ -239,6 +250,7 @@ class WriteFileToolInvocation extends BaseToolInvocation< _meta: { bom: useBOM, encoding: detectedEncoding, + lineEnding: detectedLineEnding, }, }); diff --git a/packages/core/src/utils/openaiLogger.test.ts b/packages/core/src/utils/openaiLogger.test.ts index 9d3387e4b..4aa545e10 100644 --- a/packages/core/src/utils/openaiLogger.test.ts +++ b/packages/core/src/utils/openaiLogger.test.ts @@ -387,4 +387,86 @@ describe('OpenAILogger', () => { expect(logPath).toContain(specialPath); }); }); + + describe('cwd parameter', () => { + it('should use provided cwd for default log directory instead of process.cwd()', async () => { + const customCwd = path.join(testTempDir, 'project-root'); + await fs.mkdir(customCwd, { recursive: true }); + const logger = new OpenAILogger(undefined, customCwd); + await logger.initialize(); + + const request = { test: 'request' }; + const response = { test: 'response' }; + + const logPath = await logger.logInteraction(request, response); + const expectedDir = path.join(customCwd, 'logs', 'openai'); + createdDirs.push(expectedDir); + + expect(logPath).toContain(expectedDir); + }); + + it('should resolve relative customLogDir against provided cwd', async () => { + const customCwd = path.join(testTempDir, 'project-root-2'); + await fs.mkdir(customCwd, { recursive: true }); + const relativeDir = 'my-logs'; + const logger = new OpenAILogger(relativeDir, customCwd); + await logger.initialize(); + + const request = { test: 'request' }; + const response = { test: 'response' }; + + const logPath = await logger.logInteraction(request, response); + const expectedDir = path.resolve(customCwd, relativeDir); + createdDirs.push(expectedDir); + + expect(logPath).toContain(expectedDir); + }); + + it('should not use cwd when customLogDir is an absolute path', async () => { + const customCwd = path.join(testTempDir, 'project-root-3'); + const absoluteLogDir = path.join(testTempDir, 'absolute-logs'); + const logger = new OpenAILogger(absoluteLogDir, customCwd); + await logger.initialize(); + + const request = { test: 'request' }; + const response = { test: 'response' }; + + const logPath = await logger.logInteraction(request, response); + createdDirs.push(absoluteLogDir); + + expect(logPath).toContain(absoluteLogDir); + expect(logPath).not.toContain(customCwd); + }); + + it('should not use cwd when customLogDir starts with ~', async () => { + const customCwd = path.join(testTempDir, 'project-root-4'); + const logger = new OpenAILogger('~/test-openai-logs', customCwd); + await logger.initialize(); + + const request = { test: 'request' }; + const response = { test: 'response' }; + + const logPath = await logger.logInteraction(request, response); + const expectedDir = path.join(os.homedir(), 'test-openai-logs'); + createdDirs.push(expectedDir); + + expect(logPath).toContain(expectedDir); + expect(logPath).not.toContain(customCwd); + }); + + it('should fall back to process.cwd() when cwd is not provided', async () => { + const relativeDir = 'test-relative-logs'; + const logger = new OpenAILogger(relativeDir); + await logger.initialize(); + + const request = { test: 'request' }; + const response = { test: 'response' }; + + const logPath = await logger.logInteraction(request, response); + const expectedDir = path.resolve(process.cwd(), relativeDir); + createdDirs.push(expectedDir); + + expect(logPath).toContain(expectedDir); + }); + }); }); diff --git a/packages/core/src/utils/openaiLogger.ts b/packages/core/src/utils/openaiLogger.ts index c6a56ee0a..43028de2c 100644 --- a/packages/core/src/utils/openaiLogger.ts +++ b/packages/core/src/utils/openaiLogger.ts @@ -22,8 +22,12 @@ export class OpenAILogger { /** * Creates a new OpenAI logger * @param customLogDir Optional custom log directory path (supports relative paths, absolute paths, and ~ expansion) + * @param cwd Optional working directory for resolving relative paths. Defaults to process.cwd(). + * In ACP mode, process.cwd() may be '/' (filesystem root), so callers should + * pass the project working directory from Config.getWorkingDir(). */ - constructor(customLogDir?: string) { + constructor(customLogDir?: string, cwd?: string) { + const baseCwd = cwd || process.cwd(); if (customLogDir) { // Resolve relative paths to absolute paths // Handle ~ expansion @@ -31,12 +35,12 @@ export class OpenAILogger { if (customLogDir === '~' || customLogDir.startsWith('~/')) { resolvedPath = path.join(os.homedir(), customLogDir.slice(1)); } else if (!path.isAbsolute(customLogDir)) { - // If it's a relative path, resolve it relative to current working directory - resolvedPath = path.resolve(process.cwd(), customLogDir); + // If it's a relative path, resolve it relative to provided working directory + resolvedPath = path.resolve(baseCwd, customLogDir); } this.logDir = path.normalize(resolvedPath); } else { - this.logDir = path.join(process.cwd(), 'logs', 'openai'); + this.logDir = path.join(baseCwd, 'logs', 'openai'); } } diff --git a/packages/core/src/utils/proxyUtils.test.ts b/packages/core/src/utils/proxyUtils.test.ts new file mode 100644 index 000000000..4f971aec5 --- /dev/null +++ b/packages/core/src/utils/proxyUtils.test.ts @@ -0,0 +1,105 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect } from 'vitest'; +import { normalizeProxyUrl } from './proxyUtils.js'; + +describe('normalizeProxyUrl', () => { + it('should return undefined for undefined input', () => { + expect(normalizeProxyUrl(undefined)).toBeUndefined(); + }); + + it('should return undefined for empty string', () => { + expect(normalizeProxyUrl('')).toBeUndefined(); + }); + + it('should return undefined for whitespace-only string', () => { + expect(normalizeProxyUrl(' ')).toBeUndefined(); + }); + + it('should add http:// prefix to proxy URL without protocol', () => { + expect(normalizeProxyUrl('127.0.0.1:7860')).toBe('http://127.0.0.1:7860'); + }); + + it('should add http:// prefix to proxy URL with port only', () => { + expect(normalizeProxyUrl('localhost:8080')).toBe('http://localhost:8080'); + }); + + it('should not modify URL that already has http:// prefix', () => { + expect(normalizeProxyUrl('http://127.0.0.1:7860')).toBe( + 'http://127.0.0.1:7860', + ); + }); + + it('should not modify URL that already has https:// prefix', () => { + expect(normalizeProxyUrl('https://proxy.example.com:443')).toBe( + 'https://proxy.example.com:443', + ); + }); + + it('should handle HTTP:// prefix (case insensitive)', () => { + expect(normalizeProxyUrl('HTTP://127.0.0.1:7860')).toBe( + 'HTTP://127.0.0.1:7860', + ); + }); + + it('should handle HTTPS:// prefix (case insensitive)', () => { + expect(normalizeProxyUrl('HTTPS://proxy.example.com:443')).toBe( + 'HTTPS://proxy.example.com:443', + ); + }); + + it('should handle proxy URL with authentication', () => { + expect(normalizeProxyUrl('user:pass@proxy.example.com:8080')).toBe( + 'http://user:pass@proxy.example.com:8080', + ); + }); + + it('should handle proxy URL with authentication and http:// prefix', () => { + expect(normalizeProxyUrl('http://user:pass@proxy.example.com:8080')).toBe( + 'http://user:pass@proxy.example.com:8080', + ); + }); + + it('should trim whitespace from proxy URL', () => { + expect(normalizeProxyUrl(' 127.0.0.1:7860 ')).toBe( + 'http://127.0.0.1:7860', + ); + }); + + it('should handle IPv6 addresses', () => { + expect(normalizeProxyUrl('[::1]:8080')).toBe('http://[::1]:8080'); + }); + + it('should handle IPv6 addresses with http:// prefix', () => { + expect(normalizeProxyUrl('http://[::1]:8080')).toBe('http://[::1]:8080'); + }); + + // SOCKS proxy tests - should throw error since undici doesn't support SOCKS + it('should throw error for socks:// proxy URL', () => { + expect(() => normalizeProxyUrl('socks://proxy.example.com:1080')).toThrow( + 'SOCKS proxy is not supported', + ); + }); + + it('should throw error for socks4:// proxy URL', () => { + expect(() => normalizeProxyUrl('socks4://proxy.example.com:1080')).toThrow( + 'SOCKS proxy is not supported', + ); + }); + + it('should throw error for socks5:// proxy URL', () => { + expect(() => normalizeProxyUrl('socks5://proxy.example.com:1080')).toThrow( + 'SOCKS proxy is not supported', + ); + }); + + it('should throw error for SOCKS5:// proxy URL (case insensitive)', () => { + expect(() => normalizeProxyUrl('SOCKS5://proxy.example.com:1080')).toThrow( + 'SOCKS proxy is not supported', + ); + }); +}); diff --git a/packages/core/src/utils/proxyUtils.ts b/packages/core/src/utils/proxyUtils.ts new file mode 100644 index 000000000..b989494c5 --- /dev/null +++ b/packages/core/src/utils/proxyUtils.ts @@ -0,0 +1,53 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * Normalizes a proxy URL to ensure it has a valid protocol prefix. + * + * Many proxy tools and environment variables provide proxy addresses without + * a protocol prefix (e.g., "127.0.0.1:7860" instead of "http://127.0.0.1:7860"). + * This function adds the "http://" prefix if missing, since HTTP proxies are + * the most common default. + * + * Note: Only HTTP and HTTPS proxies are supported. SOCKS proxies (socks://, + * socks4://, socks5://) are NOT supported because the underlying undici library + * does not support them. See: https://github.com/nodejs/undici/issues/2224 + * + * @param proxyUrl - The proxy URL to normalize + * @returns The normalized proxy URL with protocol prefix, or undefined if input is undefined/empty + * @throws Error if a SOCKS proxy URL is provided + */ +export function normalizeProxyUrl( + proxyUrl: string | undefined, +): string | undefined { + if (!proxyUrl) { + return undefined; + } + + const trimmed = proxyUrl.trim(); + if (!trimmed) { + return undefined; + } + + // Check if the URL already has a protocol prefix + // Only support http and https protocols (undici limitation) + if (/^https?:\/\//i.test(trimmed)) { + return trimmed; + } + + // Reject SOCKS proxies - undici does not support them + if (/^socks[45]?:\/\//i.test(trimmed)) { + throw new Error( + `SOCKS proxy is not supported. The underlying HTTP client (undici) only supports HTTP and HTTPS proxies. ` + + `Please use an HTTP/HTTPS proxy instead, or set up a SOCKS-to-HTTP proxy converter. ` + + `See: https://github.com/nodejs/undici/issues/2224`, + ); + } + + // Add http:// prefix for proxy URLs without protocol + // HTTP is the default for most proxy configurations + return `http://${trimmed}`; +} diff --git a/packages/core/src/utils/shell-utils.test.ts b/packages/core/src/utils/shell-utils.test.ts index bb77012b2..0cdeaee88 100644 --- a/packages/core/src/utils/shell-utils.test.ts +++ b/packages/core/src/utils/shell-utils.test.ts @@ -55,82 +55,82 @@ afterEach(() => { }); describe('isCommandAllowed', () => { - it('should allow a command if no restrictions are provided', () => { - const result = isCommandAllowed('ls -l', config); + it('should allow a command if no restrictions are provided', async () => { + const result = await isCommandAllowed('ls -l', config); expect(result.allowed).toBe(true); }); - it('should allow a command if it is in the global allowlist', () => { + it('should allow a command if it is in the global allowlist', async () => { config.getCoreTools = () => ['ShellTool(ls)']; - const result = isCommandAllowed('ls -l', config); + const result = await isCommandAllowed('ls -l', config); expect(result.allowed).toBe(true); }); - it('should block a command if it is not in a strict global allowlist', () => { + it('should block a command if it is not in a strict global allowlist', async () => { config.getCoreTools = () => ['ShellTool(ls -l)']; - const result = isCommandAllowed('rm -rf /', config); + const result = await isCommandAllowed('rm -rf /', config); expect(result.allowed).toBe(false); expect(result.reason).toBe( `Command(s) not in the allowed commands list. Disallowed commands: "rm -rf /"`, ); }); - it('should block a command if it is in the blocked list', () => { + it('should block a command if it is in the blocked list', async () => { config.getPermissionsDeny = () => ['ShellTool(rm -rf /)']; - const result = isCommandAllowed('rm -rf /', config); + const result = await isCommandAllowed('rm -rf /', config); expect(result.allowed).toBe(false); expect(result.reason).toBe( `Command 'rm -rf /' is blocked by configuration`, ); }); - it('should prioritize the blocklist over the allowlist', () => { + it('should prioritize the blocklist over the allowlist', async () => { config.getCoreTools = () => ['ShellTool(rm -rf /)']; config.getPermissionsDeny = () => ['ShellTool(rm -rf /)']; - const result = isCommandAllowed('rm -rf /', config); + const result = await isCommandAllowed('rm -rf /', config); expect(result.allowed).toBe(false); expect(result.reason).toBe( `Command 'rm -rf /' is blocked by configuration`, ); }); - it('should allow any command when a wildcard is in coreTools', () => { + it('should allow any command when a wildcard is in coreTools', async () => { config.getCoreTools = () => ['ShellTool']; - const result = isCommandAllowed('any random command', config); + const result = await isCommandAllowed('any random command', config); expect(result.allowed).toBe(true); }); - it('should block any command when a wildcard is in excludeTools', () => { + it('should block any command when a wildcard is in excludeTools', async () => { config.getPermissionsDeny = () => ['run_shell_command']; - const result = isCommandAllowed('any random command', config); + const result = await isCommandAllowed('any random command', config); expect(result.allowed).toBe(false); expect(result.reason).toBe( 'Shell tool is globally disabled in configuration', ); }); - it('should block a command on the blocklist even with a wildcard allow', () => { + it('should block a command on the blocklist even with a wildcard allow', async () => { config.getCoreTools = () => ['ShellTool']; config.getPermissionsDeny = () => ['ShellTool(rm -rf /)']; - const result = isCommandAllowed('rm -rf /', config); + const result = await isCommandAllowed('rm -rf /', config); expect(result.allowed).toBe(false); expect(result.reason).toBe( `Command 'rm -rf /' is blocked by configuration`, ); }); - it('should allow a chained command if all parts are on the global allowlist', () => { + it('should allow a chained command if all parts are on the global allowlist', async () => { config.getCoreTools = () => [ 'run_shell_command(echo)', 'run_shell_command(ls)', ]; - const result = isCommandAllowed('echo "hello" && ls -l', config); + const result = await isCommandAllowed('echo "hello" && ls -l', config); expect(result.allowed).toBe(true); }); - it('should block a chained command if any part is blocked', () => { + it('should block a chained command if any part is blocked', async () => { config.getPermissionsDeny = () => ['run_shell_command(rm)']; - const result = isCommandAllowed('echo "hello" && rm -rf /', config); + const result = await isCommandAllowed('echo "hello" && rm -rf /', config); expect(result.allowed).toBe(false); expect(result.reason).toBe( `Command 'rm -rf /' is blocked by configuration`, @@ -138,20 +138,20 @@ describe('isCommandAllowed', () => { }); describe('command substitution', () => { - it('should block command substitution using `$(...)`', () => { - const result = isCommandAllowed('echo $(rm -rf /)', config); + it('should block command substitution using `$(...)`', async () => { + const result = await isCommandAllowed('echo $(rm -rf /)', config); expect(result.allowed).toBe(false); expect(result.reason).toContain('Command substitution'); }); - it('should block command substitution using `<(...)`', () => { - const result = isCommandAllowed('diff <(ls) <(ls -a)', config); + it('should block command substitution using `<(...)`', async () => { + const result = await isCommandAllowed('diff <(ls) <(ls -a)', config); expect(result.allowed).toBe(false); expect(result.reason).toContain('Command substitution'); }); - it('should block command substitution using `>(...)`', () => { - const result = isCommandAllowed( + it('should block command substitution using `>(...)`', async () => { + const result = await isCommandAllowed( 'echo "Log message" > >(tee log.txt)', config, ); @@ -159,20 +159,20 @@ describe('isCommandAllowed', () => { expect(result.reason).toContain('Command substitution'); }); - it('should block command substitution using backticks', () => { - const result = isCommandAllowed('echo `rm -rf /`', config); + it('should block command substitution using backticks', async () => { + const result = await isCommandAllowed('echo `rm -rf /`', config); expect(result.allowed).toBe(false); expect(result.reason).toContain('Command substitution'); }); - it('should allow substitution-like patterns inside single quotes', () => { + it('should allow substitution-like patterns inside single quotes', async () => { config.getCoreTools = () => ['ShellTool(echo)']; - const result = isCommandAllowed("echo '$(pwd)'", config); + const result = await isCommandAllowed("echo '$(pwd)'", config); expect(result.allowed).toBe(true); }); describe('heredocs', () => { - it('should allow substitution-like content in a quoted heredoc delimiter', () => { + it('should allow substitution-like content in a quoted heredoc delimiter', async () => { const cmd = [ "cat <<'EOF' > user_session.md", '```', @@ -182,55 +182,55 @@ describe('isCommandAllowed', () => { 'EOF', ].join('\n'); - const result = isCommandAllowed(cmd, config); + const result = await isCommandAllowed(cmd, config); expect(result.allowed).toBe(true); }); - it('should block command substitution in an unquoted heredoc body', () => { + it('should block command substitution in an unquoted heredoc body', async () => { const cmd = [ 'cat < user_session.md', "'$(rm -rf /)'", 'EOF', ].join('\n'); - const result = isCommandAllowed(cmd, config); + const result = await isCommandAllowed(cmd, config); expect(result.allowed).toBe(false); expect(result.reason).toContain('Command substitution'); }); - it('should block backtick command substitution in an unquoted heredoc body', () => { + it('should block backtick command substitution in an unquoted heredoc body', async () => { const cmd = ['cat < user_session.md', '`rm -rf /`', 'EOF'].join( '\n', ); - const result = isCommandAllowed(cmd, config); + const result = await isCommandAllowed(cmd, config); expect(result.allowed).toBe(false); expect(result.reason).toContain('Command substitution'); }); - it('should allow escaped command substitution in an unquoted heredoc body', () => { + it('should allow escaped command substitution in an unquoted heredoc body', async () => { const cmd = [ 'cat < user_session.md', '\\$(rm -rf /)', 'EOF', ].join('\n'); - const result = isCommandAllowed(cmd, config); + const result = await isCommandAllowed(cmd, config); expect(result.allowed).toBe(true); }); - it('should support tab-stripping heredocs (<<-)', () => { + it('should support tab-stripping heredocs (<<-)', async () => { const cmd = [ "cat <<-'EOF' > user_session.md", '\t$(rm -rf /)', '\tEOF', ].join('\n'); - const result = isCommandAllowed(cmd, config); + const result = await isCommandAllowed(cmd, config); expect(result.allowed).toBe(true); }); - it('should block command substitution split by line continuation in an unquoted heredoc body', () => { + it('should block command substitution split by line continuation in an unquoted heredoc body', async () => { const cmd = [ 'cat < user_session.md', '$\\', @@ -238,12 +238,12 @@ describe('isCommandAllowed', () => { 'EOF', ].join('\n'); - const result = isCommandAllowed(cmd, config); + const result = await isCommandAllowed(cmd, config); expect(result.allowed).toBe(false); expect(result.reason).toContain('Command substitution'); }); - it('should allow escaped command substitution split by line continuation in an unquoted heredoc body', () => { + it('should allow escaped command substitution split by line continuation in an unquoted heredoc body', async () => { const cmd = [ 'cat < user_session.md', '\\$\\', @@ -251,36 +251,39 @@ describe('isCommandAllowed', () => { 'EOF', ].join('\n'); - const result = isCommandAllowed(cmd, config); + const result = await isCommandAllowed(cmd, config); expect(result.allowed).toBe(true); }); }); describe('comments', () => { - it('should ignore heredoc operators inside comments', () => { + it('should ignore heredoc operators inside comments', async () => { const cmd = ["# Fake heredoc <<'EOF'", '$(rm -rf /)', 'EOF'].join('\n'); - const result = isCommandAllowed(cmd, config); + const result = await isCommandAllowed(cmd, config); expect(result.allowed).toBe(false); expect(result.reason).toContain('Command substitution'); }); - it('should allow command substitution patterns inside full-line comments', () => { + it('should allow command substitution patterns inside full-line comments', async () => { const cmd = ['# Note: $(rm -rf /) is dangerous', 'echo hello'].join( '\n', ); - const result = isCommandAllowed(cmd, config); + const result = await isCommandAllowed(cmd, config); expect(result.allowed).toBe(true); }); - it('should allow command substitution patterns inside inline comments', () => { - const result = isCommandAllowed('echo hello # $(rm -rf /)', config); + it('should allow command substitution patterns inside inline comments', async () => { + const result = await isCommandAllowed( + 'echo hello # $(rm -rf /)', + config, + ); expect(result.allowed).toBe(true); }); - it('should not treat # inside a word as a comment starter', () => { - const result = isCommandAllowed('echo foo#$(rm -rf /)', config); + it('should not treat # inside a word as a comment starter', async () => { + const result = await isCommandAllowed('echo foo#$(rm -rf /)', config); expect(result.allowed).toBe(false); expect(result.reason).toContain('Command substitution'); }); @@ -290,17 +293,17 @@ describe('isCommandAllowed', () => { describe('checkCommandPermissions', () => { describe('in "Default Allow" mode (no sessionAllowlist)', () => { - it('should return a detailed success object for an allowed command', () => { - const result = checkCommandPermissions('ls -l', config); + it('should return a detailed success object for an allowed command', async () => { + const result = await checkCommandPermissions('ls -l', config); expect(result).toEqual({ allAllowed: true, disallowedCommands: [], }); }); - it('should return a detailed failure object for a blocked command', () => { + it('should return a detailed failure object for a blocked command', async () => { config.getPermissionsDeny = () => ['ShellTool(rm)']; - const result = checkCommandPermissions('rm -rf /', config); + const result = await checkCommandPermissions('rm -rf /', config); expect(result).toEqual({ allAllowed: false, disallowedCommands: ['rm -rf /'], @@ -309,9 +312,9 @@ describe('checkCommandPermissions', () => { }); }); - it('should return a detailed failure object for a command not on a strict allowlist', () => { + it('should return a detailed failure object for a command not on a strict allowlist', async () => { config.getCoreTools = () => ['ShellTool(ls)']; - const result = checkCommandPermissions('git status && ls', config); + const result = await checkCommandPermissions('git status && ls', config); expect(result).toEqual({ allAllowed: false, disallowedCommands: ['git status'], @@ -322,8 +325,8 @@ describe('checkCommandPermissions', () => { }); describe('in "Default Deny" mode (with sessionAllowlist)', () => { - it('should allow a command on the sessionAllowlist', () => { - const result = checkCommandPermissions( + it('should allow a command on the sessionAllowlist', async () => { + const result = await checkCommandPermissions( 'ls -l', config, new Set(['ls -l']), @@ -331,8 +334,8 @@ describe('checkCommandPermissions', () => { expect(result.allAllowed).toBe(true); }); - it('should block a command not on the sessionAllowlist or global allowlist', () => { - const result = checkCommandPermissions( + it('should block a command not on the sessionAllowlist or global allowlist', async () => { + const result = await checkCommandPermissions( 'rm -rf /', config, new Set(['ls -l']), @@ -344,9 +347,9 @@ describe('checkCommandPermissions', () => { expect(result.disallowedCommands).toEqual(['rm -rf /']); }); - it('should allow a command on the global allowlist even if not on the session allowlist', () => { + it('should allow a command on the global allowlist even if not on the session allowlist', async () => { config.getCoreTools = () => ['ShellTool(git status)']; - const result = checkCommandPermissions( + const result = await checkCommandPermissions( 'git status', config, new Set(['ls -l']), @@ -354,9 +357,9 @@ describe('checkCommandPermissions', () => { expect(result.allAllowed).toBe(true); }); - it('should allow a chained command if parts are on different allowlists', () => { + it('should allow a chained command if parts are on different allowlists', async () => { config.getCoreTools = () => ['ShellTool(git status)']; - const result = checkCommandPermissions( + const result = await checkCommandPermissions( 'git status && git commit', config, new Set(['git commit']), @@ -364,9 +367,9 @@ describe('checkCommandPermissions', () => { expect(result.allAllowed).toBe(true); }); - it('should block a command on the sessionAllowlist if it is also globally blocked', () => { + it('should block a command on the sessionAllowlist if it is also globally blocked', async () => { config.getPermissionsDeny = () => ['run_shell_command(rm)']; - const result = checkCommandPermissions( + const result = await checkCommandPermissions( 'rm -rf /', config, new Set(['rm -rf /']), @@ -375,9 +378,9 @@ describe('checkCommandPermissions', () => { expect(result.blockReason).toContain('is blocked by configuration'); }); - it('should block a chained command if one part is not on any allowlist', () => { + it('should block a chained command if one part is not on any allowlist', async () => { config.getCoreTools = () => ['run_shell_command(echo)']; - const result = checkCommandPermissions( + const result = await checkCommandPermissions( 'echo "hello" && rm -rf /', config, new Set(['echo']), @@ -389,91 +392,101 @@ describe('checkCommandPermissions', () => { }); describe('getCommandRoots', () => { - it('should return a single command', () => { + it('should return a single command', async () => { expect(getCommandRoots('ls -l')).toEqual(['ls']); }); - it('should handle paths and return the binary name', () => { + it('should handle paths and return the binary name', async () => { expect(getCommandRoots('/usr/local/bin/node script.js')).toEqual(['node']); }); - it('should return an empty array for an empty string', () => { + it('should return an empty array for an empty string', async () => { expect(getCommandRoots('')).toEqual([]); }); - it('should handle a mix of operators', () => { + it('should handle a mix of operators', async () => { const result = getCommandRoots('a;b|c&&d||e&f'); expect(result).toEqual(['a', 'b', 'c', 'd', 'e', 'f']); }); - it('should correctly parse a chained command with quotes', () => { + it('should correctly parse a chained command with quotes', async () => { const result = getCommandRoots('echo "hello" && git commit -m "feat"'); expect(result).toEqual(['echo', 'git']); }); - it('should split on Unix newlines (\\n)', () => { + it('should split on Unix newlines (\\n)', async () => { const result = getCommandRoots('grep pattern file\ncurl evil.com'); expect(result).toEqual(['grep', 'curl']); }); - it('should split on Windows newlines (\\r\\n)', () => { + it('should split on Windows newlines (\\r\\n)', async () => { const result = getCommandRoots('grep pattern file\r\ncurl evil.com'); expect(result).toEqual(['grep', 'curl']); }); - it('should handle mixed newlines and operators', () => { + it('should handle mixed newlines and operators', async () => { const result = getCommandRoots('ls\necho hello && cat file\r\nrm -rf /'); expect(result).toEqual(['ls', 'echo', 'cat', 'rm']); }); - it('should not split on newlines inside quotes', () => { + it('should not split on newlines inside quotes', async () => { const result = getCommandRoots('echo "line1\nline2"'); expect(result).toEqual(['echo']); }); - it('should treat escaped newline as line continuation (not a separator)', () => { + it('should treat escaped newline as line continuation (not a separator)', async () => { const result = getCommandRoots('grep pattern\\\nfile'); expect(result).toEqual(['grep']); }); - it('should filter out empty segments from consecutive newlines', () => { + it('should filter out empty segments from consecutive newlines', async () => { const result = getCommandRoots('ls\n\ngrep foo'); expect(result).toEqual(['ls', 'grep']); }); + + it('should not treat file descriptor redirection as a command separator', async () => { + const result = getCommandRoots('npm run build 2>&1 | head -100'); + expect(result).toEqual(['npm', 'head']); + }); + + it('should not treat >| redirection as a pipeline separator', async () => { + const result = getCommandRoots('echo hello >| out.txt'); + expect(result).toEqual(['echo']); + }); }); describe('stripShellWrapper', () => { - it('should strip sh -c with quotes', () => { + it('should strip sh -c with quotes', async () => { expect(stripShellWrapper('sh -c "ls -l"')).toEqual('ls -l'); }); - it('should strip bash -c with extra whitespace', () => { + it('should strip bash -c with extra whitespace', async () => { expect(stripShellWrapper(' bash -c "ls -l" ')).toEqual('ls -l'); }); - it('should strip zsh -c without quotes', () => { + it('should strip zsh -c without quotes', async () => { expect(stripShellWrapper('zsh -c ls -l')).toEqual('ls -l'); }); - it('should strip cmd.exe /c', () => { + it('should strip cmd.exe /c', async () => { expect(stripShellWrapper('cmd.exe /c "dir"')).toEqual('dir'); }); - it('should not strip anything if no wrapper is present', () => { + it('should not strip anything if no wrapper is present', async () => { expect(stripShellWrapper('ls -l')).toEqual('ls -l'); }); }); describe('escapeShellArg', () => { describe('POSIX (bash)', () => { - it('should use shell-quote for escaping', () => { + it('should use shell-quote for escaping', async () => { mockQuote.mockReturnValueOnce("'escaped value'"); const result = escapeShellArg('raw value', 'bash'); expect(mockQuote).toHaveBeenCalledWith(['raw value']); expect(result).toBe("'escaped value'"); }); - it('should handle empty strings', () => { + it('should handle empty strings', async () => { const result = escapeShellArg('', 'bash'); expect(result).toBe(''); expect(mockQuote).not.toHaveBeenCalled(); @@ -482,39 +495,39 @@ describe('escapeShellArg', () => { describe('Windows', () => { describe('when shell is cmd.exe', () => { - it('should wrap simple arguments in double quotes', () => { + it('should wrap simple arguments in double quotes', async () => { const result = escapeShellArg('search term', 'cmd'); expect(result).toBe('"search term"'); }); - it('should escape internal double quotes by doubling them', () => { + it('should escape internal double quotes by doubling them', async () => { const result = escapeShellArg('He said "Hello"', 'cmd'); expect(result).toBe('"He said ""Hello"""'); }); - it('should handle empty strings', () => { + it('should handle empty strings', async () => { const result = escapeShellArg('', 'cmd'); expect(result).toBe(''); }); }); describe('when shell is PowerShell', () => { - it('should wrap simple arguments in single quotes', () => { + it('should wrap simple arguments in single quotes', async () => { const result = escapeShellArg('search term', 'powershell'); expect(result).toBe("'search term'"); }); - it('should escape internal single quotes by doubling them', () => { + it('should escape internal single quotes by doubling them', async () => { const result = escapeShellArg("It's a test", 'powershell'); expect(result).toBe("'It''s a test'"); }); - it('should handle double quotes without escaping them', () => { + it('should handle double quotes without escaping them', async () => { const result = escapeShellArg('He said "Hello"', 'powershell'); expect(result).toBe('\'He said "Hello"\''); }); - it('should handle empty strings', () => { + it('should handle empty strings', async () => { const result = escapeShellArg('', 'powershell'); expect(result).toBe(''); }); @@ -529,7 +542,7 @@ describe('getShellConfiguration', () => { process.env = originalEnv; }); - it('should return bash configuration on Linux', () => { + it('should return bash configuration on Linux', async () => { mockPlatform.mockReturnValue('linux'); const config = getShellConfiguration(); expect(config.executable).toBe('bash'); @@ -537,7 +550,7 @@ describe('getShellConfiguration', () => { expect(config.shell).toBe('bash'); }); - it('should return bash configuration on macOS (darwin)', () => { + it('should return bash configuration on macOS (darwin)', async () => { mockPlatform.mockReturnValue('darwin'); const config = getShellConfiguration(); expect(config.executable).toBe('bash'); @@ -546,63 +559,161 @@ describe('getShellConfiguration', () => { }); describe('on Windows', () => { + const originalEnv = { ...process.env }; + beforeEach(() => { mockPlatform.mockReturnValue('win32'); }); - it('should return cmd.exe configuration by default', () => { + afterEach(() => { + process.env = originalEnv; + }); + + it('should return cmd.exe configuration by default', async () => { delete process.env['ComSpec']; + delete process.env['MSYSTEM']; + delete process.env['TERM']; const config = getShellConfiguration(); expect(config.executable).toBe('cmd.exe'); expect(config.argsPrefix).toEqual(['/d', '/s', '/c']); expect(config.shell).toBe('cmd'); }); - it('should respect ComSpec for cmd.exe', () => { + it('should respect ComSpec for cmd.exe', async () => { const cmdPath = 'C:\\WINDOWS\\system32\\cmd.exe'; process.env['ComSpec'] = cmdPath; + delete process.env['MSYSTEM']; + delete process.env['TERM']; const config = getShellConfiguration(); expect(config.executable).toBe(cmdPath); expect(config.argsPrefix).toEqual(['/d', '/s', '/c']); expect(config.shell).toBe('cmd'); }); - it('should return PowerShell configuration if ComSpec points to powershell.exe', () => { + it('should return PowerShell configuration if ComSpec points to powershell.exe', async () => { const psPath = 'C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'; process.env['ComSpec'] = psPath; + delete process.env['MSYSTEM']; + delete process.env['TERM']; const config = getShellConfiguration(); expect(config.executable).toBe(psPath); expect(config.argsPrefix).toEqual(['-NoProfile', '-Command']); expect(config.shell).toBe('powershell'); }); - it('should return PowerShell configuration if ComSpec points to pwsh.exe', () => { + it('should return PowerShell configuration if ComSpec points to pwsh.exe', async () => { const pwshPath = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe'; process.env['ComSpec'] = pwshPath; + delete process.env['MSYSTEM']; + delete process.env['TERM']; const config = getShellConfiguration(); expect(config.executable).toBe(pwshPath); expect(config.argsPrefix).toEqual(['-NoProfile', '-Command']); expect(config.shell).toBe('powershell'); }); - it('should be case-insensitive when checking ComSpec', () => { + it('should be case-insensitive when checking ComSpec', async () => { process.env['ComSpec'] = 'C:\\Path\\To\\POWERSHELL.EXE'; + delete process.env['MSYSTEM']; + delete process.env['TERM']; const config = getShellConfiguration(); expect(config.executable).toBe('C:\\Path\\To\\POWERSHELL.EXE'); expect(config.argsPrefix).toEqual(['-NoProfile', '-Command']); expect(config.shell).toBe('powershell'); }); + + describe('Git Bash / MSYS2 / MinTTY detection', () => { + it('should return bash configuration when MSYSTEM starts with MINGW', () => { + process.env['MSYSTEM'] = 'MINGW64'; + const config = getShellConfiguration(); + // executable should be bash.exe path (either 'bash' or full path like 'C:\...\bash.exe') + expect( + config.executable.endsWith('bash.exe') || + config.executable === 'bash', + ).toBe(true); + expect(config.argsPrefix).toEqual(['-c']); + expect(config.shell).toBe('bash'); + }); + + it('should return bash configuration when MSYSTEM starts with MSYS', () => { + process.env['MSYSTEM'] = 'MSYS'; + const config = getShellConfiguration(); + expect( + config.executable.endsWith('bash.exe') || + config.executable === 'bash', + ).toBe(true); + expect(config.argsPrefix).toEqual(['-c']); + expect(config.shell).toBe('bash'); + }); + + it('should return bash configuration when TERM includes msys', () => { + delete process.env['MSYSTEM']; + process.env['TERM'] = 'xterm-256color-msys'; + const config = getShellConfiguration(); + expect( + config.executable.endsWith('bash.exe') || + config.executable === 'bash', + ).toBe(true); + expect(config.argsPrefix).toEqual(['-c']); + expect(config.shell).toBe('bash'); + }); + + it('should return bash configuration when TERM includes cygwin', () => { + delete process.env['MSYSTEM']; + process.env['TERM'] = 'xterm-256color-cygwin'; + const config = getShellConfiguration(); + expect( + config.executable.endsWith('bash.exe') || + config.executable === 'bash', + ).toBe(true); + expect(config.argsPrefix).toEqual(['-c']); + expect(config.shell).toBe('bash'); + }); + + it('should prioritize MSYSTEM over TERM for Git Bash detection', () => { + process.env['MSYSTEM'] = 'MINGW64'; + process.env['TERM'] = 'xterm'; + const config = getShellConfiguration(); + expect( + config.executable.endsWith('bash.exe') || + config.executable === 'bash', + ).toBe(true); + expect(config.argsPrefix).toEqual(['-c']); + expect(config.shell).toBe('bash'); + }); + + it('should return cmd.exe when MSYSTEM and TERM do not indicate Git Bash', () => { + process.env['MSYSTEM'] = 'UNKNOWN'; + process.env['TERM'] = 'xterm'; + delete process.env['ComSpec']; + const config = getShellConfiguration(); + expect(config.executable).toBe('cmd.exe'); + expect(config.argsPrefix).toEqual(['/d', '/s', '/c']); + expect(config.shell).toBe('cmd'); + }); + + it('should return bash when MSYSTEM is MINGW32', () => { + process.env['MSYSTEM'] = 'MINGW32'; + const config = getShellConfiguration(); + expect( + config.executable.endsWith('bash.exe') || + config.executable === 'bash', + ).toBe(true); + expect(config.argsPrefix).toEqual(['-c']); + expect(config.shell).toBe('bash'); + }); + }); }); }); describe('isCommandNeedPermission', () => { - it('returns false for read-only commands', () => { + it('returns false for read-only commands', async () => { const result = isCommandNeedsPermission('ls'); expect(result.requiresPermission).toBe(false); }); - it('returns true for mutating commands with reason', () => { + it('returns true for mutating commands with reason', async () => { const result = isCommandNeedsPermission('rm -rf temp'); expect(result.requiresPermission).toBe(true); expect(result.reason).toContain('requires permission to execute'); @@ -611,13 +722,13 @@ describe('isCommandNeedPermission', () => { describe('checkArgumentSafety', () => { describe('command substitution patterns', () => { - it('should detect $() command substitution', () => { + it('should detect $() command substitution', async () => { const result = checkArgumentSafety('$(whoami)'); expect(result.isSafe).toBe(false); expect(result.dangerousPatterns).toContain('$() command substitution'); }); - it('should detect backtick command substitution', () => { + it('should detect backtick command substitution', async () => { const result = checkArgumentSafety('`whoami`'); expect(result.isSafe).toBe(false); expect(result.dangerousPatterns).toContain( @@ -625,13 +736,13 @@ describe('checkArgumentSafety', () => { ); }); - it('should detect <() process substitution', () => { + it('should detect <() process substitution', async () => { const result = checkArgumentSafety('<(cat file)'); expect(result.isSafe).toBe(false); expect(result.dangerousPatterns).toContain('<() process substitution'); }); - it('should detect >() process substitution', () => { + it('should detect >() process substitution', async () => { const result = checkArgumentSafety('>(tee file)'); expect(result.isSafe).toBe(false); expect(result.dangerousPatterns).toContain('>() process substitution'); @@ -639,25 +750,25 @@ describe('checkArgumentSafety', () => { }); describe('command separators', () => { - it('should detect semicolon separator', () => { + it('should detect semicolon separator', async () => { const result = checkArgumentSafety('arg1; rm -rf /'); expect(result.isSafe).toBe(false); expect(result.dangerousPatterns).toContain('; command separator'); }); - it('should detect pipe', () => { + it('should detect pipe', async () => { const result = checkArgumentSafety('arg1 | cat file'); expect(result.isSafe).toBe(false); expect(result.dangerousPatterns).toContain('| pipe'); }); - it('should detect && operator', () => { + it('should detect && operator', async () => { const result = checkArgumentSafety('arg1 && ls'); expect(result.isSafe).toBe(false); expect(result.dangerousPatterns).toContain('&& AND operator'); }); - it('should detect || operator', () => { + it('should detect || operator', async () => { const result = checkArgumentSafety('arg1 || ls'); expect(result.isSafe).toBe(false); expect(result.dangerousPatterns).toContain('|| OR operator'); @@ -665,7 +776,7 @@ describe('checkArgumentSafety', () => { }); describe('background execution', () => { - it('should detect background operator', () => { + it('should detect background operator', async () => { const result = checkArgumentSafety('arg1 & ls'); expect(result.isSafe).toBe(false); expect(result.dangerousPatterns).toContain('& background operator'); @@ -673,19 +784,19 @@ describe('checkArgumentSafety', () => { }); describe('input/output redirection', () => { - it('should detect output redirection', () => { + it('should detect output redirection', async () => { const result = checkArgumentSafety('arg1 > file'); expect(result.isSafe).toBe(false); expect(result.dangerousPatterns).toContain('> output redirection'); }); - it('should detect input redirection', () => { + it('should detect input redirection', async () => { const result = checkArgumentSafety('arg1 < file'); expect(result.isSafe).toBe(false); expect(result.dangerousPatterns).toContain('< input redirection'); }); - it('should detect append redirection', () => { + it('should detect append redirection', async () => { const result = checkArgumentSafety('arg1 >> file'); expect(result.isSafe).toBe(false); expect(result.dangerousPatterns).toContain('> output redirection'); @@ -693,45 +804,45 @@ describe('checkArgumentSafety', () => { }); describe('safe inputs', () => { - it('should accept simple arguments', () => { + it('should accept simple arguments', async () => { const result = checkArgumentSafety('arg1 arg2'); expect(result.isSafe).toBe(true); expect(result.dangerousPatterns).toHaveLength(0); }); - it('should accept arguments with numbers', () => { + it('should accept arguments with numbers', async () => { const result = checkArgumentSafety('file123.txt'); expect(result.isSafe).toBe(true); }); - it('should accept arguments with hyphens', () => { + it('should accept arguments with hyphens', async () => { const result = checkArgumentSafety('--flag=value'); expect(result.isSafe).toBe(true); }); - it('should accept arguments with underscores', () => { + it('should accept arguments with underscores', async () => { const result = checkArgumentSafety('my_file_name'); expect(result.isSafe).toBe(true); }); - it('should accept arguments with dots', () => { + it('should accept arguments with dots', async () => { const result = checkArgumentSafety('path/to/file.txt'); expect(result.isSafe).toBe(true); }); - it('should accept empty string', () => { + it('should accept empty string', async () => { const result = checkArgumentSafety(''); expect(result.isSafe).toBe(true); }); - it('should accept arguments with spaces (quoted)', () => { + it('should accept arguments with spaces (quoted)', async () => { const result = checkArgumentSafety('hello world'); expect(result.isSafe).toBe(true); }); }); describe('multiple dangerous patterns', () => { - it('should detect multiple dangerous patterns', () => { + it('should detect multiple dangerous patterns', async () => { const result = checkArgumentSafety('$(whoami); rm -rf / &'); expect(result.isSafe).toBe(false); expect(result.dangerousPatterns).toContain('$() command substitution'); diff --git a/packages/core/src/utils/shell-utils.ts b/packages/core/src/utils/shell-utils.ts index 7036936e2..8eeb19eaa 100644 --- a/packages/core/src/utils/shell-utils.ts +++ b/packages/core/src/utils/shell-utils.ts @@ -7,6 +7,7 @@ import type { AnyToolInvocation } from '../index.js'; import type { Config } from '../config/config.js'; import os from 'node:os'; +import path from 'node:path'; import { quote } from 'shell-quote'; import { doesToolInvocationMatch } from './tool-utils.js'; import { isShellCommandReadOnly } from './shellReadOnlyChecker.js'; @@ -38,6 +39,70 @@ export interface ShellConfiguration { shell: ShellType; } +let cachedBashPath: string | undefined; + +/** + * Attempts to find the Git Bash executable path on Windows. + * Checks common installation locations and PATH. + * @returns The path to bash.exe if found, or 'bash' as fallback. + */ +function findGitBashPath(): string { + // Return cached result if available + if (cachedBashPath) { + return cachedBashPath; + } + + // Search in PATH directories + const pathEnv = process.env['PATH'] || ''; + const pathDirs = pathEnv.split(path.delimiter).filter(Boolean); + + for (const dir of pathDirs) { + const bashPath = path.join(dir, 'bash.exe'); + try { + accessSync(bashPath, fsConstants.X_OK); + cachedBashPath = bashPath; + return bashPath; + } catch { + // Continue searching + } + } + + // Check common Git Bash installation locations + const commonPaths = [ + path.join('C:', 'Program Files', 'Git', 'bin', 'bash.exe'), + path.join('C:', 'Program Files', 'Git', 'usr', 'bin', 'bash.exe'), + path.join('C:', 'Program Files (x86)', 'Git', 'bin', 'bash.exe'), + path.join('C:', 'Program Files (x86)', 'Git', 'usr', 'bin', 'bash.exe'), + path.join( + process.env['ProgramFiles'] || path.join('C:', 'Program Files'), + 'Git', + 'bin', + 'bash.exe', + ), + path.join( + process.env['ProgramFiles(x86)'] || + path.join('C:', 'Program Files (x86)'), + 'Git', + 'bin', + 'bash.exe', + ), + ]; + + for (const bashPath of commonPaths) { + try { + accessSync(bashPath, fsConstants.X_OK); + cachedBashPath = bashPath; + return bashPath; + } catch { + // Continue searching + } + } + + // Fallback to 'bash' and let the system handle it + cachedBashPath = 'bash'; + return 'bash'; +} + /** * Determines the appropriate shell configuration for the current platform. * @@ -48,6 +113,24 @@ export interface ShellConfiguration { */ export function getShellConfiguration(): ShellConfiguration { if (isWindows()) { + // Detect Git Bash / MSYS2 / MinTTY environments + // These environments should use bash instead of cmd/PowerShell + const msystem = process.env['MSYSTEM']; + const term = process.env['TERM'] || ''; + const isGitBash = + msystem?.startsWith('MINGW') || + msystem?.startsWith('MSYS') || + term.includes('msys') || + term.includes('cygwin'); + + if (isGitBash) { + return { + executable: findGitBashPath(), + argsPrefix: ['-c'], + shell: 'bash', + }; + } + const comSpec = process.env['ComSpec'] || 'cmd.exe'; const executable = comSpec.toLowerCase(); @@ -126,6 +209,16 @@ export function splitCommands(command: string): string[] { let inDoubleQuotes = false; let i = 0; + const previousNonWhitespaceChar = (index: number): string | undefined => { + for (let j = index - 1; j >= 0; j--) { + const ch = command[j]; + if (ch && !/\s/.test(ch)) { + return ch; + } + } + return undefined; + }; + while (i < command.length) { const char = command[i]; const nextChar = command[i + 1]; @@ -145,14 +238,30 @@ export function splitCommands(command: string): string[] { if (!inSingleQuotes && !inDoubleQuotes) { if ( (char === '&' && nextChar === '&') || - (char === '|' && nextChar === '|') + (char === '|' && (nextChar === '|' || nextChar === '&')) ) { commands.push(currentCommand.trim()); currentCommand = ''; i++; // Skip the next character - } else if (char === ';' || char === '&' || char === '|') { + } else if (char === ';') { commands.push(currentCommand.trim()); currentCommand = ''; + } else if (char === '&') { + const prevChar = previousNonWhitespaceChar(i); + if (prevChar === '>' || prevChar === '<') { + currentCommand += char; + } else { + commands.push(currentCommand.trim()); + currentCommand = ''; + } + } else if (char === '|') { + const prevChar = previousNonWhitespaceChar(i); + if (prevChar === '>') { + currentCommand += char; + } else { + commands.push(currentCommand.trim()); + currentCommand = ''; + } } else if (char === '\r' && nextChar === '\n') { // Windows-style \r\n newline - treat as command separator commands.push(currentCommand.trim()); @@ -626,16 +735,16 @@ export function detectCommandSubstitution(command: string): boolean { * presence activates "Default Deny" mode. * @returns An object detailing which commands are not allowed. */ -export function checkCommandPermissions( +export async function checkCommandPermissions( command: string, config: Config, sessionAllowlist?: Set, -): { +): Promise<{ allAllowed: boolean; disallowedCommands: string[]; blockReason?: string; isHardDenial?: boolean; -} { +}> { // Disallow command substitution for security. if (detectCommandSubstitution(command)) { return { @@ -673,7 +782,7 @@ export function checkCommandPermissions( if (isSessionAllowed) continue; } - const decision = pm.isCommandAllowed(cmd); + const decision = await pm.isCommandAllowed(cmd); if (decision === 'deny') { return { @@ -866,14 +975,18 @@ export function execCommand( reject(error); } else { resolve({ - stdout: stdout ?? '', - stderr: stderr ?? '', + stdout: String(stdout ?? ''), + stderr: String(stderr ?? ''), code: typeof error.code === 'number' ? error.code : 1, }); } return; } - resolve({ stdout: stdout ?? '', stderr: stderr ?? '', code: 0 }); + resolve({ + stdout: String(stdout ?? ''), + stderr: String(stderr ?? ''), + code: 0, + }); }, ); child.on('error', reject); @@ -946,12 +1059,15 @@ export function isCommandAvailable(command: string): { return { available: path !== null, error }; } -export function isCommandAllowed( +export async function isCommandAllowed( command: string, config: Config, -): { allowed: boolean; reason?: string } { +): Promise<{ allowed: boolean; reason?: string }> { // By not providing a sessionAllowlist, we invoke "default allow" behavior. - const { allAllowed, blockReason } = checkCommandPermissions(command, config); + const { allAllowed, blockReason } = await checkCommandPermissions( + command, + config, + ); if (allAllowed) { return { allowed: true }; } diff --git a/packages/core/src/utils/shellAstParser.test.ts b/packages/core/src/utils/shellAstParser.test.ts index 0b0e6abe9..506147e6b 100644 --- a/packages/core/src/utils/shellAstParser.test.ts +++ b/packages/core/src/utils/shellAstParser.test.ts @@ -4,12 +4,14 @@ * SPDX-License-Identifier: Apache-2.0 */ +import path from 'node:path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initParser, isShellCommandReadOnlyAST, extractCommandRules, _resetParser, + _resolveWasmPathForTesting, } from './shellAstParser.js'; beforeAll(async () => { @@ -20,6 +22,44 @@ afterAll(() => { _resetParser(); }); +describe('WASM path resolution', () => { + it('resolves bundled WASM relative to the real CLI path when launched via symlink', () => { + const symlinkedCliPath = path.join('/usr', 'bin', 'qwen'); + const realCliPath = path.join( + '/opt', + 'homebrew', + 'lib', + 'node_modules', + '@qwen-code', + 'qwen-code', + 'dist', + 'cli.js', + ); + + const result = _resolveWasmPathForTesting( + 'tree-sitter.wasm', + symlinkedCliPath, + () => realCliPath, + ); + + expect(result).toBe( + path.join( + '/opt', + 'homebrew', + 'lib', + 'node_modules', + '@qwen-code', + 'qwen-code', + 'dist', + 'vendor', + 'tree-sitter', + 'tree-sitter.wasm', + ), + ); + expect(result).not.toContain(path.join('/usr', 'bin', 'vendor')); + }); +}); + // ========================================================================= // isShellCommandReadOnlyAST — mirror all tests from shellReadOnlyChecker.test.ts // ========================================================================= diff --git a/packages/core/src/utils/shellAstParser.ts b/packages/core/src/utils/shellAstParser.ts index 7b5e5d2b2..0f315b2f9 100644 --- a/packages/core/src/utils/shellAstParser.ts +++ b/packages/core/src/utils/shellAstParser.ts @@ -15,6 +15,7 @@ */ import Parser from 'web-tree-sitter'; +import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -22,8 +23,18 @@ import { fileURLToPath } from 'node:url'; // Constants // --------------------------------------------------------------------------- -const __filename_ = fileURLToPath(import.meta.url); -const __dirname_ = path.dirname(__filename_); +const __filename_ = resolveModuleFilePath(fileURLToPath(import.meta.url)); + +function resolveModuleFilePath(moduleFilePath: string): string { + try { + const resolved = fs.realpathSync(moduleFilePath); + // Guard against test environments where `fs` is mocked and realpathSync + // returns undefined rather than throwing. + return typeof resolved === 'string' ? resolved : moduleFilePath; + } catch { + return moduleFilePath; + } +} /** * Root commands considered read-only by default (no sub-command analysis needed @@ -569,10 +580,24 @@ let initPromise: Promise | null = null; * - Bundle (dist/cli.js): vendor at same level (0 levels) */ function resolveWasmPath(filename: string): string { - const inSrcUtils = __filename_.includes(path.join('src', 'utils')); - const levelsUp = !inSrcUtils ? 0 : __filename_.endsWith('.ts') ? 2 : 3; + return resolveWasmPathForModule(filename, __filename_); +} + +function resolveWasmPathForModule( + filename: string, + moduleFilePath: string, + resolvePath: (moduleFilePath: string) => string = resolveModuleFilePath, +): string { + const resolvedModuleFilePath = resolvePath(moduleFilePath); + const moduleDir = path.dirname(resolvedModuleFilePath); + const inSrcUtils = resolvedModuleFilePath.includes(path.join('src', 'utils')); + const levelsUp = !inSrcUtils + ? 0 + : resolvedModuleFilePath.endsWith('.ts') + ? 2 + : 3; return path.join( - __dirname_, + moduleDir, ...Array(levelsUp).fill('..'), 'vendor', 'tree-sitter', @@ -1084,3 +1109,15 @@ export function _resetParser(): void { bashLanguage = null; initPromise = null; } + +/** + * Internal helper exposed for tests. + * @internal + */ +export function _resolveWasmPathForTesting( + filename: string, + moduleFilePath: string, + resolvePath?: (moduleFilePath: string) => string, +): string { + return resolveWasmPathForModule(filename, moduleFilePath, resolvePath); +} diff --git a/packages/hook_design/hooks_ui/hooks_ui_implement.md b/packages/hook_design/hooks_ui/hooks_ui_implement.md new file mode 100644 index 000000000..03ab6b744 --- /dev/null +++ b/packages/hook_design/hooks_ui/hooks_ui_implement.md @@ -0,0 +1,420 @@ +# Hooks UI 实现方案 + +## 1. 概述 + +本文档描述了 Hooks UI 的重构实现方案,将原有的 `/hooks`、`/enable`、`/disable` 三个命令整合为单一的 `/hooks` 命令,并提供完整的交互式 UI 流程。 + +## 2. 设计目标 + +- **简化命令**: 将 3 个命令 (`/hooks`, `/enable`, `/disable`) 合并为 1 个 (`/hooks`) +- **完整 UI 流程**: 提供列表选择 → 详情查看 → 配置操作的完整交互 +- **清晰的状态展示**: 显示当前 hooks 配置状态和来源(User Settings / Local Settings) +- **友好的提示信息**: 为每种 hook 类型提供详细的使用说明 + +## 3. UI 流程设计 + +### 3.1 主流程 + +``` +用户输入 /hooks + ↓ +显示 Hooks 列表页面 + ↓ +用户选择特定 Hook (Enter) + ↓ +显示 Hook 详情页面 + ↓ +用户操作: Esc 返回 / Enter 确认配置 +``` + +### 3.2 页面结构 + +#### 3.2.1 Hooks 列表页面 + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Hooks │ +│ │ +│ ❯ 1. Stop [当前选择] │ +│ 2. PreToolUse - Matchers │ +│ 3. PostToolUse - Matchers │ +│ 4. Notification │ +│ ... │ +│ │ +│ Enter to select · Esc to cancel │ +└─────────────────────────────────────────────────────────────┘ +``` + +**元素说明**: + +- 列表项显示 Hook 名称 +- 当前选中的 Hook 有特殊标注(如 `❯` 符号) +- 底部显示操作提示 + +#### 3.2.2 Hook 详情页面 - Stop Hook 示例 + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Stop │ +│ │ +│ Exit code 0 - stdout/stderr not shown │ +│ Exit code 2 - show stderr to model and continue conversation│ +│ Other exit codes - show stderr to user only │ +│ │ +│ ❯ 1. [command] echo '{"decision": "block", ...}' User Settings│ +│ 2. [command] echo '{"decision": "block", ...}' Local Settings│ +│ │ +│ Enter to confirm · Esc to go back │ +└─────────────────────────────────────────────────────────────┘ +``` + +**元素说明**: + +- 顶部显示 Hook 名称 +- 中间显示该 Hook 的使用说明(退出码含义等) +- 列表显示已配置的 hooks,包含命令和配置来源 +- 底部显示操作提示 + +#### 3.2.3 Hook 详情页面 - PreToolUse 示例 + +``` +┌─────────────────────────────────────────────────────────────┐ +│ PreToolUse - Matchers │ +│ │ +│ Input to command is JSON of tool call arguments. │ +│ Exit code 0 - stdout/stderr not shown │ +│ Exit code 2 - show stderr to model and block tool call │ +│ Other exit codes - show stderr to user only but continue │ +│ │ +│ No hooks configured for this event. │ +│ │ +│ To add hooks, edit settings.json directly or ask Claude. │ +│ │ +│ Esc to go back │ +└─────────────────────────────────────────────────────────────┘ +``` + +#### 3.2.4 Hook 详情页面 - PostToolUse 示例 + +``` +┌─────────────────────────────────────────────────────────────┐ +│ PostToolUse - Matchers │ +│ │ +│ Input to command is JSON with fields "inputs" (tool call │ +│ arguments) and "response" (tool call response). │ +│ Exit code 0 - stdout shown in transcript mode (ctrl+o) │ +│ Exit code 2 - show stderr to model immediately │ +│ Other exit codes - show stderr to user only │ +│ │ +│ No hooks configured for this event. │ +│ │ +│ To add hooks, edit settings.json directly or ask Claude. │ +│ │ +│ Esc to go back │ +└─────────────────────────────────────────────────────────────┘ +``` + +## 4. 数据结构设计 + +### 4.1 现有类型定义(来自 `packages/core/src/hooks/types.ts`) + +直接使用现有的类型定义: + +```typescript +import { + HookEventName, + HookConfig, + CommandHookConfig, + HooksConfigSource, + HookDefinition, + HookExecutionResult, + HookExecutionPlan, +} from '@qwen-code/core/hooks/types'; +``` + +**关键类型说明**: + +| 类型 | 说明 | +| --------------------- | ------------------------------------------------------------------------------------ | +| `HookEventName` | Hook 事件枚举,包含 `Stop`, `PreToolUse`, `PostToolUse`, `Notification` 等 | +| `HookConfig` | Hook 配置接口,包含 `type`, `command`, `name`, `description`, `timeout`, `source` 等 | +| `HooksConfigSource` | 配置来源枚举:`Project`, `User`, `System`, `Extensions` | +| `HookDefinition` | Hook 定义,包含 `matcher`, `sequential`, `hooks` 数组 | +| `HookExecutionResult` | Hook 执行结果,包含成功/失败状态、输出、错误等 | + +### 4.2 UI 专用类型定义(新增) + +```typescript +// UI 显示用的 Hook 详情 +interface HookUIDetail { + event: HookEventName; + description: string; + exitCodes: { + code: number | string; + description: string; + }[]; + configs: HookConfig[]; +} + +// UI 状态管理 +interface HooksUIState { + currentView: 'list' | 'detail'; + selectedHookIndex: number; + hooks: HookUIDetail[]; +} +``` + +### 4.3 配置来源映射 + +将 `HooksConfigSource` 映射为 UI 显示文本: + +```typescript +const SOURCE_DISPLAY_MAP: Record = { + [HooksConfigSource.Project]: 'Local Settings', + [HooksConfigSource.User]: 'User Settings', + [HooksConfigSource.System]: 'System Settings', + [HooksConfigSource.Extensions]: 'Extensions', +}; +``` + +## 5. 实现方案 + +### 5.1 命令注册 + +```typescript +// 在命令注册处修改 +// 移除: /enable, /disable +// 保留并增强: /hooks + +commands.register('/hooks', { + description: 'Manage hooks configuration', + handler: handleHooksCommand, +}); +``` + +### 5.2 Hooks 列表渲染 + +```typescript +import { + HookEventName, + HookConfig, + HooksConfigSource, +} from '@qwen-code/core/hooks/types'; + +async function renderHooksList(hooks: HookUIDetail[]): Promise { + const items = hooks.map((hook, index) => ({ + label: hook.event, + description: + hook.configs.length > 0 + ? `${hook.configs.length} configured` + : 'Not configured', + selected: index === 0, // 默认选中第一个 + })); + + await renderSelectList({ + title: 'Hooks', + items, + onSelect: (index) => showHookDetail(hooks[index]), + onCancel: () => closeUI(), + }); +} +``` + +### 5.3 Hook 详情渲染 + +```typescript +import { HookConfig, HooksConfigSource } from '@qwen-code/core/hooks/types'; + +const SOURCE_DISPLAY_MAP: Record = { + [HooksConfigSource.Project]: 'Local Settings', + [HooksConfigSource.User]: 'User Settings', + [HooksConfigSource.System]: 'System Settings', + [HooksConfigSource.Extensions]: 'Extensions', +}; + +async function renderHookDetail(hook: HookUIDetail): Promise { + const content = [ + // 标题 + { type: 'title', text: hook.event }, + { type: 'spacer' }, + // 描述 + { type: 'text', text: hook.description }, + { type: 'spacer' }, + // 退出码说明 + ...hook.exitCodes.map((ec) => ({ + type: 'text', + text: `Exit code ${ec.code} - ${ec.description}`, + })), + { type: 'spacer' }, + ]; + + if (hook.configs.length > 0) { + // 显示已配置的 hooks + const configItems = hook.configs.map((config, index) => ({ + label: `[command] ${config.command}`, + description: config.source + ? SOURCE_DISPLAY_MAP[config.source] + : 'Unknown', + selected: index === 0, + })); + + await renderSelectList({ + content, + items: configItems, + onSelect: (index) => handleHookConfigAction(hook.configs[index]), + onCancel: () => renderHooksList(allHooks), + }); + } else { + // 显示空状态 + content.push( + { type: 'text', text: 'No hooks configured for this event.' }, + { type: 'spacer' }, + { + type: 'text', + text: 'To add hooks, edit settings.json directly or ask Claude.', + }, + { type: 'spacer' }, + ); + + await renderMessage({ + content, + onBack: () => renderHooksList(allHooks), + }); + } +} +``` + +### 5.4 Hook 提示信息配置 + +```typescript +import { HookEventName } from '@qwen-code/core/hooks/types'; + +const HOOK_DESCRIPTIONS: Record = { + [HookEventName.Stop]: { + event: HookEventName.Stop, + description: '', + exitCodes: [ + { code: 0, description: 'stdout/stderr not shown' }, + { + code: 2, + description: 'show stderr to model and continue conversation', + }, + { code: 'Other', description: 'show stderr to user only' }, + ], + configs: [], + }, + [HookEventName.PreToolUse]: { + event: HookEventName.PreToolUse, + description: 'Input to command is JSON of tool call arguments.', + exitCodes: [ + { code: 0, description: 'stdout/stderr not shown' }, + { code: 2, description: 'show stderr to model and block tool call' }, + { + code: 'Other', + description: 'show stderr to user only but continue with tool call', + }, + ], + configs: [], + }, + [HookEventName.PostToolUse]: { + event: HookEventName.PostToolUse, + description: + 'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).', + exitCodes: [ + { code: 0, description: 'stdout shown in transcript mode (ctrl+o)' }, + { code: 2, description: 'show stderr to model immediately' }, + { code: 'Other', description: 'show stderr to user only' }, + ], + configs: [], + }, + [HookEventName.Notification]: { + event: HookEventName.Notification, + description: 'Triggered when notifications are sent.', + exitCodes: [{ code: 0, description: 'notification handled' }], + configs: [], + }, +}; +``` + +## 6. 文件修改清单 + +### 6.1 需要修改的文件 + +| 文件路径 | 修改内容 | +| ---------------------------------------------- | ------------------------------------- | +| `packages/cli/src/commands/index.ts` | 移除 `/enable` 和 `/disable` 命令注册 | +| `packages/cli/src/commands/hooks.ts` | 重构为完整的交互式 UI | +| `packages/cli/src/ui/components/HooksList.ts` | 新增:Hooks 列表组件 | +| `packages/cli/src/ui/components/HookDetail.ts` | 新增:Hook 详情组件 | + +### 6.2 需要删除的文件 + +| 文件路径 | 原因 | +| -------------------------------------- | ------------------- | +| `packages/cli/src/commands/enable.ts` | 功能合并到 `/hooks` | +| `packages/cli/src/commands/disable.ts` | 功能合并到 `/hooks` | + +## 7. 实现步骤 + +### Phase 1: 基础结构 (1-2天) + +1. 创建 Hook UI 专用类型定义(`HookUIDetail`, `HooksUIState`) +2. 实现 `HooksList` 组件 +3. 实现 `HookDetail` 组件 + +### Phase 2: 命令整合 (1天) + +1. 重构 `/hooks` 命令处理器 +2. 移除 `/enable` 和 `/disable` 命令 +3. 更新命令注册 + +### Phase 3: 测试与优化 (1天) + +1. 编写单元测试 +2. 集成测试 +3. UI 交互优化 + +## 8. 兼容性考虑 + +- 保持现有的 hooks 配置文件格式不变 +- 保持现有的 hooks 执行逻辑不变 +- 复用 `packages/core/src/hooks/types.ts` 中的类型定义 +- 仅修改 UI 交互层 + +## 9. 后续扩展 + +- 支持在 UI 中直接添加/编辑/删除 hooks +- 支持 hooks 配置的导入/导出 +- 支持 hooks 执行日志查看 + +--- + +## 10. 实现完成状态 + +**Build 状态**: ✅ 成功 + +### 已完成的文件 + +| 文件 | 状态 | +| ---------------------------------------------------------------- | --------- | +| `packages/cli/src/ui/components/hooks/types.ts` | ✅ 已创建 | +| `packages/cli/src/ui/components/hooks/constants.ts` | ✅ 已创建 | +| `packages/cli/src/ui/components/hooks/HooksListStep.tsx` | ✅ 已创建 | +| `packages/cli/src/ui/components/hooks/HookDetailStep.tsx` | ✅ 已创建 | +| `packages/cli/src/ui/components/hooks/HooksManagementDialog.tsx` | ✅ 已创建 | +| `packages/cli/src/ui/components/hooks/index.ts` | ✅ 已创建 | +| `packages/cli/src/ui/hooks/useHooksDialog.ts` | ✅ 已创建 | +| `packages/cli/src/ui/commands/hooksCommand.ts` | ✅ 已修改 | +| `packages/cli/src/ui/commands/types.ts` | ✅ 已修改 | +| `packages/cli/src/ui/contexts/UIStateContext.tsx` | ✅ 已修改 | +| `packages/cli/src/ui/contexts/UIActionsContext.tsx` | ✅ 已修改 | +| `packages/cli/src/ui/hooks/slashCommandProcessor.ts` | ✅ 已修改 | +| `packages/cli/src/ui/AppContainer.tsx` | ✅ 已修改 | +| `packages/cli/src/ui/components/DialogManager.tsx` | ✅ 已修改 | +| `packages/cli/src/commands/hooks.tsx` | ✅ 已简化 | +| `packages/cli/src/commands/hooks/enable.ts` | ✅ 已删除 | +| `packages/cli/src/commands/hooks/disable.ts` | ✅ 已删除 | + +### 使用方式 + +在交互模式下输入 `/hooks` 即可打开 Hooks 管理界面。 diff --git a/packages/sdk-typescript/README.md b/packages/sdk-typescript/README.md index 96e5db072..8d31ce396 100644 --- a/packages/sdk-typescript/README.md +++ b/packages/sdk-typescript/README.md @@ -65,15 +65,18 @@ Creates a new query session with the Qwen Code. | `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | | `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | | `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. A turn consists of a user message and an assistant response. | -| `coreTools` | `string[]` | - | Equivalent to `tool.core` in settings.json. If specified, only these tools will be available to the AI. Example: `['read_file', 'write_file', 'run_terminal_cmd']`. | -| `excludeTools` | `string[]` | - | Equivalent to `tool.exclude` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports pattern matching: tool name (`'write_file'`), tool class (`'ShellTool'`), or shell command prefix (`'ShellTool(rm )'`). | -| `allowedTools` | `string[]` | - | Equivalent to `tool.allowed` in settings.json. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Supports same pattern matching as `excludeTools`. | +| `coreTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json as an allowlist. If specified, only these tools will be available to the AI (all other tools are disabled at registry level). Supports tool name aliases and pattern matching. Example: `['Read', 'Edit', 'Bash(git *)']`. | +| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | +| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Supports same pattern matching as `excludeTools`. Example: `['ShellTool(git status)', 'ShellTool(npm test)']`. | | `authType` | `'openai' \| 'qwen-oauth'` | `'openai'` | Authentication type for the AI service. Using `'qwen-oauth'` in SDK is not recommended as credentials are stored in `~/.qwen` and may need periodic refresh. | | `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | | `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | | `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | | `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | +> [!tip] +> If you need to configure `coreTools`, `excludeTools`, or `allowedTools`, it is **strongly recommended** to read the [permissions configuration documentation](../docs/users/configuration/settings.md#permissions) first, especially the **Tool name aliases** and **Rule syntax examples** sections, to understand the available aliases and pattern matching syntax (e.g., `Bash(git *)`, `Read(.env)`, `Edit(/src/**)`). + ### Timeouts The SDK enforces the following default timeouts: @@ -157,12 +160,17 @@ The SDK supports different permission modes for controlling tool execution: ### Permission Priority Chain -1. `excludeTools` - Blocks tools completely -2. `permissionMode: 'plan'` - Blocks non-read-only tools -3. `permissionMode: 'yolo'` - Auto-approves all tools -4. `allowedTools` - Auto-approves matching tools -5. `canUseTool` callback - Custom approval logic -6. Default behavior - Auto-deny in SDK mode +Decision priority (highest first): `deny` > `ask` > `allow` > _(default/interactive mode)_ + +The first matching rule wins. + +1. `excludeTools` / `permissions.deny` - Blocks tools completely (returns permission error) +2. `permissions.ask` - Always requires user confirmation +3. `permissionMode: 'plan'` - Blocks all non-read-only tools +4. `permissionMode: 'yolo'` - Auto-approves all tools +5. `allowedTools` / `permissions.allow` - Auto-approves matching tools +6. `canUseTool` callback - Custom approval logic (if provided, not called for allowed tools) +7. Default behavior - Auto-deny in SDK mode (write tools require explicit approval) ## Examples diff --git a/packages/sdk-typescript/package.json b/packages/sdk-typescript/package.json index 6215f6a09..21ab24bf2 100644 --- a/packages/sdk-typescript/package.json +++ b/packages/sdk-typescript/package.json @@ -1,6 +1,6 @@ { "name": "@qwen-code/sdk", - "version": "0.1.4", + "version": "0.1.6", "description": "TypeScript SDK for programmatic access to qwen-code CLI", "main": "./dist/index.cjs", "module": "./dist/index.mjs", diff --git a/packages/test-utils/package.json b/packages/test-utils/package.json index d4d5c1d85..5def9b873 100644 --- a/packages/test-utils/package.json +++ b/packages/test-utils/package.json @@ -1,6 +1,6 @@ { "name": "@qwen-code/qwen-code-test-utils", - "version": "0.13.0", + "version": "0.13.2", "private": true, "main": "src/index.ts", "license": "Apache-2.0", diff --git a/packages/vscode-ide-companion/package.json b/packages/vscode-ide-companion/package.json index a7c18ab4b..da87407eb 100644 --- a/packages/vscode-ide-companion/package.json +++ b/packages/vscode-ide-companion/package.json @@ -2,7 +2,7 @@ "name": "qwen-code-vscode-ide-companion", "displayName": "Qwen Code Companion", "description": "Enable Qwen Code with direct access to your VS Code workspace.", - "version": "0.13.0", + "version": "0.13.2", "publisher": "qwenlm", "icon": "assets/icon.png", "repository": { @@ -49,7 +49,7 @@ "id": "qwen-code-sidebar", "title": "Qwen Code", "icon": "assets/sidebar-icon.svg", - "when": "qwen-code:doesNotSupportSecondarySidebar" + "when": "!qwen-code:supportsSecondarySidebar" } ], "secondarySidebar": [ @@ -57,7 +57,7 @@ "id": "qwen-code-secondary", "title": "Qwen Code", "icon": "assets/sidebar-icon.svg", - "when": "!qwen-code:doesNotSupportSecondarySidebar" + "when": "qwen-code:supportsSecondarySidebar" } ] }, @@ -68,7 +68,7 @@ "id": "qwen-code.chatView.sidebar", "name": "Qwen Code", "icon": "assets/sidebar-icon.svg", - "when": "qwen-code:doesNotSupportSecondarySidebar" + "when": "!qwen-code:supportsSecondarySidebar" } ], "qwen-code-secondary": [ @@ -77,7 +77,7 @@ "id": "qwen-code.chatView.secondary", "name": "Qwen Code", "icon": "assets/sidebar-icon.svg", - "when": "!qwen-code:doesNotSupportSecondarySidebar" + "when": "qwen-code:supportsSecondarySidebar" } ] }, diff --git a/packages/vscode-ide-companion/schemas/settings.schema.json b/packages/vscode-ide-companion/schemas/settings.schema.json index 8e5725ae0..c7f53048e 100644 --- a/packages/vscode-ide-companion/schemas/settings.schema.json +++ b/packages/vscode-ide-companion/schemas/settings.schema.json @@ -796,70 +796,650 @@ "description": "Hooks that execute when notifications are sent.", "type": "array", "items": { - "type": "string" + "description": "A hook definition with an optional matcher and a list of hook configurations.", + "type": "object", + "properties": { + "matcher": { + "description": "An optional matcher pattern to filter when this hook definition applies.", + "type": "string" + }, + "sequential": { + "description": "Whether the hooks should be executed sequentially instead of in parallel.", + "type": "boolean" + }, + "hooks": { + "description": "The list of hook configurations to execute.", + "type": "array", + "items": { + "description": "A hook configuration entry that defines a command to execute.", + "type": "object", + "properties": { + "type": { + "description": "The type of hook.", + "type": "string", + "enum": [ + "command" + ] + }, + "command": { + "description": "The command to execute when the hook is triggered.", + "type": "string" + }, + "name": { + "description": "An optional name for the hook.", + "type": "string" + }, + "description": { + "description": "An optional description of what the hook does.", + "type": "string" + }, + "timeout": { + "description": "Timeout in milliseconds for the hook execution.", + "type": "number" + }, + "env": { + "description": "Environment variables to set when executing the hook command.", + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "type", + "command" + ] + } + } + }, + "required": [ + "hooks" + ] } }, "PreToolUse": { "description": "Hooks that execute before tool execution.", "type": "array", "items": { - "type": "string" + "description": "A hook definition with an optional matcher and a list of hook configurations.", + "type": "object", + "properties": { + "matcher": { + "description": "An optional matcher pattern to filter when this hook definition applies.", + "type": "string" + }, + "sequential": { + "description": "Whether the hooks should be executed sequentially instead of in parallel.", + "type": "boolean" + }, + "hooks": { + "description": "The list of hook configurations to execute.", + "type": "array", + "items": { + "description": "A hook configuration entry that defines a command to execute.", + "type": "object", + "properties": { + "type": { + "description": "The type of hook.", + "type": "string", + "enum": [ + "command" + ] + }, + "command": { + "description": "The command to execute when the hook is triggered.", + "type": "string" + }, + "name": { + "description": "An optional name for the hook.", + "type": "string" + }, + "description": { + "description": "An optional description of what the hook does.", + "type": "string" + }, + "timeout": { + "description": "Timeout in milliseconds for the hook execution.", + "type": "number" + }, + "env": { + "description": "Environment variables to set when executing the hook command.", + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "type", + "command" + ] + } + } + }, + "required": [ + "hooks" + ] } }, "PostToolUse": { "description": "Hooks that execute after successful tool execution.", "type": "array", "items": { - "type": "string" + "description": "A hook definition with an optional matcher and a list of hook configurations.", + "type": "object", + "properties": { + "matcher": { + "description": "An optional matcher pattern to filter when this hook definition applies.", + "type": "string" + }, + "sequential": { + "description": "Whether the hooks should be executed sequentially instead of in parallel.", + "type": "boolean" + }, + "hooks": { + "description": "The list of hook configurations to execute.", + "type": "array", + "items": { + "description": "A hook configuration entry that defines a command to execute.", + "type": "object", + "properties": { + "type": { + "description": "The type of hook.", + "type": "string", + "enum": [ + "command" + ] + }, + "command": { + "description": "The command to execute when the hook is triggered.", + "type": "string" + }, + "name": { + "description": "An optional name for the hook.", + "type": "string" + }, + "description": { + "description": "An optional description of what the hook does.", + "type": "string" + }, + "timeout": { + "description": "Timeout in milliseconds for the hook execution.", + "type": "number" + }, + "env": { + "description": "Environment variables to set when executing the hook command.", + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "type", + "command" + ] + } + } + }, + "required": [ + "hooks" + ] } }, "PostToolUseFailure": { "description": "Hooks that execute when tool execution fails. ", "type": "array", "items": { - "type": "string" + "description": "A hook definition with an optional matcher and a list of hook configurations.", + "type": "object", + "properties": { + "matcher": { + "description": "An optional matcher pattern to filter when this hook definition applies.", + "type": "string" + }, + "sequential": { + "description": "Whether the hooks should be executed sequentially instead of in parallel.", + "type": "boolean" + }, + "hooks": { + "description": "The list of hook configurations to execute.", + "type": "array", + "items": { + "description": "A hook configuration entry that defines a command to execute.", + "type": "object", + "properties": { + "type": { + "description": "The type of hook.", + "type": "string", + "enum": [ + "command" + ] + }, + "command": { + "description": "The command to execute when the hook is triggered.", + "type": "string" + }, + "name": { + "description": "An optional name for the hook.", + "type": "string" + }, + "description": { + "description": "An optional description of what the hook does.", + "type": "string" + }, + "timeout": { + "description": "Timeout in milliseconds for the hook execution.", + "type": "number" + }, + "env": { + "description": "Environment variables to set when executing the hook command.", + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "type", + "command" + ] + } + } + }, + "required": [ + "hooks" + ] } }, "SessionStart": { "description": "Hooks that execute when a new session starts or resumes.", "type": "array", "items": { - "type": "string" + "description": "A hook definition with an optional matcher and a list of hook configurations.", + "type": "object", + "properties": { + "matcher": { + "description": "An optional matcher pattern to filter when this hook definition applies.", + "type": "string" + }, + "sequential": { + "description": "Whether the hooks should be executed sequentially instead of in parallel.", + "type": "boolean" + }, + "hooks": { + "description": "The list of hook configurations to execute.", + "type": "array", + "items": { + "description": "A hook configuration entry that defines a command to execute.", + "type": "object", + "properties": { + "type": { + "description": "The type of hook.", + "type": "string", + "enum": [ + "command" + ] + }, + "command": { + "description": "The command to execute when the hook is triggered.", + "type": "string" + }, + "name": { + "description": "An optional name for the hook.", + "type": "string" + }, + "description": { + "description": "An optional description of what the hook does.", + "type": "string" + }, + "timeout": { + "description": "Timeout in milliseconds for the hook execution.", + "type": "number" + }, + "env": { + "description": "Environment variables to set when executing the hook command.", + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "type", + "command" + ] + } + } + }, + "required": [ + "hooks" + ] } }, "SessionEnd": { "description": "Hooks that execute when a session ends.", "type": "array", "items": { - "type": "string" + "description": "A hook definition with an optional matcher and a list of hook configurations.", + "type": "object", + "properties": { + "matcher": { + "description": "An optional matcher pattern to filter when this hook definition applies.", + "type": "string" + }, + "sequential": { + "description": "Whether the hooks should be executed sequentially instead of in parallel.", + "type": "boolean" + }, + "hooks": { + "description": "The list of hook configurations to execute.", + "type": "array", + "items": { + "description": "A hook configuration entry that defines a command to execute.", + "type": "object", + "properties": { + "type": { + "description": "The type of hook.", + "type": "string", + "enum": [ + "command" + ] + }, + "command": { + "description": "The command to execute when the hook is triggered.", + "type": "string" + }, + "name": { + "description": "An optional name for the hook.", + "type": "string" + }, + "description": { + "description": "An optional description of what the hook does.", + "type": "string" + }, + "timeout": { + "description": "Timeout in milliseconds for the hook execution.", + "type": "number" + }, + "env": { + "description": "Environment variables to set when executing the hook command.", + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "type", + "command" + ] + } + } + }, + "required": [ + "hooks" + ] } }, "PreCompact": { "description": "Hooks that execute before conversation compaction.", "type": "array", "items": { - "type": "string" + "description": "A hook definition with an optional matcher and a list of hook configurations.", + "type": "object", + "properties": { + "matcher": { + "description": "An optional matcher pattern to filter when this hook definition applies.", + "type": "string" + }, + "sequential": { + "description": "Whether the hooks should be executed sequentially instead of in parallel.", + "type": "boolean" + }, + "hooks": { + "description": "The list of hook configurations to execute.", + "type": "array", + "items": { + "description": "A hook configuration entry that defines a command to execute.", + "type": "object", + "properties": { + "type": { + "description": "The type of hook.", + "type": "string", + "enum": [ + "command" + ] + }, + "command": { + "description": "The command to execute when the hook is triggered.", + "type": "string" + }, + "name": { + "description": "An optional name for the hook.", + "type": "string" + }, + "description": { + "description": "An optional description of what the hook does.", + "type": "string" + }, + "timeout": { + "description": "Timeout in milliseconds for the hook execution.", + "type": "number" + }, + "env": { + "description": "Environment variables to set when executing the hook command.", + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "type", + "command" + ] + } + } + }, + "required": [ + "hooks" + ] } }, "SubagentStart": { "description": "Hooks that execute when a subagent (Task tool call) is started.", "type": "array", "items": { - "type": "string" + "description": "A hook definition with an optional matcher and a list of hook configurations.", + "type": "object", + "properties": { + "matcher": { + "description": "An optional matcher pattern to filter when this hook definition applies.", + "type": "string" + }, + "sequential": { + "description": "Whether the hooks should be executed sequentially instead of in parallel.", + "type": "boolean" + }, + "hooks": { + "description": "The list of hook configurations to execute.", + "type": "array", + "items": { + "description": "A hook configuration entry that defines a command to execute.", + "type": "object", + "properties": { + "type": { + "description": "The type of hook.", + "type": "string", + "enum": [ + "command" + ] + }, + "command": { + "description": "The command to execute when the hook is triggered.", + "type": "string" + }, + "name": { + "description": "An optional name for the hook.", + "type": "string" + }, + "description": { + "description": "An optional description of what the hook does.", + "type": "string" + }, + "timeout": { + "description": "Timeout in milliseconds for the hook execution.", + "type": "number" + }, + "env": { + "description": "Environment variables to set when executing the hook command.", + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "type", + "command" + ] + } + } + }, + "required": [ + "hooks" + ] } }, "SubagentStop": { "description": "Hooks that execute right before a subagent (Task tool call) concludes its response.", "type": "array", "items": { - "type": "string" + "description": "A hook definition with an optional matcher and a list of hook configurations.", + "type": "object", + "properties": { + "matcher": { + "description": "An optional matcher pattern to filter when this hook definition applies.", + "type": "string" + }, + "sequential": { + "description": "Whether the hooks should be executed sequentially instead of in parallel.", + "type": "boolean" + }, + "hooks": { + "description": "The list of hook configurations to execute.", + "type": "array", + "items": { + "description": "A hook configuration entry that defines a command to execute.", + "type": "object", + "properties": { + "type": { + "description": "The type of hook.", + "type": "string", + "enum": [ + "command" + ] + }, + "command": { + "description": "The command to execute when the hook is triggered.", + "type": "string" + }, + "name": { + "description": "An optional name for the hook.", + "type": "string" + }, + "description": { + "description": "An optional description of what the hook does.", + "type": "string" + }, + "timeout": { + "description": "Timeout in milliseconds for the hook execution.", + "type": "number" + }, + "env": { + "description": "Environment variables to set when executing the hook command.", + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "type", + "command" + ] + } + } + }, + "required": [ + "hooks" + ] } }, "PermissionRequest": { "description": "Hooks that execute when a permission dialog is displayed.", "type": "array", "items": { - "type": "string" + "description": "A hook definition with an optional matcher and a list of hook configurations.", + "type": "object", + "properties": { + "matcher": { + "description": "An optional matcher pattern to filter when this hook definition applies.", + "type": "string" + }, + "sequential": { + "description": "Whether the hooks should be executed sequentially instead of in parallel.", + "type": "boolean" + }, + "hooks": { + "description": "The list of hook configurations to execute.", + "type": "array", + "items": { + "description": "A hook configuration entry that defines a command to execute.", + "type": "object", + "properties": { + "type": { + "description": "The type of hook.", + "type": "string", + "enum": [ + "command" + ] + }, + "command": { + "description": "The command to execute when the hook is triggered.", + "type": "string" + }, + "name": { + "description": "An optional name for the hook.", + "type": "string" + }, + "description": { + "description": "An optional description of what the hook does.", + "type": "string" + }, + "timeout": { + "description": "Timeout in milliseconds for the hook execution.", + "type": "number" + }, + "env": { + "description": "Environment variables to set when executing the hook command.", + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "type", + "command" + ] + } + } + }, + "required": [ + "hooks" + ] } } } diff --git a/packages/vscode-ide-companion/src/constants/viewIds.ts b/packages/vscode-ide-companion/src/constants/viewIds.ts index b54c6eaa1..8a18cc671 100644 --- a/packages/vscode-ide-companion/src/constants/viewIds.ts +++ b/packages/vscode-ide-companion/src/constants/viewIds.ts @@ -9,7 +9,7 @@ * These IDs must match the `views` contributions declared in package.json. * * Only one of sidebar / secondary is visible at runtime — controlled by the - * `qwen-code:doesNotSupportSecondarySidebar` context key in package.json. + * `qwen-code:supportsSecondarySidebar` context key in package.json. * The secondary sidebar is preferred; the primary sidebar is a fallback for * VS Code versions that lack secondary sidebar support. */ diff --git a/packages/vscode-ide-companion/src/services/acpConnection.ts b/packages/vscode-ide-companion/src/services/acpConnection.ts index 95f50c373..deb04f24c 100644 --- a/packages/vscode-ide-companion/src/services/acpConnection.ts +++ b/packages/vscode-ide-companion/src/services/acpConnection.ts @@ -132,9 +132,16 @@ export class AcpConnection { private async setupChildProcessHandlers(): Promise { let spawnError: Error | null = null; + const stderrChunks: string[] = []; + + let rejectOnExit: ((error: Error) => void) | null = null; + const processExitPromise = new Promise((_resolve, reject) => { + rejectOnExit = reject; + }); this.child!.stderr?.on('data', (data: Buffer) => { const message = data.toString(); + stderrChunks.push(message); if ( message.toLowerCase().includes('error') && !message.includes('Loaded cached') @@ -155,6 +162,17 @@ export class AcpConnection { ); this.lastExitCode = code; this.lastExitSignal = signal; + + const stderrOutput = stderrChunks.join('').trim(); + const stderrSuffix = stderrOutput + ? `\nCLI stderr: ${stderrOutput.slice(-500)}` + : ''; + rejectOnExit?.( + new Error( + `Qwen ACP process exited unexpectedly (exit code: ${code}, signal: ${signal})${stderrSuffix}`, + ), + ); + if (this.child) { this.sdkConnection = null; this.sessionId = null; @@ -172,8 +190,12 @@ export class AcpConnection { if (!this.child || this.child.killed) { const code = this.lastExitCode ?? this.child?.exitCode ?? null; const signal = this.lastExitSignal; + const stderrOutput = stderrChunks.join('').trim(); + const stderrSuffix = stderrOutput + ? `\nCLI stderr: ${stderrOutput.slice(-500)}` + : ''; throw new Error( - `Qwen ACP process failed to start (exit code: ${code}, signal: ${signal})`, + `Qwen ACP process failed to start (exit code: ${code}, signal: ${signal})${stderrSuffix}`, ); } @@ -330,17 +352,21 @@ export class AcpConnection { stream, ); - // Initialize protocol via SDK + // Race the SDK initialize against process exit so we don't hang forever + // if the CLI crashes before responding. console.log('[ACP] Sending initialize request...'); - const initResponse = await this.sdkConnection.initialize({ - protocolVersion: PROTOCOL_VERSION, - clientCapabilities: { - fs: { - readTextFile: true, - writeTextFile: true, + const initResponse = await Promise.race([ + this.sdkConnection.initialize({ + protocolVersion: PROTOCOL_VERSION, + clientCapabilities: { + fs: { + readTextFile: true, + writeTextFile: true, + }, }, - }, - }); + }), + processExitPromise, + ]); console.log('[ACP] Initialize successful'); console.log('[ACP] Initialization response:', initResponse); diff --git a/packages/vscode-ide-companion/src/services/qwenAgentManager.test.ts b/packages/vscode-ide-companion/src/services/qwenAgentManager.test.ts index 440dc2b18..8df67c51e 100644 --- a/packages/vscode-ide-companion/src/services/qwenAgentManager.test.ts +++ b/packages/vscode-ide-companion/src/services/qwenAgentManager.test.ts @@ -5,7 +5,11 @@ */ import { describe, expect, it, vi } from 'vitest'; -import { extractSessionListItems } from './qwenAgentManager.js'; +import { + extractSessionListItems, + QwenAgentManager, +} from './qwenAgentManager.js'; +import type { ModelInfo } from '@agentclientprotocol/sdk'; vi.mock('vscode', () => ({ window: { @@ -54,3 +58,48 @@ describe('extractSessionListItems', () => { expect(extractSessionListItems({})).toEqual([]); }); }); + +describe('QwenAgentManager.setModelFromUi', () => { + it('emits the selected model metadata from the available models list', async () => { + const manager = new QwenAgentManager(); + const onModelChanged = vi.fn(); + manager.onModelChanged(onModelChanged); + + const selectedModel: ModelInfo = { + modelId: 'qwen3-coder-plus', + name: 'Qwen3 Coder Plus', + _meta: { + contextLimit: 262144, + }, + }; + + ( + manager as unknown as { + baselineAvailableModels: ModelInfo[]; + } + ).baselineAvailableModels = [ + { + modelId: 'qwen3-coder-base', + name: 'Qwen3 Coder Base', + _meta: { + contextLimit: 131072, + }, + }, + selectedModel, + ]; + + ( + manager as unknown as { + connection: { + setModel: (modelId: string) => Promise<{ modelId: string }>; + }; + } + ).connection = { + setModel: vi.fn().mockResolvedValue({ modelId: selectedModel.modelId }), + }; + + await manager.setModelFromUi(selectedModel.modelId); + + expect(onModelChanged).toHaveBeenCalledWith(selectedModel); + }); +}); diff --git a/packages/vscode-ide-companion/src/services/qwenAgentManager.ts b/packages/vscode-ide-companion/src/services/qwenAgentManager.ts index 31da317df..883a226ee 100644 --- a/packages/vscode-ide-companion/src/services/qwenAgentManager.ts +++ b/packages/vscode-ide-companion/src/services/qwenAgentManager.ts @@ -382,10 +382,13 @@ export class QwenAgentManager { try { await this.connection.setModel(modelId); const confirmedModelId = modelId; - const modelInfo: ModelInfo = { + const modelInfo = this.baselineAvailableModels.find( + (model) => model.modelId === confirmedModelId, + ) ?? { modelId: confirmedModelId, name: confirmedModelId, }; + this.baselineModelInfo = modelInfo; this.callbacks.onModelChanged?.(modelInfo); return modelInfo; } catch (err) { diff --git a/packages/vscode-ide-companion/src/webview/App.tsx b/packages/vscode-ide-companion/src/webview/App.tsx index 0a76ab5b8..ebdc61350 100644 --- a/packages/vscode-ide-companion/src/webview/App.tsx +++ b/packages/vscode-ide-companion/src/webview/App.tsx @@ -481,10 +481,18 @@ export const App: React.FC = () => { // Set loading state to false after initial mount and when we have authentication info useEffect(() => { - // If we have determined authentication status, we're done loading if (isAuthenticated !== null) { setIsLoading(false); + return; } + + // Safety-net timeout: if initialization takes too long (e.g. CLI crashed + // before the error could be surfaced), stop the spinner and let the user + // see the onboarding / error UI instead of hanging forever. + const timeout = setTimeout(() => { + setIsLoading(false); + }, 30_000); + return () => clearTimeout(timeout); }, [isAuthenticated]); // Handle permission response diff --git a/packages/vscode-ide-companion/src/webview/providers/WebViewProvider.ts b/packages/vscode-ide-companion/src/webview/providers/WebViewProvider.ts index e5e69e66a..182025917 100644 --- a/packages/vscode-ide-companion/src/webview/providers/WebViewProvider.ts +++ b/packages/vscode-ide-companion/src/webview/providers/WebViewProvider.ts @@ -256,25 +256,6 @@ export class WebViewProvider { this.agentManager.onPermissionRequest( async (request: RequestPermissionRequest) => { - // Auto-approve in auto/yolo mode (no UI, no diff) - if (this.isAutoMode()) { - const options = request.options || []; - const pick = (substr: string) => - options.find((o) => - (o.optionId || '').toLowerCase().includes(substr), - )?.optionId; - const pickByKind = (k: string) => - options.find((o) => (o.kind || '').toLowerCase().includes(k)) - ?.optionId; - const optionId = - pick('allow_once') || - pickByKind('allow') || - pick('proceed') || - options[0]?.optionId || - 'allow_once'; - return optionId; - } - // Send permission request to WebView this.sendMessageToWebView({ type: 'permissionRequest', diff --git a/packages/vscode-ide-companion/src/webview/providers/chatViewRegistration.test.ts b/packages/vscode-ide-companion/src/webview/providers/chatViewRegistration.test.ts index dcfa74f00..428f77c11 100644 --- a/packages/vscode-ide-companion/src/webview/providers/chatViewRegistration.test.ts +++ b/packages/vscode-ide-companion/src/webview/providers/chatViewRegistration.test.ts @@ -71,11 +71,15 @@ describe('registerChatViewProviders', () => { expect(calls[0]?.[2]).toEqual({ webviewOptions: { retainContextWhenHidden: true }, }); - expect(executeCommand).not.toHaveBeenCalled(); + expect(executeCommand).toHaveBeenCalledWith( + 'setContext', + 'qwen-code:supportsSecondarySidebar', + true, + ); expect(context.subscriptions).toHaveLength(2); }); - it('sets the fallback context key when secondary sidebar is unavailable', () => { + it('sets context key to false when secondary sidebar is unavailable', () => { registerChatViewProviders({ context: context as never, createViewProvider: vi.fn(), @@ -84,8 +88,8 @@ describe('registerChatViewProviders', () => { expect(executeCommand).toHaveBeenCalledWith( 'setContext', - 'qwen-code:doesNotSupportSecondarySidebar', - true, + 'qwen-code:supportsSecondarySidebar', + false, ); }); }); diff --git a/packages/vscode-ide-companion/src/webview/providers/chatViewRegistration.ts b/packages/vscode-ide-companion/src/webview/providers/chatViewRegistration.ts index d3eb5eb83..9897af026 100644 --- a/packages/vscode-ide-companion/src/webview/providers/chatViewRegistration.ts +++ b/packages/vscode-ide-companion/src/webview/providers/chatViewRegistration.ts @@ -14,8 +14,7 @@ import { type WebViewProviderFactory, } from './ChatWebviewViewProvider.js'; -const SECONDARY_SIDEBAR_CONTEXT_KEY = - 'qwen-code:doesNotSupportSecondarySidebar'; +const SECONDARY_SIDEBAR_CONTEXT_KEY = 'qwen-code:supportsSecondarySidebar'; export function detectSecondarySidebarSupport(vscodeVersion: string): boolean { const [major, minor] = vscodeVersion.split('.').map(Number); @@ -35,13 +34,16 @@ export function registerChatViewProviders(params: { const supportsSecondarySidebar = detectSecondarySidebarSupport(vscodeVersion); - if (!supportsSecondarySidebar) { - void vscode.commands.executeCommand( - 'setContext', - SECONDARY_SIDEBAR_CONTEXT_KEY, - true, - ); - } + // Set the context key so package.json `when` clauses can gate the + // secondarySidebar view container. The key defaults to undefined (falsy), + // which keeps the secondary container hidden until we explicitly enable it. + // This prevents the "view container not found" warning on older VS Code + // versions that don't recognise the `secondarySidebar` location. + void vscode.commands.executeCommand( + 'setContext', + SECONDARY_SIDEBAR_CONTEXT_KEY, + supportsSecondarySidebar, + ); const sidebarViewProvider = new ChatWebviewViewProvider(createViewProvider); const secondaryViewProvider = new ChatWebviewViewProvider(createViewProvider); diff --git a/packages/web-templates/package.json b/packages/web-templates/package.json index fbedb34d0..f90055b11 100644 --- a/packages/web-templates/package.json +++ b/packages/web-templates/package.json @@ -1,6 +1,6 @@ { "name": "@qwen-code/web-templates", - "version": "0.13.0", + "version": "0.13.2", "description": "Web templates bundled as embeddable JS/CSS strings", "repository": { "type": "git", diff --git a/packages/webui/package.json b/packages/webui/package.json index da5a463ab..45112a0d8 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -1,6 +1,6 @@ { "name": "@qwen-code/webui", - "version": "0.13.0", + "version": "0.13.2", "description": "Shared UI components for Qwen Code packages", "type": "module", "main": "./dist/index.cjs", diff --git a/scripts/copy_bundle_assets.js b/scripts/copy_bundle_assets.js index 83ca91f3f..96a65a2aa 100644 --- a/scripts/copy_bundle_assets.js +++ b/scripts/copy_bundle_assets.js @@ -72,6 +72,18 @@ if (existsSync(bundledSkillsDir)) { ); } +// Copy user docs into qc-helper bundled skill so it can reference them at runtime. +// The qc-helper skill reads docs from a `docs/` subdirectory relative to its own +// directory. In the esbuild bundle this becomes dist/bundled/qc-helper/docs/. +const userDocsDir = join(root, 'docs', 'users'); +if (existsSync(userDocsDir)) { + const destDocsDir = join(distDir, 'bundled', 'qc-helper', 'docs'); + copyRecursiveSync(userDocsDir, destDocsDir); + console.log('Copied docs/users/ to dist/bundled/qc-helper/docs/'); +} else { + console.warn(`Warning: User docs directory not found at ${userDocsDir}`); +} + console.log('\n✅ All bundle assets copied to dist/'); /** diff --git a/scripts/dev.js b/scripts/dev.js index 32f4a2280..bcbe27d89 100644 --- a/scripts/dev.js +++ b/scripts/dev.js @@ -17,13 +17,44 @@ import { spawn } from 'node:child_process'; import { dirname, join } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; -import { writeFileSync, mkdtempSync, rmSync } from 'node:fs'; +import { + writeFileSync, + mkdtempSync, + rmSync, + existsSync, + symlinkSync, + mkdirSync, +} from 'node:fs'; import { tmpdir, platform } from 'node:os'; const __dirname = dirname(fileURLToPath(import.meta.url)); const root = join(__dirname, '..'); const cliPackageDir = join(root, 'packages', 'cli'); +// Ensure qc-helper bundled skill can find user docs in dev mode. +// In dev, import.meta.url resolves to the source tree, so the bundled skill +// directory is packages/core/src/skills/bundled/qc-helper/. We create a +// symlink from there to docs/users/ so the skill can read docs at runtime. +const qcHelperDocsLink = join( + root, + 'packages', + 'core', + 'src', + 'skills', + 'bundled', + 'qc-helper', + 'docs', +); +const userDocsTarget = join(root, 'docs', 'users'); +if (existsSync(userDocsTarget) && !existsSync(qcHelperDocsLink)) { + mkdirSync(dirname(qcHelperDocsLink), { recursive: true }); + try { + symlinkSync(userDocsTarget, qcHelperDocsLink); + } catch { + // Symlink may fail on some systems; non-critical for dev + } +} + // Entry point for the CLI const cliEntry = join(cliPackageDir, 'index.ts'); diff --git a/scripts/prepare-package.js b/scripts/prepare-package.js index 02a8fb017..d38bf2e1e 100644 --- a/scripts/prepare-package.js +++ b/scripts/prepare-package.js @@ -41,6 +41,13 @@ if (!fs.existsSync(vendorDir)) { process.exit(1); } +const bundledDocsDir = path.join(distDir, 'bundled', 'qc-helper', 'docs'); +if (!fs.existsSync(bundledDocsDir)) { + console.error(`Error: Bundled docs not found at ${bundledDocsDir}`); + console.error('Please run "npm run bundle" first'); + process.exit(1); +} + // Copy README and LICENSE console.log('Copying documentation files...'); const filesToCopy = ['README.md', 'LICENSE'];