feat: restructure docs

This commit is contained in:
pomelo-nwu
2025-12-04 18:26:05 +08:00
parent 6729980b47
commit 17785c418d
72 changed files with 0 additions and 412 deletions

View File

@@ -0,0 +1,8 @@
export default {
subagents: 'Subagents',
checkpointing: 'Checkpointing',
sandbox: 'Sandbox Support',
headless: 'Headless Mode',
'welcome-back': 'Welcome Back',
'token-caching': 'Token Caching',
};

View File

@@ -0,0 +1,77 @@
# Checkpointing
Qwen Code includes a Checkpointing feature that automatically saves a snapshot of your project's state before any file modifications are made by AI-powered tools. This allows you to safely experiment with and apply code changes, knowing you can instantly revert back to the state before the tool was run.
## How It Works
When you approve a tool that modifies the file system (like `write_file` or `edit`), the CLI automatically creates a "checkpoint." This checkpoint includes:
1. **A Git Snapshot:** A commit is made in a special, shadow Git repository located in your home directory (`~/.qwen/history/<project_hash>`). This snapshot captures the complete state of your project files at that moment. It does **not** interfere with your own project's Git repository.
2. **Conversation History:** The entire conversation you've had with the agent up to that point is saved.
3. **The Tool Call:** The specific tool call that was about to be executed is also stored.
If you want to undo the change or simply go back, you can use the `/restore` command. Restoring a checkpoint will:
- Revert all files in your project to the state captured in the snapshot.
- Restore the conversation history in the CLI.
- Re-propose the original tool call, allowing you to run it again, modify it, or simply ignore it.
All checkpoint data, including the Git snapshot and conversation history, is stored locally on your machine. The Git snapshot is stored in the shadow repository while the conversation history and tool calls are saved in a JSON file in your project's temporary directory, typically located at `~/.qwen/tmp/<project_hash>/checkpoints`.
## Enabling the Feature
The Checkpointing feature is disabled by default. To enable it, you can either use a command-line flag or edit your `settings.json` file.
### Using the Command-Line Flag
You can enable checkpointing for the current session by using the `--checkpointing` flag when starting Qwen Code:
```bash
qwen --checkpointing
```
### Using the `settings.json` File
To enable checkpointing by default for all sessions, you need to edit your `settings.json` file.
Add the following key to your `settings.json`:
```json
{
"general": {
"checkpointing": {
"enabled": true
}
}
}
```
## Using the `/restore` Command
Once enabled, checkpoints are created automatically. To manage them, you use the `/restore` command.
### List Available Checkpoints
To see a list of all saved checkpoints for the current project, simply run:
```
/restore
```
The CLI will display a list of available checkpoint files. These file names are typically composed of a timestamp, the name of the file being modified, and the name of the tool that was about to be run (e.g., `2025-06-22T10-00-00_000Z-my-file.txt-write_file`).
### Restore a Specific Checkpoint
To restore your project to a specific checkpoint, use the checkpoint file from the list:
```
/restore <checkpoint_file>
```
For example:
```
/restore 2025-06-22T10-00-00_000Z-my-file.txt-write_file
```
After running the command, your files and conversation will be immediately restored to the state they were in when the checkpoint was created, and the original tool prompt will reappear.

View File

