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/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..b0366a9b8 100644 --- a/integration-tests/sdk-typescript/tool-control.test.ts +++ b/integration-tests/sdk-typescript/tool-control.test.ts @@ -316,6 +316,171 @@ 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/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/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') + ); + }); + expect(rmResults.length).toBeGreaterThan(0); + } + } + } finally { + await q.close(); + } + }, + TEST_TIMEOUT, + ); }); describe('allowedTools parameter', () => { @@ -516,6 +681,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 +891,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 +920,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 +1008,320 @@ 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/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/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/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/src/acp-integration/session/Session.ts b/packages/cli/src/acp-integration/session/Session.ts index 45b837569..f9e47cdae 100644 --- a/packages/cli/src/acp-integration/session/Session.ts +++ b/packages/cli/src/acp-integration/session/Session.ts @@ -623,7 +623,7 @@ export class Session implements SessionContext { if (confirmationDetails.type === 'edit') { content.push({ type: 'diff', - path: confirmationDetails.fileName, + path: confirmationDetails.filePath || confirmationDetails.fileName, oldText: confirmationDetails.originalContent, newText: confirmationDetails.newContent, }); diff --git a/packages/cli/src/acp-integration/session/SubAgentTracker.test.ts b/packages/cli/src/acp-integration/session/SubAgentTracker.test.ts index 0be126ff4..4c4025c82 100644 --- a/packages/cli/src/acp-integration/session/SubAgentTracker.test.ts +++ b/packages/cli/src/acp-integration/session/SubAgentTracker.test.ts @@ -531,6 +531,86 @@ describe('SubAgentTracker', () => { expect(respondSpy).toHaveBeenCalledWith(ToolConfirmationOutcome.Cancel); }); }); + + 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..7a904e9e6 100644 --- a/packages/cli/src/acp-integration/session/SubAgentTracker.ts +++ b/packages/cli/src/acp-integration/session/SubAgentTracker.ts @@ -226,12 +226,13 @@ export class SubAgentTracker { const editDetails = event.confirmationDetails as unknown as { type: 'edit'; fileName: string; + filePath: string; originalContent: string | null; newContent: string; }; content.push({ type: 'diff', - path: editDetails.fileName, + path: editDetails.filePath || editDetails.fileName, oldText: editDetails.originalContent ?? '', newText: editDetails.newContent, }); 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/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/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/i18n/locales/de.js b/packages/cli/src/i18n/locales/de.js index aa4a6d552..42070c5a1 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)', diff --git a/packages/cli/src/i18n/locales/en.js b/packages/cli/src/i18n/locales/en.js index fb4433b2a..8024ebb80 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)', diff --git a/packages/cli/src/i18n/locales/ja.js b/packages/cli/src/i18n/locales/ja.js index b06a6fdef..7f5e6dbb9 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)', diff --git a/packages/cli/src/i18n/locales/pt.js b/packages/cli/src/i18n/locales/pt.js index b2240877b..bafabb6f6 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)', diff --git a/packages/cli/src/i18n/locales/ru.js b/packages/cli/src/i18n/locales/ru.js index c3ae5953a..51eadf956 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)', diff --git a/packages/cli/src/i18n/locales/zh.js b/packages/cli/src/i18n/locales/zh.js index d22fe9b26..c646fc044 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)', 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/ui/AppContainer.tsx b/packages/cli/src/ui/AppContainer.tsx index 8ba48a4c9..b32bd89ad 100644 --- a/packages/cli/src/ui/AppContainer.tsx +++ b/packages/cli/src/ui/AppContainer.tsx @@ -110,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, @@ -552,6 +553,8 @@ export const AppContainer = (props: AppContainerProps) => { closeExtensionsManagerDialog, } = useExtensionsManagerDialog(); const { isMcpDialogOpen, openMcpDialog, closeMcpDialog } = useMcpDialog(); + const { isHooksDialogOpen, openHooksDialog, closeHooksDialog } = + useHooksDialog(); const slashCommandActions = useMemo( () => ({ @@ -578,6 +581,7 @@ export const AppContainer = (props: AppContainerProps) => { openAgentsManagerDialog, openExtensionsManagerDialog, openMcpDialog, + openHooksDialog, openResumeDialog, }), [ @@ -597,6 +601,7 @@ export const AppContainer = (props: AppContainerProps) => { openAgentsManagerDialog, openExtensionsManagerDialog, openMcpDialog, + openHooksDialog, openResumeDialog, ], ); @@ -1439,6 +1444,7 @@ export const AppContainer = (props: AppContainerProps) => { isSubagentCreateDialogOpen || isAgentsManagerDialogOpen || isMcpDialogOpen || + isHooksDialogOpen || isApprovalModeDialogOpen || isResumeDialogOpen || isExtensionsManagerDialogOpen; @@ -1561,6 +1567,8 @@ export const AppContainer = (props: AppContainerProps) => { isExtensionsManagerDialogOpen, // MCP dialog isMcpDialogOpen, + // Hooks dialog + isHooksDialogOpen, // Feedback dialog isFeedbackDialogOpen, // Per-task token tracking @@ -1662,6 +1670,8 @@ export const AppContainer = (props: AppContainerProps) => { isExtensionsManagerDialogOpen, // MCP dialog isMcpDialogOpen, + // Hooks dialog + isHooksDialogOpen, // Feedback dialog isFeedbackDialogOpen, // Per-task token tracking @@ -1713,6 +1723,10 @@ export const AppContainer = (props: AppContainerProps) => { closeExtensionsManagerDialog, // MCP dialog closeMcpDialog, + // Hooks dialog + openHooksDialog, + // Hooks dialog + closeHooksDialog, // Resume session dialog openResumeDialog, closeResumeDialog, @@ -1764,6 +1778,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/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 d74f3e393..2bd798054 100644 --- a/packages/cli/src/ui/commands/types.ts +++ b/packages/cli/src/ui/commands/types.ts @@ -164,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/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/ToolConfirmationMessage.tsx b/packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx index 3946b0b05..e3c9ed1e1 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'; @@ -243,16 +247,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 +336,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 +421,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/UIActionsContext.tsx b/packages/cli/src/ui/contexts/UIActionsContext.tsx index 8604e6744..4228149bc 100644 --- a/packages/cli/src/ui/contexts/UIActionsContext.tsx +++ b/packages/cli/src/ui/contexts/UIActionsContext.tsx @@ -83,6 +83,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 03bda1e58..9c8446368 100644 --- a/packages/cli/src/ui/contexts/UIStateContext.tsx +++ b/packages/cli/src/ui/contexts/UIStateContext.tsx @@ -136,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 2d61409f4..c0c3fac07 100644 --- a/packages/cli/src/ui/hooks/slashCommandProcessor.ts +++ b/packages/cli/src/ui/hooks/slashCommandProcessor.ts @@ -87,6 +87,7 @@ interface SlashCommandProcessorActions { openAgentsManagerDialog: () => void; openExtensionsManagerDialog: () => void; openMcpDialog: () => void; + openHooksDialog: () => void; } /** @@ -523,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' }; 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/core/src/core/coreToolScheduler.ts b/packages/core/src/core/coreToolScheduler.ts index 097120d08..7279d452b 100644 --- a/packages/core/src/core/coreToolScheduler.ts +++ b/packages/core/src/core/coreToolScheduler.ts @@ -701,7 +701,13 @@ export class CoreToolScheduler { // 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.`; + 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}`; return { status: 'error', request: reqInfo, @@ -914,10 +920,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', @@ -1002,7 +1014,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', diff --git a/packages/core/src/extension/variables.ts b/packages/core/src/extension/variables.ts index ba3d9a439..d9c623e78 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'; diff --git a/packages/core/src/hooks/hookEventHandler.test.ts b/packages/core/src/hooks/hookEventHandler.test.ts index f3c9b50d9..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; @@ -2246,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 45eacf81b..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'); @@ -415,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 @@ -451,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}`); @@ -496,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 = @@ -505,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/index.ts b/packages/core/src/index.ts index 2a97f731b..8a498b912 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -127,7 +127,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'; 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..94a5126ba 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'; @@ -1519,3 +1520,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..f10d1d4a3 100644 --- a/packages/core/src/permissions/permission-manager.ts +++ b/packages/core/src/permissions/permission-manager.ts @@ -365,6 +365,43 @@ export class PermissionManager { 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 // --------------------------------------------------------------------------- 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/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/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 ac38139b5..f08393e02 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,34 @@ 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 @@ -1001,4 +1014,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 77c1be4f0..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, diff --git a/packages/core/src/tools/glob.test.ts b/packages/core/src/tools/glob.test.ts index dc1537930..24be79d2e 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'); diff --git a/packages/core/src/tools/glob.ts b/packages/core/src/tools/glob.ts index 12a29922a..44edae4e6 100644 --- a/packages/core/src/tools/glob.ts +++ b/packages/core/src/tools/glob.ts @@ -119,61 +119,104 @@ 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 search directory so that + // .gitignore / .qwenignore patterns match correctly regardless of + // which workspace directory the file belongs to. + const relativePaths = entries.map((p) => + path.relative(searchDir, 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(searchDir, 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..868cecd78 100644 --- a/packages/core/src/tools/grep.test.ts +++ b/packages/core/src/tools/grep.test.ts @@ -357,6 +357,48 @@ 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 }); + }); }); describe('getDescription', () => { diff --git a/packages/core/src/tools/grep.ts b/packages/core/src/tools/grep.ts index e0df29140..6e16348d9 100644 --- a/packages/core/src/tools/grep.ts +++ b/packages/core/src/tools/grep.ts @@ -95,26 +95,52 @@ 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 + const 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); + } 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..5edbc680a 100644 --- a/packages/core/src/tools/ripGrep.test.ts +++ b/packages/core/src/tools/ripGrep.test.ts @@ -436,6 +436,116 @@ 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 }); + }); + }); + 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..19a98af80 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}")` @@ -171,11 +188,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 +210,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 +234,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/utils/shell-utils.test.ts b/packages/core/src/utils/shell-utils.test.ts index 7485384f8..8224f9950 100644 --- a/packages/core/src/utils/shell-utils.test.ts +++ b/packages/core/src/utils/shell-utils.test.ts @@ -556,12 +556,20 @@ describe('getShellConfiguration', () => { }); describe('on Windows', () => { + const originalEnv = { ...process.env }; + beforeEach(() => { mockPlatform.mockReturnValue('win32'); }); + afterEach(() => { + process.env = originalEnv; + }); + it('should return cmd.exe configuration by default', () => { 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']); @@ -571,6 +579,8 @@ describe('getShellConfiguration', () => { it('should respect ComSpec for cmd.exe', () => { 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']); @@ -581,6 +591,8 @@ describe('getShellConfiguration', () => { 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']); @@ -590,6 +602,8 @@ describe('getShellConfiguration', () => { it('should return PowerShell configuration if ComSpec points to pwsh.exe', () => { 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']); @@ -598,11 +612,76 @@ describe('getShellConfiguration', () => { it('should be case-insensitive when checking ComSpec', () => { 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(); + expect(config.executable).toBe('bash'); + 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).toBe('bash'); + 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).toBe('bash'); + 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).toBe('bash'); + 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).toBe('bash'); + 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).toBe('bash'); + expect(config.argsPrefix).toEqual(['-c']); + expect(config.shell).toBe('bash'); + }); + }); }); }); diff --git a/packages/core/src/utils/shell-utils.ts b/packages/core/src/utils/shell-utils.ts index 175986b1b..1ef1dd09e 100644 --- a/packages/core/src/utils/shell-utils.ts +++ b/packages/core/src/utils/shell-utils.ts @@ -48,6 +48,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: 'bash', + argsPrefix: ['-c'], + shell: 'bash', + }; + } + const comSpec = process.env['ComSpec'] || 'cmd.exe'; const executable = comSpec.toLowerCase(); @@ -892,14 +910,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); 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/vscode-ide-companion/package.json b/packages/vscode-ide-companion/package.json index a7c18ab4b..31039854c 100644 --- a/packages/vscode-ide-companion/package.json +++ b/packages/vscode-ide-companion/package.json @@ -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/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);