mirror of
https://github.com/QwenLM/qwen-code.git
synced 2025-12-23 18:19:15 +00:00
Compare commits
136 Commits
v0.0.7
...
release/v0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
20ca30a08e | ||
|
|
cd5e592b6a | ||
|
|
a815ff9425 | ||
|
|
64ce8c1d1e | ||
|
|
9a28f04ace | ||
|
|
201b476a3e | ||
|
|
1cf23c34e7 | ||
|
|
a7c8c4c2fa | ||
|
|
0ffd7c06d7 | ||
|
|
12d43589be | ||
|
|
1be10c1186 | ||
|
|
50dc2f0bf5 | ||
|
|
e0f6d6be41 | ||
|
|
2f2a2e05e7 | ||
|
|
8833a112a9 | ||
|
|
d933795d8e | ||
|
|
8caa0542c4 | ||
|
|
c8f3b15971 | ||
|
|
2fcacb70b9 | ||
|
|
a0a1d6e253 | ||
|
|
0de3236076 | ||
|
|
303b6999f4 | ||
|
|
93f5e59710 | ||
|
|
7b378e826c | ||
|
|
a19db16485 | ||
|
|
7dbc240847 | ||
|
|
5e70b34041 | ||
|
|
df1479f864 | ||
|
|
5349c4d02b | ||
|
|
67c6033147 | ||
|
|
5d1d40fa2e | ||
|
|
804c181ac4 | ||
|
|
2d1a6af890 | ||
|
|
f9efb2e24f | ||
|
|
d8fec54e81 | ||
|
|
26fe587b44 | ||
|
|
d9fb08c9da | ||
|
|
f52d073dfb | ||
|
|
c7fd4c4a96 | ||
|
|
94b6199943 | ||
|
|
c0f5f6a5f6 | ||
|
|
0e98641b51 | ||
|
|
4656f17524 | ||
|
|
110e00178b | ||
|
|
72832fb889 | ||
|
|
6390b81646 | ||
|
|
239ba63d28 | ||
|
|
2269f8a1a8 | ||
|
|
aa5c80dec4 | ||
|
|
b0b12af2ce | ||
|
|
8dd6f04199 | ||
|
|
2548facc79 | ||
|
|
2865a52778 | ||
|
|
0e44bbc85d | ||
|
|
0157eae3d7 | ||
|
|
8a9a927544 | ||
|
|
c632ec8b03 | ||
|
|
0dea7233b6 | ||
|
|
34434cd4aa | ||
|
|
6b19c8bd55 | ||
|
|
b8084ba815 | ||
|
|
6487cc1689 | ||
|
|
191cc01bf5 | ||
|
|
c184ec3224 | ||
|
|
f35921a771 | ||
|
|
c03ae43777 | ||
|
|
69322e12e4 | ||
|
|
9ac62565a0 | ||
|
|
344ee29f77 | ||
|
|
60bde58f29 | ||
|
|
34b5dc7f28 | ||
|
|
3af4913ef3 | ||
|
|
5ec4ea9b4d | ||
|
|
407393b128 | ||
|
|
51d09e720b | ||
|
|
f5e0f16157 | ||
|
|
5ab184fcaf | ||
|
|
86eaa03f8a | ||
|
|
e50d886ba8 | ||
|
|
e8815ba43c | ||
|
|
bae922a632 | ||
|
|
60362e0329 | ||
|
|
494a10e7a7 | ||
|
|
785ee5d59a | ||
|
|
4f2974dbfe | ||
|
|
65e4b941ee | ||
|
|
9bc0a4aff3 | ||
|
|
0c32a4061d | ||
|
|
9fc7115b86 | ||
|
|
c38147a3a6 | ||
|
|
908ce2be33 | ||
|
|
f1663d9615 | ||
|
|
4d4eacfc40 | ||
|
|
19491b7b94 | ||
|
|
53f8617b24 | ||
|
|
3a3b138195 | ||
|
|
8e6a565adb | ||
|
|
a3351bc985 | ||
|
|
7596481a9d | ||
|
|
8bac9e7d04 | ||
|
|
0d65baf928 | ||
|
|
8d848dca4a | ||
|
|
6ae75c9f32 | ||
|
|
36750ca49b | ||
|
|
d6a7334279 | ||
|
|
99f88851fb | ||
|
|
01f7c4b740 | ||
|
|
9ac3e8b79e | ||
|
|
4782113ceb | ||
|
|
626844b539 | ||
|
|
5cd63a6abc | ||
|
|
b55467c1dd | ||
|
|
43510ed212 | ||
|
|
ad5d2af4e3 | ||
|
|
e3e7677753 | ||
|
|
b3cfaeb6d3 | ||
|
|
024b8207eb | ||
|
|
1fb680bacc | ||
|
|
1f0ad86544 | ||
|
|
6133bea388 | ||
|
|
882a97aff9 | ||
|
|
fde9849d48 | ||
|
|
487818df27 | ||
|
|
ca4c745e3b | ||
|
|
b38f377c9a | ||
|
|
aab850668c | ||
|
|
8b1d5a2e3c | ||
|
|
a0990380b5 | ||
|
|
2fcaa302da | ||
|
|
7fa2d7be17 | ||
|
|
be3aabaea6 | ||
|
|
b87b436ebc | ||
|
|
7e5a5e2da7 | ||
|
|
9db5aab498 | ||
|
|
390edb5e0a | ||
|
|
a5a3da01f6 |
8
.github/workflows/ci.yml
vendored
8
.github/workflows/ci.yml
vendored
@@ -36,6 +36,14 @@ jobs:
|
||||
- name: Run linter
|
||||
run: npm run lint:ci
|
||||
|
||||
- name: Run linter on integration tests
|
||||
run: npx eslint integration-tests --max-warnings 0
|
||||
|
||||
- name: Run formatter on integration tests
|
||||
run: |
|
||||
npx prettier --check integration-tests
|
||||
git diff --exit-code
|
||||
|
||||
- name: Build project
|
||||
run: npm run build
|
||||
|
||||
|
||||
@@ -2,19 +2,38 @@ name: Qwen Automated Issue Triage
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened, reopened]
|
||||
types:
|
||||
- 'opened'
|
||||
- 'reopened'
|
||||
issue_comment:
|
||||
types:
|
||||
- 'created'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
issue_number:
|
||||
description: 'issue number to triage'
|
||||
required: true
|
||||
type: 'number'
|
||||
|
||||
concurrency:
|
||||
group: '${{ github.workflow }}-${{ github.event.issue.number }}'
|
||||
cancel-in-progress: true
|
||||
|
||||
defaults:
|
||||
run:
|
||||
shell: 'bash'
|
||||
|
||||
permissions:
|
||||
contents: 'read'
|
||||
id-token: 'write'
|
||||
issues: 'write'
|
||||
statuses: 'write'
|
||||
packages: 'read'
|
||||
|
||||
jobs:
|
||||
triage-issue:
|
||||
timeout-minutes: 5
|
||||
if: ${{ github.repository == 'QwenLM/qwen-code' }}
|
||||
permissions:
|
||||
issues: write
|
||||
contents: read
|
||||
id-token: write
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.issue.number }}
|
||||
cancel-in-progress: true
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Run Qwen Issue Triage
|
||||
@@ -24,34 +43,44 @@ jobs:
|
||||
ISSUE_TITLE: ${{ github.event.issue.title }}
|
||||
ISSUE_BODY: ${{ github.event.issue.body }}
|
||||
with:
|
||||
version: 0.0.6
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
OPENAI_BASE_URL: ${{ secrets.OPENAI_BASE_URL }}
|
||||
OPENAI_MODEL: ${{ secrets.OPENAI_MODEL }}
|
||||
settings_json: |
|
||||
{
|
||||
"maxSessionTurns": 25,
|
||||
"coreTools": [
|
||||
"run_shell_command(echo)",
|
||||
"run_shell_command(gh label list)",
|
||||
"run_shell_command(gh issue edit)",
|
||||
"run_shell_command(gh issue list)"
|
||||
],
|
||||
"sandbox": false
|
||||
}
|
||||
prompt: |
|
||||
You are an issue triage assistant. Analyze the current GitHub issues apply the most appropriate existing labels. Do not remove labels titled help wanted or good first issue.
|
||||
Steps:
|
||||
prompt: |-
|
||||
## Role
|
||||
|
||||
You are an issue triage assistant. Analyze the current GitHub issue and apply the most appropriate existing labels. Use the available
|
||||
tools to gather information; do not ask for information to be provided. Do not remove labels titled help wanted or good first issue.
|
||||
|
||||
## Steps
|
||||
|
||||
1. Run: `gh label list --repo ${{ github.repository }} --limit 100` to get all available labels.
|
||||
2. Review the issue title, body and any comments provided in the environment variables.
|
||||
2. Use right tool to review the issue title and body provided in the environment variables: "${ISSUE_TITLE}" and "${ISSUE_BODY}".
|
||||
3. Ignore any existing priorities or tags on the issue. Just report your findings.
|
||||
4. Select the most relevant labels from the existing labels, focusing on kind/*, area/*, sub-area/* and priority/*. For area/* and kind/* limit yourself to only the single most applicable label in each case.
|
||||
6. Apply the selected labels to this issue using: `gh issue edit ${{ github.event.issue.number }} --repo ${{ github.repository }} --add-label "label1,label2"`
|
||||
7. For each issue please check if CLI version is present, this is usually in the output of the /about command and will look like 0.1.5 for anything more than 6 versions older than the most recent should add the status/need-retesting label
|
||||
8. If you see that the issue doesn’t look like it has sufficient information recommend the status/need-information label
|
||||
9. Use Area definitions mentioned below to help you narrow down issues
|
||||
Guidelines:
|
||||
6. Apply the selected labels to this issue using: `gh issue edit ${{ github.event.issue.number }} --repo ${{ github.repository }} --add-label "label1,label2"`.
|
||||
7. For each issue please check if CLI version is present, this is usually in the output of the /about command and will look like 0.1.5 for anything more than 6 versions older than the most recent should add the status/need-retesting label.
|
||||
8. If you see that the issue doesn’t look like it has sufficient information recommend the status/need-information label.
|
||||
9. Use Area definitions mentioned below to help you narrow down issues.
|
||||
|
||||
## Guidelines
|
||||
|
||||
- Only use labels that already exist in the repository.
|
||||
- Do not add comments or modify the issue content.
|
||||
- Triage only the current issue.
|
||||
- Apply only one area/ label
|
||||
- Apply only one kind/ label
|
||||
- Apply only one area/ label.
|
||||
- Apply only one kind/ label.
|
||||
- Apply all applicable sub-area/* and priority/* labels based on the issue content. It's ok to have multiple of these.
|
||||
- Once you categorize the issue if it needs information bump down the priority by 1 eg.. a p0 would become a p1 a p1 would become a p2. P2 and P3 can stay as is in this scenario.
|
||||
Categorization Guidelines:
|
||||
@@ -130,3 +159,17 @@ jobs:
|
||||
- could also pertain to latency,
|
||||
- other general software performance like, memory usage, CPU consumption, and algorithmic efficiency.
|
||||
- Switching models from one to the other unexpectedly.
|
||||
|
||||
- name: 'Post Issue Triage Failure Comment'
|
||||
if: |-
|
||||
${{ failure() && steps.gemini_issue_triage.outcome == 'failure' }}
|
||||
uses: 'actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea'
|
||||
with:
|
||||
github-token: '${{ steps.generate_token.outputs.token }}'
|
||||
script: |-
|
||||
github.rest.issues.createComment({
|
||||
owner: '${{ github.repository }}'.split('/')[0],
|
||||
repo: '${{ github.repository }}'.split('/')[1],
|
||||
issue_number: '${{ github.event.issue.number }}',
|
||||
body: 'There is a problem with the Qwen Code issue triaging. Please check the [action logs](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) for details.'
|
||||
})
|
||||
|
||||
@@ -3,7 +3,22 @@ name: Qwen Scheduled Issue Triage
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 * * * *' # Runs every hour
|
||||
workflow_dispatch: {}
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: '${{ github.workflow }}'
|
||||
cancel-in-progress: true
|
||||
|
||||
defaults:
|
||||
run:
|
||||
shell: 'bash'
|
||||
|
||||
permissions:
|
||||
contents: 'read'
|
||||
id-token: 'write'
|
||||
issues: 'write'
|
||||
statuses: 'write'
|
||||
packages: 'read'
|
||||
|
||||
jobs:
|
||||
triage-issues:
|
||||
@@ -23,16 +38,19 @@ jobs:
|
||||
echo "🔍 Finding issues without labels..."
|
||||
NO_LABEL_ISSUES=$(gh issue list --repo ${{ github.repository }} --search "is:open is:issue no:label" --json number,title,body)
|
||||
|
||||
echo "🏷️ Finding issues that need triage..."
|
||||
NEED_TRIAGE_ISSUES=$(gh issue list --repo ${{ github.repository }} --search "is:open is:issue label:\"status/need-triage\"" --json number,title,body)
|
||||
echo '🔍 Finding issues without labels...'
|
||||
NO_LABEL_ISSUES="$(gh issue list --repo "${GITHUB_REPOSITORY}" \
|
||||
--search 'is:open is:issue no:label' --json number,title,body)"
|
||||
|
||||
echo "🔄 Merging and deduplicating issues..."
|
||||
ISSUES=$(echo "$NO_LABEL_ISSUES" "$NEED_TRIAGE_ISSUES" | jq -c -s 'add | unique_by(.number)')
|
||||
echo '🏷️ Finding issues that need triage...'
|
||||
NEED_TRIAGE_ISSUES="$(gh issue list --repo "${GITHUB_REPOSITORY}" \
|
||||
--search 'is:open is:issue label:"status/needs-triage"' --json number,title,body)"
|
||||
|
||||
echo "📝 Setting output for GitHub Actions..."
|
||||
echo "issues_to_triage=$ISSUES" >> "$GITHUB_OUTPUT"
|
||||
echo '🔄 Merging and deduplicating issues...'
|
||||
ISSUES="$(echo "${NO_LABEL_ISSUES}" "${NEED_TRIAGE_ISSUES}" | jq -c -s 'add | unique_by(.number)')"
|
||||
|
||||
echo "✅ Found $(echo "$ISSUES" | jq 'length') issues to triage! 🎯"
|
||||
echo '📝 Setting output for GitHub Actions...'
|
||||
echo "issues_to_triage=${ISSUES}" >> "${GITHUB_OUTPUT}"
|
||||
|
||||
- name: Run Qwen Issue Triage
|
||||
if: steps.find_issues.outputs.issues_to_triage != '[]'
|
||||
@@ -42,26 +60,32 @@ jobs:
|
||||
ISSUES_TO_TRIAGE: ${{ steps.find_issues.outputs.issues_to_triage }}
|
||||
REPOSITORY: ${{ github.repository }}
|
||||
with:
|
||||
version: 0.0.6
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
OPENAI_BASE_URL: ${{ secrets.OPENAI_BASE_URL }}
|
||||
OPENAI_MODEL: ${{ secrets.OPENAI_MODEL }}
|
||||
settings_json: |
|
||||
{
|
||||
"maxSessionTurns": 25,
|
||||
"coreTools": [
|
||||
"run_shell_command(echo)",
|
||||
"run_shell_command(gh label list)",
|
||||
"run_shell_command(gh issue edit)",
|
||||
"run_shell_command(gh issue list)",
|
||||
"run_shell_command(gh issue view)"
|
||||
"run_shell_command(gh issue view)",
|
||||
"run_shell_command(gh issue list)"
|
||||
],
|
||||
"sandbox": false
|
||||
}
|
||||
prompt: |
|
||||
You are an issue triage assistant. Analyze the current GitHub issues apply the most appropriate existing labels.
|
||||
Steps:
|
||||
prompt: |-
|
||||
## Role
|
||||
|
||||
You are an issue triage assistant. Analyze issues and apply
|
||||
appropriate labels. Use the available tools to gather information;
|
||||
do not ask for information to be provided.
|
||||
|
||||
## Steps
|
||||
|
||||
1. Run: `gh label list --repo ${{ github.repository }} --limit 100` to get all available labels.
|
||||
2. Check environment variable for issues to triage: $ISSUES_TO_TRIAGE (JSON array of issues)
|
||||
2. Use right tool to check environment variable for issues to triage: $ISSUES_TO_TRIAGE (JSON array of issues)
|
||||
3. Review the issue title, body and any comments provided in the environment variables.
|
||||
4. Ignore any existing priorities or tags on the issue.
|
||||
5. Select the most relevant labels from the existing labels, focusing on kind/*, area/*, sub-area/* and priority/*.
|
||||
@@ -84,8 +108,10 @@ jobs:
|
||||
- After applying appropriate labels to an issue, remove the "status/need-triage" label if present: `gh issue edit ISSUE_NUMBER --repo ${{ github.repository }} --remove-label "status/need-triage"`
|
||||
- Execute one `gh issue edit` command per issue, wait for success before proceeding to the next
|
||||
Process each issue sequentially and confirm each labeling operation before moving to the next issue.
|
||||
Guidelines:
|
||||
- Only use labels that already exist in the repository.
|
||||
|
||||
## Guidelines
|
||||
|
||||
- Only use labels that already exist in the repository.
|
||||
- Do not add comments or modify the issue content.
|
||||
- Do not remove labels titled help wanted or good first issue.
|
||||
- Triage only the current issue.
|
||||
|
||||
24
.github/workflows/release.yml
vendored
24
.github/workflows/release.yml
vendored
@@ -84,6 +84,11 @@ jobs:
|
||||
echo "RELEASE_TAG=$(echo $VERSION_JSON | jq -r .releaseTag)" >> $GITHUB_OUTPUT
|
||||
echo "RELEASE_VERSION=$(echo $VERSION_JSON | jq -r .releaseVersion)" >> $GITHUB_OUTPUT
|
||||
echo "NPM_TAG=$(echo $VERSION_JSON | jq -r .npmTag)" >> $GITHUB_OUTPUT
|
||||
|
||||
# Get the previous tag for release notes generation
|
||||
CURRENT_TAG=$(echo $VERSION_JSON | jq -r .releaseTag)
|
||||
PREVIOUS_TAG=$(node scripts/get-previous-tag.js "$CURRENT_TAG" || echo "")
|
||||
echo "PREVIOUS_TAG=${PREVIOUS_TAG}" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
IS_NIGHTLY: ${{ steps.vars.outputs.is_nightly }}
|
||||
MANUAL_VERSION: ${{ inputs.version }}
|
||||
@@ -158,11 +163,20 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
RELEASE_BRANCH: ${{ steps.release_branch.outputs.BRANCH_NAME }}
|
||||
run: |
|
||||
gh release create ${{ steps.version.outputs.RELEASE_TAG }} \
|
||||
bundle/gemini.js \
|
||||
--target "$RELEASE_BRANCH" \
|
||||
--title "Release ${{ steps.version.outputs.RELEASE_TAG }}" \
|
||||
--generate-notes
|
||||
# Build the gh release create command with appropriate options
|
||||
RELEASE_CMD="gh release create ${{ steps.version.outputs.RELEASE_TAG }} bundle/gemini.js --target \"$RELEASE_BRANCH\" --title \"Release ${{ steps.version.outputs.RELEASE_TAG }}\""
|
||||
|
||||
# Add previous tag for release notes if available
|
||||
if [[ -n "${{ steps.version.outputs.PREVIOUS_TAG }}" ]]; then
|
||||
echo "Generating release notes from previous tag: ${{ steps.version.outputs.PREVIOUS_TAG }}"
|
||||
RELEASE_CMD="$RELEASE_CMD --generate-notes --notes-start-tag ${{ steps.version.outputs.PREVIOUS_TAG }}"
|
||||
else
|
||||
echo "No previous tag found, generating release notes from repository history"
|
||||
RELEASE_CMD="$RELEASE_CMD --generate-notes"
|
||||
fi
|
||||
|
||||
# Execute the release command
|
||||
eval $RELEASE_CMD
|
||||
|
||||
- name: Create Issue on Failure
|
||||
if: failure()
|
||||
|
||||
3
.vscode/extensions.json
vendored
Normal file
3
.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"recommendations": ["vitest.explorer", "esbenp.prettier-vscode"]
|
||||
}
|
||||
15
.vscode/settings.json
vendored
15
.vscode/settings.json
vendored
@@ -1,3 +1,16 @@
|
||||
{
|
||||
"typescript.tsserver.experimental.enableProjectDiagnostics": true
|
||||
"typescript.tsserver.experimental.enableProjectDiagnostics": true,
|
||||
"editor.tabSize": 2,
|
||||
"editor.rulers": [80],
|
||||
"editor.detectIndentation": false,
|
||||
"editor.insertSpaces": true,
|
||||
"[typescript]": {
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
},
|
||||
"[json]": {
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
},
|
||||
"[javascript]": {
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
}
|
||||
}
|
||||
|
||||
26
CHANGELOG.md
Normal file
26
CHANGELOG.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# Changelog
|
||||
|
||||
## 0.0.7
|
||||
|
||||
- Fix MCP tools
|
||||
- Fix Web Fetch tool
|
||||
- Fix Web Search tool, by replacing web search from Google/Gemini to Tavily API
|
||||
- Fix: Compatible with occasional tool call parameters returned by LLM that are invalid JSON
|
||||
- Fix: prevent concurrent query submissions on some rare cases
|
||||
- Fix: incorrect qwen logger exit handler setup
|
||||
- Fix: seperate static QR code and dynamic spin components
|
||||
- Sync gemini-cli to v0.1.18
|
||||
|
||||
## 0.0.6
|
||||
|
||||
- Add usage statistics logging for Qwen integration
|
||||
- Make `/init` command respect configured context filename and align docs with QWEN.md
|
||||
- Fix EPERM error when run `qwen --sandbox` in macOS
|
||||
- Fix terminal flicker when waiting for login
|
||||
- Fix `glm-4.5` model request error
|
||||
|
||||
## 0.0.5
|
||||
|
||||
- Support Qwen OAuth login and provide up to 2000 free requests per day
|
||||
- Sync gemini-cli to v0.1.17
|
||||
- Add systemPromptMappings Configuration Feature
|
||||
14
README.md
14
README.md
@@ -15,6 +15,20 @@
|
||||
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
|
||||
<!-- Keep these links. Translations will automatically update with the README. -->
|
||||
<a href="https://readme-i18n.com/de/QwenLM/qwen-code">Deutsch</a> |
|
||||
<a href="https://readme-i18n.com/es/QwenLM/qwen-code">Español</a> |
|
||||
<a href="https://readme-i18n.com/fr/QwenLM/qwen-code">français</a> |
|
||||
<a href="https://readme-i18n.com/ja/QwenLM/qwen-code">日本語</a> |
|
||||
<a href="https://readme-i18n.com/ko/QwenLM/qwen-code">한국어</a> |
|
||||
<a href="https://readme-i18n.com/pt/QwenLM/qwen-code">Português</a> |
|
||||
<a href="https://readme-i18n.com/ru/QwenLM/qwen-code">Русский</a> |
|
||||
<a href="https://readme-i18n.com/zh/QwenLM/qwen-code">中文</a>
|
||||
|
||||
</div>
|
||||
|
||||
Qwen Code is a powerful command-line AI workflow tool adapted from [**Gemini CLI**](https://github.com/google-gemini/gemini-cli) ([details](./README.gemini.md)), specifically optimized for [Qwen3-Coder](https://github.com/QwenLM/Qwen3-Coder) models. It enhances your development workflow with advanced code understanding, automated tasks, and intelligent assistance.
|
||||
|
||||
## 💡 Free Options Available
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
# Reporting Security Issues
|
||||
|
||||
To report a security issue, please use [https://g.co/vulnz](https://g.co/vulnz).
|
||||
We use g.co/vulnz for our intake, and do coordination and disclosure here on
|
||||
GitHub (including using GitHub Security Advisory). The Google Security Team will
|
||||
respond within 5 working days of your report on g.co/vulnz.
|
||||
Please report any security issue or Higress crash report to [ASRC](https://security.alibaba.com/) (Alibaba Security Response Center) where the issue will be triaged appropriately.
|
||||
|
||||
[GitHub Security Advisory]: https://github.com/google-gemini/gemini-cli/security/advisories
|
||||
Thank you for helping keep our project secure.
|
||||
|
||||
@@ -33,10 +33,10 @@ Remove-Item -Path (Join-Path $env:LocalAppData "npm-cache\_npx") -Recurse -Force
|
||||
|
||||
## Method 2: Using npm (Global Install)
|
||||
|
||||
If you installed the CLI globally (e.g., `npm install -g @google/gemini-cli`), use the `npm uninstall` command with the `-g` flag to remove it.
|
||||
If you installed the CLI globally (e.g., `npm install -g @qwen-code/qwen-code`), use the `npm uninstall` command with the `-g` flag to remove it.
|
||||
|
||||
```bash
|
||||
npm uninstall -g @google/gemini-cli
|
||||
npm uninstall -g @qwen-code/qwen-code
|
||||
```
|
||||
|
||||
This command completely removes the package from your system.
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# Gemini CLI Architecture Overview
|
||||
# Qwen Code Architecture Overview
|
||||
|
||||
This document provides a high-level overview of the Gemini CLI's architecture.
|
||||
This document provides a high-level overview of Qwen Code's architecture.
|
||||
|
||||
## Core components
|
||||
|
||||
The Gemini CLI is primarily composed of two main packages, along with a suite of tools that can be used by the system in the course of handling command-line input:
|
||||
Qwen Code is primarily composed of two main packages, along with a suite of tools that can be used by the system in the course of handling command-line input:
|
||||
|
||||
1. **CLI package (`packages/cli`):**
|
||||
- **Purpose:** This contains the user-facing portion of the Gemini CLI, such as handling the initial user input, presenting the final output, and managing the overall user experience.
|
||||
- **Purpose:** This contains the user-facing portion of Qwen Code, such as handling the initial user input, presenting the final output, and managing the overall user experience.
|
||||
- **Key functions contained in the package:**
|
||||
- [Input processing](./cli/commands.md)
|
||||
- History management
|
||||
@@ -16,7 +16,7 @@ The Gemini CLI is primarily composed of two main packages, along with a suite of
|
||||
- [CLI configuration settings](./cli/configuration.md)
|
||||
|
||||
2. **Core package (`packages/core`):**
|
||||
- **Purpose:** This acts as the backend for the Gemini CLI. It receives requests sent from `packages/cli`, orchestrates interactions with the Gemini API, and manages the execution of available tools.
|
||||
- **Purpose:** This acts as the backend for Qwen Code. It receives requests sent from `packages/cli`, orchestrates interactions with the configured model API, and manages the execution of available tools.
|
||||
- **Key functions contained in the package:**
|
||||
- API client for communicating with the Google Gemini API
|
||||
- Prompt construction and management
|
||||
@@ -30,20 +30,20 @@ The Gemini CLI is primarily composed of two main packages, along with a suite of
|
||||
|
||||
## Interaction Flow
|
||||
|
||||
A typical interaction with the Gemini CLI follows this flow:
|
||||
A typical interaction with Qwen Code follows this flow:
|
||||
|
||||
1. **User input:** The user types a prompt or command into the terminal, which is managed by `packages/cli`.
|
||||
2. **Request to core:** `packages/cli` sends the user's input to `packages/core`.
|
||||
3. **Request processed:** The core package:
|
||||
- Constructs an appropriate prompt for the Gemini API, possibly including conversation history and available tool definitions.
|
||||
- Sends the prompt to the Gemini API.
|
||||
4. **Gemini API response:** The Gemini API processes the prompt and returns a response. This response might be a direct answer or a request to use one of the available tools.
|
||||
- Constructs an appropriate prompt for the configured model API, possibly including conversation history and available tool definitions.
|
||||
- Sends the prompt to the model API.
|
||||
4. **Model API response:** The model API processes the prompt and returns a response. This response might be a direct answer or a request to use one of the available tools.
|
||||
5. **Tool execution (if applicable):**
|
||||
- When the Gemini API requests a tool, the core package prepares to execute it.
|
||||
- When the model API requests a tool, the core package prepares to execute it.
|
||||
- If the requested tool can modify the file system or execute shell commands, the user is first given details of the tool and its arguments, and the user must approve the execution.
|
||||
- Read-only operations, such as reading files, might not require explicit user confirmation to proceed.
|
||||
- Once confirmed, or if confirmation is not required, the core package executes the relevant action within the relevant tool, and the result is sent back to the Gemini API by the core package.
|
||||
- The Gemini API processes the tool result and generates a final response.
|
||||
- Once confirmed, or if confirmation is not required, the core package executes the relevant action within the relevant tool, and the result is sent back to the model API by the core package.
|
||||
- The model API processes the tool result and generates a final response.
|
||||
6. **Response to CLI:** The core package sends the final response back to the CLI package.
|
||||
7. **Display to user:** The CLI package formats and displays the response to the user in the terminal.
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# Checkpointing
|
||||
|
||||
The Gemini CLI 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.
|
||||
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 `replace`), 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 (`~/.gemini/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.
|
||||
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.
|
||||
|
||||
@@ -16,7 +16,7 @@ If you want to undo the change or simply go back, you can use the `/restore` com
|
||||
- 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 `~/.gemini/tmp/<project_hash>/checkpoints`.
|
||||
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
|
||||
|
||||
@@ -24,10 +24,10 @@ The Checkpointing feature is disabled by default. To enable it, you can either u
|
||||
|
||||
### Using the Command-Line Flag
|
||||
|
||||
You can enable checkpointing for the current session by using the `--checkpointing` flag when starting the Gemini CLI:
|
||||
You can enable checkpointing for the current session by using the `--checkpointing` flag when starting Qwen Code:
|
||||
|
||||
```bash
|
||||
gemini --checkpointing
|
||||
qwen --checkpointing
|
||||
```
|
||||
|
||||
### Using the `settings.json` File
|
||||
|
||||
@@ -99,6 +99,11 @@ Slash commands provide meta-level control over the CLI itself.
|
||||
- **Usage:** `/restore [tool_call_id]`
|
||||
- **Note:** Only available if the CLI is invoked with the `--checkpointing` option or configured via [settings](./configuration.md). See [Checkpointing documentation](../checkpointing.md) for more details.
|
||||
|
||||
- **`/settings`**
|
||||
- **Description:** Open the settings editor to view and modify Qwen Code settings.
|
||||
- **Details:** This command provides a user-friendly interface for changing settings that control the behavior and appearance of Qwen Code. It is equivalent to manually editing the `.qwen/settings.json` file, but with validation and guidance to prevent errors.
|
||||
- **Usage:** Simply run `/settings` and the editor will open. You can then browse or search for specific settings, view their current values, and modify them as desired. Changes to some settings are applied immediately, while others require a restart.
|
||||
|
||||
- **`/stats`**
|
||||
- **Description:** Display detailed statistics for the current Qwen Code session, including token usage, cached token savings (when available), and session duration. Note: Cached token information is only displayed when cached tokens are being used, which occurs with API key authentication but not with OAuth authentication at this time.
|
||||
|
||||
@@ -133,7 +138,7 @@ Slash commands provide meta-level control over the CLI itself.
|
||||
- **Editing commands:** Delete with `x`, change with `c`, insert with `i`, `a`, `o`, `O`; complex operations like `dd`, `cc`, `dw`, `cw`
|
||||
- **Count support:** Prefix commands with numbers (e.g., `3h`, `5w`, `10G`)
|
||||
- **Repeat last command:** Use `.` to repeat the last editing operation
|
||||
- **Persistent setting:** Vim mode preference is saved to `~/.gemini/settings.json` and restored between sessions
|
||||
- **Persistent setting:** Vim mode preference is saved to `~/.qwen/settings.json` and restored between sessions
|
||||
- **Status indicator:** When enabled, shows `[NORMAL]` or `[INSERT]` in the footer
|
||||
|
||||
- **`/init`**
|
||||
@@ -143,14 +148,14 @@ Slash commands provide meta-level control over the CLI itself.
|
||||
|
||||
For a quick start, see the [example](#example-a-pure-function-refactoring-command) below.
|
||||
|
||||
Custom commands allow you to save and reuse your favorite or most frequently used prompts as personal shortcuts within Gemini CLI. You can create commands that are specific to a single project or commands that are available globally across all your projects, streamlining your workflow and ensuring consistency.
|
||||
Custom commands allow you to save and reuse your favorite or most frequently used prompts as personal shortcuts within Qwen Code. You can create commands that are specific to a single project or commands that are available globally across all your projects, streamlining your workflow and ensuring consistency.
|
||||
|
||||
#### File Locations & Precedence
|
||||
|
||||
Gemini CLI discovers commands from two locations, loaded in a specific order:
|
||||
Qwen Code discovers commands from two locations, loaded in a specific order:
|
||||
|
||||
1. **User Commands (Global):** Located in `~/.gemini/commands/`. These commands are available in any project you are working on.
|
||||
2. **Project Commands (Local):** Located in `<your-project-root>/.gemini/commands/`. These commands are specific to the current project and can be checked into version control to be shared with your team.
|
||||
1. **User Commands (Global):** Located in `~/.qwen/commands/`. These commands are available in any project you are working on.
|
||||
2. **Project Commands (Local):** Located in `<your-project-root>/.qwen/commands/`. These commands are specific to the current project and can be checked into version control to be shared with your team.
|
||||
|
||||
If a command in the project directory has the same name as a command in the user directory, the **project command will always be used.** This allows projects to override global commands with project-specific versions.
|
||||
|
||||
@@ -158,8 +163,8 @@ If a command in the project directory has the same name as a command in the user
|
||||
|
||||
The name of a command is determined by its file path relative to its `commands` directory. Subdirectories are used to create namespaced commands, with the path separator (`/` or `\`) being converted to a colon (`:`).
|
||||
|
||||
- A file at `~/.gemini/commands/test.toml` becomes the command `/test`.
|
||||
- A file at `<project>/.gemini/commands/git/commit.toml` becomes the namespaced command `/git:commit`.
|
||||
- A file at `~/.qwen/commands/test.toml` becomes the command `/test`.
|
||||
- A file at `<project>/.qwen/commands/git/commit.toml` becomes the namespaced command `/git:commit`.
|
||||
|
||||
#### TOML File Format (v1)
|
||||
|
||||
@@ -167,7 +172,7 @@ Your command definition files must be written in the TOML format and use the `.t
|
||||
|
||||
##### Required Fields
|
||||
|
||||
- `prompt` (String): The prompt that will be sent to the Gemini model when the command is executed. This can be a single-line or multi-line string.
|
||||
- `prompt` (String): The prompt that will be sent to the model when the command is executed. This can be a single-line or multi-line string.
|
||||
|
||||
##### Optional Fields
|
||||
|
||||
@@ -184,7 +189,7 @@ If your `prompt` contains the special placeholder `{{args}}`, the CLI will repla
|
||||
**Example (`git/fix.toml`):**
|
||||
|
||||
```toml
|
||||
# In: ~/.gemini/commands/git/fix.toml
|
||||
# In: ~/.qwen/commands/git/fix.toml
|
||||
# Invoked via: /git:fix "Button is misaligned on mobile"
|
||||
|
||||
description = "Generates a fix for a given GitHub issue."
|
||||
@@ -206,7 +211,7 @@ If you do **not** provide any arguments (e.g., `/mycommand`), the prompt is sent
|
||||
This example shows how to create a robust command by defining a role for the model, explaining where to find the user's input, and specifying the expected format and behavior.
|
||||
|
||||
```toml
|
||||
# In: <project>/.gemini/commands/changelog.toml
|
||||
# In: <project>/.qwen/commands/changelog.toml
|
||||
# Invoked via: /changelog 1.2.0 added "Support for default argument parsing."
|
||||
|
||||
description = "Adds a new entry to the project's CHANGELOG.md file."
|
||||
@@ -238,7 +243,7 @@ When you run `/changelog 1.2.0 added "New feature"`, the final text sent to the
|
||||
|
||||
You can make your commands dynamic by executing shell commands directly within your `prompt` and injecting their output. This is ideal for gathering context from your local environment, like reading file content or checking the status of Git.
|
||||
|
||||
When a custom command attempts to execute a shell command, Gemini CLI will now prompt you for confirmation before proceeding. This is a security measure to ensure that only intended commands can be run.
|
||||
When a custom command attempts to execute a shell command, Qwen Code will now prompt you for confirmation before proceeding. This is a security measure to ensure that only intended commands can be run.
|
||||
|
||||
**How It Works:**
|
||||
|
||||
@@ -256,7 +261,7 @@ The CLI still respects the global `excludeTools` and `coreTools` settings. A com
|
||||
This command gets the staged git diff and uses it to ask the model to write a commit message.
|
||||
|
||||
````toml
|
||||
# In: <project>/.gemini/commands/git/commit.toml
|
||||
# In: <project>/.qwen/commands/git/commit.toml
|
||||
# Invoked via: /git:commit
|
||||
|
||||
description = "Generates a Git commit message based on staged changes."
|
||||
@@ -286,16 +291,16 @@ Let's create a global command that asks the model to refactor a piece of code.
|
||||
First, ensure the user commands directory exists, then create a `refactor` subdirectory for organization and the final TOML file.
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.gemini/commands/refactor
|
||||
touch ~/.gemini/commands/refactor/pure.toml
|
||||
mkdir -p ~/.qwen/commands/refactor
|
||||
touch ~/.qwen/commands/refactor/pure.toml
|
||||
```
|
||||
|
||||
**2. Add the content to the file:**
|
||||
|
||||
Open `~/.gemini/commands/refactor/pure.toml` in your editor and add the following content. We are including the optional `description` for best practice.
|
||||
Open `~/.qwen/commands/refactor/pure.toml` in your editor and add the following content. We are including the optional `description` for best practice.
|
||||
|
||||
```toml
|
||||
# In: ~/.gemini/commands/refactor/pure.toml
|
||||
# In: ~/.qwen/commands/refactor/pure.toml
|
||||
# This command will be invoked via: /refactor:pure
|
||||
|
||||
description = "Asks the model to refactor the current context into a pure function."
|
||||
@@ -319,11 +324,11 @@ That's it! You can now run your command in the CLI. First, you might add a file
|
||||
> /refactor:pure
|
||||
```
|
||||
|
||||
Gemini CLI will then execute the multi-line prompt defined in your TOML file.
|
||||
Qwen Code will then execute the multi-line prompt defined in your TOML file.
|
||||
|
||||
## At commands (`@`)
|
||||
|
||||
At commands are used to include the content of files or directories as part of your prompt to Gemini. These commands include git-aware filtering.
|
||||
At commands are used to include the content of files or directories as part of your prompt to the model. These commands include git-aware filtering.
|
||||
|
||||
- **`@<path_to_file_or_directory>`**
|
||||
- **Description:** Inject the content of the specified file or files into your current prompt. This is useful for asking questions about specific code, text, or collections of files.
|
||||
@@ -335,28 +340,28 @@ At commands are used to include the content of files or directories as part of y
|
||||
- If a path to a single file is provided, the content of that file is read.
|
||||
- If a path to a directory is provided, the command attempts to read the content of files within that directory and any subdirectories.
|
||||
- Spaces in paths should be escaped with a backslash (e.g., `@My\ Documents/file.txt`).
|
||||
- The command uses the `read_many_files` tool internally. The content is fetched and then inserted into your query before being sent to the Gemini model.
|
||||
- The command uses the `read_many_files` tool internally. The content is fetched and then inserted into your query before being sent to the model.
|
||||
- **Git-aware filtering:** By default, git-ignored files (like `node_modules/`, `dist/`, `.env`, `.git/`) are excluded. This behavior can be changed via the `fileFiltering` settings.
|
||||
- **File types:** The command is intended for text-based files. While it might attempt to read any file, binary files or very large files might be skipped or truncated by the underlying `read_many_files` tool to ensure performance and relevance. The tool indicates if files were skipped.
|
||||
- **Output:** The CLI will show a tool call message indicating that `read_many_files` was used, along with a message detailing the status and the path(s) that were processed.
|
||||
|
||||
- **`@` (Lone at symbol)**
|
||||
- **Description:** If you type a lone `@` symbol without a path, the query is passed as-is to the Gemini model. This might be useful if you are specifically talking _about_ the `@` symbol in your prompt.
|
||||
- **Description:** If you type a lone `@` symbol without a path, the query is passed as-is to the model. This might be useful if you are specifically talking _about_ the `@` symbol in your prompt.
|
||||
|
||||
### Error handling for `@` commands
|
||||
|
||||
- If the path specified after `@` is not found or is invalid, an error message will be displayed, and the query might not be sent to the Gemini model, or it will be sent without the file content.
|
||||
- If the path specified after `@` is not found or is invalid, an error message will be displayed, and the query might not be sent to the model, or it will be sent without the file content.
|
||||
- If the `read_many_files` tool encounters an error (e.g., permission issues), this will also be reported.
|
||||
|
||||
## Shell mode & passthrough commands (`!`)
|
||||
|
||||
The `!` prefix lets you interact with your system's shell directly from within Gemini CLI.
|
||||
The `!` prefix lets you interact with your system's shell directly from within Qwen Code.
|
||||
|
||||
- **`!<shell_command>`**
|
||||
- **Description:** Execute the given `<shell_command>` using `bash` on Linux/macOS or `cmd.exe` on Windows. Any output or errors from the command are displayed in the terminal.
|
||||
- **Examples:**
|
||||
- `!ls -la` (executes `ls -la` and returns to Gemini CLI)
|
||||
- `!git status` (executes `git status` and returns to Gemini CLI)
|
||||
- `!ls -la` (executes `ls -la` and returns to Qwen Code)
|
||||
- `!git status` (executes `git status` and returns to Qwen Code)
|
||||
|
||||
- **`!` (Toggle shell mode)**
|
||||
- **Description:** Typing `!` on its own toggles shell mode.
|
||||
@@ -364,8 +369,8 @@ The `!` prefix lets you interact with your system's shell directly from within G
|
||||
- When active, shell mode uses a different coloring and a "Shell Mode Indicator".
|
||||
- While in shell mode, text you type is interpreted directly as a shell command.
|
||||
- **Exiting shell mode:**
|
||||
- When exited, the UI reverts to its standard appearance and normal Gemini CLI behavior resumes.
|
||||
- When exited, the UI reverts to its standard appearance and normal Qwen Code behavior resumes.
|
||||
|
||||
- **Caution for all `!` usage:** Commands you execute in shell mode have the same permissions and impact as if you ran them directly in your terminal.
|
||||
|
||||
- **Environment Variable:** When a command is executed via `!` or in shell mode, the `GEMINI_CLI=1` environment variable is set in the subprocess's environment. This allows scripts or tools to detect if they are being run from within the Gemini CLI.
|
||||
- **Environment Variable:** When a command is executed via `!` or in shell mode, the `QWEN_CODE=1` environment variable is set in the subprocess's environment. This allows scripts or tools to detect if they are being run from within the CLI.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Gemini CLI Configuration
|
||||
# Qwen Code Configuration
|
||||
|
||||
Gemini CLI offers several ways to configure its behavior, including environment variables, command-line arguments, and settings files. This document outlines the different configuration methods and available settings.
|
||||
Qwen Code offers several ways to configure its behavior, including environment variables, command-line arguments, and settings files. This document outlines the different configuration methods and available settings.
|
||||
|
||||
## Configuration layers
|
||||
|
||||
@@ -15,23 +15,23 @@ Configuration is applied in the following order of precedence (lower numbers are
|
||||
|
||||
## Settings files
|
||||
|
||||
Gemini CLI uses `settings.json` files for persistent configuration. There are three locations for these files:
|
||||
Qwen Code uses `settings.json` files for persistent configuration. There are three locations for these files:
|
||||
|
||||
- **User settings file:**
|
||||
- **Location:** `~/.qwen/settings.json` (where `~` is your home directory).
|
||||
- **Scope:** Applies to all Gemini CLI sessions for the current user.
|
||||
- **Scope:** Applies to all Qwen Code sessions for the current user.
|
||||
- **Project settings file:**
|
||||
- **Location:** `.qwen/settings.json` within your project's root directory.
|
||||
- **Scope:** Applies only when running Gemini CLI from that specific project. Project settings override user settings.
|
||||
- **Scope:** Applies only when running Qwen Code from that specific project. Project settings override user settings.
|
||||
- **System settings file:**
|
||||
- **Location:** `/etc/gemini-cli/settings.json` (Linux), `C:\ProgramData\gemini-cli\settings.json` (Windows) or `/Library/Application Support/GeminiCli/settings.json` (macOS). The path can be overridden using the `GEMINI_CLI_SYSTEM_SETTINGS_PATH` environment variable.
|
||||
- **Scope:** Applies to all Gemini CLI sessions on the system, for all users. System settings override user and project settings. May be useful for system administrators at enterprises to have controls over users' Gemini CLI setups.
|
||||
- **Scope:** Applies to all Qwen Code sessions on the system, for all users. System settings override user and project settings. May be useful for system administrators at enterprises to have controls over users' Qwen Code setups.
|
||||
|
||||
**Note on environment variables in settings:** String values within your `settings.json` files can reference environment variables using either `$VAR_NAME` or `${VAR_NAME}` syntax. These variables will be automatically resolved when the settings are loaded. For example, if you have an environment variable `MY_API_TOKEN`, you could use it in `settings.json` like this: `"apiKey": "$MY_API_TOKEN"`.
|
||||
|
||||
### The `.gemini` directory in your project
|
||||
### The `.qwen` directory in your project
|
||||
|
||||
In addition to a project settings file, a project's `.gemini` directory can contain other project-specific files related to Gemini CLI's operation, such as:
|
||||
In addition to a project settings file, a project's `.qwen` directory can contain other project-specific files related to Qwen Code's operation, such as:
|
||||
|
||||
- [Custom sandbox profiles](#sandboxing) (e.g., `.qwen/sandbox-macos-custom.sb`, `.qwen/sandbox.Dockerfile`).
|
||||
|
||||
@@ -44,7 +44,7 @@ In addition to a project settings file, a project's `.gemini` directory can cont
|
||||
|
||||
- **`bugCommand`** (object):
|
||||
- **Description:** Overrides the default URL for the `/bug` command.
|
||||
- **Default:** `"urlTemplate": "https://github.com/google-gemini/gemini-cli/issues/new?template=bug_report.yml&title={title}&info={info}"`
|
||||
- **Default:** `"urlTemplate": "https://github.com/QwenLM/qwen-code/issues/new?template=bug_report.yml&title={title}&info={info}"`
|
||||
- **Properties:**
|
||||
- **`urlTemplate`** (string): A URL that can contain `{title}` and `{info}` placeholders.
|
||||
- **Example:**
|
||||
@@ -70,7 +70,7 @@ In addition to a project settings file, a project's `.gemini` directory can cont
|
||||
|
||||
- **`coreTools`** (array of strings):
|
||||
- **Description:** Allows you to specify a list of core tool names that should be made available to the model. This can be used to restrict the set of built-in tools. See [Built-in Tools](../core/tools-api.md#built-in-tools) for a list of core tools. You can also specify command-specific restrictions for tools that support it, like the `ShellTool`. For example, `"coreTools": ["ShellTool(ls -l)"]` will only allow the `ls -l` command to be executed.
|
||||
- **Default:** All tools available for use by the Gemini model.
|
||||
- **Default:** All tools available for use by the model.
|
||||
- **Example:** `"coreTools": ["ReadFileTool", "GlobTool", "ShellTool(ls)"]`.
|
||||
|
||||
- **`excludeTools`** (array of strings):
|
||||
@@ -83,7 +83,7 @@ In addition to a project settings file, a project's `.gemini` directory can cont
|
||||
|
||||
- **`allowMCPServers`** (array of strings):
|
||||
- **Description:** Allows you to specify a list of MCP server names that should be made available to the model. This can be used to restrict the set of MCP servers to connect to. Note that this will be ignored if `--allowed-mcp-server-names` is set.
|
||||
- **Default:** All MCP servers are available for use by the Gemini model.
|
||||
- **Default:** All MCP servers are available for use by the model.
|
||||
- **Example:** `"allowMCPServers": ["myPythonServer"]`.
|
||||
- **Security Note:** This uses simple string matching on MCP server names, which can be modified. If you're a system administrator looking to prevent users from bypassing this, consider configuring the `mcpServers` at the system settings level such that the user will not be able to configure any MCP servers of their own. This should not be used as an airtight security mechanism.
|
||||
|
||||
@@ -99,7 +99,7 @@ In addition to a project settings file, a project's `.gemini` directory can cont
|
||||
- **Example:** `"autoAccept": true`
|
||||
|
||||
- **`theme`** (string):
|
||||
- **Description:** Sets the visual [theme](./themes.md) for Gemini CLI.
|
||||
- **Description:** Sets the visual [theme](./themes.md) for Qwen Code.
|
||||
- **Default:** `"Default"`
|
||||
- **Example:** `"theme": "GitHub"`
|
||||
|
||||
@@ -109,7 +109,7 @@ In addition to a project settings file, a project's `.gemini` directory can cont
|
||||
- **Example:** `"vimMode": true`
|
||||
|
||||
- **`sandbox`** (boolean or string):
|
||||
- **Description:** Controls whether and how to use sandboxing for tool execution. If set to `true`, Gemini CLI uses a pre-built `gemini-cli-sandbox` Docker image. For more information, see [Sandboxing](#sandboxing).
|
||||
- **Description:** Controls whether and how to use sandboxing for tool execution. If set to `true`, Qwen Code uses a pre-built `qwen-code-sandbox` Docker image. For more information, see [Sandboxing](#sandboxing).
|
||||
- **Default:** `false`
|
||||
- **Example:** `"sandbox": "docker"`
|
||||
|
||||
@@ -127,7 +127,7 @@ In addition to a project settings file, a project's `.gemini` directory can cont
|
||||
- **Example:** `"toolCallCommand": "bin/call_tool"`
|
||||
|
||||
- **`mcpServers`** (object):
|
||||
- **Description:** Configures connections to one or more Model-Context Protocol (MCP) servers for discovering and using custom tools. Gemini CLI attempts to connect to each configured MCP server to discover available tools. If multiple MCP servers expose a tool with the same name, the tool names will be prefixed with the server alias you defined in the configuration (e.g., `serverAlias__actualToolName`) to avoid conflicts. Note that the system might strip certain schema properties from MCP tool definitions for compatibility.
|
||||
- **Description:** Configures connections to one or more Model-Context Protocol (MCP) servers for discovering and using custom tools. Qwen Code attempts to connect to each configured MCP server to discover available tools. If multiple MCP servers expose a tool with the same name, the tool names will be prefixed with the server alias you defined in the configuration (e.g., `serverAlias__actualToolName`) to avoid conflicts. Note that the system might strip certain schema properties from MCP tool definitions for compatibility.
|
||||
- **Default:** Empty
|
||||
- **Properties:**
|
||||
- **`<SERVER_NAME>`** (object): The server parameters for the named server.
|
||||
@@ -177,7 +177,7 @@ In addition to a project settings file, a project's `.gemini` directory can cont
|
||||
- **Example:** `"preferredEditor": "vscode"`
|
||||
|
||||
- **`telemetry`** (object)
|
||||
- **Description:** Configures logging and metrics collection for Gemini CLI. For more information, see [Telemetry](../telemetry.md).
|
||||
- **Description:** Configures logging and metrics collection for Qwen Code. For more information, see [Telemetry](../telemetry.md).
|
||||
- **Default:** `{"enabled": false, "target": "local", "otlpEndpoint": "http://localhost:4317", "logPrompts": true}`
|
||||
- **Properties:**
|
||||
- **`enabled`** (boolean): Whether or not telemetry is enabled.
|
||||
@@ -241,7 +241,7 @@ In addition to a project settings file, a project's `.gemini` directory can cont
|
||||
```
|
||||
|
||||
- **`excludedProjectEnvVars`** (array of strings):
|
||||
- **Description:** Specifies environment variables that should be excluded from being loaded from project `.env` files. This prevents project-specific environment variables (like `DEBUG=true`) from interfering with gemini-cli behavior. Variables from `.gemini/.env` files are never excluded.
|
||||
- **Description:** Specifies environment variables that should be excluded from being loaded from project `.env` files. This prevents project-specific environment variables (like `DEBUG=true`) from interfering with the CLI behavior. Variables from `.qwen/.env` files are never excluded.
|
||||
- **Default:** `["DEBUG", "DEBUG_MODE"]`
|
||||
- **Example:**
|
||||
```json
|
||||
@@ -272,6 +272,25 @@ In addition to a project settings file, a project's `.gemini` directory can cont
|
||||
- **Description:** API key for Tavily web search service. Required to enable the `web_search` tool functionality. If not configured, the web search tool will be disabled and skipped.
|
||||
- **Default:** `undefined` (web search disabled)
|
||||
- **Example:** `"tavilyApiKey": "tvly-your-api-key-here"`
|
||||
- **`chatCompression`** (object):
|
||||
- **Description:** Controls the settings for chat history compression, both automatic and
|
||||
when manually invoked through the /compress command.
|
||||
- **Properties:**
|
||||
- **`contextPercentageThreshold`** (number): A value between 0 and 1 that specifies the token threshold for compression as a percentage of the model's total token limit. For example, a value of `0.6` will trigger compression when the chat history exceeds 60% of the token limit.
|
||||
- **Example:**
|
||||
```json
|
||||
"chatCompression": {
|
||||
"contextPercentageThreshold": 0.6
|
||||
}
|
||||
```
|
||||
|
||||
- **`showLineNumbers`** (boolean):
|
||||
- **Description:** Controls whether line numbers are displayed in code blocks in the CLI output.
|
||||
- **Default:** `true`
|
||||
- **Example:**
|
||||
```json
|
||||
"showLineNumbers": false
|
||||
```
|
||||
|
||||
### Example `settings.json`:
|
||||
|
||||
@@ -330,7 +349,7 @@ The CLI automatically loads environment variables from an `.env` file. The loadi
|
||||
2. If not found, it searches upwards in parent directories until it finds an `.env` file or reaches the project root (identified by a `.git` folder) or the home directory.
|
||||
3. If still not found, it looks for `~/.env` (in the user's home directory).
|
||||
|
||||
**Environment Variable Exclusion:** Some environment variables (like `DEBUG` and `DEBUG_MODE`) are automatically excluded from being loaded from project `.env` files to prevent interference with gemini-cli behavior. Variables from `.gemini/.env` files are never excluded. You can customize this behavior using the `excludedProjectEnvVars` setting in your `settings.json` file.
|
||||
**Environment Variable Exclusion:** Some environment variables (like `DEBUG` and `DEBUG_MODE`) are automatically excluded from project `.env` files by default to prevent interference with the CLI behavior. Variables from `.qwen/.env` files are never excluded. You can customize this behavior using the `excludedProjectEnvVars` setting in your `settings.json` file.
|
||||
|
||||
- **`GEMINI_API_KEY`** (Required):
|
||||
- Your API key for the Gemini API.
|
||||
@@ -371,7 +390,7 @@ The CLI automatically loads environment variables from an `.env` file. The loadi
|
||||
- `<profile_name>`: Uses a custom profile. To define a custom profile, create a file named `sandbox-macos-<profile_name>.sb` in your project's `.qwen/` directory (e.g., `my-project/.qwen/sandbox-macos-custom.sb`).
|
||||
- **`DEBUG` or `DEBUG_MODE`** (often used by underlying libraries or the CLI itself):
|
||||
- Set to `true` or `1` to enable verbose debug logging, which can be helpful for troubleshooting.
|
||||
- **Note:** These variables are automatically excluded from project `.env` files by default to prevent interference with gemini-cli behavior. Use `.gemini/.env` files if you need to set these for gemini-cli specifically.
|
||||
- **Note:** These variables are automatically excluded from project `.env` files by default to prevent interference with the CLI behavior. Use `.qwen/.env` files if you need to set these for Qwen Code specifically.
|
||||
- **`NO_COLOR`**:
|
||||
- Set to any value to disable all color output in the CLI.
|
||||
- **`CLI_TITLE`**:
|
||||
@@ -393,12 +412,12 @@ Arguments passed directly when running the CLI can override other configurations
|
||||
- Specifies the Gemini model to use for this session.
|
||||
- Example: `npm start -- --model gemini-1.5-pro-latest`
|
||||
- **`--prompt <your_prompt>`** (**`-p <your_prompt>`**):
|
||||
- Used to pass a prompt directly to the command. This invokes Gemini CLI in a non-interactive mode.
|
||||
- Used to pass a prompt directly to the command. This invokes Qwen Code in a non-interactive mode.
|
||||
- **`--prompt-interactive <your_prompt>`** (**`-i <your_prompt>`**):
|
||||
- Starts an interactive session with the provided prompt as the initial input.
|
||||
- The prompt is processed within the interactive session, not before it.
|
||||
- Cannot be used when piping input from stdin.
|
||||
- Example: `gemini -i "explain this code"`
|
||||
- Example: `qwen -i "explain this code"`
|
||||
- **`--sandbox`** (**`-s`**):
|
||||
- Enables sandbox mode for this session.
|
||||
- **`--sandbox-image`**:
|
||||
@@ -425,8 +444,8 @@ Arguments passed directly when running the CLI can override other configurations
|
||||
- Enables [checkpointing](../checkpointing.md).
|
||||
- **`--extensions <extension_name ...>`** (**`-e <extension_name ...>`**):
|
||||
- Specifies a list of extensions to use for the session. If not provided, all available extensions are used.
|
||||
- Use the special term `gemini -e none` to disable all extensions.
|
||||
- Example: `gemini -e my-extension -e my-other-extension`
|
||||
- Use the special term `qwen -e none` to disable all extensions.
|
||||
- Example: `qwen -e my-extension -e my-other-extension`
|
||||
- **`--list-extensions`** (**`-l`**):
|
||||
- Lists all available extensions and exits.
|
||||
- **`--proxy`**:
|
||||
@@ -443,11 +462,11 @@ Arguments passed directly when running the CLI can override other configurations
|
||||
- Enables logging of OpenAI API calls for debugging and analysis. This flag overrides the `enableOpenAILogging` setting in `settings.json`.
|
||||
- **`--tavily-api-key <api_key>`**:
|
||||
- Sets the Tavily API key for web search functionality for this session.
|
||||
- Example: `gemini --tavily-api-key tvly-your-api-key-here`
|
||||
- Example: `qwen --tavily-api-key tvly-your-api-key-here`
|
||||
|
||||
## Context Files (Hierarchical Instructional Context)
|
||||
|
||||
While not strictly configuration for the CLI's _behavior_, context files (defaulting to `GEMINI.md` but configurable via the `contextFileName` setting) are crucial for configuring the _instructional context_ (also referred to as "memory") provided to the Gemini model. This powerful feature allows you to give project-specific instructions, coding style guides, or any relevant background information to the AI, making its responses more tailored and accurate to your needs. The CLI includes UI elements, such as an indicator in the footer showing the number of loaded context files, to keep you informed about the active context.
|
||||
While not strictly configuration for the CLI's _behavior_, context files (defaulting to `QWEN.md` but configurable via the `contextFileName` setting) are crucial for configuring the _instructional context_ (also referred to as "memory"). This powerful feature allows you to give project-specific instructions, coding style guides, or any relevant background information to the AI, making its responses more tailored and accurate to your needs. The CLI includes UI elements, such as an indicator in the footer showing the number of loaded context files, to keep you informed about the active context.
|
||||
|
||||
- **Purpose:** These Markdown files contain instructions, guidelines, or context that you want the Gemini model to be aware of during your interactions. The system is designed to manage this instructional context hierarchically.
|
||||
|
||||
@@ -496,18 +515,18 @@ This example demonstrates how you can provide general project context, specific
|
||||
3. **Sub-directory Context Files (Contextual/Local):**
|
||||
- Location: The CLI also scans for the configured context file in subdirectories _below_ the current working directory (respecting common ignore patterns like `node_modules`, `.git`, etc.). The breadth of this search is limited to 200 directories by default, but can be configured with a `memoryDiscoveryMaxDirs` field in your `settings.json` file.
|
||||
- Scope: Allows for highly specific instructions relevant to a particular component, module, or subsection of your project.
|
||||
- **Concatenation & UI Indication:** The contents of all found context files are concatenated (with separators indicating their origin and path) and provided as part of the system prompt to the Gemini model. The CLI footer displays the count of loaded context files, giving you a quick visual cue about the active instructional context.
|
||||
- **Concatenation & UI Indication:** The contents of all found context files are concatenated (with separators indicating their origin and path) and provided as part of the system prompt. The CLI footer displays the count of loaded context files, giving you a quick visual cue about the active instructional context.
|
||||
- **Importing Content:** You can modularize your context files by importing other Markdown files using the `@path/to/file.md` syntax. For more details, see the [Memory Import Processor documentation](../core/memport.md).
|
||||
- **Commands for Memory Management:**
|
||||
- Use `/memory refresh` to force a re-scan and reload of all context files from all configured locations. This updates the AI's instructional context.
|
||||
- Use `/memory show` to display the combined instructional context currently loaded, allowing you to verify the hierarchy and content being used by the AI.
|
||||
- See the [Commands documentation](./commands.md#memory) for full details on the `/memory` command and its sub-commands (`show` and `refresh`).
|
||||
|
||||
By understanding and utilizing these configuration layers and the hierarchical nature of context files, you can effectively manage the AI's memory and tailor the Gemini CLI's responses to your specific needs and projects.
|
||||
By understanding and utilizing these configuration layers and the hierarchical nature of context files, you can effectively manage the AI's memory and tailor Qwen Code's responses to your specific needs and projects.
|
||||
|
||||
## Sandboxing
|
||||
|
||||
The Gemini CLI can execute potentially unsafe operations (like shell commands and file modifications) within a sandboxed environment to protect your system.
|
||||
Qwen Code can execute potentially unsafe operations (like shell commands and file modifications) within a sandboxed environment to protect your system.
|
||||
|
||||
Sandboxing is disabled by default, but you can enable it in a few ways:
|
||||
|
||||
@@ -515,12 +534,12 @@ Sandboxing is disabled by default, but you can enable it in a few ways:
|
||||
- Setting `GEMINI_SANDBOX` environment variable.
|
||||
- Sandbox is enabled in `--yolo` mode by default.
|
||||
|
||||
By default, it uses a pre-built `gemini-cli-sandbox` Docker image.
|
||||
By default, it uses a pre-built `qwen-code-sandbox` Docker image.
|
||||
|
||||
For project-specific sandboxing needs, you can create a custom Dockerfile at `.gemini/sandbox.Dockerfile` in your project's root directory. This Dockerfile can be based on the base sandbox image:
|
||||
For project-specific sandboxing needs, you can create a custom Dockerfile at `.qwen/sandbox.Dockerfile` in your project's root directory. This Dockerfile can be based on the base sandbox image:
|
||||
|
||||
```dockerfile
|
||||
FROM gemini-cli-sandbox
|
||||
FROM qwen-code-sandbox
|
||||
|
||||
# Add your custom dependencies or configurations here
|
||||
# For example:
|
||||
@@ -528,26 +547,26 @@ FROM gemini-cli-sandbox
|
||||
# COPY ./my-config /app/my-config
|
||||
```
|
||||
|
||||
When `.gemini/sandbox.Dockerfile` exists, you can use `BUILD_SANDBOX` environment variable when running Gemini CLI to automatically build the custom sandbox image:
|
||||
When `.qwen/sandbox.Dockerfile` exists, you can use `BUILD_SANDBOX` environment variable when running Qwen Code to automatically build the custom sandbox image:
|
||||
|
||||
```bash
|
||||
BUILD_SANDBOX=1 gemini -s
|
||||
BUILD_SANDBOX=1 qwen -s
|
||||
```
|
||||
|
||||
## Usage Statistics
|
||||
|
||||
To help us improve the Gemini CLI, we collect anonymized usage statistics. This data helps us understand how the CLI is used, identify common issues, and prioritize new features.
|
||||
To help us improve Qwen Code, we collect anonymized usage statistics. This data helps us understand how the CLI is used, identify common issues, and prioritize new features.
|
||||
|
||||
**What we collect:**
|
||||
|
||||
- **Tool Calls:** We log the names of the tools that are called, whether they succeed or fail, and how long they take to execute. We do not collect the arguments passed to the tools or any data returned by them.
|
||||
- **API Requests:** We log the Gemini model used for each request, the duration of the request, and whether it was successful. We do not collect the content of the prompts or responses.
|
||||
- **API Requests:** We log the model used for each request, the duration of the request, and whether it was successful. We do not collect the content of the prompts or responses.
|
||||
- **Session Information:** We collect information about the configuration of the CLI, such as the enabled tools and the approval mode.
|
||||
|
||||
**What we DON'T collect:**
|
||||
|
||||
- **Personally Identifiable Information (PII):** We do not collect any personal information, such as your name, email address, or API keys.
|
||||
- **Prompt and Response Content:** We do not log the content of your prompts or the responses from the Gemini model.
|
||||
- **Prompt and Response Content:** We do not log the content of your prompts or the responses from the model.
|
||||
- **File Content:** We do not log the content of any files that are read or written by the CLI.
|
||||
|
||||
**How to opt out:**
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Themes
|
||||
|
||||
Gemini CLI supports a variety of themes to customize its color scheme and appearance. You can change the theme to suit your preferences via the `/theme` command or `"theme":` configuration setting.
|
||||
Qwen Code supports a variety of themes to customize its color scheme and appearance. You can change the theme to suit your preferences via the `/theme` command or `"theme":` configuration setting.
|
||||
|
||||
## Available Themes
|
||||
|
||||
Gemini CLI comes with a selection of pre-defined themes, which you can list using the `/theme` command within Gemini CLI:
|
||||
Qwen Code comes with a selection of pre-defined themes, which you can list using the `/theme` command within the CLI:
|
||||
|
||||
- **Dark Themes:**
|
||||
- `ANSI`
|
||||
@@ -23,20 +23,20 @@ Gemini CLI comes with a selection of pre-defined themes, which you can list usin
|
||||
|
||||
### Changing Themes
|
||||
|
||||
1. Enter `/theme` into Gemini CLI.
|
||||
1. Enter `/theme` into Qwen Code.
|
||||
2. A dialog or selection prompt appears, listing the available themes.
|
||||
3. Using the arrow keys, select a theme. Some interfaces might offer a live preview or highlight as you select.
|
||||
4. Confirm your selection to apply the theme.
|
||||
|
||||
### Theme Persistence
|
||||
|
||||
Selected themes are saved in Gemini CLI's [configuration](./configuration.md) so your preference is remembered across sessions.
|
||||
Selected themes are saved in Qwen Code's [configuration](./configuration.md) so your preference is remembered across sessions.
|
||||
|
||||
---
|
||||
|
||||
## Custom Color Themes
|
||||
|
||||
Gemini CLI allows you to create your own custom color themes by specifying them in your `settings.json` file. This gives you full control over the color palette used in the CLI.
|
||||
Qwen Code allows you to create your own custom color themes by specifying them in your `settings.json` file. This gives you full control over the color palette used in the CLI.
|
||||
|
||||
### How to Define a Custom Theme
|
||||
|
||||
@@ -111,7 +111,7 @@ You can define multiple custom themes by adding more entries to the `customTheme
|
||||
|
||||
### Using Your Custom Theme
|
||||
|
||||
- Select your custom theme using the `/theme` command in Gemini CLI. Your custom theme will appear in the theme selection dialog.
|
||||
- Select your custom theme using the `/theme` command in Qwen Code. Your custom theme will appear in the theme selection dialog.
|
||||
- Or, set it as the default by adding `"theme": "MyCustomTheme"` to your `settings.json`.
|
||||
- Custom themes can be set at the user, project, or system level, and follow the same [configuration precedence](./configuration.md) as other settings.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Token Caching and Cost Optimization
|
||||
|
||||
Gemini CLI automatically optimizes API costs through token caching when using API key authentication (Gemini API key or Vertex AI). This feature reuses previous system instructions and context to reduce the number of tokens processed in subsequent requests.
|
||||
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:**
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Tutorials
|
||||
|
||||
This page contains tutorials for interacting with Gemini CLI.
|
||||
This page contains tutorials for interacting with Qwen Code.
|
||||
|
||||
## Setting up a Model Context Protocol (MCP) server
|
||||
|
||||
@@ -58,11 +58,11 @@ Use an environment variable to store your GitHub PAT:
|
||||
GITHUB_PERSONAL_ACCESS_TOKEN="pat_YourActualGitHubTokenHere"
|
||||
```
|
||||
|
||||
Gemini CLI uses this value in the `mcpServers` configuration that you defined in the `settings.json` file.
|
||||
Qwen Code uses this value in the `mcpServers` configuration that you defined in the `settings.json` file.
|
||||
|
||||
#### Launch Gemini CLI and verify the connection
|
||||
#### Launch Qwen Code and verify the connection
|
||||
|
||||
When you launch Gemini CLI, it automatically reads your configuration and launches the GitHub MCP server in the background. You can then use natural language prompts to ask Gemini CLI to perform GitHub actions. For example:
|
||||
When you launch Qwen Code, it automatically reads your configuration and launches the GitHub MCP server in the background. You can then use natural language prompts to ask Qwen Code to perform GitHub actions. For example:
|
||||
|
||||
```bash
|
||||
"get all open issues assigned to me in the 'foo/bar' repo and prioritize them"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Gemini CLI Core
|
||||
# Qwen Code Core
|
||||
|
||||
Gemini CLI's core package (`packages/core`) is the backend portion of Gemini CLI, handling communication with the Gemini API, managing tools, and processing requests sent from `packages/cli`. For a general overview of Gemini CLI, see the [main documentation page](../index.md).
|
||||
Qwen Code's core package (`packages/core`) is the backend portion of Qwen Code, handling communication with model APIs, managing tools, and processing requests sent from `packages/cli`. For a general overview of Qwen Code, see the [main documentation page](../index.md).
|
||||
|
||||
## Navigating this section
|
||||
|
||||
@@ -9,15 +9,15 @@ Gemini CLI's core package (`packages/core`) is the backend portion of Gemini CLI
|
||||
|
||||
## Role of the core
|
||||
|
||||
While the `packages/cli` portion of Gemini CLI provides the user interface, `packages/core` is responsible for:
|
||||
While the `packages/cli` portion of Qwen Code provides the user interface, `packages/core` is responsible for:
|
||||
|
||||
- **Gemini API interaction:** Securely communicating with the Google Gemini API, sending user prompts, and receiving model responses.
|
||||
- **Model API interaction:** Securely communicating with the configured model provider, sending user prompts, and receiving model responses.
|
||||
- **Prompt engineering:** Constructing effective prompts for the model, potentially incorporating conversation history, tool definitions, and instructional context from context files (e.g., `QWEN.md`).
|
||||
- **Tool management & orchestration:**
|
||||
- Registering available tools (e.g., file system tools, shell command execution).
|
||||
- Interpreting tool use requests from the Gemini model.
|
||||
- Interpreting tool use requests from the model.
|
||||
- Executing the requested tools with the provided arguments.
|
||||
- Returning tool execution results to the Gemini model for further processing.
|
||||
- Returning tool execution results to the model for further processing.
|
||||
- **Session and state management:** Keeping track of the conversation state, including history and any relevant context required for coherent interactions.
|
||||
- **Configuration:** Managing core-specific configurations, such as API key access, model selection, and tool settings.
|
||||
|
||||
@@ -25,20 +25,20 @@ While the `packages/cli` portion of Gemini CLI provides the user interface, `pac
|
||||
|
||||
The core plays a vital role in security:
|
||||
|
||||
- **API key management:** It handles the `GEMINI_API_KEY` and ensures it's used securely when communicating with the Gemini API.
|
||||
- **API key management:** It handles provider credentials and ensures they're used securely when communicating with APIs.
|
||||
- **Tool execution:** When tools interact with the local system (e.g., `run_shell_command`), the core (and its underlying tool implementations) must do so with appropriate caution, often involving sandboxing mechanisms to prevent unintended modifications.
|
||||
|
||||
## Chat history compression
|
||||
|
||||
To ensure that long conversations don't exceed the token limits of the Gemini model, the core includes a chat history compression feature.
|
||||
To ensure that long conversations don't exceed the token limits of the selected model, the core includes a chat history compression feature.
|
||||
|
||||
When a conversation approaches the token limit for the configured model, the core automatically compresses the conversation history before sending it to the model. This compression is designed to be lossless in terms of the information conveyed, but it reduces the overall number of tokens used.
|
||||
|
||||
You can find the token limits for each model in the [Google AI documentation](https://ai.google.dev/gemini-api/docs/models).
|
||||
You can find token limits for each provider's models in their documentation.
|
||||
|
||||
## Model fallback
|
||||
|
||||
Gemini CLI includes a model fallback mechanism to ensure that you can continue to use the CLI even if the default "pro" model is rate-limited.
|
||||
Qwen Code includes a model fallback mechanism to ensure that you can continue to use the CLI even if the default model is rate-limited.
|
||||
|
||||
If you are using the default "pro" model and the CLI detects that you are being rate-limited, it automatically switches to the "flash" model for the current session. This allows you to continue working without interruption.
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
# Gemini CLI Core: Tools API
|
||||
# Qwen Code Core: Tools API
|
||||
|
||||
The Gemini CLI core (`packages/core`) features a robust system for defining, registering, and executing tools. These tools extend the capabilities of the Gemini model, allowing it to interact with the local environment, fetch web content, and perform various actions beyond simple text generation.
|
||||
The Qwen Code core (`packages/core`) features a robust system for defining, registering, and executing tools. These tools extend the capabilities of the model, allowing it to interact with the local environment, fetch web content, and perform various actions beyond simple text generation.
|
||||
|
||||
## Core Concepts
|
||||
|
||||
- **Tool (`tools.ts`):** An interface and base class (`BaseTool`) that defines the contract for all tools. Each tool must have:
|
||||
- `name`: A unique internal name (used in API calls to Gemini).
|
||||
- `name`: A unique internal name (used in API calls to the model).
|
||||
- `displayName`: A user-friendly name.
|
||||
- `description`: A clear explanation of what the tool does, which is provided to the Gemini model.
|
||||
- `parameterSchema`: A JSON schema defining the parameters that the tool accepts. This is crucial for the Gemini model to understand how to call the tool correctly.
|
||||
- `description`: A clear explanation of what the tool does, which is provided to the model.
|
||||
- `parameterSchema`: A JSON schema defining the parameters that the tool accepts. This is crucial for the model to understand how to call the tool correctly.
|
||||
- `validateToolParams()`: A method to validate incoming parameters.
|
||||
- `getDescription()`: A method to provide a human-readable description of what the tool will do with specific parameters before execution.
|
||||
- `shouldConfirmExecute()`: A method to determine if user confirmation is required before execution (e.g., for potentially destructive operations).
|
||||
@@ -25,7 +25,7 @@ The Gemini CLI core (`packages/core`) features a robust system for defining, reg
|
||||
- **Discovering Tools:** It can also discover tools dynamically:
|
||||
- **Command-based Discovery:** If `toolDiscoveryCommand` is configured in settings, this command is executed. It's expected to output JSON describing custom tools, which are then registered as `DiscoveredTool` instances.
|
||||
- **MCP-based Discovery:** If `mcpServerCommand` is configured, the registry can connect to a Model Context Protocol (MCP) server to list and register tools (`DiscoveredMCPTool`).
|
||||
- **Providing Schemas:** Exposing the `FunctionDeclaration` schemas of all registered tools to the Gemini model, so it knows what tools are available and how to use them.
|
||||
- **Providing Schemas:** Exposing the `FunctionDeclaration` schemas of all registered tools to the model, so it knows what tools are available and how to use them.
|
||||
- **Retrieving Tools:** Allowing the core to get a specific tool by name for execution.
|
||||
|
||||
## Built-in Tools
|
||||
@@ -52,7 +52,7 @@ Each of these tools extends `BaseTool` and implements the required methods for i
|
||||
|
||||
## Tool Execution Flow
|
||||
|
||||
1. **Model Request:** The Gemini model, based on the user's prompt and the provided tool schemas, decides to use a tool and returns a `FunctionCall` part in its response, specifying the tool name and arguments.
|
||||
1. **Model Request:** The model, based on the user's prompt and the provided tool schemas, decides to use a tool and returns a `FunctionCall` part in its response, specifying the tool name and arguments.
|
||||
2. **Core Receives Request:** The core parses this `FunctionCall`.
|
||||
3. **Tool Retrieval:** It looks up the requested tool in the `ToolRegistry`.
|
||||
4. **Parameter Validation:** The tool's `validateToolParams()` method is called.
|
||||
@@ -62,14 +62,14 @@ Each of these tools extends `BaseTool` and implements the required methods for i
|
||||
- The user's decision (e.g., proceed, cancel) is sent back to the core.
|
||||
6. **Execution:** If validated and confirmed (or if no confirmation is needed), the core calls the tool's `execute()` method with the provided arguments and an `AbortSignal` (for potential cancellation).
|
||||
7. **Result Processing:** The `ToolResult` from `execute()` is received by the core.
|
||||
8. **Response to Model:** The `llmContent` from the `ToolResult` is packaged as a `FunctionResponse` and sent back to the Gemini model so it can continue generating a user-facing response.
|
||||
8. **Response to Model:** The `llmContent` from the `ToolResult` is packaged as a `FunctionResponse` and sent back to the model so it can continue generating a user-facing response.
|
||||
9. **Display to User:** The `returnDisplay` from the `ToolResult` is sent to the CLI to show the user what the tool did.
|
||||
|
||||
## Extending with Custom Tools
|
||||
|
||||
While direct programmatic registration of new tools by users isn't explicitly detailed as a primary workflow in the provided files for typical end-users, the architecture supports extension through:
|
||||
|
||||
- **Command-based Discovery:** Advanced users or project administrators can define a `toolDiscoveryCommand` in `settings.json`. This command, when run by the Gemini CLI core, should output a JSON array of `FunctionDeclaration` objects. The core will then make these available as `DiscoveredTool` instances. The corresponding `toolCallCommand` would then be responsible for actually executing these custom tools.
|
||||
- **MCP Server(s):** For more complex scenarios, one or more MCP servers can be set up and configured via the `mcpServers` setting in `settings.json`. The Gemini CLI core can then discover and use tools exposed by these servers. As mentioned, if you have multiple MCP servers, the tool names will be prefixed with the server name from your configuration (e.g., `serverAlias__actualToolName`).
|
||||
- **Command-based Discovery:** Advanced users or project administrators can define a `toolDiscoveryCommand` in `settings.json`. This command, when run by the core, should output a JSON array of `FunctionDeclaration` objects. The core will then make these available as `DiscoveredTool` instances. The corresponding `toolCallCommand` would then be responsible for actually executing these custom tools.
|
||||
- **MCP Server(s):** For more complex scenarios, one or more MCP servers can be set up and configured via the `mcpServers` setting in `settings.json`. The core can then discover and use tools exposed by these servers. As mentioned, if you have multiple MCP servers, the tool names will be prefixed with the server name from your configuration (e.g., `serverAlias__actualToolName`).
|
||||
|
||||
This tool system provides a flexible and powerful way to augment the Gemini model's capabilities, making the Gemini CLI a versatile assistant for a wide range of tasks.
|
||||
This tool system provides a flexible and powerful way to augment the model's capabilities, making Qwen Code a versatile assistant for a wide range of tasks.
|
||||
|
||||
@@ -1,57 +1,57 @@
|
||||
# Gemini CLI Execution and Deployment
|
||||
# Qwen Code Execution and Deployment
|
||||
|
||||
This document describes how to run Gemini CLI and explains the deployment architecture that Gemini CLI uses.
|
||||
This document describes how to run Qwen Code and explains the deployment architecture that Qwen Code uses.
|
||||
|
||||
## Running Gemini CLI
|
||||
## Running Qwen Code
|
||||
|
||||
There are several ways to run Gemini CLI. The option you choose depends on how you intend to use Gemini CLI.
|
||||
There are several ways to run Qwen Code. The option you choose depends on how you intend to use it.
|
||||
|
||||
---
|
||||
|
||||
### 1. Standard installation (Recommended for typical users)
|
||||
|
||||
This is the recommended way for end-users to install Gemini CLI. It involves downloading the Gemini CLI package from the NPM registry.
|
||||
This is the recommended way for end-users to install Qwen Code. It involves downloading the Qwen Code package from the NPM registry.
|
||||
|
||||
- **Global install:**
|
||||
|
||||
```bash
|
||||
npm install -g @google/gemini-cli
|
||||
npm install -g @qwen-code/qwen-code
|
||||
```
|
||||
|
||||
Then, run the CLI from anywhere:
|
||||
|
||||
```bash
|
||||
gemini
|
||||
qwen
|
||||
```
|
||||
|
||||
- **NPX execution:**
|
||||
|
||||
```bash
|
||||
# Execute the latest version from NPM without a global install
|
||||
npx @google/gemini-cli
|
||||
npx @qwen-code/qwen-code
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Running in a sandbox (Docker/Podman)
|
||||
|
||||
For security and isolation, Gemini CLI can be run inside a container. This is the default way that the CLI executes tools that might have side effects.
|
||||
For security and isolation, Qwen Code can be run inside a container. This is the default way that the CLI executes tools that might have side effects.
|
||||
|
||||
- **Directly from the Registry:**
|
||||
You can run the published sandbox image directly. This is useful for environments where you only have Docker and want to run the CLI.
|
||||
```bash
|
||||
# Run the published sandbox image
|
||||
docker run --rm -it us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.1.1
|
||||
docker run --rm -it ghcr.io/qwenlm/qwen-code:0.0.7
|
||||
```
|
||||
- **Using the `--sandbox` flag:**
|
||||
If you have Gemini CLI installed locally (using the standard installation described above), you can instruct it to run inside the sandbox container.
|
||||
If you have Qwen Code installed locally (using the standard installation described above), you can instruct it to run inside the sandbox container.
|
||||
```bash
|
||||
gemini --sandbox -y -p "your prompt here"
|
||||
qwen --sandbox -y -p "your prompt here"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Running from source (Recommended for Gemini CLI contributors)
|
||||
### 3. Running from source (Recommended for Qwen Code contributors)
|
||||
|
||||
Contributors to the project will want to run the CLI directly from the source code.
|
||||
|
||||
@@ -68,19 +68,19 @@ Contributors to the project will want to run the CLI directly from the source co
|
||||
# Link the local cli package to your global node_modules
|
||||
npm link packages/cli
|
||||
|
||||
# Now you can run your local version using the `gemini` command
|
||||
gemini
|
||||
# Now you can run your local version using the `qwen` command
|
||||
qwen
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. Running the latest Gemini CLI commit from GitHub
|
||||
### 4. Running the latest Qwen Code commit from GitHub
|
||||
|
||||
You can run the most recently committed version of Gemini CLI directly from the GitHub repository. This is useful for testing features still in development.
|
||||
You can run the most recently committed version of Qwen Code directly from the GitHub repository. This is useful for testing features still in development.
|
||||
|
||||
```bash
|
||||
# Execute the CLI directly from the main branch on GitHub
|
||||
npx https://github.com/google-gemini/gemini-cli
|
||||
npx https://github.com/QwenLM/qwen-code
|
||||
```
|
||||
|
||||
## Deployment architecture
|
||||
@@ -89,24 +89,24 @@ The execution methods described above are made possible by the following archite
|
||||
|
||||
**NPM packages**
|
||||
|
||||
Gemini CLI project is a monorepo that publishes two core packages to the NPM registry:
|
||||
Qwen Code project is a monorepo that publishes core packages to the NPM registry:
|
||||
|
||||
- `@google/gemini-cli-core`: The backend, handling logic and tool execution.
|
||||
- `@google/gemini-cli`: The user-facing frontend.
|
||||
- `@qwen-code/qwen-code-core`: The backend, handling logic and tool execution.
|
||||
- `@qwen-code/qwen-code`: The user-facing frontend.
|
||||
|
||||
These packages are used when performing the standard installation and when running Gemini CLI from the source.
|
||||
These packages are used when performing the standard installation and when running Qwen Code from the source.
|
||||
|
||||
**Build and packaging processes**
|
||||
|
||||
There are two distinct build processes used, depending on the distribution channel:
|
||||
|
||||
- **NPM publication:** For publishing to the NPM registry, the TypeScript source code in `@google/gemini-cli-core` and `@google/gemini-cli` is transpiled into standard JavaScript using the TypeScript Compiler (`tsc`). The resulting `dist/` directory is what gets published in the NPM package. This is a standard approach for TypeScript libraries.
|
||||
- **NPM publication:** For publishing to the NPM registry, the TypeScript source code in `@qwen-code/qwen-code-core` and `@qwen-code/qwen-code` is transpiled into standard JavaScript using the TypeScript Compiler (`tsc`). The resulting `dist/` directory is what gets published in the NPM package. This is a standard approach for TypeScript libraries.
|
||||
|
||||
- **GitHub `npx` execution:** When running the latest version of Gemini CLI directly from GitHub, a different process is triggered by the `prepare` script in `package.json`. This script uses `esbuild` to bundle the entire application and its dependencies into a single, self-contained JavaScript file. This bundle is created on-the-fly on the user's machine and is not checked into the repository.
|
||||
- **GitHub `npx` execution:** When running the latest version of Qwen Code directly from GitHub, a different process is triggered by the `prepare` script in `package.json`. This script uses `esbuild` to bundle the entire application and its dependencies into a single, self-contained JavaScript file. This bundle is created on-the-fly on the user's machine and is not checked into the repository.
|
||||
|
||||
**Docker sandbox image**
|
||||
|
||||
The Docker-based execution method is supported by the `gemini-cli-sandbox` container image. This image is published to a container registry and contains a pre-installed, global version of Gemini CLI.
|
||||
The Docker-based execution method is supported by the `qwen-code-sandbox` container image. This image is published to a container registry and contains a pre-installed, global version of Qwen Code.
|
||||
|
||||
## Release process
|
||||
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
# Gemini CLI Extensions
|
||||
# Qwen Code Extensions
|
||||
|
||||
Gemini CLI supports extensions that can be used to configure and extend its functionality.
|
||||
Qwen Code supports extensions that can be used to configure and extend its functionality.
|
||||
|
||||
## How it works
|
||||
|
||||
On startup, Gemini CLI looks for extensions in two locations:
|
||||
On startup, Qwen Code looks for extensions in two locations:
|
||||
|
||||
1. `<workspace>/.gemini/extensions`
|
||||
2. `<home>/.gemini/extensions`
|
||||
1. `<workspace>/.qwen/extensions`
|
||||
2. `<home>/.qwen/extensions`
|
||||
|
||||
Gemini CLI loads all extensions from both locations. If an extension with the same name exists in both locations, the extension in the workspace directory takes precedence.
|
||||
Qwen Code loads all extensions from both locations. If an extension with the same name exists in both locations, the extension in the workspace directory takes precedence.
|
||||
|
||||
Within each location, individual extensions exist as a directory that contains a `gemini-extension.json` file. For example:
|
||||
Within each location, individual extensions exist as a directory that contains a `qwen-extension.json` file. For example:
|
||||
|
||||
`<workspace>/.gemini/extensions/my-extension/gemini-extension.json`
|
||||
`<workspace>/.qwen/extensions/my-extension/qwen-extension.json`
|
||||
|
||||
### `gemini-extension.json`
|
||||
### `qwen-extension.json`
|
||||
|
||||
The `gemini-extension.json` file contains the configuration for the extension. The file has the following structure:
|
||||
The `qwen-extension.json` file contains the configuration for the extension. The file has the following structure:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -39,7 +39,7 @@ The `gemini-extension.json` file contains the configuration for the extension. T
|
||||
- `contextFileName`: The name of the file that contains the context for the extension. This will be used to load the context from the workspace. If this property is not used but a `QWEN.md` file is present in your extension directory, then that file will be loaded.
|
||||
- `excludeTools`: An array of tool names to exclude from the model. You can also specify command-specific restrictions for tools that support it, like the `run_shell_command` tool. For example, `"excludeTools": ["run_shell_command(rm -rf)"]` will block the `rm -rf` command.
|
||||
|
||||
When Gemini CLI starts, it loads all the extensions and merges their configurations. If there are any conflicts, the workspace configuration takes precedence.
|
||||
When Qwen Code starts, it loads all the extensions and merges their configurations. If there are any conflicts, the workspace configuration takes precedence.
|
||||
|
||||
## Extension Commands
|
||||
|
||||
@@ -50,8 +50,8 @@ Extensions can provide [custom commands](./cli/commands.md#custom-commands) by p
|
||||
An extension named `gcp` with the following structure:
|
||||
|
||||
```
|
||||
.gemini/extensions/gcp/
|
||||
├── gemini-extension.json
|
||||
.qwen/extensions/gcp/
|
||||
├── qwen-extension.json
|
||||
└── commands/
|
||||
├── deploy.toml
|
||||
└── gcs/
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Ignoring Files
|
||||
|
||||
This document provides an overview of the Gemini Ignore (`.geminiignore`) feature of the Gemini CLI.
|
||||
This document provides an overview of the Gemini Ignore (`.geminiignore`) feature of Qwen Code.
|
||||
|
||||
The Gemini CLI includes the ability to automatically ignore files, similar to `.gitignore` (used by Git) and `.aiexclude` (used by Gemini Code Assist). Adding paths to your `.geminiignore` file will exclude them from tools that support this feature, although they will still be visible to other services (such as Git).
|
||||
Qwen Code includes the ability to automatically ignore files, similar to `.gitignore` (used by Git) and `.aiexclude` (used by Gemini Code Assist). Adding paths to your `.geminiignore` file will exclude them from tools that support this feature, although they will still be visible to other services (such as Git).
|
||||
|
||||
## How it works
|
||||
|
||||
@@ -16,7 +16,7 @@ For the most part, `.geminiignore` follows the conventions of `.gitignore` files
|
||||
- Putting a `/` at the beginning anchors the path relative to the `.geminiignore` file.
|
||||
- `!` negates a pattern.
|
||||
|
||||
You can update your `.geminiignore` file at any time. To apply the changes, you must restart your Gemini CLI session.
|
||||
You can update your `.geminiignore` file at any time. To apply the changes, you must restart your Qwen Code session.
|
||||
|
||||
## How to use `.geminiignore`
|
||||
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
# Welcome to Gemini CLI documentation
|
||||
# Welcome to Qwen Code documentation
|
||||
|
||||
This documentation provides a comprehensive guide to installing, using, and developing Gemini CLI. This tool lets you interact with Gemini models through a command-line interface.
|
||||
This documentation provides a comprehensive guide to installing, using, and developing Qwen Code. This tool lets you interact with AI models through a command-line interface.
|
||||
|
||||
## Overview
|
||||
|
||||
Gemini CLI brings the capabilities of Gemini models to your terminal in an interactive Read-Eval-Print Loop (REPL) environment. Gemini CLI consists of a client-side application (`packages/cli`) that communicates with a local server (`packages/core`), which in turn manages requests to the Gemini API and its AI models. Gemini CLI also contains a variety of tools for tasks such as performing file system operations, running shells, and web fetching, which are managed by `packages/core`.
|
||||
Qwen Code brings the capabilities of advanced code models to your terminal in an interactive Read-Eval-Print Loop (REPL) environment. Qwen Code consists of a client-side application (`packages/cli`) that communicates with a local server (`packages/core`). Qwen Code also contains a variety of tools for tasks such as performing file system operations, running shells, and web fetching, which are managed by `packages/core`.
|
||||
|
||||
## Navigating the documentation
|
||||
|
||||
This documentation is organized into the following sections:
|
||||
|
||||
- **[Execution and Deployment](./deployment.md):** Information for running Gemini CLI.
|
||||
- **[Architecture Overview](./architecture.md):** Understand the high-level design of Gemini CLI, including its components and how they interact.
|
||||
- **[Execution and Deployment](./deployment.md):** Information for running Qwen Code.
|
||||
- **[Architecture Overview](./architecture.md):** Understand the high-level design of Qwen Code, including its components and how they interact.
|
||||
- **CLI Usage:** Documentation for `packages/cli`.
|
||||
- **[CLI Introduction](./cli/index.md):** Overview of the command-line interface.
|
||||
- **[Commands](./cli/commands.md):** Description of available CLI commands.
|
||||
@@ -33,6 +33,6 @@ This documentation is organized into the following sections:
|
||||
- **[Contributing & Development Guide](../CONTRIBUTING.md):** Information for contributors and developers, including setup, building, testing, and coding conventions.
|
||||
- **[NPM Workspaces and Publishing](./npm.md):** Details on how the project's packages are managed and published.
|
||||
- **[Troubleshooting Guide](./troubleshooting.md):** Find solutions to common problems and FAQs.
|
||||
- **[Terms of Service and Privacy Notice](./tos-privacy.md):** Information on the terms of service and privacy notices applicable to your use of Gemini CLI.
|
||||
- **[Terms of Service and Privacy Notice](./tos-privacy.md):** Information on the terms of service and privacy notices applicable to your use of Qwen Code.
|
||||
|
||||
We hope this documentation helps you make the most of the Gemini CLI!
|
||||
We hope this documentation helps you make the most of Qwen Code!
|
||||
|
||||
@@ -4,7 +4,7 @@ This document provides information about the integration testing framework used
|
||||
|
||||
## Overview
|
||||
|
||||
The integration tests are designed to validate the end-to-end functionality of the Gemini CLI. They execute the built binary in a controlled environment and verify that it behaves as expected when interacting with the file system.
|
||||
The integration tests are designed to validate the end-to-end functionality of Qwen Code. They execute the built binary in a controlled environment and verify that it behaves as expected when interacting with the file system.
|
||||
|
||||
These tests are located in the `integration-tests` directory and are run using a custom test runner.
|
||||
|
||||
@@ -81,7 +81,7 @@ When output is kept, the test runner will print the path to the unique directory
|
||||
|
||||
### Verbose output
|
||||
|
||||
For more detailed debugging, the `--verbose` flag streams the real-time output from the `gemini` command to the console.
|
||||
For more detailed debugging, the `--verbose` flag streams the real-time output from the `qwen` command to the console.
|
||||
|
||||
```bash
|
||||
npm run test:integration:sandbox:none -- --verbose
|
||||
@@ -93,7 +93,7 @@ The verbose output is formatted to clearly identify the source of the logs:
|
||||
|
||||
```
|
||||
--- TEST: <file-name-without-js>:<test-name> ---
|
||||
... output from the gemini command ...
|
||||
... output from the qwen command ...
|
||||
--- END TEST: <file-name-without-js>:<test-name> ---
|
||||
```
|
||||
|
||||
@@ -109,10 +109,10 @@ To check for linting errors, run the following command:
|
||||
npm run lint
|
||||
```
|
||||
|
||||
You can include the `--fix` flag in the command to automatically fix any fixable linting errors:
|
||||
You can include the `:fix` flag in the command to automatically fix any fixable linting errors:
|
||||
|
||||
```bash
|
||||
npm run lint --fix
|
||||
npm run lint:fix
|
||||
```
|
||||
|
||||
## Directory structure
|
||||
@@ -134,7 +134,7 @@ This structure makes it easy to locate the artifacts for a specific test run, fi
|
||||
|
||||
To ensure the integration tests are always run, a GitHub Actions workflow is defined in `.github/workflows/e2e.yml`. This workflow automatically runs the integrations tests for pull requests against the `main` branch, or when a pull request is added to a merge queue.
|
||||
|
||||
The workflow runs the tests in different sandboxing environments to ensure Gemini CLI is tested across each:
|
||||
The workflow runs the tests in different sandboxing environments to ensure Qwen Code is tested across each:
|
||||
|
||||
- `sandbox:none`: Runs the tests without any sandboxing.
|
||||
- `sandbox:docker`: Runs the tests in a Docker container.
|
||||
|
||||
@@ -71,7 +71,7 @@ This is a fallback workflow to ensure that no issue gets missed by the triage pr
|
||||
|
||||
### 5. Release Automation
|
||||
|
||||
This workflow handles the process of packaging and publishing new versions of the Gemini CLI.
|
||||
This workflow handles the process of packaging and publishing new versions of Qwen Code.
|
||||
|
||||
- **Workflow File**: `.github/workflows/release.yml`
|
||||
- **When it runs**: On a daily schedule for "nightly" releases, and manually for official patch/minor releases.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Gemini CLI Keyboard Shortcuts
|
||||
# Qwen Code Keyboard Shortcuts
|
||||
|
||||
This document lists the available keyboard shortcuts in the Gemini CLI.
|
||||
This document lists the available keyboard shortcuts in Qwen Code.
|
||||
|
||||
## General
|
||||
|
||||
|
||||
30
docs/npm.md
30
docs/npm.md
@@ -1,16 +1,16 @@
|
||||
# Package Overview
|
||||
|
||||
This monorepo contains two main packages: `@google/gemini-cli` and `@google/gemini-cli-core`.
|
||||
This monorepo contains two main packages: `@qwen-code/qwen-code` and `@qwen-code/qwen-code-core`.
|
||||
|
||||
## `@google/gemini-cli`
|
||||
## `@qwen-code/qwen-code`
|
||||
|
||||
This is the main package for the Gemini CLI. It is responsible for the user interface, command parsing, and all other user-facing functionality.
|
||||
This is the main package for Qwen Code. It is responsible for the user interface, command parsing, and all other user-facing functionality.
|
||||
|
||||
When this package is published, it is bundled into a single executable file. This bundle includes all of the package's dependencies, including `@google/gemini-cli-core`. This means that whether a user installs the package with `npm install -g @google/gemini-cli` or runs it directly with `npx @google/gemini-cli`, they are using this single, self-contained executable.
|
||||
When this package is published, it is bundled into a single executable file. This bundle includes all of the package's dependencies, including `@qwen-code/qwen-code-core`. This means that whether a user installs the package with `npm install -g @qwen-code/qwen-code` or runs it directly with `npx @qwen-code/qwen-code`, they are using this single, self-contained executable.
|
||||
|
||||
## `@google/gemini-cli-core`
|
||||
## `@qwen-code/qwen-code-core`
|
||||
|
||||
This package contains the core logic for interacting with the Gemini API. It is responsible for making API requests, handling authentication, and managing the local cache.
|
||||
This package contains the core logic for the CLI. It is responsible for making API requests to configured providers, handling authentication, and managing the local cache.
|
||||
|
||||
This package is not bundled. When it is published, it is published as a standard Node.js package with its own dependencies. This allows it to be used as a standalone package in other projects, if needed. All transpiled js code in the `dist` folder is included in the package.
|
||||
|
||||
@@ -20,7 +20,7 @@ This project follows a structured release process to ensure that all packages ar
|
||||
|
||||
## How To Release
|
||||
|
||||
Releases are managed through the [release.yml](https://github.com/google-gemini/gemini-cli/actions/workflows/release.yml) GitHub Actions workflow. To perform a manual release for a patch or hotfix:
|
||||
Releases are managed through the [release.yml](https://github.com/QwenLM/qwen-code/actions/workflows/release.yml) GitHub Actions workflow. To perform a manual release for a patch or hotfix:
|
||||
|
||||
1. Navigate to the **Actions** tab of the repository.
|
||||
2. Select the **Release** workflow from the list.
|
||||
@@ -37,7 +37,7 @@ In addition to manual releases, this project has an automated nightly release pr
|
||||
|
||||
### Process
|
||||
|
||||
Every night at midnight UTC, the [Release workflow](https://github.com/google-gemini/gemini-cli/actions/workflows/release.yml) runs automatically on a schedule. It performs the following steps:
|
||||
Every night at midnight UTC, the [Release workflow](https://github.com/QwenLM/qwen-code/actions/workflows/release.yml) runs automatically on a schedule. It performs the following steps:
|
||||
|
||||
1. Checks out the latest code from the `main` branch.
|
||||
2. Installs all dependencies.
|
||||
@@ -55,16 +55,16 @@ If any step in the nightly workflow fails, it will automatically create a new is
|
||||
To install the latest nightly build, use the `@nightly` tag:
|
||||
|
||||
```bash
|
||||
npm install -g @google/gemini-cli@nightly
|
||||
npm install -g @qwen-code/qwen-code@nightly
|
||||
```
|
||||
|
||||
We also run a Google cloud build called [release-docker.yml](../.gcp/release-docker.yaml). Which publishes the sandbox docker to match your release. This will also be moved to GH and combined with the main release file once service account permissions are sorted out.
|
||||
|
||||
### After the Release
|
||||
|
||||
After the workflow has successfully completed, you can monitor its progress in the [GitHub Actions tab](https://github.com/google-gemini/gemini-cli/actions/workflows/release.yml). Once complete, you should:
|
||||
After the workflow has successfully completed, you can monitor its progress in the [GitHub Actions tab](https://github.com/QwenLM/qwen-code/actions/workflows/release.yml). Once complete, you should:
|
||||
|
||||
1. Go to the [pull requests page](https://github.com/google-gemini/gemini-cli/pulls) of the repository.
|
||||
1. Go to the [pull requests page](https://github.com/QwenLM/qwen-code/pulls) of the repository.
|
||||
2. Create a new pull request from the `release/vX.Y.Z` branch to `main`.
|
||||
3. Review the pull request (it should only contain version updates in `package.json` files) and merge it. This keeps the version in `main` up-to-date.
|
||||
|
||||
@@ -72,9 +72,9 @@ After the workflow has successfully completed, you can monitor its progress in t
|
||||
|
||||
After pushing a new release smoke testing should be performed to ensure that the packages are working as expected. This can be done by installing the packages locally and running a set of tests to ensure that they are functioning correctly.
|
||||
|
||||
- `npx -y @google/gemini-cli@latest --version` to validate the push worked as expected if you were not doing a rc or dev tag
|
||||
- `npx -y @google/gemini-cli@<release tag> --version` to validate the tag pushed appropriately
|
||||
- _This is destructive locally_ `npm uninstall @google/gemini-cli && npm uninstall -g @google/gemini-cli && npm cache clean --force && npm install @google/gemini-cli@<version>`
|
||||
- `npx -y @qwen-code/qwen-code@latest --version` to validate the push worked as expected if you were not doing a rc or dev tag
|
||||
- `npx -y @qwen-code/qwen-code@<release tag> --version` to validate the tag pushed appropriately
|
||||
- _This is destructive locally_ `npm uninstall @qwen-code/qwen-code && npm uninstall -g @qwen-code/qwen-code && npm cache clean --force && npm install @qwen-code/qwen-code@<version>`
|
||||
- Smoke testing a basic run through of exercising a few llm commands and tools is recommended to ensure that the packages are working as expected. We'll codify this more in the future.
|
||||
|
||||
## When to merge the version change, or not?
|
||||
@@ -126,7 +126,7 @@ You typically do not merge release branches for pre-releases back into `main`.
|
||||
|
||||
If you need to test the release process without actually publishing to NPM or creating a public GitHub release, you can trigger the workflow manually from the GitHub UI.
|
||||
|
||||
1. Go to the [Actions tab](https://github.com/google-gemini/gemini-cli/actions/workflows/release.yml) of the repository.
|
||||
1. Go to the [Actions tab](https://github.com/QwenLM/qwen-code/actions/workflows/release.yml) of the repository.
|
||||
2. Click on the "Run workflow" dropdown.
|
||||
3. Leave the `dry_run` option checked (`true`).
|
||||
4. Click the "Run workflow" button.
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
# Gemini CLI: Quotas and Pricing
|
||||
|
||||
Your Gemini CLI quotas and pricing depend on the type of account you use to authenticate with Google. Additionally, both quotas and pricing may be calculated differently based on the model version, requests, and tokens used. A summary of model usage is available through the `/stats` command and presented on exit at the end of a session. See [privacy and terms](./tos-privacy.md) for details on Privacy policy and Terms of Service. Note: published prices are list price; additional negotiated commercial discounting may apply.
|
||||
|
||||
This article outlines the specific quotas and pricing applicable to the Gemini CLI when using different authentication methods.
|
||||
|
||||
## 1. Log in with Google (Gemini Code Assist Free Tier)
|
||||
|
||||
For users who authenticate by using their Google account to access Gemini Code Assist for individuals:
|
||||
|
||||
- **Quota:**
|
||||
- 60 requests per minute
|
||||
- 1000 requests per day
|
||||
- Token usage is not applicable
|
||||
- **Cost:** Free
|
||||
- **Details:** [Gemini Code Assist Quotas](https://developers.google.com/gemini-code-assist/resources/quotas#quotas-for-agent-mode-gemini-cli)
|
||||
- **Notes:** A specific quota for different models is not specified; model fallback may occur to preserve shared experience quality.
|
||||
|
||||
## 2. Gemini API Key (Unpaid)
|
||||
|
||||
If you are using a Gemini API key for the free tier:
|
||||
|
||||
- **Quota:**
|
||||
- Flash model only
|
||||
- 10 requests per minute
|
||||
- 250 requests per day
|
||||
- **Cost:** Free
|
||||
- **Details:** [Gemini API Rate Limits](https://ai.google.dev/gemini-api/docs/rate-limits)
|
||||
|
||||
## 3. Gemini API Key (Paid)
|
||||
|
||||
If you are using a Gemini API key with a paid plan:
|
||||
|
||||
- **Quota:** Varies by pricing tier.
|
||||
- **Cost:** Varies by pricing tier and model/token usage.
|
||||
- **Details:** [Gemini API Rate Limits](https://ai.google.dev/gemini-api/docs/rate-limits), [Gemini API Pricing](https://ai.google.dev/gemini-api/docs/pricing)
|
||||
|
||||
## 4. Login with Google (for Workspace or Licensed Code Assist users)
|
||||
|
||||
For users of Standard or Enterprise editions of Gemini Code Assist, quotas and pricing are based on a fixed price subscription with assigned license seats:
|
||||
|
||||
- **Standard Tier:**
|
||||
- **Quota:** 120 requests per minute, 1500 per day
|
||||
- **Enterprise Tier:**
|
||||
- **Quota:** 120 requests per minute, 2000 per day
|
||||
- **Cost:** Fixed price included with your Gemini for Google Workspace or Gemini Code Assist subscription.
|
||||
- **Details:** [Gemini Code Assist Quotas](https://developers.google.com/gemini-code-assist/resources/quotas#quotas-for-agent-mode-gemini-cli), [Gemini Code Assist Pricing](https://cloud.google.com/products/gemini/pricing)
|
||||
- **Notes:**
|
||||
- Specific quota for different models is not specified; model fallback may occur to preserve shared experience quality.
|
||||
- Members of the Google Developer Program may have Gemini Code Assist licenses through their membership.
|
||||
|
||||
## 5. Vertex AI (Express Mode)
|
||||
|
||||
If you are using Vertex AI in Express Mode:
|
||||
|
||||
- **Quota:** Quotas are variable and specific to your account. See the source for more details.
|
||||
- **Cost:** After your Express Mode usage is consumed and you enable billing for your project, cost is based on standard [Vertex AI Pricing](https://cloud.google.com/vertex-ai/pricing).
|
||||
- **Details:** [Vertex AI Express Mode Quotas](https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#quotas)
|
||||
|
||||
## 6. Vertex AI (Regular Mode)
|
||||
|
||||
If you are using the standard Vertex AI service:
|
||||
|
||||
- **Quota:** Governed by a dynamic shared quota system or pre-purchased provisioned throughput.
|
||||
- **Cost:** Based on model and token usage. See [Vertex AI Pricing](https://cloud.google.com/vertex-ai/pricing).
|
||||
- **Details:** [Vertex AI Dynamic Shared Quota](https://cloud.google.com/vertex-ai/generative-ai/docs/resources/dynamic-shared-quota)
|
||||
|
||||
## 7. Google One and Ultra plans, Gemini for Workspace plans
|
||||
|
||||
These plans currently apply only to the use of Gemini web-based products provided by Google-based experiences (for example, the Gemini web app or the Flow video editor). These plans do not apply to the API usage which powers the Gemini CLI. Supporting these plans is under active consideration for future support.
|
||||
@@ -1,19 +1,19 @@
|
||||
# Sandboxing in the Gemini CLI
|
||||
# Sandboxing in Qwen Code
|
||||
|
||||
This document provides a guide to sandboxing in the Gemini CLI, including prerequisites, quickstart, and configuration.
|
||||
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 the Gemini CLI:
|
||||
Before using sandboxing, you need to install and set up Qwen Code:
|
||||
|
||||
```bash
|
||||
npm install -g @google/gemini-cli
|
||||
npm install -g @qwen-code/qwen-code
|
||||
```
|
||||
|
||||
To verify the installation
|
||||
|
||||
```bash
|
||||
gemini --version
|
||||
qwen --version
|
||||
```
|
||||
|
||||
## Overview of sandboxing
|
||||
@@ -47,11 +47,11 @@ Cross-platform sandboxing with complete process isolation.
|
||||
|
||||
```bash
|
||||
# Enable sandboxing with command flag
|
||||
gemini -s -p "analyze the code structure"
|
||||
qwen -s -p "analyze the code structure"
|
||||
|
||||
# Use environment variable
|
||||
export GEMINI_SANDBOX=true
|
||||
gemini -p "run the test suite"
|
||||
qwen -p "run the test suite"
|
||||
|
||||
# Configure in settings.json
|
||||
{
|
||||
@@ -126,19 +126,19 @@ export SANDBOX_SET_UID_GID=false # Disable UID/GID mapping
|
||||
### Debug mode
|
||||
|
||||
```bash
|
||||
DEBUG=1 gemini -s -p "debug command"
|
||||
DEBUG=1 qwen -s -p "debug command"
|
||||
```
|
||||
|
||||
**Note:** If you have `DEBUG=true` in a project's `.env` file, it won't affect gemini-cli due to automatic exclusion. Use `.gemini/.env` files for gemini-cli specific debug settings.
|
||||
**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
|
||||
gemini -s -p "run shell command: env | grep SANDBOX"
|
||||
qwen -s -p "run shell command: env | grep SANDBOX"
|
||||
|
||||
# List mounts
|
||||
gemini -s -p "run shell command: mount | grep workspace"
|
||||
qwen -s -p "run shell command: mount | grep workspace"
|
||||
```
|
||||
|
||||
## Security notes
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
# Gemini CLI Observability Guide
|
||||
# Qwen Code Observability Guide
|
||||
|
||||
Telemetry provides data about Gemini CLI's performance, health, and usage. By enabling it, you can monitor operations, debug issues, and optimize tool usage through traces, metrics, and structured logs.
|
||||
Telemetry provides data about Qwen Code's performance, health, and usage. By enabling it, you can monitor operations, debug issues, and optimize tool usage through traces, metrics, and structured logs.
|
||||
|
||||
Gemini CLI's telemetry system is built on the **[OpenTelemetry] (OTEL)** standard, allowing you to send data to any compatible backend.
|
||||
Qwen Code's telemetry system is built on the **[OpenTelemetry] (OTEL)** standard, allowing you to send data to any compatible backend.
|
||||
|
||||
[OpenTelemetry]: https://opentelemetry.io/
|
||||
|
||||
## Enabling telemetry
|
||||
|
||||
You can enable telemetry in multiple ways. Configuration is primarily managed via the [`.gemini/settings.json` file](./cli/configuration.md) and environment variables, but CLI flags can override these settings for a specific session.
|
||||
You can enable telemetry in multiple ways. Configuration is primarily managed via the [`.qwen/settings.json` file](./cli/configuration.md) and environment variables, but CLI flags can override these settings for a specific session.
|
||||
|
||||
### Order of precedence
|
||||
|
||||
The following lists the precedence for applying telemetry settings, with items listed higher having greater precedence:
|
||||
|
||||
1. **CLI flags (for `gemini` command):**
|
||||
1. **CLI flags (for `qwen` command):**
|
||||
- `--telemetry` / `--no-telemetry`: Overrides `telemetry.enabled`.
|
||||
- `--telemetry-target <local|gcp>`: Overrides `telemetry.target`.
|
||||
- `--telemetry-otlp-endpoint <URL>`: Overrides `telemetry.otlpEndpoint`.
|
||||
@@ -24,9 +24,9 @@ The following lists the precedence for applying telemetry settings, with items l
|
||||
1. **Environment variables:**
|
||||
- `OTEL_EXPORTER_OTLP_ENDPOINT`: Overrides `telemetry.otlpEndpoint`.
|
||||
|
||||
1. **Workspace settings file (`.gemini/settings.json`):** Values from the `telemetry` object in this project-specific file.
|
||||
1. **Workspace settings file (`.qwen/settings.json`):** Values from the `telemetry` object in this project-specific file.
|
||||
|
||||
1. **User settings file (`~/.gemini/settings.json`):** Values from the `telemetry` object in this global user file.
|
||||
1. **User settings file (`~/.qwen/settings.json`):** Values from the `telemetry` object in this global user file.
|
||||
|
||||
1. **Defaults:** applied if not set by any of the above.
|
||||
- `telemetry.enabled`: `false`
|
||||
@@ -39,7 +39,7 @@ The `--target` argument to this script _only_ overrides the `telemetry.target` f
|
||||
|
||||
### Example settings
|
||||
|
||||
The following code can be added to your workspace (`.gemini/settings.json`) or user (`~/.gemini/settings.json`) settings to enable telemetry and send the output to Google Cloud:
|
||||
The following code can be added to your workspace (`.qwen/settings.json`) or user (`~/.qwen/settings.json`) settings to enable telemetry and send the output to Google Cloud:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -58,7 +58,17 @@ You can export all telemetry data to a file for local inspection.
|
||||
To enable file export, use the `--telemetry-outfile` flag with a path to your desired output file. This must be run using `--telemetry-target=local`.
|
||||
|
||||
```bash
|
||||
gemini --telemetry --telemetry-target=local --telemetry-outfile=/path/to/telemetry.log "your prompt"
|
||||
# Set your desired output file path
|
||||
TELEMETRY_FILE=".qwen/telemetry.log"
|
||||
|
||||
# Run Qwen Code with local telemetry
|
||||
# NOTE: --telemetry-otlp-endpoint="" is required to override the default
|
||||
# OTLP exporter and ensure telemetry is written to the local file.
|
||||
qwen --telemetry \
|
||||
--telemetry-target=local \
|
||||
--telemetry-otlp-endpoint="" \
|
||||
--telemetry-outfile="$TELEMETRY_FILE" \
|
||||
--prompt "What is OpenTelemetry?"
|
||||
```
|
||||
|
||||
## Running an OTEL Collector
|
||||
@@ -72,7 +82,7 @@ Learn more about OTEL exporter standard configuration in [documentation][otel-co
|
||||
|
||||
### Local
|
||||
|
||||
Use the `npm run telemetry -- --target=local` command to automate the process of setting up a local telemetry pipeline, including configuring the necessary settings in your `.gemini/settings.json` file. The underlying script installs `otelcol-contrib` (the OpenTelemetry Collector) and `jaeger` (The Jaeger UI for viewing traces). To use it:
|
||||
Use the `npm run telemetry -- --target=local` command to automate the process of setting up a local telemetry pipeline, including configuring the necessary settings in your `.qwen/settings.json` file. The underlying script installs `otelcol-contrib` (the OpenTelemetry Collector) and `jaeger` (The Jaeger UI for viewing traces). To use it:
|
||||
|
||||
1. **Run the command**:
|
||||
Execute the command from the root of the repository:
|
||||
@@ -84,22 +94,22 @@ Use the `npm run telemetry -- --target=local` command to automate the process of
|
||||
The script will:
|
||||
- Download Jaeger and OTEL if needed.
|
||||
- Start a local Jaeger instance.
|
||||
- Start an OTEL collector configured to receive data from Gemini CLI.
|
||||
- Start an OTEL collector configured to receive data from Qwen Code.
|
||||
- Automatically enable telemetry in your workspace settings.
|
||||
- On exit, disable telemetry.
|
||||
|
||||
1. **View traces**:
|
||||
Open your web browser and navigate to **http://localhost:16686** to access the Jaeger UI. Here you can inspect detailed traces of Gemini CLI operations.
|
||||
Open your web browser and navigate to **http://localhost:16686** to access the Jaeger UI. Here you can inspect detailed traces of Qwen Code operations.
|
||||
|
||||
1. **Inspect logs and metrics**:
|
||||
The script redirects the OTEL collector output (which includes logs and metrics) to `~/.gemini/tmp/<projectHash>/otel/collector.log`. The script will provide links to view and a command to tail your telemetry data (traces, metrics, logs) locally.
|
||||
The script redirects the OTEL collector output (which includes logs and metrics) to `~/.qwen/tmp/<projectHash>/otel/collector.log`. The script will provide links to view and a command to tail your telemetry data (traces, metrics, logs) locally.
|
||||
|
||||
1. **Stop the services**:
|
||||
Press `Ctrl+C` in the terminal where the script is running to stop the OTEL Collector and Jaeger services.
|
||||
|
||||
### Google Cloud
|
||||
|
||||
Use the `npm run telemetry -- --target=gcp` command to automate setting up a local OpenTelemetry collector that forwards data to your Google Cloud project, including configuring the necessary settings in your `.gemini/settings.json` file. The underlying script installs `otelcol-contrib`. To use it:
|
||||
Use the `npm run telemetry -- --target=gcp` command to automate setting up a local OpenTelemetry collector that forwards data to your Google Cloud project, including configuring the necessary settings in your `.qwen/settings.json` file. The underlying script installs `otelcol-contrib`. To use it:
|
||||
|
||||
1. **Prerequisites**:
|
||||
- Have a Google Cloud project ID.
|
||||
@@ -119,34 +129,34 @@ Use the `npm run telemetry -- --target=gcp` command to automate setting up a loc
|
||||
|
||||
The script will:
|
||||
- Download the `otelcol-contrib` binary if needed.
|
||||
- Start an OTEL collector configured to receive data from Gemini CLI and export it to your specified Google Cloud project.
|
||||
- Automatically enable telemetry and disable sandbox mode in your workspace settings (`.gemini/settings.json`).
|
||||
- Start an OTEL collector configured to receive data from Qwen Code and export it to your specified Google Cloud project.
|
||||
- Automatically enable telemetry and disable sandbox mode in your workspace settings (`.qwen/settings.json`).
|
||||
- Provide direct links to view traces, metrics, and logs in your Google Cloud Console.
|
||||
- On exit (Ctrl+C), it will attempt to restore your original telemetry and sandbox settings.
|
||||
|
||||
1. **Run Gemini CLI:**
|
||||
In a separate terminal, run your Gemini CLI commands. This generates telemetry data that the collector captures.
|
||||
1. **Run Qwen Code:**
|
||||
In a separate terminal, run your Qwen Code commands. This generates telemetry data that the collector captures.
|
||||
|
||||
1. **View telemetry in Google Cloud**:
|
||||
Use the links provided by the script to navigate to the Google Cloud Console and view your traces, metrics, and logs.
|
||||
|
||||
1. **Inspect local collector logs**:
|
||||
The script redirects the local OTEL collector output to `~/.gemini/tmp/<projectHash>/otel/collector-gcp.log`. The script provides links to view and command to tail your collector logs locally.
|
||||
The script redirects the local OTEL collector output to `~/.qwen/tmp/<projectHash>/otel/collector-gcp.log`. The script provides links to view and command to tail your collector logs locally.
|
||||
|
||||
1. **Stop the service**:
|
||||
Press `Ctrl+C` in the terminal where the script is running to stop the OTEL Collector.
|
||||
|
||||
## Logs and metric reference
|
||||
|
||||
The following section describes the structure of logs and metrics generated for Gemini CLI.
|
||||
The following section describes the structure of logs and metrics generated for Qwen Code.
|
||||
|
||||
- A `sessionId` is included as a common attribute on all logs and metrics.
|
||||
|
||||
### Logs
|
||||
|
||||
Logs are timestamped records of specific events. The following events are logged for Gemini CLI:
|
||||
Logs are timestamped records of specific events. The following events are logged for Qwen Code:
|
||||
|
||||
- `gemini_cli.config`: This event occurs once at startup with the CLI's configuration.
|
||||
- `qwen-code.config`: This event occurs once at startup with the CLI's configuration.
|
||||
- **Attributes**:
|
||||
- `model` (string)
|
||||
- `embedding_model` (string)
|
||||
@@ -161,28 +171,29 @@ Logs are timestamped records of specific events. The following events are logged
|
||||
- `debug_mode` (boolean)
|
||||
- `mcp_servers` (string)
|
||||
|
||||
- `gemini_cli.user_prompt`: This event occurs when a user submits a prompt.
|
||||
- `qwen-code.user_prompt`: This event occurs when a user submits a prompt.
|
||||
- **Attributes**:
|
||||
- `prompt_length`
|
||||
- `prompt` (this attribute is excluded if `log_prompts_enabled` is configured to be `false`)
|
||||
- `auth_type`
|
||||
|
||||
- `gemini_cli.tool_call`: This event occurs for each function call.
|
||||
- `qwen-code.tool_call`: This event occurs for each function call.
|
||||
- **Attributes**:
|
||||
- `function_name`
|
||||
- `function_args`
|
||||
- `duration_ms`
|
||||
- `success` (boolean)
|
||||
- `decision` (string: "accept", "reject", or "modify", if applicable)
|
||||
- `decision` (string: "accept", "reject", "auto_accept", or "modify", if applicable)
|
||||
- `error` (if applicable)
|
||||
- `error_type` (if applicable)
|
||||
- `metadata` (if applicable, dictionary of string -> any)
|
||||
|
||||
- `gemini_cli.api_request`: This event occurs when making a request to Gemini API.
|
||||
- `qwen-code.api_request`: This event occurs when making a request to Gemini API.
|
||||
- **Attributes**:
|
||||
- `model`
|
||||
- `request_text` (if applicable)
|
||||
|
||||
- `gemini_cli.api_error`: This event occurs if the API request fails.
|
||||
- `qwen-code.api_error`: This event occurs if the API request fails.
|
||||
- **Attributes**:
|
||||
- `model`
|
||||
- `error`
|
||||
@@ -191,7 +202,7 @@ Logs are timestamped records of specific events. The following events are logged
|
||||
- `duration_ms`
|
||||
- `auth_type`
|
||||
|
||||
- `gemini_cli.api_response`: This event occurs upon receiving a response from Gemini API.
|
||||
- `qwen-code.api_response`: This event occurs upon receiving a response from Gemini API.
|
||||
- **Attributes**:
|
||||
- `model`
|
||||
- `status_code`
|
||||
@@ -205,50 +216,54 @@ Logs are timestamped records of specific events. The following events are logged
|
||||
- `response_text` (if applicable)
|
||||
- `auth_type`
|
||||
|
||||
- `gemini_cli.flash_fallback`: This event occurs when Gemini CLI switches to flash as fallback.
|
||||
- `qwen-code.flash_fallback`: This event occurs when Qwen Code switches to flash as fallback.
|
||||
- **Attributes**:
|
||||
- `auth_type`
|
||||
|
||||
- `gemini_cli.slash_command`: This event occurs when a user executes a slash command.
|
||||
- `qwen-code.slash_command`: This event occurs when a user executes a slash command.
|
||||
- **Attributes**:
|
||||
- `command` (string)
|
||||
- `subcommand` (string, if applicable)
|
||||
|
||||
### Metrics
|
||||
|
||||
Metrics are numerical measurements of behavior over time. The following metrics are collected for Gemini CLI:
|
||||
Metrics are numerical measurements of behavior over time. The following metrics are collected for Qwen Code (metric names remain `qwen-code.*` for compatibility):
|
||||
|
||||
- `gemini_cli.session.count` (Counter, Int): Incremented once per CLI startup.
|
||||
- `qwen-code.session.count` (Counter, Int): Incremented once per CLI startup.
|
||||
|
||||
- `gemini_cli.tool.call.count` (Counter, Int): Counts tool calls.
|
||||
- `qwen-code.tool.call.count` (Counter, Int): Counts tool calls.
|
||||
- **Attributes**:
|
||||
- `function_name`
|
||||
- `success` (boolean)
|
||||
- `decision` (string: "accept", "reject", or "modify", if applicable)
|
||||
|
||||
- `gemini_cli.tool.call.latency` (Histogram, ms): Measures tool call latency.
|
||||
- `qwen-code.tool.call.latency` (Histogram, ms): Measures tool call latency.
|
||||
- **Attributes**:
|
||||
- `function_name`
|
||||
- `decision` (string: "accept", "reject", or "modify", if applicable)
|
||||
|
||||
- `gemini_cli.api.request.count` (Counter, Int): Counts all API requests.
|
||||
- `qwen-code.api.request.count` (Counter, Int): Counts all API requests.
|
||||
- **Attributes**:
|
||||
- `model`
|
||||
- `status_code`
|
||||
- `error_type` (if applicable)
|
||||
|
||||
- `gemini_cli.api.request.latency` (Histogram, ms): Measures API request latency.
|
||||
- `qwen-code.api.request.latency` (Histogram, ms): Measures API request latency.
|
||||
- **Attributes**:
|
||||
- `model`
|
||||
|
||||
- `gemini_cli.token.usage` (Counter, Int): Counts the number of tokens used.
|
||||
- `qwen-code.token.usage` (Counter, Int): Counts the number of tokens used.
|
||||
- **Attributes**:
|
||||
- `model`
|
||||
- `type` (string: "input", "output", "thought", "cache", or "tool")
|
||||
|
||||
- `gemini_cli.file.operation.count` (Counter, Int): Counts file operations.
|
||||
- `qwen-code.file.operation.count` (Counter, Int): Counts file operations.
|
||||
- **Attributes**:
|
||||
- `operation` (string: "create", "read", "update"): The type of file operation.
|
||||
- `lines` (Int, if applicable): Number of lines in the file.
|
||||
- `mimetype` (string, if applicable): Mimetype of the file.
|
||||
- `extension` (string, if applicable): File extension of the file.
|
||||
- `ai_added_lines` (Int, if applicable): Number of lines added/changed by AI.
|
||||
- `ai_removed_lines` (Int, if applicable): Number of lines removed/changed by AI.
|
||||
- `user_added_lines` (Int, if applicable): Number of lines added/changed by user in AI proposed changes.
|
||||
- `user_removed_lines` (Int, if applicable): Number of lines removed/changed by user in AI proposed changes.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Gemini CLI file system tools
|
||||
# Qwen Code file system tools
|
||||
|
||||
The Gemini CLI provides a comprehensive suite of tools for interacting with the local file system. These tools allow the Gemini model to read from, write to, list, search, and modify files and directories, all under your control and typically with confirmation for sensitive operations.
|
||||
Qwen Code provides a comprehensive suite of tools for interacting with the local file system. These tools allow the model to read from, write to, list, search, and modify files and directories, all under your control and typically with confirmation for sensitive operations.
|
||||
|
||||
**Note:** All file system tools operate within a `rootDirectory` (usually the current working directory where you launched the CLI) for security. Paths that you provide to these tools are generally expected to be absolute or are resolved relative to this root directory.
|
||||
|
||||
@@ -140,4 +140,4 @@ The Gemini CLI provides a comprehensive suite of tools for interacting with the
|
||||
- On failure: An error message explaining the reason (e.g., `Failed to edit, 0 occurrences found...`, `Failed to edit, expected 1 occurrences but found 2...`).
|
||||
- **Confirmation:** Yes. Shows a diff of the proposed changes and asks for user approval before writing to the file.
|
||||
|
||||
These file system tools provide a foundation for the Gemini CLI to understand and interact with your local project context.
|
||||
These file system tools provide a foundation for Qwen Code to understand and interact with your local project context.
|
||||
|
||||
@@ -1,47 +1,47 @@
|
||||
# Gemini CLI tools
|
||||
# Qwen Code tools
|
||||
|
||||
The Gemini CLI includes built-in tools that the Gemini model uses to interact with your local environment, access information, and perform actions. These tools enhance the CLI's capabilities, enabling it to go beyond text generation and assist with a wide range of tasks.
|
||||
Qwen Code includes built-in tools that the model uses to interact with your local environment, access information, and perform actions. These tools enhance the CLI's capabilities, enabling it to go beyond text generation and assist with a wide range of tasks.
|
||||
|
||||
## Overview of Gemini CLI tools
|
||||
## Overview of Qwen Code tools
|
||||
|
||||
In the context of the Gemini CLI, tools are specific functions or modules that the Gemini model can request to be executed. For example, if you ask Gemini to "Summarize the contents of `my_document.txt`," the model will likely identify the need to read that file and will request the execution of the `read_file` tool.
|
||||
In the context of Qwen Code, tools are specific functions or modules that the model can request to be executed. For example, if you ask the model to "Summarize the contents of `my_document.txt`," it will likely identify the need to read that file and will request the execution of the `read_file` tool.
|
||||
|
||||
The core component (`packages/core`) manages these tools, presents their definitions (schemas) to the Gemini model, executes them when requested, and returns the results to the model for further processing into a user-facing response.
|
||||
The core component (`packages/core`) manages these tools, presents their definitions (schemas) to the model, executes them when requested, and returns the results to the model for further processing into a user-facing response.
|
||||
|
||||
These tools provide the following capabilities:
|
||||
|
||||
- **Access local information:** Tools allow Gemini to access your local file system, read file contents, list directories, etc.
|
||||
- **Execute commands:** With tools like `run_shell_command`, Gemini can run shell commands (with appropriate safety measures and user confirmation).
|
||||
- **Access local information:** Tools allow the model to access your local file system, read file contents, list directories, etc.
|
||||
- **Execute commands:** With tools like `run_shell_command`, the model can run shell commands (with appropriate safety measures and user confirmation).
|
||||
- **Interact with the web:** Tools can fetch content from URLs.
|
||||
- **Take actions:** Tools can modify files, write new files, or perform other actions on your system (again, typically with safeguards).
|
||||
- **Ground responses:** By using tools to fetch real-time or specific local data, Gemini's responses can be more accurate, relevant, and grounded in your actual context.
|
||||
- **Ground responses:** By using tools to fetch real-time or specific local data, responses can be more accurate, relevant, and grounded in your actual context.
|
||||
|
||||
## How to use Gemini CLI tools
|
||||
## How to use Qwen Code tools
|
||||
|
||||
To use Gemini CLI tools, provide a prompt to the Gemini CLI. The process works as follows:
|
||||
To use Qwen Code tools, provide a prompt to the CLI. The process works as follows:
|
||||
|
||||
1. You provide a prompt to the Gemini CLI.
|
||||
1. You provide a prompt to the CLI.
|
||||
2. The CLI sends the prompt to the core.
|
||||
3. The core, along with your prompt and conversation history, sends a list of available tools and their descriptions/schemas to the Gemini API.
|
||||
4. The Gemini model analyzes your request. If it determines that a tool is needed, its response will include a request to execute a specific tool with certain parameters.
|
||||
3. The core, along with your prompt and conversation history, sends a list of available tools and their descriptions/schemas to the configured model API.
|
||||
4. The model analyzes your request. If it determines that a tool is needed, its response will include a request to execute a specific tool with certain parameters.
|
||||
5. The core receives this tool request, validates it, and (often after user confirmation for sensitive operations) executes the tool.
|
||||
6. The output from the tool is sent back to the Gemini model.
|
||||
7. The Gemini model uses the tool's output to formulate its final answer, which is then sent back through the core to the CLI and displayed to you.
|
||||
6. The output from the tool is sent back to the model.
|
||||
7. The model uses the tool's output to formulate its final answer, which is then sent back through the core to the CLI and displayed to you.
|
||||
|
||||
You will typically see messages in the CLI indicating when a tool is being called and whether it succeeded or failed.
|
||||
|
||||
## Security and confirmation
|
||||
|
||||
Many tools, especially those that can modify your file system or execute commands (`write_file`, `edit`, `run_shell_command`), are designed with safety in mind. The Gemini CLI will typically:
|
||||
Many tools, especially those that can modify your file system or execute commands (`write_file`, `edit`, `run_shell_command`), are designed with safety in mind. Qwen Code will typically:
|
||||
|
||||
- **Require confirmation:** Prompt you before executing potentially sensitive operations, showing you what action is about to be taken.
|
||||
- **Utilize sandboxing:** All tools are subject to restrictions enforced by sandboxing (see [Sandboxing in the Gemini CLI](../sandbox.md)). This means that when operating in a sandbox, any tools (including MCP servers) you wish to use must be available _inside_ the sandbox environment. For example, to run an MCP server through `npx`, the `npx` executable must be installed within the sandbox's Docker image or be available in the `sandbox-exec` environment.
|
||||
- **Utilize sandboxing:** All tools are subject to restrictions enforced by sandboxing (see [Sandboxing in Qwen Code](../sandbox.md)). This means that when operating in a sandbox, any tools (including MCP servers) you wish to use must be available _inside_ the sandbox environment. For example, to run an MCP server through `npx`, the `npx` executable must be installed within the sandbox's Docker image or be available in the `sandbox-exec` environment.
|
||||
|
||||
It's important to always review confirmation prompts carefully before allowing a tool to proceed.
|
||||
|
||||
## Learn more about Gemini CLI's tools
|
||||
## Learn more about Qwen Code's tools
|
||||
|
||||
Gemini CLI's built-in tools can be broadly categorized as follows:
|
||||
Qwen Code's built-in tools can be broadly categorized as follows:
|
||||
|
||||
- **[File System Tools](./file-system.md):** For interacting with files and directories (reading, writing, listing, searching, etc.).
|
||||
- **[Shell Tool](./shell.md) (`run_shell_command`):** For executing shell commands.
|
||||
@@ -52,5 +52,5 @@ Gemini CLI's built-in tools can be broadly categorized as follows:
|
||||
|
||||
Additionally, these tools incorporate:
|
||||
|
||||
- **[MCP servers](./mcp-server.md)**: MCP servers act as a bridge between the Gemini model and your local environment or other services like APIs.
|
||||
- **[MCP servers](./mcp-server.md)**: MCP servers act as a bridge between the model and your local environment or other services like APIs.
|
||||
- **[Sandboxing](../sandbox.md)**: Sandboxing isolates the model and its changes from your environment to reduce potential risk.
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
# MCP servers with the Gemini CLI
|
||||
# MCP servers with Qwen Code
|
||||
|
||||
This document provides a guide to configuring and using Model Context Protocol (MCP) servers with the Gemini CLI.
|
||||
This document provides a guide to configuring and using Model Context Protocol (MCP) servers with Qwen Code.
|
||||
|
||||
## What is an MCP server?
|
||||
|
||||
An MCP server is an application that exposes tools and resources to the Gemini CLI through the Model Context Protocol, allowing it to interact with external systems and data sources. MCP servers act as a bridge between the Gemini model and your local environment or other services like APIs.
|
||||
An MCP server is an application that exposes tools and resources to the CLI through the Model Context Protocol, allowing it to interact with external systems and data sources. MCP servers act as a bridge between the model and your local environment or other services like APIs.
|
||||
|
||||
An MCP server enables the Gemini CLI to:
|
||||
An MCP server enables the CLI to:
|
||||
|
||||
- **Discover tools:** List available tools, their descriptions, and parameters through standardized schema definitions.
|
||||
- **Execute tools:** Call specific tools with defined arguments and receive structured responses.
|
||||
- **Access resources:** Read data from specific resources (though the Gemini CLI primarily focuses on tool execution).
|
||||
- **Access resources:** Read data from specific resources (though the CLI primarily focuses on tool execution).
|
||||
|
||||
With an MCP server, you can extend the Gemini CLI's capabilities to perform actions beyond its built-in features, such as interacting with databases, APIs, custom scripts, or specialized workflows.
|
||||
With an MCP server, you can extend the CLI's capabilities to perform actions beyond its built-in features, such as interacting with databases, APIs, custom scripts, or specialized workflows.
|
||||
|
||||
## Core Integration Architecture
|
||||
|
||||
The Gemini CLI integrates with MCP servers through a sophisticated discovery and execution system built into the core package (`packages/core/src/tools/`):
|
||||
Qwen Code integrates with MCP servers through a sophisticated discovery and execution system built into the core package (`packages/core/src/tools/`):
|
||||
|
||||
### Discovery Layer (`mcp-client.ts`)
|
||||
|
||||
@@ -39,7 +39,7 @@ Each discovered MCP tool is wrapped in a `DiscoveredMCPTool` instance that:
|
||||
|
||||
### Transport Mechanisms
|
||||
|
||||
The Gemini CLI supports three MCP transport types:
|
||||
The CLI supports three MCP transport types:
|
||||
|
||||
- **Stdio Transport:** Spawns a subprocess and communicates via stdin/stdout
|
||||
- **SSE Transport:** Connects to Server-Sent Events endpoints
|
||||
@@ -47,11 +47,11 @@ The Gemini CLI supports three MCP transport types:
|
||||
|
||||
## How to set up your MCP server
|
||||
|
||||
The Gemini CLI uses the `mcpServers` configuration in your `settings.json` file to locate and connect to MCP servers. This configuration supports multiple servers with different transport mechanisms.
|
||||
Qwen Code uses the `mcpServers` configuration in your `settings.json` file to locate and connect to MCP servers. This configuration supports multiple servers with different transport mechanisms.
|
||||
|
||||
### Configure the MCP server in settings.json
|
||||
|
||||
You can configure MCP servers at the global level in the `~/.gemini/settings.json` file or in your project's root directory, create or open the `.gemini/settings.json` file. Within the file, add the `mcpServers` configuration block.
|
||||
You can configure MCP servers at the global level in the `~/.qwen/settings.json` file or in your project's root directory, create or open the `.qwen/settings.json` file. Within the file, add the `mcpServers` configuration block.
|
||||
|
||||
### Configuration Structure
|
||||
|
||||
@@ -97,7 +97,7 @@ Each server configuration supports the following properties:
|
||||
|
||||
### OAuth Support for Remote MCP Servers
|
||||
|
||||
The Gemini CLI supports OAuth 2.0 authentication for remote MCP servers using SSE or HTTP transports. This enables secure access to MCP servers that require authentication.
|
||||
Qwen Code supports OAuth 2.0 authentication for remote MCP servers using SSE or HTTP transports. This enables secure access to MCP servers that require authentication.
|
||||
|
||||
#### Automatic OAuth Discovery
|
||||
|
||||
@@ -175,7 +175,7 @@ Use the `/mcp auth` command to manage OAuth authentication:
|
||||
|
||||
OAuth tokens are automatically:
|
||||
|
||||
- **Stored securely** in `~/.gemini/mcp-oauth-tokens.json`
|
||||
- **Stored securely** in `~/.qwen/mcp-oauth-tokens.json`
|
||||
- **Refreshed** when expired (if refresh tokens are available)
|
||||
- **Validated** before each connection attempt
|
||||
- **Cleaned up** when invalid or expired
|
||||
@@ -312,7 +312,7 @@ You can specify the authentication provider type using the `authProviderType` pr
|
||||
|
||||
## Discovery Process Deep Dive
|
||||
|
||||
When the Gemini CLI starts, it performs MCP server discovery through the following detailed process:
|
||||
When Qwen Code starts, it performs MCP server discovery through the following detailed process:
|
||||
|
||||
### 1. Server Iteration and Connection
|
||||
|
||||
@@ -347,7 +347,7 @@ When multiple servers expose tools with the same name:
|
||||
|
||||
### 4. Schema Processing
|
||||
|
||||
Tool parameter schemas undergo sanitization for Gemini API compatibility:
|
||||
Tool parameter schemas undergo sanitization for API compatibility:
|
||||
|
||||
- **`$schema` properties** are removed
|
||||
- **`additionalProperties`** are stripped
|
||||
@@ -364,7 +364,7 @@ After discovery:
|
||||
|
||||
## Tool Execution Flow
|
||||
|
||||
When the Gemini model decides to use an MCP tool, the following execution flow occurs:
|
||||
When the model decides to use an MCP tool, the following execution flow occurs:
|
||||
|
||||
### 1. Tool Invocation
|
||||
|
||||
@@ -570,7 +570,7 @@ The MCP integration tracks several states:
|
||||
- **Name sanitization:** Tool names are automatically sanitized to meet API requirements
|
||||
- **Conflict resolution:** Tool name conflicts between servers are resolved through automatic prefixing
|
||||
|
||||
This comprehensive integration makes MCP servers a powerful way to extend the Gemini CLI's capabilities while maintaining security, reliability, and ease of use.
|
||||
This comprehensive integration makes MCP servers a powerful way to extend the CLI's capabilities while maintaining security, reliability, and ease of use.
|
||||
|
||||
## Returning Rich Content from Tools
|
||||
|
||||
@@ -580,7 +580,7 @@ All data returned from the tool is processed and sent to the model as context fo
|
||||
|
||||
### How It Works
|
||||
|
||||
To return rich content, your tool's response must adhere to the MCP specification for a [`CallToolResult`](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#tool-result). The `content` field of the result should be an array of `ContentBlock` objects. The Gemini CLI will correctly process this array, separating text from binary data and packaging it for the model.
|
||||
To return rich content, your tool's response must adhere to the MCP specification for a [`CallToolResult`](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#tool-result). The `content` field of the result should be an array of `ContentBlock` objects. The CLI will correctly process this array, separating text from binary data and packaging it for the model.
|
||||
|
||||
You can mix and match different content block types in the `content` array. The supported block types include:
|
||||
|
||||
@@ -614,7 +614,7 @@ Here is an example of a valid JSON response from an MCP tool that returns both a
|
||||
}
|
||||
```
|
||||
|
||||
When the Gemini CLI receives this response, it will:
|
||||
When Qwen Code receives this response, it will:
|
||||
|
||||
1. Extract all the text and combine it into a single `functionResponse` part for the model.
|
||||
2. Present the image data as a separate `inlineData` part.
|
||||
@@ -624,7 +624,7 @@ This enables you to build sophisticated tools that can provide rich, multi-modal
|
||||
|
||||
## MCP Prompts as Slash Commands
|
||||
|
||||
In addition to tools, MCP servers can expose predefined prompts that can be executed as slash commands within the Gemini CLI. This allows you to create shortcuts for common or complex queries that can be easily invoked by name.
|
||||
In addition to tools, MCP servers can expose predefined prompts that can be executed as slash commands within Qwen Code. This allows you to create shortcuts for common or complex queries that can be easily invoked by name.
|
||||
|
||||
### Defining Prompts on the Server
|
||||
|
||||
@@ -678,13 +678,124 @@ This can be included in `settings.json` under `mcpServers` with:
|
||||
Once a prompt is discovered, you can invoke it using its name as a slash command. The CLI will automatically handle parsing arguments.
|
||||
|
||||
```bash
|
||||
/poem-writer --title="Gemini CLI" --mood="reverent"
|
||||
/poem-writer --title="Qwen Code" --mood="reverent"
|
||||
```
|
||||
|
||||
or, using positional arguments:
|
||||
|
||||
```bash
|
||||
/poem-writer "Gemini CLI" reverent
|
||||
/poem-writer "Qwen Code" reverent
|
||||
```
|
||||
|
||||
When you run this command, the Gemini CLI executes the `prompts/get` method on the MCP server with the provided arguments. The server is responsible for substituting the arguments into the prompt template and returning the final prompt text. The CLI then sends this prompt to the model for execution. This provides a convenient way to automate and share common workflows.
|
||||
When you run this command, the CLI executes the `prompts/get` method on the MCP server with the provided arguments. The server is responsible for substituting the arguments into the prompt template and returning the final prompt text. The CLI then sends this prompt to the model for execution. This provides a convenient way to automate and share common workflows.
|
||||
|
||||
## Managing MCP Servers with `qwen mcp`
|
||||
|
||||
While you can always configure MCP servers by manually editing your `settings.json` file, the CLI provides a convenient set of commands to manage your server configurations programmatically. These commands streamline the process of adding, listing, and removing MCP servers without needing to directly edit JSON files.
|
||||
|
||||
### Adding a Server (`qwen mcp add`)
|
||||
|
||||
The `add` command configures a new MCP server in your `settings.json`. Based on the scope (`-s, --scope`), it will be added to either the user config `~/.qwen/settings.json` or the project config `.qwen/settings.json` file.
|
||||
|
||||
**Command:**
|
||||
|
||||
```bash
|
||||
qwen mcp add [options] <name> <commandOrUrl> [args...]
|
||||
```
|
||||
|
||||
- `<name>`: A unique name for the server.
|
||||
- `<commandOrUrl>`: The command to execute (for `stdio`) or the URL (for `http`/`sse`).
|
||||
- `[args...]`: Optional arguments for a `stdio` command.
|
||||
|
||||
**Options (Flags):**
|
||||
|
||||
- `-s, --scope`: Configuration scope (user or project). [default: "project"]
|
||||
- `-t, --transport`: Transport type (stdio, sse, http). [default: "stdio"]
|
||||
- `-e, --env`: Set environment variables (e.g. -e KEY=value).
|
||||
- `-H, --header`: Set HTTP headers for SSE and HTTP transports (e.g. -H "X-Api-Key: abc123" -H "Authorization: Bearer abc123").
|
||||
- `--timeout`: Set connection timeout in milliseconds.
|
||||
- `--trust`: Trust the server (bypass all tool call confirmation prompts).
|
||||
- `--description`: Set the description for the server.
|
||||
- `--include-tools`: A comma-separated list of tools to include.
|
||||
- `--exclude-tools`: A comma-separated list of tools to exclude.
|
||||
|
||||
#### Adding an stdio server
|
||||
|
||||
This is the default transport for running local servers.
|
||||
|
||||
```bash
|
||||
# Basic syntax
|
||||
qwen mcp add <name> <command> [args...]
|
||||
|
||||
# Example: Adding a local server
|
||||
qwen mcp add my-stdio-server -e API_KEY=123 /path/to/server arg1 arg2 arg3
|
||||
|
||||
# Example: Adding a local python server
|
||||
qwen mcp add python-server python server.py --port 8080
|
||||
```
|
||||
|
||||
#### Adding an HTTP server
|
||||
|
||||
This transport is for servers that use the streamable HTTP transport.
|
||||
|
||||
```bash
|
||||
# Basic syntax
|
||||
qwen mcp add --transport http <name> <url>
|
||||
|
||||
# Example: Adding an HTTP server
|
||||
qwen mcp add --transport http http-server https://api.example.com/mcp/
|
||||
|
||||
# Example: Adding an HTTP server with an authentication header
|
||||
qwen mcp add --transport http secure-http https://api.example.com/mcp/ --header "Authorization: Bearer abc123"
|
||||
```
|
||||
|
||||
#### Adding an SSE server
|
||||
|
||||
This transport is for servers that use Server-Sent Events (SSE).
|
||||
|
||||
```bash
|
||||
# Basic syntax
|
||||
qwen mcp add --transport sse <name> <url>
|
||||
|
||||
# Example: Adding an SSE server
|
||||
qwen mcp add --transport sse sse-server https://api.example.com/sse/
|
||||
|
||||
# Example: Adding an SSE server with an authentication header
|
||||
qwen mcp add --transport sse secure-sse https://api.example.com/sse/ --header "Authorization: Bearer abc123"
|
||||
```
|
||||
|
||||
### Listing Servers (`qwen mcp list`)
|
||||
|
||||
To view all MCP servers currently configured, use the `list` command. It displays each server's name, configuration details, and connection status.
|
||||
|
||||
**Command:**
|
||||
|
||||
```bash
|
||||
qwen mcp list
|
||||
```
|
||||
|
||||
**Example Output:**
|
||||
|
||||
```sh
|
||||
✓ stdio-server: command: python3 server.py (stdio) - Connected
|
||||
✓ http-server: https://api.example.com/mcp (http) - Connected
|
||||
✗ sse-server: https://api.example.com/sse (sse) - Disconnected
|
||||
```
|
||||
|
||||
### Removing a Server (`qwen mcp remove`)
|
||||
|
||||
To delete a server from your configuration, use the `remove` command with the server's name.
|
||||
|
||||
**Command:**
|
||||
|
||||
```bash
|
||||
qwen mcp remove <name>
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```bash
|
||||
qwen mcp remove my-server
|
||||
```
|
||||
|
||||
This will find and delete the "my-server" entry from the `mcpServers` object in the appropriate `settings.json` file based on the scope (`-s, --scope`).
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Memory Tool (`save_memory`)
|
||||
|
||||
This document describes the `save_memory` tool for the Gemini CLI.
|
||||
This document describes the `save_memory` tool for Qwen Code.
|
||||
|
||||
## Description
|
||||
|
||||
@@ -12,7 +12,7 @@ Use `save_memory` to save and recall information across your Qwen Code sessions.
|
||||
|
||||
- `fact` (string, required): The specific fact or piece of information to remember. This should be a clear, self-contained statement written in natural language.
|
||||
|
||||
## How to use `save_memory` with the Gemini CLI
|
||||
## How to use `save_memory` with Qwen Code
|
||||
|
||||
The tool appends the provided `fact` to your context file in the user's home directory (`~/.qwen/QWEN.md` by default). This filename can be configured via `contextFileName`.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Multi File Read Tool (`read_many_files`)
|
||||
|
||||
This document describes the `read_many_files` tool for the Gemini CLI.
|
||||
This document describes the `read_many_files` tool for Qwen Code.
|
||||
|
||||
## Description
|
||||
|
||||
@@ -24,7 +24,7 @@ Use `read_many_files` to read content from multiple files specified by paths or
|
||||
- `useDefaultExcludes` (boolean, optional): Whether to apply a list of default exclusion patterns (e.g., `node_modules`, `.git`, non image/pdf binary files). Defaults to `true`.
|
||||
- `respect_git_ignore` (boolean, optional): Whether to respect .gitignore patterns when finding files. Defaults to true.
|
||||
|
||||
## How to use `read_many_files` with the Gemini CLI
|
||||
## How to use `read_many_files` with Qwen Code
|
||||
|
||||
`read_many_files` searches for files matching the provided `paths` and `include` patterns, while respecting `exclude` patterns and default excludes (if enabled).
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Shell Tool (`run_shell_command`)
|
||||
|
||||
This document describes the `run_shell_command` tool for the Gemini CLI.
|
||||
This document describes the `run_shell_command` tool for Qwen Code.
|
||||
|
||||
## Description
|
||||
|
||||
@@ -14,7 +14,7 @@ Use `run_shell_command` to interact with the underlying system, run scripts, or
|
||||
- `description` (string, optional): A brief description of the command's purpose, which will be shown to the user.
|
||||
- `directory` (string, optional): The directory (relative to the project root) in which to execute the command. If not provided, the command runs in the project root.
|
||||
|
||||
## How to use `run_shell_command` with the Gemini CLI
|
||||
## How to use `run_shell_command` with Qwen Code
|
||||
|
||||
When using `run_shell_command`, the command is executed as a subprocess. `run_shell_command` can start background processes using `&`. The tool returns detailed information about the execution, including:
|
||||
|
||||
@@ -62,7 +62,7 @@ run_shell_command(command="npm run dev &", description="Start development server
|
||||
|
||||
## Environment Variables
|
||||
|
||||
When `run_shell_command` executes a command, it sets the `GEMINI_CLI=1` environment variable in the subprocess's environment. This allows scripts or tools to detect if they are being run from within the Gemini CLI.
|
||||
When `run_shell_command` executes a command, it sets the `QWEN_CODE=1` environment variable in the subprocess's environment. This allows scripts or tools to detect if they are being run from within the CLI.
|
||||
|
||||
## Command Restrictions
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Web Fetch Tool (`web_fetch`)
|
||||
|
||||
This document describes the `web_fetch` tool for the Gemini CLI.
|
||||
This document describes the `web_fetch` tool for Qwen Code.
|
||||
|
||||
## Description
|
||||
|
||||
@@ -13,9 +13,9 @@ Use `web_fetch` to fetch content from a specified URL and process it using an AI
|
||||
- `url` (string, required): The URL to fetch content from. Must be a fully-formed valid URL starting with `http://` or `https://`.
|
||||
- `prompt` (string, required): The prompt describing what information you want to extract from the page content.
|
||||
|
||||
## How to use `web_fetch` with the Gemini CLI
|
||||
## How to use `web_fetch` with Qwen Code
|
||||
|
||||
To use `web_fetch` with the Gemini CLI, provide a URL and a prompt describing what you want to extract from that URL. The tool will ask for confirmation before fetching the URL. Once confirmed, the tool will fetch the content directly and process it using an AI model.
|
||||
To use `web_fetch` with Qwen Code, provide a URL and a prompt describing what you want to extract from that URL. The tool will ask for confirmation before fetching the URL. Once confirmed, the tool will fetch the content directly and process it using an AI model.
|
||||
|
||||
The tool automatically converts HTML to text, handles GitHub blob URLs (converting them to raw URLs), and upgrades HTTP URLs to HTTPS for security.
|
||||
|
||||
|
||||
@@ -1,93 +1,98 @@
|
||||
# Gemini CLI: Terms of Service and Privacy Notice
|
||||
# Qwen Code: Terms of Service and Privacy Notice
|
||||
|
||||
Gemini CLI is an open-source tool that lets you interact with Google's powerful language models directly from your command-line interface. The Terms of Service and Privacy Notices that apply to your usage of the Gemini CLI depend on the type of account you use to authenticate with Google.
|
||||
|
||||
This article outlines the specific terms and privacy policies applicable for different account types and authentication methods. Note: See [quotas and pricing](./quota-and-pricing.md) for the quota and pricing details that apply to your usage of the Gemini CLI.
|
||||
Qwen Code is an open-source AI coding assistant tool maintained by the Qwen Code team. This document outlines the terms of service and privacy policies that apply when using Qwen Code's authentication methods and AI model services.
|
||||
|
||||
## How to determine your authentication method
|
||||
|
||||
Your authentication method refers to the method you use to log into and access the Gemini CLI. There are four ways to authenticate:
|
||||
Qwen Code supports two main authentication methods to access AI models. Your authentication method determines which terms of service and privacy policies apply to your usage:
|
||||
|
||||
- Logging in with your Google account to Gemini Code Assist for Individuals
|
||||
- Logging in with your Google account to Gemini Code Assist for Workspace, Standard, or Enterprise Users
|
||||
- Using an API key with Gemini Developer
|
||||
- Using an API key with Vertex AI GenAI API
|
||||
1. **Qwen OAuth** - Log in with your qwen.ai account
|
||||
2. **OpenAI-Compatible API** - Use API keys from various AI model providers
|
||||
|
||||
For each of these four methods of authentication, different Terms of Service and Privacy Notices may apply.
|
||||
For each authentication method, different Terms of Service and Privacy Notices may apply depending on the underlying service provider.
|
||||
|
||||
| Authentication | Account | Terms of Service | Privacy Notice |
|
||||
| :---------------------------- | :------------------ | :------------------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Gemini Code Assist via Google | Individual | [Google Terms of Service](https://policies.google.com/terms?hl=en-US) | [Gemini Code Assist Privacy Notice for Individuals](https://developers.google.com/gemini-code-assist/resources/privacy-notice-gemini-code-assist-individuals) |
|
||||
| Gemini Code Assist via Google | Standard/Enterprise | [Google Cloud Platform Terms of Service](https://cloud.google.com/terms) | [Gemini Code Assist Privacy Notice for Standard and Enterprise](https://cloud.google.com/gemini/docs/codeassist/security-privacy-compliance#standard_and_enterprise_data_protection_and_privacy) |
|
||||
| Gemini Developer API | Unpaid | [Gemini API Terms of Service - Unpaid Services](https://ai.google.dev/gemini-api/terms#unpaid-services) | [Google Privacy Policy](https://policies.google.com/privacy) |
|
||||
| Gemini Developer API | Paid | [Gemini API Terms of Service - Paid Services](https://ai.google.dev/gemini-api/terms#paid-services) | [Google Privacy Policy](https://policies.google.com/privacy) |
|
||||
| Vertex AI Gen API | | [Google Cloud Platform Service Terms](https://cloud.google.com/terms/service-terms/) | [Google Cloud Privacy Notice](https://cloud.google.com/terms/cloud-privacy-notice) |
|
||||
| Authentication Method | Provider | Terms of Service | Privacy Notice |
|
||||
| :-------------------- | :---------------- | :---------------------------------------------------------------------------- | :--------------------------------------------------- |
|
||||
| Qwen OAuth | Qwen AI | [Qwen Terms of Service](https://qwen.ai/termsservice) | [Qwen Privacy Policy](https://qwen.ai/privacypolicy) |
|
||||
| OpenAI-Compatible API | Various Providers | Depends on your chosen API provider (OpenAI, Alibaba Cloud, ModelScope, etc.) | Depends on your chosen API provider |
|
||||
|
||||
## 1. If you have logged in with your Google account to Gemini Code Assist for Individuals
|
||||
## 1. If you are using Qwen OAuth Authentication
|
||||
|
||||
For users who use their Google account to access [Gemini Code Assist for Individuals](https://developers.google.com/gemini-code-assist/docs/overview#supported-features-gca), these Terms of Service and Privacy Notice documents apply:
|
||||
When you authenticate using your qwen.ai account, these Terms of Service and Privacy Notice documents apply:
|
||||
|
||||
- **Terms of Service:** Your use of the Gemini CLI is governed by the [Google Terms of Service](https://policies.google.com/terms?hl=en-US).
|
||||
- **Privacy Notice:** The collection and use of your data is described in the [Gemini Code Assist Privacy Notice for Individuals](https://developers.google.com/gemini-code-assist/resources/privacy-notice-gemini-code-assist-individuals).
|
||||
- **Terms of Service:** Your use is governed by the [Qwen Terms of Service](https://qwen.ai/termsservice).
|
||||
- **Privacy Notice:** The collection and use of your data is described in the [Qwen Privacy Policy](https://qwen.ai/privacypolicy).
|
||||
|
||||
## 2. If you have logged in with your Google account to Gemini Code Assist for Workspace, Standard, or Enterprise Users
|
||||
For details about authentication setup, quotas, and supported features, see [Authentication Setup](./cli/authentication.md).
|
||||
|
||||
For users who use their Google account to access the [Standard or Enterprise edition](https://cloud.google.com/gemini/docs/codeassist/overview#editions-overview) of Gemini Code Assist, these Terms of Service and Privacy Notice documents apply:
|
||||
## 2. If you are using OpenAI-Compatible API Authentication
|
||||
|
||||
- **Terms of Service:** Your use of the Gemini CLI is governed by the [Google Cloud Platform Terms of Service](https://cloud.google.com/terms).
|
||||
- **Privacy Notice:** The collection and use of your data is described in the [Gemini Code Assist Privacy Notices for Standard and Enterprise Users](https://cloud.google.com/gemini/docs/codeassist/security-privacy-compliance#standard_and_enterprise_data_protection_and_privacy).
|
||||
When you authenticate using API keys from OpenAI-compatible providers, the applicable Terms of Service and Privacy Notice depend on your chosen provider.
|
||||
|
||||
## 3. If you have logged in with a Gemini API key to the Gemini Developer API
|
||||
**Important:** When using OpenAI-compatible API authentication, you are subject to the terms and privacy policies of your chosen API provider, not Qwen Code's terms. Please review your provider's documentation for specific details about data usage, retention, and privacy practices.
|
||||
|
||||
If you are using a Gemini API key for authentication with the [Gemini Developer API](https://ai.google.dev/gemini-api/docs), these Terms of Service and Privacy Notice documents apply:
|
||||
Qwen Code supports various OpenAI-compatible providers. Please refer to your specific provider's terms of service and privacy policy for detailed information.
|
||||
|
||||
- **Terms of Service:** Your use of the Gemini CLI is governed by the [Gemini API Terms of Service](https://ai.google.dev/gemini-api/terms). These terms may differ depending on whether you are using an unpaid or paid service:
|
||||
- For unpaid services, refer to the [Gemini API Terms of Service - Unpaid Services](https://ai.google.dev/gemini-api/terms#unpaid-services).
|
||||
- For paid services, refer to the [Gemini API Terms of Service - Paid Services](https://ai.google.dev/gemini-api/terms#paid-services).
|
||||
- **Privacy Notice:** The collection and use of your data is described in the [Google Privacy Policy](https://policies.google.com/privacy).
|
||||
## Usage Statistics and Telemetry
|
||||
|
||||
## 4. If you have logged in with a Gemini API key to the Vertex AI GenAI API
|
||||
Qwen Code may collect anonymous usage statistics and telemetry data to improve the user experience and product quality. This data collection is optional and can be controlled through configuration settings.
|
||||
|
||||
If you are using a Gemini API key for authentication with a [Vertex AI GenAI API](https://cloud.google.com/vertex-ai/generative-ai/docs/reference/rest) backend, these Terms of Service and Privacy Notice documents apply:
|
||||
### What Data is Collected
|
||||
|
||||
- **Terms of Service:** Your use of the Gemini CLI is governed by the [Google Cloud Platform Service Terms](https://cloud.google.com/terms/service-terms/).
|
||||
- **Privacy Notice:** The collection and use of your data is described in the [Google Cloud Privacy Notice](https://cloud.google.com/terms/cloud-privacy-notice).
|
||||
When enabled, Qwen Code may collect:
|
||||
|
||||
### Usage Statistics Opt-Out
|
||||
- Anonymous usage statistics (commands run, performance metrics)
|
||||
- Error reports and crash data
|
||||
- Feature usage patterns
|
||||
|
||||
You may opt-out from sending Usage Statistics to Google by following the instructions available here: [Usage Statistics Configuration](./cli/configuration.md#usage-statistics).
|
||||
### Data Collection by Authentication Method
|
||||
|
||||
## Frequently Asked Questions (FAQ) for the Gemini CLI
|
||||
- **Qwen OAuth:** Usage statistics are governed by Qwen's privacy policy. You can opt-out through Qwen Code's configuration settings.
|
||||
- **OpenAI-Compatible API:** No additional data is collected by Qwen Code beyond what your chosen API provider collects.
|
||||
|
||||
### 1. Is my code, including prompts and answers, used to train Google's models?
|
||||
### Opt-Out Instructions
|
||||
|
||||
Whether your code, including prompts and answers, is used to train Google's models depends on the type of authentication method you use and your account type.
|
||||
You can disable usage statistics collection by following the instructions in the [Usage Statistics Configuration](./cli/configuration.md#usage-statistics) documentation.
|
||||
|
||||
By default (if you have not opted out):
|
||||
## Frequently Asked Questions (FAQ)
|
||||
|
||||
- **Google account with Gemini Code Assist for Individuals**: Yes. When you use your personal Google account, the [Gemini Code Assist Privacy Notice for Individuals](https://developers.google.com/gemini-code-assist/resources/privacy-notice-gemini-code-assist-individuals) applies. Under this notice,
|
||||
your **prompts, answers, and related code are collected** and may be used to improve Google's products, including for model training.
|
||||
- **Google account with Gemini Code Assist for Workspace, Standard, or Enterprise**: No. For these accounts, your data is governed by the [Gemini Code Assist Privacy Notices](https://cloud.google.com/gemini/docs/codeassist/security-privacy-compliance#standard_and_enterprise_data_protection_and_privacy) terms, which treat your inputs as confidential. Your **prompts, answers, and related code are not collected** and are not used to train models.
|
||||
- **Gemini API key via the Gemini Developer API**: Whether your code is collected or used depends on whether you are using an unpaid or paid service.
|
||||
- **Unpaid services**: Yes. When you use the Gemini API key via the Gemini Developer API with an unpaid service, the [Gemini API Terms of Service - Unpaid Services](https://ai.google.dev/gemini-api/terms#unpaid-services) terms apply. Under this notice, your **prompts, answers, and related code are collected** and may be used to improve Google's products, including for model training.
|
||||
- **Paid services**: No. When you use the Gemini API key via the Gemini Developer API with a paid service, the [Gemini API Terms of Service - Paid Services](https://ai.google.dev/gemini-api/terms#paid-services) terms apply, which treats your inputs as confidential. Your **prompts, answers, and related code are not collected** and are not used to train models.
|
||||
- **Gemini API key via the Vertex AI GenAI API**: No. For these accounts, your data is governed by the [Google Cloud Privacy Notice](https://cloud.google.com/terms/cloud-privacy-notice) terms, which treat your inputs as confidential. Your **prompts, answers, and related code are not collected** and are not used to train models.
|
||||
### 1. Is my code, including prompts and answers, used to train AI models?
|
||||
|
||||
For more information about opting out, refer to the next question.
|
||||
Whether your code, including prompts and answers, is used to train AI models depends on your authentication method and the specific AI service provider you use:
|
||||
|
||||
- **Qwen OAuth**: Data usage is governed by [Qwen's Privacy Policy](https://qwen.ai/privacy). Please refer to their policy for specific details about data collection and model training practices.
|
||||
|
||||
- **OpenAI-Compatible API**: Data usage depends entirely on your chosen API provider. Each provider has their own data usage policies. Please review the privacy policy and terms of service of your specific provider.
|
||||
|
||||
**Important**: Qwen Code itself does not use your prompts, code, or responses for model training. Any data usage for training purposes would be governed by the policies of the AI service provider you authenticate with.
|
||||
|
||||
### 2. What are Usage Statistics and what does the opt-out control?
|
||||
|
||||
The **Usage Statistics** setting is the single control for all optional data collection in the Gemini CLI.
|
||||
The **Usage Statistics** setting controls optional data collection by Qwen Code for improving the user experience and product quality.
|
||||
|
||||
The data it collects depends on your account and authentication type:
|
||||
When enabled, Qwen Code may collect:
|
||||
|
||||
- **Google account with Gemini Code Assist for Individuals**: When enabled, this setting allows Google to collect both anonymous telemetry (for example, commands run and performance metrics) and **your prompts and answers, including code,** for model improvement.
|
||||
- **Google account with Gemini Code Assist for Workspace, Standard, or Enterprise**: This setting only controls the collection of anonymous telemetry. Your prompts and answers, including code, are never collected, regardless of this setting.
|
||||
- **Gemini API key via the Gemini Developer API**:
|
||||
**Unpaid services**: When enabled, this setting allows Google to collect both anonymous telemetry (like commands run and performance metrics) and **your prompts and answers, including code,** for model improvement. When disabled we will use your data as described in [How Google Uses Your Data](https://ai.google.dev/gemini-api/terms#data-use-unpaid).
|
||||
**Paid services**: This setting only controls the collection of anonymous telemetry. Google logs prompts and responses for a limited period of time, solely for the purpose of detecting violations of the Prohibited Use Policy and any required legal or regulatory disclosures.
|
||||
- **Gemini API key via the Vertex AI GenAI API:** This setting only controls the collection of anonymous telemetry. Your prompts and answers, including code, are never collected, regardless of this setting.
|
||||
- Anonymous telemetry (commands run, performance metrics, feature usage)
|
||||
- Error reports and crash data
|
||||
- General usage patterns
|
||||
|
||||
Please refer to the Privacy Notice that applies to your authentication method for more information about what data is collected and how this data is used.
|
||||
**What is NOT collected by Qwen Code:**
|
||||
|
||||
You can disable Usage Statistics for any account type by following the instructions in the [Usage Statistics Configuration](./cli/configuration.md#usage-statistics) documentation.
|
||||
- Your code content
|
||||
- Prompts sent to AI models
|
||||
- Responses from AI models
|
||||
- Personal information
|
||||
|
||||
The Usage Statistics setting only controls data collection by Qwen Code itself. It does not affect what data your chosen AI service provider (Qwen, OpenAI, etc.) may collect according to their own privacy policies.
|
||||
|
||||
You can disable Usage Statistics collection by following the instructions in the [Usage Statistics Configuration](./cli/configuration.md#usage-statistics) documentation.
|
||||
|
||||
### 3. How do I switch between authentication methods?
|
||||
|
||||
You can switch between Qwen OAuth and OpenAI-compatible API authentication at any time:
|
||||
|
||||
1. **During startup**: Choose your preferred authentication method when prompted
|
||||
2. **Within the CLI**: Use the `/auth` command to reconfigure your authentication method
|
||||
3. **Environment variables**: Set up `.env` files for automatic OpenAI-compatible API authentication
|
||||
|
||||
For detailed instructions, see the [Authentication Setup](./cli/authentication.md) documentation.
|
||||
|
||||
@@ -21,18 +21,18 @@ This guide provides solutions to common issues and debugging tips, including top
|
||||
|
||||
## Frequently asked questions (FAQs)
|
||||
|
||||
- **Q: How do I update Gemini CLI to the latest version?**
|
||||
- A: If you installed it globally via `npm`, update it using the command `npm install -g @google/gemini-cli@latest`. If you compiled it from source, pull the latest changes from the repository, and then rebuild using the command `npm run build`.
|
||||
- **Q: How do I update Qwen Code to the latest version?**
|
||||
- A: If you installed it globally via `npm`, update it using the command `npm install -g @qwen-code/qwen-code@latest`. If you compiled it from source, pull the latest changes from the repository, and then rebuild using the command `npm run build`.
|
||||
|
||||
- **Q: Where are the Gemini CLI configuration or settings files stored?**
|
||||
- A: The Gemini CLI configuration is stored in two `settings.json` files:
|
||||
1. In your home directory: `~/.gemini/settings.json`.
|
||||
2. In your project's root directory: `./.gemini/settings.json`.
|
||||
- **Q: Where are the Qwen Code configuration or settings files stored?**
|
||||
- A: The Qwen Code configuration is stored in two `settings.json` files:
|
||||
1. In your home directory: `~/.qwen/settings.json`.
|
||||
2. In your project's root directory: `./.qwen/settings.json`.
|
||||
|
||||
Refer to [Gemini CLI Configuration](./cli/configuration.md) for more details.
|
||||
Refer to [Qwen Code Configuration](./cli/configuration.md) for more details.
|
||||
|
||||
- **Q: Why don't I see cached token counts in my stats output?**
|
||||
- A: Cached token information is only displayed when cached tokens are being used. This feature is available for API key users (Gemini API key or Google Cloud Vertex AI) but not for OAuth users (such as Google Personal/Enterprise accounts like Google Gmail or Google Workspace, respectively). This is because the Gemini Code Assist API does not support cached content creation. You can still view your total token usage using the `/stats` command in Gemini CLI.
|
||||
- A: Cached token information is only displayed when cached tokens are being used. This feature is available for API key users (Gemini API key or Google Cloud Vertex AI) but not for OAuth users (such as Google Personal/Enterprise accounts like Google Gmail or Google Workspace, respectively). This is because the Gemini Code Assist API does not support cached content creation. You can still view your total token usage using the `/stats` command.
|
||||
|
||||
## Common error messages and solutions
|
||||
|
||||
@@ -41,12 +41,12 @@ This guide provides solutions to common issues and debugging tips, including top
|
||||
- **Solution:**
|
||||
Either stop the other process that is using the port or configure the MCP server to use a different port.
|
||||
|
||||
- **Error: Command not found (when attempting to run Gemini CLI with `gemini`).**
|
||||
- **Cause:** Gemini CLI is not correctly installed or it is not in your system's `PATH`.
|
||||
- **Error: Command not found (when attempting to run Qwen Code with `qwen`).**
|
||||
- **Cause:** The CLI is not correctly installed or it is not in your system's `PATH`.
|
||||
- **Solution:**
|
||||
The update depends on how you installed Gemini CLI:
|
||||
- If you installed `gemini` globally, check that your `npm` global binary directory is in your `PATH`. You can update Gemini CLI using the command `npm install -g @google/gemini-cli@latest`.
|
||||
- If you are running `gemini` from source, ensure you are using the correct command to invoke it (e.g., `node packages/cli/dist/index.js ...`). To update Gemini CLI, pull the latest changes from the repository, and then rebuild using the command `npm run build`.
|
||||
The update depends on how you installed Qwen Code:
|
||||
- If you installed `qwen` globally, check that your `npm` global binary directory is in your `PATH`. You can update using the command `npm install -g @qwen-code/qwen-code@latest`.
|
||||
- If you are running `qwen` from source, ensure you are using the correct command to invoke it (e.g., `node packages/cli/dist/index.js ...`). To update, pull the latest changes from the repository, and then rebuild using the command `npm run build`.
|
||||
|
||||
- **Error: `MODULE_NOT_FOUND` or import errors.**
|
||||
- **Cause:** Dependencies are not installed correctly, or the project hasn't been built.
|
||||
@@ -56,18 +56,27 @@ This guide provides solutions to common issues and debugging tips, including top
|
||||
3. Verify that the build completed successfully with `npm run start`.
|
||||
|
||||
- **Error: "Operation not permitted", "Permission denied", or similar.**
|
||||
- **Cause:** When sandboxing is enabled, Gemini CLI may attempt operations that are restricted by your sandbox configuration, such as writing outside the project directory or system temp directory.
|
||||
- **Cause:** When sandboxing is enabled, Qwen Code may attempt operations that are restricted by your sandbox configuration, such as writing outside the project directory or system temp directory.
|
||||
- **Solution:** Refer to the [Configuration: Sandboxing](./cli/configuration.md#sandboxing) documentation for more information, including how to customize your sandbox configuration.
|
||||
|
||||
- **Gemini CLI is not running in interactive mode in "CI" environments**
|
||||
- **Issue:** The Gemini CLI does not enter interactive mode (no prompt appears) if an environment variable starting with `CI_` (e.g., `CI_TOKEN`) is set. This is because the `is-in-ci` package, used by the underlying UI framework, detects these variables and assumes a non-interactive CI environment.
|
||||
- **Cause:** The `is-in-ci` package checks for the presence of `CI`, `CONTINUOUS_INTEGRATION`, or any environment variable with a `CI_` prefix. When any of these are found, it signals that the environment is non-interactive, which prevents the Gemini CLI from starting in its interactive mode.
|
||||
- **Solution:** If the `CI_` prefixed variable is not needed for the CLI to function, you can temporarily unset it for the command. e.g., `env -u CI_TOKEN gemini`
|
||||
- **Qwen Code is not running in interactive mode in "CI" environments**
|
||||
- **Issue:** Qwen Code does not enter interactive mode (no prompt appears) if an environment variable starting with `CI_` (e.g., `CI_TOKEN`) is set. This is because the `is-in-ci` package, used by the underlying UI framework, detects these variables and assumes a non-interactive CI environment.
|
||||
- **Cause:** The `is-in-ci` package checks for the presence of `CI`, `CONTINUOUS_INTEGRATION`, or any environment variable with a `CI_` prefix. When any of these are found, it signals that the environment is non-interactive, which prevents the CLI from starting in its interactive mode.
|
||||
- **Solution:** If the `CI_` prefixed variable is not needed for the CLI to function, you can temporarily unset it for the command. e.g., `env -u CI_TOKEN qwen`
|
||||
|
||||
- **DEBUG mode not working from project .env file**
|
||||
- **Issue:** Setting `DEBUG=true` in a project's `.env` file doesn't enable debug mode for gemini-cli.
|
||||
- **Cause:** The `DEBUG` and `DEBUG_MODE` variables are automatically excluded from project `.env` files to prevent interference with gemini-cli behavior.
|
||||
- **Solution:** Use a `.gemini/.env` file instead, or configure the `excludedProjectEnvVars` setting in your `settings.json` to exclude fewer variables.
|
||||
- **Issue:** Setting `DEBUG=true` in a project's `.env` file doesn't enable debug mode for the CLI.
|
||||
- **Cause:** The `DEBUG` and `DEBUG_MODE` variables are automatically excluded from project `.env` files to prevent interference with the CLI behavior.
|
||||
- **Solution:** Use a `.qwen/.env` file instead, or configure the `excludedProjectEnvVars` setting in your `settings.json` to exclude fewer variables.
|
||||
|
||||
## IDE Companion not connecting
|
||||
|
||||
- Ensure VS Code has a single workspace folder open.
|
||||
- Restart the integrated terminal after installing the extension so it inherits:
|
||||
- `QWEN_CODE_IDE_WORKSPACE_PATH`
|
||||
- `QWEN_CODE_IDE_SERVER_PORT`
|
||||
- If running in a container, verify `host.docker.internal` resolves. Otherwise, map the host appropriately.
|
||||
- Reinstall the companion with `/ide install` and use “Qwen Code: Run” in the Command Palette to verify it launches.
|
||||
|
||||
## Debugging Tips
|
||||
|
||||
@@ -90,4 +99,4 @@ This guide provides solutions to common issues and debugging tips, including top
|
||||
|
||||
## Existing GitHub Issues similar to yours or creating new Issues
|
||||
|
||||
If you encounter an issue that was not covered here in this _Troubleshooting guide_, consider searching the Gemini CLI [Issue tracker on GitHub](https://github.com/google-gemini/gemini-cli/issues). If you can't find an issue similar to yours, consider creating a new GitHub Issue with a detailed description. Pull requests are also welcome!
|
||||
If you encounter an issue that was not covered here in this _Troubleshooting guide_, consider searching the Qwen Code [Issue tracker on GitHub](https://github.com/QwenLM/qwen-code/issues). If you can't find an issue similar to yours, consider creating a new GitHub Issue with a detailed description. Pull requests are also welcome!
|
||||
|
||||
@@ -35,6 +35,7 @@ export default tseslint.config(
|
||||
'packages/vscode-ide-companion/dist/**',
|
||||
'bundle/**',
|
||||
'package/bundle/**',
|
||||
'.integration-tests/**',
|
||||
],
|
||||
},
|
||||
eslint.configs.recommended,
|
||||
|
||||
@@ -21,8 +21,8 @@ test('should be able to list a directory', async () => {
|
||||
await rig.poll(
|
||||
() => {
|
||||
// Check if the files exist in the test directory
|
||||
const file1Path = join(rig.testDir, 'file1.txt');
|
||||
const subdirPath = join(rig.testDir, 'subdir');
|
||||
const file1Path = join(rig.testDir!, 'file1.txt');
|
||||
const subdirPath = join(rig.testDir!, 'subdir');
|
||||
return existsSync(file1Path) && existsSync(subdirPath);
|
||||
},
|
||||
1000, // 1 second max wait
|
||||
199
integration-tests/mcp_server_cyclic_schema.test.js
Normal file
199
integration-tests/mcp_server_cyclic_schema.test.js
Normal file
@@ -0,0 +1,199 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* This test verifies we can match maximum schema depth errors from Gemini
|
||||
* and then detect and warn about the potential tools that caused the error.
|
||||
*/
|
||||
|
||||
import { test, describe, before } from 'node:test';
|
||||
import { strict as assert } from 'node:assert';
|
||||
import { TestRig } from './test-helper.js';
|
||||
import { join } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { writeFileSync } from 'fs';
|
||||
|
||||
const __dirname = fileURLToPath(new URL('.', import.meta.url));
|
||||
|
||||
// Create a minimal MCP server that doesn't require external dependencies
|
||||
// This implements the MCP protocol directly using Node.js built-ins
|
||||
const serverScript = `#!/usr/bin/env node
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
const readline = require('readline');
|
||||
const fs = require('fs');
|
||||
|
||||
// Debug logging to stderr (only when MCP_DEBUG or VERBOSE is set)
|
||||
const debugEnabled = process.env.MCP_DEBUG === 'true' || process.env.VERBOSE === 'true';
|
||||
function debug(msg) {
|
||||
if (debugEnabled) {
|
||||
fs.writeSync(2, \`[MCP-DEBUG] \${msg}\\n\`);
|
||||
}
|
||||
}
|
||||
|
||||
debug('MCP server starting...');
|
||||
|
||||
// Simple JSON-RPC implementation for MCP
|
||||
class SimpleJSONRPC {
|
||||
constructor() {
|
||||
this.handlers = new Map();
|
||||
this.rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
terminal: false
|
||||
});
|
||||
|
||||
this.rl.on('line', (line) => {
|
||||
debug(\`Received line: \${line}\`);
|
||||
try {
|
||||
const message = JSON.parse(line);
|
||||
debug(\`Parsed message: \${JSON.stringify(message)}\`);
|
||||
this.handleMessage(message);
|
||||
} catch (e) {
|
||||
debug(\`Parse error: \${e.message}\`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
send(message) {
|
||||
const msgStr = JSON.stringify(message);
|
||||
debug(\`Sending message: \${msgStr}\`);
|
||||
process.stdout.write(msgStr + '\\n');
|
||||
}
|
||||
|
||||
async handleMessage(message) {
|
||||
if (message.method && this.handlers.has(message.method)) {
|
||||
try {
|
||||
const result = await this.handlers.get(message.method)(message.params || {});
|
||||
if (message.id !== undefined) {
|
||||
this.send({
|
||||
jsonrpc: '2.0',
|
||||
id: message.id,
|
||||
result
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (message.id !== undefined) {
|
||||
this.send({
|
||||
jsonrpc: '2.0',
|
||||
id: message.id,
|
||||
error: {
|
||||
code: -32603,
|
||||
message: error.message
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (message.id !== undefined) {
|
||||
this.send({
|
||||
jsonrpc: '2.0',
|
||||
id: message.id,
|
||||
error: {
|
||||
code: -32601,
|
||||
message: 'Method not found'
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
on(method, handler) {
|
||||
this.handlers.set(method, handler);
|
||||
}
|
||||
}
|
||||
|
||||
// Create MCP server
|
||||
const rpc = new SimpleJSONRPC();
|
||||
|
||||
// Handle initialize
|
||||
rpc.on('initialize', async (params) => {
|
||||
debug('Handling initialize request');
|
||||
return {
|
||||
protocolVersion: '2024-11-05',
|
||||
capabilities: {
|
||||
tools: {}
|
||||
},
|
||||
serverInfo: {
|
||||
name: 'cyclic-schema-server',
|
||||
version: '1.0.0'
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
// Handle tools/list
|
||||
rpc.on('tools/list', async () => {
|
||||
debug('Handling tools/list request');
|
||||
return {
|
||||
tools: [{
|
||||
name: 'tool_with_cyclic_schema',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
data: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
child: { $ref: '#/properties/data/items' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}]
|
||||
};
|
||||
});
|
||||
|
||||
// Send initialization notification
|
||||
rpc.send({
|
||||
jsonrpc: '2.0',
|
||||
method: 'initialized'
|
||||
});
|
||||
`;
|
||||
|
||||
describe('mcp server with cyclic tool schema is detected', () => {
|
||||
const rig = new TestRig();
|
||||
|
||||
before(async () => {
|
||||
// Setup test directory with MCP server configuration
|
||||
await rig.setup('cyclic-schema-mcp-server', {
|
||||
settings: {
|
||||
mcpServers: {
|
||||
'cyclic-schema-server': {
|
||||
command: 'node',
|
||||
args: ['mcp-server.cjs'],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Create server script in the test directory
|
||||
const testServerPath = join(rig.testDir, 'mcp-server.cjs');
|
||||
writeFileSync(testServerPath, serverScript);
|
||||
|
||||
// Make the script executable (though running with 'node' should work anyway)
|
||||
if (process.platform !== 'win32') {
|
||||
const { chmodSync } = await import('fs');
|
||||
chmodSync(testServerPath, 0o755);
|
||||
}
|
||||
});
|
||||
|
||||
test('should error and suggest disabling the cyclic tool', async () => {
|
||||
// Just run any command to trigger the schema depth error.
|
||||
// If this test starts failing, check `isSchemaDepthError` from
|
||||
// geminiChat.ts to see if it needs to be updated.
|
||||
// Or, possibly it could mean that gemini has fixed the issue.
|
||||
const output = await rig.run('hello');
|
||||
|
||||
assert.match(
|
||||
output,
|
||||
/Skipping tool 'tool_with_cyclic_schema' from MCP server 'cyclic-schema-server' because it has missing types in its parameter schema/,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -52,13 +52,13 @@ async function main() {
|
||||
|
||||
const testPatterns =
|
||||
args.length > 0
|
||||
? args.map((arg) => `integration-tests/${arg}.test.js`)
|
||||
: ['integration-tests/*.test.js'];
|
||||
? args.map((arg) => `integration-tests/${arg}.test.ts`)
|
||||
: ['integration-tests/*.test.ts'];
|
||||
const testFiles = glob.sync(testPatterns, { cwd: rootDir, absolute: true });
|
||||
|
||||
for (const testFile of testFiles) {
|
||||
const testFileName = basename(testFile);
|
||||
console.log(`\tFound test file: ${testFileName}`);
|
||||
console.log(` Found test file: ${testFileName}`);
|
||||
}
|
||||
|
||||
const MAX_RETRIES = 3;
|
||||
@@ -92,7 +92,7 @@ async function main() {
|
||||
}
|
||||
nodeArgs.push(testFile);
|
||||
|
||||
const child = spawn('node', nodeArgs, {
|
||||
const child = spawn('npx', ['tsx', ...nodeArgs], {
|
||||
stdio: 'pipe',
|
||||
env: {
|
||||
...process.env,
|
||||
|
||||
@@ -14,11 +14,8 @@ import { test, describe, before } from 'node:test';
|
||||
import { strict as assert } from 'node:assert';
|
||||
import { TestRig, validateModelOutput } from './test-helper.js';
|
||||
import { join } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { writeFileSync } from 'fs';
|
||||
|
||||
const __dirname = fileURLToPath(new URL('.', import.meta.url));
|
||||
|
||||
// Create a minimal MCP server that doesn't require external dependencies
|
||||
// This implements the MCP protocol directly using Node.js built-ins
|
||||
const serverScript = `#!/usr/bin/env node
|
||||
@@ -185,7 +182,7 @@ describe('simple-mcp-server', () => {
|
||||
});
|
||||
|
||||
// Create server script in the test directory
|
||||
const testServerPath = join(rig.testDir, 'mcp-server.cjs');
|
||||
const testServerPath = join(rig.testDir!, 'mcp-server.cjs');
|
||||
writeFileSync(testServerPath, serverScript);
|
||||
|
||||
// Make the script executable (though running with 'node' should work anyway)
|
||||
@@ -14,7 +14,7 @@ import { fileExists } from '../scripts/telemetry_utils.js';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
function sanitizeTestName(name) {
|
||||
function sanitizeTestName(name: string) {
|
||||
return name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]/g, '-')
|
||||
@@ -22,7 +22,11 @@ function sanitizeTestName(name) {
|
||||
}
|
||||
|
||||
// Helper to create detailed error messages
|
||||
export function createToolCallErrorMessage(expectedTools, foundTools, result) {
|
||||
export function createToolCallErrorMessage(
|
||||
expectedTools: string | string[],
|
||||
foundTools: string[],
|
||||
result: string,
|
||||
) {
|
||||
const expectedStr = Array.isArray(expectedTools)
|
||||
? expectedTools.join(' or ')
|
||||
: expectedTools;
|
||||
@@ -34,7 +38,11 @@ export function createToolCallErrorMessage(expectedTools, foundTools, result) {
|
||||
}
|
||||
|
||||
// Helper to print debug information when tests fail
|
||||
export function printDebugInfo(rig, result, context = {}) {
|
||||
export function printDebugInfo(
|
||||
rig: TestRig,
|
||||
result: string,
|
||||
context: Record<string, unknown> = {},
|
||||
) {
|
||||
console.error('Test failed - Debug info:');
|
||||
console.error('Result length:', result.length);
|
||||
console.error('Result (first 500 chars):', result.substring(0, 500));
|
||||
@@ -60,8 +68,8 @@ export function printDebugInfo(rig, result, context = {}) {
|
||||
|
||||
// Helper to validate model output and warn about unexpected content
|
||||
export function validateModelOutput(
|
||||
result,
|
||||
expectedContent = null,
|
||||
result: string,
|
||||
expectedContent: string | (string | RegExp)[] | null = null,
|
||||
testName = '',
|
||||
) {
|
||||
// First, check if there's any output at all (this should fail the test if missing)
|
||||
@@ -102,6 +110,11 @@ export function validateModelOutput(
|
||||
}
|
||||
|
||||
export class TestRig {
|
||||
bundlePath: string;
|
||||
testDir: string | null;
|
||||
testName?: string;
|
||||
_lastRunStdout?: string;
|
||||
|
||||
constructor() {
|
||||
this.bundlePath = join(__dirname, '..', 'bundle/gemini.js');
|
||||
this.testDir = null;
|
||||
@@ -114,10 +127,13 @@ export class TestRig {
|
||||
return 15000; // 15s locally
|
||||
}
|
||||
|
||||
setup(testName, options = {}) {
|
||||
setup(
|
||||
testName: string,
|
||||
options: { settings?: Record<string, unknown> } = {},
|
||||
) {
|
||||
this.testName = testName;
|
||||
const sanitizedName = sanitizeTestName(testName);
|
||||
this.testDir = join(env.INTEGRATION_TEST_FILE_DIR, sanitizedName);
|
||||
this.testDir = join(env.INTEGRATION_TEST_FILE_DIR!, sanitizedName);
|
||||
mkdirSync(this.testDir, { recursive: true });
|
||||
|
||||
// Create a settings file to point the CLI to the local collector
|
||||
@@ -146,36 +162,43 @@ export class TestRig {
|
||||
);
|
||||
}
|
||||
|
||||
createFile(fileName, content) {
|
||||
const filePath = join(this.testDir, fileName);
|
||||
createFile(fileName: string, content: string) {
|
||||
const filePath = join(this.testDir!, fileName);
|
||||
writeFileSync(filePath, content);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
mkdir(dir) {
|
||||
mkdirSync(join(this.testDir, dir), { recursive: true });
|
||||
mkdir(dir: string) {
|
||||
mkdirSync(join(this.testDir!, dir), { recursive: true });
|
||||
}
|
||||
|
||||
sync() {
|
||||
// ensure file system is done before spawning
|
||||
execSync('sync', { cwd: this.testDir });
|
||||
execSync('sync', { cwd: this.testDir! });
|
||||
}
|
||||
|
||||
run(promptOrOptions, ...args) {
|
||||
run(
|
||||
promptOrOptions: string | { prompt?: string; stdin?: string },
|
||||
...args: string[]
|
||||
): Promise<string> {
|
||||
let command = `node ${this.bundlePath} --yolo`;
|
||||
const execOptions = {
|
||||
cwd: this.testDir,
|
||||
const execOptions: {
|
||||
cwd: string;
|
||||
encoding: 'utf-8';
|
||||
input?: string;
|
||||
} = {
|
||||
cwd: this.testDir!,
|
||||
encoding: 'utf-8',
|
||||
};
|
||||
|
||||
if (typeof promptOrOptions === 'string') {
|
||||
command += ` --prompt "${promptOrOptions}"`;
|
||||
command += ` --prompt ${JSON.stringify(promptOrOptions)}`;
|
||||
} else if (
|
||||
typeof promptOrOptions === 'object' &&
|
||||
promptOrOptions !== null
|
||||
) {
|
||||
if (promptOrOptions.prompt) {
|
||||
command += ` --prompt "${promptOrOptions.prompt}"`;
|
||||
command += ` --prompt ${JSON.stringify(promptOrOptions.prompt)}`;
|
||||
}
|
||||
if (promptOrOptions.stdin) {
|
||||
execOptions.input = promptOrOptions.stdin;
|
||||
@@ -185,10 +208,10 @@ export class TestRig {
|
||||
command += ` ${args.join(' ')}`;
|
||||
|
||||
const commandArgs = parse(command);
|
||||
const node = commandArgs.shift();
|
||||
const node = commandArgs.shift() as string;
|
||||
|
||||
const child = spawn(node, commandArgs, {
|
||||
cwd: this.testDir,
|
||||
const child = spawn(node, commandArgs as string[], {
|
||||
cwd: this.testDir!,
|
||||
stdio: 'pipe',
|
||||
});
|
||||
|
||||
@@ -197,26 +220,26 @@ export class TestRig {
|
||||
|
||||
// Handle stdin if provided
|
||||
if (execOptions.input) {
|
||||
child.stdin.write(execOptions.input);
|
||||
child.stdin.end();
|
||||
child.stdin!.write(execOptions.input);
|
||||
child.stdin!.end();
|
||||
}
|
||||
|
||||
child.stdout.on('data', (data) => {
|
||||
child.stdout!.on('data', (data: Buffer) => {
|
||||
stdout += data;
|
||||
if (env.KEEP_OUTPUT === 'true' || env.VERBOSE === 'true') {
|
||||
process.stdout.write(data);
|
||||
}
|
||||
});
|
||||
|
||||
child.stderr.on('data', (data) => {
|
||||
child.stderr!.on('data', (data: Buffer) => {
|
||||
stderr += data;
|
||||
if (env.KEEP_OUTPUT === 'true' || env.VERBOSE === 'true') {
|
||||
process.stderr.write(data);
|
||||
}
|
||||
});
|
||||
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
child.on('close', (code) => {
|
||||
const promise = new Promise<string>((resolve, reject) => {
|
||||
child.on('close', (code: number) => {
|
||||
if (code === 0) {
|
||||
// Store the raw stdout for Podman telemetry parsing
|
||||
this._lastRunStdout = stdout;
|
||||
@@ -258,6 +281,11 @@ export class TestRig {
|
||||
|
||||
result = filteredLines.join('\n');
|
||||
}
|
||||
// If we have stderr output, include that also
|
||||
if (stderr) {
|
||||
result += `\n\nStdErr:\n${stderr}`;
|
||||
}
|
||||
|
||||
resolve(result);
|
||||
} else {
|
||||
reject(new Error(`Process exited with code ${code}:\n${stderr}`));
|
||||
@@ -268,13 +296,13 @@ export class TestRig {
|
||||
return promise;
|
||||
}
|
||||
|
||||
readFile(fileName) {
|
||||
const content = readFileSync(join(this.testDir, fileName), 'utf-8');
|
||||
readFile(fileName: string) {
|
||||
const content = readFileSync(join(this.testDir!, fileName), 'utf-8');
|
||||
if (env.KEEP_OUTPUT === 'true' || env.VERBOSE === 'true') {
|
||||
const testId = `${env.TEST_FILE_NAME.replace(
|
||||
const testId = `${env.TEST_FILE_NAME!.replace(
|
||||
'.test.js',
|
||||
'',
|
||||
)}:${this.testName.replace(/ /g, '-')}`;
|
||||
)}:${this.testName!.replace(/ /g, '-')}`;
|
||||
console.log(`--- FILE: ${testId}/${fileName} ---`);
|
||||
console.log(content);
|
||||
console.log(`--- END FILE: ${testId}/${fileName} ---`);
|
||||
@@ -290,7 +318,7 @@ export class TestRig {
|
||||
} catch (error) {
|
||||
// Ignore cleanup errors
|
||||
if (env.VERBOSE === 'true') {
|
||||
console.warn('Cleanup warning:', error.message);
|
||||
console.warn('Cleanup warning:', (error as Error).message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -300,7 +328,7 @@ export class TestRig {
|
||||
// In sandbox mode, telemetry is written to a relative path in the test directory
|
||||
const logFilePath =
|
||||
env.GEMINI_SANDBOX && env.GEMINI_SANDBOX !== 'false'
|
||||
? join(this.testDir, 'telemetry.log')
|
||||
? join(this.testDir!, 'telemetry.log')
|
||||
: env.TELEMETRY_LOG_FILE;
|
||||
|
||||
if (!logFilePath) return;
|
||||
@@ -313,7 +341,7 @@ export class TestRig {
|
||||
const content = readFileSync(logFilePath, 'utf-8');
|
||||
// Check if file has meaningful content (at least one complete JSON object)
|
||||
return content.includes('"event.name"');
|
||||
} catch (_e) {
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
@@ -322,7 +350,7 @@ export class TestRig {
|
||||
);
|
||||
}
|
||||
|
||||
async waitForToolCall(toolName, timeout) {
|
||||
async waitForToolCall(toolName: string, timeout?: number) {
|
||||
// Use environment-specific timeout
|
||||
if (!timeout) {
|
||||
timeout = this.getDefaultTimeout();
|
||||
@@ -341,7 +369,7 @@ export class TestRig {
|
||||
);
|
||||
}
|
||||
|
||||
async waitForAnyToolCall(toolNames, timeout) {
|
||||
async waitForAnyToolCall(toolNames: string[], timeout?: number) {
|
||||
// Use environment-specific timeout
|
||||
if (!timeout) {
|
||||
timeout = this.getDefaultTimeout();
|
||||
@@ -362,7 +390,11 @@ export class TestRig {
|
||||
);
|
||||
}
|
||||
|
||||
async poll(predicate, timeout, interval) {
|
||||
async poll(
|
||||
predicate: () => boolean,
|
||||
timeout: number,
|
||||
interval: number,
|
||||
): Promise<boolean> {
|
||||
const startTime = Date.now();
|
||||
let attempts = 0;
|
||||
while (Date.now() - startTime < timeout) {
|
||||
@@ -384,8 +416,16 @@ export class TestRig {
|
||||
return false;
|
||||
}
|
||||
|
||||
_parseToolLogsFromStdout(stdout) {
|
||||
const logs = [];
|
||||
_parseToolLogsFromStdout(stdout: string) {
|
||||
const logs: {
|
||||
timestamp: number;
|
||||
toolRequest: {
|
||||
name: string;
|
||||
args: string;
|
||||
success: boolean;
|
||||
duration_ms: number;
|
||||
};
|
||||
}[] = [];
|
||||
|
||||
// The console output from Podman is JavaScript object notation, not JSON
|
||||
// Look for tool call events in the output
|
||||
@@ -488,7 +528,7 @@ export class TestRig {
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (_e) {
|
||||
} catch {
|
||||
// Not valid JSON
|
||||
}
|
||||
currentObject = '';
|
||||
@@ -505,7 +545,7 @@ export class TestRig {
|
||||
// If not, fall back to parsing from stdout
|
||||
if (env.GEMINI_SANDBOX === 'podman') {
|
||||
// Try reading from file first
|
||||
const logFilePath = join(this.testDir, 'telemetry.log');
|
||||
const logFilePath = join(this.testDir!, 'telemetry.log');
|
||||
|
||||
if (fileExists(logFilePath)) {
|
||||
try {
|
||||
@@ -517,7 +557,7 @@ export class TestRig {
|
||||
// File exists but is empty or doesn't have events, parse from stdout
|
||||
return this._parseToolLogsFromStdout(this._lastRunStdout);
|
||||
}
|
||||
} catch (_e) {
|
||||
} catch {
|
||||
// Error reading file, fall back to stdout
|
||||
if (this._lastRunStdout) {
|
||||
return this._parseToolLogsFromStdout(this._lastRunStdout);
|
||||
@@ -532,7 +572,7 @@ export class TestRig {
|
||||
// In sandbox mode, telemetry is written to a relative path in the test directory
|
||||
const logFilePath =
|
||||
env.GEMINI_SANDBOX && env.GEMINI_SANDBOX !== 'false'
|
||||
? join(this.testDir, 'telemetry.log')
|
||||
? join(this.testDir!, 'telemetry.log')
|
||||
: env.TELEMETRY_LOG_FILE;
|
||||
|
||||
if (!logFilePath) {
|
||||
@@ -548,7 +588,7 @@ export class TestRig {
|
||||
const content = readFileSync(logFilePath, 'utf-8');
|
||||
|
||||
// Split the content into individual JSON objects
|
||||
// They are separated by "}\n{" pattern
|
||||
// They are separated by "}\n{"
|
||||
const jsonObjects = content
|
||||
.split(/}\s*\n\s*{/)
|
||||
.map((obj, index, array) => {
|
||||
@@ -559,7 +599,14 @@ export class TestRig {
|
||||
})
|
||||
.filter((obj) => obj);
|
||||
|
||||
const logs = [];
|
||||
const logs: {
|
||||
toolRequest: {
|
||||
name: string;
|
||||
args: string;
|
||||
success: boolean;
|
||||
duration_ms: number;
|
||||
};
|
||||
}[] = [];
|
||||
|
||||
for (const jsonStr of jsonObjects) {
|
||||
try {
|
||||
@@ -579,10 +626,13 @@ export class TestRig {
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (_e) {
|
||||
} catch (e) {
|
||||
// Skip objects that aren't valid JSON
|
||||
if (env.VERBOSE === 'true') {
|
||||
console.error('Failed to parse telemetry object:', _e.message);
|
||||
console.error(
|
||||
'Failed to parse telemetry object:',
|
||||
(e as Error).message,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
8
integration-tests/tsconfig.json
Normal file
8
integration-tests/tsconfig.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"allowJs": true
|
||||
},
|
||||
"include": ["**/*.ts"]
|
||||
}
|
||||
@@ -23,10 +23,13 @@ test('should be able to search the web', async () => {
|
||||
} catch (error) {
|
||||
// Network errors can occur in CI environments
|
||||
if (
|
||||
error.message.includes('network') ||
|
||||
error.message.includes('timeout')
|
||||
error instanceof Error &&
|
||||
(error.message.includes('network') || error.message.includes('timeout'))
|
||||
) {
|
||||
console.warn('Skipping test due to network error:', error.message);
|
||||
console.warn(
|
||||
'Skipping test due to network error:',
|
||||
(error as Error).message,
|
||||
);
|
||||
return; // Skip the test
|
||||
}
|
||||
throw error; // Re-throw if not a network error
|
||||
104
package-lock.json
generated
104
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@qwen-code/qwen-code",
|
||||
"version": "0.0.6",
|
||||
"version": "0.0.8-nightly.6",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@qwen-code/qwen-code",
|
||||
"version": "0.0.6",
|
||||
"version": "0.0.8-nightly.6",
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
@@ -37,9 +37,11 @@
|
||||
"json": "^11.0.0",
|
||||
"lodash": "^4.17.21",
|
||||
"memfs": "^4.17.2",
|
||||
"mnemonist": "^0.40.3",
|
||||
"mock-fs": "^5.5.0",
|
||||
"prettier": "^3.5.3",
|
||||
"react-devtools-core": "^4.28.5",
|
||||
"tsx": "^4.20.3",
|
||||
"typescript-eslint": "^8.30.1",
|
||||
"vitest": "^3.2.4",
|
||||
"yargs": "^17.7.2"
|
||||
@@ -2515,15 +2517,7 @@
|
||||
"version": "10.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz",
|
||||
"integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/vscode": {
|
||||
"version": "1.102.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.102.0.tgz",
|
||||
"integrity": "sha512-V9sFXmcXz03FtYTSUsYsu5K0Q9wH9w9V25slddcxrh5JgORD14LpnOA7ov0L9ALi+6HrTjskLJ/tY5zeRF3TFA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@types/ws": {
|
||||
"version": "8.18.1",
|
||||
@@ -5547,6 +5541,12 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/fzf": {
|
||||
"version": "0.5.2",
|
||||
"resolved": "https://registry.npmjs.org/fzf/-/fzf-0.5.2.tgz",
|
||||
"integrity": "sha512-Tt4kuxLXFKHy8KT40zwsUPUkg1CrsgY25FxA2U/j/0WgEDCk3ddc/zLTCCcbSHX9FcKtLuVaDGtGE/STWC+j3Q==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/gcp-metadata": {
|
||||
"version": "6.1.1",
|
||||
"resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-6.1.1.tgz",
|
||||
@@ -5695,6 +5695,19 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/get-tsconfig": {
|
||||
"version": "4.10.1",
|
||||
"resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.10.1.tgz",
|
||||
"integrity": "sha512-auHyJ4AgMz7vgS8Hp3N6HXSmlMdUyhSUrfBF16w153rxtLIEOE+HGqaBppczZvnHLqQJfiHotCYpNhl0lUROFQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"resolve-pkg-maps": "^1.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/glob": {
|
||||
"version": "10.4.5",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz",
|
||||
@@ -7873,6 +7886,15 @@
|
||||
"node": ">=16 || 14 >=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/mnemonist": {
|
||||
"version": "0.40.3",
|
||||
"resolved": "https://registry.npmjs.org/mnemonist/-/mnemonist-0.40.3.tgz",
|
||||
"integrity": "sha512-Vjyr90sJ23CKKH/qPAgUKicw/v6pRoamxIEDFOF8uSgFME7DqPRpHgRTejWVjkdGg5dXj0/NyxZHZ9bcjH+2uQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"obliterator": "^2.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/mock-fs": {
|
||||
"version": "5.5.0",
|
||||
"resolved": "https://registry.npmjs.org/mock-fs/-/mock-fs-5.5.0.tgz",
|
||||
@@ -8303,6 +8325,12 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/obliterator": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/obliterator/-/obliterator-2.0.5.tgz",
|
||||
"integrity": "sha512-42CPE9AhahZRsMNslczq0ctAEtqk8Eka26QofnqC346BZdHDySk3LWka23LI7ULIw11NmltpiLagIq8gBozxTw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/on-finished": {
|
||||
"version": "2.4.1",
|
||||
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
|
||||
@@ -9271,6 +9299,16 @@
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/resolve-pkg-maps": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
|
||||
"integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/restore-cursor": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz",
|
||||
@@ -10577,6 +10615,26 @@
|
||||
"dev": true,
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/tsx": {
|
||||
"version": "4.20.3",
|
||||
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.20.3.tgz",
|
||||
"integrity": "sha512-qjbnuR9Tr+FJOMBqJCW5ehvIo/buZq7vH7qD7JziU98h6l3qGy0a/yPFjwO+y0/T7GFpNgNAvEcPPVfyT8rrPQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"esbuild": "~0.25.0",
|
||||
"get-tsconfig": "^4.7.5"
|
||||
},
|
||||
"bin": {
|
||||
"tsx": "dist/cli.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "~2.3.3"
|
||||
}
|
||||
},
|
||||
"node_modules/type-check": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
|
||||
@@ -11700,10 +11758,11 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@qwen-code/qwen-code",
|
||||
"version": "0.0.6",
|
||||
"version": "0.0.8-nightly.6",
|
||||
"dependencies": {
|
||||
"@google/genai": "1.9.0",
|
||||
"@iarna/toml": "^2.2.5",
|
||||
"@modelcontextprotocol/sdk": "^1.15.1",
|
||||
"@qwen-code/qwen-code-core": "file:../core",
|
||||
"@types/update-notifier": "^6.0.8",
|
||||
"command-exists": "^1.2.9",
|
||||
@@ -11727,7 +11786,7 @@
|
||||
"string-width": "^7.1.0",
|
||||
"strip-ansi": "^7.1.0",
|
||||
"strip-json-comments": "^3.1.1",
|
||||
"tiktoken": "^1.0.21",
|
||||
"undici": "^7.10.0",
|
||||
"update-notifier": "^7.3.1",
|
||||
"yargs": "^17.7.2",
|
||||
"zod": "^3.23.8"
|
||||
@@ -11904,7 +11963,7 @@
|
||||
},
|
||||
"packages/core": {
|
||||
"name": "@qwen-code/qwen-code-core",
|
||||
"version": "0.0.6",
|
||||
"version": "0.0.8-nightly.6",
|
||||
"dependencies": {
|
||||
"@google/genai": "1.9.0",
|
||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||
@@ -11920,6 +11979,7 @@
|
||||
"diff": "^7.0.0",
|
||||
"dotenv": "^17.1.0",
|
||||
"fdir": "^6.4.6",
|
||||
"fzf": "^0.5.2",
|
||||
"glob": "^10.4.5",
|
||||
"google-auth-library": "^9.11.0",
|
||||
"html-to-text": "^9.0.5",
|
||||
@@ -11928,6 +11988,7 @@
|
||||
"jsonrepair": "^3.13.0",
|
||||
"marked": "^15.0.12",
|
||||
"micromatch": "^4.0.8",
|
||||
"mnemonist": "^0.40.3",
|
||||
"open": "^10.1.2",
|
||||
"openai": "5.11.0",
|
||||
"picomatch": "^4.0.1",
|
||||
@@ -12052,7 +12113,7 @@
|
||||
},
|
||||
"packages/test-utils": {
|
||||
"name": "@qwen-code/qwen-code-test-utils",
|
||||
"version": "0.1.18",
|
||||
"version": "0.0.8-nightly.6",
|
||||
"license": "Apache-2.0",
|
||||
"devDependencies": {
|
||||
"typescript": "^5.3.3"
|
||||
@@ -12063,7 +12124,7 @@
|
||||
},
|
||||
"packages/vscode-ide-companion": {
|
||||
"name": "qwen-code-vscode-ide-companion",
|
||||
"version": "0.0.6",
|
||||
"version": "0.0.8-nightly.6",
|
||||
"license": "LICENSE",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.15.1",
|
||||
@@ -12075,7 +12136,7 @@
|
||||
"@types/cors": "^2.8.19",
|
||||
"@types/express": "^5.0.3",
|
||||
"@types/node": "20.x",
|
||||
"@types/vscode": "^1.101.0",
|
||||
"@types/vscode": "^1.99.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.31.1",
|
||||
"@typescript-eslint/parser": "^8.31.1",
|
||||
"esbuild": "^0.25.3",
|
||||
@@ -12085,8 +12146,15 @@
|
||||
"vitest": "^3.2.4"
|
||||
},
|
||||
"engines": {
|
||||
"vscode": "^1.101.0"
|
||||
"vscode": "^1.99.0"
|
||||
}
|
||||
},
|
||||
"packages/vscode-ide-companion/node_modules/@types/vscode": {
|
||||
"version": "1.99.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.99.0.tgz",
|
||||
"integrity": "sha512-30sjmas1hQ0gVbX68LAWlm/YYlEqUErunPJJKLpEl+xhK0mKn+jyzlCOpsdTwfkZfPy4U6CDkmygBLC3AB8W9Q==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
12
package.json
12
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@qwen-code/qwen-code",
|
||||
"version": "0.0.6",
|
||||
"version": "0.0.8-nightly.6",
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
@@ -13,7 +13,7 @@
|
||||
"url": "git+https://github.com/QwenLM/qwen-code.git"
|
||||
},
|
||||
"config": {
|
||||
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.0.6"
|
||||
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.0.8-nightly.6"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node scripts/start.js",
|
||||
@@ -28,7 +28,7 @@
|
||||
"build:packages": "npm run build --workspaces",
|
||||
"build:sandbox": "node scripts/build_sandbox.js --skip-npm-install-build",
|
||||
"bundle": "npm run generate && node esbuild.config.js && node scripts/copy_bundle_assets.js",
|
||||
"test": "npm run test --workspaces",
|
||||
"test": "npm run test --workspaces --if-present",
|
||||
"test:ci": "npm run test:ci --workspaces --if-present && npm run test:scripts",
|
||||
"test:scripts": "vitest run --config ./scripts/tests/vitest.config.ts",
|
||||
"test:e2e": "npm run test:integration:sandbox:none -- --verbose --keep-output",
|
||||
@@ -39,7 +39,7 @@
|
||||
"lint": "eslint . --ext .ts,.tsx && eslint integration-tests",
|
||||
"lint:fix": "eslint . --fix && eslint integration-tests --fix",
|
||||
"lint:ci": "eslint . --ext .ts,.tsx --max-warnings 0 && eslint integration-tests --max-warnings 0",
|
||||
"format": "prettier --write .",
|
||||
"format": "prettier --experimental-cli --write .",
|
||||
"typecheck": "npm run typecheck --workspaces --if-present",
|
||||
"preflight": "npm run clean && npm ci && npm run format && npm run lint:ci && npm run build && npm run typecheck && npm run test:ci",
|
||||
"prepare": "npm run bundle",
|
||||
@@ -83,8 +83,10 @@
|
||||
"mock-fs": "^5.5.0",
|
||||
"prettier": "^3.5.3",
|
||||
"react-devtools-core": "^4.28.5",
|
||||
"tsx": "^4.20.3",
|
||||
"typescript-eslint": "^8.30.1",
|
||||
"vitest": "^3.2.4",
|
||||
"yargs": "^17.7.2"
|
||||
"yargs": "^17.7.2",
|
||||
"mnemonist": "^0.40.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@qwen-code/qwen-code",
|
||||
"version": "0.0.6",
|
||||
"version": "0.0.8-nightly.6",
|
||||
"description": "Qwen Code",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -25,12 +25,13 @@
|
||||
"dist"
|
||||
],
|
||||
"config": {
|
||||
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.0.6"
|
||||
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.0.8-nightly.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@google/genai": "1.9.0",
|
||||
"@iarna/toml": "^2.2.5",
|
||||
"@qwen-code/qwen-code-core": "file:../core",
|
||||
"@modelcontextprotocol/sdk": "^1.15.1",
|
||||
"@types/update-notifier": "^6.0.8",
|
||||
"command-exists": "^1.2.9",
|
||||
"diff": "^7.0.0",
|
||||
@@ -53,7 +54,7 @@
|
||||
"string-width": "^7.1.0",
|
||||
"strip-ansi": "^7.1.0",
|
||||
"strip-json-comments": "^3.1.1",
|
||||
"tiktoken": "^1.0.21",
|
||||
"undici": "^7.10.0",
|
||||
"update-notifier": "^7.3.1",
|
||||
"yargs": "^17.7.2",
|
||||
"zod": "^3.23.8"
|
||||
|
||||
@@ -239,65 +239,62 @@ class GeminiAgent implements Agent {
|
||||
);
|
||||
}
|
||||
|
||||
let toolCallId;
|
||||
const confirmationDetails = await tool.shouldConfirmExecute(
|
||||
args,
|
||||
abortSignal,
|
||||
);
|
||||
if (confirmationDetails) {
|
||||
let content: acp.ToolCallContent | null = null;
|
||||
if (confirmationDetails.type === 'edit') {
|
||||
content = {
|
||||
type: 'diff',
|
||||
path: confirmationDetails.fileName,
|
||||
oldText: confirmationDetails.originalContent,
|
||||
newText: confirmationDetails.newContent,
|
||||
};
|
||||
}
|
||||
|
||||
const result = await this.client.requestToolCallConfirmation({
|
||||
label: tool.getDescription(args),
|
||||
icon: tool.icon,
|
||||
content,
|
||||
confirmation: toAcpToolCallConfirmation(confirmationDetails),
|
||||
locations: tool.toolLocations(args),
|
||||
});
|
||||
|
||||
await confirmationDetails.onConfirm(toToolCallOutcome(result.outcome));
|
||||
switch (result.outcome) {
|
||||
case 'reject':
|
||||
return errorResponse(
|
||||
new Error(`Tool "${fc.name}" not allowed to run by the user.`),
|
||||
);
|
||||
|
||||
case 'cancel':
|
||||
return errorResponse(
|
||||
new Error(`Tool "${fc.name}" was canceled by the user.`),
|
||||
);
|
||||
case 'allow':
|
||||
case 'alwaysAllow':
|
||||
case 'alwaysAllowMcpServer':
|
||||
case 'alwaysAllowTool':
|
||||
break;
|
||||
default: {
|
||||
const resultOutcome: never = result.outcome;
|
||||
throw new Error(`Unexpected: ${resultOutcome}`);
|
||||
}
|
||||
}
|
||||
|
||||
toolCallId = result.id;
|
||||
} else {
|
||||
const result = await this.client.pushToolCall({
|
||||
icon: tool.icon,
|
||||
label: tool.getDescription(args),
|
||||
locations: tool.toolLocations(args),
|
||||
});
|
||||
|
||||
toolCallId = result.id;
|
||||
}
|
||||
|
||||
let toolCallId: number | undefined = undefined;
|
||||
try {
|
||||
const toolResult: ToolResult = await tool.execute(args, abortSignal);
|
||||
const invocation = tool.build(args);
|
||||
const confirmationDetails =
|
||||
await invocation.shouldConfirmExecute(abortSignal);
|
||||
if (confirmationDetails) {
|
||||
let content: acp.ToolCallContent | null = null;
|
||||
if (confirmationDetails.type === 'edit') {
|
||||
content = {
|
||||
type: 'diff',
|
||||
path: confirmationDetails.fileName,
|
||||
oldText: confirmationDetails.originalContent,
|
||||
newText: confirmationDetails.newContent,
|
||||
};
|
||||
}
|
||||
|
||||
const result = await this.client.requestToolCallConfirmation({
|
||||
label: invocation.getDescription(),
|
||||
icon: tool.icon,
|
||||
content,
|
||||
confirmation: toAcpToolCallConfirmation(confirmationDetails),
|
||||
locations: invocation.toolLocations(),
|
||||
});
|
||||
|
||||
await confirmationDetails.onConfirm(toToolCallOutcome(result.outcome));
|
||||
switch (result.outcome) {
|
||||
case 'reject':
|
||||
return errorResponse(
|
||||
new Error(`Tool "${fc.name}" not allowed to run by the user.`),
|
||||
);
|
||||
|
||||
case 'cancel':
|
||||
return errorResponse(
|
||||
new Error(`Tool "${fc.name}" was canceled by the user.`),
|
||||
);
|
||||
case 'allow':
|
||||
case 'alwaysAllow':
|
||||
case 'alwaysAllowMcpServer':
|
||||
case 'alwaysAllowTool':
|
||||
break;
|
||||
default: {
|
||||
const resultOutcome: never = result.outcome;
|
||||
throw new Error(`Unexpected: ${resultOutcome}`);
|
||||
}
|
||||
}
|
||||
toolCallId = result.id;
|
||||
} else {
|
||||
const result = await this.client.pushToolCall({
|
||||
icon: tool.icon,
|
||||
label: invocation.getDescription(),
|
||||
locations: invocation.toolLocations(),
|
||||
});
|
||||
toolCallId = result.id;
|
||||
}
|
||||
|
||||
const toolResult: ToolResult = await invocation.execute(abortSignal);
|
||||
const toolCallContent = toToolCallContent(toolResult);
|
||||
|
||||
await this.client.updateToolCall({
|
||||
@@ -320,12 +317,13 @@ class GeminiAgent implements Agent {
|
||||
return convertToFunctionResponse(fc.name, callId, toolResult.llmContent);
|
||||
} catch (e) {
|
||||
const error = e instanceof Error ? e : new Error(String(e));
|
||||
await this.client.updateToolCall({
|
||||
toolCallId,
|
||||
status: 'error',
|
||||
content: { type: 'markdown', markdown: error.message },
|
||||
});
|
||||
|
||||
if (toolCallId) {
|
||||
await this.client.updateToolCall({
|
||||
toolCallId,
|
||||
status: 'error',
|
||||
content: { type: 'markdown', markdown: error.message },
|
||||
});
|
||||
}
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -408,7 +406,7 @@ class GeminiAgent implements Agent {
|
||||
`Path ${pathName} not found directly, attempting glob search.`,
|
||||
);
|
||||
try {
|
||||
const globResult = await globTool.execute(
|
||||
const globResult = await globTool.buildAndExecute(
|
||||
{
|
||||
pattern: `**/*${pathName}*`,
|
||||
path: this.config.getTargetDir(),
|
||||
@@ -530,12 +528,15 @@ class GeminiAgent implements Agent {
|
||||
respectGitIgnore, // Use configuration setting
|
||||
};
|
||||
|
||||
const toolCall = await this.client.pushToolCall({
|
||||
icon: readManyFilesTool.icon,
|
||||
label: readManyFilesTool.getDescription(toolArgs),
|
||||
});
|
||||
let toolCallId: number | undefined = undefined;
|
||||
try {
|
||||
const result = await readManyFilesTool.execute(toolArgs, abortSignal);
|
||||
const invocation = readManyFilesTool.build(toolArgs);
|
||||
const toolCall = await this.client.pushToolCall({
|
||||
icon: readManyFilesTool.icon,
|
||||
label: invocation.getDescription(),
|
||||
});
|
||||
toolCallId = toolCall.id;
|
||||
const result = await invocation.execute(abortSignal);
|
||||
const content = toToolCallContent(result) || {
|
||||
type: 'markdown',
|
||||
markdown: `Successfully read: ${contentLabelsForDisplay.join(', ')}`,
|
||||
@@ -578,14 +579,16 @@ class GeminiAgent implements Agent {
|
||||
|
||||
return processedQueryParts;
|
||||
} catch (error: unknown) {
|
||||
await this.client.updateToolCall({
|
||||
toolCallId: toolCall.id,
|
||||
status: 'error',
|
||||
content: {
|
||||
type: 'markdown',
|
||||
markdown: `Error reading files (${contentLabelsForDisplay.join(', ')}): ${getErrorMessage(error)}`,
|
||||
},
|
||||
});
|
||||
if (toolCallId) {
|
||||
await this.client.updateToolCall({
|
||||
toolCallId,
|
||||
status: 'error',
|
||||
content: {
|
||||
type: 'markdown',
|
||||
markdown: `Error reading files (${contentLabelsForDisplay.join(', ')}): ${getErrorMessage(error)}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
55
packages/cli/src/commands/mcp.test.ts
Normal file
55
packages/cli/src/commands/mcp.test.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { mcpCommand } from './mcp.js';
|
||||
import { type Argv } from 'yargs';
|
||||
import yargs from 'yargs';
|
||||
|
||||
describe('mcp command', () => {
|
||||
it('should have correct command definition', () => {
|
||||
expect(mcpCommand.command).toBe('mcp');
|
||||
expect(mcpCommand.describe).toBe('Manage MCP servers');
|
||||
expect(typeof mcpCommand.builder).toBe('function');
|
||||
expect(typeof mcpCommand.handler).toBe('function');
|
||||
});
|
||||
|
||||
it('should have exactly one option (help flag)', () => {
|
||||
// Test to ensure that the global 'gemini' flags are not added to the mcp command
|
||||
const yargsInstance = yargs();
|
||||
const builtYargs = mcpCommand.builder(yargsInstance);
|
||||
const options = builtYargs.getOptions();
|
||||
|
||||
// Should have exactly 1 option (help flag)
|
||||
expect(Object.keys(options.key).length).toBe(1);
|
||||
expect(options.key).toHaveProperty('help');
|
||||
});
|
||||
|
||||
it('should register add, remove, and list subcommands', () => {
|
||||
const mockYargs = {
|
||||
command: vi.fn().mockReturnThis(),
|
||||
demandCommand: vi.fn().mockReturnThis(),
|
||||
version: vi.fn().mockReturnThis(),
|
||||
};
|
||||
|
||||
mcpCommand.builder(mockYargs as unknown as Argv);
|
||||
|
||||
expect(mockYargs.command).toHaveBeenCalledTimes(3);
|
||||
|
||||
// Verify that the specific subcommands are registered
|
||||
const commandCalls = mockYargs.command.mock.calls;
|
||||
const commandNames = commandCalls.map((call) => call[0].command);
|
||||
|
||||
expect(commandNames).toContain('add <name> <commandOrUrl> [args...]');
|
||||
expect(commandNames).toContain('remove <name>');
|
||||
expect(commandNames).toContain('list');
|
||||
|
||||
expect(mockYargs.demandCommand).toHaveBeenCalledWith(
|
||||
1,
|
||||
'You need at least one command before continuing.',
|
||||
);
|
||||
});
|
||||
});
|
||||
27
packages/cli/src/commands/mcp.ts
Normal file
27
packages/cli/src/commands/mcp.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
// File for 'gemini mcp' command
|
||||
import type { CommandModule, Argv } from 'yargs';
|
||||
import { addCommand } from './mcp/add.js';
|
||||
import { removeCommand } from './mcp/remove.js';
|
||||
import { listCommand } from './mcp/list.js';
|
||||
|
||||
export const mcpCommand: CommandModule = {
|
||||
command: 'mcp',
|
||||
describe: 'Manage MCP servers',
|
||||
builder: (yargs: Argv) =>
|
||||
yargs
|
||||
.command(addCommand)
|
||||
.command(removeCommand)
|
||||
.command(listCommand)
|
||||
.demandCommand(1, 'You need at least one command before continuing.')
|
||||
.version(false),
|
||||
handler: () => {
|
||||
// yargs will automatically show help if no subcommand is provided
|
||||
// thanks to demandCommand(1) in the builder.
|
||||
},
|
||||
};
|
||||
88
packages/cli/src/commands/mcp/add.test.ts
Normal file
88
packages/cli/src/commands/mcp/add.test.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import yargs from 'yargs';
|
||||
import { addCommand } from './add.js';
|
||||
import { loadSettings, SettingScope } from '../../config/settings.js';
|
||||
|
||||
vi.mock('fs/promises', () => ({
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../config/settings.js', async () => {
|
||||
const actual = await vi.importActual('../../config/settings.js');
|
||||
return {
|
||||
...actual,
|
||||
loadSettings: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
const mockedLoadSettings = loadSettings as vi.Mock;
|
||||
|
||||
describe('mcp add command', () => {
|
||||
let parser: yargs.Argv;
|
||||
let mockSetValue: vi.Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
const yargsInstance = yargs([]).command(addCommand);
|
||||
parser = yargsInstance;
|
||||
mockSetValue = vi.fn();
|
||||
mockedLoadSettings.mockReturnValue({
|
||||
forScope: () => ({ settings: {} }),
|
||||
setValue: mockSetValue,
|
||||
});
|
||||
});
|
||||
|
||||
it('should add a stdio server to project settings', async () => {
|
||||
await parser.parseAsync(
|
||||
'add my-server /path/to/server arg1 arg2 -e FOO=bar',
|
||||
);
|
||||
|
||||
expect(mockSetValue).toHaveBeenCalledWith(
|
||||
SettingScope.Workspace,
|
||||
'mcpServers',
|
||||
{
|
||||
'my-server': {
|
||||
command: '/path/to/server',
|
||||
args: ['arg1', 'arg2'],
|
||||
env: { FOO: 'bar' },
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('should add an sse server to user settings', async () => {
|
||||
await parser.parseAsync(
|
||||
'add --transport sse sse-server https://example.com/sse-endpoint --scope user -H "X-API-Key: your-key"',
|
||||
);
|
||||
|
||||
expect(mockSetValue).toHaveBeenCalledWith(SettingScope.User, 'mcpServers', {
|
||||
'sse-server': {
|
||||
url: 'https://example.com/sse-endpoint',
|
||||
headers: { 'X-API-Key': 'your-key' },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should add an http server to project settings', async () => {
|
||||
await parser.parseAsync(
|
||||
'add --transport http http-server https://example.com/mcp -H "Authorization: Bearer your-token"',
|
||||
);
|
||||
|
||||
expect(mockSetValue).toHaveBeenCalledWith(
|
||||
SettingScope.Workspace,
|
||||
'mcpServers',
|
||||
{
|
||||
'http-server': {
|
||||
httpUrl: 'https://example.com/mcp',
|
||||
headers: { Authorization: 'Bearer your-token' },
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
211
packages/cli/src/commands/mcp/add.ts
Normal file
211
packages/cli/src/commands/mcp/add.ts
Normal file
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
// File for 'gemini mcp add' command
|
||||
import type { CommandModule } from 'yargs';
|
||||
import { loadSettings, SettingScope } from '../../config/settings.js';
|
||||
import { MCPServerConfig } from '@qwen-code/qwen-code-core';
|
||||
|
||||
async function addMcpServer(
|
||||
name: string,
|
||||
commandOrUrl: string,
|
||||
args: Array<string | number> | undefined,
|
||||
options: {
|
||||
scope: string;
|
||||
transport: string;
|
||||
env: string[] | undefined;
|
||||
header: string[] | undefined;
|
||||
timeout?: number;
|
||||
trust?: boolean;
|
||||
description?: string;
|
||||
includeTools?: string[];
|
||||
excludeTools?: string[];
|
||||
},
|
||||
) {
|
||||
const {
|
||||
scope,
|
||||
transport,
|
||||
env,
|
||||
header,
|
||||
timeout,
|
||||
trust,
|
||||
description,
|
||||
includeTools,
|
||||
excludeTools,
|
||||
} = options;
|
||||
const settingsScope =
|
||||
scope === 'user' ? SettingScope.User : SettingScope.Workspace;
|
||||
const settings = loadSettings(process.cwd());
|
||||
|
||||
let newServer: Partial<MCPServerConfig> = {};
|
||||
|
||||
const headers = header?.reduce(
|
||||
(acc, curr) => {
|
||||
const [key, ...valueParts] = curr.split(':');
|
||||
const value = valueParts.join(':').trim();
|
||||
if (key.trim() && value) {
|
||||
acc[key.trim()] = value;
|
||||
}
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, string>,
|
||||
);
|
||||
|
||||
switch (transport) {
|
||||
case 'sse':
|
||||
newServer = {
|
||||
url: commandOrUrl,
|
||||
headers,
|
||||
timeout,
|
||||
trust,
|
||||
description,
|
||||
includeTools,
|
||||
excludeTools,
|
||||
};
|
||||
break;
|
||||
case 'http':
|
||||
newServer = {
|
||||
httpUrl: commandOrUrl,
|
||||
headers,
|
||||
timeout,
|
||||
trust,
|
||||
description,
|
||||
includeTools,
|
||||
excludeTools,
|
||||
};
|
||||
break;
|
||||
case 'stdio':
|
||||
default:
|
||||
newServer = {
|
||||
command: commandOrUrl,
|
||||
args: args?.map(String),
|
||||
env: env?.reduce(
|
||||
(acc, curr) => {
|
||||
const [key, value] = curr.split('=');
|
||||
if (key && value) {
|
||||
acc[key] = value;
|
||||
}
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, string>,
|
||||
),
|
||||
timeout,
|
||||
trust,
|
||||
description,
|
||||
includeTools,
|
||||
excludeTools,
|
||||
};
|
||||
break;
|
||||
}
|
||||
|
||||
const existingSettings = settings.forScope(settingsScope).settings;
|
||||
const mcpServers = existingSettings.mcpServers || {};
|
||||
|
||||
const isExistingServer = !!mcpServers[name];
|
||||
if (isExistingServer) {
|
||||
console.log(
|
||||
`MCP server "${name}" is already configured within ${scope} settings.`,
|
||||
);
|
||||
}
|
||||
|
||||
mcpServers[name] = newServer as MCPServerConfig;
|
||||
|
||||
settings.setValue(settingsScope, 'mcpServers', mcpServers);
|
||||
|
||||
if (isExistingServer) {
|
||||
console.log(`MCP server "${name}" updated in ${scope} settings.`);
|
||||
} else {
|
||||
console.log(
|
||||
`MCP server "${name}" added to ${scope} settings. (${transport})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const addCommand: CommandModule = {
|
||||
command: 'add <name> <commandOrUrl> [args...]',
|
||||
describe: 'Add a server',
|
||||
builder: (yargs) =>
|
||||
yargs
|
||||
.usage('Usage: gemini mcp add [options] <name> <commandOrUrl> [args...]')
|
||||
.positional('name', {
|
||||
describe: 'Name of the server',
|
||||
type: 'string',
|
||||
demandOption: true,
|
||||
})
|
||||
.positional('commandOrUrl', {
|
||||
describe: 'Command (stdio) or URL (sse, http)',
|
||||
type: 'string',
|
||||
demandOption: true,
|
||||
})
|
||||
.option('scope', {
|
||||
alias: 's',
|
||||
describe: 'Configuration scope (user or project)',
|
||||
type: 'string',
|
||||
default: 'project',
|
||||
choices: ['user', 'project'],
|
||||
})
|
||||
.option('transport', {
|
||||
alias: 't',
|
||||
describe: 'Transport type (stdio, sse, http)',
|
||||
type: 'string',
|
||||
default: 'stdio',
|
||||
choices: ['stdio', 'sse', 'http'],
|
||||
})
|
||||
.option('env', {
|
||||
alias: 'e',
|
||||
describe: 'Set environment variables (e.g. -e KEY=value)',
|
||||
type: 'array',
|
||||
string: true,
|
||||
})
|
||||
.option('header', {
|
||||
alias: 'H',
|
||||
describe:
|
||||
'Set HTTP headers for SSE and HTTP transports (e.g. -H "X-Api-Key: abc123" -H "Authorization: Bearer abc123")',
|
||||
type: 'array',
|
||||
string: true,
|
||||
})
|
||||
.option('timeout', {
|
||||
describe: 'Set connection timeout in milliseconds',
|
||||
type: 'number',
|
||||
})
|
||||
.option('trust', {
|
||||
describe:
|
||||
'Trust the server (bypass all tool call confirmation prompts)',
|
||||
type: 'boolean',
|
||||
})
|
||||
.option('description', {
|
||||
describe: 'Set the description for the server',
|
||||
type: 'string',
|
||||
})
|
||||
.option('include-tools', {
|
||||
describe: 'A comma-separated list of tools to include',
|
||||
type: 'array',
|
||||
string: true,
|
||||
})
|
||||
.option('exclude-tools', {
|
||||
describe: 'A comma-separated list of tools to exclude',
|
||||
type: 'array',
|
||||
string: true,
|
||||
}),
|
||||
handler: async (argv) => {
|
||||
await addMcpServer(
|
||||
argv.name as string,
|
||||
argv.commandOrUrl as string,
|
||||
argv.args as Array<string | number>,
|
||||
{
|
||||
scope: argv.scope as string,
|
||||
transport: argv.transport as string,
|
||||
env: argv.env as string[],
|
||||
header: argv.header as string[],
|
||||
timeout: argv.timeout as number | undefined,
|
||||
trust: argv.trust as boolean | undefined,
|
||||
description: argv.description as string | undefined,
|
||||
includeTools: argv.includeTools as string[] | undefined,
|
||||
excludeTools: argv.excludeTools as string[] | undefined,
|
||||
},
|
||||
);
|
||||
},
|
||||
};
|
||||
154
packages/cli/src/commands/mcp/list.test.ts
Normal file
154
packages/cli/src/commands/mcp/list.test.ts
Normal file
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { listMcpServers } from './list.js';
|
||||
import { loadSettings } from '../../config/settings.js';
|
||||
import { loadExtensions } from '../../config/extension.js';
|
||||
import { createTransport } from '@qwen-code/qwen-code-core';
|
||||
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
||||
|
||||
vi.mock('../../config/settings.js');
|
||||
vi.mock('../../config/extension.js');
|
||||
vi.mock('@qwen-code/qwen-code-core');
|
||||
vi.mock('@modelcontextprotocol/sdk/client/index.js');
|
||||
|
||||
const mockedLoadSettings = loadSettings as vi.Mock;
|
||||
const mockedLoadExtensions = loadExtensions as vi.Mock;
|
||||
const mockedCreateTransport = createTransport as vi.Mock;
|
||||
const MockedClient = Client as vi.Mock;
|
||||
|
||||
interface MockClient {
|
||||
connect: vi.Mock;
|
||||
ping: vi.Mock;
|
||||
close: vi.Mock;
|
||||
}
|
||||
|
||||
interface MockTransport {
|
||||
close: vi.Mock;
|
||||
}
|
||||
|
||||
describe('mcp list command', () => {
|
||||
let consoleSpy: vi.SpyInstance;
|
||||
let mockClient: MockClient;
|
||||
let mockTransport: MockTransport;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
|
||||
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
|
||||
mockTransport = { close: vi.fn() };
|
||||
mockClient = {
|
||||
connect: vi.fn(),
|
||||
ping: vi.fn(),
|
||||
close: vi.fn(),
|
||||
};
|
||||
|
||||
MockedClient.mockImplementation(() => mockClient);
|
||||
mockedCreateTransport.mockResolvedValue(mockTransport);
|
||||
mockedLoadExtensions.mockReturnValue([]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should display message when no servers configured', async () => {
|
||||
mockedLoadSettings.mockReturnValue({ merged: { mcpServers: {} } });
|
||||
|
||||
await listMcpServers();
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith('No MCP servers configured.');
|
||||
});
|
||||
|
||||
it('should display different server types with connected status', async () => {
|
||||
mockedLoadSettings.mockReturnValue({
|
||||
merged: {
|
||||
mcpServers: {
|
||||
'stdio-server': { command: '/path/to/server', args: ['arg1'] },
|
||||
'sse-server': { url: 'https://example.com/sse' },
|
||||
'http-server': { httpUrl: 'https://example.com/http' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
mockClient.connect.mockResolvedValue(undefined);
|
||||
mockClient.ping.mockResolvedValue(undefined);
|
||||
|
||||
await listMcpServers();
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith('Configured MCP servers:\n');
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
'stdio-server: /path/to/server arg1 (stdio) - Connected',
|
||||
),
|
||||
);
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
'sse-server: https://example.com/sse (sse) - Connected',
|
||||
),
|
||||
);
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
'http-server: https://example.com/http (http) - Connected',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('should display disconnected status when connection fails', async () => {
|
||||
mockedLoadSettings.mockReturnValue({
|
||||
merged: {
|
||||
mcpServers: {
|
||||
'test-server': { command: '/test/server' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
mockClient.connect.mockRejectedValue(new Error('Connection failed'));
|
||||
|
||||
await listMcpServers();
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
'test-server: /test/server (stdio) - Disconnected',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('should merge extension servers with config servers', async () => {
|
||||
mockedLoadSettings.mockReturnValue({
|
||||
merged: {
|
||||
mcpServers: { 'config-server': { command: '/config/server' } },
|
||||
},
|
||||
});
|
||||
|
||||
mockedLoadExtensions.mockReturnValue([
|
||||
{
|
||||
config: {
|
||||
name: 'test-extension',
|
||||
mcpServers: { 'extension-server': { command: '/ext/server' } },
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
mockClient.connect.mockResolvedValue(undefined);
|
||||
mockClient.ping.mockResolvedValue(undefined);
|
||||
|
||||
await listMcpServers();
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
'config-server: /config/server (stdio) - Connected',
|
||||
),
|
||||
);
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
'extension-server: /ext/server (stdio) - Connected',
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
139
packages/cli/src/commands/mcp/list.ts
Normal file
139
packages/cli/src/commands/mcp/list.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
// File for 'gemini mcp list' command
|
||||
import type { CommandModule } from 'yargs';
|
||||
import { loadSettings } from '../../config/settings.js';
|
||||
import {
|
||||
MCPServerConfig,
|
||||
MCPServerStatus,
|
||||
createTransport,
|
||||
} from '@qwen-code/qwen-code-core';
|
||||
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
||||
import { loadExtensions } from '../../config/extension.js';
|
||||
|
||||
const COLOR_GREEN = '\u001b[32m';
|
||||
const COLOR_YELLOW = '\u001b[33m';
|
||||
const COLOR_RED = '\u001b[31m';
|
||||
const RESET_COLOR = '\u001b[0m';
|
||||
|
||||
async function getMcpServersFromConfig(): Promise<
|
||||
Record<string, MCPServerConfig>
|
||||
> {
|
||||
const settings = loadSettings(process.cwd());
|
||||
const extensions = loadExtensions(process.cwd());
|
||||
const mcpServers = { ...(settings.merged.mcpServers || {}) };
|
||||
for (const extension of extensions) {
|
||||
Object.entries(extension.config.mcpServers || {}).forEach(
|
||||
([key, server]) => {
|
||||
if (mcpServers[key]) {
|
||||
return;
|
||||
}
|
||||
mcpServers[key] = {
|
||||
...server,
|
||||
extensionName: extension.config.name,
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
return mcpServers;
|
||||
}
|
||||
|
||||
async function testMCPConnection(
|
||||
serverName: string,
|
||||
config: MCPServerConfig,
|
||||
): Promise<MCPServerStatus> {
|
||||
const client = new Client({
|
||||
name: 'mcp-test-client',
|
||||
version: '0.0.1',
|
||||
});
|
||||
|
||||
let transport;
|
||||
try {
|
||||
// Use the same transport creation logic as core
|
||||
transport = await createTransport(serverName, config, false);
|
||||
} catch (_error) {
|
||||
await client.close();
|
||||
return MCPServerStatus.DISCONNECTED;
|
||||
}
|
||||
|
||||
try {
|
||||
// Attempt actual MCP connection with short timeout
|
||||
await client.connect(transport, { timeout: 5000 }); // 5s timeout
|
||||
|
||||
// Test basic MCP protocol by pinging the server
|
||||
await client.ping();
|
||||
|
||||
await client.close();
|
||||
return MCPServerStatus.CONNECTED;
|
||||
} catch (_error) {
|
||||
await transport.close();
|
||||
return MCPServerStatus.DISCONNECTED;
|
||||
}
|
||||
}
|
||||
|
||||
async function getServerStatus(
|
||||
serverName: string,
|
||||
server: MCPServerConfig,
|
||||
): Promise<MCPServerStatus> {
|
||||
// Test all server types by attempting actual connection
|
||||
return await testMCPConnection(serverName, server);
|
||||
}
|
||||
|
||||
export async function listMcpServers(): Promise<void> {
|
||||
const mcpServers = await getMcpServersFromConfig();
|
||||
const serverNames = Object.keys(mcpServers);
|
||||
|
||||
if (serverNames.length === 0) {
|
||||
console.log('No MCP servers configured.');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Configured MCP servers:\n');
|
||||
|
||||
for (const serverName of serverNames) {
|
||||
const server = mcpServers[serverName];
|
||||
|
||||
const status = await getServerStatus(serverName, server);
|
||||
|
||||
let statusIndicator = '';
|
||||
let statusText = '';
|
||||
switch (status) {
|
||||
case MCPServerStatus.CONNECTED:
|
||||
statusIndicator = COLOR_GREEN + '✓' + RESET_COLOR;
|
||||
statusText = 'Connected';
|
||||
break;
|
||||
case MCPServerStatus.CONNECTING:
|
||||
statusIndicator = COLOR_YELLOW + '…' + RESET_COLOR;
|
||||
statusText = 'Connecting';
|
||||
break;
|
||||
case MCPServerStatus.DISCONNECTED:
|
||||
default:
|
||||
statusIndicator = COLOR_RED + '✗' + RESET_COLOR;
|
||||
statusText = 'Disconnected';
|
||||
break;
|
||||
}
|
||||
|
||||
let serverInfo = `${serverName}: `;
|
||||
if (server.httpUrl) {
|
||||
serverInfo += `${server.httpUrl} (http)`;
|
||||
} else if (server.url) {
|
||||
serverInfo += `${server.url} (sse)`;
|
||||
} else if (server.command) {
|
||||
serverInfo += `${server.command} ${server.args?.join(' ') || ''} (stdio)`;
|
||||
}
|
||||
|
||||
console.log(`${statusIndicator} ${serverInfo} - ${statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
export const listCommand: CommandModule = {
|
||||
command: 'list',
|
||||
describe: 'List all configured MCP servers',
|
||||
handler: async () => {
|
||||
await listMcpServers();
|
||||
},
|
||||
};
|
||||
69
packages/cli/src/commands/mcp/remove.test.ts
Normal file
69
packages/cli/src/commands/mcp/remove.test.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { vi, describe, it, expect, beforeEach } from 'vitest';
|
||||
import yargs from 'yargs';
|
||||
import { loadSettings, SettingScope } from '../../config/settings.js';
|
||||
import { removeCommand } from './remove.js';
|
||||
|
||||
vi.mock('fs/promises', () => ({
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../config/settings.js', async () => {
|
||||
const actual = await vi.importActual('../../config/settings.js');
|
||||
return {
|
||||
...actual,
|
||||
loadSettings: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
const mockedLoadSettings = loadSettings as vi.Mock;
|
||||
|
||||
describe('mcp remove command', () => {
|
||||
let parser: yargs.Argv;
|
||||
let mockSetValue: vi.Mock;
|
||||
let mockSettings: Record<string, unknown>;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
const yargsInstance = yargs([]).command(removeCommand);
|
||||
parser = yargsInstance;
|
||||
mockSetValue = vi.fn();
|
||||
mockSettings = {
|
||||
mcpServers: {
|
||||
'test-server': {
|
||||
command: 'echo "hello"',
|
||||
},
|
||||
},
|
||||
};
|
||||
mockedLoadSettings.mockReturnValue({
|
||||
forScope: () => ({ settings: mockSettings }),
|
||||
setValue: mockSetValue,
|
||||
});
|
||||
});
|
||||
|
||||
it('should remove a server from project settings', async () => {
|
||||
await parser.parseAsync('remove test-server');
|
||||
|
||||
expect(mockSetValue).toHaveBeenCalledWith(
|
||||
SettingScope.Workspace,
|
||||
'mcpServers',
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
it('should show a message if server not found', async () => {
|
||||
const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
await parser.parseAsync('remove non-existent-server');
|
||||
|
||||
expect(mockSetValue).not.toHaveBeenCalled();
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
'Server "non-existent-server" not found in project settings.',
|
||||
);
|
||||
});
|
||||
});
|
||||
60
packages/cli/src/commands/mcp/remove.ts
Normal file
60
packages/cli/src/commands/mcp/remove.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
// File for 'gemini mcp remove' command
|
||||
import type { CommandModule } from 'yargs';
|
||||
import { loadSettings, SettingScope } from '../../config/settings.js';
|
||||
|
||||
async function removeMcpServer(
|
||||
name: string,
|
||||
options: {
|
||||
scope: string;
|
||||
},
|
||||
) {
|
||||
const { scope } = options;
|
||||
const settingsScope =
|
||||
scope === 'user' ? SettingScope.User : SettingScope.Workspace;
|
||||
const settings = loadSettings(process.cwd());
|
||||
|
||||
const existingSettings = settings.forScope(settingsScope).settings;
|
||||
const mcpServers = existingSettings.mcpServers || {};
|
||||
|
||||
if (!mcpServers[name]) {
|
||||
console.log(`Server "${name}" not found in ${scope} settings.`);
|
||||
return;
|
||||
}
|
||||
|
||||
delete mcpServers[name];
|
||||
|
||||
settings.setValue(settingsScope, 'mcpServers', mcpServers);
|
||||
|
||||
console.log(`Server "${name}" removed from ${scope} settings.`);
|
||||
}
|
||||
|
||||
export const removeCommand: CommandModule = {
|
||||
command: 'remove <name>',
|
||||
describe: 'Remove a server',
|
||||
builder: (yargs) =>
|
||||
yargs
|
||||
.usage('Usage: gemini mcp remove [options] <name>')
|
||||
.positional('name', {
|
||||
describe: 'Name of the server',
|
||||
type: 'string',
|
||||
demandOption: true,
|
||||
})
|
||||
.option('scope', {
|
||||
alias: 's',
|
||||
describe: 'Configuration scope (user or project)',
|
||||
type: 'string',
|
||||
default: 'project',
|
||||
choices: ['user', 'project'],
|
||||
}),
|
||||
handler: async (argv) => {
|
||||
await removeMcpServer(argv.name as string, {
|
||||
scope: argv.scope as string,
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -8,6 +8,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import * as os from 'os';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { ShellTool, EditTool, WriteFileTool } from '@qwen-code/qwen-code-core';
|
||||
import { loadCliConfig, parseArguments } from './config.js';
|
||||
import { Settings } from './settings.js';
|
||||
import { Extension } from './extension.js';
|
||||
@@ -635,6 +636,17 @@ describe('loadCliConfig systemPromptMappings', () => {
|
||||
});
|
||||
|
||||
describe('mergeExcludeTools', () => {
|
||||
const defaultExcludes = [ShellTool.Name, EditTool.Name, WriteFileTool.Name];
|
||||
const originalIsTTY = process.stdin.isTTY;
|
||||
|
||||
beforeEach(() => {
|
||||
process.stdin.isTTY = true;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.stdin.isTTY = originalIsTTY;
|
||||
});
|
||||
|
||||
it('should merge excludeTools from settings and extensions', async () => {
|
||||
const settings: Settings = { excludeTools: ['tool1', 'tool2'] };
|
||||
const extensions: Extension[] = [
|
||||
@@ -729,7 +741,8 @@ describe('mergeExcludeTools', () => {
|
||||
expect(config.getExcludeTools()).toHaveLength(4);
|
||||
});
|
||||
|
||||
it('should return an empty array when no excludeTools are specified', async () => {
|
||||
it('should return an empty array when no excludeTools are specified and it is interactive', async () => {
|
||||
process.stdin.isTTY = true;
|
||||
const settings: Settings = {};
|
||||
const extensions: Extension[] = [];
|
||||
process.argv = ['node', 'script.js'];
|
||||
@@ -743,6 +756,21 @@ describe('mergeExcludeTools', () => {
|
||||
expect(config.getExcludeTools()).toEqual([]);
|
||||
});
|
||||
|
||||
it('should return default excludes when no excludeTools are specified and it is not interactive', async () => {
|
||||
process.stdin.isTTY = false;
|
||||
const settings: Settings = {};
|
||||
const extensions: Extension[] = [];
|
||||
process.argv = ['node', 'script.js', '-p', 'test'];
|
||||
const argv = await parseArguments();
|
||||
const config = await loadCliConfig(
|
||||
settings,
|
||||
extensions,
|
||||
'test-session',
|
||||
argv,
|
||||
);
|
||||
expect(config.getExcludeTools()).toEqual(defaultExcludes);
|
||||
});
|
||||
|
||||
it('should handle settings with excludeTools but no extensions', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const argv = await parseArguments();
|
||||
@@ -1065,7 +1093,7 @@ describe('loadCliConfig ideModeFeature', () => {
|
||||
vi.mocked(os.homedir).mockReturnValue('/mock/home/user');
|
||||
process.env.GEMINI_API_KEY = 'test-api-key';
|
||||
delete process.env.SANDBOX;
|
||||
delete process.env.GEMINI_CLI_IDE_SERVER_PORT;
|
||||
delete process.env.QWEN_CODE_IDE_SERVER_PORT;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -1083,6 +1111,91 @@ describe('loadCliConfig ideModeFeature', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadCliConfig folderTrustFeature', () => {
|
||||
const originalArgv = process.argv;
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(os.homedir).mockReturnValue('/mock/home/user');
|
||||
process.env.GEMINI_API_KEY = 'test-api-key';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.argv = originalArgv;
|
||||
process.env = originalEnv;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should be false by default', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const settings: Settings = {};
|
||||
const argv = await parseArguments();
|
||||
const config = await loadCliConfig(settings, [], 'test-session', argv);
|
||||
expect(config.getFolderTrustFeature()).toBe(false);
|
||||
});
|
||||
|
||||
it('should be true when settings.folderTrustFeature is true', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const argv = await parseArguments();
|
||||
const settings: Settings = { folderTrustFeature: true };
|
||||
const config = await loadCliConfig(settings, [], 'test-session', argv);
|
||||
expect(config.getFolderTrustFeature()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadCliConfig folderTrust', () => {
|
||||
const originalArgv = process.argv;
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(os.homedir).mockReturnValue('/mock/home/user');
|
||||
process.env.GEMINI_API_KEY = 'test-api-key';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.argv = originalArgv;
|
||||
process.env = originalEnv;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should be false if folderTrustFeature is false and folderTrust is false', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const settings: Settings = {
|
||||
folderTrustFeature: false,
|
||||
folderTrust: false,
|
||||
};
|
||||
const argv = await parseArguments();
|
||||
const config = await loadCliConfig(settings, [], 'test-session', argv);
|
||||
expect(config.getFolderTrust()).toBe(false);
|
||||
});
|
||||
|
||||
it('should be false if folderTrustFeature is true and folderTrust is false', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const argv = await parseArguments();
|
||||
const settings: Settings = { folderTrustFeature: true, folderTrust: false };
|
||||
const config = await loadCliConfig(settings, [], 'test-session', argv);
|
||||
expect(config.getFolderTrust()).toBe(false);
|
||||
});
|
||||
|
||||
it('should be false if folderTrustFeature is false and folderTrust is true', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const argv = await parseArguments();
|
||||
const settings: Settings = { folderTrustFeature: false, folderTrust: true };
|
||||
const config = await loadCliConfig(settings, [], 'test-session', argv);
|
||||
expect(config.getFolderTrust()).toBe(false);
|
||||
});
|
||||
|
||||
it('should be true when folderTrustFeature is true and folderTrust is true', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const argv = await parseArguments();
|
||||
const settings: Settings = { folderTrustFeature: true, folderTrust: true };
|
||||
const config = await loadCliConfig(settings, [], 'test-session', argv);
|
||||
expect(config.getFolderTrust()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
vi.mock('fs', async () => {
|
||||
const actualFs = await vi.importActual<typeof fs>('fs');
|
||||
const MOCK_CWD1 = process.cwd();
|
||||
@@ -1164,3 +1277,154 @@ describe('loadCliConfig with includeDirectories', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadCliConfig chatCompression', () => {
|
||||
const originalArgv = process.argv;
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(os.homedir).mockReturnValue('/mock/home/user');
|
||||
process.env.GEMINI_API_KEY = 'test-api-key';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.argv = originalArgv;
|
||||
process.env = originalEnv;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should pass chatCompression settings to the core config', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const argv = await parseArguments();
|
||||
const settings: Settings = {
|
||||
chatCompression: {
|
||||
contextPercentageThreshold: 0.5,
|
||||
},
|
||||
};
|
||||
const config = await loadCliConfig(settings, [], 'test-session', argv);
|
||||
expect(config.getChatCompression()).toEqual({
|
||||
contextPercentageThreshold: 0.5,
|
||||
});
|
||||
});
|
||||
|
||||
it('should have undefined chatCompression if not in settings', async () => {
|
||||
process.argv = ['node', 'script.js'];
|
||||
const argv = await parseArguments();
|
||||
const settings: Settings = {};
|
||||
const config = await loadCliConfig(settings, [], 'test-session', argv);
|
||||
expect(config.getChatCompression()).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadCliConfig tool exclusions', () => {
|
||||
const originalArgv = process.argv;
|
||||
const originalEnv = { ...process.env };
|
||||
const originalIsTTY = process.stdin.isTTY;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(os.homedir).mockReturnValue('/mock/home/user');
|
||||
process.env.GEMINI_API_KEY = 'test-api-key';
|
||||
process.stdin.isTTY = true;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.argv = originalArgv;
|
||||
process.env = originalEnv;
|
||||
process.stdin.isTTY = originalIsTTY;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should not exclude interactive tools in interactive mode without YOLO', async () => {
|
||||
process.stdin.isTTY = true;
|
||||
process.argv = ['node', 'script.js'];
|
||||
const argv = await parseArguments();
|
||||
const config = await loadCliConfig({}, [], 'test-session', argv);
|
||||
expect(config.getExcludeTools()).not.toContain('run_shell_command');
|
||||
expect(config.getExcludeTools()).not.toContain('replace');
|
||||
expect(config.getExcludeTools()).not.toContain('write_file');
|
||||
});
|
||||
|
||||
it('should not exclude interactive tools in interactive mode with YOLO', async () => {
|
||||
process.stdin.isTTY = true;
|
||||
process.argv = ['node', 'script.js', '--yolo'];
|
||||
const argv = await parseArguments();
|
||||
const config = await loadCliConfig({}, [], 'test-session', argv);
|
||||
expect(config.getExcludeTools()).not.toContain('run_shell_command');
|
||||
expect(config.getExcludeTools()).not.toContain('replace');
|
||||
expect(config.getExcludeTools()).not.toContain('write_file');
|
||||
});
|
||||
|
||||
it('should exclude interactive tools in non-interactive mode without YOLO', async () => {
|
||||
process.stdin.isTTY = false;
|
||||
process.argv = ['node', 'script.js', '-p', 'test'];
|
||||
const argv = await parseArguments();
|
||||
const config = await loadCliConfig({}, [], 'test-session', argv);
|
||||
expect(config.getExcludeTools()).toContain('run_shell_command');
|
||||
expect(config.getExcludeTools()).toContain('replace');
|
||||
expect(config.getExcludeTools()).toContain('write_file');
|
||||
});
|
||||
|
||||
it('should not exclude interactive tools in non-interactive mode with YOLO', async () => {
|
||||
process.stdin.isTTY = false;
|
||||
process.argv = ['node', 'script.js', '-p', 'test', '--yolo'];
|
||||
const argv = await parseArguments();
|
||||
const config = await loadCliConfig({}, [], 'test-session', argv);
|
||||
expect(config.getExcludeTools()).not.toContain('run_shell_command');
|
||||
expect(config.getExcludeTools()).not.toContain('replace');
|
||||
expect(config.getExcludeTools()).not.toContain('write_file');
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadCliConfig interactive', () => {
|
||||
const originalArgv = process.argv;
|
||||
const originalEnv = { ...process.env };
|
||||
const originalIsTTY = process.stdin.isTTY;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(os.homedir).mockReturnValue('/mock/home/user');
|
||||
process.env.GEMINI_API_KEY = 'test-api-key';
|
||||
process.stdin.isTTY = true;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.argv = originalArgv;
|
||||
process.env = originalEnv;
|
||||
process.stdin.isTTY = originalIsTTY;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should be interactive if isTTY and no prompt', async () => {
|
||||
process.stdin.isTTY = true;
|
||||
process.argv = ['node', 'script.js'];
|
||||
const argv = await parseArguments();
|
||||
const config = await loadCliConfig({}, [], 'test-session', argv);
|
||||
expect(config.isInteractive()).toBe(true);
|
||||
});
|
||||
|
||||
it('should be interactive if prompt-interactive is set', async () => {
|
||||
process.stdin.isTTY = false;
|
||||
process.argv = ['node', 'script.js', '--prompt-interactive', 'test'];
|
||||
const argv = await parseArguments();
|
||||
const config = await loadCliConfig({}, [], 'test-session', argv);
|
||||
expect(config.isInteractive()).toBe(true);
|
||||
});
|
||||
|
||||
it('should not be interactive if not isTTY and no prompt', async () => {
|
||||
process.stdin.isTTY = false;
|
||||
process.argv = ['node', 'script.js'];
|
||||
const argv = await parseArguments();
|
||||
const config = await loadCliConfig({}, [], 'test-session', argv);
|
||||
expect(config.isInteractive()).toBe(false);
|
||||
});
|
||||
|
||||
it('should not be interactive if prompt is set', async () => {
|
||||
process.stdin.isTTY = true;
|
||||
process.argv = ['node', 'script.js', '--prompt', 'test'];
|
||||
const argv = await parseArguments();
|
||||
const config = await loadCliConfig({}, [], 'test-session', argv);
|
||||
expect(config.isInteractive()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import { homedir } from 'node:os';
|
||||
import yargs from 'yargs/yargs';
|
||||
import { hideBin } from 'yargs/helpers';
|
||||
import process from 'node:process';
|
||||
import { mcpCommand } from '../commands/mcp.js';
|
||||
import {
|
||||
Config,
|
||||
loadServerHierarchicalMemory,
|
||||
@@ -22,6 +23,11 @@ import {
|
||||
FileDiscoveryService,
|
||||
TelemetryTarget,
|
||||
FileFilteringOptions,
|
||||
ShellTool,
|
||||
EditTool,
|
||||
WriteFileTool,
|
||||
MCPServerConfig,
|
||||
ConfigParameters,
|
||||
} from '@qwen-code/qwen-code-core';
|
||||
import { Settings } from './settings.js';
|
||||
|
||||
@@ -68,7 +74,6 @@ export interface CliArgs {
|
||||
openaiBaseUrl: string | undefined;
|
||||
proxy: string | undefined;
|
||||
includeDirectories: string[] | undefined;
|
||||
loadMemoryFromIncludeDirectories: boolean | undefined;
|
||||
tavilyApiKey: string | undefined;
|
||||
}
|
||||
|
||||
@@ -76,190 +81,196 @@ export async function parseArguments(): Promise<CliArgs> {
|
||||
const yargsInstance = yargs(hideBin(process.argv))
|
||||
.scriptName('qwen')
|
||||
.usage(
|
||||
'$0 [options]',
|
||||
'Qwen Code - Launch an interactive CLI, use -p/--prompt for non-interactive mode',
|
||||
'Usage: qwen [options] [command]\n\nQwen Code - Launch an interactive CLI, use -p/--prompt for non-interactive mode',
|
||||
)
|
||||
.option('model', {
|
||||
alias: 'm',
|
||||
type: 'string',
|
||||
description: `Model`,
|
||||
default: process.env.GEMINI_MODEL,
|
||||
})
|
||||
.option('prompt', {
|
||||
alias: 'p',
|
||||
type: 'string',
|
||||
description: 'Prompt. Appended to input on stdin (if any).',
|
||||
})
|
||||
.option('prompt-interactive', {
|
||||
alias: 'i',
|
||||
type: 'string',
|
||||
description:
|
||||
'Execute the provided prompt and continue in interactive mode',
|
||||
})
|
||||
.option('sandbox', {
|
||||
alias: 's',
|
||||
type: 'boolean',
|
||||
description: 'Run in sandbox?',
|
||||
})
|
||||
.option('sandbox-image', {
|
||||
type: 'string',
|
||||
description: 'Sandbox image URI.',
|
||||
})
|
||||
.option('debug', {
|
||||
alias: 'd',
|
||||
type: 'boolean',
|
||||
description: 'Run in debug mode?',
|
||||
default: false,
|
||||
})
|
||||
.option('all-files', {
|
||||
alias: ['a'],
|
||||
type: 'boolean',
|
||||
description: 'Include ALL files in context?',
|
||||
default: false,
|
||||
})
|
||||
.option('all_files', {
|
||||
type: 'boolean',
|
||||
description: 'Include ALL files in context?',
|
||||
default: false,
|
||||
})
|
||||
.deprecateOption(
|
||||
'all_files',
|
||||
'Use --all-files instead. We will be removing --all_files in the coming weeks.',
|
||||
.command('$0', 'Launch Qwen Code', (yargsInstance) =>
|
||||
yargsInstance
|
||||
.option('model', {
|
||||
alias: 'm',
|
||||
type: 'string',
|
||||
description: `Model`,
|
||||
default: process.env.GEMINI_MODEL,
|
||||
})
|
||||
.option('prompt', {
|
||||
alias: 'p',
|
||||
type: 'string',
|
||||
description: 'Prompt. Appended to input on stdin (if any).',
|
||||
})
|
||||
.option('prompt-interactive', {
|
||||
alias: 'i',
|
||||
type: 'string',
|
||||
description:
|
||||
'Execute the provided prompt and continue in interactive mode',
|
||||
})
|
||||
.option('sandbox', {
|
||||
alias: 's',
|
||||
type: 'boolean',
|
||||
description: 'Run in sandbox?',
|
||||
})
|
||||
.option('sandbox-image', {
|
||||
type: 'string',
|
||||
description: 'Sandbox image URI.',
|
||||
})
|
||||
.option('debug', {
|
||||
alias: 'd',
|
||||
type: 'boolean',
|
||||
description: 'Run in debug mode?',
|
||||
default: false,
|
||||
})
|
||||
.option('all-files', {
|
||||
alias: ['a'],
|
||||
type: 'boolean',
|
||||
description: 'Include ALL files in context?',
|
||||
default: false,
|
||||
})
|
||||
.option('all_files', {
|
||||
type: 'boolean',
|
||||
description: 'Include ALL files in context?',
|
||||
default: false,
|
||||
})
|
||||
.deprecateOption(
|
||||
'all_files',
|
||||
'Use --all-files instead. We will be removing --all_files in the coming weeks.',
|
||||
)
|
||||
.option('show-memory-usage', {
|
||||
type: 'boolean',
|
||||
description: 'Show memory usage in status bar',
|
||||
default: false,
|
||||
})
|
||||
.option('show_memory_usage', {
|
||||
type: 'boolean',
|
||||
description: 'Show memory usage in status bar',
|
||||
default: false,
|
||||
})
|
||||
.deprecateOption(
|
||||
'show_memory_usage',
|
||||
'Use --show-memory-usage instead. We will be removing --show_memory_usage in the coming weeks.',
|
||||
)
|
||||
.option('yolo', {
|
||||
alias: 'y',
|
||||
type: 'boolean',
|
||||
description:
|
||||
'Automatically accept all actions (aka YOLO mode, see https://www.youtube.com/watch?v=xvFZjo5PgG0 for more details)?',
|
||||
default: false,
|
||||
})
|
||||
.option('telemetry', {
|
||||
type: 'boolean',
|
||||
description:
|
||||
'Enable telemetry? This flag specifically controls if telemetry is sent. Other --telemetry-* flags set specific values but do not enable telemetry on their own.',
|
||||
})
|
||||
.option('telemetry-target', {
|
||||
type: 'string',
|
||||
choices: ['local', 'gcp'],
|
||||
description:
|
||||
'Set the telemetry target (local or gcp). Overrides settings files.',
|
||||
})
|
||||
.option('telemetry-otlp-endpoint', {
|
||||
type: 'string',
|
||||
description:
|
||||
'Set the OTLP endpoint for telemetry. Overrides environment variables and settings files.',
|
||||
})
|
||||
.option('telemetry-log-prompts', {
|
||||
type: 'boolean',
|
||||
description:
|
||||
'Enable or disable logging of user prompts for telemetry. Overrides settings files.',
|
||||
})
|
||||
.option('telemetry-outfile', {
|
||||
type: 'string',
|
||||
description: 'Redirect all telemetry output to the specified file.',
|
||||
})
|
||||
.option('checkpointing', {
|
||||
alias: 'c',
|
||||
type: 'boolean',
|
||||
description: 'Enables checkpointing of file edits',
|
||||
default: false,
|
||||
})
|
||||
.option('experimental-acp', {
|
||||
type: 'boolean',
|
||||
description: 'Starts the agent in ACP mode',
|
||||
})
|
||||
.option('allowed-mcp-server-names', {
|
||||
type: 'array',
|
||||
string: true,
|
||||
description: 'Allowed MCP server names',
|
||||
})
|
||||
.option('extensions', {
|
||||
alias: 'e',
|
||||
type: 'array',
|
||||
string: true,
|
||||
description:
|
||||
'A list of extensions to use. If not provided, all extensions are used.',
|
||||
})
|
||||
.option('list-extensions', {
|
||||
alias: 'l',
|
||||
type: 'boolean',
|
||||
description: 'List all available extensions and exit.',
|
||||
})
|
||||
.option('ide-mode-feature', {
|
||||
type: 'boolean',
|
||||
description: 'Run in IDE mode?',
|
||||
})
|
||||
.option('proxy', {
|
||||
type: 'string',
|
||||
description:
|
||||
'Proxy for gemini client, like schema://user:password@host:port',
|
||||
})
|
||||
.option('include-directories', {
|
||||
type: 'array',
|
||||
string: true,
|
||||
description:
|
||||
'Additional directories to include in the workspace (comma-separated or multiple --include-directories)',
|
||||
coerce: (dirs: string[]) =>
|
||||
// Handle comma-separated values
|
||||
dirs.flatMap((dir) => dir.split(',').map((d) => d.trim())),
|
||||
})
|
||||
.option('openai-logging', {
|
||||
type: 'boolean',
|
||||
description:
|
||||
'Enable logging of OpenAI API calls for debugging and analysis',
|
||||
})
|
||||
.option('openai-api-key', {
|
||||
type: 'string',
|
||||
description: 'OpenAI API key to use for authentication',
|
||||
})
|
||||
.option('openai-base-url', {
|
||||
type: 'string',
|
||||
description: 'OpenAI base URL (for custom endpoints)',
|
||||
})
|
||||
.option('tavily-api-key', {
|
||||
type: 'string',
|
||||
description: 'Tavily API key for web search functionality',
|
||||
})
|
||||
.check((argv) => {
|
||||
if (argv.prompt && argv.promptInteractive) {
|
||||
throw new Error(
|
||||
'Cannot use both --prompt (-p) and --prompt-interactive (-i) together',
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}),
|
||||
)
|
||||
.option('show-memory-usage', {
|
||||
type: 'boolean',
|
||||
description: 'Show memory usage in status bar',
|
||||
default: false,
|
||||
})
|
||||
.option('show_memory_usage', {
|
||||
type: 'boolean',
|
||||
description: 'Show memory usage in status bar',
|
||||
default: false,
|
||||
})
|
||||
.deprecateOption(
|
||||
'show_memory_usage',
|
||||
'Use --show-memory-usage instead. We will be removing --show_memory_usage in the coming weeks.',
|
||||
)
|
||||
.option('yolo', {
|
||||
alias: 'y',
|
||||
type: 'boolean',
|
||||
description:
|
||||
'Automatically accept all actions (aka YOLO mode, see https://www.youtube.com/watch?v=xvFZjo5PgG0 for more details)?',
|
||||
default: false,
|
||||
})
|
||||
.option('telemetry', {
|
||||
type: 'boolean',
|
||||
description:
|
||||
'Enable telemetry? This flag specifically controls if telemetry is sent. Other --telemetry-* flags set specific values but do not enable telemetry on their own.',
|
||||
})
|
||||
.option('telemetry-target', {
|
||||
type: 'string',
|
||||
choices: ['local', 'gcp'],
|
||||
description:
|
||||
'Set the telemetry target (local or gcp). Overrides settings files.',
|
||||
})
|
||||
.option('telemetry-otlp-endpoint', {
|
||||
type: 'string',
|
||||
description:
|
||||
'Set the OTLP endpoint for telemetry. Overrides environment variables and settings files.',
|
||||
})
|
||||
.option('telemetry-log-prompts', {
|
||||
type: 'boolean',
|
||||
description:
|
||||
'Enable or disable logging of user prompts for telemetry. Overrides settings files.',
|
||||
})
|
||||
.option('telemetry-outfile', {
|
||||
type: 'string',
|
||||
description: 'Redirect all telemetry output to the specified file.',
|
||||
})
|
||||
.option('checkpointing', {
|
||||
alias: 'c',
|
||||
type: 'boolean',
|
||||
description: 'Enables checkpointing of file edits',
|
||||
default: false,
|
||||
})
|
||||
.option('experimental-acp', {
|
||||
type: 'boolean',
|
||||
description: 'Starts the agent in ACP mode',
|
||||
})
|
||||
.option('allowed-mcp-server-names', {
|
||||
type: 'array',
|
||||
string: true,
|
||||
description: 'Allowed MCP server names',
|
||||
})
|
||||
.option('extensions', {
|
||||
alias: 'e',
|
||||
type: 'array',
|
||||
string: true,
|
||||
description:
|
||||
'A list of extensions to use. If not provided, all extensions are used.',
|
||||
})
|
||||
.option('list-extensions', {
|
||||
alias: 'l',
|
||||
type: 'boolean',
|
||||
description: 'List all available extensions and exit.',
|
||||
})
|
||||
.option('ide-mode-feature', {
|
||||
type: 'boolean',
|
||||
description: 'Run in IDE mode?',
|
||||
})
|
||||
.option('openai-logging', {
|
||||
type: 'boolean',
|
||||
description:
|
||||
'Enable logging of OpenAI API calls for debugging and analysis',
|
||||
})
|
||||
.option('openai-api-key', {
|
||||
type: 'string',
|
||||
description: 'OpenAI API key to use for authentication',
|
||||
})
|
||||
.option('openai-base-url', {
|
||||
type: 'string',
|
||||
description: 'OpenAI base URL (for custom endpoints)',
|
||||
})
|
||||
.option('tavily-api-key', {
|
||||
type: 'string',
|
||||
description: 'Tavily API key for web search functionality',
|
||||
})
|
||||
.option('proxy', {
|
||||
type: 'string',
|
||||
description:
|
||||
'Proxy for gemini client, like schema://user:password@host:port',
|
||||
})
|
||||
.option('include-directories', {
|
||||
type: 'array',
|
||||
string: true,
|
||||
description:
|
||||
'Additional directories to include in the workspace (comma-separated or multiple --include-directories)',
|
||||
coerce: (dirs: string[]) =>
|
||||
// Handle comma-separated values
|
||||
dirs.flatMap((dir) => dir.split(',').map((d) => d.trim())),
|
||||
})
|
||||
.option('load-memory-from-include-directories', {
|
||||
type: 'boolean',
|
||||
description:
|
||||
'If true, when refreshing memory, QWEN.md files should be loaded from all directories that are added. If false, QWEN.md files should only be loaded from the primary working directory.',
|
||||
default: false,
|
||||
})
|
||||
// Register MCP subcommands
|
||||
.command(mcpCommand)
|
||||
.version(await getCliVersion()) // This will enable the --version flag based on package.json
|
||||
.alias('v', 'version')
|
||||
.help()
|
||||
.alias('h', 'help')
|
||||
.strict()
|
||||
.check((argv) => {
|
||||
if (argv.prompt && argv.promptInteractive) {
|
||||
throw new Error(
|
||||
'Cannot use both --prompt (-p) and --prompt-interactive (-i) together',
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
.demandCommand(0, 0); // Allow base command to run with no subcommands
|
||||
|
||||
yargsInstance.wrap(yargsInstance.terminalWidth());
|
||||
const result = yargsInstance.parseSync();
|
||||
const result = await yargsInstance.parse();
|
||||
|
||||
// Handle case where MCP subcommands are executed - they should exit the process
|
||||
// and not return to main CLI logic
|
||||
if (result._.length > 0 && result._[0] === 'mcp') {
|
||||
// MCP commands handle their own execution and process exit
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// The import format is now only controlled by settings.memoryImportFormat
|
||||
// We no longer accept it as a CLI argument
|
||||
return result as CliArgs;
|
||||
return result as unknown as CliArgs;
|
||||
}
|
||||
|
||||
// This function is now a thin wrapper around the server's implementation.
|
||||
@@ -321,6 +332,10 @@ export async function loadCliConfig(
|
||||
const ideModeFeature =
|
||||
argv.ideModeFeature ?? settings.ideModeFeature ?? false;
|
||||
|
||||
const folderTrustFeature = settings.folderTrustFeature ?? false;
|
||||
const folderTrustSetting = settings.folderTrust ?? false;
|
||||
const folderTrust = folderTrustFeature && folderTrustSetting;
|
||||
|
||||
const allExtensions = annotateActiveExtensions(
|
||||
extensions,
|
||||
argv.extensions || [],
|
||||
@@ -383,17 +398,31 @@ export async function loadCliConfig(
|
||||
);
|
||||
|
||||
let mcpServers = mergeMcpServers(settings, activeExtensions);
|
||||
const excludeTools = mergeExcludeTools(settings, activeExtensions);
|
||||
const question = argv.promptInteractive || argv.prompt || '';
|
||||
const approvalMode =
|
||||
argv.yolo || false ? ApprovalMode.YOLO : ApprovalMode.DEFAULT;
|
||||
const interactive =
|
||||
!!argv.promptInteractive || (process.stdin.isTTY && question.length === 0);
|
||||
// In non-interactive and non-yolo mode, exclude interactive built in tools.
|
||||
const extraExcludes =
|
||||
!interactive && approvalMode !== ApprovalMode.YOLO
|
||||
? [ShellTool.Name, EditTool.Name, WriteFileTool.Name]
|
||||
: undefined;
|
||||
|
||||
const excludeTools = mergeExcludeTools(
|
||||
settings,
|
||||
activeExtensions,
|
||||
extraExcludes,
|
||||
);
|
||||
const blockedMcpServers: Array<{ name: string; extensionName: string }> = [];
|
||||
|
||||
if (!argv.allowedMcpServerNames) {
|
||||
if (settings.allowMCPServers) {
|
||||
const allowedNames = new Set(settings.allowMCPServers.filter(Boolean));
|
||||
if (allowedNames.size > 0) {
|
||||
mcpServers = Object.fromEntries(
|
||||
Object.entries(mcpServers).filter(([key]) => allowedNames.has(key)),
|
||||
);
|
||||
}
|
||||
mcpServers = allowedMcpServers(
|
||||
mcpServers,
|
||||
settings.allowMCPServers,
|
||||
blockedMcpServers,
|
||||
);
|
||||
}
|
||||
|
||||
if (settings.excludeMCPServers) {
|
||||
@@ -407,29 +436,11 @@ export async function loadCliConfig(
|
||||
}
|
||||
|
||||
if (argv.allowedMcpServerNames) {
|
||||
const allowedNames = new Set(argv.allowedMcpServerNames.filter(Boolean));
|
||||
if (allowedNames.size > 0) {
|
||||
mcpServers = Object.fromEntries(
|
||||
Object.entries(mcpServers).filter(([key, server]) => {
|
||||
const isAllowed = allowedNames.has(key);
|
||||
if (!isAllowed) {
|
||||
blockedMcpServers.push({
|
||||
name: key,
|
||||
extensionName: server.extensionName || '',
|
||||
});
|
||||
}
|
||||
return isAllowed;
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
blockedMcpServers.push(
|
||||
...Object.entries(mcpServers).map(([key, server]) => ({
|
||||
name: key,
|
||||
extensionName: server.extensionName || '',
|
||||
})),
|
||||
);
|
||||
mcpServers = {};
|
||||
}
|
||||
mcpServers = allowedMcpServers(
|
||||
mcpServers,
|
||||
argv.allowedMcpServerNames,
|
||||
blockedMcpServers,
|
||||
);
|
||||
}
|
||||
|
||||
const sandboxConfig = await loadSandboxConfig(settings, argv);
|
||||
@@ -442,11 +453,9 @@ export async function loadCliConfig(
|
||||
targetDir: process.cwd(),
|
||||
includeDirectories,
|
||||
loadMemoryFromIncludeDirectories:
|
||||
argv.loadMemoryFromIncludeDirectories ||
|
||||
settings.loadMemoryFromIncludeDirectories ||
|
||||
false,
|
||||
settings.loadMemoryFromIncludeDirectories || false,
|
||||
debugMode,
|
||||
question: argv.promptInteractive || argv.prompt || '',
|
||||
question,
|
||||
fullContext: argv.allFiles || argv.all_files || false,
|
||||
coreTools: settings.coreTools || undefined,
|
||||
excludeTools,
|
||||
@@ -456,7 +465,7 @@ export async function loadCliConfig(
|
||||
mcpServers,
|
||||
userMemory: memoryContent,
|
||||
geminiMdFileCount: fileCount,
|
||||
approvalMode: argv.yolo || false ? ApprovalMode.YOLO : ApprovalMode.DEFAULT,
|
||||
approvalMode,
|
||||
showMemoryUsage:
|
||||
argv.showMemoryUsage ||
|
||||
argv.show_memory_usage ||
|
||||
@@ -496,7 +505,6 @@ export async function loadCliConfig(
|
||||
extensionContextFilePaths,
|
||||
maxSessionTurns: settings.maxSessionTurns ?? -1,
|
||||
sessionTokenLimit: settings.sessionTokenLimit ?? -1,
|
||||
maxFolderItems: settings.maxFolderItems ?? 20,
|
||||
experimentalAcp: argv.experimentalAcp || false,
|
||||
listExtensions: argv.listExtensions || false,
|
||||
extensions: allExtensions,
|
||||
@@ -510,7 +518,7 @@ export async function loadCliConfig(
|
||||
? settings.enableOpenAILogging
|
||||
: argv.openaiLogging) ?? false,
|
||||
sampling_params: settings.sampling_params,
|
||||
systemPromptMappings: settings.systemPromptMappings ?? [
|
||||
systemPromptMappings: (settings.systemPromptMappings ?? [
|
||||
{
|
||||
baseUrls: [
|
||||
'https://dashscope.aliyuncs.com/compatible-mode/v1/',
|
||||
@@ -520,14 +528,49 @@ export async function loadCliConfig(
|
||||
template:
|
||||
'SYSTEM_TEMPLATE:{"name":"qwen3_coder","params":{"is_git_repository":{RUNTIME_VARS_IS_GIT_REPO},"sandbox":"{RUNTIME_VARS_SANDBOX}"}}',
|
||||
},
|
||||
],
|
||||
]) as ConfigParameters['systemPromptMappings'],
|
||||
contentGenerator: settings.contentGenerator,
|
||||
cliVersion,
|
||||
tavilyApiKey:
|
||||
argv.tavilyApiKey || settings.tavilyApiKey || process.env.TAVILY_API_KEY,
|
||||
chatCompression: settings.chatCompression,
|
||||
folderTrustFeature,
|
||||
folderTrust,
|
||||
interactive,
|
||||
});
|
||||
}
|
||||
|
||||
function allowedMcpServers(
|
||||
mcpServers: { [x: string]: MCPServerConfig },
|
||||
allowMCPServers: string[],
|
||||
blockedMcpServers: Array<{ name: string; extensionName: string }>,
|
||||
) {
|
||||
const allowedNames = new Set(allowMCPServers.filter(Boolean));
|
||||
if (allowedNames.size > 0) {
|
||||
mcpServers = Object.fromEntries(
|
||||
Object.entries(mcpServers).filter(([key, server]) => {
|
||||
const isAllowed = allowedNames.has(key);
|
||||
if (!isAllowed) {
|
||||
blockedMcpServers.push({
|
||||
name: key,
|
||||
extensionName: server.extensionName || '',
|
||||
});
|
||||
}
|
||||
return isAllowed;
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
blockedMcpServers.push(
|
||||
...Object.entries(mcpServers).map(([key, server]) => ({
|
||||
name: key,
|
||||
extensionName: server.extensionName || '',
|
||||
})),
|
||||
);
|
||||
mcpServers = {};
|
||||
}
|
||||
return mcpServers;
|
||||
}
|
||||
|
||||
function mergeMcpServers(settings: Settings, extensions: Extension[]) {
|
||||
const mcpServers = { ...(settings.mcpServers || {}) };
|
||||
for (const extension of extensions) {
|
||||
@@ -552,8 +595,12 @@ function mergeMcpServers(settings: Settings, extensions: Extension[]) {
|
||||
function mergeExcludeTools(
|
||||
settings: Settings,
|
||||
extensions: Extension[],
|
||||
extraExcludes?: string[] | undefined,
|
||||
): string[] {
|
||||
const allExcludeTools = new Set(settings.excludeTools || []);
|
||||
const allExcludeTools = new Set([
|
||||
...(settings.excludeTools || []),
|
||||
...(extraExcludes || []),
|
||||
]);
|
||||
for (const extension of extensions) {
|
||||
for (const tool of extension.config.excludeTools || []) {
|
||||
allExcludeTools.add(tool);
|
||||
|
||||
@@ -10,7 +10,8 @@ import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
|
||||
export const EXTENSIONS_DIRECTORY_NAME = path.join('.qwen', 'extensions');
|
||||
export const EXTENSIONS_CONFIG_FILENAME = 'gemini-extension.json';
|
||||
export const EXTENSIONS_CONFIG_FILENAME = 'qwen-extension.json';
|
||||
export const EXTENSIONS_CONFIG_FILENAME_OLD = 'gemini-extension.json';
|
||||
|
||||
export interface Extension {
|
||||
path: string;
|
||||
@@ -68,12 +69,19 @@ function loadExtension(extensionDir: string): Extension | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
const configFilePath = path.join(extensionDir, EXTENSIONS_CONFIG_FILENAME);
|
||||
let configFilePath = path.join(extensionDir, EXTENSIONS_CONFIG_FILENAME);
|
||||
if (!fs.existsSync(configFilePath)) {
|
||||
console.error(
|
||||
`Warning: extension directory ${extensionDir} does not contain a config file ${configFilePath}.`,
|
||||
const oldConfigFilePath = path.join(
|
||||
extensionDir,
|
||||
EXTENSIONS_CONFIG_FILENAME_OLD,
|
||||
);
|
||||
return null;
|
||||
if (!fs.existsSync(oldConfigFilePath)) {
|
||||
console.error(
|
||||
`Warning: extension directory ${extensionDir} does not contain a config file ${configFilePath}.`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
configFilePath = oldConfigFilePath;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
62
packages/cli/src/config/keyBindings.test.ts
Normal file
62
packages/cli/src/config/keyBindings.test.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
Command,
|
||||
KeyBindingConfig,
|
||||
defaultKeyBindings,
|
||||
} from './keyBindings.js';
|
||||
|
||||
describe('keyBindings config', () => {
|
||||
describe('defaultKeyBindings', () => {
|
||||
it('should have bindings for all commands', () => {
|
||||
const commands = Object.values(Command);
|
||||
|
||||
for (const command of commands) {
|
||||
expect(defaultKeyBindings[command]).toBeDefined();
|
||||
expect(Array.isArray(defaultKeyBindings[command])).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('should have valid key binding structures', () => {
|
||||
for (const [_, bindings] of Object.entries(defaultKeyBindings)) {
|
||||
for (const binding of bindings) {
|
||||
// Each binding should have either key or sequence, but not both
|
||||
const hasKey = binding.key !== undefined;
|
||||
const hasSequence = binding.sequence !== undefined;
|
||||
|
||||
expect(hasKey || hasSequence).toBe(true);
|
||||
expect(hasKey && hasSequence).toBe(false);
|
||||
|
||||
// Modifier properties should be boolean or undefined
|
||||
if (binding.ctrl !== undefined) {
|
||||
expect(typeof binding.ctrl).toBe('boolean');
|
||||
}
|
||||
if (binding.shift !== undefined) {
|
||||
expect(typeof binding.shift).toBe('boolean');
|
||||
}
|
||||
if (binding.command !== undefined) {
|
||||
expect(typeof binding.command).toBe('boolean');
|
||||
}
|
||||
if (binding.paste !== undefined) {
|
||||
expect(typeof binding.paste).toBe('boolean');
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should export all required types', () => {
|
||||
// Basic type checks
|
||||
expect(typeof Command.HOME).toBe('string');
|
||||
expect(typeof Command.END).toBe('string');
|
||||
|
||||
// Config should be readonly
|
||||
const config: KeyBindingConfig = defaultKeyBindings;
|
||||
expect(config[Command.HOME]).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
179
packages/cli/src/config/keyBindings.ts
Normal file
179
packages/cli/src/config/keyBindings.ts
Normal file
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* Command enum for all available keyboard shortcuts
|
||||
*/
|
||||
export enum Command {
|
||||
// Basic bindings
|
||||
RETURN = 'return',
|
||||
ESCAPE = 'escape',
|
||||
|
||||
// Cursor movement
|
||||
HOME = 'home',
|
||||
END = 'end',
|
||||
|
||||
// Text deletion
|
||||
KILL_LINE_RIGHT = 'killLineRight',
|
||||
KILL_LINE_LEFT = 'killLineLeft',
|
||||
CLEAR_INPUT = 'clearInput',
|
||||
|
||||
// Screen control
|
||||
CLEAR_SCREEN = 'clearScreen',
|
||||
|
||||
// History navigation
|
||||
HISTORY_UP = 'historyUp',
|
||||
HISTORY_DOWN = 'historyDown',
|
||||
NAVIGATION_UP = 'navigationUp',
|
||||
NAVIGATION_DOWN = 'navigationDown',
|
||||
|
||||
// Auto-completion
|
||||
ACCEPT_SUGGESTION = 'acceptSuggestion',
|
||||
COMPLETION_UP = 'completionUp',
|
||||
COMPLETION_DOWN = 'completionDown',
|
||||
|
||||
// Text input
|
||||
SUBMIT = 'submit',
|
||||
NEWLINE = 'newline',
|
||||
|
||||
// External tools
|
||||
OPEN_EXTERNAL_EDITOR = 'openExternalEditor',
|
||||
PASTE_CLIPBOARD_IMAGE = 'pasteClipboardImage',
|
||||
|
||||
// App level bindings
|
||||
SHOW_ERROR_DETAILS = 'showErrorDetails',
|
||||
TOGGLE_TOOL_DESCRIPTIONS = 'toggleToolDescriptions',
|
||||
TOGGLE_IDE_CONTEXT_DETAIL = 'toggleIDEContextDetail',
|
||||
QUIT = 'quit',
|
||||
EXIT = 'exit',
|
||||
SHOW_MORE_LINES = 'showMoreLines',
|
||||
|
||||
// Shell commands
|
||||
REVERSE_SEARCH = 'reverseSearch',
|
||||
SUBMIT_REVERSE_SEARCH = 'submitReverseSearch',
|
||||
ACCEPT_SUGGESTION_REVERSE_SEARCH = 'acceptSuggestionReverseSearch',
|
||||
}
|
||||
|
||||
/**
|
||||
* Data-driven key binding structure for user configuration
|
||||
*/
|
||||
export interface KeyBinding {
|
||||
/** The key name (e.g., 'a', 'return', 'tab', 'escape') */
|
||||
key?: string;
|
||||
/** The key sequence (e.g., '\x18' for Ctrl+X) - alternative to key name */
|
||||
sequence?: string;
|
||||
/** Control key requirement: true=must be pressed, false=must not be pressed, undefined=ignore */
|
||||
ctrl?: boolean;
|
||||
/** Shift key requirement: true=must be pressed, false=must not be pressed, undefined=ignore */
|
||||
shift?: boolean;
|
||||
/** Command/meta key requirement: true=must be pressed, false=must not be pressed, undefined=ignore */
|
||||
command?: boolean;
|
||||
/** Paste operation requirement: true=must be paste, false=must not be paste, undefined=ignore */
|
||||
paste?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration type mapping commands to their key bindings
|
||||
*/
|
||||
export type KeyBindingConfig = {
|
||||
readonly [C in Command]: readonly KeyBinding[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Default key binding configuration
|
||||
* Matches the original hard-coded logic exactly
|
||||
*/
|
||||
export const defaultKeyBindings: KeyBindingConfig = {
|
||||
// Basic bindings
|
||||
[Command.RETURN]: [{ key: 'return' }],
|
||||
// Original: key.name === 'escape'
|
||||
[Command.ESCAPE]: [{ key: 'escape' }],
|
||||
|
||||
// Cursor movement
|
||||
// Original: key.ctrl && key.name === 'a'
|
||||
[Command.HOME]: [{ key: 'a', ctrl: true }],
|
||||
// Original: key.ctrl && key.name === 'e'
|
||||
[Command.END]: [{ key: 'e', ctrl: true }],
|
||||
|
||||
// Text deletion
|
||||
// Original: key.ctrl && key.name === 'k'
|
||||
[Command.KILL_LINE_RIGHT]: [{ key: 'k', ctrl: true }],
|
||||
// Original: key.ctrl && key.name === 'u'
|
||||
[Command.KILL_LINE_LEFT]: [{ key: 'u', ctrl: true }],
|
||||
// Original: key.ctrl && key.name === 'c'
|
||||
[Command.CLEAR_INPUT]: [{ key: 'c', ctrl: true }],
|
||||
|
||||
// Screen control
|
||||
// Original: key.ctrl && key.name === 'l'
|
||||
[Command.CLEAR_SCREEN]: [{ key: 'l', ctrl: true }],
|
||||
|
||||
// History navigation
|
||||
// Original: key.ctrl && key.name === 'p'
|
||||
[Command.HISTORY_UP]: [{ key: 'p', ctrl: true }],
|
||||
// Original: key.ctrl && key.name === 'n'
|
||||
[Command.HISTORY_DOWN]: [{ key: 'n', ctrl: true }],
|
||||
// Original: key.name === 'up'
|
||||
[Command.NAVIGATION_UP]: [{ key: 'up' }],
|
||||
// Original: key.name === 'down'
|
||||
[Command.NAVIGATION_DOWN]: [{ key: 'down' }],
|
||||
|
||||
// Auto-completion
|
||||
// Original: key.name === 'tab' || (key.name === 'return' && !key.ctrl)
|
||||
[Command.ACCEPT_SUGGESTION]: [{ key: 'tab' }, { key: 'return', ctrl: false }],
|
||||
// Completion navigation (arrow or Ctrl+P/N)
|
||||
[Command.COMPLETION_UP]: [{ key: 'up' }, { key: 'p', ctrl: true }],
|
||||
[Command.COMPLETION_DOWN]: [{ key: 'down' }, { key: 'n', ctrl: true }],
|
||||
|
||||
// Text input
|
||||
// Original: key.name === 'return' && !key.ctrl && !key.meta && !key.paste
|
||||
[Command.SUBMIT]: [
|
||||
{
|
||||
key: 'return',
|
||||
ctrl: false,
|
||||
command: false,
|
||||
paste: false,
|
||||
},
|
||||
],
|
||||
// Original: key.name === 'return' && (key.ctrl || key.meta || key.paste)
|
||||
// Split into multiple data-driven bindings
|
||||
[Command.NEWLINE]: [
|
||||
{ key: 'return', ctrl: true },
|
||||
{ key: 'return', command: true },
|
||||
{ key: 'return', paste: true },
|
||||
],
|
||||
|
||||
// External tools
|
||||
// Original: key.ctrl && (key.name === 'x' || key.sequence === '\x18')
|
||||
[Command.OPEN_EXTERNAL_EDITOR]: [
|
||||
{ key: 'x', ctrl: true },
|
||||
{ sequence: '\x18', ctrl: true },
|
||||
],
|
||||
// Original: key.ctrl && key.name === 'v'
|
||||
[Command.PASTE_CLIPBOARD_IMAGE]: [{ key: 'v', ctrl: true }],
|
||||
|
||||
// App level bindings
|
||||
// Original: key.ctrl && key.name === 'o'
|
||||
[Command.SHOW_ERROR_DETAILS]: [{ key: 'o', ctrl: true }],
|
||||
// Original: key.ctrl && key.name === 't'
|
||||
[Command.TOGGLE_TOOL_DESCRIPTIONS]: [{ key: 't', ctrl: true }],
|
||||
// Original: key.ctrl && key.name === 'e'
|
||||
[Command.TOGGLE_IDE_CONTEXT_DETAIL]: [{ key: 'e', ctrl: true }],
|
||||
// Original: key.ctrl && (key.name === 'c' || key.name === 'C')
|
||||
[Command.QUIT]: [{ key: 'c', ctrl: true }],
|
||||
// Original: key.ctrl && (key.name === 'd' || key.name === 'D')
|
||||
[Command.EXIT]: [{ key: 'd', ctrl: true }],
|
||||
// Original: key.ctrl && key.name === 's'
|
||||
[Command.SHOW_MORE_LINES]: [{ key: 's', ctrl: true }],
|
||||
|
||||
// Shell commands
|
||||
// Original: key.ctrl && key.name === 'r'
|
||||
[Command.REVERSE_SEARCH]: [{ key: 'r', ctrl: true }],
|
||||
// Original: key.name === 'return' && !key.ctrl
|
||||
// Note: original logic ONLY checked ctrl=false, ignored meta/shift/paste
|
||||
[Command.SUBMIT_REVERSE_SEARCH]: [{ key: 'return', ctrl: false }],
|
||||
// Original: key.name === 'tab'
|
||||
[Command.ACCEPT_SUGGESTION_REVERSE_SEARCH]: [{ key: 'tab' }],
|
||||
};
|
||||
@@ -113,6 +113,7 @@ describe('Settings Loading and Merging', () => {
|
||||
customThemes: {},
|
||||
mcpServers: {},
|
||||
includeDirectories: [],
|
||||
chatCompression: {},
|
||||
});
|
||||
expect(settings.errors.length).toBe(0);
|
||||
});
|
||||
@@ -147,6 +148,7 @@ describe('Settings Loading and Merging', () => {
|
||||
customThemes: {},
|
||||
mcpServers: {},
|
||||
includeDirectories: [],
|
||||
chatCompression: {},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -181,6 +183,7 @@ describe('Settings Loading and Merging', () => {
|
||||
customThemes: {},
|
||||
mcpServers: {},
|
||||
includeDirectories: [],
|
||||
chatCompression: {},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -213,6 +216,7 @@ describe('Settings Loading and Merging', () => {
|
||||
customThemes: {},
|
||||
mcpServers: {},
|
||||
includeDirectories: [],
|
||||
chatCompression: {},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -251,6 +255,7 @@ describe('Settings Loading and Merging', () => {
|
||||
customThemes: {},
|
||||
mcpServers: {},
|
||||
includeDirectories: [],
|
||||
chatCompression: {},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -301,9 +306,66 @@ describe('Settings Loading and Merging', () => {
|
||||
customThemes: {},
|
||||
mcpServers: {},
|
||||
includeDirectories: [],
|
||||
chatCompression: {},
|
||||
});
|
||||
});
|
||||
|
||||
it('should ignore folderTrust from workspace settings', () => {
|
||||
(mockFsExistsSync as Mock).mockReturnValue(true);
|
||||
const userSettingsContent = {
|
||||
folderTrust: true,
|
||||
};
|
||||
const workspaceSettingsContent = {
|
||||
folderTrust: false, // This should be ignored
|
||||
};
|
||||
const systemSettingsContent = {
|
||||
// No folderTrust here
|
||||
};
|
||||
|
||||
(fs.readFileSync as Mock).mockImplementation(
|
||||
(p: fs.PathOrFileDescriptor) => {
|
||||
if (p === getSystemSettingsPath())
|
||||
return JSON.stringify(systemSettingsContent);
|
||||
if (p === USER_SETTINGS_PATH)
|
||||
return JSON.stringify(userSettingsContent);
|
||||
if (p === MOCK_WORKSPACE_SETTINGS_PATH)
|
||||
return JSON.stringify(workspaceSettingsContent);
|
||||
return '{}';
|
||||
},
|
||||
);
|
||||
|
||||
const settings = loadSettings(MOCK_WORKSPACE_DIR);
|
||||
expect(settings.merged.folderTrust).toBe(true); // User setting should be used
|
||||
});
|
||||
|
||||
it('should use system folderTrust over user setting', () => {
|
||||
(mockFsExistsSync as Mock).mockReturnValue(true);
|
||||
const userSettingsContent = {
|
||||
folderTrust: false,
|
||||
};
|
||||
const workspaceSettingsContent = {
|
||||
folderTrust: true, // This should be ignored
|
||||
};
|
||||
const systemSettingsContent = {
|
||||
folderTrust: true,
|
||||
};
|
||||
|
||||
(fs.readFileSync as Mock).mockImplementation(
|
||||
(p: fs.PathOrFileDescriptor) => {
|
||||
if (p === getSystemSettingsPath())
|
||||
return JSON.stringify(systemSettingsContent);
|
||||
if (p === USER_SETTINGS_PATH)
|
||||
return JSON.stringify(userSettingsContent);
|
||||
if (p === MOCK_WORKSPACE_SETTINGS_PATH)
|
||||
return JSON.stringify(workspaceSettingsContent);
|
||||
return '{}';
|
||||
},
|
||||
);
|
||||
|
||||
const settings = loadSettings(MOCK_WORKSPACE_DIR);
|
||||
expect(settings.merged.folderTrust).toBe(true); // System setting should be used
|
||||
});
|
||||
|
||||
it('should handle contextFileName correctly when only in user settings', () => {
|
||||
(mockFsExistsSync as Mock).mockImplementation(
|
||||
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
|
||||
@@ -622,6 +684,116 @@ describe('Settings Loading and Merging', () => {
|
||||
expect(settings.merged.mcpServers).toEqual({});
|
||||
});
|
||||
|
||||
it('should merge chatCompression settings, with workspace taking precedence', () => {
|
||||
(mockFsExistsSync as Mock).mockReturnValue(true);
|
||||
const userSettingsContent = {
|
||||
chatCompression: { contextPercentageThreshold: 0.5 },
|
||||
};
|
||||
const workspaceSettingsContent = {
|
||||
chatCompression: { contextPercentageThreshold: 0.8 },
|
||||
};
|
||||
|
||||
(fs.readFileSync as Mock).mockImplementation(
|
||||
(p: fs.PathOrFileDescriptor) => {
|
||||
if (p === USER_SETTINGS_PATH)
|
||||
return JSON.stringify(userSettingsContent);
|
||||
if (p === MOCK_WORKSPACE_SETTINGS_PATH)
|
||||
return JSON.stringify(workspaceSettingsContent);
|
||||
return '{}';
|
||||
},
|
||||
);
|
||||
|
||||
const settings = loadSettings(MOCK_WORKSPACE_DIR);
|
||||
|
||||
expect(settings.user.settings.chatCompression).toEqual({
|
||||
contextPercentageThreshold: 0.5,
|
||||
});
|
||||
expect(settings.workspace.settings.chatCompression).toEqual({
|
||||
contextPercentageThreshold: 0.8,
|
||||
});
|
||||
expect(settings.merged.chatCompression).toEqual({
|
||||
contextPercentageThreshold: 0.8,
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle chatCompression when only in user settings', () => {
|
||||
(mockFsExistsSync as Mock).mockImplementation(
|
||||
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
|
||||
);
|
||||
const userSettingsContent = {
|
||||
chatCompression: { contextPercentageThreshold: 0.5 },
|
||||
};
|
||||
(fs.readFileSync as Mock).mockImplementation(
|
||||
(p: fs.PathOrFileDescriptor) => {
|
||||
if (p === USER_SETTINGS_PATH)
|
||||
return JSON.stringify(userSettingsContent);
|
||||
return '{}';
|
||||
},
|
||||
);
|
||||
|
||||
const settings = loadSettings(MOCK_WORKSPACE_DIR);
|
||||
expect(settings.merged.chatCompression).toEqual({
|
||||
contextPercentageThreshold: 0.5,
|
||||
});
|
||||
});
|
||||
|
||||
it('should have chatCompression as an empty object if not in any settings file', () => {
|
||||
(mockFsExistsSync as Mock).mockReturnValue(false); // No settings files exist
|
||||
(fs.readFileSync as Mock).mockReturnValue('{}');
|
||||
const settings = loadSettings(MOCK_WORKSPACE_DIR);
|
||||
expect(settings.merged.chatCompression).toEqual({});
|
||||
});
|
||||
|
||||
it('should ignore chatCompression if contextPercentageThreshold is invalid', () => {
|
||||
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
(mockFsExistsSync as Mock).mockImplementation(
|
||||
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
|
||||
);
|
||||
const userSettingsContent = {
|
||||
chatCompression: { contextPercentageThreshold: 1.5 },
|
||||
};
|
||||
(fs.readFileSync as Mock).mockImplementation(
|
||||
(p: fs.PathOrFileDescriptor) => {
|
||||
if (p === USER_SETTINGS_PATH)
|
||||
return JSON.stringify(userSettingsContent);
|
||||
return '{}';
|
||||
},
|
||||
);
|
||||
|
||||
const settings = loadSettings(MOCK_WORKSPACE_DIR);
|
||||
expect(settings.merged.chatCompression).toBeUndefined();
|
||||
expect(warnSpy).toHaveBeenCalledWith(
|
||||
'Invalid value for chatCompression.contextPercentageThreshold: "1.5". Please use a value between 0 and 1. Using default compression settings.',
|
||||
);
|
||||
warnSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should deep merge chatCompression settings', () => {
|
||||
(mockFsExistsSync as Mock).mockReturnValue(true);
|
||||
const userSettingsContent = {
|
||||
chatCompression: { contextPercentageThreshold: 0.5 },
|
||||
};
|
||||
const workspaceSettingsContent = {
|
||||
chatCompression: {},
|
||||
};
|
||||
|
||||
(fs.readFileSync as Mock).mockImplementation(
|
||||
(p: fs.PathOrFileDescriptor) => {
|
||||
if (p === USER_SETTINGS_PATH)
|
||||
return JSON.stringify(userSettingsContent);
|
||||
if (p === MOCK_WORKSPACE_SETTINGS_PATH)
|
||||
return JSON.stringify(workspaceSettingsContent);
|
||||
return '{}';
|
||||
},
|
||||
);
|
||||
|
||||
const settings = loadSettings(MOCK_WORKSPACE_DIR);
|
||||
|
||||
expect(settings.merged.chatCompression).toEqual({
|
||||
contextPercentageThreshold: 0.5,
|
||||
});
|
||||
});
|
||||
|
||||
it('should merge includeDirectories from all scopes', () => {
|
||||
(mockFsExistsSync as Mock).mockReturnValue(true);
|
||||
const systemSettingsContent = {
|
||||
@@ -695,6 +867,7 @@ describe('Settings Loading and Merging', () => {
|
||||
customThemes: {},
|
||||
mcpServers: {},
|
||||
includeDirectories: [],
|
||||
chatCompression: {},
|
||||
});
|
||||
|
||||
// Check that error objects are populated in settings.errors
|
||||
@@ -1132,6 +1305,7 @@ describe('Settings Loading and Merging', () => {
|
||||
customThemes: {},
|
||||
mcpServers: {},
|
||||
includeDirectories: [],
|
||||
chatCompression: {},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,17 +9,15 @@ import * as path from 'path';
|
||||
import { homedir, platform } from 'os';
|
||||
import * as dotenv from 'dotenv';
|
||||
import {
|
||||
MCPServerConfig,
|
||||
GEMINI_CONFIG_DIR as GEMINI_DIR,
|
||||
getErrorMessage,
|
||||
BugCommandSettings,
|
||||
TelemetrySettings,
|
||||
AuthType,
|
||||
} from '@qwen-code/qwen-code-core';
|
||||
import stripJsonComments from 'strip-json-comments';
|
||||
import { DefaultLight } from '../ui/themes/default-light.js';
|
||||
import { DefaultDark } from '../ui/themes/default.js';
|
||||
import { CustomTheme } from '../ui/themes/theme.js';
|
||||
import { Settings, MemoryImportFormat } from './settingsSchema.js';
|
||||
|
||||
export type { Settings, MemoryImportFormat };
|
||||
|
||||
export const SETTINGS_DIRECTORY_NAME = '.qwen';
|
||||
export const USER_SETTINGS_DIR = path.join(homedir(), SETTINGS_DIRECTORY_NAME);
|
||||
@@ -43,7 +41,7 @@ export function getWorkspaceSettingsPath(workspaceDir: string): string {
|
||||
return path.join(workspaceDir, SETTINGS_DIRECTORY_NAME, 'settings.json');
|
||||
}
|
||||
|
||||
export type DnsResolutionOrder = 'ipv4first' | 'verbatim';
|
||||
export type { DnsResolutionOrder } from './settingsSchema.js';
|
||||
|
||||
export enum SettingScope {
|
||||
User = 'User',
|
||||
@@ -63,95 +61,6 @@ export interface AccessibilitySettings {
|
||||
disableLoadingPhrases?: boolean;
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
theme?: string;
|
||||
customThemes?: Record<string, CustomTheme>;
|
||||
selectedAuthType?: AuthType;
|
||||
useExternalAuth?: boolean;
|
||||
sandbox?: boolean | string;
|
||||
coreTools?: string[];
|
||||
excludeTools?: string[];
|
||||
toolDiscoveryCommand?: string;
|
||||
toolCallCommand?: string;
|
||||
mcpServerCommand?: string;
|
||||
mcpServers?: Record<string, MCPServerConfig>;
|
||||
allowMCPServers?: string[];
|
||||
excludeMCPServers?: string[];
|
||||
showMemoryUsage?: boolean;
|
||||
contextFileName?: string | string[];
|
||||
accessibility?: AccessibilitySettings;
|
||||
telemetry?: TelemetrySettings;
|
||||
usageStatisticsEnabled?: boolean;
|
||||
preferredEditor?: string;
|
||||
bugCommand?: BugCommandSettings;
|
||||
checkpointing?: CheckpointingSettings;
|
||||
autoConfigureMaxOldSpaceSize?: boolean;
|
||||
/** The model name to use (e.g 'gemini-9.0-pro') */
|
||||
model?: string;
|
||||
enableOpenAILogging?: boolean;
|
||||
|
||||
// Git-aware file filtering settings
|
||||
fileFiltering?: {
|
||||
respectGitIgnore?: boolean;
|
||||
respectGeminiIgnore?: boolean;
|
||||
enableRecursiveFileSearch?: boolean;
|
||||
};
|
||||
|
||||
hideWindowTitle?: boolean;
|
||||
|
||||
hideTips?: boolean;
|
||||
hideBanner?: boolean;
|
||||
|
||||
// Setting for setting maximum number of user/model/tool turns in a session.
|
||||
maxSessionTurns?: number;
|
||||
|
||||
// Setting for maximum token limit for conversation history before blocking requests
|
||||
sessionTokenLimit?: number;
|
||||
|
||||
// Setting for maximum number of files and folders to show in folder structure
|
||||
maxFolderItems?: number;
|
||||
|
||||
// A map of tool names to their summarization settings.
|
||||
summarizeToolOutput?: Record<string, SummarizeToolOutputSettings>;
|
||||
|
||||
vimMode?: boolean;
|
||||
memoryImportFormat?: 'tree' | 'flat';
|
||||
|
||||
// Flag to be removed post-launch.
|
||||
ideModeFeature?: boolean;
|
||||
/// IDE mode setting configured via slash command toggle.
|
||||
ideMode?: boolean;
|
||||
|
||||
// Setting for disabling auto-update.
|
||||
disableAutoUpdate?: boolean;
|
||||
|
||||
// Setting for disabling the update nag message.
|
||||
disableUpdateNag?: boolean;
|
||||
|
||||
memoryDiscoveryMaxDirs?: number;
|
||||
// Environment variables to exclude from project .env files
|
||||
excludedProjectEnvVars?: string[];
|
||||
dnsResolutionOrder?: DnsResolutionOrder;
|
||||
|
||||
sampling_params?: Record<string, unknown>;
|
||||
systemPromptMappings?: Array<{
|
||||
baseUrls: string[];
|
||||
modelNames: string[];
|
||||
template: string;
|
||||
}>;
|
||||
contentGenerator?: {
|
||||
timeout?: number;
|
||||
maxRetries?: number;
|
||||
};
|
||||
|
||||
includeDirectories?: string[];
|
||||
|
||||
loadMemoryFromIncludeDirectories?: boolean;
|
||||
|
||||
// Web search API keys
|
||||
tavilyApiKey?: string;
|
||||
}
|
||||
|
||||
export interface SettingsError {
|
||||
message: string;
|
||||
path: string;
|
||||
@@ -191,9 +100,13 @@ export class LoadedSettings {
|
||||
const user = this.user.settings;
|
||||
const workspace = this.workspace.settings;
|
||||
|
||||
// folderTrust is not supported at workspace level.
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { folderTrust, ...workspaceWithoutFolderTrust } = workspace;
|
||||
|
||||
return {
|
||||
...user,
|
||||
...workspace,
|
||||
...workspaceWithoutFolderTrust,
|
||||
...system,
|
||||
customThemes: {
|
||||
...(user.customThemes || {}),
|
||||
@@ -210,6 +123,11 @@ export class LoadedSettings {
|
||||
...(user.includeDirectories || []),
|
||||
...(workspace.includeDirectories || []),
|
||||
],
|
||||
chatCompression: {
|
||||
...(system.chatCompression || {}),
|
||||
...(user.chatCompression || {}),
|
||||
...(workspace.chatCompression || {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -498,6 +416,19 @@ export function loadSettings(workspaceDir: string): LoadedSettings {
|
||||
settingsErrors,
|
||||
);
|
||||
|
||||
// Validate chatCompression settings
|
||||
const chatCompression = loadedSettings.merged.chatCompression;
|
||||
const threshold = chatCompression?.contextPercentageThreshold;
|
||||
if (
|
||||
threshold != null &&
|
||||
(typeof threshold !== 'number' || threshold < 0 || threshold > 1)
|
||||
) {
|
||||
console.warn(
|
||||
`Invalid value for chatCompression.contextPercentageThreshold: "${threshold}". Please use a value between 0 and 1. Using default compression settings.`,
|
||||
);
|
||||
delete loadedSettings.merged.chatCompression;
|
||||
}
|
||||
|
||||
// Load environment with merged settings
|
||||
loadEnvironment(loadedSettings.merged);
|
||||
|
||||
|
||||
253
packages/cli/src/config/settingsSchema.test.ts
Normal file
253
packages/cli/src/config/settingsSchema.test.ts
Normal file
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { SETTINGS_SCHEMA, Settings } from './settingsSchema.js';
|
||||
|
||||
describe('SettingsSchema', () => {
|
||||
describe('SETTINGS_SCHEMA', () => {
|
||||
it('should contain all expected top-level settings', () => {
|
||||
const expectedSettings = [
|
||||
'theme',
|
||||
'customThemes',
|
||||
'showMemoryUsage',
|
||||
'usageStatisticsEnabled',
|
||||
'autoConfigureMaxOldSpaceSize',
|
||||
'preferredEditor',
|
||||
'maxSessionTurns',
|
||||
'memoryImportFormat',
|
||||
'memoryDiscoveryMaxDirs',
|
||||
'contextFileName',
|
||||
'vimMode',
|
||||
'ideMode',
|
||||
'accessibility',
|
||||
'checkpointing',
|
||||
'fileFiltering',
|
||||
'disableAutoUpdate',
|
||||
'hideWindowTitle',
|
||||
'hideTips',
|
||||
'hideBanner',
|
||||
'selectedAuthType',
|
||||
'useExternalAuth',
|
||||
'sandbox',
|
||||
'coreTools',
|
||||
'excludeTools',
|
||||
'toolDiscoveryCommand',
|
||||
'toolCallCommand',
|
||||
'mcpServerCommand',
|
||||
'mcpServers',
|
||||
'allowMCPServers',
|
||||
'excludeMCPServers',
|
||||
'telemetry',
|
||||
'bugCommand',
|
||||
'summarizeToolOutput',
|
||||
'ideModeFeature',
|
||||
'dnsResolutionOrder',
|
||||
'excludedProjectEnvVars',
|
||||
'disableUpdateNag',
|
||||
'includeDirectories',
|
||||
'loadMemoryFromIncludeDirectories',
|
||||
'model',
|
||||
'hasSeenIdeIntegrationNudge',
|
||||
'folderTrustFeature',
|
||||
];
|
||||
|
||||
expectedSettings.forEach((setting) => {
|
||||
expect(
|
||||
SETTINGS_SCHEMA[setting as keyof typeof SETTINGS_SCHEMA],
|
||||
).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
it('should have correct structure for each setting', () => {
|
||||
Object.entries(SETTINGS_SCHEMA).forEach(([_key, definition]) => {
|
||||
expect(definition).toHaveProperty('type');
|
||||
expect(definition).toHaveProperty('label');
|
||||
expect(definition).toHaveProperty('category');
|
||||
expect(definition).toHaveProperty('requiresRestart');
|
||||
expect(definition).toHaveProperty('default');
|
||||
expect(typeof definition.type).toBe('string');
|
||||
expect(typeof definition.label).toBe('string');
|
||||
expect(typeof definition.category).toBe('string');
|
||||
expect(typeof definition.requiresRestart).toBe('boolean');
|
||||
});
|
||||
});
|
||||
|
||||
it('should have correct nested setting structure', () => {
|
||||
const nestedSettings = [
|
||||
'accessibility',
|
||||
'checkpointing',
|
||||
'fileFiltering',
|
||||
];
|
||||
|
||||
nestedSettings.forEach((setting) => {
|
||||
const definition = SETTINGS_SCHEMA[
|
||||
setting as keyof typeof SETTINGS_SCHEMA
|
||||
] as (typeof SETTINGS_SCHEMA)[keyof typeof SETTINGS_SCHEMA] & {
|
||||
properties: unknown;
|
||||
};
|
||||
expect(definition.type).toBe('object');
|
||||
expect(definition.properties).toBeDefined();
|
||||
expect(typeof definition.properties).toBe('object');
|
||||
});
|
||||
});
|
||||
|
||||
it('should have accessibility nested properties', () => {
|
||||
expect(
|
||||
SETTINGS_SCHEMA.accessibility.properties?.disableLoadingPhrases,
|
||||
).toBeDefined();
|
||||
expect(
|
||||
SETTINGS_SCHEMA.accessibility.properties?.disableLoadingPhrases.type,
|
||||
).toBe('boolean');
|
||||
});
|
||||
|
||||
it('should have checkpointing nested properties', () => {
|
||||
expect(SETTINGS_SCHEMA.checkpointing.properties?.enabled).toBeDefined();
|
||||
expect(SETTINGS_SCHEMA.checkpointing.properties?.enabled.type).toBe(
|
||||
'boolean',
|
||||
);
|
||||
});
|
||||
|
||||
it('should have fileFiltering nested properties', () => {
|
||||
expect(
|
||||
SETTINGS_SCHEMA.fileFiltering.properties?.respectGitIgnore,
|
||||
).toBeDefined();
|
||||
expect(
|
||||
SETTINGS_SCHEMA.fileFiltering.properties?.respectGeminiIgnore,
|
||||
).toBeDefined();
|
||||
expect(
|
||||
SETTINGS_SCHEMA.fileFiltering.properties?.enableRecursiveFileSearch,
|
||||
).toBeDefined();
|
||||
});
|
||||
|
||||
it('should have unique categories', () => {
|
||||
const categories = new Set();
|
||||
|
||||
// Collect categories from top-level settings
|
||||
Object.values(SETTINGS_SCHEMA).forEach((definition) => {
|
||||
categories.add(definition.category);
|
||||
// Also collect from nested properties
|
||||
const defWithProps = definition as typeof definition & {
|
||||
properties?: Record<string, unknown>;
|
||||
};
|
||||
if (defWithProps.properties) {
|
||||
Object.values(defWithProps.properties).forEach(
|
||||
(nestedDef: unknown) => {
|
||||
const nestedDefTyped = nestedDef as { category?: string };
|
||||
if (nestedDefTyped.category) {
|
||||
categories.add(nestedDefTyped.category);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
expect(categories.size).toBeGreaterThan(0);
|
||||
expect(categories).toContain('General');
|
||||
expect(categories).toContain('UI');
|
||||
expect(categories).toContain('Mode');
|
||||
expect(categories).toContain('Updates');
|
||||
expect(categories).toContain('Accessibility');
|
||||
expect(categories).toContain('Checkpointing');
|
||||
expect(categories).toContain('File Filtering');
|
||||
expect(categories).toContain('Advanced');
|
||||
});
|
||||
|
||||
it('should have consistent default values for boolean settings', () => {
|
||||
const checkBooleanDefaults = (schema: Record<string, unknown>) => {
|
||||
Object.entries(schema).forEach(
|
||||
([_key, definition]: [string, unknown]) => {
|
||||
const def = definition as {
|
||||
type?: string;
|
||||
default?: unknown;
|
||||
properties?: Record<string, unknown>;
|
||||
};
|
||||
if (def.type === 'boolean') {
|
||||
// Boolean settings can have boolean or undefined defaults (for optional settings)
|
||||
expect(['boolean', 'undefined']).toContain(typeof def.default);
|
||||
}
|
||||
if (def.properties) {
|
||||
checkBooleanDefaults(def.properties);
|
||||
}
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
checkBooleanDefaults(SETTINGS_SCHEMA as Record<string, unknown>);
|
||||
});
|
||||
|
||||
it('should have showInDialog property configured', () => {
|
||||
// Check that user-facing settings are marked for dialog display
|
||||
expect(SETTINGS_SCHEMA.showMemoryUsage.showInDialog).toBe(true);
|
||||
expect(SETTINGS_SCHEMA.vimMode.showInDialog).toBe(true);
|
||||
expect(SETTINGS_SCHEMA.ideMode.showInDialog).toBe(true);
|
||||
expect(SETTINGS_SCHEMA.disableAutoUpdate.showInDialog).toBe(true);
|
||||
expect(SETTINGS_SCHEMA.hideWindowTitle.showInDialog).toBe(true);
|
||||
expect(SETTINGS_SCHEMA.hideTips.showInDialog).toBe(true);
|
||||
expect(SETTINGS_SCHEMA.hideBanner.showInDialog).toBe(true);
|
||||
expect(SETTINGS_SCHEMA.usageStatisticsEnabled.showInDialog).toBe(true);
|
||||
|
||||
// Check that advanced settings are hidden from dialog
|
||||
expect(SETTINGS_SCHEMA.selectedAuthType.showInDialog).toBe(false);
|
||||
expect(SETTINGS_SCHEMA.coreTools.showInDialog).toBe(false);
|
||||
expect(SETTINGS_SCHEMA.mcpServers.showInDialog).toBe(false);
|
||||
expect(SETTINGS_SCHEMA.telemetry.showInDialog).toBe(false);
|
||||
|
||||
// Check that some settings are appropriately hidden
|
||||
expect(SETTINGS_SCHEMA.theme.showInDialog).toBe(false); // Changed to false
|
||||
expect(SETTINGS_SCHEMA.customThemes.showInDialog).toBe(false); // Managed via theme editor
|
||||
expect(SETTINGS_SCHEMA.checkpointing.showInDialog).toBe(false); // Experimental feature
|
||||
expect(SETTINGS_SCHEMA.accessibility.showInDialog).toBe(false); // Changed to false
|
||||
expect(SETTINGS_SCHEMA.fileFiltering.showInDialog).toBe(false); // Changed to false
|
||||
expect(SETTINGS_SCHEMA.preferredEditor.showInDialog).toBe(false); // Changed to false
|
||||
expect(SETTINGS_SCHEMA.autoConfigureMaxOldSpaceSize.showInDialog).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('should infer Settings type correctly', () => {
|
||||
// This test ensures that the Settings type is properly inferred from the schema
|
||||
const settings: Settings = {
|
||||
theme: 'dark',
|
||||
includeDirectories: ['/path/to/dir'],
|
||||
loadMemoryFromIncludeDirectories: true,
|
||||
};
|
||||
|
||||
// TypeScript should not complain about these properties
|
||||
expect(settings.theme).toBe('dark');
|
||||
expect(settings.includeDirectories).toEqual(['/path/to/dir']);
|
||||
expect(settings.loadMemoryFromIncludeDirectories).toBe(true);
|
||||
});
|
||||
|
||||
it('should have includeDirectories setting in schema', () => {
|
||||
expect(SETTINGS_SCHEMA.includeDirectories).toBeDefined();
|
||||
expect(SETTINGS_SCHEMA.includeDirectories.type).toBe('array');
|
||||
expect(SETTINGS_SCHEMA.includeDirectories.category).toBe('General');
|
||||
expect(SETTINGS_SCHEMA.includeDirectories.default).toEqual([]);
|
||||
});
|
||||
|
||||
it('should have loadMemoryFromIncludeDirectories setting in schema', () => {
|
||||
expect(SETTINGS_SCHEMA.loadMemoryFromIncludeDirectories).toBeDefined();
|
||||
expect(SETTINGS_SCHEMA.loadMemoryFromIncludeDirectories.type).toBe(
|
||||
'boolean',
|
||||
);
|
||||
expect(SETTINGS_SCHEMA.loadMemoryFromIncludeDirectories.category).toBe(
|
||||
'General',
|
||||
);
|
||||
expect(SETTINGS_SCHEMA.loadMemoryFromIncludeDirectories.default).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('should have folderTrustFeature setting in schema', () => {
|
||||
expect(SETTINGS_SCHEMA.folderTrustFeature).toBeDefined();
|
||||
expect(SETTINGS_SCHEMA.folderTrustFeature.type).toBe('boolean');
|
||||
expect(SETTINGS_SCHEMA.folderTrustFeature.category).toBe('General');
|
||||
expect(SETTINGS_SCHEMA.folderTrustFeature.default).toBe(false);
|
||||
expect(SETTINGS_SCHEMA.folderTrustFeature.showInDialog).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
571
packages/cli/src/config/settingsSchema.ts
Normal file
571
packages/cli/src/config/settingsSchema.ts
Normal file
@@ -0,0 +1,571 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import {
|
||||
MCPServerConfig,
|
||||
BugCommandSettings,
|
||||
TelemetrySettings,
|
||||
AuthType,
|
||||
ChatCompressionSettings,
|
||||
} from '@qwen-code/qwen-code-core';
|
||||
import { CustomTheme } from '../ui/themes/theme.js';
|
||||
|
||||
export interface SettingDefinition {
|
||||
type: 'boolean' | 'string' | 'number' | 'array' | 'object';
|
||||
label: string;
|
||||
category: string;
|
||||
requiresRestart: boolean;
|
||||
default: boolean | string | number | string[] | object | undefined;
|
||||
description?: string;
|
||||
parentKey?: string;
|
||||
childKey?: string;
|
||||
key?: string;
|
||||
properties?: SettingsSchema;
|
||||
showInDialog?: boolean;
|
||||
}
|
||||
|
||||
export interface SettingsSchema {
|
||||
[key: string]: SettingDefinition;
|
||||
}
|
||||
|
||||
export type MemoryImportFormat = 'tree' | 'flat';
|
||||
export type DnsResolutionOrder = 'ipv4first' | 'verbatim';
|
||||
|
||||
/**
|
||||
* The canonical schema for all settings.
|
||||
* The structure of this object defines the structure of the `Settings` type.
|
||||
* `as const` is crucial for TypeScript to infer the most specific types possible.
|
||||
*/
|
||||
export const SETTINGS_SCHEMA = {
|
||||
// UI Settings
|
||||
theme: {
|
||||
type: 'string',
|
||||
label: 'Theme',
|
||||
category: 'UI',
|
||||
requiresRestart: false,
|
||||
default: undefined as string | undefined,
|
||||
description: 'The color theme for the UI.',
|
||||
showInDialog: false,
|
||||
},
|
||||
customThemes: {
|
||||
type: 'object',
|
||||
label: 'Custom Themes',
|
||||
category: 'UI',
|
||||
requiresRestart: false,
|
||||
default: {} as Record<string, CustomTheme>,
|
||||
description: 'Custom theme definitions.',
|
||||
showInDialog: false,
|
||||
},
|
||||
hideWindowTitle: {
|
||||
type: 'boolean',
|
||||
label: 'Hide Window Title',
|
||||
category: 'UI',
|
||||
requiresRestart: true,
|
||||
default: false,
|
||||
description: 'Hide the window title bar',
|
||||
showInDialog: true,
|
||||
},
|
||||
hideTips: {
|
||||
type: 'boolean',
|
||||
label: 'Hide Tips',
|
||||
category: 'UI',
|
||||
requiresRestart: false,
|
||||
default: false,
|
||||
description: 'Hide helpful tips in the UI',
|
||||
showInDialog: true,
|
||||
},
|
||||
hideBanner: {
|
||||
type: 'boolean',
|
||||
label: 'Hide Banner',
|
||||
category: 'UI',
|
||||
requiresRestart: false,
|
||||
default: false,
|
||||
description: 'Hide the application banner',
|
||||
showInDialog: true,
|
||||
},
|
||||
showMemoryUsage: {
|
||||
type: 'boolean',
|
||||
label: 'Show Memory Usage',
|
||||
category: 'UI',
|
||||
requiresRestart: false,
|
||||
default: false,
|
||||
description: 'Display memory usage information in the UI',
|
||||
showInDialog: true,
|
||||
},
|
||||
|
||||
usageStatisticsEnabled: {
|
||||
type: 'boolean',
|
||||
label: 'Enable Usage Statistics',
|
||||
category: 'General',
|
||||
requiresRestart: true,
|
||||
default: true,
|
||||
description: 'Enable collection of usage statistics',
|
||||
showInDialog: true,
|
||||
},
|
||||
autoConfigureMaxOldSpaceSize: {
|
||||
type: 'boolean',
|
||||
label: 'Auto Configure Max Old Space Size',
|
||||
category: 'General',
|
||||
requiresRestart: true,
|
||||
default: false,
|
||||
description: 'Automatically configure Node.js memory limits',
|
||||
showInDialog: true,
|
||||
},
|
||||
preferredEditor: {
|
||||
type: 'string',
|
||||
label: 'Preferred Editor',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: undefined as string | undefined,
|
||||
description: 'The preferred editor to open files in.',
|
||||
showInDialog: false,
|
||||
},
|
||||
maxSessionTurns: {
|
||||
type: 'number',
|
||||
label: 'Max Session Turns',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: undefined as number | undefined,
|
||||
description:
|
||||
'Maximum number of user/model/tool turns to keep in a session.',
|
||||
showInDialog: false,
|
||||
},
|
||||
memoryImportFormat: {
|
||||
type: 'string',
|
||||
label: 'Memory Import Format',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: undefined as MemoryImportFormat | undefined,
|
||||
description: 'The format to use when importing memory.',
|
||||
showInDialog: false,
|
||||
},
|
||||
memoryDiscoveryMaxDirs: {
|
||||
type: 'number',
|
||||
label: 'Memory Discovery Max Dirs',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: undefined as number | undefined,
|
||||
description: 'Maximum number of directories to search for memory.',
|
||||
showInDialog: false,
|
||||
},
|
||||
contextFileName: {
|
||||
type: 'object',
|
||||
label: 'Context File Name',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: undefined as string | string[] | undefined,
|
||||
description: 'The name of the context file.',
|
||||
showInDialog: false,
|
||||
},
|
||||
vimMode: {
|
||||
type: 'boolean',
|
||||
label: 'Vim Mode',
|
||||
category: 'Mode',
|
||||
requiresRestart: false,
|
||||
default: false,
|
||||
description: 'Enable Vim keybindings',
|
||||
showInDialog: true,
|
||||
},
|
||||
ideMode: {
|
||||
type: 'boolean',
|
||||
label: 'IDE Mode',
|
||||
category: 'Mode',
|
||||
requiresRestart: true,
|
||||
default: false,
|
||||
description: 'Enable IDE integration mode',
|
||||
showInDialog: true,
|
||||
},
|
||||
|
||||
accessibility: {
|
||||
type: 'object',
|
||||
label: 'Accessibility',
|
||||
category: 'Accessibility',
|
||||
requiresRestart: true,
|
||||
default: {},
|
||||
description: 'Accessibility settings.',
|
||||
showInDialog: false,
|
||||
properties: {
|
||||
disableLoadingPhrases: {
|
||||
type: 'boolean',
|
||||
label: 'Disable Loading Phrases',
|
||||
category: 'Accessibility',
|
||||
requiresRestart: true,
|
||||
default: false,
|
||||
description: 'Disable loading phrases for accessibility',
|
||||
showInDialog: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
checkpointing: {
|
||||
type: 'object',
|
||||
label: 'Checkpointing',
|
||||
category: 'Checkpointing',
|
||||
requiresRestart: true,
|
||||
default: {},
|
||||
description: 'Session checkpointing settings.',
|
||||
showInDialog: false,
|
||||
properties: {
|
||||
enabled: {
|
||||
type: 'boolean',
|
||||
label: 'Enable Checkpointing',
|
||||
category: 'Checkpointing',
|
||||
requiresRestart: true,
|
||||
default: false,
|
||||
description: 'Enable session checkpointing for recovery',
|
||||
showInDialog: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
fileFiltering: {
|
||||
type: 'object',
|
||||
label: 'File Filtering',
|
||||
category: 'File Filtering',
|
||||
requiresRestart: true,
|
||||
default: {},
|
||||
description: 'Settings for git-aware file filtering.',
|
||||
showInDialog: false,
|
||||
properties: {
|
||||
respectGitIgnore: {
|
||||
type: 'boolean',
|
||||
label: 'Respect .gitignore',
|
||||
category: 'File Filtering',
|
||||
requiresRestart: true,
|
||||
default: true,
|
||||
description: 'Respect .gitignore files when searching',
|
||||
showInDialog: true,
|
||||
},
|
||||
respectGeminiIgnore: {
|
||||
type: 'boolean',
|
||||
label: 'Respect .geminiignore',
|
||||
category: 'File Filtering',
|
||||
requiresRestart: true,
|
||||
default: true,
|
||||
description: 'Respect .geminiignore files when searching',
|
||||
showInDialog: true,
|
||||
},
|
||||
enableRecursiveFileSearch: {
|
||||
type: 'boolean',
|
||||
label: 'Enable Recursive File Search',
|
||||
category: 'File Filtering',
|
||||
requiresRestart: true,
|
||||
default: true,
|
||||
description: 'Enable recursive file search functionality',
|
||||
showInDialog: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
disableAutoUpdate: {
|
||||
type: 'boolean',
|
||||
label: 'Disable Auto Update',
|
||||
category: 'Updates',
|
||||
requiresRestart: false,
|
||||
default: false,
|
||||
description: 'Disable automatic updates',
|
||||
showInDialog: true,
|
||||
},
|
||||
|
||||
selectedAuthType: {
|
||||
type: 'string',
|
||||
label: 'Selected Auth Type',
|
||||
category: 'Advanced',
|
||||
requiresRestart: true,
|
||||
default: undefined as AuthType | undefined,
|
||||
description: 'The currently selected authentication type.',
|
||||
showInDialog: false,
|
||||
},
|
||||
useExternalAuth: {
|
||||
type: 'boolean',
|
||||
label: 'Use External Auth',
|
||||
category: 'Advanced',
|
||||
requiresRestart: true,
|
||||
default: undefined as boolean | undefined,
|
||||
description: 'Whether to use an external authentication flow.',
|
||||
showInDialog: false,
|
||||
},
|
||||
sandbox: {
|
||||
type: 'object',
|
||||
label: 'Sandbox',
|
||||
category: 'Advanced',
|
||||
requiresRestart: true,
|
||||
default: undefined as boolean | string | undefined,
|
||||
description:
|
||||
'Sandbox execution environment (can be a boolean or a path string).',
|
||||
showInDialog: false,
|
||||
},
|
||||
coreTools: {
|
||||
type: 'array',
|
||||
label: 'Core Tools',
|
||||
category: 'Advanced',
|
||||
requiresRestart: true,
|
||||
default: undefined as string[] | undefined,
|
||||
description: 'Paths to core tool definitions.',
|
||||
showInDialog: false,
|
||||
},
|
||||
excludeTools: {
|
||||
type: 'array',
|
||||
label: 'Exclude Tools',
|
||||
category: 'Advanced',
|
||||
requiresRestart: true,
|
||||
default: undefined as string[] | undefined,
|
||||
description: 'Tool names to exclude from discovery.',
|
||||
showInDialog: false,
|
||||
},
|
||||
toolDiscoveryCommand: {
|
||||
type: 'string',
|
||||
label: 'Tool Discovery Command',
|
||||
category: 'Advanced',
|
||||
requiresRestart: true,
|
||||
default: undefined as string | undefined,
|
||||
description: 'Command to run for tool discovery.',
|
||||
showInDialog: false,
|
||||
},
|
||||
toolCallCommand: {
|
||||
type: 'string',
|
||||
label: 'Tool Call Command',
|
||||
category: 'Advanced',
|
||||
requiresRestart: true,
|
||||
default: undefined as string | undefined,
|
||||
description: 'Command to run for tool calls.',
|
||||
showInDialog: false,
|
||||
},
|
||||
mcpServerCommand: {
|
||||
type: 'string',
|
||||
label: 'MCP Server Command',
|
||||
category: 'Advanced',
|
||||
requiresRestart: true,
|
||||
default: undefined as string | undefined,
|
||||
description: 'Command to start an MCP server.',
|
||||
showInDialog: false,
|
||||
},
|
||||
mcpServers: {
|
||||
type: 'object',
|
||||
label: 'MCP Servers',
|
||||
category: 'Advanced',
|
||||
requiresRestart: true,
|
||||
default: {} as Record<string, MCPServerConfig>,
|
||||
description: 'Configuration for MCP servers.',
|
||||
showInDialog: false,
|
||||
},
|
||||
allowMCPServers: {
|
||||
type: 'array',
|
||||
label: 'Allow MCP Servers',
|
||||
category: 'Advanced',
|
||||
requiresRestart: true,
|
||||
default: undefined as string[] | undefined,
|
||||
description: 'A whitelist of MCP servers to allow.',
|
||||
showInDialog: false,
|
||||
},
|
||||
excludeMCPServers: {
|
||||
type: 'array',
|
||||
label: 'Exclude MCP Servers',
|
||||
category: 'Advanced',
|
||||
requiresRestart: true,
|
||||
default: undefined as string[] | undefined,
|
||||
description: 'A blacklist of MCP servers to exclude.',
|
||||
showInDialog: false,
|
||||
},
|
||||
telemetry: {
|
||||
type: 'object',
|
||||
label: 'Telemetry',
|
||||
category: 'Advanced',
|
||||
requiresRestart: true,
|
||||
default: undefined as TelemetrySettings | undefined,
|
||||
description: 'Telemetry configuration.',
|
||||
showInDialog: false,
|
||||
},
|
||||
bugCommand: {
|
||||
type: 'object',
|
||||
label: 'Bug Command',
|
||||
category: 'Advanced',
|
||||
requiresRestart: false,
|
||||
default: undefined as BugCommandSettings | undefined,
|
||||
description: 'Configuration for the bug report command.',
|
||||
showInDialog: false,
|
||||
},
|
||||
summarizeToolOutput: {
|
||||
type: 'object',
|
||||
label: 'Summarize Tool Output',
|
||||
category: 'Advanced',
|
||||
requiresRestart: false,
|
||||
default: undefined as Record<string, { tokenBudget?: number }> | undefined,
|
||||
description: 'Settings for summarizing tool output.',
|
||||
showInDialog: false,
|
||||
},
|
||||
ideModeFeature: {
|
||||
type: 'boolean',
|
||||
label: 'IDE Mode Feature Flag',
|
||||
category: 'Advanced',
|
||||
requiresRestart: true,
|
||||
default: undefined as boolean | undefined,
|
||||
description: 'Internal feature flag for IDE mode.',
|
||||
showInDialog: false,
|
||||
},
|
||||
dnsResolutionOrder: {
|
||||
type: 'string',
|
||||
label: 'DNS Resolution Order',
|
||||
category: 'Advanced',
|
||||
requiresRestart: true,
|
||||
default: undefined as DnsResolutionOrder | undefined,
|
||||
description: 'The DNS resolution order.',
|
||||
showInDialog: false,
|
||||
},
|
||||
excludedProjectEnvVars: {
|
||||
type: 'array',
|
||||
label: 'Excluded Project Environment Variables',
|
||||
category: 'Advanced',
|
||||
requiresRestart: false,
|
||||
default: ['DEBUG', 'DEBUG_MODE'] as string[],
|
||||
description: 'Environment variables to exclude from project context.',
|
||||
showInDialog: false,
|
||||
},
|
||||
disableUpdateNag: {
|
||||
type: 'boolean',
|
||||
label: 'Disable Update Nag',
|
||||
category: 'Updates',
|
||||
requiresRestart: false,
|
||||
default: false,
|
||||
description: 'Disable update notification prompts.',
|
||||
showInDialog: false,
|
||||
},
|
||||
includeDirectories: {
|
||||
type: 'array',
|
||||
label: 'Include Directories',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: [] as string[],
|
||||
description: 'Additional directories to include in the workspace context.',
|
||||
showInDialog: false,
|
||||
},
|
||||
loadMemoryFromIncludeDirectories: {
|
||||
type: 'boolean',
|
||||
label: 'Load Memory From Include Directories',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: false,
|
||||
description: 'Whether to load memory files from include directories.',
|
||||
showInDialog: true,
|
||||
},
|
||||
model: {
|
||||
type: 'string',
|
||||
label: 'Model',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: undefined as string | undefined,
|
||||
description: 'The Gemini model to use for conversations.',
|
||||
showInDialog: false,
|
||||
},
|
||||
hasSeenIdeIntegrationNudge: {
|
||||
type: 'boolean',
|
||||
label: 'Has Seen IDE Integration Nudge',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: false,
|
||||
description: 'Whether the user has seen the IDE integration nudge.',
|
||||
showInDialog: false,
|
||||
},
|
||||
folderTrustFeature: {
|
||||
type: 'boolean',
|
||||
label: 'Folder Trust Feature',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: false,
|
||||
description: 'Enable folder trust feature for enhanced security.',
|
||||
showInDialog: true,
|
||||
},
|
||||
folderTrust: {
|
||||
type: 'boolean',
|
||||
label: 'Folder Trust',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: false,
|
||||
description: 'Setting to track whether Folder trust is enabled.',
|
||||
showInDialog: true,
|
||||
},
|
||||
chatCompression: {
|
||||
type: 'object',
|
||||
label: 'Chat Compression',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: undefined as ChatCompressionSettings | undefined,
|
||||
description: 'Chat compression settings.',
|
||||
showInDialog: false,
|
||||
},
|
||||
showLineNumbers: {
|
||||
type: 'boolean',
|
||||
label: 'Show Line Numbers',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: false,
|
||||
description: 'Show line numbers in the chat.',
|
||||
showInDialog: true,
|
||||
},
|
||||
|
||||
contentGenerator: {
|
||||
type: 'object',
|
||||
label: 'Content Generator',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: undefined as Record<string, unknown> | undefined,
|
||||
description: 'Content generator settings.',
|
||||
showInDialog: false,
|
||||
},
|
||||
sampling_params: {
|
||||
type: 'object',
|
||||
label: 'Sampling Params',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: undefined as Record<string, unknown> | undefined,
|
||||
description: 'Sampling parameters for the model.',
|
||||
showInDialog: false,
|
||||
},
|
||||
enableOpenAILogging: {
|
||||
type: 'boolean',
|
||||
label: 'Enable OpenAI Logging',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: false,
|
||||
description: 'Enable OpenAI logging.',
|
||||
showInDialog: true,
|
||||
},
|
||||
sessionTokenLimit: {
|
||||
type: 'number',
|
||||
label: 'Session Token Limit',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: undefined as number | undefined,
|
||||
description: 'The maximum number of tokens allowed in a session.',
|
||||
showInDialog: false,
|
||||
},
|
||||
systemPromptMappings: {
|
||||
type: 'object',
|
||||
label: 'System Prompt Mappings',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: undefined as Record<string, string> | undefined,
|
||||
description: 'Mappings of system prompts to model names.',
|
||||
showInDialog: false,
|
||||
},
|
||||
tavilyApiKey: {
|
||||
type: 'string',
|
||||
label: 'Tavily API Key',
|
||||
category: 'General',
|
||||
requiresRestart: false,
|
||||
default: undefined as string | undefined,
|
||||
description: 'The API key for the Tavily API.',
|
||||
showInDialog: false,
|
||||
},
|
||||
} as const;
|
||||
|
||||
type InferSettings<T extends SettingsSchema> = {
|
||||
-readonly [K in keyof T]?: T[K] extends { properties: SettingsSchema }
|
||||
? InferSettings<T[K]['properties']>
|
||||
: T[K]['default'] extends boolean
|
||||
? boolean
|
||||
: T[K]['default'];
|
||||
};
|
||||
|
||||
export type Settings = InferSettings<typeof SETTINGS_SCHEMA>;
|
||||
@@ -7,7 +7,7 @@
|
||||
import React from 'react';
|
||||
import { render } from 'ink';
|
||||
import { AppWrapper } from './ui/App.js';
|
||||
import { loadCliConfig, parseArguments, CliArgs } from './config/config.js';
|
||||
import { loadCliConfig, parseArguments } from './config/config.js';
|
||||
import { readStdin } from './utils/readStdin.js';
|
||||
import { basename } from 'node:path';
|
||||
import v8 from 'node:v8';
|
||||
@@ -25,19 +25,18 @@ import { themeManager } from './ui/themes/theme-manager.js';
|
||||
import { getStartupWarnings } from './utils/startupWarnings.js';
|
||||
import { getUserStartupWarnings } from './utils/userStartupWarnings.js';
|
||||
import { runNonInteractive } from './nonInteractiveCli.js';
|
||||
import { loadExtensions, Extension } from './config/extension.js';
|
||||
import { loadExtensions } from './config/extension.js';
|
||||
import { cleanupCheckpoints, registerCleanup } from './utils/cleanup.js';
|
||||
import { getCliVersion } from './utils/version.js';
|
||||
import {
|
||||
ApprovalMode,
|
||||
Config,
|
||||
EditTool,
|
||||
ShellTool,
|
||||
WriteFileTool,
|
||||
sessionId,
|
||||
logUserPrompt,
|
||||
AuthType,
|
||||
getOauthClient,
|
||||
logIdeConnection,
|
||||
IdeConnectionEvent,
|
||||
IdeConnectionType,
|
||||
} from '@qwen-code/qwen-code-core';
|
||||
import { validateAuthMethod } from './config/auth.js';
|
||||
import { setMaxSizedBoxDebugging } from './ui/components/shared/MaxSizedBox.js';
|
||||
@@ -45,6 +44,7 @@ import { validateNonInteractiveAuth } from './validateNonInterActiveAuth.js';
|
||||
import { checkForUpdates } from './ui/utils/updateCheck.js';
|
||||
import { handleAutoUpdate } from './utils/handleAutoUpdate.js';
|
||||
import { appEvents, AppEvent } from './utils/events.js';
|
||||
import { SettingsContext } from './ui/contexts/SettingsContext.js';
|
||||
|
||||
export function validateDnsResolutionOrder(
|
||||
order: string | undefined,
|
||||
@@ -191,6 +191,11 @@ export async function main() {
|
||||
|
||||
await config.initialize();
|
||||
|
||||
if (config.getIdeMode() && config.getIdeModeFeature()) {
|
||||
await config.getIdeClient().connect();
|
||||
logIdeConnection(config, new IdeConnectionEvent(IdeConnectionType.START));
|
||||
}
|
||||
|
||||
// Load custom themes from settings
|
||||
themeManager.loadCustomThemes(settings.merged.customThemes);
|
||||
|
||||
@@ -255,21 +260,20 @@ export async function main() {
|
||||
...(await getUserStartupWarnings(workspaceRoot)),
|
||||
];
|
||||
|
||||
const shouldBeInteractive =
|
||||
!!argv.promptInteractive || (process.stdin.isTTY && input?.length === 0);
|
||||
|
||||
// Render UI, passing necessary config values. Check that there is no command line question.
|
||||
if (shouldBeInteractive) {
|
||||
if (config.isInteractive()) {
|
||||
const version = await getCliVersion();
|
||||
setWindowTitle(basename(workspaceRoot), settings);
|
||||
const instance = render(
|
||||
<React.StrictMode>
|
||||
<AppWrapper
|
||||
config={config}
|
||||
settings={settings}
|
||||
startupWarnings={startupWarnings}
|
||||
version={version}
|
||||
/>
|
||||
<SettingsContext.Provider value={settings}>
|
||||
<AppWrapper
|
||||
config={config}
|
||||
settings={settings}
|
||||
startupWarnings={startupWarnings}
|
||||
version={version}
|
||||
/>
|
||||
</SettingsContext.Provider>
|
||||
</React.StrictMode>,
|
||||
{ exitOnCtrlC: false },
|
||||
);
|
||||
@@ -308,12 +312,10 @@ export async function main() {
|
||||
prompt_length: input.length,
|
||||
});
|
||||
|
||||
// Non-interactive mode handled by runNonInteractive
|
||||
const nonInteractiveConfig = await loadNonInteractiveConfig(
|
||||
const nonInteractiveConfig = await validateNonInteractiveAuth(
|
||||
settings.merged.selectedAuthType,
|
||||
settings.merged.useExternalAuth,
|
||||
config,
|
||||
extensions,
|
||||
settings,
|
||||
argv,
|
||||
);
|
||||
|
||||
await runNonInteractive(nonInteractiveConfig, input, prompt_id);
|
||||
@@ -334,43 +336,3 @@ function setWindowTitle(title: string, settings: LoadedSettings) {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function loadNonInteractiveConfig(
|
||||
config: Config,
|
||||
extensions: Extension[],
|
||||
settings: LoadedSettings,
|
||||
argv: CliArgs,
|
||||
) {
|
||||
let finalConfig = config;
|
||||
if (config.getApprovalMode() !== ApprovalMode.YOLO) {
|
||||
// Everything is not allowed, ensure that only read-only tools are configured.
|
||||
const existingExcludeTools = settings.merged.excludeTools || [];
|
||||
const interactiveTools = [
|
||||
ShellTool.Name,
|
||||
EditTool.Name,
|
||||
WriteFileTool.Name,
|
||||
];
|
||||
|
||||
const newExcludeTools = [
|
||||
...new Set([...existingExcludeTools, ...interactiveTools]),
|
||||
];
|
||||
|
||||
const nonInteractiveSettings = {
|
||||
...settings.merged,
|
||||
excludeTools: newExcludeTools,
|
||||
};
|
||||
finalConfig = await loadCliConfig(
|
||||
nonInteractiveSettings,
|
||||
extensions,
|
||||
config.getSessionId(),
|
||||
argv,
|
||||
);
|
||||
await finalConfig.initialize();
|
||||
}
|
||||
|
||||
return await validateNonInteractiveAuth(
|
||||
settings.merged.selectedAuthType,
|
||||
settings.merged.useExternalAuth,
|
||||
finalConfig,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -30,7 +30,6 @@ export async function runNonInteractive(
|
||||
});
|
||||
|
||||
try {
|
||||
await config.initialize();
|
||||
consolePatcher.patch();
|
||||
// Handle EPIPE errors when the output is piped to a command that closes early.
|
||||
process.stdout.on('error', (err: NodeJS.ErrnoException) => {
|
||||
|
||||
@@ -30,9 +30,9 @@ import { restoreCommand } from '../ui/commands/restoreCommand.js';
|
||||
import { statsCommand } from '../ui/commands/statsCommand.js';
|
||||
import { themeCommand } from '../ui/commands/themeCommand.js';
|
||||
import { toolsCommand } from '../ui/commands/toolsCommand.js';
|
||||
import { settingsCommand } from '../ui/commands/settingsCommand.js';
|
||||
import { vimCommand } from '../ui/commands/vimCommand.js';
|
||||
import { setupGithubCommand } from '../ui/commands/setupGithubCommand.js';
|
||||
import { isGitHubRepository } from '../utils/gitUtils.js';
|
||||
|
||||
/**
|
||||
* Loads the core, hard-coded slash commands that are an integral part
|
||||
@@ -73,8 +73,9 @@ export class BuiltinCommandLoader implements ICommandLoader {
|
||||
statsCommand,
|
||||
themeCommand,
|
||||
toolsCommand,
|
||||
settingsCommand,
|
||||
vimCommand,
|
||||
...(isGitHubRepository() ? [setupGithubCommand] : []),
|
||||
setupGithubCommand,
|
||||
];
|
||||
|
||||
return allDefinitions.filter((cmd): cmd is SlashCommand => cmd !== null);
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
SandboxConfig,
|
||||
GeminiClient,
|
||||
ideContext,
|
||||
type AuthType,
|
||||
} from '@qwen-code/qwen-code-core';
|
||||
import { LoadedSettings, SettingsFile, Settings } from '../config/settings.js';
|
||||
import process from 'node:process';
|
||||
@@ -27,6 +28,7 @@ import { checkForUpdates, UpdateObject } from './utils/updateCheck.js';
|
||||
import { EventEmitter } from 'events';
|
||||
import { updateEventEmitter } from '../utils/updateEventEmitter.js';
|
||||
import * as auth from '../config/auth.js';
|
||||
import * as useTerminalSize from './hooks/useTerminalSize.js';
|
||||
|
||||
// Define a more complete mock server config based on actual Config
|
||||
interface MockServerConfig {
|
||||
@@ -84,6 +86,7 @@ interface MockServerConfig {
|
||||
getAllGeminiMdFilenames: Mock<() => string[]>;
|
||||
getGeminiClient: Mock<() => GeminiClient | undefined>;
|
||||
getUserTier: Mock<() => Promise<string | undefined>>;
|
||||
getIdeClient: Mock<() => { getCurrentIde: Mock<() => string | undefined> }>;
|
||||
}
|
||||
|
||||
// Mock @qwen-code/qwen-code-core and its Config class
|
||||
@@ -157,6 +160,9 @@ vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
|
||||
getWorkspaceContext: vi.fn(() => ({
|
||||
getDirectories: vi.fn(() => []),
|
||||
})),
|
||||
getIdeClient: vi.fn(() => ({
|
||||
getCurrentIde: vi.fn(() => 'vscode'),
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -182,6 +188,7 @@ vi.mock('./hooks/useGeminiStream', () => ({
|
||||
submitQuery: vi.fn(),
|
||||
initError: null,
|
||||
pendingHistoryItems: [],
|
||||
thought: null,
|
||||
})),
|
||||
}));
|
||||
|
||||
@@ -196,6 +203,13 @@ vi.mock('./hooks/useAuthCommand', () => ({
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('./hooks/useFolderTrust', () => ({
|
||||
useFolderTrust: vi.fn(() => ({
|
||||
isFolderTrustDialogOpen: false,
|
||||
handleFolderTrustSelect: vi.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('./hooks/useLogger', () => ({
|
||||
useLogger: vi.fn(() => ({
|
||||
getPreviousUserMessages: vi.fn().mockResolvedValue([]),
|
||||
@@ -233,10 +247,14 @@ vi.mock('./utils/updateCheck.js', () => ({
|
||||
checkForUpdates: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('./config/auth.js', () => ({
|
||||
vi.mock('../config/auth.js', () => ({
|
||||
validateAuthMethod: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../hooks/useTerminalSize.js', () => ({
|
||||
useTerminalSize: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockedCheckForUpdates = vi.mocked(checkForUpdates);
|
||||
const { isGitRepository: mockedIsGitRepository } = vi.mocked(
|
||||
await import('@qwen-code/qwen-code-core'),
|
||||
@@ -278,6 +296,11 @@ describe('App UI', () => {
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(useTerminalSize, 'useTerminalSize').mockReturnValue({
|
||||
columns: 120,
|
||||
rows: 24,
|
||||
});
|
||||
|
||||
const ServerConfigMocked = vi.mocked(ServerConfig, true);
|
||||
mockConfig = new ServerConfigMocked({
|
||||
embeddingModel: 'test-embedding-model',
|
||||
@@ -1050,4 +1073,44 @@ describe('App UI', () => {
|
||||
expect(validateAuthMethodSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('when in a narrow terminal', () => {
|
||||
it('should render with a column layout', () => {
|
||||
vi.spyOn(useTerminalSize, 'useTerminalSize').mockReturnValue({
|
||||
columns: 60,
|
||||
rows: 24,
|
||||
});
|
||||
|
||||
const { lastFrame, unmount } = render(
|
||||
<App
|
||||
config={mockConfig as unknown as ServerConfig}
|
||||
settings={mockSettings}
|
||||
version={mockVersion}
|
||||
/>,
|
||||
);
|
||||
currentUnmount = unmount;
|
||||
expect(lastFrame()).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
describe('FolderTrustDialog', () => {
|
||||
it('should display the folder trust dialog when isFolderTrustDialogOpen is true', async () => {
|
||||
const { useFolderTrust } = await import('./hooks/useFolderTrust.js');
|
||||
vi.mocked(useFolderTrust).mockReturnValue({
|
||||
isFolderTrustDialogOpen: true,
|
||||
handleFolderTrustSelect: vi.fn(),
|
||||
});
|
||||
|
||||
const { lastFrame, unmount } = render(
|
||||
<App
|
||||
config={mockConfig as unknown as ServerConfig}
|
||||
settings={mockSettings}
|
||||
version={mockVersion}
|
||||
/>,
|
||||
);
|
||||
currentUnmount = unmount;
|
||||
await Promise.resolve();
|
||||
expect(lastFrame()).toContain('Do you trust this folder?');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,8 +13,6 @@ import {
|
||||
Text,
|
||||
useStdin,
|
||||
useStdout,
|
||||
useInput,
|
||||
type Key as InkKeyType,
|
||||
} from 'ink';
|
||||
import { StreamingState, type HistoryItem, MessageType } from './types.js';
|
||||
import { useTerminalSize } from './hooks/useTerminalSize.js';
|
||||
@@ -23,6 +21,7 @@ import { useLoadingIndicator } from './hooks/useLoadingIndicator.js';
|
||||
import { useThemeCommand } from './hooks/useThemeCommand.js';
|
||||
import { useAuthCommand } from './hooks/useAuthCommand.js';
|
||||
import { useQwenAuth } from './hooks/useQwenAuth.js';
|
||||
import { useFolderTrust } from './hooks/useFolderTrust.js';
|
||||
import { useEditorSettings } from './hooks/useEditorSettings.js';
|
||||
import { useSlashCommandProcessor } from './hooks/slashCommandProcessor.js';
|
||||
import { useAutoAcceptIndicator } from './hooks/useAutoAcceptIndicator.js';
|
||||
@@ -38,17 +37,18 @@ import { AuthDialog } from './components/AuthDialog.js';
|
||||
import { AuthInProgress } from './components/AuthInProgress.js';
|
||||
import { QwenOAuthProgress } from './components/QwenOAuthProgress.js';
|
||||
import { EditorSettingsDialog } from './components/EditorSettingsDialog.js';
|
||||
import { FolderTrustDialog } from './components/FolderTrustDialog.js';
|
||||
import { ShellConfirmationDialog } from './components/ShellConfirmationDialog.js';
|
||||
import { RadioButtonSelect } from './components/shared/RadioButtonSelect.js';
|
||||
import { Colors } from './colors.js';
|
||||
import { loadHierarchicalGeminiMemory } from '../config/config.js';
|
||||
import { LoadedSettings } from '../config/settings.js';
|
||||
import { LoadedSettings, SettingScope } from '../config/settings.js';
|
||||
import { Tips } from './components/Tips.js';
|
||||
import { ConsolePatcher } from './utils/ConsolePatcher.js';
|
||||
import { registerCleanup } from '../utils/cleanup.js';
|
||||
import { DetailedMessagesDisplay } from './components/DetailedMessagesDisplay.js';
|
||||
import { HistoryItemDisplay } from './components/HistoryItemDisplay.js';
|
||||
import { ContextSummaryDisplay } from './components/ContextSummaryDisplay.js';
|
||||
import { IDEContextDetailDisplay } from './components/IDEContextDetailDisplay.js';
|
||||
import { useHistory } from './hooks/useHistoryManager.js';
|
||||
import process from 'node:process';
|
||||
import {
|
||||
@@ -64,6 +64,10 @@ import {
|
||||
type IdeContext,
|
||||
ideContext,
|
||||
} from '@qwen-code/qwen-code-core';
|
||||
import {
|
||||
IdeIntegrationNudge,
|
||||
IdeIntegrationNudgeResult,
|
||||
} from './IdeIntegrationNudge.js';
|
||||
import { validateAuthMethod } from '../config/auth.js';
|
||||
import { useLogger } from './hooks/useLogger.js';
|
||||
import { StreamingContext } from './contexts/StreamingContext.js';
|
||||
@@ -77,6 +81,8 @@ import { useBracketedPaste } from './hooks/useBracketedPaste.js';
|
||||
import { useTextBuffer } from './components/shared/text-buffer.js';
|
||||
import { useVimMode, VimModeProvider } from './contexts/VimModeContext.js';
|
||||
import { useVim } from './hooks/vim.js';
|
||||
import { useKeypress, Key } from './hooks/useKeypress.js';
|
||||
import { keyMatchers, Command } from './keyMatchers.js';
|
||||
import * as fs from 'fs';
|
||||
import { UpdateNotification } from './components/UpdateNotification.js';
|
||||
import {
|
||||
@@ -89,8 +95,11 @@ import ansiEscapes from 'ansi-escapes';
|
||||
import { OverflowProvider } from './contexts/OverflowContext.js';
|
||||
import { ShowMoreLines } from './components/ShowMoreLines.js';
|
||||
import { PrivacyNotice } from './privacy/PrivacyNotice.js';
|
||||
import { useSettingsCommand } from './hooks/useSettingsCommand.js';
|
||||
import { SettingsDialog } from './components/SettingsDialog.js';
|
||||
import { setUpdateHandler } from '../utils/handleAutoUpdate.js';
|
||||
import { appEvents, AppEvent } from '../utils/events.js';
|
||||
import { isNarrowWidth } from './utils/isNarrowWidth.js';
|
||||
|
||||
const CTRL_EXIT_PROMPT_DURATION_MS = 1000;
|
||||
|
||||
@@ -117,6 +126,18 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
const nightly = version.includes('nightly');
|
||||
const { history, addItem, clearItems, loadHistory } = useHistory();
|
||||
|
||||
const [idePromptAnswered, setIdePromptAnswered] = useState(false);
|
||||
const currentIDE = config.getIdeClient().getCurrentIde();
|
||||
useEffect(() => {
|
||||
registerCleanup(() => config.getIdeClient().disconnect());
|
||||
}, [config]);
|
||||
const shouldShowIdePrompt =
|
||||
config.getIdeModeFeature() &&
|
||||
currentIDE &&
|
||||
!config.getIdeMode() &&
|
||||
!settings.merged.hasSeenIdeIntegrationNudge &&
|
||||
!idePromptAnswered;
|
||||
|
||||
useEffect(() => {
|
||||
const cleanup = setUpdateHandler(addItem, setUpdateInfo);
|
||||
return cleanup;
|
||||
@@ -157,8 +178,7 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
const [showErrorDetails, setShowErrorDetails] = useState<boolean>(false);
|
||||
const [showToolDescriptions, setShowToolDescriptions] =
|
||||
useState<boolean>(false);
|
||||
const [showIDEContextDetail, setShowIDEContextDetail] =
|
||||
useState<boolean>(false);
|
||||
|
||||
const [ctrlCPressedOnce, setCtrlCPressedOnce] = useState(false);
|
||||
const [quittingMessages, setQuittingMessages] = useState<
|
||||
HistoryItem[] | null
|
||||
@@ -174,6 +194,7 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
const [ideContextState, setIdeContextState] = useState<
|
||||
IdeContext | undefined
|
||||
>();
|
||||
const [showEscapePrompt, setShowEscapePrompt] = useState(false);
|
||||
const [isProcessing, setIsProcessing] = useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -208,6 +229,11 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
const openPrivacyNotice = useCallback(() => {
|
||||
setShowPrivacyNotice(true);
|
||||
}, []);
|
||||
|
||||
const handleEscapePromptChange = useCallback((showPrompt: boolean) => {
|
||||
setShowEscapePrompt(showPrompt);
|
||||
}, []);
|
||||
|
||||
const initialPromptSubmitted = useRef(false);
|
||||
|
||||
const errorCount = useMemo(
|
||||
@@ -225,6 +251,12 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
handleThemeHighlight,
|
||||
} = useThemeCommand(settings, setThemeError, addItem);
|
||||
|
||||
const { isSettingsDialogOpen, openSettingsDialog, closeSettingsDialog } =
|
||||
useSettingsCommand();
|
||||
|
||||
const { isFolderTrustDialogOpen, handleFolderTrustSelect } =
|
||||
useFolderTrust(settings);
|
||||
|
||||
const {
|
||||
isAuthDialogOpen,
|
||||
openAuthDialog,
|
||||
@@ -452,6 +484,7 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
|
||||
// Terminal and UI setup
|
||||
const { rows: terminalHeight, columns: terminalWidth } = useTerminalSize();
|
||||
const isNarrow = isNarrowWidth(terminalWidth);
|
||||
const { stdin, setRawMode } = useStdin();
|
||||
const isInitialMount = useRef(true);
|
||||
|
||||
@@ -460,7 +493,7 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
20,
|
||||
Math.floor(terminalWidth * widthFraction) - 3,
|
||||
);
|
||||
const suggestionsWidth = Math.max(60, Math.floor(terminalWidth * 0.8));
|
||||
const suggestionsWidth = Math.max(20, Math.floor(terminalWidth * 0.8));
|
||||
|
||||
// Utility callbacks
|
||||
const isValidPath = useCallback((filePath: string): boolean => {
|
||||
@@ -499,6 +532,7 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
pendingHistoryItems: pendingSlashCommandHistoryItems,
|
||||
commandContext,
|
||||
shellConfirmationRequest,
|
||||
confirmationRequest,
|
||||
} = useSlashCommandProcessor(
|
||||
config,
|
||||
settings,
|
||||
@@ -513,17 +547,37 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
toggleCorgiMode,
|
||||
setQuittingMessages,
|
||||
openPrivacyNotice,
|
||||
openSettingsDialog,
|
||||
toggleVimEnabled,
|
||||
setIsProcessing,
|
||||
setGeminiMdFileCount,
|
||||
);
|
||||
|
||||
const buffer = useTextBuffer({
|
||||
initialText: '',
|
||||
viewport: { height: 10, width: inputWidth },
|
||||
stdin,
|
||||
setRawMode,
|
||||
isValidPath,
|
||||
shellModeActive,
|
||||
});
|
||||
|
||||
const [userMessages, setUserMessages] = useState<string[]>([]);
|
||||
|
||||
const handleUserCancel = useCallback(() => {
|
||||
const lastUserMessage = userMessages.at(-1);
|
||||
if (lastUserMessage) {
|
||||
buffer.setText(lastUserMessage);
|
||||
}
|
||||
}, [buffer, userMessages]);
|
||||
|
||||
const {
|
||||
streamingState,
|
||||
submitQuery,
|
||||
initError,
|
||||
pendingHistoryItems: pendingGeminiHistoryItems,
|
||||
thought,
|
||||
cancelOngoingRequest,
|
||||
} = useGeminiStream(
|
||||
config.getGeminiClient(),
|
||||
history,
|
||||
@@ -538,6 +592,7 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
modelSwitchedFromQuotaError,
|
||||
setModelSwitchedFromQuotaError,
|
||||
refreshStatic,
|
||||
handleUserCancel,
|
||||
);
|
||||
|
||||
// Input handling
|
||||
@@ -551,14 +606,26 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
[submitQuery],
|
||||
);
|
||||
|
||||
const buffer = useTextBuffer({
|
||||
initialText: '',
|
||||
viewport: { height: 10, width: inputWidth },
|
||||
stdin,
|
||||
setRawMode,
|
||||
isValidPath,
|
||||
shellModeActive,
|
||||
});
|
||||
const handleIdePromptComplete = useCallback(
|
||||
(result: IdeIntegrationNudgeResult) => {
|
||||
if (result === 'yes') {
|
||||
handleSlashCommand('/ide install');
|
||||
settings.setValue(
|
||||
SettingScope.User,
|
||||
'hasSeenIdeIntegrationNudge',
|
||||
true,
|
||||
);
|
||||
} else if (result === 'dismiss') {
|
||||
settings.setValue(
|
||||
SettingScope.User,
|
||||
'hasSeenIdeIntegrationNudge',
|
||||
true,
|
||||
);
|
||||
}
|
||||
setIdePromptAnswered(true);
|
||||
},
|
||||
[handleSlashCommand, settings],
|
||||
);
|
||||
|
||||
const { handleInput: vimHandleInput } = useVim(buffer, handleFinalSubmit);
|
||||
const pendingHistoryItems = [...pendingSlashCommandHistoryItems];
|
||||
@@ -591,46 +658,75 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
[handleSlashCommand],
|
||||
);
|
||||
|
||||
useInput((input: string, key: InkKeyType) => {
|
||||
let enteringConstrainHeightMode = false;
|
||||
if (!constrainHeight) {
|
||||
// Automatically re-enter constrain height mode if the user types
|
||||
// anything. When constrainHeight==false, the user will experience
|
||||
// significant flickering so it is best to disable it immediately when
|
||||
// the user starts interacting with the app.
|
||||
enteringConstrainHeightMode = true;
|
||||
setConstrainHeight(true);
|
||||
}
|
||||
|
||||
if (key.ctrl && input === 'o') {
|
||||
setShowErrorDetails((prev) => !prev);
|
||||
} else if (key.ctrl && input === 't') {
|
||||
const newValue = !showToolDescriptions;
|
||||
setShowToolDescriptions(newValue);
|
||||
|
||||
const mcpServers = config.getMcpServers();
|
||||
if (Object.keys(mcpServers || {}).length > 0) {
|
||||
handleSlashCommand(newValue ? '/mcp desc' : '/mcp nodesc');
|
||||
const handleGlobalKeypress = useCallback(
|
||||
(key: Key) => {
|
||||
let enteringConstrainHeightMode = false;
|
||||
if (!constrainHeight) {
|
||||
enteringConstrainHeightMode = true;
|
||||
setConstrainHeight(true);
|
||||
}
|
||||
} else if (
|
||||
key.ctrl &&
|
||||
input === 'e' &&
|
||||
config.getIdeMode() &&
|
||||
ideContextState
|
||||
) {
|
||||
setShowIDEContextDetail((prev) => !prev);
|
||||
} else if (key.ctrl && (input === 'c' || input === 'C')) {
|
||||
handleExit(ctrlCPressedOnce, setCtrlCPressedOnce, ctrlCTimerRef);
|
||||
} else if (key.ctrl && (input === 'd' || input === 'D')) {
|
||||
if (buffer.text.length > 0) {
|
||||
// Do nothing if there is text in the input.
|
||||
return;
|
||||
|
||||
if (keyMatchers[Command.SHOW_ERROR_DETAILS](key)) {
|
||||
setShowErrorDetails((prev) => !prev);
|
||||
} else if (keyMatchers[Command.TOGGLE_TOOL_DESCRIPTIONS](key)) {
|
||||
const newValue = !showToolDescriptions;
|
||||
setShowToolDescriptions(newValue);
|
||||
|
||||
const mcpServers = config.getMcpServers();
|
||||
if (Object.keys(mcpServers || {}).length > 0) {
|
||||
handleSlashCommand(newValue ? '/mcp desc' : '/mcp nodesc');
|
||||
}
|
||||
} else if (
|
||||
keyMatchers[Command.TOGGLE_IDE_CONTEXT_DETAIL](key) &&
|
||||
config.getIdeMode() &&
|
||||
ideContextState
|
||||
) {
|
||||
// Show IDE status when in IDE mode and context is available.
|
||||
handleSlashCommand('/ide status');
|
||||
} else if (keyMatchers[Command.QUIT](key)) {
|
||||
// When authenticating, let AuthInProgress component handle Ctrl+C.
|
||||
if (isAuthenticating) {
|
||||
return;
|
||||
}
|
||||
if (!ctrlCPressedOnce) {
|
||||
cancelOngoingRequest?.();
|
||||
}
|
||||
handleExit(ctrlCPressedOnce, setCtrlCPressedOnce, ctrlCTimerRef);
|
||||
} else if (keyMatchers[Command.EXIT](key)) {
|
||||
if (buffer.text.length > 0) {
|
||||
return;
|
||||
}
|
||||
handleExit(ctrlDPressedOnce, setCtrlDPressedOnce, ctrlDTimerRef);
|
||||
} else if (
|
||||
keyMatchers[Command.SHOW_MORE_LINES](key) &&
|
||||
!enteringConstrainHeightMode
|
||||
) {
|
||||
setConstrainHeight(false);
|
||||
}
|
||||
handleExit(ctrlDPressedOnce, setCtrlDPressedOnce, ctrlDTimerRef);
|
||||
} else if (key.ctrl && input === 's' && !enteringConstrainHeightMode) {
|
||||
setConstrainHeight(false);
|
||||
}
|
||||
});
|
||||
},
|
||||
[
|
||||
constrainHeight,
|
||||
setConstrainHeight,
|
||||
setShowErrorDetails,
|
||||
showToolDescriptions,
|
||||
setShowToolDescriptions,
|
||||
config,
|
||||
ideContextState,
|
||||
handleExit,
|
||||
ctrlCPressedOnce,
|
||||
setCtrlCPressedOnce,
|
||||
ctrlCTimerRef,
|
||||
buffer.text.length,
|
||||
ctrlDPressedOnce,
|
||||
setCtrlDPressedOnce,
|
||||
ctrlDTimerRef,
|
||||
handleSlashCommand,
|
||||
isAuthenticating,
|
||||
cancelOngoingRequest,
|
||||
],
|
||||
);
|
||||
|
||||
useKeypress(handleGlobalKeypress, { isActive: true });
|
||||
|
||||
useEffect(() => {
|
||||
if (config) {
|
||||
@@ -639,7 +735,6 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
}, [config, config.getGeminiMdFileCount]);
|
||||
|
||||
const logger = useLogger();
|
||||
const [userMessages, setUserMessages] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchUserMessages = async () => {
|
||||
@@ -791,6 +886,7 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const mainAreaWidth = Math.floor(terminalWidth * 0.9);
|
||||
const debugConsoleMaxHeight = Math.floor(Math.max(terminalHeight * 0.2, 5));
|
||||
// Arbitrary threshold to ensure that items in the static area are large
|
||||
@@ -819,11 +915,7 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
items={[
|
||||
<Box flexDirection="column" key="header">
|
||||
{!settings.merged.hideBanner && (
|
||||
<Header
|
||||
terminalWidth={terminalWidth}
|
||||
version={version}
|
||||
nightly={nightly}
|
||||
/>
|
||||
<Header version={version} nightly={nightly} />
|
||||
)}
|
||||
{!settings.merged.hideTips && <Tips config={config} />}
|
||||
</Box>,
|
||||
@@ -882,8 +974,30 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{shellConfirmationRequest ? (
|
||||
{shouldShowIdePrompt ? (
|
||||
<IdeIntegrationNudge
|
||||
ideName={config.getIdeClient().getDetectedIdeDisplayName()}
|
||||
onComplete={handleIdePromptComplete}
|
||||
/>
|
||||
) : isFolderTrustDialogOpen ? (
|
||||
<FolderTrustDialog onSelect={handleFolderTrustSelect} />
|
||||
) : shellConfirmationRequest ? (
|
||||
<ShellConfirmationDialog request={shellConfirmationRequest} />
|
||||
) : confirmationRequest ? (
|
||||
<Box flexDirection="column">
|
||||
{confirmationRequest.prompt}
|
||||
<Box paddingY={1}>
|
||||
<RadioButtonSelect
|
||||
items={[
|
||||
{ label: 'Yes', value: true },
|
||||
{ label: 'No', value: false },
|
||||
]}
|
||||
onSelect={(value: boolean) => {
|
||||
confirmationRequest.onConfirm(value);
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
) : isThemeDialogOpen ? (
|
||||
<Box flexDirection="column">
|
||||
{themeError && (
|
||||
@@ -903,6 +1017,14 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
terminalWidth={mainAreaWidth}
|
||||
/>
|
||||
</Box>
|
||||
) : isSettingsDialogOpen ? (
|
||||
<Box flexDirection="column">
|
||||
<SettingsDialog
|
||||
settings={settings}
|
||||
onSelect={() => closeSettingsDialog()}
|
||||
onRestartRequest={() => process.exit(0)}
|
||||
/>
|
||||
</Box>
|
||||
) : isAuthenticating ? (
|
||||
<>
|
||||
{isQwenAuth && isQwenAuthenticating ? (
|
||||
@@ -994,9 +1116,10 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
|
||||
<Box
|
||||
marginTop={1}
|
||||
display="flex"
|
||||
justifyContent="space-between"
|
||||
width="100%"
|
||||
flexDirection={isNarrow ? 'column' : 'row'}
|
||||
alignItems={isNarrow ? 'flex-start' : 'center'}
|
||||
>
|
||||
<Box>
|
||||
{process.env.GEMINI_SYSTEM_MD && (
|
||||
@@ -1010,6 +1133,8 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
<Text color={Colors.AccentYellow}>
|
||||
Press Ctrl+D again to exit.
|
||||
</Text>
|
||||
) : showEscapePrompt ? (
|
||||
<Text color={Colors.Gray}>Press Esc again to clear.</Text>
|
||||
) : (
|
||||
<ContextSummaryDisplay
|
||||
ideContext={ideContextState}
|
||||
@@ -1021,7 +1146,7 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
<Box>
|
||||
<Box paddingTop={isNarrow ? 1 : 0}>
|
||||
{showAutoAcceptIndicator !== ApprovalMode.DEFAULT &&
|
||||
!shellModeActive && (
|
||||
<AutoAcceptIndicator
|
||||
@@ -1031,14 +1156,7 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
{shellModeActive && <ShellModeIndicator />}
|
||||
</Box>
|
||||
</Box>
|
||||
{showIDEContextDetail && (
|
||||
<IDEContextDetailDisplay
|
||||
ideContext={ideContextState}
|
||||
detectedIdeDisplay={config
|
||||
.getIdeClient()
|
||||
.getDetectedIdeDisplayName()}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showErrorDetails && (
|
||||
<OverflowProvider>
|
||||
<Box flexDirection="column">
|
||||
@@ -1067,6 +1185,7 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
commandContext={commandContext}
|
||||
shellModeActive={shellModeActive}
|
||||
setShellModeActive={setShellModeActive}
|
||||
onEscapePromptChange={handleEscapePromptChange}
|
||||
focus={isFocused}
|
||||
vimHandleInput={vimHandleInput}
|
||||
placeholder={placeholder}
|
||||
@@ -1117,7 +1236,7 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
|
||||
errorCount={errorCount}
|
||||
showErrorDetails={showErrorDetails}
|
||||
showMemoryUsage={
|
||||
config.getDebugMode() || config.getShowMemoryUsage()
|
||||
config.getDebugMode() || settings.merged.showMemoryUsage || false
|
||||
}
|
||||
promptTokenCount={sessionStats.lastPromptTokenCount}
|
||||
nightly={nightly}
|
||||
|
||||
70
packages/cli/src/ui/IdeIntegrationNudge.tsx
Normal file
70
packages/cli/src/ui/IdeIntegrationNudge.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import {
|
||||
RadioButtonSelect,
|
||||
RadioSelectItem,
|
||||
} from './components/shared/RadioButtonSelect.js';
|
||||
|
||||
export type IdeIntegrationNudgeResult = 'yes' | 'no' | 'dismiss';
|
||||
|
||||
interface IdeIntegrationNudgeProps {
|
||||
ideName?: string;
|
||||
onComplete: (result: IdeIntegrationNudgeResult) => void;
|
||||
}
|
||||
|
||||
export function IdeIntegrationNudge({
|
||||
ideName,
|
||||
onComplete,
|
||||
}: IdeIntegrationNudgeProps) {
|
||||
useInput((_input, key) => {
|
||||
if (key.escape) {
|
||||
onComplete('no');
|
||||
}
|
||||
});
|
||||
|
||||
const OPTIONS: Array<RadioSelectItem<IdeIntegrationNudgeResult>> = [
|
||||
{
|
||||
label: 'Yes',
|
||||
value: 'yes',
|
||||
},
|
||||
{
|
||||
label: 'No (esc)',
|
||||
value: 'no',
|
||||
},
|
||||
{
|
||||
label: "No, don't ask again",
|
||||
value: 'dismiss',
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
borderStyle="round"
|
||||
borderColor="yellow"
|
||||
padding={1}
|
||||
width="100%"
|
||||
marginLeft={1}
|
||||
>
|
||||
<Box marginBottom={1} flexDirection="column">
|
||||
<Text>
|
||||
<Text color="yellow">{'> '}</Text>
|
||||
{`Do you want to connect your ${ideName ?? 'your'} editor to Gemini CLI?`}
|
||||
</Text>
|
||||
<Text
|
||||
dimColor
|
||||
>{`If you select Yes, we'll install an extension that allows the CLI to access your open files and display diffs directly in ${ideName ?? 'your editor'}.`}</Text>
|
||||
</Box>
|
||||
<RadioButtonSelect
|
||||
items={OPTIONS}
|
||||
onSelect={onComplete}
|
||||
isFocused={true}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -10,9 +10,22 @@ exports[`App UI > should render correctly with the prompt input box 1`] = `
|
||||
`;
|
||||
|
||||
exports[`App UI > should render the initial UI correctly 1`] = `
|
||||
"
|
||||
I'm Feeling Lucky (esc to cancel, 0s)
|
||||
" I'm Feeling Lucky (esc to cancel, 0s)
|
||||
|
||||
|
||||
/test/dir no sandbox (see /docs) model (100% context left)"
|
||||
`;
|
||||
|
||||
exports[`App UI > when in a narrow terminal > should render with a column layout 1`] = `
|
||||
"
|
||||
|
||||
|
||||
╭────────────────────────────────────────────────────────────────────────────────────────╮
|
||||
│ > Type your message or @path/to/file │
|
||||
╰────────────────────────────────────────────────────────────────────────────────────────╯
|
||||
dir
|
||||
|
||||
no sandbox (see /docs)
|
||||
|
||||
model (100% context left)| ✖ 5 errors (ctrl+o for details)"
|
||||
`;
|
||||
|
||||
@@ -168,8 +168,12 @@ describe('chatCommand', () => {
|
||||
describe('save subcommand', () => {
|
||||
let saveCommand: SlashCommand;
|
||||
const tag = 'my-tag';
|
||||
let mockCheckpointExists: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
saveCommand = getSubCommand('save');
|
||||
mockCheckpointExists = vi.fn().mockResolvedValue(false);
|
||||
mockContext.services.logger.checkpointExists = mockCheckpointExists;
|
||||
});
|
||||
|
||||
it('should return an error if tag is missing', async () => {
|
||||
@@ -191,7 +195,7 @@ describe('chatCommand', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should save the conversation', async () => {
|
||||
it('should save the conversation if checkpoint does not exist', async () => {
|
||||
const history: HistoryItemWithoutId[] = [
|
||||
{
|
||||
type: 'user',
|
||||
@@ -199,8 +203,52 @@ describe('chatCommand', () => {
|
||||
},
|
||||
];
|
||||
mockGetHistory.mockReturnValue(history);
|
||||
mockCheckpointExists.mockResolvedValue(false);
|
||||
|
||||
const result = await saveCommand?.action?.(mockContext, tag);
|
||||
|
||||
expect(mockCheckpointExists).toHaveBeenCalledWith(tag);
|
||||
expect(mockSaveCheckpoint).toHaveBeenCalledWith(history, tag);
|
||||
expect(result).toEqual({
|
||||
type: 'message',
|
||||
messageType: 'info',
|
||||
content: `Conversation checkpoint saved with tag: ${tag}.`,
|
||||
});
|
||||
});
|
||||
|
||||
it('should return confirm_action if checkpoint already exists', async () => {
|
||||
mockCheckpointExists.mockResolvedValue(true);
|
||||
mockContext.invocation = {
|
||||
raw: `/chat save ${tag}`,
|
||||
name: 'save',
|
||||
args: tag,
|
||||
};
|
||||
|
||||
const result = await saveCommand?.action?.(mockContext, tag);
|
||||
|
||||
expect(mockCheckpointExists).toHaveBeenCalledWith(tag);
|
||||
expect(mockSaveCheckpoint).not.toHaveBeenCalled();
|
||||
expect(result).toMatchObject({
|
||||
type: 'confirm_action',
|
||||
originalInvocation: { raw: `/chat save ${tag}` },
|
||||
});
|
||||
// Check that prompt is a React element
|
||||
expect(result).toHaveProperty('prompt');
|
||||
});
|
||||
|
||||
it('should save the conversation if overwrite is confirmed', async () => {
|
||||
const history: HistoryItemWithoutId[] = [
|
||||
{
|
||||
type: 'user',
|
||||
text: 'hello',
|
||||
},
|
||||
];
|
||||
mockGetHistory.mockReturnValue(history);
|
||||
mockContext.overwriteConfirmed = true;
|
||||
|
||||
const result = await saveCommand?.action?.(mockContext, tag);
|
||||
|
||||
expect(mockCheckpointExists).not.toHaveBeenCalled(); // Should skip existence check
|
||||
expect(mockSaveCheckpoint).toHaveBeenCalledWith(history, tag);
|
||||
expect(result).toEqual({
|
||||
type: 'message',
|
||||
|
||||
@@ -5,11 +5,15 @@
|
||||
*/
|
||||
|
||||
import * as fsPromises from 'fs/promises';
|
||||
import React from 'react';
|
||||
import { Text } from 'ink';
|
||||
import { Colors } from '../colors.js';
|
||||
import {
|
||||
CommandContext,
|
||||
SlashCommand,
|
||||
MessageActionReturn,
|
||||
CommandKind,
|
||||
SlashCommandActionReturn,
|
||||
} from './types.js';
|
||||
import path from 'path';
|
||||
import { HistoryItemWithoutId, MessageType } from '../types.js';
|
||||
@@ -96,7 +100,7 @@ const saveCommand: SlashCommand = {
|
||||
description:
|
||||
'Save the current conversation as a checkpoint. Usage: /chat save <tag>',
|
||||
kind: CommandKind.BUILT_IN,
|
||||
action: async (context, args): Promise<MessageActionReturn> => {
|
||||
action: async (context, args): Promise<SlashCommandActionReturn | void> => {
|
||||
const tag = args.trim();
|
||||
if (!tag) {
|
||||
return {
|
||||
@@ -108,6 +112,26 @@ const saveCommand: SlashCommand = {
|
||||
|
||||
const { logger, config } = context.services;
|
||||
await logger.initialize();
|
||||
|
||||
if (!context.overwriteConfirmed) {
|
||||
const exists = await logger.checkpointExists(tag);
|
||||
if (exists) {
|
||||
return {
|
||||
type: 'confirm_action',
|
||||
prompt: React.createElement(
|
||||
Text,
|
||||
null,
|
||||
'A checkpoint with the tag ',
|
||||
React.createElement(Text, { color: Colors.AccentPurple }, tag),
|
||||
' already exists. Do you want to overwrite it?',
|
||||
),
|
||||
originalInvocation: {
|
||||
raw: context.invocation?.raw || `/chat save ${tag}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const chat = await config?.getGeminiClient()?.getChat();
|
||||
if (!chat) {
|
||||
return {
|
||||
|
||||
@@ -93,13 +93,14 @@ describe('ideCommand', () => {
|
||||
} as unknown as ReturnType<Config['getIdeClient']>);
|
||||
});
|
||||
|
||||
it('should show connected status', () => {
|
||||
it('should show connected status', async () => {
|
||||
mockGetConnectionStatus.mockReturnValue({
|
||||
status: core.IDEConnectionStatus.Connected,
|
||||
});
|
||||
const command = ideCommand(mockConfig);
|
||||
const result = command!.subCommands!.find((c) => c.name === 'status')!
|
||||
.action!(mockContext, '');
|
||||
const result = await command!.subCommands!.find(
|
||||
(c) => c.name === 'status',
|
||||
)!.action!(mockContext, '');
|
||||
expect(mockGetConnectionStatus).toHaveBeenCalled();
|
||||
expect(result).toEqual({
|
||||
type: 'message',
|
||||
@@ -108,13 +109,14 @@ describe('ideCommand', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should show connecting status', () => {
|
||||
it('should show connecting status', async () => {
|
||||
mockGetConnectionStatus.mockReturnValue({
|
||||
status: core.IDEConnectionStatus.Connecting,
|
||||
});
|
||||
const command = ideCommand(mockConfig);
|
||||
const result = command!.subCommands!.find((c) => c.name === 'status')!
|
||||
.action!(mockContext, '');
|
||||
const result = await command!.subCommands!.find(
|
||||
(c) => c.name === 'status',
|
||||
)!.action!(mockContext, '');
|
||||
expect(mockGetConnectionStatus).toHaveBeenCalled();
|
||||
expect(result).toEqual({
|
||||
type: 'message',
|
||||
@@ -122,13 +124,14 @@ describe('ideCommand', () => {
|
||||
content: `🟡 Connecting...`,
|
||||
});
|
||||
});
|
||||
it('should show disconnected status', () => {
|
||||
it('should show disconnected status', async () => {
|
||||
mockGetConnectionStatus.mockReturnValue({
|
||||
status: core.IDEConnectionStatus.Disconnected,
|
||||
});
|
||||
const command = ideCommand(mockConfig);
|
||||
const result = command!.subCommands!.find((c) => c.name === 'status')!
|
||||
.action!(mockContext, '');
|
||||
const result = await command!.subCommands!.find(
|
||||
(c) => c.name === 'status',
|
||||
)!.action!(mockContext, '');
|
||||
expect(mockGetConnectionStatus).toHaveBeenCalled();
|
||||
expect(result).toEqual({
|
||||
type: 'message',
|
||||
@@ -137,15 +140,16 @@ describe('ideCommand', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should show disconnected status with details', () => {
|
||||
it('should show disconnected status with details', async () => {
|
||||
const details = 'Something went wrong';
|
||||
mockGetConnectionStatus.mockReturnValue({
|
||||
status: core.IDEConnectionStatus.Disconnected,
|
||||
details,
|
||||
});
|
||||
const command = ideCommand(mockConfig);
|
||||
const result = command!.subCommands!.find((c) => c.name === 'status')!
|
||||
.action!(mockContext, '');
|
||||
const result = await command!.subCommands!.find(
|
||||
(c) => c.name === 'status',
|
||||
)!.action!(mockContext, '');
|
||||
expect(mockGetConnectionStatus).toHaveBeenCalled();
|
||||
expect(result).toEqual({
|
||||
type: 'message',
|
||||
|
||||
@@ -7,11 +7,15 @@
|
||||
import {
|
||||
Config,
|
||||
DetectedIde,
|
||||
QWEN_CODE_COMPANION_EXTENSION_NAME,
|
||||
IDEConnectionStatus,
|
||||
IdeClient,
|
||||
getIdeDisplayName,
|
||||
getIdeInstaller,
|
||||
IdeClient,
|
||||
type File,
|
||||
ideContext,
|
||||
} from '@qwen-code/qwen-code-core';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
CommandContext,
|
||||
SlashCommand,
|
||||
@@ -49,6 +53,68 @@ function getIdeStatusMessage(ideClient: IdeClient): {
|
||||
}
|
||||
}
|
||||
|
||||
function formatFileList(openFiles: File[]): string {
|
||||
const basenameCounts = new Map<string, number>();
|
||||
for (const file of openFiles) {
|
||||
const basename = path.basename(file.path);
|
||||
basenameCounts.set(basename, (basenameCounts.get(basename) || 0) + 1);
|
||||
}
|
||||
|
||||
const fileList = openFiles
|
||||
.map((file: File) => {
|
||||
const basename = path.basename(file.path);
|
||||
const isDuplicate = (basenameCounts.get(basename) || 0) > 1;
|
||||
const parentDir = path.basename(path.dirname(file.path));
|
||||
const displayName = isDuplicate
|
||||
? `${basename} (/${parentDir})`
|
||||
: basename;
|
||||
|
||||
return ` - ${displayName}${file.isActive ? ' (active)' : ''}`;
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
const infoMessage = `
|
||||
(Note: The file list is limited to a number of recently accessed files within your workspace and only includes local files on disk)`;
|
||||
|
||||
return `\n\nOpen files:\n${fileList}\n${infoMessage}`;
|
||||
}
|
||||
|
||||
async function getIdeStatusMessageWithFiles(ideClient: IdeClient): Promise<{
|
||||
messageType: 'info' | 'error';
|
||||
content: string;
|
||||
}> {
|
||||
const connection = ideClient.getConnectionStatus();
|
||||
switch (connection.status) {
|
||||
case IDEConnectionStatus.Connected: {
|
||||
let content = `🟢 Connected to ${ideClient.getDetectedIdeDisplayName()}`;
|
||||
const context = ideContext.getIdeContext();
|
||||
const openFiles = context?.workspaceState?.openFiles;
|
||||
if (openFiles && openFiles.length > 0) {
|
||||
content += formatFileList(openFiles);
|
||||
}
|
||||
return {
|
||||
messageType: 'info',
|
||||
content,
|
||||
};
|
||||
}
|
||||
case IDEConnectionStatus.Connecting:
|
||||
return {
|
||||
messageType: 'info',
|
||||
content: `🟡 Connecting...`,
|
||||
};
|
||||
default: {
|
||||
let content = `🔴 Disconnected`;
|
||||
if (connection?.details) {
|
||||
content += `: ${connection.details}`;
|
||||
}
|
||||
return {
|
||||
messageType: 'error',
|
||||
content,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const ideCommand = (config: Config | null): SlashCommand | null => {
|
||||
if (!config || !config.getIdeModeFeature()) {
|
||||
return null;
|
||||
@@ -84,8 +150,9 @@ export const ideCommand = (config: Config | null): SlashCommand | null => {
|
||||
name: 'status',
|
||||
description: 'check status of IDE integration',
|
||||
kind: CommandKind.BUILT_IN,
|
||||
action: (): SlashCommandActionReturn => {
|
||||
const { messageType, content } = getIdeStatusMessage(ideClient);
|
||||
action: async (): Promise<SlashCommandActionReturn> => {
|
||||
const { messageType, content } =
|
||||
await getIdeStatusMessageWithFiles(ideClient);
|
||||
return {
|
||||
type: 'message',
|
||||
messageType,
|
||||
@@ -104,7 +171,7 @@ export const ideCommand = (config: Config | null): SlashCommand | null => {
|
||||
context.ui.addItem(
|
||||
{
|
||||
type: 'error',
|
||||
text: `No installer is available for ${ideClient.getDetectedIdeDisplayName()}. Please install the IDE companion manually from its marketplace.`,
|
||||
text: `No installer is available for ${ideClient.getDetectedIdeDisplayName()}. Please install the '${QWEN_CODE_COMPANION_EXTENSION_NAME}' extension manually from the marketplace.`,
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
|
||||
36
packages/cli/src/ui/commands/settingsCommand.test.ts
Normal file
36
packages/cli/src/ui/commands/settingsCommand.test.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { settingsCommand } from './settingsCommand.js';
|
||||
import { type CommandContext } from './types.js';
|
||||
import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
|
||||
|
||||
describe('settingsCommand', () => {
|
||||
let mockContext: CommandContext;
|
||||
|
||||
beforeEach(() => {
|
||||
mockContext = createMockCommandContext();
|
||||
});
|
||||
|
||||
it('should return a dialog action to open the settings dialog', () => {
|
||||
if (!settingsCommand.action) {
|
||||
throw new Error('The settings command must have an action.');
|
||||
}
|
||||
const result = settingsCommand.action(mockContext, '');
|
||||
expect(result).toEqual({
|
||||
type: 'dialog',
|
||||
dialog: 'settings',
|
||||
});
|
||||
});
|
||||
|
||||
it('should have the correct name and description', () => {
|
||||
expect(settingsCommand.name).toBe('settings');
|
||||
expect(settingsCommand.description).toBe(
|
||||
'View and edit Gemini CLI settings',
|
||||
);
|
||||
});
|
||||
});
|
||||
17
packages/cli/src/ui/commands/settingsCommand.ts
Normal file
17
packages/cli/src/ui/commands/settingsCommand.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { CommandKind, OpenDialogActionReturn, SlashCommand } from './types.js';
|
||||
|
||||
export const settingsCommand: SlashCommand = {
|
||||
name: 'settings',
|
||||
description: 'View and edit Gemini CLI settings',
|
||||
kind: CommandKind.BUILT_IN,
|
||||
action: (_context, _args): OpenDialogActionReturn => ({
|
||||
type: 'dialog',
|
||||
dialog: 'settings',
|
||||
}),
|
||||
};
|
||||
@@ -4,63 +4,103 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import fs from 'node:fs/promises';
|
||||
|
||||
import { vi, describe, expect, it, afterEach, beforeEach } from 'vitest';
|
||||
import * as child_process from 'child_process';
|
||||
import * as gitUtils from '../../utils/gitUtils.js';
|
||||
import { setupGithubCommand } from './setupGithubCommand.js';
|
||||
import { CommandContext, ToolActionReturn } from './types.js';
|
||||
import * as commandUtils from '../utils/commandUtils.js';
|
||||
|
||||
vi.mock('child_process');
|
||||
|
||||
describe('setupGithubCommand', () => {
|
||||
beforeEach(() => {
|
||||
// Mock fetch globally
|
||||
global.fetch = vi.fn();
|
||||
|
||||
vi.mock('../../utils/gitUtils.js', () => ({
|
||||
isGitHubRepository: vi.fn(),
|
||||
getGitRepoRoot: vi.fn(),
|
||||
getLatestGitHubRelease: vi.fn(),
|
||||
getGitHubRepoInfo: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../utils/commandUtils.js', () => ({
|
||||
getUrlOpenCommand: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('setupGithubCommand', async () => {
|
||||
let scratchDir = '';
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetAllMocks();
|
||||
scratchDir = await fs.mkdtemp(
|
||||
path.join(os.tmpdir(), 'setup-github-command-'),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
if (scratchDir) await fs.rm(scratchDir, { recursive: true });
|
||||
});
|
||||
|
||||
it('returns a tool action to download github workflows and handles paths', () => {
|
||||
const fakeRepoRoot = '/github.com/fake/repo/root';
|
||||
vi.mocked(child_process.execSync).mockReturnValue(fakeRepoRoot);
|
||||
it('returns a tool action to download github workflows and handles paths', async () => {
|
||||
const fakeRepoOwner = 'fake';
|
||||
const fakeRepoName = 'repo';
|
||||
const fakeRepoRoot = scratchDir;
|
||||
const fakeReleaseVersion = 'v1.2.3';
|
||||
|
||||
const result = setupGithubCommand.action?.(
|
||||
const workflows = [
|
||||
'gemini-cli.yml',
|
||||
'gemini-issue-automated-triage.yml',
|
||||
'gemini-issue-scheduled-triage.yml',
|
||||
'gemini-pr-review.yml',
|
||||
];
|
||||
for (const workflow of workflows) {
|
||||
vi.mocked(global.fetch).mockReturnValueOnce(
|
||||
Promise.resolve(new Response(workflow)),
|
||||
);
|
||||
}
|
||||
|
||||
vi.mocked(gitUtils.isGitHubRepository).mockReturnValueOnce(true);
|
||||
vi.mocked(gitUtils.getGitRepoRoot).mockReturnValueOnce(fakeRepoRoot);
|
||||
vi.mocked(gitUtils.getLatestGitHubRelease).mockResolvedValueOnce(
|
||||
fakeReleaseVersion,
|
||||
);
|
||||
vi.mocked(gitUtils.getGitHubRepoInfo).mockReturnValue({
|
||||
owner: fakeRepoOwner,
|
||||
repo: fakeRepoName,
|
||||
});
|
||||
vi.mocked(commandUtils.getUrlOpenCommand).mockReturnValueOnce(
|
||||
'fakeOpenCommand',
|
||||
);
|
||||
|
||||
const result = (await setupGithubCommand.action?.(
|
||||
{} as CommandContext,
|
||||
'',
|
||||
) as ToolActionReturn;
|
||||
|
||||
expect(result.type).toBe('tool');
|
||||
expect(result.toolName).toBe('run_shell_command');
|
||||
expect(child_process.execSync).toHaveBeenCalledWith(
|
||||
'git rev-parse --show-toplevel',
|
||||
{
|
||||
encoding: 'utf-8',
|
||||
},
|
||||
);
|
||||
expect(child_process.execSync).toHaveBeenCalledWith('git remote -v', {
|
||||
encoding: 'utf-8',
|
||||
});
|
||||
)) as ToolActionReturn;
|
||||
|
||||
const { command } = result.toolArgs;
|
||||
|
||||
const expectedSubstrings = [
|
||||
`mkdir -p "${fakeRepoRoot}/.github/workflows"`,
|
||||
`curl -fsSL -o "${fakeRepoRoot}/.github/workflows/gemini-cli.yml"`,
|
||||
`curl -fsSL -o "${fakeRepoRoot}/.github/workflows/gemini-issue-automated-triage.yml"`,
|
||||
`curl -fsSL -o "${fakeRepoRoot}/.github/workflows/gemini-issue-scheduled-triage.yml"`,
|
||||
`curl -fsSL -o "${fakeRepoRoot}/.github/workflows/gemini-pr-review.yml"`,
|
||||
'https://raw.githubusercontent.com/google-github-actions/run-gemini-cli/refs/tags/v0/examples/workflows/',
|
||||
`set -eEuo pipefail`,
|
||||
`fakeOpenCommand "https://github.com/google-github-actions/run-gemini-cli`,
|
||||
];
|
||||
|
||||
for (const substring of expectedSubstrings) {
|
||||
expect(command).toContain(substring);
|
||||
}
|
||||
});
|
||||
|
||||
it('throws an error if git root cannot be determined', () => {
|
||||
vi.mocked(child_process.execSync).mockReturnValue('');
|
||||
expect(() => {
|
||||
setupGithubCommand.action?.({} as CommandContext, '');
|
||||
}).toThrow('Unable to determine the Git root directory.');
|
||||
for (const workflow of workflows) {
|
||||
const workflowFile = path.join(
|
||||
scratchDir,
|
||||
'.github',
|
||||
'workflows',
|
||||
workflow,
|
||||
);
|
||||
const contents = await fs.readFile(workflowFile, 'utf8');
|
||||
expect(contents).toContain(workflow);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,32 +4,93 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import path from 'path';
|
||||
import { execSync } from 'child_process';
|
||||
import { isGitHubRepository } from '../../utils/gitUtils.js';
|
||||
import path from 'node:path';
|
||||
import * as fs from 'node:fs';
|
||||
import { Writable } from 'node:stream';
|
||||
import { ProxyAgent } from 'undici';
|
||||
|
||||
import { CommandContext } from '../../ui/commands/types.js';
|
||||
import {
|
||||
getGitRepoRoot,
|
||||
getLatestGitHubRelease,
|
||||
isGitHubRepository,
|
||||
getGitHubRepoInfo,
|
||||
} from '../../utils/gitUtils.js';
|
||||
|
||||
import {
|
||||
CommandKind,
|
||||
SlashCommand,
|
||||
SlashCommandActionReturn,
|
||||
} from './types.js';
|
||||
import { getUrlOpenCommand } from '../../ui/utils/commandUtils.js';
|
||||
|
||||
// Generate OS-specific commands to open the GitHub pages needed for setup.
|
||||
function getOpenUrlsCommands(readmeUrl: string): string[] {
|
||||
// Determine the OS-specific command to open URLs, ex: 'open', 'xdg-open', etc
|
||||
const openCmd = getUrlOpenCommand();
|
||||
|
||||
// Build a list of URLs to open
|
||||
const urlsToOpen = [readmeUrl];
|
||||
|
||||
const repoInfo = getGitHubRepoInfo();
|
||||
if (repoInfo) {
|
||||
urlsToOpen.push(
|
||||
`https://github.com/${repoInfo.owner}/${repoInfo.repo}/settings/secrets/actions`,
|
||||
);
|
||||
}
|
||||
|
||||
// Create and join the individual commands
|
||||
const commands = urlsToOpen.map((url) => `${openCmd} "${url}"`);
|
||||
return commands;
|
||||
}
|
||||
|
||||
export const setupGithubCommand: SlashCommand = {
|
||||
name: 'setup-github',
|
||||
description: 'Set up GitHub Actions',
|
||||
kind: CommandKind.BUILT_IN,
|
||||
action: (): SlashCommandActionReturn => {
|
||||
const gitRootRepo = execSync('git rev-parse --show-toplevel', {
|
||||
encoding: 'utf-8',
|
||||
}).trim();
|
||||
action: async (
|
||||
context: CommandContext,
|
||||
): Promise<SlashCommandActionReturn> => {
|
||||
const abortController = new AbortController();
|
||||
|
||||
if (!isGitHubRepository()) {
|
||||
throw new Error('Unable to determine the Git root directory.');
|
||||
throw new Error(
|
||||
'Unable to determine the GitHub repository. /setup-github must be run from a git repository.',
|
||||
);
|
||||
}
|
||||
|
||||
const version = 'v0';
|
||||
const workflowBaseUrl = `https://raw.githubusercontent.com/google-github-actions/run-gemini-cli/refs/tags/${version}/examples/workflows/`;
|
||||
// Find the root directory of the repo
|
||||
let gitRepoRoot: string;
|
||||
try {
|
||||
gitRepoRoot = getGitRepoRoot();
|
||||
} catch (_error) {
|
||||
console.debug(`Failed to get git repo root:`, _error);
|
||||
throw new Error(
|
||||
'Unable to determine the GitHub repository. /setup-github must be run from a git repository.',
|
||||
);
|
||||
}
|
||||
|
||||
// Get the latest release tag from GitHub
|
||||
const proxy = context?.services?.config?.getProxy();
|
||||
const releaseTag = await getLatestGitHubRelease(proxy);
|
||||
const readmeUrl = `https://github.com/google-github-actions/run-gemini-cli/blob/${releaseTag}/README.md#quick-start`;
|
||||
|
||||
// Create the .github/workflows directory to download the files into
|
||||
const githubWorkflowsDir = path.join(gitRepoRoot, '.github', 'workflows');
|
||||
try {
|
||||
await fs.promises.mkdir(githubWorkflowsDir, { recursive: true });
|
||||
} catch (_error) {
|
||||
console.debug(
|
||||
`Failed to create ${githubWorkflowsDir} directory:`,
|
||||
_error,
|
||||
);
|
||||
throw new Error(
|
||||
`Unable to create ${githubWorkflowsDir} directory. Do you have file permissions in the current directory?`,
|
||||
);
|
||||
}
|
||||
|
||||
// Download each workflow in parallel - there aren't enough files to warrant
|
||||
// a full workerpool model here.
|
||||
const workflows = [
|
||||
'gemini-cli/gemini-cli.yml',
|
||||
'issue-triage/gemini-issue-automated-triage.yml',
|
||||
@@ -37,15 +98,63 @@ export const setupGithubCommand: SlashCommand = {
|
||||
'pr-review/gemini-pr-review.yml',
|
||||
];
|
||||
|
||||
const command = [
|
||||
'set -e',
|
||||
`mkdir -p "${gitRootRepo}/.github/workflows"`,
|
||||
...workflows.map((workflow) => {
|
||||
const fileName = path.basename(workflow);
|
||||
return `curl -fsSL -o "${gitRootRepo}/.github/workflows/${fileName}" "${workflowBaseUrl}/${workflow}"`;
|
||||
}),
|
||||
'echo "Workflows downloaded successfully."',
|
||||
].join(' && ');
|
||||
const downloads = [];
|
||||
for (const workflow of workflows) {
|
||||
downloads.push(
|
||||
(async () => {
|
||||
const endpoint = `https://raw.githubusercontent.com/google-github-actions/run-gemini-cli/refs/tags/${releaseTag}/examples/workflows/${workflow}`;
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'GET',
|
||||
dispatcher: proxy ? new ProxyAgent(proxy) : undefined,
|
||||
signal: AbortSignal.any([
|
||||
AbortSignal.timeout(30_000),
|
||||
abortController.signal,
|
||||
]),
|
||||
} as RequestInit);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Invalid response code downloading ${endpoint}: ${response.status} - ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
const body = response.body;
|
||||
if (!body) {
|
||||
throw new Error(
|
||||
`Empty body while downloading ${endpoint}: ${response.status} - ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const destination = path.resolve(
|
||||
githubWorkflowsDir,
|
||||
path.basename(workflow),
|
||||
);
|
||||
|
||||
const fileStream = fs.createWriteStream(destination, {
|
||||
mode: 0o644, // -rw-r--r--, user(rw), group(r), other(r)
|
||||
flags: 'w', // write and overwrite
|
||||
flush: true,
|
||||
});
|
||||
|
||||
await body.pipeTo(Writable.toWeb(fileStream));
|
||||
})(),
|
||||
);
|
||||
}
|
||||
|
||||
// Wait for all downloads to complete
|
||||
await Promise.all(downloads).finally(() => {
|
||||
// Stop existing downloads
|
||||
abortController.abort();
|
||||
});
|
||||
|
||||
// Print out a message
|
||||
const commands = [];
|
||||
commands.push('set -eEuo pipefail');
|
||||
commands.push(
|
||||
`echo "Successfully downloaded ${workflows.length} workflows. Follow the steps in ${readmeUrl} (skipping the /setup-github step) to complete setup."`,
|
||||
);
|
||||
commands.push(...getOpenUrlsCommands(readmeUrl));
|
||||
|
||||
const command = `(${commands.join(' && ')})`;
|
||||
return {
|
||||
type: 'tool',
|
||||
toolName: 'run_shell_command',
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { type ReactNode } from 'react';
|
||||
import { Content } from '@google/genai';
|
||||
import { HistoryItemWithoutId } from '../types.js';
|
||||
import { Config, GitService, Logger } from '@qwen-code/qwen-code-core';
|
||||
@@ -68,6 +69,8 @@ export interface CommandContext {
|
||||
/** A transient list of shell commands the user has approved for this session. */
|
||||
sessionShellAllowlist: Set<string>;
|
||||
};
|
||||
// Flag to indicate if an overwrite has been confirmed
|
||||
overwriteConfirmed?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -100,7 +103,8 @@ export interface MessageActionReturn {
|
||||
*/
|
||||
export interface OpenDialogActionReturn {
|
||||
type: 'dialog';
|
||||
dialog: 'auth' | 'theme' | 'editor' | 'privacy';
|
||||
|
||||
dialog: 'help' | 'auth' | 'theme' | 'editor' | 'privacy' | 'settings';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -136,6 +140,16 @@ export interface ConfirmShellCommandsActionReturn {
|
||||
};
|
||||
}
|
||||
|
||||
export interface ConfirmActionReturn {
|
||||
type: 'confirm_action';
|
||||
/** The React node to display as the confirmation prompt. */
|
||||
prompt: ReactNode;
|
||||
/** The original invocation context to be re-run after confirmation. */
|
||||
originalInvocation: {
|
||||
raw: string;
|
||||
};
|
||||
}
|
||||
|
||||
export type SlashCommandActionReturn =
|
||||
| ToolActionReturn
|
||||
| MessageActionReturn
|
||||
@@ -143,7 +157,8 @@ export type SlashCommandActionReturn =
|
||||
| OpenDialogActionReturn
|
||||
| LoadHistoryActionReturn
|
||||
| SubmitPromptActionReturn
|
||||
| ConfirmShellCommandsActionReturn;
|
||||
| ConfirmShellCommandsActionReturn
|
||||
| ConfirmActionReturn;
|
||||
|
||||
export enum CommandKind {
|
||||
BUILT_IN = 'built-in',
|
||||
|
||||
@@ -20,3 +20,14 @@ export const longAsciiLogo = `
|
||||
██╔╝ ╚██████╔╝╚███╔███╔╝███████╗██║ ╚████║
|
||||
╚═╝ ╚══▀▀═╝ ╚══╝╚══╝ ╚══════╝╚═╝ ╚═══╝
|
||||
`;
|
||||
|
||||
export const tinyAsciiLogo = `
|
||||
███ █████████
|
||||
░░░███ ███░░░░░███
|
||||
░░░███ ███ ░░░
|
||||
░░░███░███
|
||||
███░ ░███ █████
|
||||
███░ ░░███ ░░███
|
||||
███░ ░░█████████
|
||||
░░░ ░░░░░░░░░
|
||||
`;
|
||||
|
||||
@@ -18,8 +18,8 @@ export function AuthInProgress({
|
||||
}: AuthInProgressProps): React.JSX.Element {
|
||||
const [timedOut, setTimedOut] = useState(false);
|
||||
|
||||
useInput((_, key) => {
|
||||
if (key.escape) {
|
||||
useInput((input, key) => {
|
||||
if (key.escape || (key.ctrl && (input === 'c' || input === 'C'))) {
|
||||
onTimeout();
|
||||
}
|
||||
});
|
||||
@@ -48,7 +48,8 @@ export function AuthInProgress({
|
||||
) : (
|
||||
<Box>
|
||||
<Text>
|
||||
<Spinner type="dots" /> Waiting for auth... (Press ESC to cancel)
|
||||
<Spinner type="dots" /> Waiting for auth... (Press ESC or CTRL+C to
|
||||
cancel)
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { render } from 'ink-testing-library';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { ContextSummaryDisplay } from './ContextSummaryDisplay.js';
|
||||
import * as useTerminalSize from '../hooks/useTerminalSize.js';
|
||||
|
||||
vi.mock('../hooks/useTerminalSize.js', () => ({
|
||||
useTerminalSize: vi.fn(),
|
||||
}));
|
||||
|
||||
const useTerminalSizeMock = vi.mocked(useTerminalSize.useTerminalSize);
|
||||
|
||||
const renderWithWidth = (
|
||||
width: number,
|
||||
props: React.ComponentProps<typeof ContextSummaryDisplay>,
|
||||
) => {
|
||||
useTerminalSizeMock.mockReturnValue({ columns: width, rows: 24 });
|
||||
return render(<ContextSummaryDisplay {...props} />);
|
||||
};
|
||||
|
||||
describe('<ContextSummaryDisplay />', () => {
|
||||
const baseProps = {
|
||||
geminiMdFileCount: 1,
|
||||
contextFileNames: ['GEMINI.md'],
|
||||
mcpServers: { 'test-server': { command: 'test' } },
|
||||
showToolDescriptions: false,
|
||||
ideContext: {
|
||||
workspaceState: {
|
||||
openFiles: [{ path: '/a/b/c' }],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
it('should render on a single line on a wide screen', () => {
|
||||
const { lastFrame } = renderWithWidth(120, baseProps);
|
||||
const output = lastFrame();
|
||||
expect(output).toContain(
|
||||
'Using: 1 open file (ctrl+e to view) | 1 GEMINI.md file | 1 MCP server (ctrl+t to view)',
|
||||
);
|
||||
// Check for absence of newlines
|
||||
expect(output.includes('\n')).toBe(false);
|
||||
});
|
||||
|
||||
it('should render on multiple lines on a narrow screen', () => {
|
||||
const { lastFrame } = renderWithWidth(60, baseProps);
|
||||
const output = lastFrame();
|
||||
const expectedLines = [
|
||||
'Using:',
|
||||
' - 1 open file (ctrl+e to view)',
|
||||
' - 1 GEMINI.md file',
|
||||
' - 1 MCP server (ctrl+t to view)',
|
||||
];
|
||||
const actualLines = output.split('\n');
|
||||
expect(actualLines).toEqual(expectedLines);
|
||||
});
|
||||
|
||||
it('should switch layout at the 80-column breakpoint', () => {
|
||||
// At 80 columns, should be on one line
|
||||
const { lastFrame: wideFrame } = renderWithWidth(80, baseProps);
|
||||
expect(wideFrame().includes('\n')).toBe(false);
|
||||
|
||||
// At 79 columns, should be on multiple lines
|
||||
const { lastFrame: narrowFrame } = renderWithWidth(79, baseProps);
|
||||
expect(narrowFrame().includes('\n')).toBe(true);
|
||||
expect(narrowFrame().split('\n').length).toBe(4);
|
||||
});
|
||||
|
||||
it('should not render empty parts', () => {
|
||||
const props = {
|
||||
...baseProps,
|
||||
geminiMdFileCount: 0,
|
||||
mcpServers: {},
|
||||
};
|
||||
const { lastFrame } = renderWithWidth(60, props);
|
||||
const expectedLines = ['Using:', ' - 1 open file (ctrl+e to view)'];
|
||||
const actualLines = lastFrame().split('\n');
|
||||
expect(actualLines).toEqual(expectedLines);
|
||||
});
|
||||
});
|
||||
@@ -5,12 +5,14 @@
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { Text } from 'ink';
|
||||
import { Box, Text } from 'ink';
|
||||
import { Colors } from '../colors.js';
|
||||
import {
|
||||
type IdeContext,
|
||||
type MCPServerConfig,
|
||||
} from '@qwen-code/qwen-code-core';
|
||||
import { useTerminalSize } from '../hooks/useTerminalSize.js';
|
||||
import { isNarrowWidth } from '../utils/isNarrowWidth.js';
|
||||
|
||||
interface ContextSummaryDisplayProps {
|
||||
geminiMdFileCount: number;
|
||||
@@ -29,6 +31,8 @@ export const ContextSummaryDisplay: React.FC<ContextSummaryDisplayProps> = ({
|
||||
showToolDescriptions,
|
||||
ideContext,
|
||||
}) => {
|
||||
const { columns: terminalWidth } = useTerminalSize();
|
||||
const isNarrow = isNarrowWidth(terminalWidth);
|
||||
const mcpServerCount = Object.keys(mcpServers || {}).length;
|
||||
const blockedMcpServerCount = blockedMcpServers?.length || 0;
|
||||
const openFileCount = ideContext?.workspaceState?.openFiles?.length ?? 0;
|
||||
@@ -81,30 +85,36 @@ export const ContextSummaryDisplay: React.FC<ContextSummaryDisplayProps> = ({
|
||||
}
|
||||
parts.push(blockedText);
|
||||
}
|
||||
return parts.join(', ');
|
||||
let text = parts.join(', ');
|
||||
// Add ctrl+t hint when MCP servers are available
|
||||
if (mcpServers && Object.keys(mcpServers).length > 0) {
|
||||
if (showToolDescriptions) {
|
||||
text += ' (ctrl+t to toggle)';
|
||||
} else {
|
||||
text += ' (ctrl+t to view)';
|
||||
}
|
||||
}
|
||||
return text;
|
||||
})();
|
||||
|
||||
let summaryText = 'Using: ';
|
||||
const summaryParts = [];
|
||||
if (openFilesText) {
|
||||
summaryParts.push(openFilesText);
|
||||
}
|
||||
if (geminiMdText) {
|
||||
summaryParts.push(geminiMdText);
|
||||
}
|
||||
if (mcpText) {
|
||||
summaryParts.push(mcpText);
|
||||
}
|
||||
summaryText += summaryParts.join(' | ');
|
||||
const summaryParts = [openFilesText, geminiMdText, mcpText].filter(Boolean);
|
||||
|
||||
// Add ctrl+t hint when MCP servers are available
|
||||
if (mcpServers && Object.keys(mcpServers).length > 0) {
|
||||
if (showToolDescriptions) {
|
||||
summaryText += ' (ctrl+t to toggle)';
|
||||
} else {
|
||||
summaryText += ' (ctrl+t to view)';
|
||||
}
|
||||
if (isNarrow) {
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text color={Colors.Gray}>Using:</Text>
|
||||
{summaryParts.map((part, index) => (
|
||||
<Text key={index} color={Colors.Gray}>
|
||||
{' '}- {part}
|
||||
</Text>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
return <Text color={Colors.Gray}>{summaryText}</Text>;
|
||||
return (
|
||||
<Box>
|
||||
<Text color={Colors.Gray}>Using: {summaryParts.join(' | ')}</Text>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
25
packages/cli/src/ui/components/ContextUsageDisplay.tsx
Normal file
25
packages/cli/src/ui/components/ContextUsageDisplay.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { Text } from 'ink';
|
||||
import { Colors } from '../colors.js';
|
||||
import { tokenLimit } from '@qwen-code/qwen-code-core';
|
||||
|
||||
export const ContextUsageDisplay = ({
|
||||
promptTokenCount,
|
||||
model,
|
||||
}: {
|
||||
promptTokenCount: number;
|
||||
model: string;
|
||||
}) => {
|
||||
const percentage = promptTokenCount / tokenLimit(model);
|
||||
|
||||
return (
|
||||
<Text color={Colors.Gray}>
|
||||
({((1 - percentage) * 100).toFixed(0)}% context left)
|
||||
</Text>
|
||||
);
|
||||
};
|
||||
29
packages/cli/src/ui/components/FolderTrustDialog.test.tsx
Normal file
29
packages/cli/src/ui/components/FolderTrustDialog.test.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { render } from 'ink-testing-library';
|
||||
import { vi } from 'vitest';
|
||||
import { FolderTrustDialog, FolderTrustChoice } from './FolderTrustDialog.js';
|
||||
|
||||
describe('FolderTrustDialog', () => {
|
||||
it('should render the dialog with title and description', () => {
|
||||
const { lastFrame } = render(<FolderTrustDialog onSelect={vi.fn()} />);
|
||||
|
||||
expect(lastFrame()).toContain('Do you trust this folder?');
|
||||
expect(lastFrame()).toContain(
|
||||
'Trusting a folder allows Gemini to execute commands it suggests.',
|
||||
);
|
||||
});
|
||||
|
||||
it('should call onSelect with DO_NOT_TRUST when escape is pressed', () => {
|
||||
const onSelect = vi.fn();
|
||||
const { stdin } = render(<FolderTrustDialog onSelect={onSelect} />);
|
||||
|
||||
stdin.write('\u001B'); // Simulate escape key
|
||||
|
||||
expect(onSelect).toHaveBeenCalledWith(FolderTrustChoice.DO_NOT_TRUST);
|
||||
});
|
||||
});
|
||||
70
packages/cli/src/ui/components/FolderTrustDialog.tsx
Normal file
70
packages/cli/src/ui/components/FolderTrustDialog.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import React from 'react';
|
||||
import { Colors } from '../colors.js';
|
||||
import {
|
||||
RadioButtonSelect,
|
||||
RadioSelectItem,
|
||||
} from './shared/RadioButtonSelect.js';
|
||||
|
||||
export enum FolderTrustChoice {
|
||||
TRUST_FOLDER = 'trust_folder',
|
||||
TRUST_PARENT = 'trust_parent',
|
||||
DO_NOT_TRUST = 'do_not_trust',
|
||||
}
|
||||
|
||||
interface FolderTrustDialogProps {
|
||||
onSelect: (choice: FolderTrustChoice) => void;
|
||||
}
|
||||
|
||||
export const FolderTrustDialog: React.FC<FolderTrustDialogProps> = ({
|
||||
onSelect,
|
||||
}) => {
|
||||
useInput((_, key) => {
|
||||
if (key.escape) {
|
||||
onSelect(FolderTrustChoice.DO_NOT_TRUST);
|
||||
}
|
||||
});
|
||||
|
||||
const options: Array<RadioSelectItem<FolderTrustChoice>> = [
|
||||
{
|
||||
label: 'Trust folder',
|
||||
value: FolderTrustChoice.TRUST_FOLDER,
|
||||
},
|
||||
{
|
||||
label: 'Trust parent folder',
|
||||
value: FolderTrustChoice.TRUST_PARENT,
|
||||
},
|
||||
{
|
||||
label: "Don't trust (esc)",
|
||||
value: FolderTrustChoice.DO_NOT_TRUST,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
borderStyle="round"
|
||||
borderColor={Colors.AccentYellow}
|
||||
padding={1}
|
||||
width="100%"
|
||||
marginLeft={1}
|
||||
>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text bold>Do you trust this folder?</Text>
|
||||
<Text>
|
||||
Trusting a folder allows Gemini to execute commands it suggests. This
|
||||
is a security feature to prevent accidental execution in untrusted
|
||||
directories.
|
||||
</Text>
|
||||
</Box>
|
||||
|
||||
<RadioButtonSelect items={options} onSelect={onSelect} isFocused />
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
106
packages/cli/src/ui/components/Footer.test.tsx
Normal file
106
packages/cli/src/ui/components/Footer.test.tsx
Normal file
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { render } from 'ink-testing-library';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { Footer } from './Footer.js';
|
||||
import * as useTerminalSize from '../hooks/useTerminalSize.js';
|
||||
import { tildeifyPath } from '@qwen-code/qwen-code-core';
|
||||
import path from 'node:path';
|
||||
|
||||
vi.mock('../hooks/useTerminalSize.js');
|
||||
const useTerminalSizeMock = vi.mocked(useTerminalSize.useTerminalSize);
|
||||
|
||||
vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
|
||||
const original =
|
||||
await importOriginal<typeof import('@qwen-code/qwen-code-core')>();
|
||||
return {
|
||||
...original,
|
||||
shortenPath: (p: string, len: number) => {
|
||||
if (p.length > len) {
|
||||
return '...' + p.slice(p.length - len + 3);
|
||||
}
|
||||
return p;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const defaultProps = {
|
||||
model: 'gemini-pro',
|
||||
targetDir:
|
||||
'/Users/test/project/foo/bar/and/some/more/directories/to/make/it/long',
|
||||
branchName: 'main',
|
||||
debugMode: false,
|
||||
debugMessage: '',
|
||||
corgiMode: false,
|
||||
errorCount: 0,
|
||||
showErrorDetails: false,
|
||||
showMemoryUsage: false,
|
||||
promptTokenCount: 100,
|
||||
nightly: false,
|
||||
};
|
||||
|
||||
const renderWithWidth = (width: number, props = defaultProps) => {
|
||||
useTerminalSizeMock.mockReturnValue({ columns: width, rows: 24 });
|
||||
return render(<Footer {...props} />);
|
||||
};
|
||||
|
||||
describe('<Footer />', () => {
|
||||
it('renders the component', () => {
|
||||
const { lastFrame } = renderWithWidth(120);
|
||||
expect(lastFrame()).toBeDefined();
|
||||
});
|
||||
|
||||
describe('path display', () => {
|
||||
it('should display shortened path on a wide terminal', () => {
|
||||
const { lastFrame } = renderWithWidth(120);
|
||||
const tildePath = tildeifyPath(defaultProps.targetDir);
|
||||
const expectedPath = '...' + tildePath.slice(tildePath.length - 48 + 3);
|
||||
expect(lastFrame()).toContain(expectedPath);
|
||||
});
|
||||
|
||||
it('should display only the base directory name on a narrow terminal', () => {
|
||||
const { lastFrame } = renderWithWidth(79);
|
||||
const expectedPath = path.basename(defaultProps.targetDir);
|
||||
expect(lastFrame()).toContain(expectedPath);
|
||||
});
|
||||
|
||||
it('should use wide layout at 80 columns', () => {
|
||||
const { lastFrame } = renderWithWidth(80);
|
||||
const tildePath = tildeifyPath(defaultProps.targetDir);
|
||||
const expectedPath = '...' + tildePath.slice(tildePath.length - 32 + 3);
|
||||
expect(lastFrame()).toContain(expectedPath);
|
||||
});
|
||||
|
||||
it('should use narrow layout at 79 columns', () => {
|
||||
const { lastFrame } = renderWithWidth(79);
|
||||
const expectedPath = path.basename(defaultProps.targetDir);
|
||||
expect(lastFrame()).toContain(expectedPath);
|
||||
const tildePath = tildeifyPath(defaultProps.targetDir);
|
||||
const unexpectedPath = '...' + tildePath.slice(tildePath.length - 31 + 3);
|
||||
expect(lastFrame()).not.toContain(unexpectedPath);
|
||||
});
|
||||
});
|
||||
|
||||
it('displays the branch name when provided', () => {
|
||||
const { lastFrame } = renderWithWidth(120);
|
||||
expect(lastFrame()).toContain(`(${defaultProps.branchName}*)`);
|
||||
});
|
||||
|
||||
it('does not display the branch name when not provided', () => {
|
||||
const { lastFrame } = renderWithWidth(120, {
|
||||
...defaultProps,
|
||||
branchName: undefined,
|
||||
});
|
||||
expect(lastFrame()).not.toContain(`(${defaultProps.branchName}*)`);
|
||||
});
|
||||
|
||||
it('displays the model name and context percentage', () => {
|
||||
const { lastFrame } = renderWithWidth(120);
|
||||
expect(lastFrame()).toContain(defaultProps.model);
|
||||
expect(lastFrame()).toMatch(/\(\d+% context[\s\S]*left\)/);
|
||||
});
|
||||
});
|
||||
@@ -6,19 +6,19 @@
|
||||
|
||||
import React from 'react';
|
||||
import { Box, Text } from 'ink';
|
||||
import { Colors } from '../colors.js';
|
||||
import {
|
||||
shortenPath,
|
||||
tildeifyPath,
|
||||
tokenLimit,
|
||||
} from '@qwen-code/qwen-code-core';
|
||||
import { theme } from '../semantic-colors.js';
|
||||
import { shortenPath, tildeifyPath } from '@qwen-code/qwen-code-core';
|
||||
import { ConsoleSummaryDisplay } from './ConsoleSummaryDisplay.js';
|
||||
import process from 'node:process';
|
||||
import path from 'node:path';
|
||||
import Gradient from 'ink-gradient';
|
||||
import { MemoryUsageDisplay } from './MemoryUsageDisplay.js';
|
||||
|
||||
import { ContextUsageDisplay } from './ContextUsageDisplay.js';
|
||||
import { DebugProfiler } from './DebugProfiler.js';
|
||||
|
||||
import { useTerminalSize } from '../hooks/useTerminalSize.js';
|
||||
import { isNarrowWidth } from '../utils/isNarrowWidth.js';
|
||||
|
||||
interface FooterProps {
|
||||
model: string;
|
||||
targetDir: string;
|
||||
@@ -48,29 +48,43 @@ export const Footer: React.FC<FooterProps> = ({
|
||||
nightly,
|
||||
vimMode,
|
||||
}) => {
|
||||
const limit = tokenLimit(model);
|
||||
const percentage = promptTokenCount / limit;
|
||||
const { columns: terminalWidth } = useTerminalSize();
|
||||
|
||||
const isNarrow = isNarrowWidth(terminalWidth);
|
||||
|
||||
// Adjust path length based on terminal width
|
||||
const pathLength = Math.max(20, Math.floor(terminalWidth * 0.4));
|
||||
const displayPath = isNarrow
|
||||
? path.basename(tildeifyPath(targetDir))
|
||||
: shortenPath(tildeifyPath(targetDir), pathLength);
|
||||
|
||||
return (
|
||||
<Box justifyContent="space-between" width="100%">
|
||||
<Box
|
||||
justifyContent="space-between"
|
||||
width="100%"
|
||||
flexDirection={isNarrow ? 'column' : 'row'}
|
||||
alignItems={isNarrow ? 'flex-start' : 'center'}
|
||||
>
|
||||
<Box>
|
||||
{debugMode && <DebugProfiler />}
|
||||
{vimMode && <Text color={Colors.Gray}>[{vimMode}] </Text>}
|
||||
{vimMode && <Text color={theme.text.secondary}>[{vimMode}] </Text>}
|
||||
{nightly ? (
|
||||
<Gradient colors={Colors.GradientColors}>
|
||||
<Gradient colors={theme.ui.gradient}>
|
||||
<Text>
|
||||
{shortenPath(tildeifyPath(targetDir), 70)}
|
||||
{displayPath}
|
||||
{branchName && <Text> ({branchName}*)</Text>}
|
||||
</Text>
|
||||
</Gradient>
|
||||
) : (
|
||||
<Text color={Colors.LightBlue}>
|
||||
{shortenPath(tildeifyPath(targetDir), 70)}
|
||||
{branchName && <Text color={Colors.Gray}> ({branchName}*)</Text>}
|
||||
<Text color={theme.text.link}>
|
||||
{displayPath}
|
||||
{branchName && (
|
||||
<Text color={theme.text.secondary}> ({branchName}*)</Text>
|
||||
)}
|
||||
</Text>
|
||||
)}
|
||||
{debugMode && (
|
||||
<Text color={Colors.AccentRed}>
|
||||
<Text color={theme.status.error}>
|
||||
{' ' + (debugMessage || '--debug')}
|
||||
</Text>
|
||||
)}
|
||||
@@ -78,49 +92,54 @@ export const Footer: React.FC<FooterProps> = ({
|
||||
|
||||
{/* Middle Section: Centered Sandbox Info */}
|
||||
<Box
|
||||
flexGrow={1}
|
||||
flexGrow={isNarrow ? 0 : 1}
|
||||
alignItems="center"
|
||||
justifyContent="center"
|
||||
justifyContent={isNarrow ? 'flex-start' : 'center'}
|
||||
display="flex"
|
||||
paddingX={isNarrow ? 0 : 1}
|
||||
paddingTop={isNarrow ? 1 : 0}
|
||||
>
|
||||
{process.env.SANDBOX && process.env.SANDBOX !== 'sandbox-exec' ? (
|
||||
<Text color="green">
|
||||
{process.env.SANDBOX.replace(/^gemini-(?:cli-)?/, '')}
|
||||
</Text>
|
||||
) : process.env.SANDBOX === 'sandbox-exec' ? (
|
||||
<Text color={Colors.AccentYellow}>
|
||||
<Text color={theme.status.warning}>
|
||||
macOS Seatbelt{' '}
|
||||
<Text color={Colors.Gray}>({process.env.SEATBELT_PROFILE})</Text>
|
||||
<Text color={theme.text.secondary}>
|
||||
({process.env.SEATBELT_PROFILE})
|
||||
</Text>
|
||||
</Text>
|
||||
) : (
|
||||
<Text color={Colors.AccentRed}>
|
||||
no sandbox <Text color={Colors.Gray}>(see /docs)</Text>
|
||||
<Text color={theme.status.error}>
|
||||
no sandbox <Text color={theme.text.secondary}>(see /docs)</Text>
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* Right Section: Gemini Label and Console Summary */}
|
||||
<Box alignItems="center">
|
||||
<Text color={Colors.AccentBlue}>
|
||||
{' '}
|
||||
<Box alignItems="center" paddingTop={isNarrow ? 1 : 0}>
|
||||
<Text color={theme.text.accent}>
|
||||
{isNarrow ? '' : ' '}
|
||||
{model}{' '}
|
||||
<Text color={Colors.Gray}>
|
||||
({((1 - percentage) * 100).toFixed(0)}% context left)
|
||||
</Text>
|
||||
<ContextUsageDisplay
|
||||
promptTokenCount={promptTokenCount}
|
||||
model={model}
|
||||
/>
|
||||
</Text>
|
||||
{corgiMode && (
|
||||
<Text>
|
||||
<Text color={Colors.Gray}>| </Text>
|
||||
<Text color={Colors.AccentRed}>▼</Text>
|
||||
<Text color={Colors.Foreground}>(´</Text>
|
||||
<Text color={Colors.AccentRed}>ᴥ</Text>
|
||||
<Text color={Colors.Foreground}>`)</Text>
|
||||
<Text color={Colors.AccentRed}>▼ </Text>
|
||||
<Text color={theme.ui.symbol}>| </Text>
|
||||
<Text color={theme.status.error}>▼</Text>
|
||||
<Text color={theme.text.primary}>(´</Text>
|
||||
<Text color={theme.status.error}>ᴥ</Text>
|
||||
<Text color={theme.text.primary}>`)</Text>
|
||||
<Text color={theme.status.error}>▼ </Text>
|
||||
</Text>
|
||||
)}
|
||||
{!showErrorDetails && errorCount > 0 && (
|
||||
<Box>
|
||||
<Text color={Colors.Gray}>| </Text>
|
||||
<Text color={theme.ui.symbol}>| </Text>
|
||||
<ConsoleSummaryDisplay errorCount={errorCount} />
|
||||
</Box>
|
||||
)}
|
||||
|
||||
44
packages/cli/src/ui/components/Header.test.tsx
Normal file
44
packages/cli/src/ui/components/Header.test.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { render } from 'ink-testing-library';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { Header } from './Header.js';
|
||||
import * as useTerminalSize from '../hooks/useTerminalSize.js';
|
||||
import { longAsciiLogo } from './AsciiArt.js';
|
||||
|
||||
vi.mock('../hooks/useTerminalSize.js');
|
||||
|
||||
describe('<Header />', () => {
|
||||
beforeEach(() => {});
|
||||
|
||||
it('renders the long logo on a wide terminal', () => {
|
||||
vi.spyOn(useTerminalSize, 'useTerminalSize').mockReturnValue({
|
||||
columns: 120,
|
||||
rows: 20,
|
||||
});
|
||||
const { lastFrame } = render(<Header version="1.0.0" nightly={false} />);
|
||||
expect(lastFrame()).toContain(longAsciiLogo);
|
||||
});
|
||||
|
||||
it('renders custom ASCII art when provided', () => {
|
||||
const customArt = 'CUSTOM ART';
|
||||
const { lastFrame } = render(
|
||||
<Header version="1.0.0" nightly={false} customAsciiArt={customArt} />,
|
||||
);
|
||||
expect(lastFrame()).toContain(customArt);
|
||||
});
|
||||
|
||||
it('displays the version number when nightly is true', () => {
|
||||
const { lastFrame } = render(<Header version="1.0.0" nightly={true} />);
|
||||
expect(lastFrame()).toContain('v1.0.0');
|
||||
});
|
||||
|
||||
it('does not display the version number when nightly is false', () => {
|
||||
const { lastFrame } = render(<Header version="1.0.0" nightly={false} />);
|
||||
expect(lastFrame()).not.toContain('v1.0.0');
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user