@@ -0,0 +1,307 @@
# Headless Mode
Headless mode allows you to run Qwen Code programmatically from command line
scripts and automation tools without any interactive UI. This is ideal for
scripting, automation, CI/CD pipelines, and building AI-powered tools.
- [Headless Mode](#headless-mode)
- [Overview](#overview)
- [Basic Usage](#basic-usage)
- [Direct Prompts](#direct-prompts)
- [Stdin Input](#stdin-input)
- [Combining with File Input](#combining-with-file-input)
- [Output Formats](#output-formats)
- [Text Output (Default)](#text-output-default)
- [JSON Output](#json-output)
- [Example Usage](#example-usage)
- [Stream-JSON Output](#stream-json-output)
- [Input Format](#input-format)
- [File Redirection](#file-redirection)
- [Configuration Options](#configuration-options)
- [Examples](#examples)
- [Code review](#code-review)
- [Generate commit messages](#generate-commit-messages)
- [API documentation](#api-documentation)
- [Batch code analysis](#batch-code-analysis)
- [PR code review](#pr-code-review)
- [Log analysis](#log-analysis)
- [Release notes generation](#release-notes-generation)
- [Model and tool usage tracking](#model-and-tool-usage-tracking)
- [Resources](#resources)
## Overview
The headless mode provides a headless interface to Qwen Code that:
- Accepts prompts via command line arguments or stdin
- Returns structured output (text or JSON)
- Supports file redirection and piping
- Enables automation and scripting workflows
- Provides consistent exit codes for error handling
- Can resume previous sessions scoped to the current project for multi-step automation
## Basic Usage
### Direct Prompts
Use the `--prompt` (or `-p`) flag to run in headless mode:
```bash
qwen --prompt "What is machine learning?"
```
### Stdin Input
Pipe input to Qwen Code from your terminal:
```bash
echo "Explain this code" | qwen
```
### Combining with File Input
Read from files and process with Qwen Code:
```bash
cat README.md | qwen --prompt "Summarize this documentation"
```
### Resume Previous Sessions (Headless)
Reuse conversation context from the current project in headless scripts:
```bash
# Continue the most recent session for this project and run a new prompt
qwen --continue -p "Run the tests again and summarize failures"
# Resume a specific session ID directly (no UI)
qwen --resume 123e4567-e89b-12d3-a456-426614174000 -p "Apply the follow-up refactor"
```
Notes:
- Session data is project-scoped JSONL under `~/.qwen/projects/<sanitized-cwd>/chats`.
- Restores conversation history, tool outputs, and chat-compression checkpoints before sending the new prompt.
## Output Formats
Qwen Code supports multiple output formats for different use cases:
### Text Output (Default)
Standard human-readable output:
```bash
qwen -p "What is the capital of France?"
```
Response format:
```
The capital of France is Paris.
```
### JSON Output
Returns structured data as a JSON array. All messages are buffered and output together when the session completes. This format is ideal for programmatic processing and automation scripts.
The JSON output is an array of message objects. The output includes multiple message types: system messages (session initialization), assistant messages (AI responses), and result messages (execution summary).
#### Example Usage
```bash
qwen -p "What is the capital of France?" --output-format json
```
Output (at end of execution):
```json
[
{
"type": "system",
"subtype": "session_start",
"uuid": "...",
"session_id": "...",
"model": "qwen3-coder-plus",
...
},
{
"type": "assistant",
"uuid": "...",
"session_id": "...",
"message": {
"id": "...",
"type": "message",
"role": "assistant",
"model": "qwen3-coder-plus",
"content": [
{
"type": "text",
"text": "The capital of France is Paris."
}
],
"usage": {...}
},
"parent_tool_use_id": null
},
{
"type": "result",
"subtype": "success",
"uuid": "...",
"session_id": "...",
"is_error": false,
"duration_ms": 1234,
"result": "The capital of France is Paris.",
"usage": {...}
}
]
```
### Stream-JSON Output
Stream-JSON format emits JSON messages immediately as they occur during execution, enabling real-time monitoring. This format uses line-delimited JSON where each message is a complete JSON object on a single line.
```bash
qwen -p "Explain TypeScript" --output-format stream-json
```
Output (streaming as events occur):
```json
{"type":"system","subtype":"session_start","uuid":"...","session_id":"..."}
{"type":"assistant","uuid":"...","session_id":"...","message":{...}}
{"type":"result","subtype":"success","uuid":"...","session_id":"..."}
```
When combined with `--include-partial-messages`, additional stream events are emitted in real-time (message_start, content_block_delta, etc.) for real-time UI updates.
```bash
qwen -p "Write a Python script" --output-format stream-json --include-partial-messages
```
### Input Format
The `--input-format` parameter controls how Qwen Code consumes input from standard input:
- **`text`** (default): Standard text input from stdin or command-line arguments
- **`stream-json`**: JSON message protocol via stdin for bidirectional communication
> **Note:** Stream-json input mode is currently under construction and is intended for SDK integration. It requires `--output-format stream-json` to be set.
### File Redirection
Save output to files or pipe to other commands:
```bash
# Save to file
qwen -p "Explain Docker" > docker-explanation.txt
qwen -p "Explain Docker" --output-format json > docker-explanation.json
# Append to file
qwen -p "Add more details" >> docker-explanation.txt
# Pipe to other tools
qwen -p "What is Kubernetes?" --output-format json | jq '.response'
qwen -p "Explain microservices" | wc -w
qwen -p "List programming languages" | grep -i "python"
# Stream-JSON output for real-time processing
qwen -p "Explain Docker" --output-format stream-json | jq '.type'
qwen -p "Write code" --output-format stream-json --include-partial-messages | jq '.event.type'
```
## Configuration Options
Key command-line options for headless usage:
| Option | Description | Example |
| ---------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------ |
| `--prompt`, `-p` | Run in headless mode | `qwen -p "query"` |
| `--output-format`, `-o` | Specify output format (text, json, stream-json) | `qwen -p "query" --output-format json` |
| `--input-format` | Specify input format (text, stream-json) | `qwen --input-format text --output-format stream-json` |
| `--include-partial-messages` | Include partial messages in stream-json output | `qwen -p "query" --output-format stream-json --include-partial-messages` |
| `--debug`, `-d` | Enable debug mode | `qwen -p "query" --debug` |
| `--all-files`, `-a` | Include all files in context | `qwen -p "query" --all-files` |
| `--include-directories` | Include additional directories | `qwen -p "query" --include-directories src,docs` |
| `--yolo`, `-y` | Auto-approve all actions | `qwen -p "query" --yolo` |
| `--approval-mode` | Set approval mode | `qwen -p "query" --approval-mode auto_edit` |
| `--continue` | Resume the most recent session for this project | `qwen --continue -p "Pick up where we left off"` |
| `--resume [sessionId]` | Resume a specific session (or choose interactively) | `qwen --resume 123e... -p "Finish the refactor"` |
For complete details on all available configuration options, settings files, and environment variables, see the [Configuration Guide](./cli/configuration.md).
## Examples
### Code review
```bash
cat src/auth.py | qwen -p "Review this authentication code for security issues" > security-review.txt
```
### Generate commit messages
```bash
result=$(git diff --cached | qwen -p "Write a concise commit message for these changes" --output-format json)
echo "$result" | jq -r '.response'
```
### API documentation
```bash
result=$(cat api/routes.js | qwen -p "Generate OpenAPI spec for these routes" --output-format json)
echo "$result" | jq -r '.response' > openapi.json
```
### Batch code analysis
```bash
for file in src/*.py; do
echo "Analyzing $file..."
result=$(cat "$file" | qwen -p "Find potential bugs and suggest improvements" --output-format json)
echo "$result" | jq -r '.response' > "reports/$(basename "$file").analysis"
echo "Completed analysis for $(basename "$file")" >> reports/progress.log
done
```
### PR code review
```bash
result=$(git diff origin/main...HEAD | qwen -p "Review these changes for bugs, security issues, and code quality" --output-format json)
echo "$result" | jq -r '.response' > pr-review.json
```
### Log analysis
```bash
grep "ERROR" /var/log/app.log | tail -20 | qwen -p "Analyze these errors and suggest root cause and fixes" > error-analysis.txt
```
### Release notes generation
```bash
result=$(git log --oneline v1.0.0..HEAD | qwen -p "Generate release notes from these commits" --output-format json)
response=$(echo "$result" | jq -r '.response')
echo "$response"
echo "$response" >> CHANGELOG.md
```
### Model and tool usage tracking
```bash
result=$(qwen -p "Explain this database schema" --include-directories db --output-format json)
total_tokens=$(echo "$result" | jq -r '.stats.models // {} | to_entries | map(.value.tokens.total) | add // 0')
models_used=$(echo "$result" | jq -r '.stats.models // {} | keys | join(", ") | if . == "" then "none" else . end')
tool_calls=$(echo "$result" | jq -r '.stats.tools.totalCalls // 0')
tools_used=$(echo "$result" | jq -r '.stats.tools.byName // {} | keys | join(", ") | if . == "" then "none" else . end')
echo "$(date): $total_tokens tokens, $tool_calls tool calls ($tools_used) used with models: $models_used" >> usage.log
echo "$result" | jq -r '.response' > schema-docs.md
echo "Recent usage trends:"
tail -5 usage.log
```
## Resources
- [CLI Configuration](./cli/configuration.md) - Complete configuration guide
- [Authentication](./cli/authentication.md) - Setup authentication
- [Commands](./cli/commands.md) - Interactive commands reference
- [Tutorials](./cli/tutorials.md) - Step-by-step automation guides

View File

@@ -0,0 +1,157 @@
# Sandboxing in Qwen Code
This document provides a guide to sandboxing in Qwen Code, including prerequisites, quickstart, and configuration.
## Prerequisites
Before using sandboxing, you need to install and set up Qwen Code:
```bash
npm install -g @qwen-code/qwen-code
```
To verify the installation
```bash
qwen --version
```
## Overview of sandboxing
Sandboxing isolates potentially dangerous operations (such as shell commands or file modifications) from your host system, providing a security barrier between AI operations and your environment.
The benefits of sandboxing include:
- **Security**: Prevent accidental system damage or data loss.
- **Isolation**: Limit file system access to project directory.
- **Consistency**: Ensure reproducible environments across different systems.
- **Safety**: Reduce risk when working with untrusted code or experimental commands.
## Sandboxing methods
Your ideal method of sandboxing may differ depending on your platform and your preferred container solution.
### 1. macOS Seatbelt (macOS only)
Lightweight, built-in sandboxing using `sandbox-exec`.
**Default profile**: `permissive-open` - restricts writes outside project directory but allows most other operations.
### 2. Container-based (Docker/Podman)
Cross-platform sandboxing with complete process isolation.
**Note**: Requires building the sandbox image locally or using a published image from your organization's registry.
## Quickstart
```bash
# Enable sandboxing with command flag
qwen -s -p "analyze the code structure"
# Use environment variable
export GEMINI_SANDBOX=true
qwen -p "run the test suite"
# Configure in settings.json
{
"tools": {
"sandbox": "docker"
}
}
```
## Configuration
### Enable sandboxing (in order of precedence)
1. **Command flag**: `-s` or `--sandbox`
2. **Environment variable**: `GEMINI_SANDBOX=true|docker|podman|sandbox-exec`
3. **Settings file**: `"sandbox": true` in the `tools` object of your `settings.json` file (e.g., `{"tools": {"sandbox": true}}`).
### macOS Seatbelt profiles
Built-in profiles (set via `SEATBELT_PROFILE` env var):
- `permissive-open` (default): Write restrictions, network allowed
- `permissive-closed`: Write restrictions, no network
- `permissive-proxied`: Write restrictions, network via proxy
- `restrictive-open`: Strict restrictions, network allowed
- `restrictive-closed`: Maximum restrictions
### Custom Sandbox Flags
For container-based sandboxing, you can inject custom flags into the `docker` or `podman` command using the `SANDBOX_FLAGS` environment variable. This is useful for advanced configurations, such as disabling security features for specific use cases.
**Example (Podman)**:
To disable SELinux labeling for volume mounts, you can set the following:
```bash
export SANDBOX_FLAGS="--security-opt label=disable"
```
Multiple flags can be provided as a space-separated string:
```bash
export SANDBOX_FLAGS="--flag1 --flag2=value"
```
## Linux UID/GID handling
The sandbox automatically handles user permissions on Linux. Override these permissions with:
```bash
export SANDBOX_SET_UID_GID=true # Force host UID/GID
export SANDBOX_SET_UID_GID=false # Disable UID/GID mapping
```
## Troubleshooting
### Common issues
**"Operation not permitted"**
- Operation requires access outside sandbox.
- Try more permissive profile or add mount points.
**Missing commands**
- Add to custom Dockerfile.
- Install via `sandbox.bashrc`.
**Network issues**
- Check sandbox profile allows network.
- Verify proxy configuration.
### Debug mode
```bash
DEBUG=1 qwen -s -p "debug command"
```
**Note:** If you have `DEBUG=true` in a project's `.env` file, it won't affect the CLI due to automatic exclusion. Use `.qwen/.env` files for Qwen Code-specific debug settings.
### Inspect sandbox
```bash
# Check environment
qwen -s -p "run shell command: env | grep SANDBOX"
# List mounts
qwen -s -p "run shell command: mount | grep workspace"
```
## Security notes
- Sandboxing reduces but doesn't eliminate all risks.
- Use the most restrictive profile that allows your work.
- Container overhead is minimal after first build.
- GUI applications may not work in sandboxes.
## Related documentation
- [Configuration](./cli/configuration.md): Full configuration options.
- [Commands](./cli/commands.md): Available commands.
- [Troubleshooting](./troubleshooting.md): General troubleshooting.

View File

@@ -0,0 +1,512 @@
# Subagents
Subagents are specialized AI assistants that handle specific types of tasks within Qwen Code. They allow you to delegate focused work to AI agents that are configured with task-specific prompts, tools, and behaviors.
## What are Subagents?
Subagents are independent AI assistants that:
- **Specialize in specific tasks** - Each subagent is configured with a focused system prompt for particular types of work
- **Have separate context** - They maintain their own conversation history, separate from your main chat
- **Use controlled tools** - You can configure which tools each subagent has access to
- **Work autonomously** - Once given a task, they work independently until completion or failure
- **Provide detailed feedback** - You can see their progress, tool usage, and execution statistics in real-time
## Key Benefits
- **Task Specialization**: Create agents optimized for specific workflows (testing, documentation, refactoring, etc.)
- **Context Isolation**: Keep specialized work separate from your main conversation
- **Reusability**: Save and reuse agent configurations across projects and sessions
- **Controlled Access**: Limit which tools each agent can use for security and focus
- **Progress Visibility**: Monitor agent execution with real-time progress updates
## How Subagents Work
1. **Configuration**: You create subagent configurations that define their behavior, tools, and system prompts
2. **Delegation**: The main AI can automatically delegate tasks to appropriate subagents
3. **Execution**: Subagents work independently, using their configured tools to complete tasks
4. **Results**: They return results and execution summaries back to the main conversation
## Getting Started
### Quick Start
1. **Create your first subagent**:
```
/agents create
```
Follow the guided wizard to create a specialized agent.
2. **Manage existing agents**:
```
/agents manage
```
View and manage your configured subagents.
3. **Use subagents automatically**:
Simply ask the main AI to perform tasks that match your subagents' specializations. The AI will automatically delegate appropriate work.
### Example Usage
```
User: "Please write comprehensive tests for the authentication module"
AI: I'll delegate this to your testing specialist subagent.
[Delegates to "testing-expert" subagent]
[Shows real-time progress of test creation]
[Returns with completed test files and execution summary]
```
## Management
### CLI Commands
Subagents are managed through the `/agents` slash command and its subcommands:
#### `/agents create`
Creates a new subagent through a guided step wizard.
**Usage:**
```
/agents create
```
#### `/agents manage`
Opens an interactive management dialog for viewing and managing existing subagents.
**Usage:**
```
/agents manage
```
### Storage Locations
Subagents are stored as Markdown files in two locations:
- **Project-level**: `.qwen/agents/` (takes precedence)
- **User-level**: `~/.qwen/agents/` (fallback)
This allows you to have both project-specific agents and personal agents that work across all projects.
### File Format
Subagents are configured using Markdown files with YAML frontmatter. This format is human-readable and easy to edit with any text editor.
#### Basic Structure
```markdown
---
name: agent-name
description: Brief description of when and how to use this agent
tools:
- tool1
- tool2
- tool3 # Optional
---
System prompt content goes here.
Multiple paragraphs are supported.
You can use ${variable} templating for dynamic content.
```
#### Example Usage
```markdown
---
name: project-documenter
description: Creates project documentation and README files
---
You are a documentation specialist for the ${project_name} project.
Your task: ${task_description}
Working directory: ${current_directory}
Generated on: ${timestamp}
Focus on creating clear, comprehensive documentation that helps both
new contributors and end users understand the project.
```
## Using Subagents Effectively
### Automatic Delegation
Qwen Code proactively delegates tasks based on:
- The task description in your request
- The description field in subagent configurations
- Current context and available tools
To encourage more proactive subagent use, include phrases like "use PROACTIVELY" or "MUST BE USED" in your description field.
### Explicit Invocation
Request a specific subagent by mentioning it in your command:
```
> Let the testing-expert subagent create unit tests for the payment module
> Have the documentation-writer subagent update the API reference
> Get the react-specialist subagent to optimize this component's performance
```
## Examples
### Development Workflow Agents
#### Testing Specialist
Perfect for comprehensive test creation and test-driven development.
```markdown
---
name: testing-expert
description: Writes comprehensive unit tests, integration tests, and handles test automation with best practices
tools:
- read_file
- write_file
- read_many_files
- run_shell_command
---
You are a testing specialist focused on creating high-quality, maintainable tests.
Your expertise includes:
- Unit testing with appropriate mocking and isolation
- Integration testing for component interactions
- Test-driven development practices
- Edge case identification and comprehensive coverage
- Performance and load testing when appropriate
For each testing task:
1. Analyze the code structure and dependencies
2. Identify key functionality, edge cases, and error conditions
3. Create comprehensive test suites with descriptive names
4. Include proper setup/teardown and meaningful assertions
5. Add comments explaining complex test scenarios
6. Ensure tests are maintainable and follow DRY principles
Always follow testing best practices for the detected language and framework.
Focus on both positive and negative test cases.
```
**Use Cases:**
- "Write unit tests for the authentication service"
- "Create integration tests for the payment processing workflow"
- "Add test coverage for edge cases in the data validation module"
#### Documentation Writer
Specialized in creating clear, comprehensive documentation.
```markdown
---
name: documentation-writer
description: Creates comprehensive documentation, README files, API docs, and user guides
tools:
- read_file
- write_file
- read_many_files
- web_search
---
You are a technical documentation specialist for ${project_name}.
Your role is to create clear, comprehensive documentation that serves both
developers and end users. Focus on:
**For API Documentation:**
- Clear endpoint descriptions with examples
- Parameter details with types and constraints
- Response format documentation
- Error code explanations
- Authentication requirements
**For User Documentation:**
- Step-by-step instructions with screenshots when helpful
- Installation and setup guides
- Configuration options and examples
- Troubleshooting sections for common issues
- FAQ sections based on common user questions
**For Developer Documentation:**
- Architecture overviews and design decisions
- Code examples that actually work
- Contributing guidelines
- Development environment setup
Always verify code examples and ensure documentation stays current with
the actual implementation. Use clear headings, bullet points, and examples.
```
**Use Cases:**
- "Create API documentation for the user management endpoints"
- "Write a comprehensive README for this project"
- "Document the deployment process with troubleshooting steps"
#### Code Reviewer
Focused on code quality, security, and best practices.
```markdown
---
name: code-reviewer
description: Reviews code for best practices, security issues, performance, and maintainability
tools:
- read_file
- read_many_files
---
You are an experienced code reviewer focused on quality, security, and maintainability.
Review criteria:
- **Code Structure**: Organization, modularity, and separation of concerns
- **Performance**: Algorithmic efficiency and resource usage
- **Security**: Vulnerability assessment and secure coding practices
- **Best Practices**: Language/framework-specific conventions
- **Error Handling**: Proper exception handling and edge case coverage
- **Readability**: Clear naming, comments, and code organization
- **Testing**: Test coverage and testability considerations
Provide constructive feedback with:
1. **Critical Issues**: Security vulnerabilities, major bugs
2. **Important Improvements**: Performance issues, design problems
3. **Minor Suggestions**: Style improvements, refactoring opportunities
4. **Positive Feedback**: Well-implemented patterns and good practices
Focus on actionable feedback with specific examples and suggested solutions.
Prioritize issues by impact and provide rationale for recommendations.
```
**Use Cases:**
- "Review this authentication implementation for security issues"
- "Check the performance implications of this database query logic"
- "Evaluate the code structure and suggest improvements"
### Technology-Specific Agents
#### React Specialist
Optimized for React development, hooks, and component patterns.
```markdown
---
name: react-specialist
description: Expert in React development, hooks, component patterns, and modern React best practices
tools:
- read_file
- write_file
- read_many_files
- run_shell_command
---
You are a React specialist with deep expertise in modern React development.
Your expertise covers:
- **Component Design**: Functional components, custom hooks, composition patterns
- **State Management**: useState, useReducer, Context API, and external libraries
- **Performance**: React.memo, useMemo, useCallback, code splitting
- **Testing**: React Testing Library, Jest, component testing strategies
- **TypeScript Integration**: Proper typing for props, hooks, and components
- **Modern Patterns**: Suspense, Error Boundaries, Concurrent Features
For React tasks:
1. Use functional components and hooks by default
2. Implement proper TypeScript typing
3. Follow React best practices and conventions
4. Consider performance implications
5. Include appropriate error handling
6. Write testable, maintainable code
Always stay current with React best practices and avoid deprecated patterns.
Focus on accessibility and user experience considerations.
```
**Use Cases:**
- "Create a reusable data table component with sorting and filtering"
- "Implement a custom hook for API data fetching with caching"
- "Refactor this class component to use modern React patterns"
#### Python Expert
Specialized in Python development, frameworks, and best practices.
```markdown
---
name: python-expert
description: Expert in Python development, frameworks, testing, and Python-specific best practices
tools:
- read_file
- write_file
- read_many_files
- run_shell_command
---
You are a Python expert with deep knowledge of the Python ecosystem.
Your expertise includes:
- **Core Python**: Pythonic patterns, data structures, algorithms
- **Frameworks**: Django, Flask, FastAPI, SQLAlchemy
- **Testing**: pytest, unittest, mocking, test-driven development
- **Data Science**: pandas, numpy, matplotlib, jupyter notebooks
- **Async Programming**: asyncio, async/await patterns
- **Package Management**: pip, poetry, virtual environments
- **Code Quality**: PEP 8, type hints, linting with pylint/flake8
For Python tasks:
1. Follow PEP 8 style guidelines
2. Use type hints for better code documentation
3. Implement proper error handling with specific exceptions
4. Write comprehensive docstrings
5. Consider performance and memory usage
6. Include appropriate logging
7. Write testable, modular code
Focus on writing clean, maintainable Python code that follows community standards.
```
**Use Cases:**
- "Create a FastAPI service for user authentication with JWT tokens"
- "Implement a data processing pipeline with pandas and error handling"
- "Write a CLI tool using argparse with comprehensive help documentation"
## Best Practices
### Design Principles
#### Single Responsibility Principle
Each subagent should have a clear, focused purpose.
**✅ Good:**
```markdown
---
name: testing-expert
description: Writes comprehensive unit tests and integration tests
---
```
**❌ Avoid:**
```markdown
---
name: general-helper
description: Helps with testing, documentation, code review, and deployment
---
```
**Why:** Focused agents produce better results and are easier to maintain.
#### Clear Specialization
Define specific expertise areas rather than broad capabilities.
**✅ Good:**
```markdown
---
name: react-performance-optimizer
description: Optimizes React applications for performance using profiling and best practices
---
```
**❌ Avoid:**
```markdown
---
name: frontend-developer
description: Works on frontend development tasks
---
```
**Why:** Specific expertise leads to more targeted and effective assistance.
#### Actionable Descriptions
Write descriptions that clearly indicate when to use the agent.
**✅ Good:**
```markdown
description: Reviews code for security vulnerabilities, performance issues, and maintainability concerns
```
**❌ Avoid:**
```markdown
description: A helpful code reviewer
```
**Why:** Clear descriptions help the main AI choose the right agent for each task.
### Configuration Best Practices
#### System Prompt Guidelines
**Be Specific About Expertise:**
```markdown
You are a Python testing specialist with expertise in:
- pytest framework and fixtures
- Mock objects and dependency injection
- Test-driven development practices
- Performance testing with pytest-benchmark
```
**Include Step-by-Step Approaches:**
```markdown
For each testing task:
1. Analyze the code structure and dependencies
2. Identify key functionality and edge cases
3. Create comprehensive test suites with clear naming
4. Include setup/teardown and proper assertions
5. Add comments explaining complex test scenarios
```
**Specify Output Standards:**
```markdown
Always follow these standards:
- Use descriptive test names that explain the scenario
- Include both positive and negative test cases
- Add docstrings for complex test functions
- Ensure tests are independent and can run in any order
```
## Security Considerations
- **Tool Restrictions**: Subagents only have access to their configured tools
- **Sandboxing**: All tool execution follows the same security model as direct tool use
- **Audit Trail**: All subagent actions are logged and visible in real-time
- **Access Control**: Project and user-level separation provides appropriate boundaries
- **Sensitive Information**: Avoid including secrets or credentials in agent configurations
- **Production Environments**: Consider separate agents for production vs development environments

View File

@@ -0,0 +1,14 @@
# Token Caching and Cost Optimization
Qwen Code automatically optimizes API costs through token caching when using API key authentication (e.g., OpenAI-compatible providers). This feature reuses previous system instructions and context to reduce the number of tokens processed in subsequent requests.
**Token caching is available for:**
- API key users (Qwen API key)
- Vertex AI users (with project and location setup)
**Token caching is not available for:**
- OAuth users (Google Personal/Enterprise accounts) - the Code Assist API does not support cached content creation at this time
You can view your token usage and cached token savings using the `/stats` command. When cached tokens are available, they will be displayed in the stats output.

View File

@@ -0,0 +1,133 @@
# Welcome Back Feature
The Welcome Back feature helps you seamlessly resume your work by automatically detecting when you return to a project with existing conversation history and offering to continue from where you left off.
## Overview
When you start Qwen Code in a project directory that contains a previously generated project summary (`.qwen/PROJECT_SUMMARY.md`), the Welcome Back dialog will automatically appear, giving you the option to either start fresh or continue your previous conversation.
## How It Works
### Automatic Detection
The Welcome Back feature automatically detects:
- **Project Summary File:** Looks for `.qwen/PROJECT_SUMMARY.md` in your current project directory
- **Conversation History:** Checks if there's meaningful conversation history to resume
- **Settings:** Respects your `enableWelcomeBack` setting (enabled by default)
### Welcome Back Dialog
When a project summary is found, you'll see a dialog with:
- **Last Updated Time:** Shows when the summary was last generated
- **Overall Goal:** Displays the main objective from your previous session
- **Current Plan:** Shows task progress with status indicators:
- `[DONE]` - Completed tasks
- `[IN PROGRESS]` - Currently working on
- `[TODO]` - Planned tasks
- **Task Statistics:** Summary of total tasks, completed, in progress, and pending
### Options
You have two choices when the Welcome Back dialog appears:
1. **Start new chat session**
- Closes the dialog and begins a fresh conversation
- No previous context is loaded
2. **Continue previous conversation**
- Automatically fills the input with: `@.qwen/PROJECT_SUMMARY.md, Based on our previous conversation, Let's continue?`
- Loads the project summary as context for the AI
- Allows you to seamlessly pick up where you left off
## Configuration
### Enable/Disable Welcome Back
You can control the Welcome Back feature through settings:
**Via Settings Dialog:**
1. Run `/settings` in Qwen Code
2. Find "Enable Welcome Back" in the UI category
3. Toggle the setting on/off
**Via Settings File:**
Add to your `.qwen/settings.json`:
```json
{
"enableWelcomeBack": true
}
```
**Settings Locations:**
- **User settings:** `~/.qwen/settings.json` (affects all projects)
- **Project settings:** `.qwen/settings.json` (project-specific)
### Keyboard Shortcuts
- **Escape:** Close the Welcome Back dialog (defaults to "Start new chat session")
## Integration with Other Features
### Project Summary Generation
The Welcome Back feature works seamlessly with the `/summary` command:
1. **Generate Summary:** Use `/summary` to create a project summary
2. **Automatic Detection:** Next time you start Qwen Code in this project, Welcome Back will detect the summary
3. **Resume Work:** Choose to continue and the summary will be loaded as context
### Quit Confirmation
When exiting with `/quit-confirm` and choosing "Generate summary and quit":
1. A project summary is automatically created
2. Next session will trigger the Welcome Back dialog
3. You can seamlessly continue your work
## File Structure
The Welcome Back feature creates and uses:
```
your-project/
├── .qwen/
│ └── PROJECT_SUMMARY.md # Generated project summary
```
### PROJECT_SUMMARY.md Format
The generated summary follows this structure:
```markdown
# Project Summary
## Overall Goal
<!-- Single, concise sentence describing the high-level objective -->
## Key Knowledge
<!-- Crucial facts, conventions, and constraints -->
<!-- Includes: technology choices, architecture decisions, user preferences -->
## Recent Actions
<!-- Summary of significant recent work and outcomes -->
<!-- Includes: accomplishments, discoveries, recent changes -->
## Current Plan
<!-- The current development roadmap and next steps -->
<!-- Uses status markers: [DONE], [IN PROGRESS], [TODO] -->
---
## Summary Metadata
**Update time**: 2025-01-10T15:30:00.000Z
```