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/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/SubAgentTracker.test.ts b/packages/cli/src/acp-integration/session/SubAgentTracker.test.ts index 7e65d95eb..573a9afee 100644 --- a/packages/cli/src/acp-integration/session/SubAgentTracker.test.ts +++ b/packages/cli/src/acp-integration/session/SubAgentTracker.test.ts @@ -585,6 +585,86 @@ describe('SubAgentTracker', () => { ); }); }); + + 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/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/i18n/locales/de.js b/packages/cli/src/i18n/locales/de.js index ff700188c..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', diff --git a/packages/cli/src/i18n/locales/en.js b/packages/cli/src/i18n/locales/en.js index 8c37e2f78..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', diff --git a/packages/cli/src/i18n/locales/ja.js b/packages/cli/src/i18n/locales/ja.js index 677b85a67..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: '接続済み', diff --git a/packages/cli/src/i18n/locales/pt.js b/packages/cli/src/i18n/locales/pt.js index 1a0b26a39..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', diff --git a/packages/cli/src/i18n/locales/ru.js b/packages/cli/src/i18n/locales/ru.js index 49226706c..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: 'подключение', diff --git a/packages/cli/src/i18n/locales/zh.js b/packages/cli/src/i18n/locales/zh.js index f2428fd23..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: '已连接', 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/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/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/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/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/tools/agent.test.ts b/packages/core/src/tools/agent.test.ts index ac38139b5..505b434a0 100644 --- a/packages/core/src/tools/agent.test.ts +++ b/packages/core/src/tools/agent.test.ts @@ -8,6 +8,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { AgentTool, type AgentParams } from './agent.js'; import type { PartListUnion } from '@google/genai'; import type { ToolResultDisplay, AgentResultDisplay } from './tools.js'; +import { ToolConfirmationOutcome } from './tools.js'; import type { Config } from '../config/config.js'; import { SubagentManager } from '../subagents/subagent-manager.js'; import type { SubagentConfig } from '../subagents/types.js'; @@ -16,22 +17,32 @@ import { type AgentHeadless, ContextState, } from '../agents/runtime/agent-headless.js'; +import { AgentEventType } from '../agents/runtime/agent-events.js'; +import type { + AgentToolCallEvent, + AgentToolResultEvent, + AgentApprovalRequestEvent, + AgentEventEmitter, +} from '../agents/runtime/agent-events.js'; import { partToString } from '../utils/partUtils.js'; import type { HookSystem } from '../hooks/hookSystem.js'; import { PermissionMode } from '../hooks/types.js'; // Type for accessing protected methods in tests +type AgentToolInvocation = { + execute: ( + signal?: AbortSignal, + updateOutput?: (output: ToolResultDisplay) => void, + ) => Promise<{ + llmContent: PartListUnion; + returnDisplay: ToolResultDisplay; + }>; + getDescription: () => string; + eventEmitter: AgentEventEmitter; +}; + type AgentToolWithProtectedMethods = AgentTool & { - createInvocation: (params: AgentParams) => { - execute: ( - signal?: AbortSignal, - liveOutputCallback?: (chunk: string) => void, - ) => Promise<{ - llmContent: PartListUnion; - returnDisplay: ToolResultDisplay; - }>; - getDescription: () => string; - }; + createInvocation: (params: AgentParams) => AgentToolInvocation; }; // Mock dependencies @@ -1001,4 +1012,295 @@ describe('AgentTool', () => { expect(startAgentId).toMatch(/^file-search-\d+$/); }); }); + + describe('IDE diff-tab confirmation clears pendingConfirmation', () => { + let mockAgent: AgentHeadless; + let mockContextState: ContextState; + + // We capture the eventEmitter from the invocation so we can simulate + // events during subagent execution. + let capturedInvocation: AgentToolInvocation; + + beforeEach(() => { + mockContextState = { + set: vi.fn(), + } as unknown as ContextState; + + MockedContextState.mockImplementation(() => mockContextState); + + vi.mocked(mockSubagentManager.loadSubagent).mockResolvedValue( + mockSubagents[0], + ); + }); + + function createInvocationWithEventDrivenAgent( + emitDuringExecute: (emitter: AgentEventEmitter) => void, + ) { + // Create a mock agent whose execute() emits events on the invocation's + // eventEmitter, simulating a real subagent lifecycle. + mockAgent = { + execute: vi.fn(), + result: 'Done', + terminateMode: AgentTerminateMode.GOAL, + getFinalText: vi.fn().mockReturnValue('Done'), + formatCompactResult: vi.fn().mockReturnValue('✅ Success'), + getExecutionSummary: vi.fn().mockReturnValue({ + rounds: 1, + totalDurationMs: 100, + totalToolCalls: 1, + successfulToolCalls: 1, + failedToolCalls: 0, + successRate: 100, + inputTokens: 10, + outputTokens: 5, + totalTokens: 15, + toolUsage: [], + }), + getStatistics: vi.fn().mockReturnValue({ + rounds: 1, + totalDurationMs: 100, + totalToolCalls: 1, + successfulToolCalls: 1, + failedToolCalls: 0, + }), + getTerminateMode: vi.fn().mockReturnValue(AgentTerminateMode.GOAL), + } as unknown as AgentHeadless; + + vi.mocked(mockAgent.execute).mockImplementation(async () => { + emitDuringExecute(capturedInvocation.eventEmitter); + }); + + vi.mocked(mockSubagentManager.createAgentHeadless).mockResolvedValue( + mockAgent, + ); + + const params: AgentParams = { + description: 'Edit files', + prompt: 'Fix the bug', + subagent_type: 'file-search', + }; + + capturedInvocation = ( + agentTool as AgentToolWithProtectedMethods + ).createInvocation(params); + + return capturedInvocation; + } + + it('should clear pendingConfirmation when TOOL_RESULT arrives for the pending tool (IDE accept path)', async () => { + // Track whether pendingConfirmation was set then cleared, using + // snapshots that safely handle function properties (structuredClone + // can't serialize functions). + const snapshots: Array<{ + hasPendingConfirmation: boolean; + toolStatuses: Array<{ callId: string; status: string }>; + }> = []; + + const invocation = createInvocationWithEventDrivenAgent((emitter) => { + emitter.emit(AgentEventType.TOOL_CALL, { + subagentId: 'sub-1', + round: 1, + callId: 'call-edit-1', + name: 'edit_file', + args: { path: '/test.ts' }, + description: 'Editing test.ts', + timestamp: Date.now(), + } satisfies AgentToolCallEvent); + + // Tool needs approval → pendingConfirmation is set + emitter.emit(AgentEventType.TOOL_WAITING_APPROVAL, { + subagentId: 'sub-1', + round: 1, + callId: 'call-edit-1', + name: 'edit_file', + description: 'Editing test.ts', + timestamp: Date.now(), + confirmationDetails: { + type: 'edit' as const, + title: 'Edit file', + fileName: 'test.ts', + filePath: '/test.ts', + fileDiff: '', + originalContent: 'old', + newContent: 'new', + }, + respond: vi.fn(), + } as unknown as AgentApprovalRequestEvent); + + // IDE diff-tab accepted → TOOL_RESULT arrives without onConfirm + emitter.emit(AgentEventType.TOOL_RESULT, { + subagentId: 'sub-1', + round: 1, + callId: 'call-edit-1', + name: 'edit_file', + success: true, + timestamp: Date.now(), + } satisfies AgentToolResultEvent); + }); + + await invocation.execute(undefined, (output) => { + const display = output as AgentResultDisplay; + snapshots.push({ + hasPendingConfirmation: display.pendingConfirmation !== undefined, + toolStatuses: (display.toolCalls ?? []).map((tc) => ({ + callId: tc.callId, + status: tc.status, + })), + }); + }); + + // Should have at least one snapshot with pendingConfirmation set + const hasApproval = snapshots.some((s) => s.hasPendingConfirmation); + expect(hasApproval).toBe(true); + + // The final snapshot after TOOL_RESULT should have cleared it + const resultSnapshot = snapshots.find( + (s) => + !s.hasPendingConfirmation && + s.toolStatuses.some( + (tc) => tc.callId === 'call-edit-1' && tc.status === 'success', + ), + ); + expect(resultSnapshot).toBeDefined(); + }); + + it('should NOT clear pendingConfirmation when TOOL_RESULT is for a different tool', async () => { + const snapshots: Array<{ + hasPendingConfirmation: boolean; + toolStatuses: Array<{ callId: string; status: string }>; + }> = []; + + const invocation = createInvocationWithEventDrivenAgent((emitter) => { + // Tool A starts + emitter.emit(AgentEventType.TOOL_CALL, { + subagentId: 'sub-1', + round: 1, + callId: 'call-read-1', + name: 'read_file', + args: {}, + description: 'Reading', + timestamp: Date.now(), + } satisfies AgentToolCallEvent); + + // Tool B starts + emitter.emit(AgentEventType.TOOL_CALL, { + subagentId: 'sub-1', + round: 1, + callId: 'call-edit-1', + name: 'edit_file', + args: {}, + description: 'Editing', + timestamp: Date.now(), + } satisfies AgentToolCallEvent); + + // Tool B needs approval + emitter.emit(AgentEventType.TOOL_WAITING_APPROVAL, { + subagentId: 'sub-1', + round: 1, + callId: 'call-edit-1', + name: 'edit_file', + description: 'Editing', + timestamp: Date.now(), + confirmationDetails: { + type: 'edit' as const, + title: 'Edit', + fileName: 'test.ts', + filePath: '/test.ts', + fileDiff: '', + originalContent: '', + newContent: 'new', + }, + respond: vi.fn(), + } as unknown as AgentApprovalRequestEvent); + + // Tool A finishes (different callId) + emitter.emit(AgentEventType.TOOL_RESULT, { + subagentId: 'sub-1', + round: 1, + callId: 'call-read-1', + name: 'read_file', + success: true, + timestamp: Date.now(), + } satisfies AgentToolResultEvent); + }); + + await invocation.execute(undefined, (output) => { + const display = output as AgentResultDisplay; + snapshots.push({ + hasPendingConfirmation: display.pendingConfirmation !== undefined, + toolStatuses: (display.toolCalls ?? []).map((tc) => ({ + callId: tc.callId, + status: tc.status, + })), + }); + }); + + // The snapshot for read_file's TOOL_RESULT should still have + // pendingConfirmation because the result was for a different tool. + const readResultSnapshot = snapshots.find((s) => + s.toolStatuses.some( + (tc) => tc.callId === 'call-read-1' && tc.status === 'success', + ), + ); + expect(readResultSnapshot).toBeDefined(); + expect(readResultSnapshot!.hasPendingConfirmation).toBe(true); + }); + + it('should clear pendingConfirmation via onConfirm callback (terminal UI path)', async () => { + let capturedOnConfirm: + | ((outcome: ToolConfirmationOutcome) => Promise) + | undefined; + const snapshots: Array<{ hasPendingConfirmation: boolean }> = []; + + const invocation = createInvocationWithEventDrivenAgent((emitter) => { + emitter.emit(AgentEventType.TOOL_CALL, { + subagentId: 'sub-1', + round: 1, + callId: 'call-edit-1', + name: 'edit_file', + args: {}, + description: 'Editing', + timestamp: Date.now(), + } satisfies AgentToolCallEvent); + + emitter.emit(AgentEventType.TOOL_WAITING_APPROVAL, { + subagentId: 'sub-1', + round: 1, + callId: 'call-edit-1', + name: 'edit_file', + description: 'Editing', + timestamp: Date.now(), + confirmationDetails: { + type: 'edit' as const, + title: 'Edit', + fileName: 'test.ts', + filePath: '/test.ts', + fileDiff: '', + originalContent: '', + newContent: 'new', + }, + respond: vi.fn(), + } as unknown as AgentApprovalRequestEvent); + }); + + await invocation.execute(undefined, (output) => { + const display = output as AgentResultDisplay; + snapshots.push({ + hasPendingConfirmation: display.pendingConfirmation !== undefined, + }); + if (display.pendingConfirmation?.onConfirm) { + capturedOnConfirm = display.pendingConfirmation.onConfirm; + } + }); + + expect(capturedOnConfirm).toBeDefined(); + + // Call onConfirm as if the user pressed "accept" in the terminal UI + snapshots.length = 0; + await capturedOnConfirm!(ToolConfirmationOutcome.ProceedOnce); + + // The onConfirm callback should have cleared pendingConfirmation + expect(snapshots.some((s) => !s.hasPendingConfirmation)).toBe(true); + }); + }); }); diff --git a/packages/core/src/tools/agent.ts b/packages/core/src/tools/agent.ts index 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/utils/shell-utils.test.ts b/packages/core/src/utils/shell-utils.test.ts index 183e4f539..91162af37 100644 --- a/packages/core/src/utils/shell-utils.test.ts +++ b/packages/core/src/utils/shell-utils.test.ts @@ -559,12 +559,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', async () => { delete process.env['ComSpec']; + delete process.env['MSYSTEM']; + delete process.env['TERM']; const config = getShellConfiguration(); expect(config.executable).toBe('cmd.exe'); expect(config.argsPrefix).toEqual(['/d', '/s', '/c']); @@ -574,6 +582,8 @@ describe('getShellConfiguration', () => { it('should respect ComSpec for cmd.exe', async () => { const cmdPath = 'C:\\WINDOWS\\system32\\cmd.exe'; process.env['ComSpec'] = cmdPath; + delete process.env['MSYSTEM']; + delete process.env['TERM']; const config = getShellConfiguration(); expect(config.executable).toBe(cmdPath); expect(config.argsPrefix).toEqual(['/d', '/s', '/c']); @@ -584,6 +594,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']); @@ -593,6 +605,8 @@ describe('getShellConfiguration', () => { it('should return PowerShell configuration if ComSpec points to pwsh.exe', async () => { const pwshPath = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe'; process.env['ComSpec'] = pwshPath; + delete process.env['MSYSTEM']; + delete process.env['TERM']; const config = getShellConfiguration(); expect(config.executable).toBe(pwshPath); expect(config.argsPrefix).toEqual(['-NoProfile', '-Command']); @@ -601,11 +615,76 @@ describe('getShellConfiguration', () => { it('should be case-insensitive when checking ComSpec', async () => { process.env['ComSpec'] = 'C:\\Path\\To\\POWERSHELL.EXE'; + delete process.env['MSYSTEM']; + delete process.env['TERM']; const config = getShellConfiguration(); expect(config.executable).toBe('C:\\Path\\To\\POWERSHELL.EXE'); expect(config.argsPrefix).toEqual(['-NoProfile', '-Command']); expect(config.shell).toBe('powershell'); }); + + describe('Git Bash / MSYS2 / MinTTY detection', () => { + it('should return bash configuration when MSYSTEM starts with MINGW', () => { + process.env['MSYSTEM'] = 'MINGW64'; + const config = getShellConfiguration(); + 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 b44fb9b2a..fe806323f 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(); 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/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" + ] } } }