Merge branch 'zed-industries:main' into win-legacy-compat

This commit is contained in:
kevin-mai 2026-05-27 21:12:58 +08:00 committed by GitHub
commit 27a07cf75b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
497 changed files with 53955 additions and 21222 deletions

View file

@ -44,6 +44,7 @@ jobs:
uses: zed-industries/zed/.github/workflows/deploy_docs.yml@main
secrets:
DOCS_AMPLITUDE_API_KEY: ${{ secrets.DOCS_AMPLITUDE_API_KEY }}
DOCS_CONSENT_IO_INSTANCE: ${{ secrets.DOCS_CONSENT_IO_INSTANCE }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
with:

View file

@ -74,8 +74,8 @@ jobs:
git diff > autofix.patch
echo "has_changes=true" >> "$GITHUB_OUTPUT"
fi
- name: upload artifact autofix-patch
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: autofix_pr::upload_patch_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: autofix-patch
path: autofix.patch
@ -112,7 +112,7 @@ jobs:
PR_NUMBER: ${{ inputs.pr_number }}
GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }}
- name: autofix_pr::download_patch_artifact
uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c
with:
name: autofix-patch
- name: autofix_pr::commit_changes::apply_patch
@ -122,10 +122,10 @@ jobs:
git commit -am "Autofix"
git push
env:
GIT_COMMITTER_NAME: Zed Zippy
GIT_COMMITTER_EMAIL: 234243425+zed-zippy[bot]@users.noreply.github.com
GIT_AUTHOR_NAME: Zed Zippy
GIT_AUTHOR_NAME: zed-zippy[bot]
GIT_AUTHOR_EMAIL: 234243425+zed-zippy[bot]@users.noreply.github.com
GIT_COMMITTER_NAME: zed-zippy[bot]
GIT_COMMITTER_EMAIL: 234243425+zed-zippy[bot]@users.noreply.github.com
GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }}
concurrency:
group: ${{ github.workflow }}-${{ inputs.pr_number }}

View file

@ -45,9 +45,9 @@ jobs:
COMMIT: ${{ inputs.commit }}
CHANNEL: ${{ inputs.channel }}
GIT_AUTHOR_NAME: zed-zippy[bot]
GIT_AUTHOR_EMAIL: <234243425+zed-zippy[bot]@users.noreply.github.com>
GIT_AUTHOR_EMAIL: 234243425+zed-zippy[bot]@users.noreply.github.com
GIT_COMMITTER_NAME: zed-zippy[bot]
GIT_COMMITTER_EMAIL: <234243425+zed-zippy[bot]@users.noreply.github.com>
GIT_COMMITTER_EMAIL: 234243425+zed-zippy[bot]@users.noreply.github.com
GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }}
defaults:
run:

View file

@ -69,8 +69,8 @@ jobs:
env:
BASE: ${{ inputs.base }}
HEAD: ${{ inputs.head }}
- name: '@actions/upload-artifact results.md'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: results.md
path: results.md

View file

@ -42,9 +42,9 @@ jobs:
GITHUB_APP_KEY: ${{ secrets.ZED_ZIPPY_APP_PRIVATE_KEY }}
LATEST_TAG: ${{ steps.determine-version.outputs.tag }}
continue-on-error: true
- name: '@actions/upload-artifact compliance-report-${{ github.ref_name }}.md'
- name: run_bundling::upload_artifact
if: always()
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: compliance-report-${{ github.ref_name }}.md
path: compliance-report-${{ github.ref_name }}.md

View file

@ -16,6 +16,9 @@ on:
DOCS_AMPLITUDE_API_KEY:
description: DOCS_AMPLITUDE_API_KEY
required: true
DOCS_CONSENT_IO_INSTANCE:
description: DOCS_CONSENT_IO_INSTANCE
required: true
CLOUDFLARE_API_TOKEN:
description: CLOUDFLARE_API_TOKEN
required: true
@ -39,6 +42,7 @@ jobs:
runs-on: namespace-profile-16x32-ubuntu-2204
env:
DOCS_AMPLITUDE_API_KEY: ${{ secrets.DOCS_AMPLITUDE_API_KEY }}
DOCS_CONSENT_IO_INSTANCE: ${{ secrets.DOCS_CONSENT_IO_INSTANCE }}
CC: clang
CXX: clang++
steps:
@ -143,7 +147,7 @@ jobs:
command: deploy .cloudflare/docs-proxy/src/worker.js
- name: deploy_docs::docs_deploy_steps::upload_wrangler_logs
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: wrangler_logs
path: /home/runner/.config/.wrangler/logs/

View file

@ -13,6 +13,7 @@ jobs:
uses: zed-industries/zed/.github/workflows/deploy_docs.yml@main
secrets:
DOCS_AMPLITUDE_API_KEY: ${{ secrets.DOCS_AMPLITUDE_API_KEY }}
DOCS_CONSENT_IO_INSTANCE: ${{ secrets.DOCS_CONSENT_IO_INSTANCE }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
with:

View file

@ -5,7 +5,7 @@ env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: '1'
CARGO_INCREMENTAL: '0'
ZED_EXTENSION_CLI_SHA: 1fa7f1a3ec28ea1eae6db2e937d7a538fb10c0c7
ZED_EXTENSION_CLI_SHA: 2a00db06ce6d01089bfafd207b6348078e980df9
on:
workflow_call:
inputs:
@ -187,10 +187,10 @@ jobs:
env:
CURRENT_VERSION: ${{ needs.check_version_changed.outputs.current_version }}
WORKING_DIR: ${{ inputs.working-directory }}
- name: extension_bump::create_version_tag
- name: steps::create_tag
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b
with:
script: |-
script: |
github.rest.git.createRef({
owner: context.repo.owner,
repo: context.repo.repo,
@ -239,10 +239,9 @@ jobs:
tag: ${{ needs.create_version_label.outputs.tag }}
env:
COMMITTER_TOKEN: ${{ steps.generate-token.outputs.token }}
- name: extension_bump::enable_automerge_if_staff
- name: enable_automerge_if_staff
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b
with:
github-token: ${{ steps.generate-token.outputs.token }}
script: |
const prNumber = process.env.PR_NUMBER;
if (!prNumber) {
@ -301,6 +300,7 @@ jobs:
`, { pullRequestId: pr.node_id });
console.log(`Automerge enabled for PR #${prNumber} in zed-industries/extensions`);
github-token: ${{ steps.generate-token.outputs.token }}
env:
PR_NUMBER: ${{ steps.extension-update.outputs.pull-request-number }}
defaults:

View file

@ -5,7 +5,7 @@ env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: '1'
CARGO_INCREMENTAL: '0'
ZED_EXTENSION_CLI_SHA: 1fa7f1a3ec28ea1eae6db2e937d7a538fb10c0c7
ZED_EXTENSION_CLI_SHA: 2a00db06ce6d01089bfafd207b6348078e980df9
RUSTUP_TOOLCHAIN: stable
CARGO_BUILD_TARGET: wasm32-wasip2
on:
@ -149,7 +149,7 @@ jobs:
- name: run_tests::run_ts_query_ls
run: |-
tar -xf "$GITHUB_WORKSPACE/ts_query_ls-x86_64-unknown-linux-gnu.tar.gz" -C "$GITHUB_WORKSPACE"
"$GITHUB_WORKSPACE/ts_query_ls" format --check . || {
"$GITHUB_WORKSPACE/ts_query_ls" format --check languages || {
echo "Found unformatted queries, please format them with ts_query_ls."
echo "For easy use, install the Tree-sitter query extension:"
echo "zed://extension/tree-sitter-query"

View file

@ -56,7 +56,7 @@ jobs:
env:
PREV_COMMIT: ${{ steps.prev-tag.outputs.prev_commit }}
- id: list-repos
name: extension_workflow_rollout::fetch_extension_repos::get_repositories
name: get_repositories
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b
with:
script: |
@ -91,7 +91,7 @@ jobs:
env:
COMMIT_SHA: ${{ github.sha }}
- name: extension_workflow_rollout::fetch_extension_repos::upload_workflow_files
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: extension-workflow-files
path: extensions/workflows/**/*.yml
@ -132,7 +132,7 @@ jobs:
repository: zed-extensions/${{ matrix.repo }}
token: ${{ steps.generate-token.outputs.token }}
- name: extension_workflow_rollout::rollout_workflows_to_extension::download_workflow_files
uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c
with:
name: extension-workflow-files
path: workflow-files
@ -220,10 +220,6 @@ jobs:
clean: false
fetch-depth: 0
token: ${{ steps.generate-token.outputs.token }}
- name: extension_workflow_rollout::create_rollout_tag::configure_git
run: |
git config user.name "zed-zippy[bot]"
git config user.email "234243425+zed-zippy[bot]@users.noreply.github.com"
- name: extension_workflow_rollout::create_rollout_tag::update_rollout_tag
run: |
if git rev-parse "extension-workflows" >/dev/null 2>&1; then
@ -234,6 +230,11 @@ jobs:
echo "Creating new tag 'extension-workflows' at $(git rev-parse --short HEAD)"
git tag "extension-workflows"
git push origin "extension-workflows"
env:
GIT_AUTHOR_NAME: zed-zippy[bot]
GIT_AUTHOR_EMAIL: 234243425+zed-zippy[bot]@users.noreply.github.com
GIT_COMMITTER_NAME: zed-zippy[bot]
GIT_COMMITTER_EMAIL: 234243425+zed-zippy[bot]@users.noreply.github.com
timeout-minutes: 1
defaults:
run:

View file

@ -321,9 +321,9 @@ jobs:
GITHUB_APP_ID: ${{ secrets.ZED_ZIPPY_APP_ID }}
GITHUB_APP_KEY: ${{ secrets.ZED_ZIPPY_APP_PRIVATE_KEY }}
continue-on-error: true
- name: '@actions/upload-artifact compliance-report-${{ github.ref_name }}.md'
- name: run_bundling::upload_artifact
if: always()
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: compliance-report-${{ github.ref_name }}.md
path: compliance-report-${{ github.ref_name }}.md
@ -377,14 +377,14 @@ jobs:
run: ./script/download-wasi-sdk
- name: ./script/bundle-linux
run: ./script/bundle-linux
- name: '@actions/upload-artifact zed-linux-aarch64.tar.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-linux-aarch64.tar.gz
path: target/release/zed-linux-aarch64.tar.gz
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-linux-aarch64.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-linux-aarch64.gz
path: target/zed-remote-server-linux-aarch64.gz
@ -417,14 +417,14 @@ jobs:
run: ./script/download-wasi-sdk
- name: ./script/bundle-linux
run: ./script/bundle-linux
- name: '@actions/upload-artifact zed-linux-x86_64.tar.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-linux-x86_64.tar.gz
path: target/release/zed-linux-x86_64.tar.gz
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-linux-x86_64.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-linux-x86_64.gz
path: target/zed-remote-server-linux-x86_64.gz
@ -462,14 +462,14 @@ jobs:
run: ./script/clear-target-dir-if-larger-than 350 200
- name: run_bundling::bundle_mac::bundle_mac
run: ./script/bundle-mac aarch64-apple-darwin
- name: '@actions/upload-artifact Zed-aarch64.dmg'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: Zed-aarch64.dmg
path: target/aarch64-apple-darwin/release/Zed-aarch64.dmg
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-macos-aarch64.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-macos-aarch64.gz
path: target/zed-remote-server-macos-aarch64.gz
@ -507,14 +507,14 @@ jobs:
run: ./script/clear-target-dir-if-larger-than 350 200
- name: run_bundling::bundle_mac::bundle_mac
run: ./script/bundle-mac x86_64-apple-darwin
- name: '@actions/upload-artifact Zed-x86_64.dmg'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: Zed-x86_64.dmg
path: target/x86_64-apple-darwin/release/Zed-x86_64.dmg
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-macos-x86_64.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-macos-x86_64.gz
path: target/zed-remote-server-macos-x86_64.gz
@ -552,14 +552,14 @@ jobs:
run: script/bundle-windows.ps1 -Architecture aarch64
shell: pwsh
working-directory: ${{ env.ZED_WORKSPACE }}
- name: '@actions/upload-artifact Zed-aarch64.exe'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: Zed-aarch64.exe
path: target/Zed-aarch64.exe
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-windows-aarch64.zip'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-windows-aarch64.zip
path: target/zed-remote-server-windows-aarch64.zip
@ -597,14 +597,14 @@ jobs:
run: script/bundle-windows.ps1 -Architecture x86_64
shell: pwsh
working-directory: ${{ env.ZED_WORKSPACE }}
- name: '@actions/upload-artifact Zed-x86_64.exe'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: Zed-x86_64.exe
path: target/Zed-x86_64.exe
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-windows-x86_64.zip'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-windows-x86_64.zip
path: target/zed-remote-server-windows-x86_64.zip
@ -622,7 +622,7 @@ jobs:
runs-on: namespace-profile-4x8-ubuntu-2204
steps:
- name: release::download_workflow_artifacts
uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c
with:
path: ./artifacts/
- name: ls -lR ./artifacts
@ -694,9 +694,9 @@ jobs:
env:
GITHUB_APP_ID: ${{ secrets.ZED_ZIPPY_APP_ID }}
GITHUB_APP_KEY: ${{ secrets.ZED_ZIPPY_APP_PRIVATE_KEY }}
- name: '@actions/upload-artifact compliance-report-${{ github.ref_name }}.md'
- name: run_bundling::upload_artifact
if: always()
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: compliance-report-${{ github.ref_name }}.md
path: compliance-report-${{ github.ref_name }}.md

View file

@ -5,29 +5,40 @@ env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: '1'
on:
push:
tags:
- nightly
schedule:
- cron: 0 7 * * *
- cron: 0 */4 * * *
workflow_dispatch: {}
jobs:
check_style:
check_nightly_tag:
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions')
runs-on: namespace-profile-mac-large
runs-on: namespace-profile-2x4-ubuntu-2404
steps:
- name: steps::checkout_repo
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
with:
clean: false
fetch-depth: 0
- name: steps::cargo_fmt
run: cargo fmt --all -- --check
- name: ./script/clippy
run: ./script/clippy
timeout-minutes: 60
run_tests_windows:
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions')
runs-on: self-32vcpu-windows-2022
fetch-tags: true
- id: check
name: release_nightly::check_nightly_tag
run: |
NIGHTLY_SHA=$(git rev-parse "nightly" 2>/dev/null || echo "")
if [ "$NIGHTLY_SHA" = "$GITHUB_SHA" ]; then
echo "Nightly tag already points to current commit. Skipping."
echo "skip=true" >> "$GITHUB_OUTPUT"
else
echo "skip=false" >> "$GITHUB_OUTPUT"
fi
outputs:
skip: ${{ steps.check.outputs.skip }}
timeout-minutes: 5
run_tests_linux:
needs:
- check_nightly_tag
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') && needs.check_nightly_tag.outputs.skip != 'true'
runs-on: namespace-profile-16x32-ubuntu-2204
env:
CC: clang
CXX: clang++
steps:
- name: steps::checkout_repo
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
@ -35,19 +46,27 @@ jobs:
clean: false
- name: steps::setup_cargo_config
run: |
New-Item -ItemType Directory -Path "./../.cargo" -Force
Copy-Item -Path "./.cargo/ci-config.toml" -Destination "./../.cargo/config.toml"
shell: pwsh
mkdir -p ./../.cargo
cp ./.cargo/ci-config.toml ./../.cargo/config.toml
- name: steps::cache_rust_dependencies_namespace
uses: namespacelabs/nscloud-cache-action@a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9
with:
cache: rust
path: ~/.rustup
- name: steps::setup_linux
run: ./script/linux
- name: steps::download_wasi_sdk
run: ./script/download-wasi-sdk
- name: steps::setup_node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version: '20'
- name: steps::cargo_install_nextest
uses: taiki-e/install-action@921e2c9f7148d7ba14cd819f417db338f63e733c
- name: steps::clear_target_dir_if_large
run: ./script/clear-target-dir-if-larger-than.ps1 350 200
shell: pwsh
run: ./script/clear-target-dir-if-larger-than 350 200
- name: steps::setup_sccache
run: ./script/setup-sccache.ps1
shell: pwsh
run: ./script/setup-sccache
env:
R2_ACCOUNT_ID: ${{ secrets.R2_ACCOUNT_ID }}
R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
@ -55,49 +74,24 @@ jobs:
SCCACHE_BUCKET: sccache-zed
- name: steps::cargo_nextest
run: cargo nextest run --workspace --no-fail-fast --no-tests=warn
shell: pwsh
- name: steps::show_sccache_stats
run: if ($env:RUSTC_WRAPPER) { & $env:RUSTC_WRAPPER --show-stats }; exit 0
shell: pwsh
run: sccache --show-stats || true
- name: steps::cleanup_cargo_config
if: always()
run: |
Remove-Item -Recurse -Path "./../.cargo" -Force -ErrorAction SilentlyContinue
shell: pwsh
timeout-minutes: 60
clippy_windows:
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions')
runs-on: self-32vcpu-windows-2022
steps:
- name: steps::checkout_repo
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
with:
clean: false
- name: steps::setup_cargo_config
run: |
New-Item -ItemType Directory -Path "./../.cargo" -Force
Copy-Item -Path "./.cargo/ci-config.toml" -Destination "./../.cargo/config.toml"
shell: pwsh
- name: steps::setup_sccache
run: ./script/setup-sccache.ps1
shell: pwsh
env:
R2_ACCOUNT_ID: ${{ secrets.R2_ACCOUNT_ID }}
R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
SCCACHE_BUCKET: sccache-zed
- name: steps::clippy
run: ./script/clippy.ps1
shell: pwsh
- name: steps::show_sccache_stats
run: if ($env:RUSTC_WRAPPER) { & $env:RUSTC_WRAPPER --show-stats }; exit 0
shell: pwsh
rm -rf ./../.cargo
timeout-minutes: 60
services:
postgres:
image: postgres:15
env:
POSTGRES_HOST_AUTH_METHOD: trust
ports:
- 5432:5432
options: --health-cmd pg_isready --health-interval 500ms --health-timeout 5s --health-retries 10
bundle_linux_aarch64:
needs:
- check_style
- run_tests_windows
- clippy_windows
- run_tests_linux
runs-on: namespace-profile-8x32-ubuntu-2004-arm-m4
env:
CARGO_INCREMENTAL: 0
@ -126,14 +120,14 @@ jobs:
run: ./script/download-wasi-sdk
- name: ./script/bundle-linux
run: ./script/bundle-linux
- name: '@actions/upload-artifact zed-linux-aarch64.tar.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-linux-aarch64.tar.gz
path: target/release/zed-linux-aarch64.tar.gz
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-linux-aarch64.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-linux-aarch64.gz
path: target/zed-remote-server-linux-aarch64.gz
@ -141,9 +135,7 @@ jobs:
timeout-minutes: 60
bundle_linux_x86_64:
needs:
- check_style
- run_tests_windows
- clippy_windows
- run_tests_linux
runs-on: namespace-profile-32x64-ubuntu-2004
env:
CARGO_INCREMENTAL: 0
@ -172,14 +164,14 @@ jobs:
run: ./script/download-wasi-sdk
- name: ./script/bundle-linux
run: ./script/bundle-linux
- name: '@actions/upload-artifact zed-linux-x86_64.tar.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-linux-x86_64.tar.gz
path: target/release/zed-linux-x86_64.tar.gz
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-linux-x86_64.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-linux-x86_64.gz
path: target/zed-remote-server-linux-x86_64.gz
@ -187,9 +179,7 @@ jobs:
timeout-minutes: 60
bundle_mac_aarch64:
needs:
- check_style
- run_tests_windows
- clippy_windows
- run_tests_linux
runs-on: namespace-profile-mac-large
env:
CARGO_INCREMENTAL: 0
@ -223,14 +213,14 @@ jobs:
run: ./script/clear-target-dir-if-larger-than 350 200
- name: run_bundling::bundle_mac::bundle_mac
run: ./script/bundle-mac aarch64-apple-darwin
- name: '@actions/upload-artifact Zed-aarch64.dmg'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: Zed-aarch64.dmg
path: target/aarch64-apple-darwin/release/Zed-aarch64.dmg
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-macos-aarch64.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-macos-aarch64.gz
path: target/zed-remote-server-macos-aarch64.gz
@ -238,9 +228,7 @@ jobs:
timeout-minutes: 60
bundle_mac_x86_64:
needs:
- check_style
- run_tests_windows
- clippy_windows
- run_tests_linux
runs-on: namespace-profile-mac-large
env:
CARGO_INCREMENTAL: 0
@ -274,14 +262,14 @@ jobs:
run: ./script/clear-target-dir-if-larger-than 350 200
- name: run_bundling::bundle_mac::bundle_mac
run: ./script/bundle-mac x86_64-apple-darwin
- name: '@actions/upload-artifact Zed-x86_64.dmg'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: Zed-x86_64.dmg
path: target/x86_64-apple-darwin/release/Zed-x86_64.dmg
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-macos-x86_64.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-macos-x86_64.gz
path: target/zed-remote-server-macos-x86_64.gz
@ -289,9 +277,7 @@ jobs:
timeout-minutes: 60
bundle_windows_aarch64:
needs:
- check_style
- run_tests_windows
- clippy_windows
- run_tests_linux
runs-on: self-32vcpu-windows-2022
env:
CARGO_INCREMENTAL: 0
@ -327,14 +313,14 @@ jobs:
run: script/bundle-windows.ps1 -Architecture aarch64
shell: pwsh
working-directory: ${{ env.ZED_WORKSPACE }}
- name: '@actions/upload-artifact Zed-aarch64.exe'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: Zed-aarch64.exe
path: target/Zed-aarch64.exe
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-windows-aarch64.zip'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-windows-aarch64.zip
path: target/zed-remote-server-windows-aarch64.zip
@ -342,9 +328,7 @@ jobs:
timeout-minutes: 60
bundle_windows_x86_64:
needs:
- check_style
- run_tests_windows
- clippy_windows
- run_tests_linux
runs-on: self-32vcpu-windows-2022
env:
CARGO_INCREMENTAL: 0
@ -380,14 +364,14 @@ jobs:
run: script/bundle-windows.ps1 -Architecture x86_64
shell: pwsh
working-directory: ${{ env.ZED_WORKSPACE }}
- name: '@actions/upload-artifact Zed-x86_64.exe'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: Zed-x86_64.exe
path: target/Zed-x86_64.exe
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-windows-x86_64.zip'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-windows-x86_64.zip
path: target/zed-remote-server-windows-x86_64.zip
@ -395,8 +379,7 @@ jobs:
timeout-minutes: 60
build_nix_linux_x86_64:
needs:
- check_style
- run_tests_windows
- run_tests_linux
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions')
runs-on: namespace-profile-32x64-ubuntu-2004
env:
@ -429,8 +412,7 @@ jobs:
continue-on-error: true
build_nix_mac_aarch64:
needs:
- check_style
- run_tests_windows
- run_tests_linux
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions')
runs-on: namespace-profile-mac-large
env:
@ -487,13 +469,20 @@ jobs:
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions')
runs-on: namespace-profile-4x8-ubuntu-2204
steps:
- id: generate-token
name: steps::authenticate_as_zippy
uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859
with:
app-id: ${{ secrets.ZED_ZIPPY_APP_ID }}
private-key: ${{ secrets.ZED_ZIPPY_APP_PRIVATE_KEY }}
permission-contents: write
- name: steps::checkout_repo
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
with:
clean: false
fetch-depth: 0
fetch-tags: true
- name: release::download_workflow_artifacts
uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c
with:
path: ./artifacts/
- name: ls -lR ./artifacts
@ -519,16 +508,18 @@ jobs:
env:
DIGITALOCEAN_SPACES_ACCESS_KEY: ${{ secrets.DIGITALOCEAN_SPACES_ACCESS_KEY }}
DIGITALOCEAN_SPACES_SECRET_KEY: ${{ secrets.DIGITALOCEAN_SPACES_SECRET_KEY }}
- name: release_nightly::update_nightly_tag_job::update_nightly_tag
run: |
if [ "$(git rev-parse nightly)" = "$(git rev-parse HEAD)" ]; then
echo "Nightly tag already points to current commit. Skipping tagging."
exit 0
fi
git config user.name github-actions
git config user.email github-actions@github.com
git tag -f nightly
git push origin nightly --force
- name: steps::update_tag
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b
with:
script: |
github.rest.git.updateRef({
owner: context.repo.owner,
repo: context.repo.repo,
ref: 'tags/nightly',
sha: context.sha,
force: true
})
github-token: ${{ steps.generate-token.outputs.token }}
- name: release::create_sentry_release
uses: getsentry/action-release@526942b68292201ac6bbb99b9a0747d4abee354c
with:
@ -554,6 +545,9 @@ jobs:
env:
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK_WORKFLOW_FAILURES }}
SLACK_MESSAGE: '❌ ${{ github.workflow }} failed: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}'
concurrency:
group: release-nightly
cancel-in-progress: true
defaults:
run:
shell: bash -euxo pipefail {0}

View file

@ -36,14 +36,14 @@ jobs:
run: ./script/download-wasi-sdk
- name: ./script/bundle-linux
run: ./script/bundle-linux
- name: '@actions/upload-artifact zed-linux-aarch64.tar.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-linux-aarch64.tar.gz
path: target/release/zed-linux-aarch64.tar.gz
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-linux-aarch64.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-linux-aarch64.gz
path: target/zed-remote-server-linux-aarch64.gz
@ -75,14 +75,14 @@ jobs:
run: ./script/download-wasi-sdk
- name: ./script/bundle-linux
run: ./script/bundle-linux
- name: '@actions/upload-artifact zed-linux-x86_64.tar.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-linux-x86_64.tar.gz
path: target/release/zed-linux-x86_64.tar.gz
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-linux-x86_64.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-linux-x86_64.gz
path: target/zed-remote-server-linux-x86_64.gz
@ -119,14 +119,14 @@ jobs:
run: ./script/clear-target-dir-if-larger-than 350 200
- name: run_bundling::bundle_mac::bundle_mac
run: ./script/bundle-mac aarch64-apple-darwin
- name: '@actions/upload-artifact Zed-aarch64.dmg'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: Zed-aarch64.dmg
path: target/aarch64-apple-darwin/release/Zed-aarch64.dmg
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-macos-aarch64.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-macos-aarch64.gz
path: target/zed-remote-server-macos-aarch64.gz
@ -163,14 +163,14 @@ jobs:
run: ./script/clear-target-dir-if-larger-than 350 200
- name: run_bundling::bundle_mac::bundle_mac
run: ./script/bundle-mac x86_64-apple-darwin
- name: '@actions/upload-artifact Zed-x86_64.dmg'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: Zed-x86_64.dmg
path: target/x86_64-apple-darwin/release/Zed-x86_64.dmg
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-macos-x86_64.gz'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-macos-x86_64.gz
path: target/zed-remote-server-macos-x86_64.gz
@ -207,14 +207,14 @@ jobs:
run: script/bundle-windows.ps1 -Architecture aarch64
shell: pwsh
working-directory: ${{ env.ZED_WORKSPACE }}
- name: '@actions/upload-artifact Zed-aarch64.exe'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: Zed-aarch64.exe
path: target/Zed-aarch64.exe
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-windows-aarch64.zip'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-windows-aarch64.zip
path: target/zed-remote-server-windows-aarch64.zip
@ -251,14 +251,14 @@ jobs:
run: script/bundle-windows.ps1 -Architecture x86_64
shell: pwsh
working-directory: ${{ env.ZED_WORKSPACE }}
- name: '@actions/upload-artifact Zed-x86_64.exe'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: Zed-x86_64.exe
path: target/Zed-x86_64.exe
if-no-files-found: error
- name: '@actions/upload-artifact zed-remote-server-windows-x86_64.zip'
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
- name: run_bundling::upload_artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: zed-remote-server-windows-x86_64.zip
path: target/zed-remote-server-windows-x86_64.zip

View file

@ -448,6 +448,34 @@ jobs:
run: |
rm -rf ./../.cargo
timeout-minutes: 60
miri_scheduler:
needs:
- orchestrate
if: needs.orchestrate.outputs.run_tests == 'true' && github.event_name != 'merge_group'
runs-on: namespace-profile-16x32-ubuntu-2204
steps:
- name: steps::checkout_repo
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
with:
clean: false
- name: steps::setup_cargo_config
run: |
mkdir -p ./../.cargo
cp ./.cargo/ci-config.toml ./../.cargo/config.toml
- name: steps::cache_rust_dependencies_namespace
uses: namespacelabs/nscloud-cache-action@a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9
with:
cache: rust
path: ~/.rustup
- name: run_tests::miri_scheduler::install_miri
run: rustup toolchain install nightly --profile minimal --component miri --component rust-src
- name: run_tests::miri_scheduler::run_scheduler_tests_under_miri
run: cargo +nightly -q miri test -p scheduler
- name: steps::cleanup_cargo_config
if: always()
run: |
rm -rf ./../.cargo
timeout-minutes: 60
doctests:
needs:
- orchestrate
@ -640,6 +668,7 @@ jobs:
runs-on: namespace-profile-16x32-ubuntu-2204
env:
DOCS_AMPLITUDE_API_KEY: ${{ secrets.DOCS_AMPLITUDE_API_KEY }}
DOCS_CONSENT_IO_INSTANCE: ${{ secrets.DOCS_CONSENT_IO_INSTANCE }}
CC: clang
CXX: clang++
steps:
@ -804,6 +833,7 @@ jobs:
- run_tests_windows
- run_tests_linux
- run_tests_mac
- miri_scheduler
- doctests
- check_workspace_binaries
- build_visual_tests_binary
@ -835,6 +865,7 @@ jobs:
check_result "run_tests_windows" "$RESULT_RUN_TESTS_WINDOWS"
check_result "run_tests_linux" "$RESULT_RUN_TESTS_LINUX"
check_result "run_tests_mac" "$RESULT_RUN_TESTS_MAC"
check_result "miri_scheduler" "$RESULT_MIRI_SCHEDULER"
check_result "doctests" "$RESULT_DOCTESTS"
check_result "check_workspace_binaries" "$RESULT_CHECK_WORKSPACE_BINARIES"
check_result "build_visual_tests_binary" "$RESULT_BUILD_VISUAL_TESTS_BINARY"
@ -856,6 +887,7 @@ jobs:
RESULT_RUN_TESTS_WINDOWS: ${{ needs.run_tests_windows.result }}
RESULT_RUN_TESTS_LINUX: ${{ needs.run_tests_linux.result }}
RESULT_RUN_TESTS_MAC: ${{ needs.run_tests_mac.result }}
RESULT_MIRI_SCHEDULER: ${{ needs.miri_scheduler.result }}
RESULT_DOCTESTS: ${{ needs.doctests.result }}
RESULT_CHECK_WORKSPACE_BINARIES: ${{ needs.check_workspace_binaries.result }}
RESULT_BUILD_VISUAL_TESTS_BINARY: ${{ needs.build_visual_tests_binary.result }}

View file

@ -16,8 +16,9 @@ jobs:
github.event_name == 'issues' &&
github.repository == 'zed-industries/zed' &&
github.event.issue.pull_request == null &&
github.event.issue.type != null &&
(github.event.issue.type.name == 'Bug' || github.event.issue.type.name == 'Crash')
(github.event.issue.type == null ||
github.event.issue.type.name == 'Bug' ||
github.event.issue.type.name == 'Crash')
runs-on: ubuntu-latest
timeout-minutes: 5
steps:

214
Cargo.lock generated
View file

@ -81,6 +81,7 @@ dependencies = [
"futures 0.3.32",
"git",
"gpui",
"indoc",
"language",
"log",
"pretty_assertions",
@ -223,13 +224,14 @@ dependencies = [
[[package]]
name = "agent-client-protocol"
version = "0.11.1"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af62fb84df2af0f933d8f5fd78b843fa5eb0ec5a48fa1b528c41951d0bbe36c"
checksum = "4361ba6627e51de955b10f3c77fb9eb959c85191a236c1c2c84e32f4ff240faf"
dependencies = [
"agent-client-protocol-derive",
"agent-client-protocol-schema",
"anyhow",
"async-process",
"blocking",
"futures 0.3.32",
"futures-concurrency",
"jsonrpcmsg",
@ -238,7 +240,7 @@ dependencies = [
"schemars 1.0.4",
"serde",
"serde_json",
"thiserror 2.0.17",
"shell-words",
"tokio",
"tokio-util",
"tracing",
@ -247,20 +249,19 @@ dependencies = [
[[package]]
name = "agent-client-protocol-derive"
version = "0.11.0"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce42c2d3c048c12897eef2e577dfff1e3355c632c9f1625cc953b9df48b44631"
checksum = "cabdc9d845d08ec7ed2d0c9de1ae4a1b198301407d55855261572761be90ec9f"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "agent-client-protocol-schema"
version = "0.12.0"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49bae57dad1c28a362fbdcf7bab0583316a02b45a70792109fced55780a3b63c"
checksum = "b957d8391ac3933e2a940446171c508d2b8ffc386d8fa7d0b9c936a2575b463e"
dependencies = [
"anyhow",
"derive_more",
@ -344,6 +345,7 @@ name = "agent_skills"
version = "0.1.0"
dependencies = [
"anyhow",
"const_format",
"fs",
"futures 0.3.32",
"gpui",
@ -364,6 +366,7 @@ dependencies = [
"agent-client-protocol",
"agent_servers",
"agent_settings",
"agent_skills",
"ai_onboarding",
"anyhow",
"async-channel 2.5.0",
@ -404,6 +407,7 @@ dependencies = [
"language_models",
"languages",
"log",
"lru",
"lsp",
"markdown",
"menu",
@ -435,6 +439,7 @@ dependencies = [
"serde_json",
"serde_json_lenient",
"settings",
"skill_creator",
"streaming_diff",
"task",
"telemetry",
@ -1290,22 +1295,20 @@ dependencies = [
name = "auto_update_ui"
version = "0.1.0"
dependencies = [
"agent_settings",
"agent_skills",
"anyhow",
"auto_update",
"client",
"db",
"editor",
"fs",
"gpui",
"markdown_preview",
"notifications",
"project",
"prompt_store",
"release_channel",
"semver",
"serde",
"serde_json",
"settings",
"smol",
"telemetry",
"ui",
@ -2251,6 +2254,15 @@ dependencies = [
"utf8-chars",
]
[[package]]
name = "bs58"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4"
dependencies = [
"tinyvec",
]
[[package]]
name = "bstr"
version = "1.12.1"
@ -2269,8 +2281,8 @@ dependencies = [
"clock",
"ctor",
"futures 0.3.32",
"git2",
"gpui",
"imara-diff",
"language",
"log",
"pretty_assertions",
@ -2995,7 +3007,6 @@ dependencies = [
"cloud_llm_client",
"collections",
"credentials_provider",
"db",
"derive_more",
"feature_flags",
"fs",
@ -3597,6 +3608,7 @@ dependencies = [
"http_client",
"log",
"net",
"oauth_callback_server",
"parking_lot",
"pollster 0.4.0",
"postage",
@ -3608,7 +3620,6 @@ dependencies = [
"sha2",
"slotmap",
"tempfile",
"tiny_http",
"url",
"util",
]
@ -3903,9 +3914,9 @@ dependencies = [
[[package]]
name = "cosmic-text"
version = "0.17.1"
version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c5c9868e64aa6c5410629a83450e142c80e721c727a5bc0fb18107af6c2d66b"
checksum = "be17b688510d934ce13f48a2beba700e11583e281e0fda99c22bb256a14eda73"
dependencies = [
"bitflags 2.10.0",
"fontdb",
@ -4369,20 +4380,14 @@ dependencies = [
[[package]]
name = "ctor"
version = "0.4.3"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec09e802f5081de6157da9a75701d6c713d8dc3ba52571fd4bd25f412644e8a6"
checksum = "6d765eb1c0bda10d31e0ea185f5ee15da532d60b0912d2bd1441783439e749c5"
dependencies = [
"ctor-proc-macro",
"dtor",
"link-section",
"linktime-proc-macro",
]
[[package]]
name = "ctor-proc-macro"
version = "0.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2931af7e13dc045d8e9d26afccc6fa115d64e115c9c84b1166288b46f6782c2"
[[package]]
name = "ctrlc"
version = "3.5.0"
@ -4928,6 +4933,7 @@ dependencies = [
"gpui",
"http 1.3.1",
"http_client",
"indoc",
"log",
"menu",
"paths",
@ -4937,6 +4943,7 @@ dependencies = [
"serde",
"serde_json",
"serde_json_lenient",
"serde_yaml",
"settings",
"shlex",
"ui",
@ -5168,21 +5175,6 @@ dependencies = [
"dtoa",
]
[[package]]
name = "dtor"
version = "0.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97cbdf2ad6846025e8e25df05171abfb30e3ababa12ee0a0e44b9bbe570633a8"
dependencies = [
"dtor-proc-macro",
]
[[package]]
name = "dtor-proc-macro"
version = "0.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7454e41ff9012c00d53cf7f475c5e3afa3b91b7c90568495495e8d9bf47a1055"
[[package]]
name = "dunce"
version = "1.0.5"
@ -5952,6 +5944,8 @@ dependencies = [
"settings",
"shellexpand",
"terminal_view",
"theme",
"theme_settings",
"util",
"watch",
]
@ -6088,6 +6082,7 @@ dependencies = [
"snippet_provider",
"task",
"theme_settings",
"thiserror 2.0.17",
"tokio",
"toml 0.8.23",
"tree-sitter",
@ -6153,7 +6148,6 @@ name = "extensions_ui"
version = "0.1.0"
dependencies = [
"anyhow",
"client",
"cloud_api_types",
"collections",
"db",
@ -7364,6 +7358,7 @@ dependencies = [
"project",
"project_panel",
"rand 0.9.4",
"release_channel",
"remote_connection",
"search",
"serde_json",
@ -7447,6 +7442,7 @@ dependencies = [
"settings",
"smallvec",
"strum 0.27.2",
"sysinfo 0.37.2",
"task",
"telemetry",
"theme",
@ -7928,6 +7924,7 @@ dependencies = [
"bytemuck",
"collections",
"cosmic-text",
"criterion",
"etagere",
"gpui",
"gpui_util",
@ -7940,6 +7937,7 @@ dependencies = [
"raw-window-handle",
"smallvec",
"swash",
"unicode-segmentation",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
@ -9633,6 +9631,7 @@ dependencies = [
"futures 0.3.32",
"gpui_shared_string",
"http_client",
"log",
"partial-json-fixer",
"schemars 1.0.4",
"serde",
@ -9683,20 +9682,26 @@ dependencies = [
"log",
"menu",
"mistral",
"oauth_callback_server",
"ollama",
"open_ai",
"open_router",
"opencode",
"parking_lot",
"pretty_assertions",
"rand 0.9.4",
"release_channel",
"schemars 1.0.4",
"serde",
"serde_json",
"settings",
"sha2",
"smol",
"strum 0.27.2",
"tokio",
"ui",
"ui_input",
"url",
"util",
"x_ai",
]
@ -10049,6 +10054,12 @@ dependencies = [
"cc",
]
[[package]]
name = "link-section"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d1e908a416d6e9f725743b84a36feea40c4c131e805fbc26d61f9f451f36080"
[[package]]
name = "linkify"
version = "0.10.0"
@ -10058,6 +10069,12 @@ dependencies = [
"memchr",
]
[[package]]
name = "linktime-proc-macro"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a44cd706ff0d503ee32b2071166510ca27e281228de10cd3aa8d35ff94560f81"
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
@ -10982,8 +10999,8 @@ checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a"
[[package]]
name = "naga"
version = "29.0.0"
source = "git+https://github.com/zed-industries/wgpu.git?branch=v29#a466bc382ea747f8e1ac810efdb6dcd49a514575"
version = "29.0.3"
source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88"
dependencies = [
"arrayvec",
"bit-set 0.9.1",
@ -11156,6 +11173,7 @@ dependencies = [
"async-std",
"async-tar",
"async-trait",
"chrono",
"futures 0.3.32",
"http_client",
"log",
@ -11509,6 +11527,17 @@ dependencies = [
"tokio-util",
]
[[package]]
name = "oauth_callback_server"
version = "0.1.0"
dependencies = [
"anyhow",
"futures 0.3.32",
"log",
"tiny_http",
"url",
]
[[package]]
name = "objc"
version = "0.2.7"
@ -11877,6 +11906,7 @@ dependencies = [
"gpui",
"picker",
"project",
"project_panel",
"schemars 1.0.4",
"serde",
"serde_json",
@ -12271,6 +12301,7 @@ dependencies = [
name = "paths"
version = "0.1.0"
dependencies = [
"const_format",
"dirs",
"ignore",
"util",
@ -13648,6 +13679,7 @@ dependencies = [
"assets",
"chrono",
"collections",
"db",
"fs",
"futures 0.3.32",
"fuzzy",
@ -13660,6 +13692,7 @@ dependencies = [
"paths",
"rope",
"serde",
"serde_json",
"strum 0.27.2",
"tempfile",
"text",
@ -14681,6 +14714,7 @@ dependencies = [
"smol",
"sysinfo 0.37.2",
"task",
"tempfile",
"theme",
"theme_settings",
"thiserror 2.0.17",
@ -14717,6 +14751,7 @@ dependencies = [
"anyhow",
"async-dispatcher",
"async-task",
"async-trait",
"async-tungstenite",
"base64 0.22.1",
"client",
@ -14749,6 +14784,7 @@ dependencies = [
"settings",
"shlex",
"smol",
"task",
"telemetry",
"terminal",
"terminal_view",
@ -16012,11 +16048,12 @@ dependencies = [
[[package]]
name = "serde_with"
version = "3.18.0"
version = "3.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd5414fad8e6907dbdd5bc441a50ae8d6e26151a03b1de04d89a5576de61d01f"
checksum = "e72c1c2cb7b223fafb600a619537a871c2818583d619401b785e7c0b746ccde2"
dependencies = [
"base64 0.22.1",
"bs58",
"chrono",
"hex",
"indexmap 1.9.3",
@ -16031,9 +16068,9 @@ dependencies = [
[[package]]
name = "serde_with_macros"
version = "3.18.0"
version = "3.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3db8978e608f1fe7357e211969fd9abdcae80bac1ba7a3369bb7eb6b404eb65"
checksum = "b90c488738ecb4fb0262f41f43bc40efc5868d9fb744319ddf5f5317f417bfac"
dependencies = [
"darling 0.23.0",
"proc-macro2",
@ -16190,6 +16227,7 @@ version = "0.1.0"
dependencies = [
"agent",
"agent_settings",
"agent_skills",
"anyhow",
"audio",
"codestral",
@ -16489,6 +16527,32 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d"
[[package]]
name = "skill_creator"
version = "0.1.0"
dependencies = [
"agent_skills",
"anyhow",
"editor",
"fs",
"futures 0.3.32",
"gpui",
"http_client",
"language",
"menu",
"platform_title_bar",
"release_channel",
"serde_json",
"serde_yaml_ng",
"settings",
"theme_settings",
"ui",
"ui_input",
"util",
"workspace",
"worktree",
]
[[package]]
name = "skrifa"
version = "0.37.0"
@ -18726,9 +18790,9 @@ dependencies = [
[[package]]
name = "tree-sitter"
version = "0.26.8"
version = "0.26.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "887bd495d0582c5e3e0d8ece2233666169fa56a9644d172fc22ad179ab2d0538"
checksum = "4dab76d0b724ba557954125188cf0633a1ca43199ced82d95c7b9c32cc3de1f3"
dependencies = [
"cc",
"regex",
@ -19129,7 +19193,9 @@ dependencies = [
"gpui_util",
"icons",
"itertools 0.14.0",
"log",
"menu",
"num-format",
"schemars 1.0.4",
"serde",
"smallvec",
@ -20012,9 +20078,9 @@ dependencies = [
[[package]]
name = "wasmtime-c-api-impl"
version = "36.0.6"
version = "36.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c62ea3fa30e6b0cf61116b3035121b8f515c60ac118ebfdab2ee56d028ed1e"
checksum = "e5e71e971a27df819171b79597c0f1826fc7cf2c168111c64dbc5505a1ffbda7"
dependencies = [
"anyhow",
"log",
@ -20061,9 +20127,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-c-api-macros"
version = "36.0.6"
version = "36.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c8c61294155a6d23c202f08cf7a2f9392a866edd50517508208818be626ce9f"
checksum = "20b9553165039d365931a998d9b60278cc968ba9d81531cecde8ffc3effa1fe3"
dependencies = [
"proc-macro2",
"quote",
@ -20517,8 +20583,8 @@ checksum = "a751b3277700db47d3e574514de2eced5e54dc8a5436a3bf7a0b248b2cee16f3"
[[package]]
name = "wgpu"
version = "29.0.0"
source = "git+https://github.com/zed-industries/wgpu.git?branch=v29#a466bc382ea747f8e1ac810efdb6dcd49a514575"
version = "29.0.3"
source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88"
dependencies = [
"arrayvec",
"bitflags 2.10.0",
@ -20546,8 +20612,8 @@ dependencies = [
[[package]]
name = "wgpu-core"
version = "29.0.0"
source = "git+https://github.com/zed-industries/wgpu.git?branch=v29#a466bc382ea747f8e1ac810efdb6dcd49a514575"
version = "29.0.3"
source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88"
dependencies = [
"arrayvec",
"bit-set 0.9.1",
@ -20578,32 +20644,32 @@ dependencies = [
[[package]]
name = "wgpu-core-deps-apple"
version = "29.0.0"
source = "git+https://github.com/zed-industries/wgpu.git?branch=v29#a466bc382ea747f8e1ac810efdb6dcd49a514575"
version = "29.0.3"
source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88"
dependencies = [
"wgpu-hal",
]
[[package]]
name = "wgpu-core-deps-emscripten"
version = "29.0.0"
source = "git+https://github.com/zed-industries/wgpu.git?branch=v29#a466bc382ea747f8e1ac810efdb6dcd49a514575"
version = "29.0.3"
source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88"
dependencies = [
"wgpu-hal",
]
[[package]]
name = "wgpu-core-deps-windows-linux-android"
version = "29.0.0"
source = "git+https://github.com/zed-industries/wgpu.git?branch=v29#a466bc382ea747f8e1ac810efdb6dcd49a514575"
version = "29.0.3"
source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88"
dependencies = [
"wgpu-hal",
]
[[package]]
name = "wgpu-hal"
version = "29.0.0"
source = "git+https://github.com/zed-industries/wgpu.git?branch=v29#a466bc382ea747f8e1ac810efdb6dcd49a514575"
version = "29.0.3"
source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88"
dependencies = [
"android_system_properties",
"arrayvec",
@ -20650,12 +20716,13 @@ dependencies = [
"wgpu-types",
"windows 0.62.2",
"windows-core 0.62.2",
"windows-result 0.4.1",
]
[[package]]
name = "wgpu-naga-bridge"
version = "29.0.0"
source = "git+https://github.com/zed-industries/wgpu.git?branch=v29#a466bc382ea747f8e1ac810efdb6dcd49a514575"
version = "29.0.3"
source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88"
dependencies = [
"naga",
"wgpu-types",
@ -20663,8 +20730,8 @@ dependencies = [
[[package]]
name = "wgpu-types"
version = "29.0.0"
source = "git+https://github.com/zed-industries/wgpu.git?branch=v29#a466bc382ea747f8e1ac810efdb6dcd49a514575"
version = "29.0.3"
source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88"
dependencies = [
"bitflags 2.10.0",
"bytemuck",
@ -21948,6 +22015,7 @@ dependencies = [
"collections",
"component",
"db",
"dirs",
"fs",
"futures 0.3.32",
"futures-lite 1.13.0",
@ -22407,7 +22475,7 @@ dependencies = [
[[package]]
name = "zed"
version = "1.4.0"
version = "1.5.0"
dependencies = [
"acp_thread",
"acp_tools",

View file

@ -140,6 +140,7 @@ members = [
"crates/net",
"crates/node_runtime",
"crates/notifications",
"crates/oauth_callback_server",
"crates/ollama",
"crates/onboarding",
"crates/opencode",
@ -171,6 +172,7 @@ members = [
"crates/rope",
"crates/rpc",
"crates/rules_library",
"crates/skill_creator",
"crates/scheduler",
"crates/schema_generator",
"crates/search",
@ -399,6 +401,7 @@ nc = { path = "crates/nc" }
net = { path = "crates/net" }
node_runtime = { path = "crates/node_runtime" }
notifications = { path = "crates/notifications" }
oauth_callback_server = { path = "crates/oauth_callback_server" }
ollama = { path = "crates/ollama" }
onboarding = { path = "crates/onboarding" }
opencode = { path = "crates/opencode" }
@ -430,6 +433,7 @@ rodio = { git = "https://github.com/RustAudio/rodio", rev = "e50e726ddd0292f6ef9
rope = { path = "crates/rope" }
rpc = { path = "crates/rpc" }
rules_library = { path = "crates/rules_library" }
skill_creator = { path = "crates/skill_creator" }
scheduler = { path = "crates/scheduler" }
search = { path = "crates/search" }
session = { path = "crates/session" }
@ -498,7 +502,7 @@ ztracing_macro = { path = "crates/ztracing_macro" }
# External crates
#
agent-client-protocol = { version = "=0.11.1", features = ["unstable"] }
agent-client-protocol = { version = "=0.12.1", features = ["unstable"] }
aho-corasick = "1.1"
alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "9d9640d4" }
any_vec = "0.14"
@ -551,6 +555,7 @@ circular-buffer = "1.0"
clap = { version = "4.4", features = ["derive", "wrap_help"] }
cocoa = "=0.26.0"
cocoa-foundation = "=0.2.0"
const_format = "0.2"
convert_case = "0.8.0"
core-foundation = "=0.10.0"
core-foundation-sys = "0.8.6"
@ -558,7 +563,7 @@ core-video = { version = "0.5.2", features = ["metal"] }
cpal = "0.17"
crash-handler = "0.7"
criterion = { version = "0.5", features = ["html_reports"] }
ctor = "0.4.0"
ctor = "1.0.6"
dap-types = { git = "https://github.com/zed-industries/dap-types", rev = "1b461b310481d01e02b2603c16d7144b926339f8" }
dashmap = "6.0"
derive_more = { version = "2.1.1", features = [
@ -617,6 +622,7 @@ linkify = "0.10.0"
libwebrtc = "0.3.26"
livekit = { version = "0.7.32", features = ["tokio", "rustls-tls-native-roots"] }
log = { version = "0.4.16", features = ["kv_unstable_serde", "serde"] }
lru = "0.16"
lsp-types = { git = "https://github.com/zed-industries/lsp-types", rev = "f4dfa89a21ca35cd929b70354b1583fabae325f8" }
mach2 = "0.5"
markup5ever_rcdom = "0.3.0"
@ -718,6 +724,7 @@ serde_json_lenient = { version = "0.2", features = [
"preserve_order",
"raw_value",
] }
serde_yaml = "0.9.34"
serde_path_to_error = "0.1.17"
serde_urlencoded = "0.7"
sha2 = "0.10"
@ -759,7 +766,7 @@ toml_edit = { version = "0.22", default-features = false, features = [
"serde",
] }
tower-http = "0.4.4"
tree-sitter = { version = "0.26.8", features = ["wasm"] }
tree-sitter = { version = "0.26.9", features = ["wasm"] }
tree-sitter-bash = "0.25.1"
tree-sitter-c = "0.24.1"
tree-sitter-cpp = { git = "https://github.com/tree-sitter/tree-sitter-cpp", rev = "5cb9b693cfd7bfacab1d9ff4acac1a4150700609" }
@ -809,7 +816,7 @@ which = "6.0.0"
wasm-bindgen = "0.2.120"
web-time = "1.1.0"
webrtc-sys = "0.3.23"
wgpu = { git = "https://github.com/zed-industries/wgpu.git", branch = "v29" }
wgpu = { git = "https://github.com/zed-industries/wgpu.git", rev = "357a0c56e0070480ad9daea5d2eaa83150b79e88" }
windows-core = "0.61"
yaml-rust2 = "0.8"
yawc = "0.2.5"

View file

@ -1,4 +1,4 @@
<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
<path opacity="0.3" d="M9 1.5H3C2.17157 1.5 1.5 2.17157 1.5 3V9C1.5 9.82843 2.17157 10.5 3 10.5H9C9.82843 10.5 10.5 9.82843 10.5 9V3C10.5 2.17157 9.82843 1.5 9 1.5Z" stroke="#C6CAD0" stroke-width="0.9"/>
<path d="M4.32058 8.53711C3.99873 8.53711 3.79672 8.34879 3.79672 8.05092C3.79672 7.96532 3.82069 7.84891 3.8652 7.72222L5.21422 4.04838C5.35802 3.64778 5.60112 3.46289 5.99144 3.46289C6.39546 3.46289 6.63514 3.64093 6.78236 4.04495L8.13823 7.72222C8.18616 7.85575 8.20328 7.9482 8.20328 8.05092C8.20328 8.3351 7.98758 8.53711 7.68627 8.53711C7.39524 8.53711 7.24117 8.40358 7.14872 8.08173L6.8885 7.30108H5.10465L4.84444 8.07146C4.74857 8.40015 4.59449 8.53711 4.32058 8.53711ZM5.33063 6.49989H6.64883L5.99487 4.47636H5.9709L5.33063 6.49989Z" fill="#C6CAD0"/>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5.76074 11.3828C5.3316 11.3828 5.06226 11.1317 5.06226 10.7346C5.06226 10.6204 5.09422 10.4652 5.15356 10.2963L6.95226 5.39784C7.14399 4.86371 7.46812 4.61719 7.98855 4.61719C8.52724 4.61719 8.84682 4.85457 9.04311 5.39327L10.8509 10.2963C10.9148 10.4743 10.9377 10.5976 10.9377 10.7346C10.9377 11.1135 10.6501 11.3828 10.2483 11.3828C9.86028 11.3828 9.65486 11.2048 9.53159 10.7756L9.18463 9.73477H6.80616L6.45922 10.7619C6.33139 11.2002 6.12595 11.3828 5.76074 11.3828ZM7.10747 8.66652H8.86507L7.99312 5.96848H7.96116L7.10747 8.66652Z" fill="#C6CAD0"/>
<path opacity="0.3" d="M12 2H4C2.89543 2 2 2.89543 2 4V12C2 13.1046 2.89543 14 4 14H12C13.1046 14 14 13.1046 14 12V4C14 2.89543 13.1046 2 12 2Z" stroke="#C6CAD0" stroke-width="1.2"/>
</svg>

Before

Width:  |  Height:  |  Size: 868 B

After

Width:  |  Height:  |  Size: 851 B

View file

@ -1,15 +1,15 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12.146 2H4.85398C3.55391 2 2.5 3.05391 2.5 4.35398V11.646C2.5 12.9461 3.55391 14 4.85398 14H12.146C13.4461 14 14.5 12.9461 14.5 11.646V4.35398C14.5 3.05391 13.4461 2 12.146 2Z" stroke="black" stroke-width="1.11504"/>
<path opacity="0.487119" d="M10.5177 3.60177H6.21681C5.8698 3.60177 5.58849 3.88308 5.58849 4.23009V4.23894C5.58849 4.58595 5.8698 4.86726 6.21681 4.86726H10.5177C10.8647 4.86726 11.146 4.58595 11.146 4.23894V4.23009C11.146 3.88308 10.8647 3.60177 10.5177 3.60177Z" fill="black"/>
<path opacity="0.845099" d="M8.83628 3.60177H4.53539C4.18838 3.60177 3.90707 3.88308 3.90707 4.23009V4.23894C3.90707 4.58595 4.18838 4.86726 4.53539 4.86726H8.83628C9.18329 4.86726 9.4646 4.58595 9.4646 4.23894V4.23009C9.4646 3.88308 9.18329 3.60177 8.83628 3.60177Z" fill="black"/>
<path opacity="0.487119" d="M12.7389 5.10619H8.43806C8.09105 5.10619 7.80974 5.3875 7.80974 5.73451V5.74336C7.80974 6.09037 8.09105 6.37168 8.43806 6.37168H12.7389C13.086 6.37168 13.3673 6.09037 13.3673 5.74336V5.73451C13.3673 5.3875 13.086 5.10619 12.7389 5.10619Z" fill="black"/>
<path opacity="0.845099" d="M11.0575 5.10619H6.75664C6.40963 5.10619 6.12832 5.3875 6.12832 5.73451V5.74336C6.12832 6.09037 6.40963 6.37168 6.75664 6.37168H11.0575C11.4045 6.37168 11.6858 6.09037 11.6858 5.74336V5.73451C11.6858 5.3875 11.4045 5.10619 11.0575 5.10619Z" fill="black"/>
<path opacity="0.487119" d="M11.5619 6.59292H7.26106C6.91405 6.59292 6.63274 6.87423 6.63274 7.22124V7.23009C6.63274 7.5771 6.91405 7.85841 7.26106 7.85841H11.5619C11.909 7.85841 12.1903 7.5771 12.1903 7.23009V7.22124C12.1903 6.87423 11.909 6.59292 11.5619 6.59292Z" fill="black"/>
<path opacity="0.845099" d="M9.86284 6.59292H5.56195C5.21494 6.59292 4.93363 6.87423 4.93363 7.22124V7.23009C4.93363 7.5771 5.21494 7.85841 5.56195 7.85841H9.86284C10.2098 7.85841 10.4912 7.5771 10.4912 7.23009V7.22124C10.4912 6.87423 10.2098 6.59292 9.86284 6.59292Z" fill="black"/>
<path opacity="0.487119" d="M10.1903 8.10619H5.88937C5.54236 8.10619 5.26105 8.3875 5.26105 8.73451V8.74336C5.26105 9.09037 5.54236 9.37168 5.88937 9.37168H10.1903C10.5373 9.37168 10.8186 9.09037 10.8186 8.74336V8.73451C10.8186 8.3875 10.5373 8.10619 10.1903 8.10619Z" fill="black"/>
<path opacity="0.845099" d="M8.50886 8.10619H4.20797C3.86096 8.10619 3.57965 8.3875 3.57965 8.73451V8.74336C3.57965 9.09037 3.86096 9.37168 4.20797 9.37168H8.50886C8.85587 9.37168 9.13717 9.09037 9.13717 8.74336V8.73451C9.13717 8.3875 8.85587 8.10619 8.50886 8.10619Z" fill="black"/>
<path opacity="0.487119" d="M10.9513 9.59292H7.37611C7.0291 9.59292 6.74779 9.87423 6.74779 10.2212V10.2301C6.74779 10.5771 7.0291 10.8584 7.37611 10.8584H10.9513C11.2983 10.8584 11.5796 10.5771 11.5796 10.2301V10.2212C11.5796 9.87423 11.2983 9.59292 10.9513 9.59292Z" fill="black"/>
<path opacity="0.845099" d="M9.23452 9.59292H5.65929C5.31228 9.59292 5.03098 9.87423 5.03098 10.2212V10.2301C5.03098 10.5771 5.31228 10.8584 5.65929 10.8584H9.23452C9.58153 10.8584 9.86283 10.5771 9.86283 10.2301V10.2212C9.86283 9.87423 9.58153 9.59292 9.23452 9.59292Z" fill="black"/>
<path opacity="0.487119" d="M12.6062 11.0973H9.82744C9.48043 11.0973 9.19912 11.3787 9.19912 11.7257V11.7345C9.19912 12.0815 9.48043 12.3628 9.82744 12.3628H12.6062C12.9532 12.3628 13.2345 12.0815 13.2345 11.7345V11.7257C13.2345 11.3787 12.9532 11.0973 12.6062 11.0973Z" fill="black"/>
<path opacity="0.845099" d="M10.7389 11.0973H7.96017C7.61316 11.0973 7.33186 11.3787 7.33186 11.7257V11.7345C7.33186 12.0815 7.61316 12.3628 7.96017 12.3628H10.7389C11.0859 12.3628 11.3673 12.0815 11.3673 11.7345V11.7257C11.3673 11.3787 11.0859 11.0973 10.7389 11.0973Z" fill="black"/>
<path d="M11.646 2H4.35398C3.05391 2 2 3.05391 2 4.35398V11.646C2 12.9461 3.05391 14 4.35398 14H11.646C12.9461 14 14 12.9461 14 11.646V4.35398C14 3.05391 12.9461 2 11.646 2Z" stroke="#C6CAD0" stroke-width="1.11504"/>
<path opacity="0.487119" d="M10.0177 3.60178H5.71681C5.3698 3.60178 5.08849 3.88309 5.08849 4.2301V4.23895C5.08849 4.58596 5.3698 4.86727 5.71681 4.86727H10.0177C10.3647 4.86727 10.646 4.58596 10.646 4.23895V4.2301C10.646 3.88309 10.3647 3.60178 10.0177 3.60178Z" fill="#C6CAD0"/>
<path opacity="0.845099" d="M8.33628 3.60178H4.03539C3.68838 3.60178 3.40707 3.88309 3.40707 4.2301V4.23895C3.40707 4.58596 3.68838 4.86727 4.03539 4.86727H8.33628C8.68329 4.86727 8.9646 4.58596 8.9646 4.23895V4.2301C8.9646 3.88309 8.68329 3.60178 8.33628 3.60178Z" fill="#C6CAD0"/>
<path opacity="0.487119" d="M12.2389 5.1062H7.93806C7.59105 5.1062 7.30974 5.38751 7.30974 5.73452V5.74337C7.30974 6.09038 7.59105 6.37169 7.93806 6.37169H12.2389C12.586 6.37169 12.8673 6.09038 12.8673 5.74337V5.73452C12.8673 5.38751 12.586 5.1062 12.2389 5.1062Z" fill="#C6CAD0"/>
<path opacity="0.845099" d="M10.5575 5.1062H6.25665C5.90964 5.1062 5.62833 5.38751 5.62833 5.73452V5.74337C5.62833 6.09038 5.90964 6.37169 6.25665 6.37169H10.5575C10.9045 6.37169 11.1858 6.09038 11.1858 5.74337V5.73452C11.1858 5.38751 10.9045 5.1062 10.5575 5.1062Z" fill="#C6CAD0"/>
<path opacity="0.487119" d="M11.0619 6.59293H6.76106C6.41405 6.59293 6.13274 6.87424 6.13274 7.22125V7.2301C6.13274 7.57711 6.41405 7.85842 6.76106 7.85842H11.0619C11.409 7.85842 11.6903 7.57711 11.6903 7.2301V7.22125C11.6903 6.87424 11.409 6.59293 11.0619 6.59293Z" fill="#C6CAD0"/>
<path opacity="0.845099" d="M9.36283 6.59293H5.06194C4.71493 6.59293 4.43362 6.87424 4.43362 7.22125V7.2301C4.43362 7.57711 4.71493 7.85842 5.06194 7.85842H9.36283C9.70979 7.85842 9.99119 7.57711 9.99119 7.2301V7.22125C9.99119 6.87424 9.70979 6.59293 9.36283 6.59293Z" fill="#C6CAD0"/>
<path opacity="0.487119" d="M9.6903 8.1062H5.38937C5.04236 8.1062 4.76105 8.38751 4.76105 8.73452V8.74337C4.76105 9.09038 5.04236 9.37169 5.38937 9.37169H9.6903C10.0373 9.37169 10.3186 9.09038 10.3186 8.74337V8.73452C10.3186 8.38751 10.0373 8.1062 9.6903 8.1062Z" fill="#C6CAD0"/>
<path opacity="0.845099" d="M8.00886 8.1062H3.70797C3.36096 8.1062 3.07965 8.38751 3.07965 8.73452V8.74337C3.07965 9.09038 3.36096 9.37169 3.70797 9.37169H8.00886C8.35587 9.37169 8.63717 9.09038 8.63717 8.74337V8.73452C8.63717 8.38751 8.35587 8.1062 8.00886 8.1062Z" fill="#C6CAD0"/>
<path opacity="0.487119" d="M10.4513 9.59293H6.87611C6.5291 9.59293 6.24779 9.87424 6.24779 10.2212V10.2301C6.24779 10.5771 6.5291 10.8584 6.87611 10.8584H10.4513C10.7983 10.8584 11.0796 10.5771 11.0796 10.2301V10.2212C11.0796 9.87424 10.7983 9.59293 10.4513 9.59293Z" fill="#C6CAD0"/>
<path opacity="0.845099" d="M8.73452 9.59293H5.15929C4.81228 9.59293 4.53098 9.87424 4.53098 10.2212V10.2301C4.53098 10.5771 4.81228 10.8584 5.15929 10.8584H8.73452C9.08153 10.8584 9.36283 10.5771 9.36283 10.2301V10.2212C9.36283 9.87424 9.08153 9.59293 8.73452 9.59293Z" fill="#C6CAD0"/>
<path opacity="0.487119" d="M12.1062 11.0973H9.32745C8.98044 11.0973 8.69913 11.3787 8.69913 11.7257V11.7345C8.69913 12.0815 8.98044 12.3628 9.32745 12.3628H12.1062C12.4532 12.3628 12.7345 12.0815 12.7345 11.7345V11.7257C12.7345 11.3787 12.4532 11.0973 12.1062 11.0973Z" fill="#C6CAD0"/>
<path opacity="0.845099" d="M10.2389 11.0973H7.46017C7.11316 11.0973 6.83186 11.3787 6.83186 11.7257V11.7345C6.83186 12.0815 7.11316 12.3628 7.46017 12.3628H10.2389C10.5859 12.3628 10.8673 12.0815 10.8673 11.7345V11.7257C10.8673 11.3787 10.5859 11.0973 10.2389 11.0973Z" fill="#C6CAD0"/>
</svg>

Before

Width:  |  Height:  |  Size: 3.6 KiB

After

Width:  |  Height:  |  Size: 3.6 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 8.3 KiB

After

Width:  |  Height:  |  Size: 8.4 KiB

View file

@ -1,3 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14.5768 6.73011C14.8987 5.77678 14.7879 4.73245 14.2731 3.86531C13.4989 2.53528 11.9427 1.85102 10.4227 2.17303C9.74656 1.42139 8.7751 0.993944 7.75664 1.00006C6.20301 0.996569 4.82452 1.98358 4.34655 3.44224C3.34849 3.64393 2.48699 4.26038 1.98286 5.13408C1.20294 6.46061 1.38074 8.13277 2.4227 9.27029C2.1008 10.2236 2.21164 11.268 2.72642 12.1351C3.50057 13.4651 5.05686 14.1494 6.57679 13.8274C7.25251 14.579 8.22441 15.0064 9.24287 14.9999C10.7974 15.0038 12.1763 14.0159 12.6543 12.556C13.6524 12.3543 14.5139 11.7379 15.018 10.8641C15.797 9.5376 15.6188 7.86676 14.5773 6.72924L14.5768 6.73011ZM9.24376 14.0851C8.62169 14.0859 8.01912 13.8711 7.5416 13.4778C7.56332 13.4664 7.60101 13.4459 7.6254 13.431L10.4507 11.821C10.5952 11.7401 10.6839 11.5882 10.683 11.4242V7.49401L11.877 8.17433C11.8899 8.18045 11.8983 8.1927 11.9001 8.2067V11.4614C11.8983 12.9086 10.7105 14.082 9.24376 14.0851ZM3.53116 11.6775C3.21946 11.1464 3.10729 10.5237 3.21414 9.91955C3.23498 9.9318 3.27178 9.95411 3.29794 9.96898L6.1232 11.5791C6.26642 11.6617 6.44377 11.6617 6.58743 11.5791L10.0365 9.61373V10.9744C10.0374 10.9884 10.0308 11.002 10.0197 11.0107L7.16383 12.6378C5.89175 13.3606 4.26674 12.9309 3.53116 11.6775ZM2.7876 5.59215C3.09797 5.06014 3.58792 4.65326 4.17141 4.44195C4.17141 4.46601 4.17008 4.50845 4.17008 4.5382V7.75869C4.1692 7.92232 4.25787 8.07414 4.40198 8.15508L7.85108 10.1199L6.65704 10.8002C6.64507 10.8081 6.62999 10.8094 6.61669 10.8037L3.76039 9.17535C2.49098 8.44995 2.05601 6.84692 2.7876 5.59215ZM12.598 7.84488L9.14887 5.8796L10.3429 5.19971C10.3549 5.19183 10.37 5.19052 10.3833 5.19621L13.2396 6.8233C14.5112 7.54826 14.947 9.15347 14.2124 10.4082C13.9015 10.9394 13.412 11.3463 12.829 11.5581V8.24127C12.8303 8.07764 12.7417 7.92626 12.598 7.84488ZM13.7863 6.07998C13.7654 6.06729 13.7286 6.04541 13.7025 6.03054L10.8772 4.42051C10.734 4.33782 10.5566 4.33782 10.413 4.42051L6.96386 6.3858V5.02514C6.96298 5.01114 6.96963 4.99758 6.98071 4.98883L9.83657 3.36305C11.1086 2.63898 12.735 3.06992 13.4683 4.32557C13.7783 4.85583 13.8914 5.47665 13.7863 6.07998ZM6.31475 8.50509L5.12026 7.82476C5.1074 7.81863 5.09898 7.80638 5.09721 7.79238V4.53776C5.09809 3.08873 6.28947 1.91446 7.75797 1.91533C8.37916 1.91533 8.98039 2.13059 9.45792 2.52259C9.43619 2.53397 9.39894 2.55453 9.37412 2.56941L6.54885 4.17944C6.40431 4.26038 6.31563 4.41176 6.31652 4.57582L6.31475 8.50509ZM6.96342 7.12518L8.49976 6.24973L10.0361 7.12475V8.87521L8.49976 9.75023L6.96342 8.87521V7.12518Z" fill="black"/>
<path d="M14.0768 6.73011C14.3987 5.77678 14.2879 4.73245 13.7731 3.86531C12.9989 2.53528 11.4427 1.85102 9.9227 2.17303C9.24656 1.42139 8.2751 0.993949 7.25664 1.00006C5.70301 0.996574 4.32452 1.98358 3.84655 3.44224C2.84849 3.64393 1.98699 4.26038 1.48286 5.13408C0.702939 6.46061 0.880738 8.13278 1.9227 9.2703C1.6008 10.2236 1.71164 11.268 2.22642 12.1351C3.00057 13.4651 4.55686 14.1494 6.07679 13.8274C6.75251 14.579 7.72441 15.0064 8.74287 14.9999C10.2974 15.0038 11.6763 14.0159 12.1543 12.556C13.1524 12.3543 14.0139 11.7379 14.518 10.8641C15.297 9.53761 15.1188 7.86676 14.0773 6.72924L14.0768 6.73011ZM8.74376 14.0851C8.12169 14.0859 7.51912 13.8711 7.0416 13.4778C7.06332 13.4664 7.10101 13.4459 7.1254 13.431L9.9507 11.821C10.0952 11.7401 10.1839 11.5882 10.183 11.4242V7.49401L11.377 8.17433C11.3899 8.18045 11.3983 8.19271 11.4001 8.20671V11.4614C11.3983 12.9086 10.2105 14.082 8.74376 14.0851ZM3.03116 11.6775C2.71946 11.1464 2.60729 10.5237 2.71414 9.91955C2.73498 9.9318 2.77178 9.95411 2.79794 9.96898L5.6232 11.5791C5.76642 11.6617 5.94377 11.6617 6.08743 11.5791L9.5365 9.61374V10.9744C9.5374 10.9884 9.5308 11.002 9.5197 11.0107L6.66383 12.6378C5.39175 13.3606 3.76674 12.9309 3.03116 11.6775ZM2.2876 5.59215C2.59797 5.06014 3.08792 4.65326 3.67141 4.44195C3.67141 4.46601 3.67008 4.50845 3.67008 4.5382V7.75869C3.6692 7.92232 3.75787 8.07414 3.90198 8.15508L7.35108 10.1199L6.15704 10.8002C6.14507 10.8081 6.12999 10.8094 6.11669 10.8037L3.26039 9.17535C1.99098 8.44995 1.55601 6.84693 2.2876 5.59215ZM12.098 7.84488L8.64887 5.8796L9.8429 5.19971C9.8549 5.19183 9.87 5.19052 9.8833 5.19621L12.7396 6.8233C14.0112 7.54826 14.447 9.15348 13.7124 10.4082C13.4015 10.9394 12.912 11.3463 12.329 11.5581V8.24127C12.3303 8.07764 12.2417 7.92626 12.098 7.84488ZM13.2863 6.07998C13.2654 6.06729 13.2286 6.04541 13.2025 6.03054L10.3772 4.42051C10.234 4.33782 10.0566 4.33782 9.913 4.42051L6.46386 6.3858V5.02514C6.46298 5.01114 6.46963 4.99758 6.48071 4.98883L9.33657 3.36305C10.6086 2.63898 12.235 3.06992 12.9683 4.32557C13.2783 4.85583 13.3914 5.47665 13.2863 6.07998ZM5.81475 8.50509L4.62026 7.82476C4.6074 7.81863 4.59898 7.80638 4.59721 7.79238V4.53776C4.59809 3.08873 5.78947 1.91446 7.25797 1.91533C7.87916 1.91533 8.48039 2.13059 8.95792 2.52259C8.93619 2.53397 8.89894 2.55453 8.87412 2.56941L6.04885 4.17944C5.90431 4.26038 5.81563 4.41176 5.81652 4.57582L5.81475 8.50509ZM6.46342 7.12518L7.99976 6.24973L9.5361 7.12475V8.87521L7.99976 9.75023L6.46342 8.87521V7.12518Z" fill="#C6CAD0"/>
</svg>

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

View file

@ -1,3 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12.8451 5.50949L13.1109 15H15.2342L15.5 2.05527L12.8451 5.50949ZM15.499 1H12.2574L7.17206 7.61904L8.79335 9.72761L15.499 1ZM1.5 14.999H4.73963L6.36092 12.8905L4.73963 10.7809L1.5 14.999ZM1.5 5.50851L8.79335 14.999H12.034L4.74061 5.50949L1.5 5.50851Z" fill="black"/>
<path d="M12.3451 5.50949L12.6109 15H14.7342L15 2.05527L12.3451 5.50949ZM14.999 1H11.7574L6.67206 7.61904L8.29335 9.72761L14.999 1ZM1 14.999H4.23963L5.86092 12.8905L4.23963 10.7809L1 14.999ZM1 5.50851L8.29335 14.999H11.534L4.24061 5.50949L1 5.50851Z" fill="#C6CAD0"/>
</svg>

Before

Width:  |  Height:  |  Size: 379 B

After

Width:  |  Height:  |  Size: 371 B

View file

@ -1,3 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M3.625 2.75C3.4179 2.75 3.25 2.9179 3.25 3.125V11.375H2.5V3.125C2.5 2.50368 3.00368 2 3.625 2H13.6723C14.1735 2 14.4244 2.6059 14.0701 2.96025L7.88189 9.14843H9.625V8.375H10.375V9.33593C10.375 9.6466 10.1232 9.8984 9.8125 9.8984H7.13189L5.84282 11.1875H11.6875V6.5H12.4375V11.1875C12.4375 11.6017 12.1017 11.9375 11.6875 11.9375H5.09282L3.78032 13.25H13.375C13.5821 13.25 13.75 13.0821 13.75 12.875V4.625H14.5V12.875C14.5 13.4963 13.9963 14 13.375 14H3.32767C2.82653 14 2.57557 13.3941 2.92992 13.0397L9.09468 6.875H7.375V7.625H6.625V6.6875C6.625 6.37684 6.87684 6.125 7.1875 6.125H9.84468L11.1571 4.8125H5.3125V9.5H4.5625V4.8125C4.5625 4.39829 4.89829 4.0625 5.3125 4.0625H11.9071L13.2197 2.75H3.625Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M3.125 2.75C2.9179 2.75 2.75 2.9179 2.75 3.125V11.375H2V3.125C2 2.50368 2.50368 2 3.125 2H13.1723C13.6735 2 13.9244 2.6059 13.5701 2.96025L7.38189 9.14843H9.125V8.375H9.875V9.33593C9.875 9.6466 9.6232 9.8984 9.3125 9.8984H6.63189L5.34282 11.1875H11.1875V6.5H11.9375V11.1875C11.9375 11.6017 11.6017 11.9375 11.1875 11.9375H4.59282L3.28032 13.25H12.875C13.0821 13.25 13.25 13.0821 13.25 12.875V4.625H14V12.875C14 13.4963 13.4963 14 12.875 14H2.82767C2.32653 14 2.07557 13.3941 2.42992 13.0397L8.59468 6.875H6.875V7.625H6.125V6.6875C6.125 6.37684 6.37684 6.125 6.6875 6.125H9.34468L10.6571 4.8125H4.8125V9.5H4.0625V4.8125C4.0625 4.39829 4.39829 4.0625 4.8125 4.0625H11.4071L12.7197 2.75H3.125Z" fill="#C6CAD0"/>
</svg>

Before

Width:  |  Height:  |  Size: 870 B

After

Width:  |  Height:  |  Size: 861 B

View file

@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2.38893 2.60654C2.33283 2.6058 2.27725 2.61737 2.2261 2.64042C2.17496 2.66347 2.12948 2.69745 2.09288 2.73996C2.05627 2.78247 2.02943 2.83249 2.01423 2.8865C1.99904 2.9405 1.99586 2.99718 2.00492 3.05254L3.63644 12.9576C3.67844 13.2076 3.89394 13.3916 4.14744 13.3941H11.975C12.0672 13.3951 12.1567 13.3631 12.2273 13.3039C12.2979 13.2446 12.345 13.1621 12.36 13.0711L13.995 3.05604C14.004 3.00072 14.0008 2.94409 13.9856 2.89015C13.9703 2.83621 13.9435 2.78626 13.9069 2.7438C13.8703 2.70134 13.8248 2.66741 13.7737 2.64439C13.7226 2.62137 13.6671 2.60982 13.611 2.61054L2.38893 2.60654ZM9.26 9.76511H6.76097L6.08496 6.23308H9.8655L9.26 9.76511Z" fill="#C6CAD0"/>
</svg>

After

Width:  |  Height:  |  Size: 778 B

View file

@ -1,3 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8 11C9.65685 11 11 9.65685 11 8C11 6.34315 9.65685 5 8 5C6.34315 5 5 6.34315 5 8C5 9.65685 6.34315 11 8 11Z" fill="black"/>
<path d="M8 12C10.2091 12 12 10.2091 12 8C12 5.79087 10.2091 4 8 4C5.79087 4 4 5.79087 4 8C4 10.2091 5.79087 12 8 12Z" fill="#C6CAD0"/>
</svg>

Before

Width:  |  Height:  |  Size: 237 B

After

Width:  |  Height:  |  Size: 239 B

View file

@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.99947 2.00001C7.15863 1.99826 6.32573 2.16261 5.54858 2.48364C4.77144 2.80466 4.06536 3.27604 3.4709 3.87071C2.87644 4.46537 2.40529 5.1716 2.08452 5.94885C1.76376 6.7261 1.59968 7.55906 1.60172 8.39989C1.60172 9.6017 1.94029 10.7806 2.57906 11.7995L7.91309 4.90217C7.95148 4.85311 8.04692 4.85311 8.08531 4.90217L10.313 7.78246H8.71767L8.75233 7.90989H10.4122L10.8824 8.51666H8.92348L8.9784 8.71608H11.0365L11.4508 9.25087H9.12716L9.19914 9.5084H11.6481L12.0187 9.98507H9.33244L9.42042 10.2991H12.2602L12.5849 10.7177H9.53665L9.63369 11.0642H12.8531L13.1527 11.4519H9.74193L9.83951 11.7984H13.4209C14.0594 10.7799 14.3982 9.60205 14.3983 8.39989C14.4001 7.55903 14.2359 6.72608 13.9149 5.94885C13.594 5.17163 13.1228 4.46543 12.5283 3.8708C11.9337 3.27616 11.2276 2.8048 10.4504 2.48376C9.67326 2.16272 8.84033 1.99833 7.99947 2.00001ZM9.94774 12.1861L10.0448 12.5327H12.8846C12.9768 12.4239 13.0728 12.3018 13.1581 12.1861H9.94774ZM10.153 12.9203L10.249 13.2669H12.1488C12.273 13.1613 12.4073 13.0386 12.5284 12.9203H10.153ZM10.3572 13.6545L10.4543 14H11.0957C11.2855 13.8912 11.4609 13.7803 11.6513 13.6545H10.3572Z" fill="#C6CAD0"/>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 6.3 KiB

After

Width:  |  Height:  |  Size: 6.3 KiB

View file

@ -1,3 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M13.2806 4.66818L8.26042 1.76982C8.09921 1.67673 7.9003 1.67673 7.73909 1.76982L2.71918 4.66818C2.58367 4.74642 2.5 4.89112 2.5 5.04785V10.8924C2.5 11.0489 2.58367 11.1938 2.71918 11.2721L7.73934 14.1704C7.90054 14.2635 8.09946 14.2635 8.26066 14.1704L13.2808 11.2721C13.4163 11.1938 13.5 11.0491 13.5 10.8924V5.04785C13.5 4.89136 13.4163 4.74642 13.2808 4.66818H13.2806ZM12.9653 5.28212L8.11901 13.676C8.08626 13.7326 7.99977 13.7095 7.99977 13.6439V8.14771C7.99977 8.03788 7.94107 7.9363 7.84586 7.88115L3.08613 5.13317C3.02957 5.10041 3.05266 5.0139 3.11818 5.0139H12.8106C12.9483 5.0139 13.0343 5.1631 12.9655 5.28236H12.9653V5.28212Z" fill="#C4CAD4"/>
<path d="M13.2806 4.69807L8.26042 1.79971C8.09921 1.70662 7.9003 1.70662 7.73909 1.79971L2.71918 4.69807C2.58367 4.77631 2.5 4.92101 2.5 5.07774V10.9223C2.5 11.0788 2.58367 11.2237 2.71918 11.302L7.73934 14.2003C7.90054 14.2934 8.09946 14.2934 8.26066 14.2003L13.2808 11.302C13.4163 11.2237 13.5 11.079 13.5 10.9223V5.07774C13.5 4.92125 13.4161 4.77631 13.2806 4.69807ZM12.9653 5.31201L8.11901 13.7059C8.08626 13.7625 7.99977 13.7394 7.99977 13.6738V8.1776C7.99977 8.06777 7.94107 7.96619 7.84586 7.91104L3.08613 5.16306C3.02957 5.1303 3.05266 5.04379 3.11818 5.04379H12.8106C12.9483 5.04379 13.0341 5.19275 12.9653 5.31201Z" fill="#C6CAD0"/>
</svg>

Before

Width:  |  Height:  |  Size: 769 B

After

Width:  |  Height:  |  Size: 746 B

View file

@ -1,10 +1,8 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_2716_663)">
<path d="M8.47552 2.45453C11.5167 2.45457 13.9814 4.94501 13.9814 8.01623C13.9814 11.0875 11.5167 13.578 8.47552 13.5781C5.43427 13.5781 2.96948 11.0875 2.96948 8.01623C2.9695 4.94498 5.43429 2.45453 8.47552 2.45453ZM10.8795 4.70348C10.7605 4.16887 10.1328 3.85468 9.53627 3.96342C8.97622 4.06552 7.62871 4.45681 7.62057 4.45916C9.29414 4.44469 9.57429 4.4726 9.69939 4.64751C9.77324 4.7508 9.66576 4.89248 9.21944 4.96538C8.73515 5.04447 7.73014 5.13958 7.72343 5.14022C6.75441 5.19776 6.07177 5.20168 5.86705 5.63512C5.73334 5.91827 6.00968 6.16857 6.13082 6.32527C6.64271 6.89455 7.38215 7.20158 7.85809 7.42767C8.03716 7.51274 8.56257 7.67345 8.56257 7.67345C7.01855 7.58853 5.90474 8.06267 5.2514 8.60855C4.51246 9.29204 4.83937 10.1067 6.35327 10.6084C7.24742 10.9047 7.69094 11.0439 9.02473 10.9238C9.81031 10.8815 9.9342 10.9068 9.94203 10.9712C9.95275 11.062 9.06932 11.2874 8.82812 11.357C8.21455 11.534 6.60645 11.8913 6.59758 11.8932C6.60115 11.8935 7.06249 11.9257 7.65531 11.8735C7.89632 11.8522 8.81142 11.7624 9.49557 11.6123C9.49557 11.6123 10.3297 11.4338 10.7759 11.2693C11.2429 11.0973 11.497 10.9512 11.6113 10.7443C11.6063 10.7019 11.6465 10.5516 11.4313 10.4613C10.8807 10.2304 10.2423 10.2721 8.9789 10.2453C7.57789 10.1972 7.11184 9.9626 6.86356 9.77373C6.62548 9.58212 6.74518 9.05204 7.76528 8.5851C8.27917 8.33646 10.2935 7.87759 10.2935 7.87759C9.61511 7.54227 8.35014 6.95284 8.09005 6.82552C7.86199 6.71388 7.49701 6.54572 7.4179 6.34233C7.32824 6.14709 7.6297 5.97888 7.79813 5.9307C8.34057 5.77424 9.10635 5.67701 9.8033 5.66609C10.1536 5.66061 10.2105 5.63806 10.2105 5.63806C10.6939 5.55787 11.0121 5.22722 10.8795 4.70348Z" fill="black"/>
<mask id="mask0_4385_22072" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="2" y="2" width="12" height="12">
<path d="M14 2H2V14H14V2Z" fill="white"/>
</mask>
<g mask="url(#mask0_4385_22072)">
<path d="M7.97552 2.45453C11.0167 2.45457 13.4814 4.94501 13.4814 8.01623C13.4814 11.0875 11.0167 13.578 7.97552 13.5781C4.93427 13.5781 2.46948 11.0875 2.46948 8.01623C2.4695 4.94498 4.93429 2.45453 7.97552 2.45453ZM10.3795 4.70348C10.2605 4.16887 9.6328 3.85468 9.03627 3.96342C8.47622 4.06552 7.12871 4.45681 7.12057 4.45916C8.79414 4.44469 9.07429 4.4726 9.19939 4.64751C9.27324 4.7508 9.16576 4.89248 8.71944 4.96538C8.23515 5.04447 7.23014 5.13958 7.22343 5.14022C6.25441 5.19776 5.57177 5.20168 5.36705 5.63512C5.23334 5.91827 5.50968 6.16857 5.63082 6.32527C6.14271 6.89455 6.88215 7.20158 7.35809 7.42767C7.53716 7.51274 8.06257 7.67345 8.06257 7.67345C6.51855 7.58853 5.40474 8.06267 4.7514 8.60855C4.01246 9.29204 4.33937 10.1067 5.85327 10.6084C6.74742 10.9047 7.19094 11.0439 8.52473 10.9238C9.31031 10.8815 9.4342 10.9068 9.44203 10.9712C9.45275 11.062 8.56932 11.2874 8.32812 11.357C7.71455 11.534 6.10645 11.8913 6.09758 11.8932C6.10115 11.8935 6.56249 11.9257 7.15531 11.8735C7.39632 11.8522 8.31142 11.7624 8.99557 11.6123C8.99557 11.6123 9.8297 11.4338 10.2759 11.2693C10.7429 11.0973 10.997 10.9512 11.1113 10.7443C11.1063 10.7019 11.1465 10.5516 10.9313 10.4613C10.3807 10.2304 9.7423 10.2721 8.4789 10.2453C7.07789 10.1972 6.61184 9.9626 6.36356 9.77373C6.12548 9.58212 6.24518 9.05204 7.26528 8.5851C7.77917 8.33646 9.7935 7.87759 9.7935 7.87759C9.11511 7.54227 7.85014 6.95284 7.59005 6.82552C7.36199 6.71388 6.99701 6.54572 6.9179 6.34233C6.82824 6.14709 7.1297 5.97888 7.29813 5.9307C7.84057 5.77424 8.60635 5.67701 9.3033 5.66609C9.6536 5.66061 9.7105 5.63806 9.7105 5.63806C10.1939 5.55787 10.5121 5.22722 10.3795 4.70348Z" fill="#C6CAD0"/>
</g>
<defs>
<clipPath id="clip0_2716_663">
<rect width="12" height="12" fill="white" transform="translate(2.5 2)"/>
</clipPath>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

View file

@ -1,3 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3.6725 13.9985C3.36161 13.9982 3.06354 13.8746 2.84371 13.6548C2.62388 13.435 2.50026 13.1369 2.5 12.826V7.494C2.5 6.8325 2.7675 6.185 3.2365 5.7165L6.219 2.736C6.45192 2.50247 6.72867 2.31724 7.03335 2.19094C7.33804 2.06464 7.66467 1.99975 7.9945 2H13.3275C13.6384 2.00027 13.9365 2.12388 14.1563 2.34371C14.3761 2.56354 14.4997 2.86162 14.5 3.1725V8.5045C14.4983 9.17074 14.2336 9.80936 13.7635 10.2815L10.781 13.264C10.5477 13.4976 10.2706 13.6829 9.96561 13.8092C9.66059 13.9355 9.33364 14.0003 9.0035 14V13.9985H3.6725ZM8.157 10.5715H5.243V11.257H8.157V10.5715ZM4.4815 5.257H11.243V12.0165L13.3715 9.888C13.7373 9.52036 13.9433 9.02316 13.9445 8.5045V3.1725C13.9445 2.8335 13.6685 2.5555 13.3275 2.5555H7.9945C7.73753 2.55499 7.483 2.6053 7.24556 2.70356C7.00813 2.80181 6.79246 2.94606 6.611 3.128L4.4815 5.257ZM4.3855 5.353L3.628 6.11C3.26258 6.47809 3.0569 6.97533 3.0555 7.494V12.826C3.0555 13.165 3.3315 13.443 3.6725 13.443H9.0055C9.26249 13.4434 9.51701 13.3929 9.75445 13.2946C9.99188 13.1963 10.2075 13.052 10.389 12.87L11.145 12.1145H4.3855V5.353Z" fill="black"/>
<path d="M3.1725 13.9985C2.86161 13.9982 2.56354 13.8746 2.34371 13.6548C2.12388 13.435 2.00026 13.1369 2 12.826V7.494C2 6.8325 2.2675 6.185 2.7365 5.7165L5.719 2.736C5.95192 2.50247 6.22867 2.31724 6.53335 2.19094C6.83804 2.06464 7.16467 1.99975 7.4945 2H12.8275C13.1384 2.00027 13.4365 2.12388 13.6563 2.34371C13.8761 2.56354 13.9997 2.86162 14 3.1725V8.5045C13.9983 9.17074 13.7336 9.80936 13.2635 10.2815L10.281 13.264C10.0477 13.4976 9.7706 13.6829 9.46561 13.8092C9.16059 13.9355 8.83364 14.0003 8.5035 14V13.9985H3.1725ZM7.657 10.5715H4.743V11.257H7.657V10.5715ZM3.9815 5.257H10.743V12.0165L12.8715 9.888C13.2373 9.52036 13.4433 9.02316 13.4445 8.5045V3.1725C13.4445 2.8335 13.1685 2.5555 12.8275 2.5555H7.4945C7.23753 2.55499 6.983 2.6053 6.74556 2.70356C6.50813 2.80181 6.29246 2.94606 6.111 3.128L3.9815 5.257ZM3.8855 5.353L3.128 6.11C2.76258 6.47809 2.5569 6.97533 2.5555 7.494V12.826C2.5555 13.165 2.8315 13.443 3.1725 13.443H8.5055C8.76249 13.4434 9.01701 13.3929 9.25445 13.2946C9.49188 13.1963 9.7075 13.052 9.889 12.87L10.645 12.1145H3.8855V5.353Z" fill="#C6CAD0"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

View file

@ -1,5 +1,5 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M13.0945 8.01611C13.0945 7.87619 12.9911 7.79551 12.8642 7.8356L4.13456 10.6038C4.00742 10.6441 3.90427 10.7904 3.90427 10.9301V13.7593C3.90427 13.8992 4.00742 13.9801 4.13456 13.9398L12.8642 11.1719C12.9911 11.1315 13.0945 10.9852 13.0945 10.8453V8.01611Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M3.90427 7.92597C3.90427 8.06588 4.00742 8.21218 4.13456 8.25252L12.8655 11.0209C12.9926 11.0613 13.0958 10.9803 13.0958 10.8407V8.01124C13.0958 7.87158 12.9926 7.72529 12.8655 7.68494L4.13456 4.91652C4.00742 4.87618 3.90427 4.95686 3.90427 5.09677V7.92597Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M13.0945 2.20248C13.0945 2.06256 12.9911 1.98163 12.8642 2.02197L4.13456 4.78988C4.00742 4.83022 3.90427 4.97652 3.90427 5.11644V7.94563C3.90427 8.08554 4.00742 8.16622 4.13456 8.12614L12.8642 5.35797C12.9911 5.31763 13.0945 5.17133 13.0945 5.03167V2.20248Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M12.5945 8.03524C12.5945 7.89532 12.4911 7.81464 12.3642 7.85473L3.63453 10.6229C3.50739 10.6632 3.40424 10.8095 3.40424 10.9492V13.7784C3.40424 13.9183 3.50739 13.9992 3.63453 13.9589L12.3642 11.191C12.4911 11.1506 12.5945 11.0043 12.5945 10.8644V8.03524Z" fill="#C6CAD0"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M3.40424 7.9451C3.40424 8.08501 3.50739 8.23131 3.63453 8.27165L12.3655 11.04C12.4926 11.0804 12.5958 10.9994 12.5958 10.8598V8.03037C12.5958 7.89071 12.4926 7.74442 12.3655 7.70407L3.63453 4.93565C3.50739 4.89531 3.40424 4.97599 3.40424 5.1159V7.9451Z" fill="#C6CAD0"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M12.5945 2.22161C12.5945 2.08169 12.4911 2.00076 12.3642 2.0411L3.63453 4.80901C3.50739 4.84935 3.40424 4.99565 3.40424 5.13557V7.96476C3.40424 8.10467 3.50739 8.18535 3.63453 8.14527L12.3642 5.3771C12.4911 5.33676 12.5945 5.19046 12.5945 5.0508V2.22161Z" fill="#C6CAD0"/>
</svg>

Before

Width:  |  Height:  |  Size: 1 KiB

After

Width:  |  Height:  |  Size: 1 KiB

View file

@ -1,3 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M11.0094 13.9181C11.1984 13.9917 11.4139 13.987 11.6047 13.8952L14.0753 12.7064C14.3349 12.5814 14.5 12.3187 14.5 12.0305V3.9696C14.5 3.68136 14.3349 3.41862 14.0753 3.2937L11.6047 2.10485C11.3543 1.98438 11.0614 2.01389 10.8416 2.17363C10.8102 2.19645 10.7803 2.22193 10.7523 2.25001L6.02261 6.56498L3.96246 5.00115C3.77068 4.85558 3.50244 4.86751 3.32432 5.02953L2.66356 5.63059C2.44569 5.82877 2.44544 6.17152 2.66302 6.37004L4.44965 8.00001L2.66302 9.62998C2.44544 9.82849 2.44569 10.1713 2.66356 10.3694L3.32432 10.9705C3.50244 11.1325 3.77068 11.1444 3.96246 10.9989L6.02261 9.43504L10.7523 13.75C10.8271 13.8249 10.915 13.8812 11.0094 13.9181ZM11.5018 5.27587L7.91309 8.00001L11.5018 10.7241V5.27587Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M10.5094 13.9181C10.6984 13.9917 10.9139 13.987 11.1047 13.8952L13.5753 12.7064C13.8349 12.5814 14 12.3187 14 12.0305V3.9696C14 3.68136 13.8349 3.41862 13.5753 3.2937L11.1047 2.10485C10.8543 1.98438 10.5614 2.01389 10.3416 2.17363C10.3102 2.19645 10.2803 2.22193 10.2523 2.25001L5.52261 6.56498L3.46246 5.00115C3.27068 4.85558 3.00244 4.86751 2.82432 5.02953L2.16356 5.63059C1.94569 5.82877 1.94544 6.17152 2.16302 6.37004L3.94965 8.00001L2.16302 9.62998C1.94544 9.82849 1.94569 10.1713 2.16356 10.3694L2.82432 10.9705C3.00244 11.1325 3.27068 11.1444 3.46246 10.9989L5.52261 9.43504L10.2523 13.75C10.3271 13.8249 10.415 13.8812 10.5094 13.9181ZM11.0018 5.27587L7.41309 8.00001L11.0018 10.7241V5.27587Z" fill="#C6CAD0"/>
</svg>

Before

Width:  |  Height:  |  Size: 876 B

After

Width:  |  Height:  |  Size: 872 B

View file

@ -0,0 +1,8 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M4.57391 3.54203V5.2877L5.96882 5.81793C6.73561 6.10752 7.38411 6.35224 7.41674 6.36039C7.46161 6.37263 7.46977 5.96476 7.46977 4.08858V1.80044H6.02184H4.57391V3.54203Z" fill="#C6CAD0" stroke="#C6CAD0" stroke-width="0.483833"/>
<path d="M8.53021 4.08451C8.53021 5.34074 8.54245 6.36856 8.56284 6.36856C8.57916 6.36856 9.22359 6.12384 9.99853 5.8261L11.4057 5.28771L11.4179 3.54205L11.4261 1.80046H9.97814H8.53021V4.08451Z" fill="#C6CAD0" stroke="#C6CAD0" stroke-width="0.483833"/>
<path d="M4.57391 7.1435C4.57391 7.54728 4.58615 7.87766 4.60654 7.87766C4.66772 7.87766 6.49089 7.16797 6.49089 7.1435C6.49089 7.11902 4.66772 6.40934 4.60654 6.40934C4.58615 6.40934 4.57391 6.73971 4.57391 7.1435Z" fill="#C6CAD0" stroke="#C6CAD0" stroke-width="0.483833"/>
<path d="M10.4186 6.76826C9.91696 6.95996 9.50909 7.12718 9.50909 7.1435C9.50909 7.16797 11.3323 7.87766 11.3975 7.87766C11.4138 7.87766 11.4261 7.54728 11.4261 7.1435C11.4261 6.58064 11.4138 6.40934 11.3771 6.41341C11.3486 6.41749 10.9162 6.57656 10.4186 6.76826Z" fill="#C6CAD0" stroke="#C6CAD0" stroke-width="0.483833"/>
<path d="M5.9729 8.46498L4.57391 8.99929V11.5974V14.1996H5.32439C6.00553 14.1996 6.07894 14.1914 6.09933 14.1262C6.11157 14.0895 6.42563 13.0616 6.79679 11.8421L7.46977 9.63148V8.77496C7.46977 8.11422 7.45753 7.91844 7.42082 7.92252C7.39227 7.9266 6.73969 8.16724 5.9729 8.46498Z" fill="#C6CAD0" stroke="#C6CAD0" stroke-width="0.483833"/>
<path d="M8.53021 8.77904V9.63964L9.1828 11.785C9.5458 12.9678 9.85986 13.9957 9.88025 14.065L9.92512 14.1996H10.6756H11.4261L11.4179 11.5974L11.4057 8.99929L9.99853 8.45682C9.22359 8.16316 8.57916 7.91844 8.56284 7.91844C8.54245 7.91844 8.53021 8.30591 8.53021 8.77904Z" fill="#C6CAD0" stroke="#C6CAD0" stroke-width="0.483833"/>
</svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

3
assets/icons/forgejo.svg Normal file
View file

@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.4889 1.74811C11.3234 1.74811 12 2.42467 12 3.25924C12 4.09382 11.3234 4.77032 10.4889 4.77032C9.92344 4.77032 9.43053 4.45981 9.17144 3.99993H8.4741C7.25904 3.99993 6.27176 4.97512 6.25212 6.18549L6.25176 7.28869C6.87559 6.81941 7.63228 6.56028 8.41283 6.54862L8.4741 6.5481L9.17144 6.5482C9.43053 6.08832 9.92344 5.77776 10.4889 5.77776C11.3234 5.77776 12 6.45432 12 7.28889C12 8.12347 11.3234 8.79998 10.4889 8.79998C9.92344 8.79998 9.43053 8.48947 9.17144 8.02959H8.4741C7.25904 8.02959 6.27176 9.00478 6.25212 10.2151L6.25176 11.4233C6.71164 11.6824 7.0222 12.1753 7.0222 12.7407C7.0222 13.5754 6.34564 14.2519 5.51107 14.2519C4.67654 14.2519 3.99998 13.5753 3.99998 12.7407C3.99998 12.1753 4.3105 11.6824 4.77043 11.4233L4.77032 6.22222C4.77032 4.19713 6.39555 2.55168 8.41283 2.51902L8.4741 2.5185H9.17144C9.43053 2.05872 9.92349 1.74811 10.4889 1.74811ZM5.51107 12.1185C5.16742 12.1185 4.88885 12.3971 4.88885 12.7407C4.88885 13.0844 5.16742 13.363 5.51107 13.363C5.85471 13.363 6.13334 13.0844 6.13334 12.7407C6.13334 12.3971 5.85471 12.1185 5.51107 12.1185ZM10.4889 6.66668C10.1453 6.66668 9.86665 6.94525 9.86665 7.28889C9.86665 7.63254 10.1453 7.91111 10.4889 7.91111C10.8326 7.91111 11.1111 7.63254 11.1111 7.28889C11.1111 6.94525 10.8326 6.66668 10.4889 6.66668ZM10.4889 2.63702C10.1453 2.63702 9.86665 2.9156 9.86665 3.25924C9.86665 3.60289 10.1453 3.88146 10.4889 3.88146C10.8326 3.88146 11.1111 3.60289 11.1111 3.25924C11.1111 2.9156 10.8326 2.63702 10.4889 2.63702Z" fill="#C6CAD0"/>
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

3
assets/icons/gitea.svg Normal file
View file

@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3.45524 3.60059C3.31116 3.60059 3.14899 3.61226 2.96524 3.65192C2.77099 3.69276 2.21858 3.81701 1.76707 4.25101C0.764907 5.14467 1.02041 6.56509 1.05191 6.77917C1.08982 7.03934 1.20532 7.76326 1.75774 8.39384C2.77799 9.64276 4.97366 9.61418 4.97366 9.61418C4.97366 9.61418 5.24316 10.2576 5.65499 10.8503C6.21208 11.587 6.78433 12.1616 7.34083 12.231C8.74433 12.231 11.5478 12.2287 11.5478 12.2287C11.5478 12.2287 11.815 12.231 12.1778 11.9988C12.4899 11.8098 12.7687 11.4779 12.7687 11.4779C12.7687 11.4779 13.0557 11.1705 13.4571 10.4688C13.5796 10.2529 13.6817 10.0435 13.7709 9.84576C13.7709 9.84576 15 7.23768 15 4.69901C14.9755 3.93017 14.7859 3.79484 14.7416 3.74992C14.6506 3.65892 14.5281 3.66067 14.5281 3.66067C14.5281 3.66067 11.9177 3.80767 10.5661 3.83917C10.2697 3.84559 9.97575 3.85259 9.68408 3.85492V6.46476L9.31425 6.28917C9.31425 5.47834 9.31191 3.85667 9.31191 3.85667C8.66616 3.86601 7.32566 3.80767 7.32566 3.80767C7.32566 3.80767 4.17624 3.65017 3.83324 3.61867C3.72416 3.61226 3.59933 3.60059 3.45524 3.60059ZM3.66174 4.66926H3.72649C3.72649 4.66926 3.88458 5.99284 4.07649 6.76751C4.23691 7.41792 4.62833 8.49884 4.62833 8.49884C4.62833 8.49884 4.04733 8.42943 3.67108 8.29584C3.09358 8.10684 2.84916 7.87934 2.84916 7.87934C2.84916 7.87934 2.42333 7.58126 2.20983 6.99268C1.84232 6.00801 2.17891 5.40717 2.17891 5.40717C2.17891 5.40717 2.36558 4.90609 3.03641 4.73926C3.26683 4.67742 3.53983 4.66926 3.66174 4.66926ZM8.52091 6.15909C8.67258 6.16084 8.81783 6.23317 8.81783 6.23317L9.32416 6.47934L9.01558 7.10642C8.94244 7.10526 8.87038 7.12417 8.80724 7.16109C8.74409 7.19801 8.69227 7.25153 8.65741 7.31584C8.62013 7.3853 8.60423 7.46422 8.61171 7.5427C8.61918 7.62117 8.64969 7.69567 8.69941 7.75684L8.15166 8.87918C8.0625 8.88053 7.97631 8.91146 7.90663 8.9671C7.83695 9.02274 7.78772 9.09994 7.76666 9.18659C7.74656 9.27272 7.75551 9.36308 7.79213 9.44358C7.82874 9.52409 7.89096 9.59022 7.96908 9.63168C8.05388 9.67515 8.15141 9.68693 8.24412 9.6649C8.33684 9.64287 8.41864 9.58848 8.47483 9.51151C8.52969 9.43471 8.55573 9.34103 8.54837 9.24693C8.541 9.15284 8.50072 9.06435 8.43458 8.99701L8.96891 7.90384C9.01532 7.90827 9.06215 7.90432 9.10716 7.89218C9.16538 7.87825 9.21952 7.85088 9.26525 7.81226C9.46902 7.89896 9.66699 7.99873 9.85791 8.11093C9.92725 8.14983 9.98487 8.20664 10.0247 8.27543C10.0673 8.39793 9.98216 8.60734 9.98216 8.60734C9.93141 8.77651 9.57266 9.51151 9.57266 9.51151C9.48573 9.50923 9.40039 9.53508 9.32933 9.58521C9.25828 9.63535 9.20532 9.70709 9.17833 9.78976C9.15763 9.85611 9.15471 9.92673 9.16985 9.99456C9.18498 10.0624 9.21765 10.1251 9.26459 10.1763C9.31153 10.2276 9.3711 10.2656 9.43734 10.2867C9.50359 10.3077 9.57419 10.311 9.6421 10.2962C9.71001 10.2814 9.77285 10.2491 9.82435 10.2024C9.87585 10.1557 9.9142 10.0963 9.93557 10.0302C9.95694 9.96406 9.96058 9.89347 9.94614 9.82548C9.93169 9.7575 9.89966 9.69449 9.85325 9.64276C9.89583 9.56051 9.9355 9.47826 9.97808 9.39134C10.0889 9.15976 10.2785 8.71468 10.2785 8.71468C10.2989 8.67618 10.4057 8.48484 10.3386 8.23984C10.2832 7.98609 10.0586 7.86768 10.0586 7.86768C9.78616 7.69209 9.40758 7.52934 9.40758 7.52934C9.40758 7.52934 9.40758 7.43834 9.38308 7.37184C9.36435 7.31951 9.33495 7.27164 9.29675 7.23126L9.59775 6.61176L11.2836 7.42901C11.2836 7.42901 11.5636 7.55618 11.6237 7.79009C11.6662 7.95459 11.6126 8.10159 11.5834 8.17334C11.4434 8.51576 10.3584 10.6916 10.3584 10.6916C10.3584 10.6916 10.2231 11.0148 9.92208 11.0346C9.8447 11.0402 9.76694 11.0313 9.69283 11.0083L9.575 10.9617L7.06083 9.73668C7.06083 9.73668 6.81758 9.60951 6.77499 9.38901C6.72658 9.20818 6.83566 8.98593 6.83566 8.98593L8.04491 6.49392C8.04491 6.49392 8.15166 6.27809 8.31675 6.20401C8.38086 6.17478 8.45045 6.15947 8.52091 6.15909Z" fill="#C6CAD0"/>
</svg>

After

Width:  |  Height:  |  Size: 3.8 KiB

3
assets/icons/gitlab.svg Normal file
View file

@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14.0228 6.75008L14.0053 6.70533L12.3092 2.27915C12.2747 2.19237 12.2136 2.11876 12.1347 2.06887C12.0557 2.01987 11.9636 1.99627 11.8708 2.00128C11.7779 2.00628 11.6889 2.03964 11.6156 2.09686C11.5432 2.15571 11.4906 2.23546 11.4651 2.32525L10.32 5.82877H5.68303L4.53784 2.32525C4.513 2.23496 4.46031 2.1548 4.38727 2.09618C4.31401 2.03898 4.22496 2.00564 4.13214 2.00065C4.03932 1.99567 3.94721 2.01928 3.86824 2.0683C3.78948 2.11837 3.72842 2.1919 3.69368 2.27852L1.99452 6.70273L1.97764 6.74748C1.73349 7.38539 1.70335 8.08539 1.89177 8.74192C2.08018 9.39845 2.47694 9.97594 3.02221 10.3873L3.02808 10.3918L3.04365 10.4029L5.62716 12.3376L6.90542 13.305L7.68395 13.8928C7.77502 13.9619 7.88623 13.9994 8.00058 13.9994C8.11493 13.9994 8.22613 13.9619 8.31721 13.8928L9.09574 13.305L10.3739 12.3376L12.973 10.3912L12.9795 10.386C13.5236 9.97456 13.9194 9.39768 14.1075 8.74203C14.2957 8.08638 14.2659 7.38738 14.0228 6.75008Z" fill="#C6CAD0"/>
</svg>

After

Width:  |  Height:  |  Size: 1 KiB

5
assets/icons/share.svg Normal file
View file

@ -0,0 +1,5 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.99689 2.05652L7.99929 9.98113" stroke="#C6CAD0" stroke-width="1.17299" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M11.1699 5.22637L8.00001 2.05652L4.83015 5.22637" stroke="#C6CAD0" stroke-width="1.17299" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M3.24522 8L3.24522 12.2653C3.24522 12.7104 3.37046 13.1372 3.59338 13.4519C3.81631 13.7667 4.11866 13.9435 4.43392 13.9435H11.5661C11.8813 13.9435 12.1837 13.7667 12.4066 13.4519C12.6295 13.1372 12.7548 12.7104 12.7548 12.2653V8" stroke="#C6CAD0" stroke-width="1.17299" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 711 B

View file

@ -0,0 +1,6 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M11.748 5.74794L14 7.99998L11.748 10.252" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M14 7.99997L3 7.99997" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8 3L8 6" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8 10L8 13" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 566 B

View file

@ -0,0 +1,5 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5.19924 8.90081L2.9472 6.64876L5.19924 4.39673" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M2.9472 6.64877H7.67649C8.00178 6.64877 8.32391 6.71285 8.6245 6.83734C8.92501 6.96184 9.19813 7.14431 9.42817 7.37434C9.6582 7.60437 9.84067 7.87746 9.96512 8.17802C10.0897 8.47856 10.1537 8.8007 10.1537 9.12601C10.1537 9.45131 10.0897 9.77345 9.96512 10.074C9.84067 10.3745 9.6582 10.6477 9.42817 10.8777C9.19813 11.1077 8.92501 11.2902 8.6245 11.4147C8.32391 11.5392 8.00178 11.6033 7.67649 11.6033H6.10005" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M13.0528 3.33331V12.6666" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 871 B

View file

@ -729,6 +729,7 @@
"use_key_equivalents": true,
"bindings": {
"space": "menu::Confirm",
"shift-r": "agent::RenameSelectedThread",
},
},
{
@ -979,6 +980,13 @@
"space": "project_panel::Open",
},
},
{
"context": "GitPanel",
"bindings": {
"ctrl-1": "git_panel::ActivateChangesTab",
"ctrl-2": "git_panel::ActivateHistoryTab",
},
},
{
"context": "GitPanel && ChangesList && !GitBranchSelector",
"bindings": {
@ -1551,4 +1559,20 @@
"shift-tab": "git_graph::FocusPreviousTabStop",
},
},
{
"context": "SkillCreator",
"bindings": {
"ctrl-w": "workspace::CloseWindow",
"tab": "skill_creator::FocusNextField",
"shift-tab": "skill_creator::FocusPreviousField",
},
},
{
"context": "SkillCreator > Editor",
"bindings": {
"ctrl-w": "workspace::CloseWindow",
"tab": "skill_creator::FocusNextField",
"shift-tab": "skill_creator::FocusPreviousField",
},
},
]

View file

@ -785,6 +785,7 @@
"use_key_equivalents": true,
"bindings": {
"space": "menu::Confirm",
"shift-r": "agent::RenameSelectedThread",
},
},
{
@ -1040,6 +1041,13 @@
"alt-enter": "variable_list::AddWatch",
},
},
{
"context": "GitPanel",
"bindings": {
"cmd-1": "git_panel::ActivateChangesTab",
"cmd-2": "git_panel::ActivateHistoryTab",
},
},
{
"context": "GitPanel && ChangesList && !GitBranchSelector",
"use_key_equivalents": true,
@ -1644,4 +1652,22 @@
"shift-tab": "git_graph::FocusPreviousTabStop",
},
},
{
"context": "SkillCreator",
"use_key_equivalents": true,
"bindings": {
"cmd-w": "workspace::CloseWindow",
"tab": "skill_creator::FocusNextField",
"shift-tab": "skill_creator::FocusPreviousField",
},
},
{
"context": "SkillCreator > Editor",
"use_key_equivalents": true,
"bindings": {
"cmd-w": "workspace::CloseWindow",
"tab": "skill_creator::FocusNextField",
"shift-tab": "skill_creator::FocusPreviousField",
},
},
]

View file

@ -732,6 +732,7 @@
"use_key_equivalents": true,
"bindings": {
"space": "menu::Confirm",
"shift-r": "agent::RenameSelectedThread",
},
},
{
@ -972,6 +973,13 @@
"space": "project_panel::Open",
},
},
{
"context": "GitPanel",
"bindings": {
"ctrl-1": "git_panel::ActivateChangesTab",
"ctrl-2": "git_panel::ActivateHistoryTab",
},
},
{
"context": "GitPanel && ChangesList && !GitBranchSelector",
"use_key_equivalents": true,
@ -1570,4 +1578,22 @@
"shift-tab": "git_graph::FocusPreviousTabStop",
},
},
{
"context": "SkillCreator",
"use_key_equivalents": true,
"bindings": {
"ctrl-w": "workspace::CloseWindow",
"tab": "skill_creator::FocusNextField",
"shift-tab": "skill_creator::FocusPreviousField",
},
},
{
"context": "SkillCreator > Editor",
"use_key_equivalents": true,
"bindings": {
"ctrl-w": "workspace::CloseWindow",
"tab": "skill_creator::FocusNextField",
"shift-tab": "skill_creator::FocusPreviousField",
},
},
]

View file

@ -494,6 +494,10 @@
"n": "vim::HelixSelectNext",
"shift-n": "vim::HelixSelectPrevious",
// Macros Helix swaps Vim's q/Q: Q records, q replays
"q": "vim::ReplayLastRecording",
"shift-q": "vim::ToggleRecord",
// Goto mode
"g e": "vim::EndOfDocument",
"g h": "vim::StartOfLine",
@ -503,6 +507,8 @@
"g c": "vim::WindowMiddle",
"g b": "vim::WindowBottom",
"g r": "editor::FindAllReferences",
"g i": "editor::GoToImplementation",
"g a": "pane::AlternateFile",
"g n": "pane::ActivateNextItem",
"shift-l": "pane::ActivateNextItem", // not a helix default
"g p": "pane::ActivatePreviousItem",
@ -943,7 +949,7 @@
"space w j": "workspace::ActivatePaneDown",
"space w k": "workspace::ActivatePaneUp",
"space w l": "workspace::ActivatePaneRight",
"space w q": "pane::CloseActiveItem",
"space w q": "pane::CloseActiveItem",
},
},
{
@ -1056,8 +1062,8 @@
"ctrl-d": "git_graph::ScrollDown",
"ctrl-u": "git_graph::ScrollUp",
"shift-g": "menu::SelectLast",
"g g": "menu::SelectFirst"
}
"g g": "menu::SelectFirst",
},
},
{
"context": "GitPanel && ChangesList && !GitBranchSelector",
@ -1205,4 +1211,18 @@
"enter": "editor::Newline",
},
},
{
"context": "SkillCreator",
"bindings": {
"tab": "skill_creator::FocusNextField",
"shift-tab": "skill_creator::FocusPreviousField",
},
},
{
"context": "SkillCreator > Editor",
"bindings": {
"tab": "skill_creator::FocusNextField",
"shift-tab": "skill_creator::FocusPreviousField",
},
},
]

View file

@ -71,6 +71,8 @@
"agent_ui_font_size": null,
// The default font size for user messages in the agent panel.
"agent_buffer_font_size": 12,
// The default font size for the commit editor in the git panel and commit modal.
"git_commit_buffer_font_size": 12,
// How much to fade out unused code.
"unnecessary_code_fade": 0.3,
// Active pane styling settings.
@ -1133,6 +1135,7 @@
"spawn_agent": true,
"terminal": true,
"update_plan": true,
"update_title": true,
"search_web": true,
},
},
@ -1153,6 +1156,7 @@
"skill": true,
"spawn_agent": true,
"update_plan": true,
"update_title": true,
"search_web": true,
},
},
@ -1496,6 +1500,10 @@
// 4. Draw a background behind the color text..
// "lsp_document_colors": "background",
"lsp_document_colors": "inlay",
// Whether to query and display LSP `textDocument/documentLink` links in the editor.
//
// Default: true
"lsp_document_links": true,
// Diagnostics configuration.
"diagnostics": {
// Whether to show the project diagnostics button in the status bar.
@ -1610,6 +1618,8 @@
// Should the name or path be displayed first in the git view.
// "path_style": "file_name_first" or "file_path_first"
"path_style": "file_name_first",
// Whether to show the stage and restore buttons on diff hunks.
"show_stage_restore_buttons": true,
// Directory where git worktrees are created, relative to the repository
// working directory.
//

View file

@ -104,14 +104,6 @@
"version_control.deleted": "#e06c76ff",
"version_control.conflict_marker.ours": "#a1c1811a",
"version_control.conflict_marker.theirs": "#74ade81a",
"vim.normal.background": "#485e82",
"vim.insert.background": "#825b48",
"vim.visual.background": "#488251",
"vim.replace.background": "#827d48",
"vim.visual_line.background": "#488268",
"vim.visual_block.background": "#488276",
"vim.helix_normal.background": "#485e82",
"vim.helix_select.background": "#488251",
"conflict": "#dec184ff",
"conflict.background": "#dec1841a",
"conflict.border": "#5d4c2fff",
@ -524,14 +516,6 @@
"version_control.word_added": "#2EA04859",
"version_control.word_deleted": "#F85149CC",
"version_control.deleted": "#e06c76ff",
"vim.normal.background": "#b0c8e8",
"vim.insert.background": "#e8c0a8",
"vim.visual.background": "#b0dcb8",
"vim.replace.background": "#e0dcb0",
"vim.visual_line.background": "#b0dccc",
"vim.visual_block.background": "#b0d4dc",
"vim.helix_normal.background": "#b0c8e8",
"vim.helix_select.background": "#b0dcb8",
"conflict": "#a48819ff",
"conflict.background": "#faf2e6ff",
"conflict.border": "#f4e7d1ff",

View file

@ -13,7 +13,7 @@ path = "src/acp_thread.rs"
doctest = false
[features]
test-support = ["gpui/test-support", "project/test-support", "dep:parking_lot", "dep:image"]
test-support = ["gpui/test-support", "project/test-support", "dep:parking_lot"]
[dependencies]
action_log.workspace = true
@ -35,7 +35,7 @@ language_model.workspace = true
log.workspace = true
markdown.workspace = true
parking_lot = { workspace = true, optional = true }
image = { workspace = true, optional = true }
image.workspace = true
portable-pty.workspace = true
project.workspace = true
prompt_store.workspace = true

View file

@ -93,35 +93,6 @@ pub fn subagent_session_info_from_meta(meta: &Option<acp::Meta>) -> Option<Subag
.and_then(|v| serde_json::from_value(v.clone()).ok())
}
/// Key used in ACP `AvailableCommand` meta to indicate where a skill
/// originated from (e.g. `"global"` or a worktree root name). Set by
/// the native agent so the completion popup can surface skill origin to
/// disambiguate same-named global vs. project-local skills.
pub const SKILL_SOURCE_META_KEY: &str = "zed.skill_source";
/// Borrowing accessor for the skill source label stored in ACP meta.
/// Prefer this over [`skill_source_from_meta`] in hot paths (e.g. per-
/// command iteration during validation), since it avoids allocating
/// a `SharedString` for callers that only need to compare against a
/// `&str`.
pub fn skill_source_str_from_meta(meta: &Option<acp::Meta>) -> Option<&str> {
meta.as_ref()
.and_then(|m| m.get(SKILL_SOURCE_META_KEY))
.and_then(|v| v.as_str())
}
/// Helper to extract skill source label from ACP meta as an owned
/// `SharedString`. Use this when the value needs to outlive the meta
/// reference; otherwise prefer [`skill_source_str_from_meta`].
pub fn skill_source_from_meta(meta: &Option<acp::Meta>) -> Option<SharedString> {
skill_source_str_from_meta(meta).map(|s| SharedString::from(s.to_owned()))
}
/// Helper to create meta tagging an `AvailableCommand` with a skill source.
pub fn meta_with_skill_source(source: &str) -> acp::Meta {
acp::Meta::from_iter([(SKILL_SOURCE_META_KEY.into(), source.into())])
}
#[derive(Debug)]
pub struct UserMessage {
pub id: Option<UserMessageId>,
@ -677,9 +648,16 @@ impl Display for ToolCallStatus {
#[derive(Debug, PartialEq, Clone)]
pub enum ContentBlock {
Empty,
Markdown { markdown: Entity<Markdown> },
ResourceLink { resource_link: acp::ResourceLink },
Image { image: Arc<gpui::Image> },
Markdown {
markdown: Entity<Markdown>,
},
ResourceLink {
resource_link: acp::ResourceLink,
},
Image {
image: Arc<gpui::Image>,
dimensions: Option<gpui::Size<u32>>,
},
}
impl ContentBlock {
@ -721,8 +699,8 @@ impl ContentBlock {
};
}
(ContentBlock::Empty, acp::ContentBlock::Image(image_content)) => {
if let Some(image) = Self::decode_image(image_content) {
*self = ContentBlock::Image { image };
if let Some((image, dimensions)) = Self::decode_image(image_content) {
*self = ContentBlock::Image { image, dimensions };
} else {
let new_content = Self::image_md(image_content);
*self = Self::create_markdown_block(new_content, language_registry, cx);
@ -750,14 +728,36 @@ impl ContentBlock {
}
}
fn decode_image(image_content: &acp::ImageContent) -> Option<Arc<gpui::Image>> {
fn decode_image(
image_content: &acp::ImageContent,
) -> Option<(Arc<gpui::Image>, Option<gpui::Size<u32>>)> {
use base64::Engine as _;
let bytes = base64::engine::general_purpose::STANDARD
.decode(image_content.data.as_bytes())
.ok()?;
let format = gpui::ImageFormat::from_mime_type(&image_content.mime_type)?;
Some(Arc::new(gpui::Image::from_bytes(format, bytes)))
let dimensions = Self::image_dimensions(&bytes, format);
Some((Arc::new(gpui::Image::from_bytes(format, bytes)), dimensions))
}
fn image_dimensions(bytes: &[u8], format: gpui::ImageFormat) -> Option<gpui::Size<u32>> {
let format = match format {
gpui::ImageFormat::Png => image::ImageFormat::Png,
gpui::ImageFormat::Jpeg => image::ImageFormat::Jpeg,
gpui::ImageFormat::Webp => image::ImageFormat::WebP,
gpui::ImageFormat::Gif => image::ImageFormat::Gif,
gpui::ImageFormat::Svg => return None,
gpui::ImageFormat::Bmp => image::ImageFormat::Bmp,
gpui::ImageFormat::Tiff => image::ImageFormat::Tiff,
gpui::ImageFormat::Ico => image::ImageFormat::Ico,
gpui::ImageFormat::Pnm => image::ImageFormat::Pnm,
};
image::ImageReader::with_format(std::io::Cursor::new(bytes), format)
.into_dimensions()
.ok()
.map(|(width, height)| gpui::Size { width, height })
}
fn create_markdown_block(
@ -837,9 +837,9 @@ impl ContentBlock {
}
}
pub fn image(&self) -> Option<&Arc<gpui::Image>> {
pub fn image(&self) -> Option<(&Arc<gpui::Image>, Option<gpui::Size<u32>>)> {
match self {
ContentBlock::Image { image } => Some(image),
ContentBlock::Image { image, dimensions } => Some((image, *dimensions)),
_ => None,
}
}
@ -924,7 +924,7 @@ impl ToolCallContent {
}
}
pub fn image(&self) -> Option<&Arc<gpui::Image>> {
pub fn image(&self) -> Option<(&Arc<gpui::Image>, Option<gpui::Size<u32>>)> {
match self {
Self::ContentBlock(content) => content.image(),
_ => None,

View file

@ -7,14 +7,14 @@ use gpui::{Entity, SharedString, Task};
use language_model::LanguageModelProviderId;
use project::{AgentId, Project};
use serde::{Deserialize, Serialize};
use std::{any::Any, error::Error, fmt, path::PathBuf, rc::Rc, sync::Arc};
use std::{any::Any, error::Error, fmt, path::PathBuf, rc::Rc};
use task::{HideStrategy, SpawnInTerminal, TaskId};
use ui::{App, IconName};
use util::path_list::PathList;
use uuid::Uuid;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub struct UserMessageId(Arc<str>);
pub struct UserMessageId(SharedString);
impl UserMessageId {
pub fn new() -> Self {
@ -115,6 +115,11 @@ pub trait AgentConnection {
self.supports_load_session() || self.supports_resume_session()
}
/// Whether this agent supports additional session directories.
fn supports_session_additional_directories(&self) -> bool {
false
}
fn auth_methods(&self) -> &[acp::AuthMethod];
fn terminal_auth_task(
@ -127,6 +132,14 @@ pub trait AgentConnection {
fn authenticate(&self, method: acp::AuthMethodId, cx: &mut App) -> Task<Result<()>>;
fn supports_logout(&self) -> bool {
false
}
fn logout(&self, _cx: &mut App) -> Task<Result<()>> {
Task::ready(Err(anyhow::Error::msg("Logout is not supported")))
}
fn prompt(
&self,
user_message_id: UserMessageId,
@ -310,7 +323,7 @@ pub trait AgentSessionList {
cx: &mut App,
) -> Task<Result<AgentSessionListResponse>>;
fn supports_delete(&self) -> bool {
fn supports_delete(&self, _cx: &App) -> bool {
false
}
@ -694,6 +707,7 @@ mod test_support {
permission_requests: HashMap<acp::ToolCallId, PermissionOptions>,
next_prompt_updates: Arc<Mutex<Vec<acp::SessionUpdate>>>,
supports_load_session: bool,
supports_session_additional_directories: bool,
agent_id: AgentId,
telemetry_id: SharedString,
}
@ -716,6 +730,7 @@ mod test_support {
permission_requests: HashMap::default(),
sessions: Arc::default(),
supports_load_session: false,
supports_session_additional_directories: false,
agent_id: AgentId::new("stub"),
telemetry_id: "stub".into(),
}
@ -738,6 +753,14 @@ mod test_support {
self
}
pub fn with_supports_session_additional_directories(
mut self,
supports_session_additional_directories: bool,
) -> Self {
self.supports_session_additional_directories = supports_session_additional_directories;
self
}
pub fn with_agent_id(mut self, agent_id: AgentId) -> Self {
self.agent_id = agent_id;
self
@ -855,6 +878,10 @@ mod test_support {
self.supports_load_session
}
fn supports_session_additional_directories(&self) -> bool {
self.supports_session_additional_directories
}
fn load_session(
self: Rc<Self>,
session_id: acp::SessionId,

View file

@ -51,6 +51,8 @@ pub enum MentionUri {
#[serde(default, skip_serializing_if = "Option::is_none")]
abs_path: Option<PathBuf>,
line_range: RangeInclusive<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
column: Option<u32>,
},
Fetch {
url: Url,
@ -64,6 +66,11 @@ pub enum MentionUri {
MergeConflict {
file_path: String,
},
Skill {
name: String,
source: String,
skill_file_path: PathBuf,
},
}
impl MentionUri {
@ -100,6 +107,17 @@ impl MentionUri {
Ok(start_line..=end_line)
}
let parse_column =
|input: Option<String>| -> Option<u32> { input?.parse::<u32>().ok()?.checked_sub(1) };
let validate_query_params = |url: &Url, allowed: &[&str]| -> Result<()> {
for (key, _) in url.query_pairs() {
if !allowed.contains(&key.as_ref()) {
bail!("invalid query parameter")
}
}
Ok(())
};
let parse_absolute_path = |input: &str| -> Result<Self> {
let (path_input, fragment) = input
.split_once('#')
@ -109,6 +127,7 @@ impl MentionUri {
return Ok(MentionUri::Selection {
abs_path: Some(path_input.into()),
line_range: fragment,
column: None,
});
}
@ -118,10 +137,12 @@ impl MentionUri {
let line = row
.checked_sub(1)
.context("Line numbers should be 1-based")?;
// TODO: Preserve column info too.
Ok(MentionUri::Selection {
abs_path: Some(abs_path),
line_range: line..=line,
column: path_with_position
.column
.map(|column| column.saturating_sub(1)),
})
} else {
Ok(MentionUri::File { abs_path })
@ -151,8 +172,10 @@ impl MentionUri {
let path = normalized.as_ref();
if let Some(fragment) = url.fragment() {
validate_query_params(&url, &["symbol", "column"])?;
let line_range = parse_line_range(fragment).log_err().unwrap_or(1..=1);
if let Some(name) = single_query_param(&url, "symbol")? {
let column = parse_column(query_param(&url, "column"));
if let Some(name) = query_param(&url, "symbol") {
Ok(Self::Symbol {
name,
abs_path: path.into(),
@ -162,6 +185,7 @@ impl MentionUri {
Ok(Self::Selection {
abs_path: Some(path.into()),
line_range,
column,
})
}
} else if input.ends_with("/") {
@ -211,9 +235,11 @@ impl MentionUri {
.fragment()
.context("Missing fragment for untitled buffer selection")?;
let line_range = parse_line_range(fragment)?;
validate_query_params(&url, &["column"])?;
Ok(Self::Selection {
abs_path: None,
line_range,
column: parse_column(query_param(&url, "column")),
})
} else if let Some(name) = path.strip_prefix("/agent/symbol/") {
let fragment = url
@ -240,13 +266,15 @@ impl MentionUri {
abs_path: path.into(),
})
} else if path.starts_with("/agent/selection") {
validate_query_params(&url, &["path", "column"])?;
let fragment = url.fragment().context("Missing fragment for selection")?;
let line_range = parse_line_range(fragment)?;
let path =
single_query_param(&url, "path")?.context("Missing path for selection")?;
let column = parse_column(query_param(&url, "column"));
let path = query_param(&url, "path").context("Missing path for selection")?;
Ok(Self::Selection {
abs_path: Some(path.into()),
line_range,
column,
})
} else if path.starts_with("/agent/terminal-selection") {
let line_count = single_query_param(&url, "lines")?
@ -261,6 +289,40 @@ impl MentionUri {
} else if path.starts_with("/agent/merge-conflict") {
let file_path = single_query_param(&url, "path")?.unwrap_or_default();
Ok(Self::MergeConflict { file_path })
} else if path.starts_with("/agent/skill") {
let mut name = None;
let mut source = None;
let mut skill_file_path = None;
for (key, value) in url.query_pairs() {
match key.as_ref() {
"name" => {
if name.replace(value.to_string()).is_some() {
bail!("duplicate skill name query parameter");
}
}
"source" => {
if source.replace(value.to_string()).is_some() {
bail!("duplicate skill source query parameter");
}
}
"path" => {
if skill_file_path
.replace(PathBuf::from(value.to_string()))
.is_some()
{
bail!("duplicate skill file path query parameter");
}
}
_ => bail!("invalid query parameter"),
}
}
Ok(Self::Skill {
name: name.context("missing skill name")?,
source: source.context("missing skill source")?,
skill_file_path: skill_file_path.context("missing skill file path")?,
})
} else {
bail!("invalid zed url: {:?}", input);
}
@ -303,6 +365,33 @@ impl MentionUri {
..
} => selection_name(path.as_deref(), line_range),
MentionUri::Fetch { url } => url.to_string(),
MentionUri::Skill { name, .. } => name.clone(),
}
}
/// Returns a label for this mention at the given disambiguation `detail`
/// level. `detail == 0` is the base name returned by [`Self::name`]; higher
/// levels include progressively more context (e.g. additional parent path
/// components for files, or the source for skills) until a fixed point is
/// reached. Intended to be driven by [`util::disambiguate::compute_disambiguation_details`].
pub fn disambiguated_name(&self, detail: usize) -> String {
if detail == 0 {
return self.name();
}
match self {
MentionUri::Skill { name, source, .. } => {
if source.is_empty() {
// Must match `SkillSource::display_label()` in agent_skills.
format!("{} (global)", name)
} else {
format!("{} ({})", name, source)
}
}
MentionUri::File { abs_path, .. } | MentionUri::Directory { abs_path, .. } => {
project::path_suffix(abs_path, detail)
}
_ => self.name(),
}
}
@ -337,6 +426,9 @@ impl MentionUri {
)
.into(),
),
MentionUri::Skill {
skill_file_path, ..
} => Some(skill_file_path.to_string_lossy().into_owned().into()),
_ => None,
}
}
@ -358,6 +450,7 @@ impl MentionUri {
MentionUri::Fetch { .. } => IconName::ToolWeb.path().into(),
MentionUri::GitDiff { .. } => IconName::GitBranch.path().into(),
MentionUri::MergeConflict { .. } => IconName::GitMergeConflict.path().into(),
MentionUri::Skill { .. } => IconName::Sparkle.path().into(),
}
}
@ -390,6 +483,7 @@ impl MentionUri {
abs_path,
name,
line_range,
..
} => {
let mut url = Url::parse("file:///").unwrap();
url.set_path(&abs_path.to_string_lossy());
@ -404,6 +498,7 @@ impl MentionUri {
MentionUri::Selection {
abs_path,
line_range,
column,
} => {
let mut url = if let Some(path) = abs_path {
let mut url = Url::parse("file:///").unwrap();
@ -414,6 +509,10 @@ impl MentionUri {
url.set_path("/agent/untitled-buffer");
url
};
if let Some(column) = column {
url.query_pairs_mut()
.append_pair("column", &(column + 1).to_string());
}
url.set_fragment(Some(&format!(
"L{}:{}",
line_range.start() + 1,
@ -465,6 +564,19 @@ impl MentionUri {
url.query_pairs_mut().append_pair("path", file_path);
url
}
MentionUri::Skill {
name,
source,
skill_file_path,
} => {
let mut url = Url::parse("zed:///").unwrap();
url.set_path("/agent/skill");
url.query_pairs_mut()
.append_pair("name", name)
.append_pair("source", source)
.append_pair("path", &skill_file_path.to_string_lossy());
url
}
}
}
}
@ -481,6 +593,11 @@ fn default_include_errors() -> bool {
true
}
fn query_param(url: &Url, name: &'static str) -> Option<String> {
url.query_pairs()
.find_map(|(key, value)| (key == name).then(|| value.to_string()))
}
fn single_query_param(url: &Url, name: &'static str) -> Result<Option<String>> {
let pairs = url.query_pairs().collect::<Vec<_>>();
match pairs.as_slice() {
@ -615,6 +732,7 @@ mod tests {
abs_path: path,
name,
line_range,
..
} => {
assert_eq!(path, Path::new(path!("/path/to/file.rs")));
assert_eq!(name, "MySymbol");
@ -634,6 +752,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
assert_eq!(line_range.start(), &4);
@ -665,6 +784,7 @@ mod tests {
MentionUri::Selection {
abs_path: None,
line_range,
..
} => {
assert_eq!(line_range.start(), &0);
assert_eq!(line_range.end(), &9);
@ -705,6 +825,20 @@ mod tests {
assert_eq!(parsed.to_uri().to_string(), rule_uri);
}
#[test]
fn test_parse_skill_uri_round_trip() {
let skill_uri = MentionUri::Skill {
name: "rust-best-practices".to_string(),
source: "my-personal-project".to_string(),
skill_file_path: PathBuf::from(path!("/path/to/skills/rust-best-practices/SKILL.md")),
};
let serialized = skill_uri.to_uri().to_string();
let parsed = MentionUri::parse(&serialized, PathStyle::local()).unwrap();
assert_eq!(parsed, skill_uri);
}
#[test]
fn test_parse_fetch_http_uri() {
let http_uri = "http://example.com/path?query=value#fragment";
@ -798,6 +932,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
assert_eq!(line_range.start(), &41);
@ -807,6 +942,29 @@ mod tests {
}
}
#[test]
fn test_parse_absolute_file_path_with_row_and_column() {
let file_path = "/path/to/file.rs:42:5";
let parsed = MentionUri::parse(file_path, PathStyle::Posix).unwrap();
match &parsed {
MentionUri::Selection {
abs_path: path,
line_range,
column,
} => {
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
assert_eq!(line_range.start(), &41);
assert_eq!(line_range.end(), &41);
assert_eq!(column, &Some(4));
let parsed_again = MentionUri::parse(parsed.to_uri().as_ref(), PathStyle::Posix)
.expect("selection URI with column should parse");
assert_eq!(parsed_again, parsed.clone());
}
_ => panic!("Expected Selection variant"),
}
}
#[test]
fn test_parse_absolute_file_path_with_fragment_line() {
let file_path = "/path/to/file.rs#L42";
@ -815,6 +973,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
assert_eq!(line_range.start(), &41);
@ -844,6 +1003,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(
path.as_ref().unwrap(),
@ -864,6 +1024,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(
path.as_ref().unwrap(),
@ -896,6 +1057,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
assert_eq!(line_range.start(), &41);
@ -913,6 +1075,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(
path.as_ref().unwrap(),
@ -934,6 +1097,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
assert_eq!(line_range.start(), &1871);
@ -951,6 +1115,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
assert_eq!(line_range.start(), &9);
@ -966,6 +1131,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
assert_eq!(line_range.start(), &9);
@ -993,4 +1159,68 @@ mod tests {
let parsed_single = MentionUri::parse(single_line_uri, PathStyle::local()).unwrap();
assert_eq!(parsed_single.name(), "Terminal (1 line)");
}
#[test]
fn test_disambiguated_name() {
// Two files with the same name — should disambiguate with parent dir
let file_a = MentionUri::File {
abs_path: PathBuf::from(path!("/project/src/README.md")),
};
let file_b = MentionUri::File {
abs_path: PathBuf::from(path!("/project/docs/README.md")),
};
assert_eq!(file_a.name(), "README.md");
assert_eq!(file_b.name(), "README.md");
assert_eq!(file_a.disambiguated_name(0), "README.md");
assert_eq!(file_a.disambiguated_name(1), "src/README.md");
assert_eq!(file_b.disambiguated_name(1), "docs/README.md");
// Files that still collide at one parent should grow further.
let deep_a = MentionUri::File {
abs_path: PathBuf::from(path!("/a/src/foo.rs")),
};
let deep_b = MentionUri::File {
abs_path: PathBuf::from(path!("/b/src/foo.rs")),
};
assert_eq!(deep_a.disambiguated_name(1), "src/foo.rs");
assert_eq!(deep_b.disambiguated_name(1), "src/foo.rs");
assert_eq!(deep_a.disambiguated_name(2), "a/src/foo.rs");
assert_eq!(deep_b.disambiguated_name(2), "b/src/foo.rs");
// Two skills with the same name — should disambiguate with source
let global_skill = MentionUri::Skill {
name: "create-skill".into(),
source: "".into(),
skill_file_path: PathBuf::from("/global/create-skill/SKILL.md"),
};
let project_skill = MentionUri::Skill {
name: "create-skill".into(),
source: "my-project".into(),
skill_file_path: PathBuf::from("/project/create-skill/SKILL.md"),
};
assert_eq!(global_skill.name(), "create-skill");
assert_eq!(global_skill.disambiguated_name(0), "create-skill");
assert_eq!(global_skill.disambiguated_name(1), "create-skill (global)");
assert_eq!(
project_skill.disambiguated_name(1),
"create-skill (my-project)"
);
// A type without special disambiguation (Thread) — detail has no effect
// (the value is a fixed point so the disambiguation loop terminates).
let thread = MentionUri::Thread {
id: acp::SessionId::new("123"),
name: "My Thread".into(),
};
assert_eq!(thread.disambiguated_name(0), "My Thread");
assert_eq!(thread.disambiguated_name(1), "My Thread");
assert_eq!(thread.disambiguated_name(5), "My Thread");
// Edge case: file at filesystem root has no parent to show
let root_file = MentionUri::File {
abs_path: PathBuf::from(path!("/README.md")),
};
assert_eq!(root_file.disambiguated_name(1), "README.md");
assert_eq!(root_file.disambiguated_name(5), "README.md");
}
}

View file

@ -508,6 +508,7 @@ impl AcpTools {
} else {
CopyButtonVisibility::Hidden
},
wrap_button_visibility: markdown::WrapButtonVisibility::Hidden,
border: false,
},
),

View file

@ -33,12 +33,12 @@ watch.workspace = true
[dev-dependencies]
buffer_diff = { workspace = true, features = ["test-support"] }
git.workspace = true
collections = { workspace = true, features = ["test-support"] }
clock = { workspace = true, features = ["test-support"] }
collections = { workspace = true, features = ["test-support"] }
ctor.workspace = true
git.workspace = true
gpui = { workspace = true, features = ["test-support"] }
indoc.workspace = true
language = { workspace = true, features = ["test-support"] }
log.workspace = true
pretty_assertions.workspace = true

View file

@ -387,6 +387,11 @@ impl ActionLog {
let git_diff_base = git_diff.read(cx).base_text(cx).as_rope().clone();
let buffer_text = tracked_buffer.snapshot.as_rope().clone();
anyhow::Ok(cx.background_spawn(async move {
if buffer_text.len() == git_diff_base.len()
&& buffer_text.chars_at(0).eq(git_diff_base.chars_at(0))
{
return (Arc::<str>::from(git_diff_base.to_string()), git_diff_base);
}
let mut old_unreviewed_edits = old_unreviewed_edits.into_iter().peekable();
let committed_edits = language::line_diff(
&agent_diff_base.to_string(),
@ -931,7 +936,11 @@ impl ActionLog {
let mut undo_buffers = Vec::new();
let mut futures = Vec::new();
for buffer in self.changed_buffers(cx).into_keys() {
for buffer in self
.changed_buffers(cx)
.map(|(buffer, _)| buffer)
.collect::<Vec<_>>()
{
let buffer_ranges = vec![Anchor::min_max_range_for_buffer(
buffer.read(cx).remote_id(),
)];
@ -1018,17 +1027,19 @@ impl ActionLog {
}
/// Returns the set of buffers that contain edits that haven't been reviewed by the user.
pub fn changed_buffers(&self, cx: &App) -> BTreeMap<Entity<Buffer>, Entity<BufferDiff>> {
pub fn changed_buffers(
&self,
cx: &App,
) -> impl Iterator<Item = (Entity<Buffer>, Entity<BufferDiff>)> {
self.tracked_buffers
.iter()
.filter(|(_, tracked)| tracked.has_edits(cx))
.map(|(buffer, tracked)| (buffer.clone(), tracked.diff.clone()))
.collect()
}
/// Returns the total number of lines added and removed across all unreviewed buffers.
pub fn diff_stats(&self, cx: &App) -> DiffStats {
DiffStats::all_files(&self.changed_buffers(cx), cx)
DiffStats::all_files(self.changed_buffers(cx), cx)
}
/// Iterate over buffers changed since last read or edited by the model
@ -1074,7 +1085,7 @@ impl DiffStats {
}
pub fn all_files(
changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
changed_buffers: impl IntoIterator<Item = (Entity<Buffer>, Entity<BufferDiff>)>,
cx: &App,
) -> Self {
let mut total = DiffStats::default();
@ -1320,6 +1331,7 @@ mod tests {
use super::*;
use buffer_diff::DiffHunkStatusKind;
use gpui::TestAppContext;
use indoc::indoc;
use language::Point;
use project::{FakeFs, Fs, Project, RemoveOptions};
use rand::prelude::*;
@ -1328,7 +1340,7 @@ mod tests {
use std::env;
use util::{RandomCharIter, path};
#[ctor::ctor]
#[ctor::ctor(unsafe)]
fn init_logger() {
zlog::init_test();
}
@ -2703,6 +2715,86 @@ mod tests {
assert_eq!(unreviewed_hunks(&action_log, cx), vec![]);
}
#[gpui::test]
async fn test_keep_edits_on_commit_with_shifted_diff_boundaries(cx: &mut TestAppContext) {
init_test(cx);
let initial_text = indoc! {"
use crate::{Alpha, Beta};
fn keep() {
work();
}
fn remove() {
work();
}
fn after() {
work();
}
"};
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/project"),
json!({
".git": {},
"file.rs": initial_text,
}),
)
.await;
fs.set_head_for_repo(
path!("/project/.git").as_ref(),
&[("file.rs", initial_text.into())],
"0000000",
);
cx.run_until_parked();
let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
let action_log = cx.new(|_| ActionLog::new(project.clone()));
let file_path = project
.read_with(cx, |project, cx| {
project.find_project_path(path!("/project/file.rs"), cx)
})
.unwrap();
let buffer = project
.update(cx, |project, cx| project.open_buffer(file_path, cx))
.await
.unwrap();
let final_text = indoc! {"
use crate::{Alpha};
fn keep() {
work();
}
fn after() {
work();
}
"};
cx.update(|cx| {
action_log.update(cx, |log, cx| log.buffer_read(buffer.clone(), cx));
buffer.update(cx, |buffer, cx| {
buffer.set_text(final_text, cx);
});
action_log.update(cx, |log, cx| log.buffer_edited(buffer.clone(), cx));
});
cx.run_until_parked();
assert!(!unreviewed_hunks(&action_log, cx).is_empty());
fs.set_head_for_repo(
path!("/project/.git").as_ref(),
&[("file.rs", final_text.into())],
"0000001",
);
cx.run_until_parked();
assert_eq!(unreviewed_hunks(&action_log, cx), vec![]);
}
/// Regression test: when head_commit updates before the BufferDiff's base
/// text does, an intermediate DiffChanged (e.g. from a buffer-edit diff
/// recalculation) must NOT consume the commit signal. The subscription
@ -3168,21 +3260,21 @@ mod tests {
child_log_1
.read(cx)
.changed_buffers(cx)
.into_keys()
.map(|(buffer, _)| buffer)
.collect()
});
let child_2_changed: Vec<_> = cx.read(|cx| {
child_log_2
.read(cx)
.changed_buffers(cx)
.into_keys()
.map(|(buffer, _)| buffer)
.collect()
});
let parent_changed: Vec<_> = cx.read(|cx| {
parent_log
.read(cx)
.changed_buffers(cx)
.into_keys()
.map(|(buffer, _)| buffer)
.collect()
});
@ -3408,7 +3500,6 @@ mod tests {
action_log
.read(cx)
.changed_buffers(cx)
.into_iter()
.map(|(buffer, diff)| {
let snapshot = buffer.read(cx).snapshot();
(

View file

@ -377,7 +377,7 @@ impl ActivityIndicator {
return Some(Content {
icon: ActivityIcon::LoadingSpinner,
message,
on_click: Some(Arc::new(Self::toggle_language_server_work_context_menu)),
on_click: None,
tooltip_message: None,
});
}
@ -639,14 +639,6 @@ impl ActivityIndicator {
None
}
fn toggle_language_server_work_context_menu(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.context_menu_handle.toggle(window, cx);
}
}
impl EventEmitter<Event> for ActivityIndicator {}
@ -659,15 +651,16 @@ impl Render for ActivityIndicator {
.id("activity-indicator")
.on_action(cx.listener(Self::show_error_message))
.on_action(cx.listener(Self::dismiss_message));
let Some(content) = self.content_to_render(cx) else {
return result;
};
let activity_indicator = cx.entity().downgrade();
let truncate_content = content.message.len() > MAX_MESSAGE_LEN;
let has_click_handler = content.on_click.is_some();
result.gap_2().child(
result.child(
PopoverMenu::new("activity-indicator-popover")
.trigger(
Button::new("activity-indicator-trigger", {
@ -705,10 +698,9 @@ impl Render for ActivityIndicator {
.when(!has_click_handler, |this| {
this.menu(move |window, cx| {
let strong_this = activity_indicator.upgrade()?;
let mut has_work = false;
let mut has_cancellable_work = false;
let menu = ContextMenu::build(window, cx, |mut menu, _, cx| {
for work in strong_this.read(cx).pending_language_server_work(cx) {
has_work = true;
let activity_indicator = activity_indicator.clone();
let mut title = work
.progress
@ -717,16 +709,21 @@ impl Render for ActivityIndicator {
.unwrap_or(work.progress_token.to_string());
if work.progress.is_cancellable {
has_cancellable_work = true;
let language_server_id = work.language_server_id;
let token = work.progress_token.clone();
let title = SharedString::from(title);
let title = SharedString::from(format!("Cancel {title}"));
menu = menu.custom_entry(
move |_, _| {
h_flex()
.w_full()
.justify_between()
.gap_1()
.child(
Icon::new(IconName::Close)
.color(Color::Muted)
.size(IconSize::Small),
)
.child(Label::new(title.clone()))
.child(Icon::new(IconName::XCircle))
.into_any_element()
},
move |_, cx| {
@ -760,7 +757,7 @@ impl Render for ActivityIndicator {
}
menu
});
has_work.then_some(menu)
has_cancellable_work.then_some(menu)
})
}),
)

View file

@ -10,6 +10,7 @@ mod thread;
mod thread_store;
mod tool_permissions;
mod tools;
mod user_agents_md;
use context_server::ContextServerId;
pub use db::*;
@ -22,6 +23,7 @@ pub use thread::*;
pub use thread_store::*;
pub use tool_permissions::*;
pub use tools::*;
pub use user_agents_md::{UserAgentsMd, UserAgentsMdState, init as init_user_agents_md};
use acp_thread::{
AcpThread, AgentModelSelector, AgentSessionInfo, AgentSessionList, AgentSessionListRequest,
@ -29,13 +31,14 @@ use acp_thread::{
};
use agent_client_protocol::schema as acp;
use agent_skills::{
MAX_SKILL_DESCRIPTIONS_SIZE, Skill, SkillLoadError, SkillScopeId, SkillSource, SkillSummary,
global_skills_dir, load_skills_from_directory, project_skills_relative_path,
MAX_SKILL_DESCRIPTIONS_SIZE, ProjectSkillGroup, Skill, SkillIndex, SkillLoadError,
SkillScopeId, SkillSource, SkillSummary, builtin_skills, global_skills_dir,
load_skills_from_directory, project_skills_relative_path,
};
use anyhow::{Context as _, Result, anyhow};
use chrono::{DateTime, Utc};
use collections::{HashMap, HashSet, IndexMap};
use feature_flags::{FeatureFlagAppExt as _, SkillsFeatureFlag};
use fs::Fs;
use futures::channel::{mpsc, oneshot};
use futures::future::Shared;
@ -89,6 +92,25 @@ pub struct SkillLoadingErrorsUpdated {
pub errors: Vec<SkillLoadingError>,
}
#[derive(Clone, Debug)]
pub struct NativeAvailableSkill {
pub name: String,
pub description: String,
pub source: SharedString,
pub skill_file_path: PathBuf,
}
impl From<&Skill> for NativeAvailableSkill {
fn from(skill: &Skill) -> Self {
Self {
name: skill.name.clone(),
description: skill.description.clone(),
source: skill.source.display_label().to_string().into(),
skill_file_path: skill.skill_file_path.clone(),
}
}
}
struct ProjectState {
project: Entity<Project>,
project_context: Entity<ProjectContext>,
@ -348,6 +370,10 @@ impl NativeAgent {
subscriptions.push(cx.subscribe(prompt_store, Self::handle_prompts_updated_event))
}
if !cx.has_global::<SkillIndex>() {
cx.set_global(SkillIndex::default());
}
Self {
sessions: HashMap::default(),
pending_sessions: HashMap::default(),
@ -366,11 +392,11 @@ impl NativeAgent {
/// Kicks off a one-time scan of the global skills directory if one
/// isn't already in progress and a watch isn't already active.
///
/// Idempotent and cheap: returns immediately if the user lacks the
/// skills feature flag, or if a scan or watch is already running.
/// The expected callers are user-interaction events from the agent
/// panel (input focus, slash autocomplete, conversation submit);
/// firing this from any of them is equivalent and safe to repeat.
/// Idempotent and cheap: returns immediately if a scan or watch is
/// already running. The expected callers are user-interaction events
/// from the agent panel (input focus, slash autocomplete, conversation
/// submit); firing this from any of them is equivalent and safe to
/// repeat.
///
/// The scan itself runs detached on the foreground executor. If
/// `~/.agents/skills/` exists it transitions state to
@ -379,9 +405,6 @@ impl NativeAgent {
/// next trigger retries (covering the case where the user creates
/// the directory after the first scan).
pub fn ensure_skills_scan_started(&mut self, cx: &mut Context<Self>) {
if !cx.has_flag::<SkillsFeatureFlag>() {
return;
}
if !matches!(self.skills_state, SkillsState::Idle) {
return;
}
@ -572,12 +595,10 @@ impl NativeAgent {
// after the thread is constructed are still visible to the
// model — without this, the catalog and tool would drift out
// of sync until the session was reopened.
if cx.has_flag::<SkillsFeatureFlag>() {
thread.add_tool(SkillTool::new(
skills_resolver_for_project(weak.clone(), project_id),
self.fs.clone(),
));
}
thread.add_tool(SkillTool::new(
skills_resolver_for_project(weak.clone(), project_id),
self.fs.clone(),
));
});
let subscriptions = vec![
@ -775,6 +796,7 @@ impl NativeAgent {
// the available commands) can change without affecting the
// skill error list.
this.update_available_commands_for_project(project_id, cx);
this.publish_skill_index(cx);
})?;
}
@ -795,12 +817,8 @@ impl NativeAgent {
})
.collect::<Vec<_>>();
// Skills are gated behind the "skills" feature flag. Without it we
// skip all on-disk lookups so users see no behavior change.
let skills_enabled = cx.has_flag::<SkillsFeatureFlag>();
// Load global skills
let global_skills_task = if skills_enabled {
let global_skills_task = {
let global_skills_dir = global_skills_dir();
let global_skills_fs = fs.clone();
cx.background_spawn(async move {
@ -811,8 +829,6 @@ impl NativeAgent {
)
.await
})
} else {
Task::ready(Vec::new())
};
// Load project-local skills, but only from worktrees the user has
@ -825,7 +841,7 @@ impl NativeAgent {
// worktrees pick up their skills without restarting.
let trusted_worktrees = TrustedWorktrees::try_get_global(cx);
let worktree_store = project.read(cx).worktree_store();
let project_skills_task = if skills_enabled {
let project_skills_task = {
let project_skills_futures: Vec<
futures::future::BoxFuture<'static, Vec<Result<Skill, SkillLoadError>>>,
> = worktrees
@ -870,8 +886,6 @@ impl NativeAgent {
})
.collect();
cx.background_spawn(async move { future::join_all(project_skills_futures).await })
} else {
Task::ready(Vec::new())
};
let default_user_rules_task = if let Some(prompt_store) = prompt_store.as_ref() {
prompt_store.read_with(cx, |prompt_store, cx| {
@ -1080,7 +1094,7 @@ impl NativeAgent {
&mut self,
project: Entity<Project>,
event: &project::Event,
cx: &mut Context<Self>,
_cx: &mut Context<Self>,
) {
let project_id = project.entity_id();
let Some(state) = self.projects.get_mut(&project_id) else {
@ -1091,16 +1105,14 @@ impl NativeAgent {
state.project_context_needs_refresh.send(()).ok();
}
project::Event::WorktreeUpdatedEntries(_, items) => {
let skills_enabled = cx.has_flag::<SkillsFeatureFlag>();
if items.iter().any(|(path, _, _)| {
let path_ref = path.as_ref();
RULES_FILE_REL_PATHS
.iter()
.any(|rules_path| path_ref == rules_path.as_ref())
|| (skills_enabled
&& SKILLS_PREFIX
.as_ref()
.is_some_and(|prefix| path_ref.starts_with(prefix)))
|| SKILLS_PREFIX
.as_ref()
.is_some_and(|prefix| path_ref.starts_with(prefix))
}) {
state.project_context_needs_refresh.send(()).ok();
}
@ -1192,6 +1204,50 @@ impl NativeAgent {
}
}
fn publish_skill_index(&self, cx: &mut Context<Self>) {
let mut global_skills = Vec::new();
let mut project_groups: Vec<ProjectSkillGroup> = Vec::new();
let mut seen_global = false;
for state in self.projects.values() {
for skill in state.skills.iter() {
match &skill.source {
SkillSource::BuiltIn => {}
SkillSource::Global => {
if !seen_global {
global_skills.push(skill.clone());
}
}
SkillSource::ProjectLocal {
worktree_id,
worktree_root_name,
} => {
if let Some(group) = project_groups
.iter_mut()
.find(|g| g.worktree_id == *worktree_id)
{
group.skills.push(skill.clone());
} else {
project_groups.push(ProjectSkillGroup {
worktree_id: *worktree_id,
worktree_root_name: SharedString::from(worktree_root_name.clone()),
skills: vec![skill.clone()],
});
}
}
}
}
if !global_skills.is_empty() {
seen_global = true;
}
}
cx.set_global(SkillIndex {
global_skills,
project_skills: project_groups,
});
}
fn update_available_commands_for_project(&self, project_id: EntityId, cx: &mut Context<Self>) {
let available_commands =
Self::build_available_commands_for_project(self.projects.get(&project_id), cx);
@ -1264,21 +1320,7 @@ impl NativeAgent {
Some(command)
});
// Skills are exposed as slash commands regardless of
// `disable_model_invocation`. The flag controls catalog visibility
// for the model, not user-driven invocation — that's the whole
// point of marking a skill model-disabled.
let skill_commands = state.skills.iter().map(|skill| {
// The meta carries the literal scope prefix the popup
// inserts as `/<prefix>:<name>`: empty for globals (so
// the inserted text is `/:<name>`) and the worktree root
// name for project-locals. See `SkillSource::scope_prefix`.
acp::AvailableCommand::new(skill.name.clone(), skill.description.clone()).meta(
acp_thread::meta_with_skill_source(skill.source.scope_prefix()),
)
});
mcp_commands.chain(skill_commands).collect()
mcp_commands.collect()
}
pub fn load_thread(
@ -1443,6 +1485,7 @@ impl NativeAgent {
let has_remaining = self.sessions.values().any(|s| s.project_id == project_id);
if !has_remaining {
self.projects.remove(&project_id);
self.publish_skill_index(cx);
}
session.pending_save
@ -1637,14 +1680,18 @@ impl NativeAgent {
// Read the body on demand here — bodies live on disk between
// materializations to keep memory cost O(total frontmatter)
// rather than O(total file size).
let body = agent_skills::read_skill_body(fs.as_ref(), &skill.skill_file_path)
.await
.with_context(|| {
format!(
"Failed to read skill body from {}",
skill.skill_file_path.display()
)
})?;
let body = if let Some(embedded) = skill.embedded_body {
embedded.to_string()
} else {
agent_skills::read_skill_body(fs.as_ref(), &skill.skill_file_path)
.await
.with_context(|| {
format!(
"Failed to read skill body from {}",
skill.skill_file_path.display()
)
})?
};
let envelope = crate::tools::render_skill_envelope(&skill, &body);
let envelope_block = acp::ContentBlock::Text(acp::TextContent::new(envelope));
@ -1719,6 +1766,34 @@ impl NativeAgentConnection {
.update(cx, |agent, cx| agent.ensure_skills_scan_started(cx));
}
pub fn refresh_skills_for_project(&self, project: Entity<Project>, cx: &mut App) {
self.0.update(cx, |agent, cx| {
let project_id = agent.get_or_create_project_state(&project, cx);
agent.ensure_skills_scan_started(cx);
if let Some(state) = agent.projects.get_mut(&project_id) {
state.project_context_needs_refresh.send(()).ok();
}
});
}
pub fn available_skills(
&self,
session_id: &acp::SessionId,
cx: &App,
) -> Vec<NativeAvailableSkill> {
self.0
.read(cx)
.session_project_state(session_id)
.map(|state| {
state
.skills
.iter()
.map(NativeAvailableSkill::from)
.collect()
})
.unwrap_or_default()
}
pub fn load_thread(
&self,
id: acp::SessionId,
@ -1769,10 +1844,10 @@ impl NativeAgentConnection {
match event {
ThreadEvent::UserMessage(message) => {
acp_thread.update(cx, |thread, cx| {
for content in message.content {
for content in &*message.content {
thread.push_user_content_block(
Some(message.id.clone()),
content.into(),
content.clone().into(),
cx,
);
}
@ -2220,9 +2295,12 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
// we don't clone the entire skill list on every prompt
// (including prompts like `/help` that aren't skills at
// all). The resolution rule matches the override-applied
// view: prefer a project-local with the matching name,
// falling back to a global, so the slash command picks the
// same entry the model sees in its catalog.
// view: among skills with the matching name, pick the one
// with the highest source precedence, so the slash command
// picks the same entry the model sees in its catalog.
// Ties (e.g. two project-local skills from different
// worktrees) resolve to the first in iteration order to
// match `apply_skill_overrides`.
if parsed_command.explicit_server_id.is_none()
&& parsed_command.skill_scope.is_none()
&& !project_state.skills.is_empty()
@ -2231,15 +2309,13 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
let resolved = project_state
.skills
.iter()
.find(|skill| {
skill.name == prompt_name
&& matches!(skill.source, SkillSource::ProjectLocal { .. })
})
.or_else(|| {
project_state
.skills
.iter()
.find(|skill| skill.name == prompt_name)
.filter(|skill| skill.name == prompt_name)
.reduce(|best, candidate| {
if candidate.source.precedence() > best.source.precedence() {
candidate
} else {
best
}
});
if let Some(skill) = resolved {
let skill = skill.clone();
@ -2403,7 +2479,7 @@ impl AgentSessionList for NativeAgentSessionList {
Task::ready(Ok(AgentSessionListResponse::new(sessions)))
}
fn supports_delete(&self) -> bool {
fn supports_delete(&self, _cx: &App) -> bool {
true
}
@ -2935,7 +3011,9 @@ fn combine_skills(
global: Vec<Result<Skill, SkillLoadError>>,
project: impl Iterator<Item = Result<Skill, SkillLoadError>>,
) -> (Vec<Skill>, Vec<SkillLoadError>) {
let mut skills = Vec::new();
// Built-in skills go first (lowest priority) so that global and
// project-local skills with the same name shadow them.
let mut skills = builtin_skills();
let mut errors = Vec::new();
for result in global.into_iter().chain(project) {
match result {
@ -2954,17 +3032,16 @@ fn log_skill_conflicts(skills: &[Skill]) {
let mut by_name: HashMap<&str, &Skill> = HashMap::default();
for skill in skills {
match by_name.get(skill.name.as_str()) {
Some(existing) => match (&existing.source, &skill.source) {
(SkillSource::Global, SkillSource::ProjectLocal { .. }) => {
Some(existing) => {
if skill.source.precedence() > existing.source.precedence() {
log::warn!(
"Project skill '{}' at '{}' overrides global skill at '{}' for the model; both appear in the slash-command popup with their source",
"Skill '{}' at '{}' overrides skill at '{}' for the model; both appear in the slash-command popup with their source",
skill.name,
skill.skill_file_path.display(),
existing.skill_file_path.display(),
);
by_name.insert(skill.name.as_str(), skill);
}
_ => {
} else {
log::warn!(
"Skill '{}' at '{}' conflicts with skill at '{}'; the model will see the first one, but both appear in the slash-command popup with their source",
skill.name,
@ -2972,7 +3049,7 @@ fn log_skill_conflicts(skills: &[Skill]) {
existing.skill_file_path.display(),
);
}
},
}
None => {
by_name.insert(skill.name.as_str(), skill);
}
@ -2999,9 +3076,7 @@ fn apply_skill_overrides(skills: &[Skill]) -> Vec<Skill> {
for skill in skills {
match indices.get(skill.name.as_str()).copied() {
Some(idx) => {
if matches!(result[idx].source, SkillSource::Global)
&& matches!(skill.source, SkillSource::ProjectLocal { .. })
{
if skill.source.precedence() > result[idx].source.precedence() {
result[idx] = skill.clone();
}
}
@ -3039,6 +3114,7 @@ mod internal_tests {
directory_path: PathBuf::from(format!("/home/user/.agents/skills/{name}")),
skill_file_path: PathBuf::from(format!("/home/user/.agents/skills/{name}/SKILL.md")),
disable_model_invocation: false,
embedded_body: None,
}
}
@ -3053,9 +3129,30 @@ mod internal_tests {
directory_path: PathBuf::from(format!("/{worktree}/.agents/skills/{name}")),
skill_file_path: PathBuf::from(format!("/{worktree}/.agents/skills/{name}/SKILL.md")),
disable_model_invocation: false,
embedded_body: None,
}
}
fn make_builtin_skill(name: &str, description: &str) -> Skill {
Skill {
name: name.to_string(),
description: description.to_string(),
source: SkillSource::BuiltIn,
directory_path: PathBuf::from(format!("/builtin/{name}")),
skill_file_path: PathBuf::from(format!("/builtin/{name}/SKILL.md")),
disable_model_invocation: false,
embedded_body: Some("built-in body"),
}
}
/// Filter to only user-defined (non-built-in) skills for test assertions.
fn user_skills(skills: &[Skill]) -> Vec<&Skill> {
skills
.iter()
.filter(|s| !matches!(s.source, SkillSource::BuiltIn))
.collect()
}
#[test]
fn test_combine_skills_keeps_every_entry_for_autocomplete() {
// The autocomplete popup needs both same-named entries so the
@ -3067,9 +3164,10 @@ mod internal_tests {
let (skills, errors) = combine_skills(vec![Ok(global)], vec![Ok(project)].into_iter());
assert!(errors.is_empty());
assert_eq!(skills.len(), 2);
assert!(matches!(skills[0].source, SkillSource::Global));
assert!(matches!(skills[1].source, SkillSource::ProjectLocal { .. }));
let user = user_skills(&skills);
assert_eq!(user.len(), 2);
assert!(matches!(user[0].source, SkillSource::Global));
assert!(matches!(user[1].source, SkillSource::ProjectLocal { .. }));
}
#[test]
@ -3105,6 +3203,51 @@ mod internal_tests {
assert_eq!(resolved[0].description, "First");
}
#[test]
fn test_apply_skill_overrides_global_wins_over_builtin() {
// A global skill with the same name as a built-in must shadow
// the built-in in the model-facing projection, regardless of
// iteration order.
let built_in = make_builtin_skill("create-skill", "Built-in version");
let global = make_global_skill("create-skill", "User override");
let resolved = apply_skill_overrides(&[built_in, global]);
assert_eq!(resolved.len(), 1);
assert_eq!(resolved[0].description, "User override");
assert!(matches!(resolved[0].source, SkillSource::Global));
}
#[test]
fn test_apply_skill_overrides_project_wins_over_builtin() {
let built_in = make_builtin_skill("create-skill", "Built-in version");
let project = make_project_skill("create-skill", "Project override", "my-project");
let resolved = apply_skill_overrides(&[built_in, project]);
assert_eq!(resolved.len(), 1);
assert_eq!(resolved[0].description, "Project override");
assert!(matches!(
resolved[0].source,
SkillSource::ProjectLocal { .. }
));
}
#[test]
fn test_apply_skill_overrides_project_wins_over_builtin_and_global() {
// All three sources present — the project-local must win and
// both lower-precedence entries must be dropped from the
// model-facing projection.
let built_in = make_builtin_skill("create-skill", "Built-in");
let global = make_global_skill("create-skill", "Global");
let project = make_project_skill("create-skill", "Project", "my-project");
let resolved = apply_skill_overrides(&[built_in, global, project]);
assert_eq!(resolved.len(), 1);
assert_eq!(resolved[0].description, "Project");
}
#[test]
fn test_apply_skill_overrides_preserves_unique_skills() {
let global_a = make_global_skill("alpha", "a");
@ -3176,6 +3319,7 @@ mod internal_tests {
directory_path: PathBuf::from(format!("/skills/{name}")),
skill_file_path: PathBuf::from(format!("/skills/{name}/SKILL.md")),
disable_model_invocation: false,
embedded_body: None,
});
}
@ -3250,6 +3394,7 @@ mod internal_tests {
directory_path: PathBuf::from("/skills/skill-01-first"),
skill_file_path: PathBuf::from("/skills/skill-01-first/SKILL.md"),
disable_model_invocation: false,
embedded_body: None,
};
let second = Skill {
name: "skill-02-overflows".to_string(),
@ -3258,6 +3403,7 @@ mod internal_tests {
directory_path: PathBuf::from("/skills/skill-02-overflows"),
skill_file_path: PathBuf::from("/skills/skill-02-overflows/SKILL.md"),
disable_model_invocation: false,
embedded_body: None,
};
let third = Skill {
name: "skill-03-would-fit".to_string(),
@ -3266,6 +3412,7 @@ mod internal_tests {
directory_path: PathBuf::from("/skills/skill-03-would-fit"),
skill_file_path: PathBuf::from("/skills/skill-03-would-fit/SKILL.md"),
disable_model_invocation: false,
embedded_body: None,
};
// Sanity-check the test setup: the third skill is small enough
@ -3321,6 +3468,7 @@ mod internal_tests {
directory_path: PathBuf::from("/skills/hidden-huge"),
skill_file_path: PathBuf::from("/skills/hidden-huge/SKILL.md"),
disable_model_invocation: true,
embedded_body: None,
};
let visible = Skill {
name: "visible".to_string(),
@ -3329,6 +3477,7 @@ mod internal_tests {
directory_path: PathBuf::from("/skills/visible"),
skill_file_path: PathBuf::from("/skills/visible/SKILL.md"),
disable_model_invocation: false,
embedded_body: None,
};
let (kept, errors) = select_catalog_skills(&[hidden, visible]);
@ -3429,9 +3578,6 @@ mod internal_tests {
#[gpui::test]
async fn test_global_skills_load_and_reload(cx: &mut TestAppContext) {
init_test(cx);
cx.update(|cx| {
cx.update_flags(true, vec!["skills".to_string()]);
});
let fs = FakeFs::new(cx.executor());
let skills_dir = global_skills_dir();
let initial_skill_dir = skills_dir.join("my-skill");
@ -3471,9 +3617,10 @@ mod internal_tests {
// The pre-existing skill should be loaded into the project state.
agent.read_with(cx, |agent, _cx| {
let state = agent.projects.get(&project.entity_id()).unwrap();
assert_eq!(state.skills.len(), 1);
assert_eq!(state.skills[0].name, "my-skill");
assert_eq!(state.skills[0].description, "First version");
let user = user_skills(&state.skills);
assert_eq!(user.len(), 1);
assert_eq!(user[0].name, "my-skill");
assert_eq!(user[0].description, "First version");
});
// Modify the SKILL.md and verify the project context refreshes.
@ -3487,17 +3634,15 @@ mod internal_tests {
agent.read_with(cx, |agent, _cx| {
let state = agent.projects.get(&project.entity_id()).unwrap();
assert_eq!(state.skills.len(), 1);
assert_eq!(state.skills[0].description, "Second version");
let user = user_skills(&state.skills);
assert_eq!(user.len(), 1);
assert_eq!(user[0].description, "Second version");
});
}
#[gpui::test]
async fn test_global_skills_dir_created_after_startup(cx: &mut TestAppContext) {
init_test(cx);
cx.update(|cx| {
cx.update_flags(true, vec!["skills".to_string()]);
});
let fs = FakeFs::new(cx.executor());
let skills_dir = global_skills_dir();
@ -3534,8 +3679,8 @@ mod internal_tests {
agent.read_with(cx, |agent, _cx| {
let state = agent.projects.get(&project.entity_id()).unwrap();
assert!(
state.skills.is_empty(),
"expected no skills before the global skills dir exists, got {:?}",
user_skills(&state.skills).is_empty(),
"expected no user skills before the global skills dir exists, got {:?}",
state.skills
);
});
@ -3560,9 +3705,10 @@ mod internal_tests {
agent.read_with(cx, |agent, _cx| {
let state = agent.projects.get(&project.entity_id()).unwrap();
assert_eq!(state.skills.len(), 1);
assert_eq!(state.skills[0].name, "late-skill");
assert_eq!(state.skills[0].description, "Created after startup");
let user = user_skills(&state.skills);
assert_eq!(user.len(), 1);
assert_eq!(user[0].name, "late-skill");
assert_eq!(user[0].description, "Created after startup");
});
}
@ -3578,9 +3724,6 @@ mod internal_tests {
#[gpui::test]
async fn test_skills_added_after_session_visible_to_skill_tool(cx: &mut TestAppContext) {
init_test(cx);
cx.update(|cx| {
cx.update_flags(true, vec!["skills".to_string()]);
});
let fs = FakeFs::new(cx.executor());
let skills_dir = global_skills_dir();
@ -3613,8 +3756,8 @@ mod internal_tests {
agent.read_with(cx, |agent, _cx| {
let state = agent.projects.get(&project_id).unwrap();
assert!(
state.skills.is_empty(),
"expected no skills before the global skills dir exists, got {:?}",
user_skills(&state.skills).is_empty(),
"expected no user skills before the global skills dir exists, got {:?}",
state.skills
);
});
@ -3631,7 +3774,12 @@ mod internal_tests {
// empty list — NOT the snapshot that `Thread::new` would have
// captured.
cx.update(|cx| {
assert!(resolve(cx).is_empty());
let all = resolve(cx);
let user: Vec<_> = all
.iter()
.filter(|s| !matches!(s.source, SkillSource::BuiltIn))
.collect();
assert!(user.is_empty());
});
// Now create a SKILL.md AFTER the session was registered. With
@ -3656,15 +3804,20 @@ mod internal_tests {
// `state.skills` reflects the new skill (the watcher ran).
agent.read_with(cx, |agent, _cx| {
let state = agent.projects.get(&project_id).unwrap();
assert_eq!(state.skills.len(), 1);
assert_eq!(state.skills[0].name, "my-skill");
let user = user_skills(&state.skills);
assert_eq!(user.len(), 1);
assert_eq!(user[0].name, "my-skill");
});
// The resolver the `SkillTool` uses must see it too. This is the
// crux of the regression test: the tool's view of skills is
// resolved at invocation time, not at thread-construction time.
cx.update(|cx| {
let snapshot = resolve(cx);
let all = resolve(cx);
let snapshot: Vec<_> = all
.iter()
.filter(|s| !matches!(s.source, SkillSource::BuiltIn))
.collect();
assert_eq!(
snapshot.len(),
1,
@ -3712,9 +3865,6 @@ mod internal_tests {
#[gpui::test]
async fn test_subagent_skills_lookup_matches_parent(cx: &mut TestAppContext) {
init_test(cx);
cx.update(|cx| {
cx.update_flags(true, vec!["skills".to_string()]);
});
let fs = FakeFs::new(cx.executor());
let skills_dir = global_skills_dir();
let skill_dir = skills_dir.join("shared-skill");
@ -3752,7 +3902,11 @@ mod internal_tests {
let parent_resolve =
cx.update(|_cx| super::skills_resolver_for_project(agent.downgrade(), project_id));
cx.update(|cx| {
let parent_skills = parent_resolve(cx);
let all = parent_resolve(cx);
let parent_skills: Vec<_> = all
.iter()
.filter(|s| !matches!(s.source, SkillSource::BuiltIn))
.collect();
assert_eq!(parent_skills.len(), 1);
assert_eq!(parent_skills[0].name, "shared-skill");
});
@ -3798,24 +3952,25 @@ mod internal_tests {
let subagent_resolve = cx
.update(|_cx| super::skills_resolver_for_project(agent.downgrade(), parent_project_id));
cx.update(|cx| {
let subagent_skills = subagent_resolve(cx);
let all = subagent_resolve(cx);
let subagent_skills: Vec<_> = all
.iter()
.filter(|s| !matches!(s.source, SkillSource::BuiltIn))
.collect();
assert_eq!(subagent_skills.len(), 1);
assert_eq!(subagent_skills[0].name, "shared-skill");
});
}
#[gpui::test]
async fn test_skills_appear_as_slash_commands(cx: &mut TestAppContext) {
async fn test_skills_appear_as_available_skills(cx: &mut TestAppContext) {
init_test(cx);
cx.update(|cx| {
cx.update_flags(true, vec!["skills".to_string()]);
});
let fs = FakeFs::new(cx.executor());
let skills_dir = global_skills_dir();
// Two skills: one model-invocable (default), one slash-only via
// `disable-model-invocation: true`. Both should still appear as
// slash commands.
// `disable-model-invocation: true`. Both should still appear in
// the slash menu as first-class skills.
let visible_dir = skills_dir.join("visible-skill");
fs.create_dir(&visible_dir).await.unwrap();
fs.insert_file(
@ -3839,9 +3994,9 @@ mod internal_tests {
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
let connection = NativeAgentConnection(agent.clone());
let _acp_thread = cx
let acp_thread = cx
.update(|cx| {
Rc::new(connection).new_session(
Rc::new(connection.clone()).new_session(
project.clone(),
PathList::new(&[Path::new("/")]),
cx,
@ -3852,21 +4007,34 @@ mod internal_tests {
cx.run_until_parked();
let project_id = project.entity_id();
let session_id = acp_thread.read_with(cx, |thread, _cx| thread.session_id().clone());
// Both skills should be exposed as slash commands.
agent.read_with(cx, |agent, cx| {
let commands = NativeAgent::build_available_commands_for_project(
agent.projects.get(&project_id),
cx,
);
let names: Vec<&str> = commands.iter().map(|c| c.name.as_str()).collect();
assert!(
!names.contains(&"visible-skill"),
"skills should not be exposed as ACP slash commands: {names:?}"
);
assert!(
!names.contains(&"deploy"),
"slash-only skills should not be exposed as ACP slash commands: {names:?}"
);
});
cx.update(|cx| {
let skills = connection.available_skills(&session_id, cx);
let names: Vec<&str> = skills.iter().map(|skill| skill.name.as_str()).collect();
assert!(
names.contains(&"visible-skill"),
"visible skill missing from slash commands: {names:?}"
"visible skill missing from available skills: {names:?}"
);
assert!(
names.contains(&"deploy"),
"slash-only skill missing from slash commands: {names:?}"
"slash-only skill missing from available skills: {names:?}"
);
});
@ -3881,7 +4049,14 @@ mod internal_tests {
.iter()
.map(|s| s.name.as_str())
.collect();
assert_eq!(catalog, vec!["visible-skill"]);
assert!(
catalog.contains(&"visible-skill"),
"visible skill missing from catalog: {catalog:?}"
);
assert!(
!catalog.contains(&"deploy"),
"deploy should be excluded from catalog: {catalog:?}"
);
});
}
@ -3892,7 +4067,6 @@ mod internal_tests {
init_test(cx);
cx.update(|cx| {
cx.update_flags(true, vec!["skills".to_string()]);
// The trust global isn't created by `init_test`. We need it
// for `Project::test_with_worktree_trust` to actually wire up
// trust tracking and for our subscription in
@ -3925,9 +4099,9 @@ mod internal_tests {
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
let connection = NativeAgentConnection(agent.clone());
let _acp_thread = cx
let acp_thread = cx
.update(|cx| {
Rc::new(connection).new_session(
Rc::new(connection.clone()).new_session(
project.clone(),
PathList::new(&[Path::new("/project")]),
cx,
@ -3938,6 +4112,7 @@ mod internal_tests {
cx.run_until_parked();
let project_id = project.entity_id();
let session_id = acp_thread.read_with(cx, |thread, _cx| thread.session_id().clone());
let worktree_id = project.read_with(cx, |project, cx| {
project.worktrees(cx).next().unwrap().read(cx).id()
});
@ -3947,7 +4122,7 @@ mod internal_tests {
agent.read_with(cx, |agent, cx| {
let state = agent.projects.get(&project_id).unwrap();
assert!(
state.skills.is_empty(),
user_skills(&state.skills).is_empty(),
"untrusted worktree skills should not load: {:?}",
state
.skills
@ -3978,15 +4153,19 @@ mod internal_tests {
});
cx.run_until_parked();
agent.read_with(cx, |agent, cx| {
agent.read_with(cx, |agent, _cx| {
let state = agent.projects.get(&project_id).unwrap();
let names: Vec<&str> = state.skills.iter().map(|s| s.name.as_str()).collect();
let user = user_skills(&state.skills);
let names: Vec<&str> = user.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names, vec!["my-skill"]);
let commands = NativeAgent::build_available_commands_for_project(Some(state), cx);
let command_names: Vec<&str> = commands.iter().map(|c| c.name.as_str()).collect();
});
cx.update(|cx| {
let skills = connection.available_skills(&session_id, cx);
let skill_names: Vec<&str> = skills.iter().map(|s| s.name.as_str()).collect();
assert!(
command_names.contains(&"my-skill"),
"trusted skill should appear in slash commands: {command_names:?}"
skill_names.contains(&"my-skill"),
"trusted skill should appear in available skills: {skill_names:?}"
);
});
}

View file

@ -53,7 +53,7 @@ impl From<&DbThreadMetadata> for acp_thread::AgentSessionInfo {
#[derive(Debug, Serialize, Deserialize)]
pub struct DbThread {
pub title: SharedString,
pub messages: Vec<DbMessage>,
pub messages: Vec<Arc<DbMessage>>,
pub updated_at: DateTime<Utc>,
#[serde(default)]
pub detailed_summary: Option<SharedString>,
@ -92,7 +92,7 @@ pub struct SerializedScrollPosition {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SharedThread {
pub title: SharedString,
pub messages: Vec<DbMessage>,
pub messages: Vec<Arc<DbMessage>>,
pub updated_at: DateTime<Utc>,
#[serde(default)]
pub model: Option<DbLanguageModel>,
@ -206,7 +206,7 @@ impl DbThread {
crate::Message::User(UserMessage {
// MessageId from old format can't be meaningfully converted, so generate a new one
id,
content,
content: Arc::from(content),
})
}
language_model::Role::Assistant => {
@ -285,7 +285,7 @@ impl DbThread {
}
};
messages.push(message);
messages.push(Arc::new(message));
}
Ok(Self {

View file

@ -11,10 +11,15 @@ pub const AUTO_OUTLINE_SIZE: usize = 16384;
/// Result of getting buffer content, which can be either full content or an outline.
pub struct BufferContent {
/// The actual content (either full text or outline)
/// The actual content (either full text, a symbol outline, or a
/// truncated fallback — see `is_synthetic`).
pub text: String,
/// Whether this is an outline (true) or full content (false)
pub is_outline: bool,
/// `true` when `text` is not the file's full content — either a symbol
/// outline or the truncated first-1KB fallback used when no outline is
/// available. Callers that prefix line numbers to file content must
/// skip prefixing in this case, because line numbers in `text` would
/// not correspond to the file's real line numbers.
pub is_synthetic: bool,
}
/// Returns either the full content of a buffer or its outline, depending on size.
@ -44,7 +49,10 @@ pub async fn get_buffer_content_or_outline(
.collect::<Vec<_>>()
});
// If no outline exists, fall back to first 1KB so the agent has some context
// If no outline exists, fall back to first 1KB so the agent has some context.
// This is reported as `is_synthetic: true` because the returned text is not
// the file's full content — it has a synthetic header and is truncated — so
// callers must not attach real-file line numbers to it.
if outline_items.is_empty() {
let text = buffer.read_with(cx, |buffer, _| {
let snapshot = buffer.snapshot();
@ -59,7 +67,7 @@ pub async fn get_buffer_content_or_outline(
return Ok(BufferContent {
text,
is_outline: false,
is_synthetic: true,
});
}
@ -72,14 +80,14 @@ pub async fn get_buffer_content_or_outline(
};
Ok(BufferContent {
text,
is_outline: true,
is_synthetic: true,
})
} else {
// File is small enough, return full content
let text = buffer.read_with(cx, |buffer, _| buffer.text());
Ok(BufferContent {
text,
is_outline: false,
is_synthetic: false,
})
}
}
@ -196,10 +204,13 @@ mod tests {
"Result did not contain content subset"
);
// Should be marked as not an outline (it's truncated content)
// Should be marked synthetic: the returned text is not the file's full
// content (it's a truncated first-1KB fallback with a synthetic header), so
// callers must treat it the same as the symbol-outline case and not attach
// real-file line numbers to it.
assert!(
!result.is_outline,
"Large file without outline should not be marked as outline"
result.is_synthetic,
"Truncated fallback should be reported as synthetic so callers skip line numbering"
);
// Should be reasonably sized (much smaller than original)

View file

@ -40,6 +40,9 @@ pub struct SystemPromptTemplate<'a> {
pub available_tools: Vec<SharedString>,
pub model_name: Option<String>,
pub date: String,
/// Contents of the user-global `~/.config/zed/AGENTS.md` file (or the
/// platform equivalent), if present and non-empty.
pub user_agents_md: Option<SharedString>,
}
impl Template for SystemPromptTemplate<'_> {
@ -80,9 +83,10 @@ mod tests {
let project = prompt_store::ProjectContext::default();
let template = SystemPromptTemplate {
project: &project,
available_tools: vec!["echo".into(), "update_plan".into()],
available_tools: vec!["echo".into(), "update_plan".into(), "update_title".into()],
model_name: Some("test-model".to_string()),
date: "2026-01-01".to_string(),
user_agents_md: None,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
@ -90,6 +94,60 @@ mod tests {
assert!(rendered.contains("Today's Date: 2026-01-01"));
assert!(rendered.contains("## Fixing Diagnostics"));
assert!(rendered.contains("## Planning"));
assert!(rendered.contains("## Session Title"));
assert!(rendered.contains("test-model"));
}
#[test]
fn test_system_prompt_renders_user_agents_md_before_project_rules() {
use prompt_store::{ProjectContext, RulesFileContext, WorktreeContext};
use util::rel_path::RelPath;
let worktrees = vec![WorktreeContext {
root_name: "my-project".to_string(),
abs_path: std::path::Path::new("/tmp/my-project").into(),
rules_file: Some(RulesFileContext {
path_in_worktree: RelPath::unix("AGENTS.md").unwrap().into(),
text: "project-specific guidance".to_string(),
project_entry_id: 1,
}),
}];
let project = ProjectContext::new(worktrees, Vec::new());
let template = SystemPromptTemplate {
project: &project,
available_tools: vec!["echo".into()],
model_name: Some("test-model".to_string()),
date: "2026-01-01".to_string(),
user_agents_md: Some("always be concise".into()),
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
assert!(rendered.contains("### Personal `AGENTS.md`"));
assert!(rendered.contains("always be concise"));
assert!(rendered.contains("### Project Rules"));
assert!(rendered.contains("project-specific guidance"));
let personal_idx = rendered.find("### Personal `AGENTS.md`").unwrap();
let project_idx = rendered.find("### Project Rules").unwrap();
assert!(
personal_idx < project_idx,
"personal AGENTS.md should render before project rules so project rules can override it"
);
}
#[test]
fn test_system_prompt_omits_user_agents_md_section_when_absent() {
let project = prompt_store::ProjectContext::default();
let template = SystemPromptTemplate {
project: &project,
available_tools: vec!["echo".into()],
model_name: Some("test-model".to_string()),
date: "2026-01-01".to_string(),
user_agents_md: None,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
assert!(!rendered.contains("### Personal `AGENTS.md`"));
}
}

View file

@ -52,6 +52,17 @@ Use a plan when:
- The user asked you to do more than one thing in a single prompt.
- You discover additional steps while working and intend to complete them before yielding to the user.
{{/if}}
{{#if (contains available_tools 'update_title') }}
## Session Title
- Use the `update_title` tool to set the title shown to the user for the current session.
- You MUST set a title at least once, even for small tasks. Do it early in the conversation, after the first user message, before you start working. There is no title to begin with, so you are responsible for setting one.
- Update the title again whenever the goal changes materially.
- Titles are very important to communicate to the user what you are working on. A session should always have a title.
- Keep titles concise and specific. Prefer a short noun phrase over a full sentence, and do not wrap the title in quotes.
- Do not mention that you changed the title unless it is directly relevant to the user.
{{/if}}
## Searching and Reading

View file

@ -74,6 +74,17 @@ Use a plan when:
- The user asked you to do more than one thing in a single prompt.
- You discover additional steps while working and intend to complete them before yielding to the user.
{{/if}}
{{#if (contains available_tools 'update_title') }}
## Session Title
- Use the `update_title` tool to set the title shown to the user for the current session.
- You MUST set a title at least once, even for small tasks. Do it early in the conversation, after the first user message, before you start working. There is no title to begin with, so you are responsible for setting one.
- Update the title again whenever the goal changes materially.
- Titles are very important to communicate to the user what you are working on. A session should always have a title.
- Keep titles concise and specific. Prefer a short noun phrase over a full sentence, and do not wrap the title in quotes.
- Do not mention that you changed the title unless it is directly relevant to the user.
{{/if}}
## Searching and Reading
@ -212,12 +223,26 @@ To use a Skill:
4. If the Skill references additional files, use `read_file` to access them. Paths inside a Skill resolve relative to that Skill's directory (the parent of its `SKILL.md`).
{{/if}}
{{#if (or has_rules has_user_rules)}}
{{#if (or user_agents_md has_rules has_user_rules)}}
## User's Custom Instructions
The following additional instructions are provided by the user and should be followed to the best of your ability{{#if (gt (len available_tools) 0)}} without interfering with the tool use guidelines{{/if}}.
{{#if user_agents_md}}
### Personal `AGENTS.md`
These instructions apply to every project this user opens. Project-specific rules below may override them.
``````
{{{user_agents_md}}}
``````
{{/if}}
{{#if has_rules}}
### Project Rules
These instructions are scoped to the current project. They take precedence over the personal `AGENTS.md` above when they conflict.
There are project rules that apply to these root directories:
{{#each worktrees}}
{{#if rules_file}}

View file

@ -26,10 +26,10 @@ use gpui::{
use indoc::indoc;
use language_model::{
CompletionIntent, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
LanguageModelId, LanguageModelProviderId, LanguageModelProviderName, LanguageModelRegistry,
LanguageModelRequest, LanguageModelRequestMessage, LanguageModelToolResult,
LanguageModelToolSchemaFormat, LanguageModelToolUse, MessageContent, Role, StopReason,
TokenUsage,
LanguageModelId, LanguageModelImageExt, LanguageModelProviderId, LanguageModelProviderName,
LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
LanguageModelToolResult, LanguageModelToolSchemaFormat, LanguageModelToolUse, MessageContent,
Role, StopReason, TokenUsage,
fake_provider::{FakeLanguageModel, FakeLanguageModelProvider},
};
use pretty_assertions::assert_eq;
@ -1656,6 +1656,7 @@ async fn test_mcp_tool_multi_content_response(cx: &mut TestAppContext) {
let (tool_call_params, tool_call_response) = mcp_tool_calls.next().await.unwrap();
assert_eq!(tool_call_params.name, "screenshot");
let image_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
tool_call_response
.send(context_server::types::CallToolResponse {
content: vec![
@ -1663,7 +1664,7 @@ async fn test_mcp_tool_multi_content_response(cx: &mut TestAppContext) {
text: "Some text".into(),
},
context_server::types::ToolResponseContent::Image {
data: "aGVsbG8=".into(),
data: image_data.into(),
mime_type: "image/png".into(),
},
context_server::types::ToolResponseContent::Text {
@ -1691,13 +1692,25 @@ async fn test_mcp_tool_multi_content_response(cx: &mut TestAppContext) {
})
.expect("expected a tool result");
assert_eq!(tool_result.tool_use_id, "tool_1".into());
assert_eq!(tool_result.content.len(), 2);
assert_eq!(tool_result.content.len(), 3);
assert_eq!(
tool_result.content[0],
language_model::LanguageModelToolResultContent::Text(Arc::from("Some text"))
);
let expected_image =
language_model::LanguageModelImage::from_base64_image(image_data, "image/png")
.expect("image conversion should not error")
.expect("image conversion should succeed");
assert_eq!(
tool_result.content[0],
language_model::LanguageModelToolResultContent::Text(Arc::from("Some text"))
);
assert_eq!(
tool_result.content[1],
language_model::LanguageModelToolResultContent::Image(expected_image)
);
assert_eq!(
tool_result.content[2],
language_model::LanguageModelToolResultContent::Text(Arc::from("Some more text"))
);
fake_model.end_last_completion_stream();
@ -3794,6 +3807,155 @@ async fn test_update_plan_tool_updates_thread_events(cx: &mut TestAppContext) {
);
}
#[gpui::test]
async fn test_update_title_tool_sets_thread_title(cx: &mut TestAppContext) {
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
let fake_model = model.as_fake();
let summary_model = Arc::new(FakeLanguageModel::default());
cx.update(|cx| {
cx.update_flags(true, vec!["update-title-tool".to_string()]);
});
thread.update(cx, |thread, cx| {
thread.add_tool(UpdateTitleTool::new(cx.weak_entity()));
thread.set_summarization_model(Some(summary_model.clone()), cx);
});
let mut events = thread
.update(cx, |thread, cx| {
thread.send(UserMessageId::new(), ["Explore title tooling"], cx)
})
.unwrap();
cx.run_until_parked();
let input = json!({
"title": "Session title tool"
});
fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
LanguageModelToolUse {
id: "title_1".into(),
name: UpdateTitleTool::NAME.into(),
raw_input: input.to_string(),
input,
is_input_complete: true,
thought_signature: None,
},
));
fake_model.end_last_completion_stream();
cx.run_until_parked();
let tool_call = expect_tool_call(&mut events).await;
assert_eq!(
tool_call,
acp::ToolCall::new("title_1", "Update title: Session title tool")
.kind(acp::ToolKind::Think)
.raw_input(json!({
"title": "Session title tool"
}))
.meta(acp::Meta::from_iter([(
"tool_name".into(),
"update_title".into()
)]))
);
let update = expect_tool_call_update_fields(&mut events).await;
assert_eq!(
update,
acp::ToolCallUpdate::new(
"title_1",
acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress)
)
);
let update = expect_tool_call_update_fields(&mut events).await;
assert_eq!(
update,
acp::ToolCallUpdate::new(
"title_1",
acp::ToolCallUpdateFields::new()
.status(acp::ToolCallStatus::Completed)
.raw_output("Session title updated")
)
);
thread.read_with(cx, |thread, _| {
assert_eq!(thread.title(), Some("Session title tool".into()));
});
assert_eq!(summary_model.pending_completions(), Vec::new());
}
#[gpui::test]
async fn test_update_title_availability_suppresses_summary_title_generation(
cx: &mut TestAppContext,
) {
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
let fake_model = model.as_fake();
let summary_model = Arc::new(FakeLanguageModel::default());
cx.update(|cx| {
cx.update_flags(true, vec!["update-title-tool".to_string()]);
});
thread.update(cx, |thread, cx| {
thread.add_tool(UpdateTitleTool::new(cx.weak_entity()));
thread.set_summarization_model(Some(summary_model.clone()), cx);
});
let send = thread
.update(cx, |thread, cx| {
thread.send(UserMessageId::new(), ["Explore title tooling"], cx)
})
.unwrap();
cx.run_until_parked();
fake_model.send_last_completion_stream_text_chunk("Done");
fake_model.end_last_completion_stream();
send.collect::<Vec<_>>().await;
cx.run_until_parked();
thread.read_with(cx, |thread, _| {
assert_eq!(thread.title(), None);
});
assert_eq!(summary_model.pending_completions(), Vec::new());
}
#[gpui::test]
async fn test_update_title_flag_without_available_tool_falls_back_to_summary_title_generation(
cx: &mut TestAppContext,
) {
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
let fake_model = model.as_fake();
let summary_model = Arc::new(FakeLanguageModel::default());
cx.update(|cx| {
cx.update_flags(true, vec!["update-title-tool".to_string()]);
});
thread.update(cx, |thread, cx| {
thread.set_summarization_model(Some(summary_model.clone()), cx);
});
let send = thread
.update(cx, |thread, cx| {
thread.send(UserMessageId::new(), ["Explore title tooling"], cx)
})
.unwrap();
cx.run_until_parked();
fake_model.send_last_completion_stream_text_chunk("Done");
fake_model.end_last_completion_stream();
cx.run_until_parked();
assert_eq!(summary_model.pending_completions().len(), 1);
summary_model.send_last_completion_stream_text_chunk("Fallback title");
summary_model.end_last_completion_stream();
send.collect::<Vec<_>>().await;
cx.run_until_parked();
thread.read_with(cx, |thread, _| {
assert_eq!(thread.title(), Some("Fallback title".into()));
});
}
#[gpui::test]
async fn test_send_no_retry_on_success(cx: &mut TestAppContext) {
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
@ -3971,8 +4133,8 @@ async fn test_send_retry_finishes_tool_calls_on_error(cx: &mut TestAppContext) {
events.collect::<Vec<_>>().await;
thread.read_with(cx, |thread, _cx| {
assert_eq!(
thread.last_received_or_pending_message(),
Some(Message::Agent(AgentMessage {
thread.last_received_or_pending_message().as_deref(),
Some(&Message::Agent(AgentMessage {
content: vec![AgentMessageContent::Text("Done".into())],
tool_results: IndexMap::default(),
reasoning_details: None,
@ -4307,6 +4469,7 @@ async fn setup(cx: &mut TestAppContext, model: TestModel) -> ThreadTest {
StreamingFailingEchoTool::NAME: true,
TerminalTool::NAME: true,
UpdatePlanTool::NAME: true,
UpdateTitleTool::NAME: true,
}
}
}
@ -4389,7 +4552,7 @@ async fn setup(cx: &mut TestAppContext, model: TestModel) -> ThreadTest {
}
#[cfg(test)]
#[ctor::ctor]
#[ctor::ctor(unsafe)]
fn init_logger() {
if std::env::var("RUST_LOG").is_ok() {
env_logger::init();

View file

@ -4,12 +4,14 @@ use crate::{
FindPathTool, FindReferencesTool, GetCodeActionsTool, GoToDefinitionTool, GrepTool,
ListDirectoryTool, MovePathTool, ProjectSnapshot, ReadFileTool, RenameTool, SpawnAgentTool,
SystemPromptTemplate, Template, Templates, TerminalTool, ToolPermissionDecision,
UpdatePlanTool, WebSearchTool, WriteFileTool, decide_permission_from_settings,
UpdatePlanTool, UpdateTitleTool, UserAgentsMd, WebSearchTool, WriteFileTool,
decide_permission_from_settings,
};
use acp_thread::{MentionUri, UserMessageId};
use action_log::ActionLog;
use feature_flags::{
FeatureFlagAppExt as _, LspToolFeatureFlag, RenameToolFeatureFlag, UpdatePlanToolFeatureFlag,
UpdateTitleToolFeatureFlag,
};
use agent_client_protocol::schema as acp;
@ -121,7 +123,7 @@ enum RetryStrategy {
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Message {
User(UserMessage),
Agent(AgentMessage),
@ -174,13 +176,16 @@ impl Message {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserMessage {
pub id: UserMessageId,
pub content: Vec<UserMessageContent>,
pub content: Arc<[UserMessageContent]>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum UserMessageContent {
Text(String),
Mention { uri: MentionUri, content: String },
Mention {
uri: MentionUri,
content: SharedString,
},
Image(LanguageModelImage),
}
@ -188,7 +193,7 @@ impl UserMessage {
pub fn to_markdown(&self) -> String {
let mut markdown = String::new();
for content in &self.content {
for content in &*self.content {
match content {
UserMessageContent::Text(text) => {
markdown.push_str(text);
@ -233,6 +238,8 @@ impl UserMessage {
const OPEN_DIAGNOSTICS_TAG: &str = "<diagnostics>";
const OPEN_DIFFS_TAG: &str = "<diffs>";
const MERGE_CONFLICT_TAG: &str = "<merge_conflicts>";
const OPEN_SKILLS_TAG: &str =
"<skills>\nThe user has attached the following agent skills:\n";
let mut file_context = OPEN_FILES_TAG.to_string();
let mut directory_context = OPEN_DIRECTORIES_TAG.to_string();
@ -244,8 +251,9 @@ impl UserMessage {
let mut diagnostics_context = OPEN_DIAGNOSTICS_TAG.to_string();
let mut diffs_context = OPEN_DIFFS_TAG.to_string();
let mut merge_conflict_context = MERGE_CONFLICT_TAG.to_string();
let mut skills_context = OPEN_SKILLS_TAG.to_string();
for chunk in &self.content {
for chunk in &*self.content {
let chunk = match chunk {
UserMessageContent::Text(text) => {
language_model::MessageContent::Text(text.clone())
@ -261,7 +269,7 @@ impl UserMessage {
"\n{}",
MarkdownCodeBlock {
tag: &codeblock_tag(abs_path, None),
text: &content.to_string(),
text: content,
}
)
.ok();
@ -360,6 +368,10 @@ impl UserMessage {
)
.ok();
}
MentionUri::Skill { name, source, .. } => {
let label = format!("{} ({})", name, source);
write!(&mut skills_context, "\nSkill: {}\n{}\n", label, content).ok();
}
}
language_model::MessageContent::Text(uri.as_link().to_string())
@ -434,6 +446,13 @@ impl UserMessage {
.push(language_model::MessageContent::Text(diagnostics_context));
}
if skills_context.len() > OPEN_SKILLS_TAG.len() {
skills_context.push_str("</skills>\n");
message
.content
.push(language_model::MessageContent::Text(skills_context));
}
if merge_conflict_context.len() > MERGE_CONFLICT_TAG.len() {
merge_conflict_context.push_str("</merge_conflicts>\n");
message
@ -611,9 +630,9 @@ impl AgentMessage {
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentMessage {
pub content: Vec<AgentMessageContent>,
pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
pub reasoning_details: Option<serde_json::Value>,
pub(crate) content: Vec<AgentMessageContent>,
pub(crate) tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
pub(crate) reasoning_details: Option<Arc<serde_json::Value>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@ -947,7 +966,7 @@ pub struct Thread {
title_generation_failed: bool,
pending_summary_generation: Option<Shared<Task<Option<SharedString>>>>,
summary: Option<SharedString>,
messages: Vec<Message>,
messages: Vec<Arc<Message>>,
user_store: Entity<UserStore>,
/// Holds the task that handles agent interaction until the end of the turn.
/// Survives across multiple requests as the model performs tool calls and
@ -1167,7 +1186,7 @@ impl Thread {
let (tx, rx) = mpsc::unbounded();
let stream = ThreadEventStream(tx);
for message in &self.messages {
match message {
match &**message {
Message::User(user_message) => stream.send_user_message(user_message),
Message::Agent(assistant_message) => {
for content in &assistant_message.content {
@ -1201,10 +1220,10 @@ impl Thread {
stream: &ThreadEventStream,
cx: &mut Context<Self>,
) {
// Extract saved output and status first, so they're available even if tool is not found
let output = tool_result
.as_ref()
.and_then(|result| result.output.clone());
let replay_content = tool_result.and_then(Self::tool_result_content_for_replay);
let status = tool_result
.as_ref()
.map_or(acp::ToolCallStatus::Failed, |result| {
@ -1233,21 +1252,25 @@ impl Thread {
// but still display the saved result if available.
// We need to send both ToolCall and ToolCallUpdate events because the UI
// only converts raw_output to displayable content in update_fields, not from_acp.
let title = Self::title_for_replayed_tool_use(tool_use);
stream
.0
.unbounded_send(Ok(ThreadEvent::ToolCall(
acp::ToolCall::new(tool_use.id.to_string(), tool_use.name.to_string())
acp::ToolCall::new(tool_use.id.to_string(), title.clone())
.status(status)
.raw_input(tool_use.input.clone()),
)))
.ok();
stream.update_tool_call_fields(
&tool_use.id,
acp::ToolCallUpdateFields::new()
.status(status)
.raw_output(output),
None,
);
let mut fields = acp::ToolCallUpdateFields::new()
.status(status)
.raw_output(output);
if tool_use.name.as_ref() == UpdateTitleTool::NAME {
fields = fields.title(title);
}
if let Some(content) = replay_content {
fields = fields.content(content);
}
stream.update_tool_call_fields(&tool_use.id, fields, None);
return;
};
@ -1261,6 +1284,14 @@ impl Thread {
tool_use.input.clone(),
);
if let Some(content) = replay_content {
stream.update_tool_call_fields(
&tool_use.id,
acp::ToolCallUpdateFields::new().content(content),
None,
);
}
if let Some(output) = output.clone() {
// For replay, we use a dummy cancellation receiver since the tool already completed
let (_cancellation_tx, cancellation_rx) = watch::channel(false);
@ -1283,6 +1314,55 @@ impl Thread {
);
}
fn title_for_replayed_tool_use(tool_use: &LanguageModelToolUse) -> String {
if tool_use.name.as_ref() == UpdateTitleTool::NAME {
let input = serde_json::from_value(tool_use.input.clone())
.map_err(|_| serde_json::Value::String(tool_use.raw_input.clone()));
UpdateTitleTool::title_for_input(input).to_string()
} else {
tool_use.name.to_string()
}
}
fn tool_result_content_for_replay(
tool_result: &LanguageModelToolResult,
) -> Option<Vec<acp::ToolCallContent>> {
let has_image = tool_result
.content
.iter()
.any(|part| matches!(part, LanguageModelToolResultContent::Image(_)));
if !has_image && tool_result.output.is_some() {
return None;
}
let content = tool_result
.content
.iter()
.filter_map(|part| match part {
LanguageModelToolResultContent::Text(text) => {
if text.is_empty() {
None
} else {
Some(acp::ToolCallContent::Content(acp::Content::new(
acp::ContentBlock::Text(acp::TextContent::new(text.to_string())),
)))
}
}
LanguageModelToolResultContent::Image(image) => Some(
acp::ToolCallContent::Content(acp::Content::new(acp::ContentBlock::Image(
acp::ImageContent::new(image.source.clone(), "image/png"),
))),
),
})
.collect::<Vec<_>>();
if content.is_empty() {
None
} else {
Some(content)
}
}
pub fn from_db(
id: acp::SessionId,
db_thread: DbThread,
@ -1562,13 +1642,13 @@ impl Thread {
}
pub fn last_message(&self) -> Option<&Message> {
self.messages.last()
self.messages.last().map(std::ops::Deref::deref)
}
#[cfg(any(test, feature = "test-support"))]
pub fn last_received_or_pending_message(&self) -> Option<Message> {
pub fn last_received_or_pending_message(&self) -> Option<Arc<Message>> {
if let Some(message) = self.pending_message.clone() {
Some(Message::Agent(message))
Some(Arc::new(Message::Agent(message)))
} else {
self.messages.last().cloned()
}
@ -1609,6 +1689,9 @@ impl Thread {
if cx.has_flag::<UpdatePlanToolFeatureFlag>() {
self.add_tool(UpdatePlanTool);
}
if cx.has_flag::<UpdateTitleToolFeatureFlag>() {
self.add_tool(UpdateTitleTool::new(cx.weak_entity()));
}
self.add_tool(ReadFileTool::new(
self.project.clone(),
self.action_log.clone(),
@ -1722,13 +1805,13 @@ impl Thread {
// and we don't want that content to be added after we truncate
self.pending_message.take();
let Some(position) = self.messages.iter().position(
|msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
|msg| matches!(&**msg, Message::User(UserMessage { id, .. }) if id == &message_id),
) else {
return Err(anyhow!("Message not found"));
};
for message in self.messages.drain(position..) {
match message {
match &*message {
Message::User(message) => {
self.request_token_usage.remove(&message.id);
}
@ -1770,7 +1853,7 @@ impl Thread {
let mut previous_user_message_id: Option<&UserMessageId> = None;
for message in &self.messages {
if let Message::User(user_msg) = message {
if let Message::User(user_msg) = &**message {
if &user_msg.id == target_id {
let prev_id = previous_user_message_id?;
let usage = self.request_token_usage.get(prev_id)?;
@ -1815,7 +1898,7 @@ impl Thread {
&mut self,
cx: &mut Context<Self>,
) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
self.messages.push(Message::Resume);
self.messages.push(Arc::new(Message::Resume));
cx.notify();
log::debug!("Total messages in thread: {}", self.messages.len());
@ -1834,11 +1917,11 @@ impl Thread {
where
T: Into<UserMessageContent>,
{
let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
let content = content.into_iter().map(Into::into).collect::<Arc<_>>();
log::debug!("Thread::send content: {:?}", content);
self.messages
.push(Message::User(UserMessage { id, content }));
.push(Arc::new(Message::User(UserMessage { id, content })));
cx.notify();
self.send_existing(cx)
@ -1869,9 +1952,9 @@ impl Thread {
let content = blocks
.into_iter()
.map(|block| UserMessageContent::from_content_block(block, path_style))
.collect::<Vec<_>>();
.collect::<Arc<_>>();
self.messages
.push(Message::User(UserMessage { id, content }));
.push(Arc::new(Message::User(UserMessage { id, content })));
cx.notify();
}
@ -1889,10 +1972,10 @@ impl Thread {
_ => "[unknown]".to_string(),
};
self.messages.push(Message::Agent(AgentMessage {
self.messages.push(Arc::new(Message::Agent(AgentMessage {
content: vec![AgentMessageContent::Text(text)],
..Default::default()
}));
})));
cx.notify();
}
@ -2122,7 +2205,7 @@ impl Thread {
this.update(cx, |this, cx| {
this.flush_pending_message(cx);
if this.title.is_none() && this.pending_title_generation.is_none() {
if this.title.is_none() {
this.generate_title(cx);
}
})?;
@ -2150,10 +2233,10 @@ impl Thread {
}
}
this.update(cx, |this, _cx| {
if let Some(Message::Agent(message)) = this.messages.last() {
if let Some(Message::Agent(message)) = this.last_message() {
if message.tool_results.is_empty() {
intent = CompletionIntent::UserPrompt;
this.messages.push(Message::Resume);
this.messages.push(Arc::new(Message::Resume));
}
}
})?;
@ -2276,12 +2359,12 @@ impl Thread {
let last_message = self.pending_message();
// Store the last non-empty reasoning_details (overwrites earlier ones)
// This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
if let serde_json::Value::Array(ref arr) = details {
if let serde_json::Value::Array(arr) = &details {
if !arr.is_empty() {
last_message.reasoning_details = Some(details);
last_message.reasoning_details = Some(Arc::new(details));
}
} else {
last_message.reasoning_details = Some(details);
last_message.reasoning_details = Some(Arc::new(details));
}
}
ToolUse(tool_use) => {
@ -2651,6 +2734,20 @@ impl Thread {
self.title_generation_failed
}
pub fn can_generate_title(&self, cx: &App) -> bool {
self.pending_title_generation.is_none()
&& self.summarization_model.is_some()
&& !self.update_title_tool_available(cx)
}
fn update_title_tool_available(&self, cx: &App) -> bool {
if let Some(running_turn) = self.running_turn.as_ref() {
running_turn.tools.contains_key(UpdateTitleTool::NAME)
} else {
self.enabled_tools(cx).contains_key(UpdateTitleTool::NAME)
}
}
pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
if let Some(summary) = self.summary.as_ref() {
return Task::ready(Some(summary.clone())).shared();
@ -2712,6 +2809,10 @@ impl Thread {
}
pub fn generate_title(&mut self, cx: &mut Context<Self>) {
if !self.can_generate_title(cx) {
return;
}
self.title_generation_failed = false;
let Some(model) = self.summarization_model.clone() else {
return;
@ -2797,7 +2898,7 @@ impl Thread {
self.messages
.iter()
.rev()
.find_map(|message| match message {
.find_map(|message| match &**message {
Message::User(user_message) => Some(user_message),
Message::Agent(_) => None,
Message::Resume => None,
@ -2838,7 +2939,7 @@ impl Thread {
}
}
self.messages.push(Message::Agent(message));
self.messages.push(Arc::new(Message::Agent(message)));
self.updated_at = Utc::now();
self.clear_summary();
cx.notify()
@ -3063,11 +3164,13 @@ impl Thread {
self.messages.len()
);
let user_agents_md = UserAgentsMd::global(cx).and_then(|s| s.content().cloned());
let system_prompt = SystemPromptTemplate {
project: self.project_context.read(cx),
available_tools,
model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
date: Local::now().format("%Y-%m-%d").to_string(),
user_agents_md,
}
.render(&self.templates)
.context("failed to build system prompt")
@ -3099,7 +3202,7 @@ impl Thread {
if ix > 0 {
markdown.push('\n');
}
match message {
match &**message {
Message::User(_) => markdown.push_str("## User\n\n"),
Message::Agent(_) => markdown.push_str("## Assistant\n\n"),
Message::Resume => {}
@ -4311,7 +4414,7 @@ impl UserMessageContent {
match MentionUri::parse(&resource_link.uri, path_style) {
Ok(uri) => Self::Mention {
uri,
content: String::new(),
content: SharedString::default(),
},
Err(err) => {
log::error!("Failed to parse mention link: {}", err);
@ -4324,7 +4427,7 @@ impl UserMessageContent {
match MentionUri::parse(&resource.uri, path_style) {
Ok(uri) => Self::Mention {
uri,
content: resource.text,
content: resource.text.into(),
},
Err(err) => {
log::error!("Failed to parse mention link: {}", err);
@ -4374,7 +4477,6 @@ impl From<UserMessageContent> for acp::ContentBlock {
fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
LanguageModelImage {
source: image_content.data.into(),
size: None,
}
}
@ -4439,6 +4541,259 @@ mod tests {
})
}
struct ReplayImageTool;
impl AgentTool for ReplayImageTool {
type Input = ();
type Output = String;
const NAME: &'static str = "registered_image_tool";
fn kind() -> acp::ToolKind {
acp::ToolKind::Other
}
fn initial_title(
&self,
_input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
"Registered Image Tool".into()
}
fn run(
self: Arc<Self>,
_input: ToolInput<Self::Input>,
_event_stream: ToolCallEventStream,
_cx: &mut App,
) -> Task<Result<Self::Output, Self::Output>> {
Task::ready(Ok(String::new()))
}
}
#[gpui::test]
async fn test_replay_tool_call_replays_image_content(cx: &mut TestAppContext) {
let (thread, _event_stream) = setup_thread_for_test(cx).await;
let registered_tool_use_id = LanguageModelToolUseId::from("registered_tool_id");
let missing_tool_use_id = LanguageModelToolUseId::from("missing_tool_id");
let image_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
let image = LanguageModelImage {
source: image_data.into(),
};
let mut replay_events = cx.update(|cx| {
thread.update(cx, |thread, cx| {
thread.add_tool(ReplayImageTool);
let registered_tool_use = LanguageModelToolUse {
id: registered_tool_use_id.clone(),
name: ReplayImageTool::NAME.into(),
raw_input: "null".to_string(),
input: json!(null),
is_input_complete: true,
thought_signature: None,
};
let missing_tool_use = LanguageModelToolUse {
id: missing_tool_use_id.clone(),
name: "missing_image_tool".into(),
raw_input: "{}".to_string(),
input: json!({}),
is_input_complete: true,
thought_signature: None,
};
let mut tool_results = IndexMap::default();
tool_results.insert(
registered_tool_use_id.clone(),
LanguageModelToolResult {
tool_use_id: registered_tool_use_id.clone(),
tool_name: ReplayImageTool::NAME.into(),
is_error: false,
content: vec![
LanguageModelToolResultContent::Text("before".into()),
LanguageModelToolResultContent::Image(image.clone()),
LanguageModelToolResultContent::Text("after".into()),
],
output: Some(json!("raw output")),
},
);
tool_results.insert(
missing_tool_use_id.clone(),
LanguageModelToolResult {
tool_use_id: missing_tool_use_id.clone(),
tool_name: "missing_image_tool".into(),
is_error: false,
content: vec![LanguageModelToolResultContent::Image(image.clone())],
output: Some(json!("raw output")),
},
);
thread.messages.push(Arc::new(Message::Agent(AgentMessage {
content: vec![
AgentMessageContent::ToolUse(registered_tool_use),
AgentMessageContent::ToolUse(missing_tool_use),
],
tool_results,
reasoning_details: None,
})));
thread.replay(cx)
})
});
let mut tool_use_ids_with_image_content = HashSet::default();
while let Some(event) = replay_events.next().await {
let event = event.unwrap();
if let ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update)) =
event
&& let Some(content) = &update.fields.content
&& content.iter().any(|content| {
matches!(
content,
acp::ToolCallContent::Content(acp::Content {
content: acp::ContentBlock::Image(_),
..
})
)
})
{
tool_use_ids_with_image_content.insert(update.tool_call_id.to_string());
}
}
assert!(tool_use_ids_with_image_content.contains(&registered_tool_use_id.to_string()));
assert!(tool_use_ids_with_image_content.contains(&missing_tool_use_id.to_string()));
}
#[gpui::test]
async fn test_update_title_tool_replay_does_not_reenter_thread(cx: &mut TestAppContext) {
let (thread, _event_stream) = setup_thread_for_test(cx).await;
let tool_use_id = LanguageModelToolUseId::from("title_tool_id");
let mut replay_events = cx.update(|cx| {
thread.update(cx, |thread, cx| {
thread.add_tool(UpdateTitleTool::new(cx.weak_entity()));
push_completed_update_title_tool_call(thread, tool_use_id.clone());
thread.replay(cx)
})
});
let mut saw_tool_call_title = false;
let mut saw_replayed_title_update = false;
let mut saw_completed_update = false;
while let Some(event) = replay_events.next().await {
let event = event.unwrap();
match event {
ThreadEvent::ToolCall(tool_call)
if tool_call.tool_call_id.to_string() == tool_use_id.to_string()
&& tool_call.title == "Update title: Replayed title" =>
{
saw_tool_call_title = true;
}
ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update))
if update.tool_call_id.to_string() == tool_use_id.to_string() =>
{
if update.fields.title == Some("Update title: Replayed title".to_string()) {
saw_replayed_title_update = true;
}
if update.fields.status == Some(acp::ToolCallStatus::Completed) {
saw_completed_update = true;
}
}
_ => {}
}
}
assert!(saw_tool_call_title);
assert!(saw_replayed_title_update);
assert!(saw_completed_update);
thread.read_with(cx, |thread, _cx| {
assert_eq!(thread.title(), None);
});
}
#[gpui::test]
async fn test_update_title_tool_replay_title_when_tool_not_registered(cx: &mut TestAppContext) {
let (thread, _event_stream) = setup_thread_for_test(cx).await;
let tool_use_id = LanguageModelToolUseId::from("title_tool_id");
let mut replay_events = cx.update(|cx| {
thread.update(cx, |thread, cx| {
push_completed_update_title_tool_call(thread, tool_use_id.clone());
thread.replay(cx)
})
});
let mut saw_tool_call_title = false;
let mut saw_replayed_title_update = false;
let mut saw_completed_update = false;
while let Some(event) = replay_events.next().await {
let event = event.unwrap();
match event {
ThreadEvent::ToolCall(tool_call)
if tool_call.tool_call_id.to_string() == tool_use_id.to_string()
&& tool_call.title == "Update title: Replayed title" =>
{
saw_tool_call_title = true;
}
ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update))
if update.tool_call_id.to_string() == tool_use_id.to_string() =>
{
if update.fields.title == Some("Update title: Replayed title".to_string()) {
saw_replayed_title_update = true;
}
if update.fields.status == Some(acp::ToolCallStatus::Completed) {
saw_completed_update = true;
}
}
_ => {}
}
}
assert!(saw_tool_call_title);
assert!(saw_replayed_title_update);
assert!(saw_completed_update);
thread.read_with(cx, |thread, _cx| {
assert_eq!(thread.title(), None);
});
}
fn push_completed_update_title_tool_call(
thread: &mut Thread,
tool_use_id: LanguageModelToolUseId,
) {
let tool_use = LanguageModelToolUse {
id: tool_use_id.clone(),
name: UpdateTitleTool::NAME.into(),
raw_input: json!({ "title": "Replayed title" }).to_string(),
input: json!({ "title": "Replayed title" }),
is_input_complete: true,
thought_signature: None,
};
let mut tool_results = IndexMap::default();
tool_results.insert(
tool_use_id.clone(),
LanguageModelToolResult {
tool_use_id,
tool_name: UpdateTitleTool::NAME.into(),
is_error: false,
content: vec![LanguageModelToolResultContent::Text(
"Session title updated".into(),
)],
output: Some(json!("Session title updated")),
},
);
thread.messages.push(Arc::new(Message::Agent(AgentMessage {
content: vec![AgentMessageContent::ToolUse(tool_use)],
tool_results,
reasoning_details: None,
})));
}
#[gpui::test]
async fn test_set_model_propagates_to_subagents(cx: &mut TestAppContext) {
let (parent, _event_stream) = setup_thread_for_test(cx).await;

View file

@ -24,6 +24,7 @@ mod symbol_locator;
mod terminal_tool;
mod tool_permissions;
mod update_plan_tool;
mod update_title_tool;
mod web_search_tool;
mod write_file_tool;
@ -80,6 +81,7 @@ pub use symbol_locator::*;
pub use terminal_tool::*;
pub use tool_permissions::*;
pub use update_plan_tool::*;
pub use update_title_tool::*;
pub use web_search_tool::*;
pub use write_file_tool::*;
@ -172,6 +174,7 @@ tools! {
SpawnAgentTool,
TerminalTool,
UpdatePlanTool,
UpdateTitleTool,
WebSearchTool,
WriteFileTool,
}

View file

@ -5,7 +5,7 @@ use collections::{BTreeMap, HashMap};
use context_server::{ContextServerId, client::NotificationSubscription};
use futures::FutureExt as _;
use gpui::{App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task};
use language_model::LanguageModelToolResultContent;
use language_model::{LanguageModelImage, LanguageModelImageExt, LanguageModelToolResultContent};
use project::context_server_store::{ContextServerStatus, ContextServerStore};
use std::sync::Arc;
use util::ResultExt;
@ -261,7 +261,8 @@ impl ContextServerRegistry {
}
ContextServerStatus::Stopped
| ContextServerStatus::Error(_)
| ContextServerStatus::AuthRequired => {
| ContextServerStatus::AuthRequired
| ContextServerStatus::ClientSecretRequired { .. } => {
if let Some(registered_server) = self.registered_servers.remove(server_id) {
if !registered_server.tools.is_empty() {
cx.emit(ContextServerRegistryEvent::ToolsChanged);
@ -346,7 +347,7 @@ impl AnyAgentTool for ContextServerTool {
let authorize =
event_stream.authorize_third_party_tool(initial_title, tool_id, display_name, cx);
cx.spawn(async move |_cx| {
cx.spawn(async move |cx| {
let input = input
.recv()
.await
@ -394,15 +395,50 @@ impl AnyAgentTool for ContextServerTool {
}
let mut llm_output = Vec::new();
let mut tool_call_content = Vec::new();
let mut concatenated_text = String::new();
for content in response.content {
match content {
context_server::types::ToolResponseContent::Text { text } => {
concatenated_text.push_str(&text);
tool_call_content.push(acp::ToolCallContent::Content(acp::Content::new(
acp::ContentBlock::Text(acp::TextContent::new(text.clone())),
)));
llm_output.push(LanguageModelToolResultContent::Text(text.into()));
}
context_server::types::ToolResponseContent::Image { .. } => {
log::warn!("Ignoring image content from tool response");
context_server::types::ToolResponseContent::Image { data, mime_type } => {
tool_call_content.push(acp::ToolCallContent::Content(acp::Content::new(
acp::ContentBlock::Image(acp::ImageContent::new(
data.clone(),
mime_type.clone(),
)),
)));
let language_model_image = cx
.background_spawn({
let mime_type = mime_type.clone();
async move {
LanguageModelImage::from_base64_image(&data, &mime_type)
}
})
.await;
match language_model_image {
Ok(Some(image)) => {
llm_output.push(LanguageModelToolResultContent::Image(image));
}
Ok(None) => {
log::warn!(
"Skipping MCP tool response image with MIME type `{}` because it cannot be converted for language model input",
mime_type
);
}
Err(error) => {
log::warn!(
"Failed to convert MCP tool response image with MIME type `{}` for language model input: {:#}",
mime_type,
error
);
}
}
}
context_server::types::ToolResponseContent::Audio { .. } => {
log::warn!("Ignoring audio content from tool response");
@ -415,6 +451,10 @@ impl AnyAgentTool for ContextServerTool {
}
}
}
if !tool_call_content.is_empty() {
event_stream
.update_fields(acp::ToolCallUpdateFields::new().content(tool_call_content));
}
let raw_output = serde_json::Value::String(concatenated_text);
Ok(AgentToolOutput {
raw_output,

View file

@ -1,6 +1,6 @@
use super::tool_permissions::{
authorize_symlink_access, canonicalize_worktree_roots, detect_symlink_escape,
sensitive_settings_kind,
resolve_creatable_global_skill_path, sensitive_settings_kind,
};
use agent_client_protocol::schema as acp;
use agent_settings::AgentSettings;
@ -22,6 +22,7 @@ use std::path::Path;
/// Creates a new directory at the specified path within the project. Returns confirmation that the directory was created.
///
/// This tool creates a directory and all necessary parent directories. It should be used whenever you need to create new directories within the project.
/// The only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct CreateDirectoryToolInput {
/// The path of the new directory.
@ -34,6 +35,10 @@ pub struct CreateDirectoryToolInput {
///
/// You can create a new directory by providing a path of "directory1/new_directory"
/// </example>
///
/// <example>
/// To create a global agent skill directory, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill`.
/// </example>
pub path: String,
}
@ -144,6 +149,21 @@ impl AgentTool for CreateDirectoryTool {
authorize.await.map_err(|e| e.to_string())?;
}
if let Some(global_skill_directory) =
resolve_creatable_global_skill_path(Path::new(&input.path), fs.as_ref()).await
{
futures::select! {
result = fs.create_dir(&global_skill_directory).fuse() => {
result.map_err(|e| format!("Creating directory {destination_path}: {e}"))?;
}
_ = event_stream.cancelled_by_user().fuse() => {
return Err("Create directory cancelled by user".to_string());
}
}
return Ok(format!("Created directory {destination_path}"));
}
let create_entry = project.update(cx, |project, cx| {
match project.find_project_path(&input.path, cx) {
Some(project_path) => Ok(project.create_entry(project_path, true, cx)),
@ -190,6 +210,96 @@ mod tests {
});
}
#[gpui::test]
async fn test_create_directory_allows_global_skill_directory(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(path!("/root/project"), json!({})).await;
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
cx.executor().run_until_parked();
let tool = Arc::new(CreateDirectoryTool::new(project));
let input_path = PathBuf::from("~")
.join(".agents")
.join("skills")
.join("my-skill")
.to_string_lossy()
.into_owned();
let created_path = agent_skills::global_skills_dir().join("my-skill");
let (event_stream, mut event_rx) = ToolCallEventStream::test();
let task = cx.update(|cx| {
tool.run(
ToolInput::resolved(CreateDirectoryToolInput { path: input_path }),
event_stream,
cx,
)
});
let auth = event_rx.expect_authorization().await;
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
);
auth.response
.send(acp_thread::SelectedPermissionOutcome::new(
acp::PermissionOptionId::new("allow"),
acp::PermissionOptionKind::AllowOnce,
))
.expect("authorization response should send");
let result = task.await;
assert!(
result.is_ok(),
"Tool should create global skill directory: {result:?}"
);
assert!(fs.is_dir(&created_path).await);
}
#[gpui::test]
async fn test_create_directory_rejects_other_global_paths(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(path!("/root/project"), json!({})).await;
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
cx.executor().run_until_parked();
let tool = Arc::new(CreateDirectoryTool::new(project));
let outside_path = agent_skills::global_skills_dir()
.parent()
.expect("global skills directory should have a parent")
.join("not-skills");
let (event_stream, mut event_rx) = ToolCallEventStream::test();
let result = cx
.update(|cx| {
tool.run(
ToolInput::resolved(CreateDirectoryToolInput {
path: outside_path.to_string_lossy().into_owned(),
}),
event_stream,
cx,
)
})
.await;
assert!(
result.is_err(),
"Tool should reject paths outside the project and global skills directory"
);
assert!(!fs.is_dir(&outside_path).await);
assert!(
!matches!(
event_rx.try_recv(),
Ok(Ok(crate::ThreadEvent::ToolCallAuthorization(_)))
),
"Non-skill global path should not emit an agent-skills authorization prompt",
);
}
#[gpui::test]
async fn test_create_directory_symlink_escape_requests_authorization(cx: &mut TestAppContext) {
init_test(cx);

View file

@ -1,16 +1,18 @@
use crate::{AgentTool, ToolCallEventStream, ToolInput};
use agent_client_protocol::schema as acp;
use anyhow::Result;
use futures::FutureExt as _;
use gpui::{App, Entity, Task};
use futures::{Future, FutureExt as _};
use gpui::{App, AsyncApp, Entity, Task};
use language::{DiagnosticSeverity, OffsetRangeExt};
use project::Project;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::{fmt::Write, sync::Arc};
use ui::SharedString;
use util::markdown::MarkdownInlineCode;
type Result<T, E = String> = core::result::Result<T, E>;
/// Get errors and warnings for the project or a specific file.
///
/// This tool can be invoked after a series of edits to determine if further edits are necessary, or if the user asks to fix errors or warnings in their codebase.
@ -18,6 +20,11 @@ use util::markdown::MarkdownInlineCode;
/// When a path is provided, shows all diagnostics for that specific file.
/// When no path is provided, shows a summary of error and warning counts for all files in the project.
///
/// This tool attempts to refresh diagnostics before returning.
/// If refreshing diagnostics fails (for example, if the language server does not support pull-based diagnostics), it will return any diagnostics already present.
/// Note that, in this case, the results may be out-of-date, and may or may not reflect the most recent edits.
/// If this happens, do not attempt to re-run this tool in the hope that refreshing will later succeed. Failures are typically persistent.
///
/// <example>
/// To get diagnostics for a specific file:
/// {
@ -60,6 +67,71 @@ impl DiagnosticsTool {
}
}
async fn with_cancellation<T>(f: impl Future<Output = T>, s: &ToolCallEventStream) -> Result<T> {
futures::select! {
result = f.fuse() => Ok(result),
_ = s.cancelled_by_user().fuse() => {
Err("Diagnostics cancelled by user".to_string())
}
}
}
fn freshness_message(refreshed: bool) -> &'static str {
if refreshed {
"Diagnostics successfully refreshed."
} else {
"Failed to refresh diagnostics. Diagnostics may be stale."
}
}
/// Attempt to pull fresh diagnostics from the LSP before reading them.
///
/// Returns `Ok(true)` if diagnostics were successfully refreshed,
/// `Ok(false)` if the pull failed (callers should fall through to
/// read cached diagnostics), or `Err` if cancelled by the user.
async fn pull_diagnostics(
project: &Entity<Project>,
path: Option<&Path>,
event_stream: &ToolCallEventStream,
cx: &mut AsyncApp,
) -> Result<bool, String> {
match path {
Some(path) => {
let open_buffer_task = project.update(cx, |project, cx| {
let Some(project_path) = project.find_project_path(path, cx) else {
return Err(format!("Could not find path {} in project", path.display()));
};
Ok(project.open_buffer(project_path, cx))
})?;
let buffer = with_cancellation(open_buffer_task, event_stream)
.await?
.map_err(|e| e.to_string())?;
let lsp_store = project.read_with(cx, |project, _cx| project.lsp_store());
let pull_task = lsp_store.update(cx, |lsp_store, cx| {
lsp_store.pull_diagnostics_for_buffer(buffer, cx)
});
let pull_result = with_cancellation(pull_task, event_stream).await?;
if let Err(error) = &pull_result {
log::warn!("Failed to pull diagnostics, using cached: {error:#}");
}
Ok(pull_result.is_ok())
}
None => {
let lsp_store = project.read_with(cx, |project, _cx| project.lsp_store());
let pull_task = lsp_store.update(cx, |lsp_store, cx| {
lsp_store.pull_workspace_diagnostics_once(cx)
});
let succeeded = with_cancellation(pull_task, event_stream).await?;
if !succeeded {
log::warn!("Failed to pull workspace diagnostics, using cached");
}
Ok(succeeded)
}
}
}
impl AgentTool for DiagnosticsTool {
type Input = DiagnosticsToolInput;
type Output = String;
@ -96,21 +168,22 @@ impl AgentTool for DiagnosticsTool {
let input = input.recv().await.map_err(|e| e.to_string())?;
match input.path {
Some(path) if !path.is_empty() => {
let (_project_path, open_buffer_task) = project.update(cx, |project, cx| {
let Some(project_path) = project.find_project_path(&path, cx) else {
Some(ref path) if !path.is_empty() => {
let refreshed =
pull_diagnostics(&project, Some(Path::new(path)), &event_stream, cx)
.await?;
let open_buffer_task = project.update(cx, |project, cx| {
let Some(project_path) = project.find_project_path(path, cx) else {
return Err(format!("Could not find path {path} in project"));
};
let task = project.open_buffer(project_path.clone(), cx);
Ok((project_path, task))
Ok(project.open_buffer(project_path, cx))
})?;
let buffer = futures::select! {
result = open_buffer_task.fuse() => result.map_err(|e| e.to_string())?,
_ = event_stream.cancelled_by_user().fuse() => {
return Err("Diagnostics cancelled by user".to_string());
}
};
let buffer = with_cancellation(open_buffer_task, &event_stream)
.await?
.map_err(|e| e.to_string())?;
let mut output = String::new();
let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
@ -133,13 +206,18 @@ impl AgentTool for DiagnosticsTool {
.ok();
}
let freshness = freshness_message(refreshed);
if output.is_empty() {
Ok("File doesn't have errors or warnings!".to_string())
Ok(format!(
"{freshness}\n\nFile doesn't have errors or warnings!"
))
} else {
Ok(output)
Ok(format!("{freshness}\n\n{output}"))
}
}
_ => {
let refreshed = pull_diagnostics(&project, None, &event_stream, cx).await?;
let (output, has_diagnostics) = project.read_with(cx, |project, cx| {
let mut output = String::new();
let mut has_diagnostics = false;
@ -165,10 +243,13 @@ impl AgentTool for DiagnosticsTool {
(output, has_diagnostics)
});
let freshness = freshness_message(refreshed);
if has_diagnostics {
Ok(output)
Ok(format!("{freshness}\n\n{output}"))
} else {
Ok("No errors or warnings found in the project.".into())
Ok(format!(
"{freshness}\n\nNo errors or warnings found in the project."
))
}
}
}

View file

@ -23,13 +23,21 @@ const DEFAULT_UI_TEXT: &str = "Editing file";
/// This is a tool for applying edits to an existing file.
///
/// Before using this tool, use the `read_file` tool to understand the file's contents and context
/// Before using this tool, use the `read_file` tool to understand the file's contents and context.
/// To create a new file or overwrite an existing one with completely new contents, use the `write_file` tool instead.
///
/// The only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.
///
/// `read_file` prefixes each line of its output with a line number right-aligned in a
/// 6-character field followed by a single tab, then the line's actual content. When you
/// derive `old_text` or `new_text` from that output, strip this prefix and keep only what
/// comes after the tab, preserving the original indentation (tabs and spaces) exactly.
/// Never include any part of the line number prefix in `old_text` or `new_text`.
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
pub struct EditFileToolInput {
/// The full path of the file to edit in the project.
///
/// WARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories.
/// WARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories, unless it's a global agent skill under `~/.agents/skills`.
///
/// The following examples assume we have two root directories in the project:
/// - /a/b/backend
@ -44,6 +52,10 @@ pub struct EditFileToolInput {
/// <example>
/// `frontend/db.js`
/// </example>
///
/// <example>
/// To edit a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.
/// </example>
pub path: PathBuf,
/// List of edit operations to apply sequentially.
@ -253,6 +265,7 @@ impl AgentTool for EditFileTool {
run_session(
self.process_streaming_edits(&mut input, &event_stream, cx)
.await,
&event_stream,
cx,
)
.await
@ -457,6 +470,63 @@ mod tests {
assert_eq!(input_path, None);
}
#[gpui::test]
async fn test_streaming_edit_global_skill_file(cx: &mut TestAppContext) {
init_test(cx);
let fs = project::FakeFs::new(cx.executor());
fs.insert_tree(path!("/root"), json!({})).await;
let skill_dir = agent_skills::global_skills_dir().join("my-skill");
fs.insert_tree(&skill_dir, json!({ "SKILL.md": "old content\n" }))
.await;
let (edit_tool, _project, _action_log, fs, _thread) =
setup_test_with_fs(cx, fs, &[path!("/root").as_ref()]).await;
let input_path = PathBuf::from("~")
.join(".agents")
.join("skills")
.join("my-skill")
.join("SKILL.md");
let skill_file = agent_skills::global_skills_dir()
.join("my-skill")
.join("SKILL.md");
let (event_stream, mut event_rx) = ToolCallEventStream::test();
let task = cx.update(|cx| {
edit_tool.clone().run(
ToolInput::resolved(EditFileToolInput {
path: input_path,
edits: vec![Edit {
old_text: "old content".into(),
new_text: "new content".into(),
}],
}),
event_stream,
cx,
)
});
event_rx.expect_update_fields().await;
let auth = event_rx.expect_authorization().await;
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
);
auth.response
.send(acp_thread::SelectedPermissionOutcome::new(
acp::PermissionOptionId::new("allow"),
acp::PermissionOptionKind::AllowOnce,
))
.expect("authorization response should send");
let EditFileToolOutput::Success { new_text, .. } = task.await.unwrap() else {
panic!("expected success");
};
assert_eq!(new_text, "new content\n");
assert_eq!(fs.load(&skill_file).await.unwrap(), "new content\n");
}
#[gpui::test]
async fn test_streaming_edit_failed_match(cx: &mut TestAppContext) {
let (edit_tool, _project, _action_log, _fs, _thread) =
@ -486,6 +556,69 @@ mod tests {
);
}
/// When the edit fails after a session is created but before any edits are
/// actually applied (e.g., the first `old_text` doesn't match), the empty
/// diff placeholder in the UI should be replaced with the error message.
#[gpui::test]
async fn test_streaming_edit_surfaces_error_when_no_edits_applied(cx: &mut TestAppContext) {
async fn find_first_text_content_in_events(
receiver: &mut crate::ToolCallEventStreamReceiver,
) -> Option<String> {
use futures::StreamExt as _;
while let Some(event) = receiver.next().await {
let Ok(crate::ThreadEvent::ToolCallUpdate(
acp_thread::ToolCallUpdate::UpdateFields(update),
)) = event
else {
continue;
};
let Some(content) = update.fields.content else {
continue;
};
for item in content {
if let acp::ToolCallContent::Content(c) = item
&& let acp::ContentBlock::Text(text) = c.content
{
return Some(text.text);
}
}
}
None
}
let (edit_tool, _project, _action_log, _fs, _thread) =
setup_test(cx, json!({"file.txt": "hello world"})).await;
let (event_stream, mut receiver) = ToolCallEventStream::test();
let task = cx.update(|cx| {
edit_tool.clone().run(
ToolInput::resolved(EditFileToolInput {
path: "root/file.txt".into(),
edits: vec![Edit {
old_text: "nonexistent text that is not in the file".into(),
new_text: "replacement".into(),
}],
}),
event_stream,
cx,
)
});
let EditFileToolOutput::Error { error, diff, .. } = task.await.unwrap_err() else {
panic!("expected error");
};
assert!(
diff.is_empty(),
"sanity check: no edits should have been applied",
);
let content_text = find_first_text_content_in_events(&mut receiver).await;
assert_eq!(
content_text.as_deref(),
Some(error.as_str()),
"expected the failure message to be surfaced as tool call content",
);
}
#[gpui::test]
async fn test_streaming_early_buffer_open(cx: &mut TestAppContext) {
let (edit_tool, _project, _action_log, _fs, _thread) =
@ -2475,7 +2608,8 @@ mod tests {
cx.run_until_parked();
let changed = action_log.read_with(cx, |log, cx| log.changed_buffers(cx));
let changed =
action_log.read_with(cx, |log, cx| log.changed_buffers(cx).collect::<Vec<_>>());
assert!(
!changed.is_empty(),
"action_log.changed_buffers() should be non-empty after streaming edit,

View file

@ -2,6 +2,7 @@ mod reindent;
mod streaming_fuzzy_matcher;
mod streaming_parser;
use super::tool_permissions::resolve_creatable_global_skill_path;
use crate::{Thread, ToolCallEventStream};
use acp_thread::Diff;
use action_log::ActionLog;
@ -277,6 +278,7 @@ pub(crate) enum EditSessionResult {
pub(crate) async fn run_session(
result: EditSessionResult,
event_stream: &ToolCallEventStream,
cx: &mut AsyncApp,
) -> Result<EditSessionOutput, EditSessionOutput> {
match result {
@ -302,6 +304,11 @@ pub(crate) async fn run_session(
.ensure_buffer_saved(&session.buffer, cx)
.await;
let (_new_text, diff) = session.compute_new_text_and_diff(cx).await;
if diff.is_empty() {
event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
acp::ToolCallContent::Content(acp::Content::new(error.clone())),
]));
}
Err(EditSessionOutput::Error {
error,
input_path: Some(session.input_path),
@ -311,11 +318,16 @@ pub(crate) async fn run_session(
EditSessionResult::Failed {
error,
session: None,
} => Err(EditSessionOutput::Error {
error,
input_path: None,
diff: String::new(),
}),
} => {
event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
acp::ToolCallContent::Content(acp::Content::new(error.clone())),
]));
Err(EditSessionOutput::Error {
error,
input_path: None,
diff: String::new(),
})
}
}
}
@ -352,6 +364,16 @@ pub(crate) struct EditSession {
_finalize_diff_guard: Deferred<Box<dyn FnOnce()>>,
}
/// The destination of an edit session, identified by its absolute path on
/// disk. `project_path` is `Some` for files that live inside one of the
/// project's worktrees (i.e. that the standard project-path machinery can
/// resolve), and `None` for global skill files reached through the
/// `~/.agents/skills` allowlist.
struct EditSessionTarget {
abs_path: PathBuf,
project_path: Option<ProjectPath>,
}
enum Pipeline {
Write(WritePipeline),
Edit(EditPipeline),
@ -639,16 +661,34 @@ impl EditSession {
event_stream: &ToolCallEventStream,
cx: &mut AsyncApp,
) -> Result<Self, String> {
let project_path = cx.update(|cx| resolve_path(mode, &path, &context.project, cx))?;
let target = if let Some(abs_path) =
resolve_global_skill_path_for_edit_session(mode, &path, &context, cx).await?
{
EditSessionTarget {
abs_path,
project_path: None,
}
} else {
let project_path = cx.update(|cx| resolve_path(mode, &path, &context.project, cx))?;
let Some(abs_path) =
cx.update(|cx| context.project.read(cx).absolute_path(&project_path, cx))
else {
return Err(format!(
"Worktree at '{}' does not exist",
path.to_string_lossy()
));
let Some(abs_path) =
cx.update(|cx| context.project.read(cx).absolute_path(&project_path, cx))
else {
return Err(format!(
"Worktree at '{}' does not exist",
path.to_string_lossy()
));
};
EditSessionTarget {
abs_path,
project_path: Some(project_path),
}
};
let EditSessionTarget {
abs_path,
project_path,
} = target;
event_stream.update_fields(
ToolCallUpdateFields::new().locations(vec![ToolCallLocation::new(abs_path.clone())]),
@ -658,11 +698,20 @@ impl EditSession {
.await
.map_err(|e| e.to_string())?;
let buffer = context
.project
.update(cx, |project, cx| project.open_buffer(project_path, cx))
.await
.map_err(|e| e.to_string())?;
let buffer = match project_path {
Some(project_path) => context
.project
.update(cx, |project, cx| project.open_buffer(project_path, cx))
.await
.map_err(|e| e.to_string())?,
None => context
.project
.update(cx, |project, cx| {
project.open_local_buffer(abs_path.clone(), cx)
})
.await
.map_err(|e| e.to_string())?,
};
let file_changed_since_last_read =
ensure_buffer_saved(&buffer, &abs_path, mode, &context, event_stream, cx).await?;
@ -1055,6 +1104,72 @@ async fn resolve_dirty_buffer(
Ok(())
}
/// Mirrors [`resolve_path`]'s pre-auth validation for the global-skill
/// branch: returns `Ok(Some(abs_path))` if the path lives under
/// `~/.agents/skills` and is in a valid state for the requested mode,
/// `Ok(None)` if the path isn't a global skill at all (so the caller should
/// fall through to project-path resolution), or `Err(message)` if the path
/// is a global skill but can't be used (missing in Edit mode, parent
/// missing in Write mode, etc.).
///
/// Errors returned from here surface to the model as tool-result errors
/// without prompting the user — same contract as [`resolve_path`]. The
/// idea is that "file doesn't exist" or "parent isn't a directory" are
/// model mistakes, not decisions the user should be asked to approve.
async fn resolve_global_skill_path_for_edit_session(
mode: EditSessionMode,
path: &PathBuf,
context: &EditSessionContext,
cx: &mut AsyncApp,
) -> Result<Option<PathBuf>, String> {
let fs = context
.project
.read_with(cx, |project, _cx| project.fs().clone());
let Some(abs_path) = resolve_creatable_global_skill_path(path, fs.as_ref()).await else {
return Ok(None);
};
match mode {
EditSessionMode::Edit => {
let metadata = fs
.metadata(&abs_path)
.await
.map_err(|e| format!("Can't edit file: {e}"))?
.ok_or_else(|| "Can't edit file: path not found".to_string())?;
if metadata.is_dir {
return Err("Can't edit file: path is a directory".to_string());
}
}
EditSessionMode::Write => {
if let Some(metadata) = fs
.metadata(&abs_path)
.await
.map_err(|e| format!("Can't write to file: {e}"))?
{
if metadata.is_dir {
return Err("Can't write to file: path is a directory".to_string());
}
} else {
let parent_path = abs_path
.parent()
.ok_or_else(|| "Can't create file: incorrect path".to_string())?;
let parent_metadata = fs
.metadata(parent_path)
.await
.map_err(|e| format!("Can't create file: {e}"))?
.ok_or_else(|| {
"Can't create file: parent directory doesn't exist".to_string()
})?;
if !parent_metadata.is_dir {
return Err("Can't create file: parent is not a directory".to_string());
}
}
}
}
Ok(Some(abs_path))
}
fn resolve_path(
mode: EditSessionMode,
path: &PathBuf,

View file

@ -113,7 +113,7 @@ impl StreamingParser {
{
if partial.new_text.is_some() && !state.buffer_new_text_until_old_text_done {
// new_text appeared after old_text, so old_text is done — emit everything.
let start = state.old_text_emitted_len.min(old_text.len());
let start = find_char_boundary(old_text, state.old_text_emitted_len);
let chunk = normalize_done_chunk(old_text[start..].to_string());
state.old_text_done = true;
state.old_text_emitted_len = old_text.len();
@ -124,9 +124,10 @@ impl StreamingParser {
});
} else {
let safe_end = safe_emit_end_for_edit_text(old_text);
let safe_start = find_char_boundary(old_text, state.old_text_emitted_len);
if safe_end > state.old_text_emitted_len {
let chunk = old_text[state.old_text_emitted_len..safe_end].to_string();
if safe_end > safe_start {
let chunk = old_text[safe_start..safe_end].to_string();
state.old_text_emitted_len = safe_end;
events.push(EditEvent::OldTextChunk {
edit_index: index,
@ -143,9 +144,10 @@ impl StreamingParser {
&& !state.new_text_done
{
let safe_end = safe_emit_end_for_edit_text(new_text);
let safe_start = find_char_boundary(new_text, state.new_text_emitted_len);
if safe_end > state.new_text_emitted_len {
let chunk = new_text[state.new_text_emitted_len..safe_end].to_string();
if safe_end > safe_start {
let chunk = new_text[safe_start..safe_end].to_string();
state.new_text_emitted_len = safe_end;
events.push(EditEvent::NewTextChunk {
edit_index: index,
@ -343,8 +345,10 @@ impl StreamingParser {
/// held back because it may be an artifact of the partial JSON fixer closing
/// an incomplete escape sequence (e.g. turning a half-received `\n` into `\\`).
/// The next partial will reveal the correct character.
///
/// The returned position is always a valid UTF-8 character boundary.
fn safe_emit_end(text: &str) -> usize {
if text.as_bytes().last() == Some(&b'\\') {
if text.ends_with('\\') {
text.len() - 1
} else {
text.len()
@ -353,13 +357,35 @@ fn safe_emit_end(text: &str) -> usize {
fn safe_emit_end_for_edit_text(text: &str) -> usize {
let safe_end = safe_emit_end(text);
if safe_end > 0 && text.as_bytes()[safe_end - 1] == b'\n' {
// Use string slicing to check the last character, ensuring we respect UTF-8 boundaries.
if safe_end > 0 && text[..safe_end].ends_with('\n') {
safe_end - 1
} else {
safe_end
}
}
/// Finds a valid UTF-8 character boundary at or before the target position.
///
/// When streaming partial JSON, the text structure can change between updates
/// (e.g., an escape sequence being completed). This means a byte position that
/// was valid in one partial may land inside a multi-byte character in the next.
/// This function finds the nearest valid boundary at or before the target.
fn find_char_boundary(text: &str, target: usize) -> usize {
if target >= text.len() {
return text.len();
}
if text.is_char_boundary(target) {
return target;
}
// Walk backwards to find a valid boundary.
let mut pos = target;
while pos > 0 && !text.is_char_boundary(pos) {
pos -= 1;
}
pos
}
fn normalize_done_chunk(mut chunk: String) -> String {
if chunk.ends_with('\n') {
chunk.pop();
@ -1146,4 +1172,77 @@ mod tests {
}]
);
}
#[test]
fn test_multibyte_char_with_trailing_backslash() {
// Reproduces a panic where the stored `old_text_emitted_len` from a previous
// partial lands inside a multi-byte UTF-8 character in the current partial.
//
// Scenario: The JSON fixer produces a literal backslash when the stream cuts
// mid-escape. If the *next* partial replaces that backslash with a multi-byte
// character (e.g., em-dash '—'), the stored byte position is no longer valid.
let mut parser = StreamingParser::default();
// First partial: text ends with backslash (held back by safe_emit_end).
// "abc" = 3 bytes, backslash held back, so emitted_len = 3.
let events = parser.push_edits(&[PartialEdit {
old_text: Some("abc\\".into()),
new_text: None,
}]);
assert_eq!(
events.as_slice(),
&[EditEvent::OldTextChunk {
edit_index: 0,
chunk: "abc".into(),
done: false,
}]
);
// Second partial: the backslash is replaced by em-dash '—' (3 bytes: E2 80 94).
// "ab—" = 2 + 3 = 5 bytes total, with em-dash at bytes 2..5.
// The stored emitted_len (3) is inside the em-dash!
// This should NOT panic.
let events = parser.push_edits(&[PartialEdit {
old_text: Some("ab—".into()),
new_text: None,
}]);
// The parser should handle this gracefully.
let _ = events;
}
#[test]
fn test_emitted_len_inside_multibyte_char_boundary() {
// More direct reproduction: emitted_len points inside a multi-byte character.
//
// This can happen when:
// 1. First partial has text where byte N is a valid boundary
// 2. Second partial has *different* text where byte N is inside a multi-byte char
let mut parser = StreamingParser::default();
// First partial: "ab" (2 bytes), backslash held back.
// After processing: emitted_len = 2
let events = parser.push_edits(&[PartialEdit {
old_text: Some("ab\\".into()),
new_text: None,
}]);
assert_eq!(
events.as_slice(),
&[EditEvent::OldTextChunk {
edit_index: 0,
chunk: "ab".into(),
done: false,
}]
);
// Second partial: "a—" where em-dash starts at byte 1 and spans bytes 1-3.
// Stored emitted_len = 2, but byte 2 is inside the em-dash!
// This should NOT panic.
let events = parser.push_edits(&[PartialEdit {
old_text: Some("a—".into()),
new_text: None,
}]);
// The parser should handle this gracefully.
// We don't care exactly what it emits, just that it doesn't panic.
let _ = events;
}
}

View file

@ -371,6 +371,7 @@ impl EditToolTest {
available_tools: tool_names,
model_name: None,
date: chrono::Local::now().format("%Y-%m-%d").to_string(),
user_agents_md: None,
};
let templates = Templates::new();
template.render(&templates)?

View file

@ -230,6 +230,7 @@ impl TerminalToolTest {
available_tools: tool_names,
model_name: None,
date: chrono::Local::now().format("%Y-%m-%d").to_string(),
user_agents_md: None,
};
template.render(&Templates::new())?
};

View file

@ -201,6 +201,7 @@ impl WriteToolTest {
available_tools: tool_names,
model_name: None,
date: chrono::Local::now().format("%Y-%m-%d").to_string(),
user_agents_md: None,
};
let templates = Templates::new();
template.render(&templates)?

View file

@ -18,11 +18,13 @@ use std::sync::Arc;
use util::markdown::MarkdownInlineCode;
/// Lists files and directories in a given path. Prefer the `grep` or `find_path` tools when searching the codebase.
///
/// The only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct ListDirectoryToolInput {
/// The fully-qualified path of the directory to list in the project.
///
/// This path should never be absolute, and the first component of the path should always be a root directory in a project.
/// This path should never be absolute, and the first component of the path should always be a root directory in a project, unless it's a global agent skill directory under `~/.agents/skills`.
///
/// <example>
/// If the project has the following root directories:
@ -41,6 +43,10 @@ pub struct ListDirectoryToolInput {
///
/// If you wanna list contents in the directory `foo/baz`, you should use the path `foo/baz`.
/// </example>
///
/// <example>
/// To list a global agent skill directory, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill`.
/// </example>
pub path: String,
}
@ -234,7 +240,7 @@ impl AgentTool for ListDirectoryTool {
// Fast path: a global skill resource lives outside any worktree, so
// standard project-path resolution would refuse it. If the path
// resolves under the global skills tree, list it directly.
// expands and resolves under the global skills tree, list it directly.
if let Some(skill_path) =
resolve_global_skill_path(Path::new(&input.path), fs.as_ref()).await
{

View file

@ -18,6 +18,80 @@ fn tool_content_err(e: impl std::fmt::Display) -> LanguageModelToolResultContent
LanguageModelToolResultContent::from(e.to_string())
}
/// Resolves the optional `start_line` / `end_line` inputs from the tool schema
/// to a concrete 1-indexed, inclusive `(start, end)` line range:
///
/// - `start` defaults to 1 and is clamped to `>= 1` (the model occasionally passes
/// `0` despite instructions to be 1-indexed).
/// - `end` defaults to `u32::MAX` and is clamped to `>= start`, so callers always
/// read at least one line even when the model passes `end < start`.
///
/// Callers translate this 1-indexed inclusive range to whichever coordinate
/// system their slicing API wants (e.g. 0-indexed exclusive row ranges for
/// `Buffer::text_for_range`).
fn resolve_line_range(start_line: Option<u32>, end_line: Option<u32>) -> (u32, u32) {
let start = start_line.unwrap_or(1).max(1);
let end = end_line.unwrap_or(u32::MAX).max(start);
(start, end)
}
/// Prefixes each line of `text` with its line number in `cat -n` format:
/// the line number is right-aligned in a 6-character field, followed by a
/// single tab, followed by the line's original content (including its
/// trailing newline if present). Numbering starts at `start_line`.
///
/// This format matches what the model expects in the edit tool, where the
/// line number prefix is `line number + tab` and everything after the tab is
/// the actual file content to match.
fn format_with_line_numbers(text: &str, start_line: u32) -> String {
if text.is_empty() {
return String::new();
}
let mut output = String::with_capacity(text.len() + text.len() / 4);
write_lines_numbered(&mut output, std::iter::once(text), start_line);
output
}
/// Streams `cat -n`-style line-numbered output directly into `output` from an
/// iterator of string slices. Chunks do not need to align to line boundaries:
/// a single chunk may contain multiple newlines, span multiple lines, or end
/// mid-line. This lets callers consume `Buffer::text_for_range`'s `Chunks`
/// iterator without materializing the unnumbered text first.
fn write_lines_numbered<'a>(
output: &mut String,
chunks: impl IntoIterator<Item = &'a str>,
start_line: u32,
) {
use std::fmt::Write as _;
let mut line_number = start_line;
let mut at_line_start = true;
for chunk in chunks {
let mut rest = chunk;
while !rest.is_empty() {
if at_line_start {
// Writes to a `String` are infallible, so the `Result` can be ignored.
let _ = write!(output, "{line_number:>6}\t");
at_line_start = false;
}
match rest.find('\n') {
Some(nl) => {
let (head, tail) = rest.split_at(nl + 1);
output.push_str(head);
line_number = line_number.saturating_add(1);
at_line_start = true;
rest = tail;
}
None => {
output.push_str(rest);
break;
}
}
}
}
}
/// Read a file under the global skills directory directly via the filesystem,
/// bypassing project/worktree resolution. Used for skill resources that live
/// outside any worktree.
@ -40,26 +114,21 @@ async fn read_global_skill_file(
.line(start_line.map(|line| line.saturating_sub(1))),
]));
let result_text = if start_line.is_some() || end_line.is_some() {
// Mirror the line-range semantics of the buffer-backed path: 1-indexed,
// start clamped to >= 1, end exclusive of the next line, and always
// returning at least one line. `split_inclusive` keeps each line's
// terminator attached, so CRLF stays CRLF and the trailing newline of
// the last returned line is preserved — matching `Buffer::text_for_range`.
let start = start_line.unwrap_or(1).max(1);
let mut end = end_line.unwrap_or(u32::MAX);
if end < start {
end = start;
}
let (raw_text, first_line_number) = if start_line.is_some() || end_line.is_some() {
// `split_inclusive` keeps each line's terminator attached, so CRLF stays
// CRLF and the trailing newline of the last returned line is preserved —
// matching `Buffer::text_for_range` in the buffer-backed path.
let (start, end) = resolve_line_range(start_line, end_line);
let lines: Vec<&str> = content.split_inclusive('\n').collect();
let start_idx = (start as usize).saturating_sub(1).min(lines.len());
let end_idx = (end as usize).min(lines.len()).max(start_idx);
lines[start_idx..end_idx].concat()
(lines[start_idx..end_idx].concat(), start)
} else {
content
(content, 1)
};
let result_text = format_with_line_numbers(&raw_text, first_line_number);
let markdown = MarkdownCodeBlock {
tag: requested_path,
text: &result_text,
@ -86,11 +155,13 @@ use crate::{AgentTool, ToolCallEventStream, ToolInput, outline};
/// Do NOT retry reading the same file without line numbers if you receive an outline.
/// - This tool supports reading image files. Supported formats: PNG, JPEG, WebP, GIF, BMP, TIFF.
/// Image files are returned as visual content that you can analyze directly.
///
/// The only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct ReadFileToolInput {
/// The relative path of the file to read.
///
/// This path should never be absolute, and the first component of the path should always be a root directory in a project.
/// This path should never be absolute, and the first component of the path should always be a root directory in a project, unless it's a global agent skill under `~/.agents/skills`.
///
/// <example>
/// If the project has the following root directories:
@ -101,6 +172,10 @@ pub struct ReadFileToolInput {
/// If you want to access `file.txt` in `directory1`, you should use the path `directory1/file.txt`.
/// If you want to access `file.txt` in `directory2`, you should use the path `directory2/file.txt`.
/// </example>
///
/// <example>
/// To read a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.
/// </example>
pub path: String,
/// Optional line number to start reading on (1-based index)
#[serde(default)]
@ -182,8 +257,8 @@ impl AgentTool for ReadFileTool {
.map_err(tool_content_err)?;
let fs = project.read_with(cx, |project, _cx| project.fs().clone());
// Fast path: if the model passes an absolute path that resolves
// under the global skills directory, read it directly via the
// Fast path: if the model passes a path that resolves under the
// global skills directory, read it directly via the
// filesystem. Global skills live outside any worktree, so the
// standard project-path machinery would refuse them.
if let Some(skill_path) =
@ -338,32 +413,42 @@ impl AgentTool for ReadFileTool {
}
let mut anchor = None;
let mut is_outline_response = false;
// Check if specific line ranges are provided
let result = if input.start_line.is_some() || input.end_line.is_some() {
let result = buffer.read_with(cx, |buffer, _cx| {
// .max(1) because despite instructions to be 1-indexed, sometimes the model passes 0.
let start = input.start_line.unwrap_or(1).max(1);
let result_text = buffer.read_with(cx, |buffer, _cx| {
let (start, end) = resolve_line_range(input.start_line, input.end_line);
let start_row = start - 1;
if start_row <= buffer.max_point().row {
let column = buffer.line_indent_for_row(start_row).raw_len();
anchor = Some(buffer.anchor_before(Point::new(start_row, column)));
}
let mut end_row = input.end_line.unwrap_or(u32::MAX);
if end_row <= start_row {
end_row = start_row + 1; // read at least one lines
}
let start = buffer.anchor_before(Point::new(start_row, 0));
let end = buffer.anchor_before(Point::new(end_row, 0));
buffer.text_for_range(start..end).collect::<String>()
// `end` is 1-indexed inclusive; `Point` rows are 0-indexed.
// Using `end` directly as the (exclusive) end row is the
// standard inclusive→exclusive translation, and since
// `resolve_line_range` guarantees `end >= start`, we always
// read at least one line.
let start_anchor = buffer.anchor_before(Point::new(start_row, 0));
let end_anchor = buffer.anchor_before(Point::new(end, 0));
// Stream the numbered output directly from the buffer's
// chunk iterator so the unnumbered range is never
// materialized as its own `String`.
let mut output = String::new();
write_lines_numbered(
&mut output,
buffer.text_for_range(start_anchor..end_anchor),
start,
);
output
});
action_log.update(cx, |log, cx| {
log.buffer_read(buffer.clone(), cx);
});
Ok(result.into())
Ok(result_text.into())
} else {
// No line ranges specified, so check file size to see if it's too big.
let buffer_content = outline::get_buffer_content_or_outline(
@ -377,7 +462,10 @@ impl AgentTool for ReadFileTool {
log.buffer_read(buffer.clone(), cx);
});
if buffer_content.is_outline {
is_outline_response = buffer_content.is_synthetic;
if buffer_content.is_synthetic {
Ok(formatdoc! {"
SUCCESS: File outline retrieved. This file is too large to read all at once, so the outline below shows the file's structure with line numbers.
@ -391,7 +479,7 @@ impl AgentTool for ReadFileTool {
}
.into())
} else {
Ok(buffer_content.text.into())
Ok(format_with_line_numbers(&buffer_content.text, 1).into())
}
};
@ -409,11 +497,12 @@ impl AgentTool for ReadFileTool {
}
if let Ok(LanguageModelToolResultContent::Text(text)) = &result {
let text: &str = text;
let markdown = MarkdownCodeBlock {
tag: &input.path,
text,
}
.to_string();
// For outline responses, omit the path tag so the markdown renderer
// does not invoke tree-sitter syntax highlighting against pseudo-code
// outline text. The outline is not valid source for the file's language,
// so highlighting would be both expensive and incorrect.
let tag: &str = if is_outline_response { "" } else { &input.path };
let markdown = MarkdownCodeBlock { tag, text }.to_string();
event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
acp::ToolCallContent::Content(acp::Content::new(markdown)),
]));
@ -423,6 +512,27 @@ impl AgentTool for ReadFileTool {
result
})
}
fn replay(
&self,
input: Self::Input,
output: Self::Output,
event_stream: ToolCallEventStream,
_cx: &mut App,
) -> Result<()> {
if let LanguageModelToolResultContent::Text(text) = output {
let markdown = MarkdownCodeBlock {
tag: &input.path,
text: &text,
}
.to_string();
event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
acp::ToolCallContent::Content(acp::Content::new(markdown)),
]));
}
Ok(())
}
}
#[cfg(test)]
@ -526,7 +636,10 @@ mod test {
)
})
.await;
assert_eq!(result.unwrap(), "This is a small file content".into());
assert_eq!(
result.unwrap(),
" 1\tThis is a small file content".into()
);
}
#[gpui::test]
@ -610,6 +723,172 @@ mod test {
);
}
// The outline returned for a large file is not valid source for the file's
// language, so the UI-side markdown wrapping must omit the path tag.
// Otherwise the markdown renderer routes the fenced block through
// `CodeBlockKind::FencedSrc`, resolves the file's language, and runs
// tree-sitter against pseudo-code outline text on every paint.
#[gpui::test]
async fn test_outline_response_uses_untagged_code_block(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/root"),
json!({
"large_file.rs": (0..1000).map(|i| format!("struct Test{} {{\n a: u32,\n b: usize,\n}}", i)).collect::<Vec<_>>().join("\n")
}),
)
.await;
let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
let language_registry = project.read_with(cx, |project, _| project.languages().clone());
language_registry.add(language::rust_lang());
let action_log = cx.new(|_| ActionLog::new(project.clone()));
let tool = Arc::new(ReadFileTool::new(project, action_log, true));
let (event_stream, mut rx) = ToolCallEventStream::test();
let result = cx
.update(|cx| {
let input = ReadFileToolInput {
path: "root/large_file.rs".into(),
start_line: None,
end_line: None,
};
tool.clone()
.run(ToolInput::resolved(input), event_stream, cx)
})
.await
.unwrap();
// Sanity-check: the file is large enough to trigger the outline branch.
assert!(
result
.to_str()
.unwrap()
.starts_with("SUCCESS: File outline retrieved."),
"expected outline response, got: {:?}",
result.to_str().unwrap()
);
// The first update carries the location; the second carries the
// markdown content destined for the tool-call UI.
let _location_update = rx.expect_update_fields().await;
let content_update = rx.expect_update_fields().await;
let content_blocks = content_update.content.expect("expected content update");
let acp::ToolCallContent::Content(content) = content_blocks
.first()
.expect("expected at least one content block")
else {
panic!("expected ContentBlock, got {:?}", content_blocks.first());
};
let acp::ContentBlock::Text(text) = &content.content else {
panic!("expected text content block, got {:?}", content.content);
};
assert!(
text.text.starts_with("```\n"),
"outline response must use an untagged fenced code block; got first line: {:?}",
text.text.lines().next()
);
assert!(
!text.text.starts_with("```root/"),
"outline response must not include the file path as a code block tag"
);
}
// The full-file (non-outline) response should still tag the code block
// with the file path so the markdown renderer can resolve the file's
// language for syntax highlighting.
#[gpui::test]
async fn test_full_file_response_keeps_path_tag(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/root"),
json!({
"small_file.rs": "fn main() {}"
}),
)
.await;
let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
let action_log = cx.new(|_| ActionLog::new(project.clone()));
let tool = Arc::new(ReadFileTool::new(project, action_log, true));
let (event_stream, mut rx) = ToolCallEventStream::test();
cx.update(|cx| {
let input = ReadFileToolInput {
path: "root/small_file.rs".into(),
start_line: None,
end_line: None,
};
tool.clone()
.run(ToolInput::resolved(input), event_stream, cx)
})
.await
.unwrap();
let _location_update = rx.expect_update_fields().await;
let content_update = rx.expect_update_fields().await;
let content_blocks = content_update.content.expect("expected content update");
let acp::ToolCallContent::Content(content) = content_blocks
.first()
.expect("expected at least one content block")
else {
panic!("expected ContentBlock, got {:?}", content_blocks.first());
};
let acp::ContentBlock::Text(text) = &content.content else {
panic!("expected text content block, got {:?}", content.content);
};
assert!(
text.text.starts_with("```root/small_file.rs\n"),
"full-file response must tag the code block with the file path; got first line: {:?}",
text.text.lines().next()
);
}
// When a worktree is named "foo" and contains a subdirectory also named "foo",
// read_file({"path": "foo/test.txt"}) should return the file at the worktree
// root (as the tool schema promises), not the one inside the foo/ subdirectory.
#[gpui::test]
async fn test_read_file_worktree_root_not_shadowed_by_subdir(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/foo"),
json!({
"test.txt": "root content",
"foo": {
"test.txt": "subdir content"
}
}),
)
.await;
let project = Project::test(fs.clone(), [path!("/foo").as_ref()], cx).await;
let action_log = cx.new(|_| ActionLog::new(project.clone()));
let tool = Arc::new(ReadFileTool::new(project, action_log, true));
// The tool schema says the first component must be the worktree root name,
// so "foo/test.txt" means test.txt at the root of the "foo" worktree.
let result = cx
.update(|cx| {
let input = ReadFileToolInput {
path: "foo/test.txt".into(),
start_line: None,
end_line: None,
};
tool.run(
ToolInput::resolved(input),
ToolCallEventStream::test().0,
cx,
)
})
.await;
assert_eq!(result.unwrap(), " 1\troot content".into());
}
#[gpui::test]
async fn test_read_file_with_line_range(cx: &mut TestAppContext) {
init_test(cx);
@ -640,7 +919,10 @@ mod test {
)
})
.await;
assert_eq!(result.unwrap(), "Line 2\nLine 3\nLine 4\n".into());
assert_eq!(
result.unwrap(),
" 2\tLine 2\n 3\tLine 3\n 4\tLine 4\n".into()
);
}
#[gpui::test]
@ -674,7 +956,7 @@ mod test {
)
})
.await;
assert_eq!(result.unwrap(), "Line 1\nLine 2\n".into());
assert_eq!(result.unwrap(), " 1\tLine 1\n 2\tLine 2\n".into());
// end_line of 0 should result in at least 1 line
let result = cx
@ -691,7 +973,7 @@ mod test {
)
})
.await;
assert_eq!(result.unwrap(), "Line 1\n".into());
assert_eq!(result.unwrap(), " 1\tLine 1\n".into());
// when start_line > end_line, should still return at least 1 line
let result = cx
@ -708,7 +990,7 @@ mod test {
)
})
.await;
assert_eq!(result.unwrap(), "Line 3\n".into());
assert_eq!(result.unwrap(), " 3\tLine 3\n".into());
}
fn error_text(content: LanguageModelToolResultContent) -> String {
@ -942,7 +1224,7 @@ mod test {
})
.await;
assert!(result.is_ok(), "Should be able to read normal files");
assert_eq!(result.unwrap(), "Normal file content".into());
assert_eq!(result.unwrap(), " 1\tNormal file content".into());
// Path traversal attempts with .. should fail
let result = cx
@ -1112,7 +1394,7 @@ mod test {
assert_eq!(
result,
"fn main() { println!(\"Hello from worktree1\"); }".into()
" 1\tfn main() { println!(\"Hello from worktree1\"); }".into()
);
// Test reading private file in worktree1 should fail
@ -1178,7 +1460,7 @@ mod test {
assert_eq!(
result,
"export function greet() { return 'Hello from worktree2'; }".into()
" 1\texport function greet() { return 'Hello from worktree2'; }".into()
);
// Test reading private file in worktree2 should fail
@ -1488,7 +1770,10 @@ mod test {
let LanguageModelToolResultContent::Text(text) = content else {
panic!("expected text content");
};
assert_eq!(text.as_ref(), "# Spec\n\nReference body.");
assert_eq!(
text.as_ref(),
" 1\t# Spec\n 2\t\n 3\tReference body."
);
}
#[gpui::test]
@ -1535,7 +1820,7 @@ mod test {
};
// Mirrors the buffer-backed path: lines 2-3 inclusive, WITH trailing
// newline of the last returned line.
assert_eq!(text.as_ref(), "line two\nline three\n");
assert_eq!(text.as_ref(), " 2\tline two\n 3\tline three\n");
}
#[gpui::test]
@ -1580,7 +1865,7 @@ mod test {
let LanguageModelToolResultContent::Text(text) = result.unwrap() else {
panic!("expected text content");
};
assert_eq!(text.as_ref(), "Line 1\nLine 2\n");
assert_eq!(text.as_ref(), " 1\tLine 1\n 2\tLine 2\n");
}
#[gpui::test]
@ -1625,7 +1910,7 @@ mod test {
let LanguageModelToolResultContent::Text(text) = result.unwrap() else {
panic!("expected text content");
};
assert_eq!(text.as_ref(), "Line 1\n");
assert_eq!(text.as_ref(), " 1\tLine 1\n");
}
#[gpui::test]
@ -1670,7 +1955,7 @@ mod test {
let LanguageModelToolResultContent::Text(text) = result.unwrap() else {
panic!("expected text content");
};
assert_eq!(text.as_ref(), "Line 3\n");
assert_eq!(text.as_ref(), " 3\tLine 3\n");
}
#[gpui::test]
@ -1715,7 +2000,7 @@ mod test {
let LanguageModelToolResultContent::Text(text) = result.unwrap() else {
panic!("expected text content");
};
assert_eq!(text.as_ref(), "line one\r\nline two\r\n");
assert_eq!(text.as_ref(), " 1\tline one\r\n 2\tline two\r\n");
}
#[gpui::test]

View file

@ -2,6 +2,7 @@ use std::fmt::Write;
use std::sync::Arc;
use agent_client_protocol::schema as acp;
use collections::HashSet;
use gpui::{App, Entity, SharedString, Task};
use project::Project;
use schemars::JsonSchema;
@ -95,6 +96,12 @@ impl AgentTool for RenameTool {
));
}
let buffers = transaction.0.keys().cloned().collect::<HashSet<_>>();
project
.update(cx, |project, cx| project.save_buffers(buffers, cx))
.await
.map_err(|e| format!("Rename succeeded, but failed to save renamed files: {e}"))?;
let mut output = format!(
"Renamed `{}` to `{}` in {} file(s):\n",
input.symbol.symbol_name,

View file

@ -46,11 +46,12 @@ fn neutralize_envelope_tags(input: &str) -> String {
/// frontmatter), not O(total file size).
pub fn render_skill_envelope(skill: &Skill, body: &str) -> String {
let source = match &skill.source {
agent_skills::SkillSource::BuiltIn => "built-in",
agent_skills::SkillSource::Global => "global",
agent_skills::SkillSource::ProjectLocal { .. } => "project-local",
};
let worktree = match &skill.source {
agent_skills::SkillSource::Global => None,
agent_skills::SkillSource::BuiltIn | agent_skills::SkillSource::Global => None,
agent_skills::SkillSource::ProjectLocal {
worktree_root_name, ..
} => Some(worktree_root_name.clone()),
@ -200,31 +201,33 @@ impl AgentTool for SkillTool {
(skill.clone(), path_string)
};
// Read the body on demand. Bodies are not kept in memory
// between materializations — see `agent_skills::read_skill_body`.
let body = agent_skills::read_skill_body(self.fs.as_ref(), &skill.skill_file_path)
.await
.map_err(|e| SkillToolOutput::Error {
error: e.to_string(),
})?;
// For built-in skills the body is already in memory (compiled
// into the binary). For user skills, read on demand from disk.
let body = if let Some(embedded) = skill.embedded_body {
embedded.to_string()
} else {
agent_skills::read_skill_body(self.fs.as_ref(), &skill.skill_file_path)
.await
.map_err(|e| SkillToolOutput::Error {
error: e.to_string(),
})?
};
let rendered = render_skill_envelope(&skill, &body);
// Activations go through the standard tool-permission flow so
// they participate in the same Allow-Once / Always-Allow UX as
// every other built-in tool. The auth context value is the
// skill's absolute SKILL.md path so that "always allow this
// specific skill" is keyed to a specific file: editing the
// SKILL.md will change the path's content but not the path,
// so for content-change re-trust we'd want a hash too — but
// at minimum, two skills with the same name from different
// locations get independent trust grants.
let authorize = cx.update(|cx| {
let context = crate::ToolPermissionContext::new(Self::NAME, vec![skill_file_path]);
event_stream.authorize(self.initial_title(Ok(input), cx), context, cx)
});
authorize.await.map_err(|e| SkillToolOutput::Error {
error: e.to_string(),
})?;
// Built-in skills ship with Zed and are trusted by default,
// so they skip the authorization prompt. User-installed skills
// go through the standard Allow-Once / Always-Allow UX.
let is_builtin = skill.source == agent_skills::SkillSource::BuiltIn;
if !is_builtin {
let authorize = cx.update(|cx| {
let context =
crate::ToolPermissionContext::new(Self::NAME, vec![skill_file_path]);
event_stream.authorize(self.initial_title(Ok(input), cx), context, cx)
});
authorize.await.map_err(|e| SkillToolOutput::Error {
error: e.to_string(),
})?;
}
Ok(SkillToolOutput::Found { rendered })
})

View file

@ -9,9 +9,9 @@ use fs::Fs;
use gpui::{App, Entity, Task, WeakEntity};
use project::{Project, ProjectPath};
use settings::Settings;
use std::path::{Path, PathBuf};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use util::paths::component_matches_ignore_ascii_case;
use util::{normalize_path, paths::component_matches_ignore_ascii_case};
pub enum SensitiveSettingsKind {
Local,
@ -116,25 +116,80 @@ fn is_within_any_worktree(canonical_path: &Path, canonical_worktree_roots: &[Pat
.any(|root| canonical_path.starts_with(root))
}
/// If `path` is an absolute path under the global skills directory
/// (`~/.agents/skills`), return the canonicalized absolute path. Returns
/// `None` for any path that resolves outside the global skills tree, for
/// relative paths, or if the skills directory itself can't be canonicalized
/// (fail closed — better to refuse access than to compare against a
/// non-canonical path).
/// If `path` names `~/.agents/skills` or one of its descendants, return the
/// canonicalized absolute path. Returns `None` for any path that resolves
/// outside the global skills tree, for relative paths that don't start with
/// `~`, or if the skills directory itself can't be canonicalized (fail closed
/// — better to refuse access than to compare against a non-canonical path).
///
/// This is the gate that lets `read_file` / `list_directory` reach into the
/// global skills directory — which lives outside any worktree — without
/// also opening up arbitrary external paths.
pub async fn resolve_global_skill_path(path: &Path, fs: &dyn Fs) -> Option<PathBuf> {
if !path.is_absolute() {
let normalized_path = resolve_lexical_global_skill_path(path)?;
// Canonicalize both sides so symlinks can't sneak the path out of the
// skills tree (and so different but equivalent path representations
// match). The lexical check above intentionally runs first, so a
// symlinked `~/.agents/skills` root can't broaden the allowlist to every
// path under the symlink target.
let canonical_path = fs.canonicalize(&normalized_path).await.ok()?;
let canonical_skills_dir = canonical_global_skills_dir(fs).await?;
if canonical_path.starts_with(&canonical_skills_dir) {
Some(canonical_path)
} else {
None
}
}
fn expand_home_prefix(path: &Path) -> Option<PathBuf> {
if path.is_absolute() {
return Some(path.to_path_buf());
}
let mut components = path.components();
let first_component = components.next()?;
if !matches!(first_component, Component::Normal(component) if component == "~") {
return None;
}
// Canonicalize both sides so symlinks and `..` segments can't sneak the
// path out of the skills tree (and so different but equivalent path
// representations match).
let canonical_path = fs.canonicalize(path).await.ok()?;
let mut expanded = paths::home_dir().clone();
for component in components {
match component {
Component::Normal(component) => expanded.push(component),
Component::CurDir => {}
Component::ParentDir => expanded.push(".."),
Component::Prefix(_) | Component::RootDir => return None,
}
}
Some(expanded)
}
fn expand_and_normalize_absolute_path(path: &Path) -> Option<PathBuf> {
let expanded_path = expand_home_prefix(path)?;
let normalized_path = normalize_path(&expanded_path);
normalized_path.is_absolute().then_some(normalized_path)
}
fn resolve_lexical_global_skill_path(path: &Path) -> Option<PathBuf> {
let normalized_path = expand_and_normalize_absolute_path(path)?;
let normalized_skills_dir = normalize_path(&agent_skills::global_skills_dir());
normalized_path
.starts_with(&normalized_skills_dir)
.then_some(normalized_path)
}
/// If `path` names `~/.agents/skills` or one of its descendants, return a
/// canonical absolute path for it. Unlike [`resolve_global_skill_path`], the
/// target path may or may not exist on disk yet — the caller decides whether
/// to read, write, or create it. Returns `None` for any other path, including
/// siblings of the global skills tree or paths that would escape it with `..`
/// or symlinks.
pub async fn resolve_creatable_global_skill_path(path: &Path, fs: &dyn Fs) -> Option<PathBuf> {
let normalized_path = resolve_lexical_global_skill_path(path)?;
let canonical_path = canonicalize_with_ancestors(&normalized_path, fs).await?;
let canonical_skills_dir = canonical_global_skills_dir(fs).await?;
if canonical_path.starts_with(&canonical_skills_dir) {
@ -773,6 +828,189 @@ mod tests {
roots
}
#[gpui::test]
async fn test_resolve_creatable_global_skill_path_allows_tilde_path(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
let input_path = PathBuf::from("~")
.join(".agents")
.join("skills")
.join("my-skill");
let expected_path = agent_skills::global_skills_dir().join("my-skill");
let resolved = resolve_creatable_global_skill_path(&input_path, fs.as_ref())
.await
.expect("global skill path should resolve");
assert_eq!(resolved, expected_path);
}
#[gpui::test]
async fn test_resolve_global_skill_path_allows_tilde_path(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
let skill_file = agent_skills::global_skills_dir()
.join("my-skill")
.join("SKILL.md");
fs.insert_tree(
skill_file
.parent()
.expect("skill file should have a parent"),
json!({ "SKILL.md": "---\nname: my-skill\ndescription: test\n---" }),
)
.await;
let input_path = PathBuf::from("~")
.join(".agents")
.join("skills")
.join("my-skill")
.join("SKILL.md");
let resolved = resolve_global_skill_path(&input_path, fs.as_ref())
.await
.expect("global skill file should resolve");
assert_eq!(resolved, skill_file);
}
#[gpui::test]
async fn test_resolve_creatable_global_skill_path_rejects_other_home_paths(
cx: &mut TestAppContext,
) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
let sibling_path = PathBuf::from("~").join(".agents").join("not-skills");
let escaped_path = PathBuf::from("~")
.join(".agents")
.join("skills")
.join("..")
.join("not-skills");
assert!(
resolve_creatable_global_skill_path(&sibling_path, fs.as_ref())
.await
.is_none()
);
assert!(
resolve_creatable_global_skill_path(&escaped_path, fs.as_ref())
.await
.is_none()
);
}
#[gpui::test]
async fn test_resolve_creatable_global_skill_path_rejects_symlink_escape(
cx: &mut TestAppContext,
) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
let skills_dir = agent_skills::global_skills_dir();
fs.create_dir(&skills_dir)
.await
.expect("global skills directory should be created");
fs.create_dir(path!("/external").as_ref())
.await
.expect("external directory should be created");
fs.create_symlink(&skills_dir.join("link"), PathBuf::from(path!("/external")))
.await
.expect("symlink should be created");
let escaped_path = PathBuf::from("~")
.join(".agents")
.join("skills")
.join("link")
.join("new-dir");
assert!(
resolve_creatable_global_skill_path(&escaped_path, fs.as_ref())
.await
.is_none()
);
}
#[gpui::test]
async fn test_global_skill_path_resolvers_reject_absolute_paths_when_skills_dir_is_symlink_to_root(
cx: &mut TestAppContext,
) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(paths::home_dir(), json!({ ".agents": {} }))
.await;
fs.insert_tree(path!("/tmp"), json!({ "outside.txt": "outside" }))
.await;
let skills_dir = agent_skills::global_skills_dir();
fs.create_symlink(&skills_dir, PathBuf::from(path!("/")))
.await
.expect("global skills directory should be symlinked to root");
let outside_path = PathBuf::from(path!("/tmp/outside.txt"));
assert!(
resolve_global_skill_path(&outside_path, fs.as_ref())
.await
.is_none(),
"existing absolute paths outside the lexical global skills tree should not resolve",
);
assert!(
resolve_creatable_global_skill_path(&outside_path, fs.as_ref())
.await
.is_none(),
"creatable absolute paths outside the lexical global skills tree should not resolve",
);
let traversed_path = PathBuf::from("~")
.join(".agents")
.join("skills")
.join("..")
.join("outside");
assert!(
resolve_creatable_global_skill_path(&traversed_path, fs.as_ref())
.await
.is_none(),
"paths that normalize outside the lexical global skills tree should not resolve",
);
}
#[gpui::test]
async fn test_global_skill_path_resolvers_reject_absolute_paths_when_skills_dir_is_symlink_to_home(
cx: &mut TestAppContext,
) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
paths::home_dir(),
json!({
".agents": {},
"outside.txt": "outside",
}),
)
.await;
let skills_dir = agent_skills::global_skills_dir();
fs.create_symlink(&skills_dir, paths::home_dir().clone())
.await
.expect("global skills directory should be symlinked to home");
let outside_path = paths::home_dir().join("outside.txt");
assert!(
resolve_global_skill_path(&outside_path, fs.as_ref())
.await
.is_none(),
"existing absolute paths outside the lexical global skills tree should not resolve",
);
assert!(
resolve_creatable_global_skill_path(&outside_path, fs.as_ref())
.await
.is_none(),
"creatable absolute paths outside the lexical global skills tree should not resolve",
);
}
#[gpui::test]
async fn test_resolve_project_path_safe_for_normal_files(cx: &mut TestAppContext) {
init_test(cx);

View file

@ -0,0 +1,140 @@
use crate::{AgentTool, Thread, ToolCallEventStream, ToolInput};
use agent_client_protocol::schema as acp;
use gpui::{App, SharedString, Task, WeakEntity};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
const MAX_TITLE_LEN: usize = 200;
/// Updates the current session title.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct UpdateTitleToolInput {
/// A concise, human-readable title for the current session.
pub title: String,
}
pub struct UpdateTitleTool {
thread: WeakEntity<Thread>,
}
impl UpdateTitleTool {
pub fn new(thread: WeakEntity<Thread>) -> Self {
Self { thread }
}
pub(crate) fn title_for_input(
input: Result<UpdateTitleToolInput, serde_json::Value>,
) -> SharedString {
let Ok(input) = input else {
return "Update title".into();
};
let Ok(title) = normalize_title(&input.title) else {
return "Update title".into();
};
format!("Update title: {title}").into()
}
}
impl AgentTool for UpdateTitleTool {
type Input = UpdateTitleToolInput;
type Output = String;
const NAME: &'static str = "update_title";
fn kind() -> acp::ToolKind {
acp::ToolKind::Think
}
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
Self::title_for_input(input)
}
fn run(
self: Arc<Self>,
input: ToolInput<Self::Input>,
_event_stream: ToolCallEventStream,
cx: &mut App,
) -> Task<Result<Self::Output, Self::Output>> {
let thread = self.thread.clone();
cx.spawn(async move |cx| {
let input = input.recv().await.map_err(|error| error.to_string())?;
let title = normalize_title(&input.title)?;
thread
.update(cx, |thread, cx| {
thread.set_title(title.into(), cx);
})
.map_err(|error| error.to_string())?;
Ok("Session title updated".to_string())
})
}
fn replay(
&self,
input: Self::Input,
_output: Self::Output,
event_stream: ToolCallEventStream,
cx: &mut App,
) -> anyhow::Result<()> {
let title = self.initial_title(Ok(input), cx).to_string();
event_stream.update_fields(acp::ToolCallUpdateFields::new().title(title));
Ok(())
}
}
fn normalize_title(title: &str) -> Result<String, String> {
let title = title.lines().next().unwrap_or("").trim();
if title.is_empty() {
return Err("Title cannot be empty".to_string());
}
Ok(util::truncate_and_trailoff(title, MAX_TITLE_LEN))
}
#[cfg(test)]
mod tests {
use super::*;
use gpui::TestAppContext;
#[test]
fn test_normalize_title() {
assert_eq!(
normalize_title(" Title from model\nignored").unwrap(),
"Title from model"
);
assert!(normalize_title(" \nignored").is_err());
}
#[gpui::test]
async fn test_initial_title(cx: &mut TestAppContext) {
let tool = UpdateTitleTool::new(WeakEntity::new_invalid());
let title = cx.update(|cx| {
tool.initial_title(
Ok(UpdateTitleToolInput {
title: "Investigate title updates".to_string(),
}),
cx,
)
});
assert_eq!(
title,
SharedString::from("Update title: Investigate title updates")
);
let title = cx.update(|cx| {
tool.initial_title(
Ok(UpdateTitleToolInput {
title: " ".to_string(),
}),
cx,
)
});
assert_eq!(title, SharedString::from("Update title"));
}
}

View file

@ -22,11 +22,13 @@ const DEFAULT_UI_TEXT: &str = "Writing file";
/// To make granular edits to an existing file, prefer the `edit_file` tool instead.
///
/// Before using this tool, verify the directory path is correct (only applicable when creating new files). Use the `list_directory` tool to verify the parent directory exists and is the correct location
///
/// The only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
pub struct WriteFileToolInput {
/// The full path of the file to create or overwrite in the project.
///
/// WARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories.
/// WARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories, unless it's a global agent skill under `~/.agents/skills`.
///
/// The following examples assume we have two root directories in the project:
/// - /a/b/backend
@ -41,6 +43,10 @@ pub struct WriteFileToolInput {
/// <example>
/// `frontend/db.js`
/// </example>
///
/// <example>
/// To create or overwrite a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.
/// </example>
pub path: PathBuf,
/// The entire content for the file.
@ -237,6 +243,7 @@ impl AgentTool for WriteFileTool {
run_session(
self.process_streaming_writes(&mut input, &event_stream, cx)
.await,
&event_stream,
cx,
)
.await
@ -272,7 +279,7 @@ mod tests {
use prompt_store::ProjectContext;
use serde_json::json;
use settings::{Settings, SettingsStore};
use std::sync::Arc;
use std::{path::PathBuf, sync::Arc};
use util::path;
use util::rel_path::{RelPath, rel_path};
@ -327,6 +334,62 @@ mod tests {
assert_eq!(*old_text, "old content");
}
#[gpui::test]
async fn test_streaming_write_global_skill_file(cx: &mut TestAppContext) {
init_test(cx);
let fs = project::FakeFs::new(cx.executor());
fs.insert_tree(path!("/root"), json!({})).await;
let skill_dir = agent_skills::global_skills_dir().join("my-skill");
fs.insert_tree(&skill_dir, json!({})).await;
let (write_tool, _project, _action_log, fs, _thread) =
setup_test_with_fs(cx, fs, &[path!("/root").as_ref()]).await;
let input_path = PathBuf::from("~")
.join(".agents")
.join("skills")
.join("my-skill")
.join("SKILL.md");
let skill_file = agent_skills::global_skills_dir()
.join("my-skill")
.join("SKILL.md");
let (event_stream, mut event_rx) = ToolCallEventStream::test();
let task = cx.update(|cx| {
write_tool.clone().run(
ToolInput::resolved(WriteFileToolInput {
path: input_path,
content: "# My Skill\n".into(),
}),
event_stream,
cx,
)
});
event_rx.expect_update_fields().await;
let auth = event_rx.expect_authorization().await;
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
);
auth.response
.send(acp_thread::SelectedPermissionOutcome::new(
acp::PermissionOptionId::new("allow"),
acp::PermissionOptionKind::AllowOnce,
))
.expect("authorization response should send");
let EditSessionOutput::Success { new_text, .. } = task.await.unwrap() else {
panic!("expected success");
};
assert_eq!(new_text, "# My Skill\n");
assert_eq!(
fs.load(&skill_file).await.unwrap().replace("\r\n", "\n"),
"# My Skill\n"
);
}
#[gpui::test]
async fn test_streaming_path_completeness_heuristic(cx: &mut TestAppContext) {
let (write_tool, _project, _action_log, _fs, _thread) =
@ -998,7 +1061,8 @@ mod tests {
cx.run_until_parked();
let changed = action_log.read_with(cx, |log, cx| log.changed_buffers(cx));
let changed =
action_log.read_with(cx, |log, cx| log.changed_buffers(cx).collect::<Vec<_>>());
assert!(
!changed.is_empty(),
"action_log.changed_buffers() should be non-empty after streaming write, \
@ -1070,7 +1134,8 @@ mod tests {
);
// Reject all edits — this should delete the newly created file
let changed = action_log.read_with(cx, |log, cx| log.changed_buffers(cx));
let changed =
action_log.read_with(cx, |log, cx| log.changed_buffers(cx).collect::<Vec<_>>());
assert!(
!changed.is_empty(),
"action_log should track the created file as changed"

View file

@ -0,0 +1,264 @@
//! User-global `AGENTS.md` support.
//!
//! Loads `~/.config/zed/AGENTS.md` (or the platform equivalent) into an
//! in-memory global, watches the file for changes, and surfaces read errors
//! through a caller-supplied notifier (so the host application can present
//! them with the same UI it uses for settings/keymap errors).
//!
//! Empty or whitespace-only files are treated as "no user `AGENTS.md`".
//! Read errors are also treated as "no user `AGENTS.md`" for the purpose of
//! the system prompt, but the error itself is exposed via
//! [`UserAgentsMdState::Error`] and forwarded to the notifier.
//!
//! The file is read in full, mirroring how project rules / repo `AGENTS.md`
//! files are loaded by the native agent today.
use std::sync::Arc;
use fs::Fs;
use futures::StreamExt as _;
use gpui::{App, BorrowAppContext, Global, SharedString, Task};
use settings::watch_config_file;
/// In-memory state of the user-global `AGENTS.md` file.
#[derive(Debug, Default, Clone)]
pub enum UserAgentsMdState {
/// The file is missing, empty, or whitespace-only.
#[default]
Empty,
/// The file was loaded successfully; carries its trimmed contents.
Loaded(SharedString),
/// The file exists but could not be read; carries the error message.
Error(SharedString),
}
impl UserAgentsMdState {
/// The trimmed `AGENTS.md` content, if the file was loaded successfully.
pub fn content(&self) -> Option<&SharedString> {
match self {
Self::Loaded(content) => Some(content),
Self::Empty | Self::Error(_) => None,
}
}
/// The most recent read error, if the file exists but could not be read.
pub fn error(&self) -> Option<&SharedString> {
match self {
Self::Error(message) => Some(message),
Self::Empty | Self::Loaded(_) => None,
}
}
}
/// Global wrapper that owns the current [`UserAgentsMdState`] plus the watcher
/// task responsible for keeping it up to date.
///
/// Holding the [`Task`] in a `_watcher` field (matching the
/// `_settings_files_watcher` pattern in `SettingsStore`) ties the watcher's
/// lifetime to the data it produces: replacing or removing the global cancels
/// the watcher.
pub struct UserAgentsMd {
state: UserAgentsMdState,
_watcher: Task<()>,
}
impl Global for UserAgentsMd {}
impl UserAgentsMd {
pub fn global(cx: &App) -> Option<&Self> {
cx.try_global::<UserAgentsMd>()
}
pub fn state(&self) -> &UserAgentsMdState {
&self.state
}
/// Convenience accessor for the trimmed `AGENTS.md` content.
pub fn content(&self) -> Option<&SharedString> {
self.state.content()
}
/// Convenience accessor for the most recent read error.
pub fn error(&self) -> Option<&SharedString> {
self.state.error()
}
}
/// Initialize the user-global `AGENTS.md` watcher.
///
/// Starts a background task that watches [`paths::agents_file`] for changes
/// and updates the [`UserAgentsMd`] global accordingly. The `on_change`
/// callback is invoked on the foreground thread whenever a new read completes,
/// so callers can show or dismiss notifications matching the
/// settings/keymap-error UI.
///
/// Calling this more than once replaces the previous global, which drops the
/// previous watcher task and cancels it.
pub fn init(
fs: Arc<dyn Fs>,
cx: &mut App,
on_change: impl Fn(&UserAgentsMdState, &mut App) + 'static,
) {
let watcher = spawn_watcher(fs, cx, on_change);
cx.set_global(UserAgentsMd {
state: UserAgentsMdState::default(),
_watcher: watcher,
});
}
fn spawn_watcher(
fs: Arc<dyn Fs>,
cx: &mut App,
on_change: impl Fn(&UserAgentsMdState, &mut App) + 'static,
) -> Task<()> {
let path = paths::agents_file().clone();
let (mut rx, watcher_task) = watch_config_file(cx.background_executor(), fs.clone(), path);
cx.spawn(async move |cx| {
// Keep the file watcher task alive for as long as this task runs.
let _watcher_task = watcher_task;
// `watch_config_file` swallows file-open errors (it emits an empty
// string when the file is missing or unreadable), so we probe the
// path on each event to tell "missing / empty" apart from "exists but
// failed to read". This mirrors how `settings.json` is watched, with
// the extra probe being the only addition: settings.json doesn't need
// to surface read errors because invalid JSON is reported separately,
// but for AGENTS.md a raw read error is the only signal we get.
while let Some(raw) = rx.next().await {
let trimmed = raw.trim();
let new_state = if !trimmed.is_empty() {
UserAgentsMdState::Loaded(SharedString::from(trimmed.to_string()))
} else if let Some(error) = probe_read_error(fs.as_ref(), paths::agents_file()).await {
UserAgentsMdState::Error(error)
} else {
UserAgentsMdState::Empty
};
cx.update(|cx| {
cx.update_global::<UserAgentsMd, _>(|md, _| {
md.state = new_state.clone();
});
on_change(&new_state, cx);
});
}
})
}
async fn probe_read_error(fs: &dyn Fs, path: &std::path::Path) -> Option<SharedString> {
match fs.load(path).await {
Ok(_) => None,
Err(err) => {
if let Some(io_err) = err.downcast_ref::<std::io::Error>()
&& io_err.kind() == std::io::ErrorKind::NotFound
{
return None;
}
Some(SharedString::from(format!("{err:#}")))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use fs::FakeFs;
use gpui::TestAppContext;
use std::cell::RefCell;
use std::rc::Rc;
async fn init_test(
cx: &mut TestAppContext,
) -> (Arc<FakeFs>, Rc<RefCell<Vec<UserAgentsMdState>>>) {
cx.executor().allow_parking();
let fs = FakeFs::new(cx.executor());
// FakeFs requires the parent directory to exist before insert_file.
let config_dir = paths::agents_file()
.parent()
.expect("AGENTS.md path should have a parent")
.to_path_buf();
fs.create_dir(&config_dir).await.unwrap();
let history: Rc<RefCell<Vec<UserAgentsMdState>>> = Rc::new(RefCell::new(vec![]));
let history_clone = history.clone();
cx.update(|cx| {
init(fs.clone(), cx, move |state, _cx| {
history_clone.borrow_mut().push(state.clone());
});
});
(fs, history)
}
#[gpui::test]
async fn loads_initial_content(cx: &mut TestAppContext) {
let path = paths::agents_file();
let (fs, history) = init_test(cx).await;
fs.insert_file(path, b"be concise".to_vec()).await;
cx.run_until_parked();
cx.update(|cx| {
assert_eq!(
UserAgentsMd::global(cx)
.and_then(|md| md.content().cloned())
.as_deref(),
Some("be concise"),
);
assert!(
UserAgentsMd::global(cx)
.and_then(|md| md.error().cloned())
.is_none()
);
});
assert!(matches!(
history.borrow().last(),
Some(UserAgentsMdState::Loaded(_))
));
}
#[gpui::test]
async fn empty_file_is_ignored(cx: &mut TestAppContext) {
let path = paths::agents_file();
let (fs, history) = init_test(cx).await;
fs.insert_file(path, b" \n \t".to_vec()).await;
cx.run_until_parked();
cx.update(|cx| {
assert!(
UserAgentsMd::global(cx)
.and_then(|md| md.content().cloned())
.is_none()
);
});
assert!(matches!(
history.borrow().last(),
Some(UserAgentsMdState::Empty)
));
}
#[gpui::test]
async fn reacts_to_file_changes(cx: &mut TestAppContext) {
let path = paths::agents_file();
let (fs, _history) = init_test(cx).await;
fs.insert_file(path, b"first".to_vec()).await;
cx.run_until_parked();
cx.update(|cx| {
assert_eq!(
UserAgentsMd::global(cx)
.and_then(|md| md.content().cloned())
.as_deref(),
Some("first"),
);
});
fs.insert_file(path, b"second".to_vec()).await;
cx.run_until_parked();
cx.update(|cx| {
assert_eq!(
UserAgentsMd::global(cx)
.and_then(|md| md.content().cloned())
.as_deref(),
Some("second"),
);
});
}
}

File diff suppressed because it is too large Load diff

View file

@ -88,22 +88,18 @@ impl AgentServer for CustomAgentServer {
let config_id = config_id.to_string();
let value_id = value_id.to_string();
update_settings_file(fs, cx, move |settings, cx| {
update_settings_file(fs, cx, move |settings, _cx| {
let settings = settings
.agent_servers
.get_or_insert_default()
.entry(agent_id.0.to_string())
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
.or_insert_with(default_settings_for_agent);
match settings {
settings::CustomAgentServerSettings::Custom {
favorite_config_option_values,
..
}
| settings::CustomAgentServerSettings::Extension {
favorite_config_option_values,
..
}
| settings::CustomAgentServerSettings::Registry {
favorite_config_option_values,
..
@ -129,16 +125,15 @@ impl AgentServer for CustomAgentServer {
fn set_default_mode(&self, mode_id: Option<acp::SessionModeId>, fs: Arc<dyn Fs>, cx: &mut App) {
let agent_id = self.agent_id();
update_settings_file(fs, cx, move |settings, cx| {
update_settings_file(fs, cx, move |settings, _cx| {
let settings = settings
.agent_servers
.get_or_insert_default()
.entry(agent_id.0.to_string())
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
.or_insert_with(default_settings_for_agent);
match settings {
settings::CustomAgentServerSettings::Custom { default_mode, .. }
| settings::CustomAgentServerSettings::Extension { default_mode, .. }
| settings::CustomAgentServerSettings::Registry { default_mode, .. } => {
*default_mode = mode_id.map(|m| m.to_string());
}
@ -161,16 +156,15 @@ impl AgentServer for CustomAgentServer {
fn set_default_model(&self, model_id: Option<acp::ModelId>, fs: Arc<dyn Fs>, cx: &mut App) {
let agent_id = self.agent_id();
update_settings_file(fs, cx, move |settings, cx| {
update_settings_file(fs, cx, move |settings, _cx| {
let settings = settings
.agent_servers
.get_or_insert_default()
.entry(agent_id.0.to_string())
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
.or_insert_with(default_settings_for_agent);
match settings {
settings::CustomAgentServerSettings::Custom { default_model, .. }
| settings::CustomAgentServerSettings::Extension { default_model, .. }
| settings::CustomAgentServerSettings::Registry { default_model, .. } => {
*default_model = model_id.map(|m| m.to_string());
}
@ -205,20 +199,17 @@ impl AgentServer for CustomAgentServer {
cx: &App,
) {
let agent_id = self.agent_id();
update_settings_file(fs, cx, move |settings, cx| {
update_settings_file(fs, cx, move |settings, _cx| {
let settings = settings
.agent_servers
.get_or_insert_default()
.entry(agent_id.0.to_string())
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
.or_insert_with(default_settings_for_agent);
let favorite_models = match settings {
settings::CustomAgentServerSettings::Custom {
favorite_models, ..
}
| settings::CustomAgentServerSettings::Extension {
favorite_models, ..
}
| settings::CustomAgentServerSettings::Registry {
favorite_models, ..
} => favorite_models,
@ -258,22 +249,18 @@ impl AgentServer for CustomAgentServer {
let agent_id = self.agent_id();
let config_id = config_id.to_string();
let value_id = value_id.map(|s| s.to_string());
update_settings_file(fs, cx, move |settings, cx| {
update_settings_file(fs, cx, move |settings, _cx| {
let settings = settings
.agent_servers
.get_or_insert_default()
.entry(agent_id.0.to_string())
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
.or_insert_with(default_settings_for_agent);
match settings {
settings::CustomAgentServerSettings::Custom {
default_config_options,
..
}
| settings::CustomAgentServerSettings::Extension {
default_config_options,
..
}
| settings::CustomAgentServerSettings::Registry {
default_config_options,
..
@ -307,10 +294,6 @@ impl AgentServer for CustomAgentServer {
default_config_options,
..
}
| project::agent_server_store::CustomAgentServerSettings::Extension {
default_config_options,
..
}
| project::agent_server_store::CustomAgentServerSettings::Registry {
default_config_options,
..
@ -422,28 +405,14 @@ fn is_registry_agent(agent_id: impl Into<AgentId>, cx: &App) -> bool {
is_in_registry || is_settings_registry
}
fn default_settings_for_agent(
agent_id: impl Into<AgentId>,
cx: &App,
) -> settings::CustomAgentServerSettings {
if is_registry_agent(agent_id, cx) {
settings::CustomAgentServerSettings::Registry {
default_model: None,
default_mode: None,
env: Default::default(),
favorite_models: Vec::new(),
default_config_options: Default::default(),
favorite_config_option_values: Default::default(),
}
} else {
settings::CustomAgentServerSettings::Extension {
default_model: None,
default_mode: None,
env: Default::default(),
favorite_models: Vec::new(),
default_config_options: Default::default(),
favorite_config_option_values: Default::default(),
}
fn default_settings_for_agent() -> settings::CustomAgentServerSettings {
settings::CustomAgentServerSettings::Registry {
default_model: None,
default_mode: None,
env: Default::default(),
favorite_models: Vec::new(),
default_config_options: Default::default(),
favorite_config_option_values: Default::default(),
}
}
@ -547,53 +516,4 @@ mod tests {
assert!(is_registry_agent("agent-from-settings", cx));
});
}
#[gpui::test]
fn test_agent_with_extension_settings_type_is_not_registry(cx: &mut TestAppContext) {
init_test(cx);
set_agent_server_settings(
cx,
vec![(
"my-extension-agent",
settings::CustomAgentServerSettings::Extension {
env: HashMap::default(),
default_mode: None,
default_model: None,
favorite_models: Vec::new(),
default_config_options: HashMap::default(),
favorite_config_option_values: HashMap::default(),
},
)],
);
cx.update(|cx| {
assert!(!is_registry_agent("my-extension-agent", cx));
});
}
#[gpui::test]
fn test_default_settings_for_extension_agent(cx: &mut TestAppContext) {
init_test(cx);
cx.update(|cx| {
assert!(matches!(
default_settings_for_agent("some-extension-agent", cx),
settings::CustomAgentServerSettings::Extension { .. }
));
});
}
#[gpui::test]
fn test_default_settings_for_agent_in_registry(cx: &mut TestAppContext) {
init_test(cx);
init_registry_with_agents(cx, &["new-registry-agent"]);
cx.update(|cx| {
assert!(matches!(
default_settings_for_agent("new-registry-agent", cx),
settings::CustomAgentServerSettings::Registry { .. }
));
assert!(matches!(
default_settings_for_agent("not-in-registry", cx),
settings::CustomAgentServerSettings::Extension { .. }
));
});
}
}

View file

@ -13,6 +13,7 @@ path = "agent_skills.rs"
[dependencies]
anyhow.workspace = true
const_format.workspace = true
fs.workspace = true
futures.workspace = true
gpui.workspace = true

View file

@ -1,6 +1,8 @@
use anyhow::{Context as _, Result};
use const_format::{concatcp, formatcp};
use fs::Fs;
use futures::StreamExt;
use gpui::{Global, SharedString};
use serde::{Deserialize, Serialize};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
@ -13,6 +15,18 @@ pub const AGENTS_DIR_NAME: &str = ".agents";
/// Second segment of the skills directory path: `skills`.
pub const SKILLS_DIR_NAME: &str = "skills";
/// User-facing display form of the global skills directory path — i.e.
/// what a human should see in messages and prompts, with the platform's
/// native path separator and home-directory shorthand.
///
/// Windows doesn't recognize `~` as the home directory, so the env-var
/// form is used there instead.
#[cfg(target_os = "windows")]
pub const GLOBAL_SKILLS_DIR_DISPLAY: &str =
concatcp!("%USERPROFILE%\\", AGENTS_DIR_NAME, "\\", SKILLS_DIR_NAME);
#[cfg(not(target_os = "windows"))]
pub const GLOBAL_SKILLS_DIR_DISPLAY: &str = concatcp!("~/", AGENTS_DIR_NAME, "/", SKILLS_DIR_NAME);
/// Opaque identifier for the project scope a skill was loaded from.
///
/// `agent_skills` is a leaf crate and intentionally does not depend on
@ -27,6 +41,7 @@ pub struct SkillScopeId(pub usize);
/// entries would fan out an equally large number of concurrent OS-level I/O
/// operations, potentially exhausting file descriptors or stalling the app.
const SKILL_IO_CONCURRENCY: usize = 16;
const SKILL_READ_CHUNK_SIZE: usize = 4096;
/// Maximum size for a single SKILL.md file (100KB)
pub const MAX_SKILL_FILE_SIZE: usize = 100 * 1024;
@ -51,11 +66,19 @@ pub struct Skill {
/// `skill` tool refuses to load it. The user can still invoke it as a
/// slash command.
pub disable_model_invocation: bool,
/// For built-in skills whose content is compiled into the binary,
/// this holds the full SKILL.md body so the skill tool can serve it
/// without a filesystem read.
pub embedded_body: Option<&'static str>,
}
/// Indicates where a skill was loaded from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SkillSource {
/// Compiled into the Zed binary. These are always available and have
/// the lowest override priority (global and project-local skills can
/// shadow them).
BuiltIn,
/// From ~/.agents/skills/
Global,
/// From {project}/.agents/skills/
@ -66,6 +89,23 @@ pub enum SkillSource {
}
impl SkillSource {
/// Precedence for resolving same-named skills. Higher values shadow
/// lower ones: `ProjectLocal` > `Global` > `BuiltIn`. Two sources
/// returning equal precedence (e.g. two project-local skills from
/// different worktrees) leave the winner up to the caller, which by
/// convention keeps the first one in iteration order.
///
/// Adding a new `SkillSource` variant should be a one-line change
/// here — every consumer routes through this method so the hierarchy
/// stays in sync.
pub fn precedence(&self) -> u8 {
match self {
Self::BuiltIn => 0,
Self::Global => 1,
Self::ProjectLocal { .. } => 2,
}
}
/// Scope prefix used in the `/<prefix>:<name>` slash-command
/// syntax that the autocomplete popup inserts. Global skills use
/// an empty prefix (so the inserted text is `/:<name>`), and
@ -78,9 +118,21 @@ impl SkillSource {
/// invoked as `/:<name>`, and the worktree's skill is invoked as
/// `/global:<name>`. The two grammars never collide on the
/// inserted text.
/// Human-readable label for this source, used in the UI to
/// distinguish skills from different origins.
pub fn display_label(&self) -> &str {
match self {
Self::BuiltIn => "built-in",
Self::Global => "global",
Self::ProjectLocal {
worktree_root_name, ..
} => worktree_root_name.as_ref(),
}
}
pub fn scope_prefix(&self) -> &str {
match self {
Self::Global => "",
Self::BuiltIn | Self::Global => "",
Self::ProjectLocal {
worktree_root_name, ..
} => worktree_root_name.as_ref(),
@ -99,7 +151,7 @@ impl SkillSource {
/// strictness only affects users typing by memory.
pub fn matches_scope(&self, scope: &str) -> bool {
match self {
Self::Global => scope.is_empty(),
Self::BuiltIn | Self::Global => scope.is_empty(),
Self::ProjectLocal {
worktree_root_name, ..
} => !scope.is_empty() && worktree_root_name.as_ref() == scope,
@ -107,6 +159,23 @@ impl SkillSource {
}
}
/// App-wide index of loaded skills, published by NativeAgent and read
/// by any UI that needs to display the skill list (e.g. Settings UI).
#[derive(Default)]
pub struct SkillIndex {
pub global_skills: Vec<Skill>,
pub project_skills: Vec<ProjectSkillGroup>,
}
#[derive(Clone)]
pub struct ProjectSkillGroup {
pub worktree_id: SkillScopeId,
pub worktree_root_name: SharedString,
pub skills: Vec<Skill>,
}
impl Global for SkillIndex {}
/// Just the frontmatter, used for parsing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillMetadata {
@ -174,17 +243,7 @@ pub fn parse_skill_frontmatter(
content: &str,
source: SkillSource,
) -> Result<Skill> {
if content.len() > MAX_SKILL_FILE_SIZE {
anyhow::bail!(
"SKILL.md file exceeds maximum size of {}KB",
MAX_SKILL_FILE_SIZE / 1024
);
}
let (metadata, _body) = extract_frontmatter(content)?;
validate_name(&metadata.name)?;
validate_description(&metadata.description)?;
let (metadata, _body) = parse_skill_file_content(content)?;
let directory_path = skill_file_path
.parent()
@ -198,9 +257,33 @@ pub fn parse_skill_frontmatter(
directory_path,
skill_file_path: skill_file_path.to_path_buf(),
disable_model_invocation: metadata.disable_model_invocation,
embedded_body: None,
})
}
/// Extract the YAML frontmatter and body from a SKILL.md file without
/// validating the metadata fields.
pub fn extract_skill_frontmatter(content: &str) -> Result<(SkillMetadata, &str)> {
if content.len() > MAX_SKILL_FILE_SIZE {
anyhow::bail!(
"SKILL.md file exceeds maximum size of {}KB",
MAX_SKILL_FILE_SIZE / 1024
);
}
extract_frontmatter(content)
}
/// Parse and validate the YAML frontmatter and body from a SKILL.md file.
pub fn parse_skill_file_content(content: &str) -> Result<(SkillMetadata, &str)> {
let (metadata, body) = extract_skill_frontmatter(content)?;
validate_name(&metadata.name).map_err(anyhow::Error::msg)?;
validate_description(&metadata.description).map_err(anyhow::Error::msg)?;
Ok((metadata, body))
}
fn extract_frontmatter(content: &str) -> Result<(SkillMetadata, &str)> {
let content = content.trim_start();
@ -273,34 +356,130 @@ fn extract_frontmatter(content: &str) -> Result<(SkillMetadata, &str)> {
.context("Invalid YAML frontmatter"))
}
fn validate_name(name: &str) -> Result<()> {
/// Maximum length for a valid skill name. Mirrors the upper bound enforced
/// by [`validate_name`].
pub const MAX_SKILL_NAME_LEN: usize = 64;
/// Maximum length (in bytes) for a valid skill description. Mirrors the
/// upper bound enforced by [`validate_description`].
///
/// Byte-based rather than char-based because that's what `.len()` returns
/// and what every caller currently measures; the UI also surfaces this
/// limit as a byte count so the editor's counter matches the validator.
pub const MAX_SKILL_DESCRIPTION_LEN: usize = 1024;
/// Convert an arbitrary human-readable string into a valid skill name, or
/// return `None` if no valid name can be produced (e.g. the input contains
/// no ASCII alphanumeric characters at all).
///
/// The transformation:
///
/// 1. Replaces each `&` with the word `and` (with separators on either
/// side), so titles like "rock & roll" or "AT&T" round-trip something
/// meaningful (`rock-and-roll`, `at-and-t`) rather than dropping the
/// `&` and silently mashing the neighbours together.
/// 2. ASCII-lowercases every ASCII letter.
/// 3. Replaces each space with `-`. Existing `-` characters are kept.
/// 4. **Drops** every other non-alphanumeric character entirely (NOT
/// replaced with a dash). So `foo!bar` slugifies to `foobar`, not
/// `foo-bar` — only word boundaries the user actually wrote (spaces)
/// become dashes.
/// 5. Collapses runs of `-` into a single `-`.
/// 6. Trims leading and trailing `-`.
/// 7. Truncates to [`MAX_SKILL_NAME_LEN`] bytes (then re-trims trailing `-`
/// in case the truncation landed on one).
///
/// The result, if `Some`, always satisfies [`validate_name`].
pub fn slugify_skill_name(input: &str) -> Option<String> {
// Substitute `&` with `-and-` BEFORE the per-character pass; the
// existing dash-collapsing and edge-trimming logic then handles the
// boundary cases (`foo & bar`, `&foo`, `foo&`, `&&`, etc.) for free.
let input = input.replace('&', "-and-");
let mut slug = String::with_capacity(input.len());
let mut last_was_dash = true; // suppress a leading `-`
for ch in input.chars() {
let mapped = if ch.is_ascii_alphanumeric() {
Some(ch.to_ascii_lowercase())
} else if ch == ' ' || ch == '-' {
Some('-')
} else {
// Drop the character entirely — and importantly, do NOT touch
// `last_was_dash`. That way `foo!bar` stays one run of
// alphanumerics (`foobar`) rather than getting a fake
// separator inserted (`foo-bar`).
None
};
let Some(c) = mapped else { continue };
if c == '-' {
if last_was_dash {
continue;
}
last_was_dash = true;
} else {
last_was_dash = false;
}
slug.push(c);
}
if slug.ends_with('-') {
slug.pop();
}
if slug.len() > MAX_SKILL_NAME_LEN {
slug.truncate(MAX_SKILL_NAME_LEN);
while slug.ends_with('-') {
slug.pop();
}
}
if slug.is_empty() { None } else { Some(slug) }
}
/// Validate a skill name against the rules enforced by both the loader
/// and the create-skill UI.
///
/// Rules:
/// * non-empty
/// * at most [`MAX_SKILL_NAME_LEN`] bytes
/// * ASCII lowercase letters, digits, and hyphens only
/// * must not start or end with a hyphen — [`slugify_skill_name`]
/// already guarantees this for its output, so requiring it in the
/// validator keeps hand-written `SKILL.md` files consistent with
/// slugifier output
///
/// Error messages are returned as `&'static str` (interpolated at
/// compile time via `formatcp!`) so that UI surfaces can store them in
/// `Option<&'static str>` fields without allocating, and loader callers
/// can convert them to `anyhow::Error` via `anyhow::Error::msg`.
pub fn validate_name(name: &str) -> Result<(), &'static str> {
if name.is_empty() {
anyhow::bail!("Skill name cannot be empty");
return Err("Skill name cannot be empty");
}
if name.len() > 64 {
anyhow::bail!("Skill name must be at most 64 characters");
if name.len() > MAX_SKILL_NAME_LEN {
return Err(formatcp!(
"Skill name must be at most {MAX_SKILL_NAME_LEN} characters"
));
}
if name.starts_with('-') || name.ends_with('-') {
return Err("Skill name must not start or end with a hyphen");
}
if !name
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
{
anyhow::bail!("Skill name must contain only lowercase letters, numbers, and hyphens");
return Err("Skill name must contain only lowercase letters, numbers, and hyphens");
}
Ok(())
}
fn validate_description(description: &str) -> Result<()> {
if description.is_empty() {
anyhow::bail!("Skill description cannot be empty");
/// Validate a skill description against the rules enforced by both the
/// loader and the create-skill UI.
pub fn validate_description(description: &str) -> Result<(), &'static str> {
if description.trim().is_empty() {
return Err("Skill description cannot be empty");
}
if description.len() > 1024 {
anyhow::bail!("Skill description must be at most 1024 characters");
if description.len() > MAX_SKILL_DESCRIPTION_LEN {
return Err(formatcp!(
"Skill description must be at most {MAX_SKILL_DESCRIPTION_LEN} bytes"
));
}
Ok(())
}
@ -466,14 +645,17 @@ pub async fn load_skill_frontmatter(
// panic with "Parking forbidden" under `TestAppContext`.
let read_result: Result<Vec<u8>, io::Error> = (|| {
let mut accumulated: Vec<u8> = Vec::new();
let mut chunk = [0u8; 4096];
let mut chunk = [0u8; SKILL_READ_CHUNK_SIZE];
loop {
let n = reader.read(&mut chunk)?;
if n == 0 {
break;
}
accumulated.extend_from_slice(&chunk[..n]);
if closing_delimiter_end(&accumulated).is_some() {
if let Some(end) = closing_delimiter_end(&accumulated) {
// Discard body bytes swept up in the last chunk so that e.g. multi-byte
// graphemes split at the boundary won't cause `str::from_utf8` to fail.
accumulated.truncate(end);
break;
}
if accumulated.len() > MAX_SKILL_FILE_SIZE {
@ -519,6 +701,53 @@ pub async fn read_skill_body(
Ok(body.trim().to_string())
}
/// Content of the built-in `create-skill` SKILL.md, embedded at compile time.
const CREATE_SKILL_CONTENT: &str = include_str!("builtin/create-skill/SKILL.md");
/// Returns the set of skills that are compiled into the Zed binary.
pub fn builtin_skills() -> Vec<Skill> {
let mut skills = Vec::new();
if let Ok(skill) = parse_builtin_skill("create-skill", CREATE_SKILL_CONTENT) {
skills.push(skill);
}
skills
}
/// Parse a built-in skill from its embedded SKILL.md content. The skill
/// gets a synthetic `<built-in>` path since it doesn't live on disk.
fn parse_builtin_skill(name: &str, content: &'static str) -> Result<Skill> {
let (metadata, body) = extract_frontmatter(content)?;
validate_name(&metadata.name).map_err(anyhow::Error::msg)?;
validate_description(&metadata.description).map_err(anyhow::Error::msg)?;
let synthetic_dir = PathBuf::from(format!("<built-in>/{}", name));
let synthetic_path = synthetic_dir.join(SKILL_FILE_NAME);
Ok(Skill {
name: metadata.name,
description: metadata.description,
source: SkillSource::BuiltIn,
directory_path: synthetic_dir,
skill_file_path: synthetic_path,
disable_model_invocation: metadata.disable_model_invocation,
embedded_body: Some(body.trim()),
})
}
/// All built-in skills as `(name, raw_content)` pairs. Used by
/// `builtin_skill_content` to serve the full SKILL.md without disk I/O.
const BUILTIN_SKILL_ENTRIES: &[(&str, &str)] = &[("create-skill", CREATE_SKILL_CONTENT)];
/// Look up the full embedded content of a built-in skill by its
/// synthetic file path. Returns `None` if the path doesn't match any
/// built-in skill.
pub fn builtin_skill_content(skill_file_path: &Path) -> Option<&'static str> {
BUILTIN_SKILL_ENTRIES.iter().find_map(|(name, content)| {
let expected = PathBuf::from(format!("<built-in>/{}", name)).join(SKILL_FILE_NAME);
(expected == skill_file_path).then_some(*content)
})
}
/// Returns the global skills directory: `~/.agents/skills`.
///
/// Other agents (e.g. Claude Code) already write skill files into this
@ -582,6 +811,34 @@ mod tests {
use fs::FakeFs;
use gpui::TestAppContext;
#[test]
fn test_skill_source_precedence_is_total_and_ordered() {
// Pin the hierarchy: project-local > global > built-in. Every
// override and conflict-resolution site routes through this,
// so the rest of the codebase relies on it being correct.
let built_in = SkillSource::BuiltIn.precedence();
let global = SkillSource::Global.precedence();
let project = SkillSource::ProjectLocal {
worktree_id: SkillScopeId(1),
worktree_root_name: "my-project".into(),
}
.precedence();
assert!(built_in < global, "global must shadow built-in");
assert!(global < project, "project-local must shadow global");
// Two project-local skills from different worktrees tie. The
// "first wins" convention is enforced by the callers, but the
// precedence itself must be equal so neither silently shadows
// the other.
let other_project = SkillSource::ProjectLocal {
worktree_id: SkillScopeId(2),
worktree_root_name: "other-project".into(),
}
.precedence();
assert_eq!(project, other_project);
}
#[test]
fn test_parse_valid_skill() {
let content = r#"---
@ -609,6 +866,26 @@ Do the thing.
assert!(!skill.disable_model_invocation);
}
#[test]
fn test_parse_skill_file_content_returns_body() {
let content = r#"---
name: my-skill
description: A test skill for testing purposes
---
# My Skill
Do the thing.
"#;
let (metadata, body) = parse_skill_file_content(content)
.expect("valid skill content should parse successfully");
assert_eq!(metadata.name, "my-skill");
assert_eq!(metadata.description, "A test skill for testing purposes");
assert_eq!(body.trim(), "# My Skill\n\nDo the thing.");
}
#[test]
fn test_parse_disable_model_invocation_true() {
let content = r#"---
@ -792,12 +1069,8 @@ Content.
SkillSource::Global,
);
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("at most 64 characters")
);
let expected = format!("at most {MAX_SKILL_NAME_LEN} characters");
assert!(result.unwrap_err().to_string().contains(&expected));
}
#[test]
@ -824,6 +1097,236 @@ Content.
);
}
#[test]
fn test_slugify_basic() {
assert_eq!(
slugify_skill_name("My Cool Skill").as_deref(),
Some("my-cool-skill")
);
}
#[test]
fn test_slugify_strips_invalid_chars() {
// Punctuation is dropped; spaces between words still produce dashes.
// `Hello,` → `hello`, then `␣` → `-`, then `World!` → `world`, etc.
assert_eq!(
slugify_skill_name("Hello, World! (v2)").as_deref(),
Some("hello-world-v2")
);
}
#[test]
fn test_slugify_drops_punctuation_in_middle_no_spaces() {
// Punctuation between alphanumerics is dropped entirely — it does
// NOT become a dash. Only user-written spaces become dashes.
assert_eq!(slugify_skill_name("foo!bar").as_deref(), Some("foobar"));
assert_eq!(slugify_skill_name("foo?bar").as_deref(), Some("foobar"));
assert_eq!(slugify_skill_name("foo%bar").as_deref(), Some("foobar"));
assert_eq!(slugify_skill_name("100%sure").as_deref(), Some("100sure"));
assert_eq!(
slugify_skill_name("what's that").as_deref(),
Some("whats-that")
);
// `&` is special-cased to become `and` — see
// `test_slugify_ampersand_becomes_and` for the full coverage.
assert_eq!(
slugify_skill_name("don't&won't").as_deref(),
Some("dont-and-wont")
);
}
#[test]
fn test_slugify_ampersand_becomes_and() {
// No spaces around `&`.
assert_eq!(
slugify_skill_name("foo&bar").as_deref(),
Some("foo-and-bar")
);
assert_eq!(
slugify_skill_name("rock&roll").as_deref(),
Some("rock-and-roll")
);
// Spaces around `&`: collapses to a single dash on each side.
assert_eq!(
slugify_skill_name("foo & bar").as_deref(),
Some("foo-and-bar")
);
// Asymmetric spacing.
assert_eq!(
slugify_skill_name("foo& bar").as_deref(),
Some("foo-and-bar")
);
assert_eq!(
slugify_skill_name("foo &bar").as_deref(),
Some("foo-and-bar")
);
// Leading/trailing `&`: the substituted spaces become leading/
// trailing dashes which then get trimmed.
assert_eq!(slugify_skill_name("&foo").as_deref(), Some("and-foo"));
assert_eq!(slugify_skill_name("foo&").as_deref(), Some("foo-and"));
// `&` alone slugifies to the word `and`, not to `None`.
assert_eq!(slugify_skill_name("&").as_deref(), Some("and"));
assert_eq!(slugify_skill_name(" & ").as_deref(), Some("and"));
// Multiple `&`s with various spacing all collapse properly.
assert_eq!(slugify_skill_name("&&").as_deref(), Some("and-and"));
assert_eq!(
slugify_skill_name("foo & & bar").as_deref(),
Some("foo-and-and-bar")
);
// Mixed with other punctuation (other punctuation is still dropped).
assert_eq!(slugify_skill_name("AT&T").as_deref(), Some("at-and-t"));
assert_eq!(slugify_skill_name("Q&A!").as_deref(), Some("q-and-a"));
}
#[test]
fn test_slugify_punctuation_surrounded_by_spaces() {
// `foo ! bar` → `foo-bar`: the two spaces would each produce a
// dash, but consecutive dashes are collapsed.
assert_eq!(slugify_skill_name("foo ! bar").as_deref(), Some("foo-bar"));
assert_eq!(slugify_skill_name("foo ? bar").as_deref(), Some("foo-bar"));
assert_eq!(
slugify_skill_name("100 % sure").as_deref(),
Some("100-sure")
);
assert_eq!(
slugify_skill_name("foo @ bar @ baz").as_deref(),
Some("foo-bar-baz")
);
}
#[test]
fn test_slugify_punctuation_adjacent_to_space() {
// `foo! bar` and `foo !bar` both produce `foo-bar` — the
// punctuation contributes nothing, the single space contributes
// the dash.
assert_eq!(slugify_skill_name("foo! bar").as_deref(), Some("foo-bar"));
assert_eq!(slugify_skill_name("foo !bar").as_deref(), Some("foo-bar"));
assert_eq!(slugify_skill_name("foo? bar").as_deref(), Some("foo-bar"));
}
#[test]
fn test_slugify_leading_and_trailing_punctuation() {
// Punctuation at the edges is dropped; there's no leading/trailing
// dash to trim because the punctuation never became a dash in the
// first place.
assert_eq!(slugify_skill_name("!foo").as_deref(), Some("foo"));
assert_eq!(slugify_skill_name("foo!").as_deref(), Some("foo"));
assert_eq!(slugify_skill_name("!!!foo!!!").as_deref(), Some("foo"));
assert_eq!(slugify_skill_name("?foo?").as_deref(), Some("foo"));
assert_eq!(slugify_skill_name("...foo...").as_deref(), Some("foo"));
}
#[test]
fn test_slugify_only_punctuation_returns_none() {
assert_eq!(slugify_skill_name("!!!"), None);
assert_eq!(slugify_skill_name("?@$"), None);
assert_eq!(slugify_skill_name("()[]{}"), None);
assert_eq!(slugify_skill_name(".,;:"), None);
}
#[test]
fn test_slugify_mixed_punctuation_spaces_and_dashes() {
// A messy realistic input: combination of punctuation, spaces,
// existing dashes, and casing.
assert_eq!(
slugify_skill_name(" -- Hello, World!! -- ").as_deref(),
Some("hello-world")
);
assert_eq!(
slugify_skill_name("C++ vs. Rust?").as_deref(),
Some("c-vs-rust")
);
assert_eq!(
slugify_skill_name("v1.2.3-beta").as_deref(),
Some("v123-beta")
);
}
#[test]
fn test_slugify_underscores_are_dropped() {
// Underscores aren't a valid skill-name character and aren't
// separators — only spaces become dashes — so underscores get
// dropped entirely.
assert_eq!(slugify_skill_name("foo_bar").as_deref(), Some("foobar"));
assert_eq!(slugify_skill_name("FOO_BAR").as_deref(), Some("foobar"));
assert_eq!(
slugify_skill_name("snake_case style").as_deref(),
Some("snakecase-style")
);
}
#[test]
fn test_slugify_collapses_consecutive_dashes() {
assert_eq!(
slugify_skill_name("foo --- bar").as_deref(),
Some("foo-bar")
);
}
#[test]
fn test_slugify_trims_leading_and_trailing_dashes() {
assert_eq!(slugify_skill_name("---foo---").as_deref(), Some("foo"));
assert_eq!(slugify_skill_name(" foo ").as_deref(), Some("foo"));
}
#[test]
fn test_slugify_lowercases() {
assert_eq!(slugify_skill_name("FOO BAR").as_deref(), Some("foo-bar"));
assert_eq!(
slugify_skill_name("MyCoolSkill").as_deref(),
Some("mycoolskill")
);
}
#[test]
fn test_slugify_strips_non_ascii_letters() {
// Non-ASCII chars are replaced with `-`, then collapsed.
assert_eq!(slugify_skill_name("abc\u{00e9}").as_deref(), Some("abc"));
assert_eq!(slugify_skill_name("\u{4e2d}\u{6587}"), None);
}
#[test]
fn test_slugify_returns_none_for_empty_or_unmappable() {
assert_eq!(slugify_skill_name(""), None);
assert_eq!(slugify_skill_name(" "), None);
assert_eq!(slugify_skill_name("!!!"), None);
assert_eq!(slugify_skill_name("---"), None);
}
#[test]
fn test_slugify_truncates_long_inputs() {
let input = "a".repeat(200);
let slug = slugify_skill_name(&input).expect("should slugify");
assert_eq!(slug.len(), MAX_SKILL_NAME_LEN);
assert!(slug.chars().all(|c| c == 'a'));
}
#[test]
fn test_slugify_truncation_does_not_leave_trailing_dash() {
// The 64th byte lands on a `-`, which we must strip post-truncation.
let mut input = "a".repeat(63);
input.push_str(" extra");
let slug = slugify_skill_name(&input).expect("should slugify");
assert!(!slug.ends_with('-'));
assert!(slug.len() <= MAX_SKILL_NAME_LEN);
}
#[test]
fn test_slugify_output_passes_validate_name() {
for input in [
"My Cool Skill",
"Hello, World!",
"---foo---",
"123 abc",
"a".repeat(200).as_str(),
] {
let slug = slugify_skill_name(input).expect("should slugify");
validate_name(&slug).unwrap_or_else(|err| {
panic!("slug {slug:?} from {input:?} failed validation: {err}")
});
}
}
#[test]
fn test_parse_description_too_long() {
let long_desc = "a".repeat(1025);
@ -843,12 +1346,8 @@ Content.
SkillSource::Global,
);
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("at most 1024 characters")
);
let expected = format!("at most {MAX_SKILL_DESCRIPTION_LEN} bytes");
assert!(result.unwrap_err().to_string().contains(&expected));
}
#[test]
@ -1221,6 +1720,7 @@ description: A skill with no body content
directory_path: PathBuf::from("/skills/test-skill"),
skill_file_path: PathBuf::from("/skills/test-skill/SKILL.md"),
disable_model_invocation: false,
embedded_body: None,
};
let summary = SkillSummary::from(&skill);
@ -1336,6 +1836,46 @@ description: A skill with no body content
assert_eq!(skill.directory_path, PathBuf::from("/skills/my-skill"));
}
#[gpui::test]
async fn test_load_skill_frontmatter_with_emoji_at_chunk_boundary(cx: &mut TestAppContext) {
// We must be able to load skill frontmatter even when a
// multipoint grapheme crosses the chunk read boundary.
let fs = FakeFs::new(cx.executor());
let frontmatter = "---\nname: my-skill\ndescription: Example skill testing multipoint graphemes at chunk boundary\n---\n";
// Pad contents so that the emoji's first byte lands
// at the last byte of the first read chunk.
let padding = "a".repeat(SKILL_READ_CHUNK_SIZE - frontmatter.len() - 1);
let content = format!("{frontmatter}{padding}");
assert!(
(frontmatter.len() + padding.len()) < SKILL_READ_CHUNK_SIZE,
"emoji must start before the second chunk"
);
assert!(
content.len() > SKILL_READ_CHUNK_SIZE,
"skill is longer than a chunk, so we know that the emoji crosses chunk boundaries"
);
fs.insert_tree(
"/skills",
serde_json::json!({
"my-skill": {
"SKILL.md": content,
}
}),
)
.await;
load_skill_frontmatter(
fs as Arc<dyn Fs>,
PathBuf::from("/skills/my-skill/SKILL.md"),
SkillSource::Global,
)
.await
.expect("frontmatter should parse even when a multipoint grapheme such as an emoji crosses the byte chunk boundary");
}
#[gpui::test]
async fn test_read_skill_body_returns_trimmed_body(cx: &mut TestAppContext) {
let fs = FakeFs::new(cx.executor());
@ -1448,4 +1988,89 @@ description: A skill with no body content
"project/.AGENTS/SKILLS/foo"
)));
}
#[test]
fn validate_name_accepts_valid_names() {
assert!(validate_name("draft-pr").is_ok());
assert!(validate_name("a").is_ok());
assert!(validate_name("skill1").is_ok());
assert!(validate_name(&"a".repeat(MAX_SKILL_NAME_LEN)).is_ok());
}
#[test]
fn validate_name_rejects_empty() {
assert!(validate_name("").is_err());
}
#[test]
fn validate_name_rejects_uppercase() {
assert!(validate_name("Draft-PR").is_err());
}
#[test]
fn validate_name_rejects_leading_and_trailing_hyphens() {
assert!(validate_name("-draft").is_err());
assert!(validate_name("draft-").is_err());
}
#[test]
fn validate_name_rejects_invalid_chars() {
assert!(validate_name("draft_pr").is_err());
assert!(validate_name("draft pr").is_err());
assert!(validate_name("draft.pr").is_err());
}
#[test]
fn validate_name_rejects_too_long() {
assert!(validate_name(&"a".repeat(MAX_SKILL_NAME_LEN + 1)).is_err());
}
#[test]
fn validate_description_accepts_valid() {
assert!(validate_description("A useful skill").is_ok());
}
#[test]
fn validate_description_rejects_empty_and_whitespace_only() {
assert!(validate_description("").is_err());
assert!(validate_description(" ").is_err());
assert!(validate_description("\t\n ").is_err());
}
#[test]
fn validate_description_rejects_too_long() {
assert!(validate_description(&"a".repeat(MAX_SKILL_DESCRIPTION_LEN + 1)).is_err());
}
#[test]
fn validate_description_length_is_measured_in_bytes() {
// "é" is 2 bytes in UTF-8. A string of MAX/2 + 1 "é" characters has
// only ~MAX/2 + 1 chars but exceeds MAX bytes, so it must be
// rejected by a byte-based validator (and accepted by a char-based
// one). This regression-tests the byte semantics that the loader
// and UI both rely on.
let chars = MAX_SKILL_DESCRIPTION_LEN / 2 + 1;
let description = "é".repeat(chars);
assert!(description.chars().count() <= MAX_SKILL_DESCRIPTION_LEN);
assert!(description.len() > MAX_SKILL_DESCRIPTION_LEN);
assert!(validate_description(&description).is_err());
}
#[test]
fn slugify_output_always_passes_validate_name() {
for input in [
"foo",
"Foo Bar",
"rock & roll",
"---weird---",
"a".repeat(200).as_str(),
] {
if let Some(slug) = slugify_skill_name(input) {
assert!(
validate_name(&slug).is_ok(),
"slug {slug:?} from {input:?} failed validate_name"
);
}
}
}
}

View file

@ -0,0 +1,95 @@
---
name: create-skill
description: Helps you create new agent skills for Zed. Use this to create a skill, ask about SKILLs.md, or package reusable agent instructions.
---
# Creating a Zed Agent Skill
Use this skill when the user wants to create, edit, or understand agent skills in Zed.
## What is a Skill?
A skill is a reusable set of instructions that an agent can load on demand. Each skill lives in its own directory and is defined by a `SKILL.md` file with YAML frontmatter.
## Where Skills Live
Skills can be placed in two locations:
| Scope | Path | When to use |
|-------|------|-------------|
| Global | `~/.agents/skills/<skill-name>/SKILL.md` | Personal skills, available in all projects |
| Project-local | `<project>/.agents/skills/<skill-name>/SKILL.md` | Project-specific skills, shared with collaborators through version control |
Prefer project-local when the skill is specific to a repository. Prefer global when the skill is a personal workflow the user wants everywhere.
## SKILL.md Format
Every `SKILL.md` must start with YAML frontmatter between `---` delimiters:
```markdown
---
name: my-skill-name
description: A clear, specific description of what this skill does and when to use it.
---
# Skill Title
Instructions for the agent go here. Write them as if you're telling the agent
what to do when this skill is activated.
```
### Required Frontmatter Fields
- **`name`** (required): Must be 164 characters, lowercase alphanumeric with single-hyphen separators. Must match the containing directory name exactly. Regex: `^[a-z0-9]+(-[a-z0-9]+)*$`
- **`description`** (required): Must be 11024 characters. This is what the agent sees when deciding whether to use the skill — make it specific and actionable.
### Optional Frontmatter Fields
- **`disable-model-invocation`**: When set to `true`, the skill is hidden from the agent's automatic catalog. The user can still invoke it manually via the `/` slash command menu. Useful for skills that should only run when explicitly requested.
## Naming Rules
The skill name must:
- Be lowercase letters and numbers only, with single hyphens as separators
- Not start or end with `-`
- Not contain consecutive `--`
- Match the directory name that contains the `SKILL.md`
Good: `git-release`, `pr-review`, `rust-patterns`
Bad: `Git-Release`, `pr--review`, `-my-skill`, `my_skill`
## Writing Good Skill Instructions
The body of the SKILL.md (after the frontmatter) contains the instructions the agent will follow. Guidelines:
1. **Be direct**: Write instructions as if talking to the agent. "Do X", "Check Y", "Ask the user about Z".
2. **Be specific**: Include concrete file paths, commands, formats, and patterns.
3. **Include when-to-use guidance**: Help the agent understand the right context for this skill.
4. **Reference supporting files**: Skills can include additional files in their directory. Reference them with relative paths (e.g., `templates/component.tsx`). The agent can read these files when the skill is activated.
5. **Keep descriptions actionable**: The `description` field is the agent's primary signal for whether to load this skill. "Helps with code" is too vague. "Generate React components following the project's design system patterns" is specific.
## Supporting Files
A skill directory can contain additional files beyond `SKILL.md`:
```
~/.agents/skills/react-component/
├── SKILL.md
├── templates/
│ ├── component.tsx
│ └── test.tsx
└── examples/
└── button.tsx
```
Reference these in the skill body. The agent can read them using the file path shown in the `<directory>` tag of the skill envelope.
## Step-by-Step: Creating a Skill
1. Decide on scope (global vs project-local) based on the user's needs.
2. Choose a descriptive, hyphenated name.
3. Create the directory structure. The `create_directory` tool normally only creates directories inside the current project, but it has a special allow case for global skills under `~/.agents/skills`.
4. Write the `SKILL.md` with frontmatter and instructions. The `write_file` and `edit_file` tools also have a special allow case for creating or modifying files under `~/.agents/skills`.
5. Optionally add supporting files (templates, examples, references).
After creating the skill, it will be automatically discovered by Zed's agent on the next conversation (no restart needed for global skills if the `~/.agents/skills/` directory already exists).

View file

@ -33,6 +33,7 @@ agent.workspace = true
async-channel.workspace = true
agent_servers.workspace = true
agent_settings.workspace = true
agent_skills.workspace = true
ai_onboarding.workspace = true
anyhow.workspace = true
heapless.workspace = true
@ -68,6 +69,7 @@ language.workspace = true
language_model.workspace = true
language_models.workspace = true
log.workspace = true
lru.workspace = true
lsp.workspace = true
markdown.workspace = true
menu.workspace = true
@ -88,6 +90,7 @@ remote.workspace = true
remote_connection.workspace = true
rope.workspace = true
rules_library.workspace = true
skill_creator.workspace = true
schemars.workspace = true
serde.workspace = true
serde_json.workspace = true
@ -144,3 +147,4 @@ tempfile.workspace = true
vim.workspace = true
tree-sitter-md.workspace = true
unindent.workspace = true
terminal = { workspace = true, features = ["test-support"] }

View file

@ -664,8 +664,14 @@ impl AgentConfiguration {
None
};
let auth_required = matches!(server_status, ContextServerStatus::AuthRequired);
let client_secret_required = matches!(
server_status,
ContextServerStatus::ClientSecretRequired { .. }
);
let authenticating = matches!(server_status, ContextServerStatus::Authenticating);
let context_server_store = self.context_server_store.clone();
let workspace = self.workspace.clone();
let language_registry = self.language_registry.clone();
let tool_count = self
.context_server_registry
@ -685,6 +691,9 @@ impl AgentConfiguration {
ContextServerStatus::Error(_) => AiSettingItemStatus::Error,
ContextServerStatus::Stopped => AiSettingItemStatus::Stopped,
ContextServerStatus::AuthRequired => AiSettingItemStatus::AuthRequired,
ContextServerStatus::ClientSecretRequired { .. } => {
AiSettingItemStatus::ClientSecretRequired
}
ContextServerStatus::Authenticating => AiSettingItemStatus::Authenticating,
};
@ -886,7 +895,7 @@ impl AgentConfiguration {
),
)
.child(
Button::new("error-logout-server", "Authenticate")
Button::new("authenticate-server", "Authenticate")
.style(ButtonStyle::Outlined)
.label_size(LabelSize::Small)
.on_click({
@ -900,6 +909,46 @@ impl AgentConfiguration {
)
.into_any_element(),
)
} else if client_secret_required {
Some(
feedback_base_container()
.child(
h_flex()
.pr_4()
.min_w_0()
.w_full()
.gap_2()
.child(
Icon::new(IconName::Info)
.size(IconSize::XSmall)
.color(Color::Muted),
)
.child(
Label::new("Enter a client secret to connect this server")
.color(Color::Muted)
.size(LabelSize::Small),
),
)
.child(
Button::new("enter-client-secret", "Enter Client Secret")
.style(ButtonStyle::Outlined)
.label_size(LabelSize::Small)
.on_click({
let context_server_id = context_server_id.clone();
move |_event, window, cx| {
ConfigureContextServerModal::show_modal_for_existing_server(
context_server_id.clone(),
language_registry.clone(),
workspace.clone(),
window,
cx,
)
.detach();
}
}),
)
.into_any_element(),
)
} else if authenticating {
Some(
h_flex()
@ -1125,7 +1174,6 @@ impl AgentConfiguration {
};
let source_kind = match source {
ExternalAgentSource::Extension => AiSettingItemSource::Extension,
ExternalAgentSource::Registry => AiSettingItemSource::Registry,
ExternalAgentSource::Custom => AiSettingItemSource::Custom,
};
@ -1169,26 +1217,6 @@ impl AgentConfiguration {
});
let uninstall_button = match source {
ExternalAgentSource::Extension => Some(
IconButton::new(
SharedString::from(format!("uninstall-{}", id)),
IconName::Trash,
)
.icon_color(Color::Muted)
.icon_size(IconSize::Small)
.tooltip(Tooltip::text("Uninstall Agent Extension"))
.on_click(cx.listener(move |this, _, _window, cx| {
let agent_name = agent_server_name.clone();
if let Some(ext_id) = this.agent_server_store.update(cx, |store, _cx| {
store.get_extension_id_for_agent(&agent_name)
}) {
ExtensionStore::global(cx)
.update(cx, |store, cx| store.uninstall_extension(ext_id, cx))
.detach_and_log_err(cx);
}
})),
),
ExternalAgentSource::Registry => {
let fs = self.fs.clone();
Some(

View file

@ -17,7 +17,7 @@ use project::{
ContextServerStatus, ContextServerStore, ServerStatusChangedEvent,
registry::ContextServerDescriptorRegistry,
},
project_settings::{ContextServerSettings, ProjectSettings},
project_settings::{ContextServerSettings, OAuthClientSettings, ProjectSettings},
worktree_store::WorktreeStore,
};
use serde::Deserialize;
@ -43,7 +43,9 @@ enum ConfigurationTarget {
id: ContextServerId,
url: String,
headers: HashMap<String, String>,
oauth: Option<OAuthClientSettings>,
},
Extension {
id: ContextServerId,
repository_url: Option<SharedString>,
@ -121,15 +123,17 @@ impl ConfigurationSource {
id,
url,
headers: auth,
oauth,
} => ConfigurationSource::Existing {
editor: create_editor(
context_server_http_input(Some((id, url, auth))),
context_server_http_input(Some((id, url, auth, oauth))),
jsonc_language,
window,
cx,
),
is_http: true,
},
ConfigurationTarget::Extension {
id,
repository_url,
@ -168,7 +172,7 @@ impl ConfigurationSource {
ConfigurationSource::New { editor, is_http }
| ConfigurationSource::Existing { editor, is_http } => {
if *is_http {
parse_http_input(&editor.read(cx).text(cx)).map(|(id, url, auth)| {
parse_http_input(&editor.read(cx).text(cx)).map(|(id, url, auth, oauth)| {
(
id,
ContextServerSettings::Http {
@ -176,6 +180,7 @@ impl ConfigurationSource {
url,
headers: auth,
timeout: None,
oauth,
},
)
})
@ -256,11 +261,16 @@ fn context_server_input(existing: Option<(ContextServerId, ContextServerCommand)
}
fn context_server_http_input(
existing: Option<(ContextServerId, String, HashMap<String, String>)>,
existing: Option<(
ContextServerId,
String,
HashMap<String, String>,
Option<OAuthClientSettings>,
)>,
) -> String {
let (name, url, headers) = match existing {
Some((id, url, headers)) => {
let header = if headers.is_empty() {
let (name, url, headers, oauth) = match existing {
Some((id, url, headers, oauth)) => {
let headers = if headers.is_empty() {
r#"// "Authorization": "Bearer <token>"#.to_string()
} else {
let json = serde_json::to_string_pretty(&headers).unwrap();
@ -274,15 +284,48 @@ fn context_server_http_input(
.map(|line| format!(" {}", line))
.collect::<String>()
};
(id.0.to_string(), url, header)
(id.0.to_string(), url, headers, oauth)
}
None => (
"some-remote-server".to_string(),
"https://example.com/mcp".to_string(),
r#"// "Authorization": "Bearer <token>"#.to_string(),
None,
),
};
let oauth = oauth.map_or_else(
|| {
r#"
/// Uncomment to use a pre-registered OAuth client. You can include the client secret here as well, otherwise it will be prompted interactively and saved in the system keychain.
// "oauth": {
// "client_id": "your-client-id",
// },"#
.to_string()
},
|oauth| {
let mut lines = vec![
String::from("\n \"oauth\": {"),
format!(" \"client_id\": {},", serde_json::to_string(&oauth.client_id).unwrap()),
];
if let Some(client_secret) = oauth.client_secret {
lines.push(format!(
" \"client_secret\": {}",
serde_json::to_string(&client_secret).unwrap()
));
} else {
lines.push(String::from(
" /// Optional client secret for confidential clients\n // \"client_secret\": \"your-client-secret\"",
));
}
lines.push(String::from(" },"));
lines.join("\n")
},
);
format!(
r#"{{
/// Configure an MCP server that you connect to over HTTP
@ -290,7 +333,7 @@ fn context_server_http_input(
/// The name of your remote MCP server
"{name}": {{
/// The URL of the remote MCP server
"url": "{url}",
"url": "{url}",{oauth}
"headers": {{
/// Any headers to send along
{headers}
@ -300,12 +343,21 @@ fn context_server_http_input(
)
}
fn parse_http_input(text: &str) -> Result<(ContextServerId, String, HashMap<String, String>)> {
fn parse_http_input(
text: &str,
) -> Result<(
ContextServerId,
String,
HashMap<String, String>,
Option<OAuthClientSettings>,
)> {
#[derive(Deserialize)]
struct Temp {
url: String,
#[serde(default)]
headers: HashMap<String, String>,
#[serde(default)]
oauth: Option<OAuthClientSettings>,
}
let value: HashMap<String, Temp> = serde_json_lenient::from_str(text)?;
if value.len() != 1 {
@ -314,7 +366,12 @@ fn parse_http_input(text: &str) -> Result<(ContextServerId, String, HashMap<Stri
let (key, value) = value.into_iter().next().unwrap();
Ok((ContextServerId(key.into()), value.url, value.headers))
Ok((
ContextServerId(key.into()),
value.url,
value.headers,
value.oauth,
))
}
fn resolve_context_server_extension(
@ -349,8 +406,16 @@ fn resolve_context_server_extension(
enum State {
Idle,
Waiting,
AuthRequired { server_id: ContextServerId },
Authenticating { _server_id: ContextServerId },
AuthRequired {
server_id: ContextServerId,
},
ClientSecretRequired {
server_id: ContextServerId,
error: Option<SharedString>,
},
Authenticating {
server_id: ContextServerId,
},
Error(SharedString),
}
@ -361,10 +426,47 @@ pub struct ConfigureContextServerModal {
state: State,
original_server_id: Option<ContextServerId>,
scroll_handle: ScrollHandle,
secret_editor: Entity<Editor>,
_auth_subscription: Option<Subscription>,
}
impl ConfigureContextServerModal {
fn initial_state(
context_server_store: &Entity<ContextServerStore>,
target: &ConfigurationTarget,
cx: &App,
) -> State {
let Some(server_id) = (match target {
ConfigurationTarget::Existing { id, .. }
| ConfigurationTarget::ExistingHttp { id, .. }
| ConfigurationTarget::Extension { id, .. } => Some(id),
ConfigurationTarget::New => None,
}) else {
return State::Idle;
};
match context_server_store.read(cx).status_for_server(server_id) {
Some(ContextServerStatus::AuthRequired) => State::AuthRequired {
server_id: server_id.clone(),
},
Some(ContextServerStatus::ClientSecretRequired { error }) => {
State::ClientSecretRequired {
server_id: server_id.clone(),
error: error.map(SharedString::from),
}
}
Some(ContextServerStatus::Authenticating) => State::Authenticating {
server_id: server_id.clone(),
},
Some(ContextServerStatus::Error(error)) => State::Error(error.into()),
Some(ContextServerStatus::Starting)
| Some(ContextServerStatus::Running)
| Some(ContextServerStatus::Stopped)
| None => State::Idle,
}
}
pub fn register(
workspace: &mut Workspace,
language_registry: Arc<LanguageRegistry>,
@ -426,12 +528,14 @@ impl ConfigureContextServerModal {
url,
headers,
timeout: _,
..
oauth,
} => Some(ConfigurationTarget::ExistingHttp {
id: server_id,
url,
headers,
oauth,
}),
ContextServerSettings::Extension { .. } => {
match workspace
.update(cx, |workspace, cx| {
@ -468,9 +572,10 @@ impl ConfigureContextServerModal {
let workspace_handle = cx.weak_entity();
let context_server_store = workspace.project().read(cx).context_server_store();
workspace.toggle_modal(window, cx, |window, cx| Self {
context_server_store,
context_server_store: context_server_store.clone(),
workspace: workspace_handle,
state: State::Idle,
state: Self::initial_state(&context_server_store, &target, cx),
original_server_id: match &target {
ConfigurationTarget::Existing { id, .. } => Some(id.clone()),
ConfigurationTarget::ExistingHttp { id, .. } => Some(id.clone()),
@ -485,6 +590,16 @@ impl ConfigureContextServerModal {
cx,
),
scroll_handle: ScrollHandle::new(),
secret_editor: cx.new(|cx| {
let mut editor = Editor::single_line(window, cx);
editor.set_placeholder_text(
"Enter client secret (leave empty for public clients)",
window,
cx,
);
editor.set_masked(true, cx);
editor
}),
_auth_subscription: None,
})
})
@ -497,13 +612,12 @@ impl ConfigureContextServerModal {
}
fn confirm(&mut self, _: &menu::Confirm, cx: &mut Context<Self>) {
if matches!(
self.state,
State::Waiting | State::AuthRequired { .. } | State::Authenticating { .. }
) {
if matches!(self.state, State::Waiting | State::Authenticating { .. }) {
return;
}
self._auth_subscription = None;
self.state = State::Idle;
let Some(workspace) = self.workspace.upgrade() else {
return;
@ -519,7 +633,7 @@ impl ConfigureContextServerModal {
self.state = State::Waiting;
let existing_server = self.context_server_store.read(cx).get_running_server(&id);
let existing_server = self.context_server_store.read(cx).get_server(&id);
if existing_server.is_some() {
self.context_server_store.update(cx, |store, cx| {
store.stop_server(&id, cx).log_err();
@ -542,6 +656,13 @@ impl ConfigureContextServerModal {
this.state = State::AuthRequired { server_id: id };
cx.notify();
}
Ok(ContextServerStatus::ClientSecretRequired { error }) => {
this.state = State::ClientSecretRequired {
server_id: id,
error: error.map(SharedString::from),
};
cx.notify();
}
Err(err) => {
this.set_error(err, cx);
}
@ -581,13 +702,33 @@ impl ConfigureContextServerModal {
cx.emit(DismissEvent);
}
fn cancel_authentication(&mut self, server_id: &ContextServerId, cx: &mut Context<Self>) {
self._auth_subscription = None;
self.context_server_store.update(cx, |store, cx| {
store.stop_server(server_id, cx).log_err();
});
self.state = State::Idle;
cx.notify();
}
fn authenticate(&mut self, server_id: ContextServerId, cx: &mut Context<Self>) {
self.context_server_store.update(cx, |store, cx| {
store.authenticate_server(&server_id, cx).log_err();
});
self.await_auth_outcome(server_id, cx);
}
fn submit_client_secret(&mut self, server_id: ContextServerId, cx: &mut Context<Self>) {
let secret = self.secret_editor.read(cx).text(cx);
self.context_server_store.update(cx, |store, cx| {
store.submit_client_secret(&server_id, secret, cx).log_err();
});
self.await_auth_outcome(server_id, cx);
}
fn await_auth_outcome(&mut self, server_id: ContextServerId, cx: &mut Context<Self>) {
self.state = State::Authenticating {
_server_id: server_id.clone(),
server_id: server_id.clone(),
};
self._auth_subscription = Some(cx.subscribe(
@ -610,6 +751,14 @@ impl ConfigureContextServerModal {
};
cx.notify();
}
ContextServerStatus::ClientSecretRequired { error } => {
this._auth_subscription = None;
this.state = State::ClientSecretRequired {
server_id: event.server_id.clone(),
error: error.clone().map(SharedString::from),
};
cx.notify();
}
ContextServerStatus::Error(error) => {
this._auth_subscription = None;
this.set_error(error.clone(), cx);
@ -814,10 +963,7 @@ impl ConfigureContextServerModal {
fn render_modal_footer(&self, cx: &mut Context<Self>) -> ModalFooter {
let focus_handle = self.focus_handle(cx);
let is_busy = matches!(
self.state,
State::Waiting | State::AuthRequired { .. } | State::Authenticating { .. }
);
let is_busy = matches!(self.state, State::Waiting | State::Authenticating { .. });
ModalFooter::new()
.start_slot::<Button>(
@ -944,6 +1090,112 @@ impl ConfigureContextServerModal {
)
}
fn render_client_secret_required(
&self,
server_id: &ContextServerId,
error: Option<SharedString>,
cx: &mut Context<Self>,
) -> Div {
let settings = ThemeSettings::get_global(cx);
let text_style = TextStyle {
color: cx.theme().colors().text,
font_family: settings.buffer_font.family.clone(),
font_fallbacks: settings.buffer_font.fallbacks.clone(),
font_size: settings.buffer_font_size(cx).into(),
font_weight: settings.buffer_font.weight,
line_height: relative(settings.buffer_line_height.value()),
..Default::default()
};
v_flex()
.w_full()
.gap_2()
.when_some(error, |this, error| {
this.child(Self::render_modal_error(error))
})
.child(
h_flex()
.gap_1p5()
.child(
Icon::new(IconName::Info)
.size(IconSize::Small)
.color(Color::Muted),
)
.child(
Label::new(
"Enter your OAuth client secret, or leave empty for public clients",
)
.size(LabelSize::Small)
.color(Color::Muted),
),
)
.child(
h_flex()
.w_full()
.gap_2()
.capture_action({
let server_id = server_id.clone();
cx.listener(move |this, _: &editor::actions::Newline, _window, cx| {
this.submit_client_secret(server_id.clone(), cx);
})
})
.child(div().flex_1().child(EditorElement::new(
&self.secret_editor,
EditorStyle {
background: cx.theme().colors().editor_background,
local_player: cx.theme().players().local(),
text: text_style,
syntax: cx.theme().syntax().clone(),
..Default::default()
},
)))
.child(
Button::new("submit-client-secret", "Submit")
.style(ButtonStyle::Outlined)
.label_size(LabelSize::Small)
.on_click({
let server_id = server_id.clone();
cx.listener(move |this, _event, _window, cx| {
this.submit_client_secret(server_id.clone(), cx);
})
}),
),
)
}
fn render_authenticating(&self, server_id: &ContextServerId, cx: &mut Context<Self>) -> Div {
h_flex()
.h_8()
.gap_2()
.justify_center()
.child(
h_flex()
.gap_1p5()
.child(
Icon::new(IconName::LoadCircle)
.size(IconSize::XSmall)
.color(Color::Muted)
.with_rotate_animation(3),
)
.child(
Label::new("Authenticating…")
.size(LabelSize::Small)
.color(Color::Muted),
),
)
.child(
Button::new("cancel-authentication", "Cancel")
.style(ButtonStyle::Outlined)
.label_size(LabelSize::Small)
.on_click({
let server_id = server_id.clone();
cx.listener(move |this, _event, _window, cx| {
this.cancel_authentication(&server_id, cx);
})
}),
)
}
fn render_modal_error(error: SharedString) -> Div {
h_flex()
.h_8()
@ -1003,8 +1255,15 @@ impl Render for ConfigureContextServerModal {
State::AuthRequired { server_id } => {
self.render_auth_required(&server_id.clone(), cx)
}
State::Authenticating { .. } => {
self.render_loading("Authenticating…")
State::ClientSecretRequired { server_id, error } => {
self.render_client_secret_required(
&server_id.clone(),
error.clone(),
cx,
)
}
State::Authenticating { server_id } => {
self.render_authenticating(&server_id.clone(), cx)
}
State::Error(error) => {
Self::render_modal_error(error.clone())
@ -1040,7 +1299,9 @@ fn wait_for_context_server(
}
match status {
ContextServerStatus::Running | ContextServerStatus::AuthRequired => {
ContextServerStatus::Running
| ContextServerStatus::AuthRequired
| ContextServerStatus::ClientSecretRequired { .. } => {
if let Some(tx) = tx.lock().take() {
let _ = tx.send(Ok(status.clone()));
}
@ -1104,3 +1365,52 @@ pub(crate) fn default_markdown_style(window: &Window, cx: &App) -> MarkdownStyle
..Default::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_http_input_reads_oauth_settings() {
let (id, url, headers, oauth) = parse_http_input(
r#"{
"figma": {
"url": "https://mcp.figma.com/mcp",
"oauth": {
"client_id": "client-id",
"client_secret": "client-secret"
},
"headers": {
"X-Test": "test"
}
}
}"#,
)
.unwrap();
assert_eq!(id, ContextServerId("figma".into()));
assert_eq!(url, "https://mcp.figma.com/mcp");
assert_eq!(headers.get("X-Test"), Some(&String::from("test")));
let oauth = oauth.expect("oauth should be present");
assert_eq!(oauth.client_id, "client-id");
assert_eq!(oauth.client_secret.as_deref(), Some("client-secret"));
}
#[test]
fn context_server_http_input_preserves_existing_oauth_settings() {
let text = context_server_http_input(Some((
ContextServerId("figma".into()),
String::from("https://mcp.figma.com/mcp"),
HashMap::default(),
Some(OAuthClientSettings {
client_id: String::from("client-id"),
client_secret: Some(String::from("client-secret")),
}),
)));
let (_, _, _, oauth) = parse_http_input(&text).unwrap();
let oauth = oauth.expect("oauth should be present");
assert_eq!(oauth.client_id, "client-id");
assert_eq!(oauth.client_secret.as_deref(), Some("client-secret"));
}
}

View file

@ -138,7 +138,7 @@ impl AgentDiffPane {
.changed_buffers(cx);
// Sort edited files alphabetically for consistency with Git diff view
let mut sorted_buffers: Vec<_> = changed_buffers.iter().collect();
let mut sorted_buffers: Vec<_> = changed_buffers.collect();
sorted_buffers.sort_by(|(buffer_a, _), (buffer_b, _)| {
let path_a = buffer_a.read(cx).file().map(|f| f.path().clone());
let path_b = buffer_b.read(cx).file().map(|f| f.path().clone());
@ -566,6 +566,10 @@ impl Item for AgentDiffPane {
.for_each_project_item(cx, f)
}
fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
self.editor.read(cx).active_project_path(cx)
}
fn set_nav_history(
&mut self,
nav_history: ItemNavHistory,
@ -1531,7 +1535,7 @@ impl AgentDiff {
};
let action_log = thread.read(cx).action_log();
let changed_buffers = action_log.read(cx).changed_buffers(cx);
let changed_buffers = action_log.read(cx).changed_buffers(cx).collect::<Vec<_>>();
let mut unaffected = self.reviewing_editors.clone();
@ -1765,12 +1769,13 @@ impl AgentDiff {
{
let changed_buffers = thread.read(cx).action_log().read(cx).changed_buffers(cx);
let mut keys = changed_buffers.keys();
keys.find(|k| *k == &curr_buffer);
let mut keys = changed_buffers.map(|(buffer, _)| buffer);
keys.find(|k| *k == curr_buffer);
let next_project_path = keys
.next()
.filter(|k| *k != &curr_buffer)
.filter(|k| *k != curr_buffer)
.and_then(|after| after.read(cx).project_path(cx));
drop(keys);
if let Some(path) = next_project_path {
let task = workspace.open_path(path, None, true, window, cx);
@ -2253,7 +2258,7 @@ mod tests {
});
let editor2_path = editor2
.read_with(cx, |editor, cx| editor.project_path(cx))
.read_with(cx, |editor, cx| editor.active_project_path(cx))
.unwrap();
assert_eq!(editor2_path, buffer_path2);

File diff suppressed because it is too large Load diff

View file

@ -34,7 +34,6 @@ enum RegistryInstallStatus {
NotInstalled,
InstalledRegistry,
InstalledCustom,
InstalledExtension,
}
#[derive(IntoElement)]
@ -155,9 +154,6 @@ impl AgentRegistryPage {
RegistryInstallStatus::InstalledRegistry
}
CustomAgentServerSettings::Custom { .. } => RegistryInstallStatus::InstalledCustom,
CustomAgentServerSettings::Extension { .. } => {
RegistryInstallStatus::InstalledExtension
}
};
self.installed_statuses.insert(id.clone(), status);
}
@ -560,9 +556,6 @@ impl AgentRegistryPage {
RegistryInstallStatus::InstalledCustom => Button::new(button_id, "Installed")
.style(ButtonStyle::OutlinedGhost)
.disabled(true),
RegistryInstallStatus::InstalledExtension => Button::new(button_id, "Installed")
.style(ButtonStyle::OutlinedGhost)
.disabled(true),
}
}
}

View file

@ -26,6 +26,7 @@ mod model_selector_popover;
mod profile_selector;
mod terminal_codegen;
mod terminal_inline_assistant;
pub mod terminal_thread_metadata_store;
#[cfg(any(test, feature = "test-support"))]
pub mod test_support;
mod thread_import;
@ -42,10 +43,12 @@ use ::ui::IconName;
use agent_client_protocol::schema as acp;
use agent_settings::{AgentProfileId, AgentSettings};
use command_palette_hooks::CommandPaletteFilter;
use editor::{Editor, SelectionEffects, scroll::Autoscroll};
use feature_flags::FeatureFlagAppExt as _;
use fs::Fs;
use gpui::{
Action, App, Context, Entity, ImageSource, Resource, SharedString, SharedUri, Window, actions,
Action, App, Context, Entity, ImageSource, Resource, SharedString, SharedUri, TaskExt, Window,
actions,
};
use language::{
LanguageRegistry,
@ -55,10 +58,11 @@ use language_model::{
ConfiguredModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
};
use project::{AgentId, DisableAiSettings};
use prompt_store::PromptBuilder;
use prompt_store::{PromptBuilder, rules_to_skills_migration};
use rope::Point;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use settings::{LanguageModelSelection, Settings as _, SettingsStore};
use settings::{LanguageModelSelection, Settings as _, SettingsStore, SidebarSide};
use std::any::TypeId;
use std::path::{Path, PathBuf};
use workspace::Workspace;
@ -111,8 +115,69 @@ pub(crate) fn resolve_agent_image(
None
}
pub(crate) fn open_abs_path_at_point(
workspace: &mut Workspace,
abs_path: PathBuf,
point: Point,
window: &mut Window,
cx: &mut Context<Workspace>,
) -> bool {
let project = workspace.project();
let Some(path) = project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
else {
return false;
};
let item = workspace.open_path(path, None, true, window, cx);
window
.spawn(cx, async move |cx| {
let Some(editor) = item.await?.downcast::<Editor>() else {
return Ok(());
};
let range = point..point;
editor
.update_in(cx, |editor, window, cx| {
editor.change_selections(
SelectionEffects::scroll(Autoscroll::center()),
window,
cx,
|selections| selections.select_ranges([range]),
);
})
.ok();
anyhow::Ok(())
})
.detach_and_log_err(cx);
true
}
pub const DEFAULT_THREAD_TITLE: &str = "New Agent Thread";
const PARALLEL_AGENT_LAYOUT_BACKFILL_KEY: &str = "parallel_agent_layout_backfilled";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AgentThreadSource {
AgentPanel,
GitPanel,
Sidebar,
}
impl AgentThreadSource {
pub fn as_str(self) -> &'static str {
match self {
Self::AgentPanel => "agent_panel",
Self::GitPanel => "git_panel",
Self::Sidebar => "sidebar",
}
}
}
pub(crate) fn agent_sidebar_side(cx: &App) -> &'static str {
match AgentSettings::get_global(cx).sidebar_side() {
SidebarSide::Left => "left",
SidebarSide::Right => "right",
}
}
actions!(
agent,
[
@ -134,6 +199,8 @@ actions!(
ArchiveSelectedThread,
/// Removes the currently selected thread.
RemoveSelectedThread,
/// Renames the currently selected thread.
RenameSelectedThread,
/// Starts a chat conversation with follow-up enabled.
ChatWithFollow,
/// Cycles to the next inline assist suggestion.
@ -178,6 +245,8 @@ actions!(
ResetTrialUpsell,
/// Resets the trial end upsell notification.
ResetTrialEndUpsell,
/// Re-enables the fast mode warning for every provider and model.
ResetFastModeWarnings,
/// Opens the "Add Context" menu in the message editor.
OpenAddContextMenu,
/// Interrupts the current generation and sends the message immediately.
@ -218,6 +287,8 @@ actions!(
ScrollOutputToNextMessage,
/// Import agent threads from other Zed release channels (e.g. Preview, Nightly).
ImportThreadsFromOtherChannels,
/// Starts a new terminal thread.
NewTerminalThread,
]
);
@ -480,6 +551,7 @@ pub fn init(
) {
agent::ThreadStore::init_global(cx);
rules_library::init(cx);
skill_creator::init(cx);
if !is_eval {
// Initializing the language model from the user settings messes with the eval, so we only initialize them when
// we're not running inside of the eval.
@ -488,6 +560,7 @@ pub fn init(
agent_panel::init(cx);
context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
thread_metadata_store::init(cx);
terminal_thread_metadata_store::init(cx);
inline_assistant::init(fs.clone(), prompt_builder.clone(), cx);
terminal_inline_assistant::init(fs.clone(), prompt_builder, cx);
@ -555,6 +628,24 @@ pub fn init(
})
.detach();
// Kick off the one-time migration of non-Default Rules to global
// Skills, deferred until server feature flags arrive.
//
// The migration itself is idempotent and no longer gated on a flag,
// but the deferral via `on_flags_ready` still matters: the migration
// writes to the on-disk `GlobalKeyValueStore`, which dispatches work
// on the `sqlezWorker` background thread. In `gpui::test` contexts,
// server flags are never received, so this callback never fires —
// which keeps that sqlite worker activity from racing with the
// `TestScheduler` and tripping its non-determinism panic.
{
let fs = fs.clone();
cx.on_flags_ready(move |_, cx| {
rules_to_skills_migration::migrate_rules_to_skills_if_needed(fs.clone(), cx);
})
.detach();
}
maybe_backfill_editor_layout(fs, is_new_install, cx);
}
@ -604,6 +695,12 @@ fn update_command_palette_filter(cx: &mut App) {
TypeId::of::<ToggleEditPrediction>(),
];
let open_rules_library_action = [TypeId::of::<zed_actions::assistant::OpenRulesLibrary>()];
let skill_creator_actions = [
TypeId::of::<zed_actions::assistant::OpenSkillCreator>(),
TypeId::of::<zed_actions::assistant::CreateSkillFromUrl>(),
];
if disable_ai {
filter.hide_namespace("agent");
filter.hide_namespace("agents");
@ -652,6 +749,19 @@ fn update_command_palette_filter(cx: &mut App) {
filter.show_namespace("multi_workspace");
}
// Hide `assistant: open rules library` — Rules are surfaced
// through the Skills UI now. Applied after the disable-ai /
// agent-enabled branches so it overrides the
// `show_namespace("assistant")` call above without affecting the
// rest of that namespace's actions.
if !disable_ai {
filter.hide_action_types(&open_rules_library_action);
filter.show_action_types(skill_creator_actions.iter());
} else {
filter.show_action_types(open_rules_library_action.iter());
filter.hide_action_types(&skill_creator_actions);
}
});
}
@ -788,6 +898,18 @@ mod tests {
!filter.is_hidden(&NewThread),
"NewThread should be visible by default"
);
assert!(
!filter.is_hidden(&NewTerminalThread),
"NewTerminalThread should be visible by default"
);
assert!(
!filter.is_hidden(&zed_actions::assistant::OpenSkillCreator),
"OpenSkillCreator should be visible by default"
);
assert!(
!filter.is_hidden(&zed_actions::assistant::CreateSkillFromUrl),
"CreateSkillFromUrl should be visible by default"
);
});
// Disable agent
@ -807,6 +929,10 @@ mod tests {
filter.is_hidden(&NewThread),
"NewThread should be hidden when agent is disabled"
);
assert!(
filter.is_hidden(&NewTerminalThread),
"NewTerminalThread should be hidden when agent is disabled"
);
});
// Test EditPredictionProvider

File diff suppressed because it is too large Load diff

View file

@ -19,7 +19,7 @@ use ui::{
};
use util::ResultExt as _;
use crate::ui::{HoldForDefault, documentation_aside_side};
use crate::ui::documentation_aside_side;
const PICKER_THRESHOLD: usize = 5;
@ -101,6 +101,13 @@ impl ConfigOptionsView {
return false;
};
self.agent_server.set_default_config_option(
config_id.0.as_ref(),
Some(next_value.0.as_ref()),
self.fs.clone(),
cx,
);
let task = self
.config_options
.set_config_option(config_id, next_value, cx);
@ -412,7 +419,7 @@ struct ConfigOptionPickerDelegate {
filtered_entries: Vec<ConfigOptionPickerEntry>,
all_options: Vec<ConfigOptionValue>,
selected_index: usize,
selected_description: Option<(usize, SharedString, bool)>,
selected_description: Option<(usize, SharedString)>,
favorites: HashSet<acp::SessionConfigValueId>,
_settings_subscription: Subscription,
}
@ -544,28 +551,16 @@ impl PickerDelegate for ConfigOptionPickerDelegate {
})
}
fn confirm(&mut self, _secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
fn confirm(&mut self, _secondary: bool, _window: &mut Window, cx: &mut Context<Picker<Self>>) {
if let Some(ConfigOptionPickerEntry::Option(option)) =
self.filtered_entries.get(self.selected_index)
{
if window.modifiers().secondary() {
let default_value = self
.agent_server
.default_config_option(self.config_id.0.as_ref(), cx);
let is_default = default_value.as_deref() == Some(&*option.value.0);
self.agent_server.set_default_config_option(
self.config_id.0.as_ref(),
if is_default {
None
} else {
Some(option.value.0.as_ref())
},
self.fs.clone(),
cx,
);
}
self.agent_server.set_default_config_option(
self.config_id.0.as_ref(),
Some(option.value.0.as_ref()),
self.fs.clone(),
cx,
);
let task = self.config_options.set_config_option(
self.config_id.clone(),
option.value.clone(),
@ -614,11 +609,6 @@ impl PickerDelegate for ConfigOptionPickerDelegate {
let current_value = self.current_value();
let is_selected = current_value.as_ref() == Some(&option.value);
let default_value = self
.agent_server
.default_config_option(self.config_id.0.as_ref(), cx);
let is_default = default_value.as_deref() == Some(&*option.value.0);
let is_favorite = self.favorites.contains(&option.value);
let option_name = option.name.clone();
@ -631,9 +621,8 @@ impl PickerDelegate for ConfigOptionPickerDelegate {
let desc: SharedString = desc.into();
this.on_hover(cx.listener(move |menu, hovered, _, cx| {
if *hovered {
menu.delegate.selected_description =
Some((ix, desc.clone(), is_default));
} else if matches!(menu.delegate.selected_description, Some((id, _, _)) if id == ix)
menu.delegate.selected_description = Some((ix, desc.clone()));
} else if matches!(menu.delegate.selected_description, Some((id, _)) if id == ix)
{
menu.delegate.selected_description = None;
}
@ -688,29 +677,20 @@ impl PickerDelegate for ConfigOptionPickerDelegate {
_window: &mut Window,
cx: &mut Context<Picker<Self>>,
) -> Option<ui::DocumentationAside> {
self.selected_description
.as_ref()
.map(|(_, description, is_default)| {
let description = description.clone();
let is_default = *is_default;
self.selected_description.as_ref().map(|(_, description)| {
let description = description.clone();
let side = documentation_aside_side(cx);
let side = documentation_aside_side(cx);
ui::DocumentationAside::new(
side,
Rc::new(move |_| {
v_flex()
.gap_1()
.child(Label::new(description.clone()))
.child(HoldForDefault::new(is_default))
.into_any_element()
}),
)
})
ui::DocumentationAside::new(
side,
Rc::new(move |_| Label::new(description.clone()).into_any_element()),
)
})
}
fn documentation_aside_index(&self) -> Option<usize> {
self.selected_description.as_ref().map(|(ix, _, _)| *ix)
self.selected_description.as_ref().map(|(ix, _)| *ix)
}
}
@ -878,3 +858,143 @@ fn count_config_options(option: &acp::SessionConfigOption) -> usize {
_ => 0,
}
}
#[cfg(test)]
mod tests {
use super::*;
use acp_thread::AgentConnection;
use fs::FakeFs;
use gpui::TestAppContext;
use parking_lot::Mutex;
use project::{AgentId, Project};
use std::{any::Any, cell::RefCell};
#[gpui::test]
fn cycling_config_option_saves_selected_value_as_default(cx: &mut TestAppContext) {
let agent_server = Rc::new(TestAgentServer::default());
let config_options = Rc::new(TestSessionConfigOptions::new(vec![
acp::SessionConfigOption::select(
"mode",
"Mode",
"auto",
vec![
acp::SessionConfigSelectOption::new("auto", "Auto"),
acp::SessionConfigSelectOption::new("manual", "Manual"),
],
)
.category(acp::SessionConfigOptionCategory::Mode),
]));
let fs: Arc<dyn Fs> = FakeFs::new(cx.executor());
cx.update(|cx| {
let config_options: Rc<dyn AgentSessionConfigOptions> = config_options.clone();
let agent_server: Rc<dyn AgentServer> = agent_server.clone();
let fs = fs.clone();
let view = cx.new(|_| ConfigOptionsView {
config_option_ids: ConfigOptionsView::config_option_ids(&config_options),
config_options,
selectors: Vec::new(),
agent_server,
fs,
_refresh_task: Task::ready(()),
});
assert!(view.update(cx, |view, cx| {
view.cycle_category_option(acp::SessionConfigOptionCategory::Mode, false, cx)
}));
});
assert_eq!(
agent_server.saved_defaults.lock().as_slice(),
&[("mode".to_string(), Some("manual".to_string()))]
);
assert_eq!(
config_options.set_values.borrow().as_slice(),
&[("mode".to_string(), "manual".to_string())]
);
}
#[derive(Default)]
struct TestAgentServer {
saved_defaults: Arc<Mutex<Vec<(String, Option<String>)>>>,
}
impl AgentServer for TestAgentServer {
fn logo(&self) -> IconName {
IconName::ZedAssistant
}
fn agent_id(&self) -> AgentId {
AgentId::new("test-agent")
}
fn connect(
&self,
_delegate: agent_servers::AgentServerDelegate,
_project: Entity<Project>,
_cx: &mut App,
) -> Task<anyhow::Result<Rc<dyn AgentConnection>>> {
Task::ready(Err(anyhow::anyhow!("test agent server cannot connect")))
}
fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
self
}
fn set_default_config_option(
&self,
config_id: &str,
value_id: Option<&str>,
_fs: Arc<dyn Fs>,
_cx: &mut App,
) {
self.saved_defaults.lock().push((
config_id.to_string(),
value_id.map(|value| value.to_string()),
));
}
}
struct TestSessionConfigOptions {
options: RefCell<Vec<acp::SessionConfigOption>>,
set_values: RefCell<Vec<(String, String)>>,
}
impl TestSessionConfigOptions {
fn new(options: Vec<acp::SessionConfigOption>) -> Self {
Self {
options: RefCell::new(options),
set_values: RefCell::new(Vec::new()),
}
}
}
impl AgentSessionConfigOptions for TestSessionConfigOptions {
fn config_options(&self) -> Vec<acp::SessionConfigOption> {
self.options.borrow().clone()
}
fn set_config_option(
&self,
config_id: acp::SessionConfigId,
value: acp::SessionConfigValueId,
_cx: &mut App,
) -> Task<anyhow::Result<Vec<acp::SessionConfigOption>>> {
self.set_values
.borrow_mut()
.push((config_id.0.to_string(), value.0.to_string()));
let options = {
let mut options = self.options.borrow_mut();
if let Some(option) = options.iter_mut().find(|option| option.id == config_id)
&& let acp::SessionConfigKind::Select(select) = &mut option.kind
{
select.current_value = value;
}
options.clone()
};
Task::ready(Ok(options))
}
}
}

View file

@ -53,7 +53,6 @@ pub fn load_context(mention_set: &Entity<MentionSet>, cx: &mut App) -> Task<Opti
}
Mention::Image(mention_image) => loaded_context.images.push(LanguageModelImage {
source: mention_image.data,
..LanguageModelImage::empty()
}),
Mention::Link => {}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -12,6 +12,7 @@ use agent_client_protocol::schema as acp;
use anyhow::Context as _;
use db::kvp::KeyValueStore;
use gpui::{App, AppContext as _, Entity, Task};
use itertools::Itertools;
use ui::SharedString;
use util::ResultExt as _;
use workspace::Workspace;
@ -28,7 +29,7 @@ pub fn read(thread_id: ThreadId, cx: &App) -> Option<Vec<acp::ContentBlock>> {
let kvp = KeyValueStore::global(cx);
let raw = kvp
.scoped(NAMESPACE)
.read(&thread_id_key(thread_id))
.read(&thread_id.to_key_string())
.log_err()
.flatten()?;
serde_json::from_str(&raw).log_err()
@ -40,7 +41,7 @@ pub fn write(
cx: &App,
) -> Task<anyhow::Result<()>> {
let kvp = KeyValueStore::global(cx);
let key = thread_id_key(thread_id);
let key = thread_id.to_key_string();
let payload = match serde_json::to_string(prompt).context("serializing draft prompt") {
Ok(payload) => payload,
Err(err) => return Task::ready(Err(err)),
@ -50,12 +51,43 @@ pub fn write(
pub fn delete(thread_id: ThreadId, cx: &App) -> Task<anyhow::Result<()>> {
let kvp = KeyValueStore::global(cx);
let key = thread_id_key(thread_id);
let key = thread_id.to_key_string();
cx.background_spawn(async move { kvp.scoped(NAMESPACE).delete(key).await })
}
fn thread_id_key(thread_id: ThreadId) -> String {
thread_id.to_key_string()
pub fn draft_has_user_content<'a>(
thread_id: ThreadId,
workspaces: impl IntoIterator<Item = &'a Entity<Workspace>>,
cx: &App,
) -> bool {
let mut found_live_copy = false;
for blocks in workspaces
.into_iter()
.filter_map(|workspace| workspace.read(cx).panel::<AgentPanel>(cx))
.filter_map(|panel| {
panel
.read(cx)
.draft_prompt_blocks_if_in_memory(thread_id, cx)
})
{
found_live_copy = true;
if blocks_have_user_content(&blocks) {
return true;
}
}
if found_live_copy {
false
} else {
read(thread_id, cx).is_some_and(|blocks| blocks_have_user_content(&blocks))
}
}
fn blocks_have_user_content(blocks: &[acp::ContentBlock]) -> bool {
blocks.iter().any(|block| match block {
acp::ContentBlock::Text(text) => !text.text.trim().is_empty(),
_ => true,
})
}
/// Rewrites `[@Something](scheme://...)` mention links as `@Something` so the
@ -128,7 +160,6 @@ pub fn display_label_for_draft(
acp::ContentBlock::ResourceLink(link) => Some(link.uri.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join(" ");
truncate_draft_label(&raw)
}

View file

@ -63,7 +63,6 @@ pub struct PromptEditor<T> {
pub editor: Entity<Editor>,
mode: PromptEditorMode,
mention_set: Entity<MentionSet>,
prompt_store: Option<Entity<PromptStore>>,
workspace: WeakEntity<Workspace>,
model_selector: Entity<AgentModelSelector>,
edited_since_done: bool,
@ -334,7 +333,6 @@ impl<T: 'static> PromptEditor<T> {
PromptEditorCompletionProviderDelegate,
cx.weak_entity(),
self.mention_set.clone(),
self.prompt_store.clone(),
self.workspace.clone(),
))));
});
@ -1214,7 +1212,7 @@ impl PromptCompletionProviderDelegate for PromptEditorCompletionProviderDelegate
PromptContextType::Symbol,
PromptContextType::Thread,
PromptContextType::Fetch,
PromptContextType::Rules,
PromptContextType::Skill,
]
}
@ -1286,7 +1284,6 @@ impl PromptEditor<BufferCodegen> {
let mut this: PromptEditor<BufferCodegen> = PromptEditor {
editor: prompt_editor.clone(),
mention_set,
prompt_store,
workspace,
model_selector: cx.new(|cx| {
AgentModelSelector::new(
@ -1438,7 +1435,6 @@ impl PromptEditor<TerminalCodegen> {
let mut this = Self {
editor: prompt_editor.clone(),
mention_set,
prompt_store,
workspace,
model_selector: cx.new(|cx| {
AgentModelSelector::new(

View file

@ -63,6 +63,7 @@ pub struct MentionSet {
thread_store: Option<Entity<ThreadStore>>,
prompt_store: Option<Entity<PromptStore>>,
mentions: HashMap<CreaseId, (MentionUri, MentionTask)>,
crease_entities: HashMap<CreaseId, Entity<LoadingContext>>,
}
impl MentionSet {
@ -76,6 +77,7 @@ impl MentionSet {
thread_store,
prompt_store,
mentions: HashMap::default(),
crease_entities: HashMap::default(),
}
}
@ -110,12 +112,24 @@ impl MentionSet {
for (crease_id, crease) in snapshot.crease_snapshot.creases() {
if !crease.range().start.is_valid(snapshot.buffer_snapshot()) {
self.mentions.remove(&crease_id);
self.crease_entities.remove(&crease_id);
}
}
}
pub fn insert_mention(&mut self, crease_id: CreaseId, uri: MentionUri, task: MentionTask) {
pub fn insert_mention(
&mut self,
crease_id: CreaseId,
uri: MentionUri,
task: MentionTask,
crease_entity: Option<Entity<LoadingContext>>,
cx: &mut App,
) {
self.mentions.insert(crease_id, (uri, task));
if let Some(entity) = crease_entity {
self.crease_entities.insert(crease_id, entity);
}
self.recompute_disambiguation(cx);
}
/// Creates the appropriate confirmation task for a mention based on its URI type.
@ -140,6 +154,9 @@ impl MentionSet {
..
} => self.confirm_mention_for_symbol(abs_path, line_range, cx),
MentionUri::Rule { id, .. } => self.confirm_mention_for_rule(id, cx),
MentionUri::Skill {
skill_file_path, ..
} => self.confirm_mention_for_skill(skill_file_path, cx),
MentionUri::Diagnostics {
include_errors,
include_warnings,
@ -150,6 +167,7 @@ impl MentionSet {
MentionUri::Selection {
abs_path: Some(abs_path),
line_range,
..
} => self.confirm_mention_for_symbol(abs_path, line_range, cx),
MentionUri::Selection { abs_path: None, .. } => Task::ready(Err(anyhow!(
"Untitled buffer selection mentions are not supported for paste"
@ -162,8 +180,10 @@ impl MentionSet {
}
}
pub fn remove_mention(&mut self, crease_id: &CreaseId) {
pub fn remove_mention(&mut self, crease_id: &CreaseId, cx: &mut App) {
self.mentions.remove(crease_id);
self.crease_entities.remove(crease_id);
self.recompute_disambiguation(cx);
}
pub fn creases(&self) -> HashSet<CreaseId> {
@ -193,13 +213,32 @@ impl MentionSet {
}
pub fn set_mentions(&mut self, mentions: HashMap<CreaseId, (MentionUri, MentionTask)>) {
self.crease_entities
.retain(|id, _| mentions.contains_key(id));
self.mentions = mentions;
}
pub fn clear(&mut self) -> impl Iterator<Item = (CreaseId, (MentionUri, MentionTask))> {
self.crease_entities.clear();
self.mentions.drain()
}
fn recompute_disambiguation(&self, cx: &mut App) {
let labels =
compute_disambiguated_labels(self.mentions.iter().map(|(id, (uri, _))| (*id, uri)));
for (crease_id, new_label) in labels {
if let Some(entity) = self.crease_entities.get(&crease_id) {
entity.update(cx, |loading_ctx, cx| {
if loading_ctx.label != new_label {
loading_ctx.label = new_label;
cx.notify();
}
});
}
}
}
pub fn confirm_mention_completion(
&mut self,
crease_text: SharedString,
@ -270,7 +309,7 @@ impl MentionSet {
cx,
)
};
let Some((crease_id, tx)) = crease else {
let Some((crease_id, tx, crease_entity)) = crease else {
return Task::ready(());
};
@ -289,6 +328,9 @@ impl MentionSet {
..
} => self.confirm_mention_for_symbol(abs_path, line_range, cx),
MentionUri::Rule { id, .. } => self.confirm_mention_for_rule(id, cx),
MentionUri::Skill {
skill_file_path, ..
} => self.confirm_mention_for_skill(skill_file_path, cx),
MentionUri::Diagnostics {
include_errors,
include_warnings,
@ -319,6 +361,10 @@ impl MentionSet {
.spawn(async move |_, _| task.await.map_err(|e| e.to_string()))
.shared();
self.mentions.insert(crease_id, (mention_uri, task.clone()));
if let Some(entity) = crease_entity {
self.crease_entities.insert(crease_id, entity);
}
self.recompute_disambiguation(cx);
// Notify the user if we failed to load the mentioned context
let workspace = workspace.downgrade();
@ -332,6 +378,7 @@ impl MentionSet {
editor.edit([(start_anchor..end_anchor, "")], cx);
});
this.mentions.remove(&crease_id);
this.crease_entities.remove(&crease_id);
})
.ok();
}
@ -440,6 +487,34 @@ impl MentionSet {
})
}
fn confirm_mention_for_skill(
&self,
skill_file_path: PathBuf,
cx: &mut Context<Self>,
) -> Task<Result<Mention>> {
// Built-in skills have synthetic paths that don't exist on disk;
// serve their content directly from the compiled-in data.
if let Some(content) = agent_skills::builtin_skill_content(&skill_file_path) {
return Task::ready(Ok(Mention::Text {
content: content.to_string(),
tracked_buffers: Vec::new(),
}));
}
cx.background_spawn(async move {
let content = std::fs::read_to_string(&skill_file_path).map_err(|e| {
anyhow!(
"Failed to read skill file {}: {}",
skill_file_path.display(),
e
)
})?;
Ok(Mention::Text {
content,
tracked_buffers: Vec::new(),
})
})
}
fn confirm_mention_for_rule(
&mut self,
id: PromptId,
@ -496,6 +571,7 @@ impl MentionSet {
let uri = MentionUri::Selection {
abs_path: abs_path.clone(),
line_range: line_range.clone(),
column: None,
};
let crease = crease_for_mention(
selection_name(abs_path.as_deref(), &line_range).into(),
@ -643,6 +719,26 @@ impl MentionSet {
}
}
/// Computes disambiguated labels for a set of mentions. When multiple mentions
/// share the same base name, their labels include extra context (additional
/// parent path components for files/directories, source for skills) so the user
/// can tell them apart. Driven by [`util::disambiguate::compute_disambiguation_details`],
/// which is the same utility used for buffer tab titles and the sidebar.
fn compute_disambiguated_labels<'a>(
mentions: impl Iterator<Item = (CreaseId, &'a MentionUri)>,
) -> HashMap<CreaseId, SharedString> {
let mentions: Vec<_> = mentions.collect();
let details =
util::disambiguate::compute_disambiguation_details(&mentions, |(_, uri), detail| {
uri.disambiguated_name(detail)
});
mentions
.into_iter()
.zip(details)
.map(|((id, uri), detail)| (id, uri.disambiguated_name(detail).into()))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
@ -711,6 +807,7 @@ mod tests {
MentionUri::Selection {
abs_path: Some(path!("/project/file.rs").into()),
line_range: 1..=2,
column: None,
},
false,
http_client,
@ -795,7 +892,7 @@ pub(crate) async fn insert_images_as_context(
snapshot.anchor_before(start_anchor.to_offset(&snapshot) + content_len)
});
let image = Arc::new(image);
let Ok(Some((crease_id, tx))) = cx.update(|window, cx| {
let Ok(Some((crease_id, tx, crease_entity))) = cx.update(|window, cx| {
insert_crease_for_mention(
text_anchor,
content_len,
@ -830,13 +927,15 @@ pub(crate) async fn insert_images_as_context(
})
.shared();
mention_set.update(cx, |mention_set, _cx| {
mention_set.update(cx, |mention_set, cx| {
mention_set.insert_mention(
crease_id,
MentionUri::PastedImage {
name: name.to_string(),
},
task.clone(),
crease_entity,
cx,
)
});
@ -848,8 +947,8 @@ pub(crate) async fn insert_images_as_context(
editor.update(cx, |editor, cx| {
editor.edit([(start_anchor..end_anchor, "")], cx);
});
mention_set.update(cx, |mention_set, _cx| {
mention_set.remove_mention(&crease_id)
mention_set.update(cx, |mention_set, cx| {
mention_set.remove_mention(&crease_id, cx)
});
}
}
@ -965,7 +1064,11 @@ pub(crate) fn insert_crease_for_mention(
editor: Entity<Editor>,
window: &mut Window,
cx: &mut App,
) -> Option<(CreaseId, postage::barrier::Sender)> {
) -> Option<(
CreaseId,
postage::barrier::Sender,
Option<Entity<LoadingContext>>,
)> {
let (tx, rx) = postage::barrier::channel();
let crease_id = editor.update(cx, |editor, cx| {
@ -976,19 +1079,20 @@ pub(crate) fn insert_crease_for_mention(
let start = start.bias_right(&snapshot);
let end = snapshot.anchor_before(start.to_offset(&snapshot) + content_len);
let (render, crease_entity) = render_mention_fold_button(
crease_label.clone(),
crease_icon.clone(),
crease_tooltip,
mention_uri.clone(),
workspace.clone(),
start..end,
rx,
image,
cx.weak_entity(),
cx,
);
let placeholder = FoldPlaceholder {
render: render_mention_fold_button(
crease_label.clone(),
crease_icon.clone(),
crease_tooltip,
mention_uri.clone(),
workspace.clone(),
start..end,
rx,
image,
cx.weak_entity(),
cx,
),
render,
merge_adjacent: false,
..Default::default()
};
@ -1007,10 +1111,11 @@ pub(crate) fn insert_crease_for_mention(
let ids = editor.insert_creases(vec![crease.clone()], cx);
editor.fold_creases(vec![crease], false, window, cx);
Some(ids[0])
Some((ids[0], crease_entity))
})?;
Some((crease_id, tx))
let (crease_id, crease_entity) = crease_id;
Some((crease_id, tx, Some(crease_entity)))
}
pub(crate) fn crease_for_mention(
@ -1189,7 +1294,10 @@ fn render_mention_fold_button(
image_task: Option<Shared<Task<Result<Arc<Image>, String>>>>,
editor: WeakEntity<Editor>,
cx: &mut App,
) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
) -> (
Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement>,
Entity<LoadingContext>,
) {
let loading = cx.new(|cx| {
let loading = cx.spawn(async move |this, cx| {
loading_finished.recv().await;
@ -1212,10 +1320,13 @@ fn render_mention_fold_button(
image: image_task.clone(),
}
});
Arc::new(move |_fold_id, _fold_range, _cx| loading.clone().into_any_element())
let loading_clone = loading.clone();
let render: Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> =
Arc::new(move |_fold_id, _fold_range, _cx| loading_clone.clone().into_any_element());
(render, loading)
}
struct LoadingContext {
pub struct LoadingContext {
id: EntityId,
label: SharedString,
icon: SharedString,

View file

@ -3,8 +3,9 @@ use crate::SendImmediately;
use crate::{
ChatWithFollow,
completion_provider::{
AgentContextSelection, PromptCompletionProvider, PromptCompletionProviderDelegate,
PromptContextAction, PromptContextType, SlashCommandCompletion,
AgentContextSelection, AvailableCommand, AvailableSkill, PromptCompletionProvider,
PromptCompletionProviderDelegate, PromptContextAction, PromptContextType,
SlashCommandCompletion,
},
mention_set::{Mention, MentionImage, MentionSet, insert_crease_for_mention},
};
@ -47,19 +48,29 @@ use zed_actions::agent::{Chat, PasteRaw};
pub struct SessionCapabilities {
prompt_capabilities: acp::PromptCapabilities,
available_commands: Vec<acp::AvailableCommand>,
available_skills: Vec<AvailableSkill>,
}
impl SessionCapabilities {
pub fn new(
prompt_capabilities: acp::PromptCapabilities,
available_commands: Vec<acp::AvailableCommand>,
available_skills: Vec<AvailableSkill>,
) -> Self {
Self {
prompt_capabilities,
available_commands,
available_skills,
}
}
pub fn from_acp_commands(
prompt_capabilities: acp::PromptCapabilities,
available_commands: Vec<acp::AvailableCommand>,
) -> Self {
Self::new(prompt_capabilities, available_commands, Vec::new())
}
pub fn supports_images(&self) -> bool {
self.prompt_capabilities.image
}
@ -72,6 +83,14 @@ impl SessionCapabilities {
&self.available_commands
}
pub fn available_skills(&self) -> &[AvailableSkill] {
&self.available_skills
}
pub fn has_slash_completions(&self) -> bool {
!self.available_commands.is_empty() || !self.available_skills.is_empty()
}
fn supported_modes(&self, has_thread_store: bool) -> Vec<PromptContextType> {
let mut supported = vec![PromptContextType::File, PromptContextType::Symbol];
if self.prompt_capabilities.embedded_context {
@ -81,25 +100,29 @@ impl SessionCapabilities {
supported.extend(&[
PromptContextType::Diagnostics,
PromptContextType::Fetch,
PromptContextType::Rules,
PromptContextType::Skill,
PromptContextType::BranchDiff,
]);
}
supported
}
pub fn completion_commands(&self) -> Vec<crate::completion_provider::AvailableCommand> {
pub fn completion_commands(&self) -> Vec<AvailableCommand> {
self.available_commands
.iter()
.map(|cmd| crate::completion_provider::AvailableCommand {
name: cmd.name.clone().into(),
description: cmd.description.clone().into(),
requires_argument: cmd.input.is_some(),
source: acp_thread::skill_source_from_meta(&cmd.meta),
.map(|command| AvailableCommand {
name: command.name.clone().into(),
description: command.description.clone().into(),
requires_argument: command.input.is_some(),
source: None,
})
.collect()
}
pub fn completion_skills(&self) -> Vec<AvailableSkill> {
self.available_skills.clone()
}
pub fn set_prompt_capabilities(&mut self, prompt_capabilities: acp::PromptCapabilities) {
self.prompt_capabilities = prompt_capabilities;
}
@ -107,6 +130,10 @@ impl SessionCapabilities {
pub fn set_available_commands(&mut self, available_commands: Vec<acp::AvailableCommand>) {
self.available_commands = available_commands;
}
pub fn set_available_skills(&mut self, available_skills: Vec<AvailableSkill>) {
self.available_skills = available_skills;
}
}
pub type SharedSessionCapabilities = Arc<RwLock<SessionCapabilities>>;
@ -128,10 +155,14 @@ impl PromptCompletionProviderDelegate for MessageEditorCompletionDelegate {
.supported_modes(self.has_thread_store)
}
fn available_commands(&self, _cx: &App) -> Vec<crate::completion_provider::AvailableCommand> {
fn available_commands(&self, _cx: &App) -> Vec<AvailableCommand> {
self.session_capabilities.read().completion_commands()
}
fn available_skills(&self, _cx: &App) -> Vec<AvailableSkill> {
self.session_capabilities.read().completion_skills()
}
fn slash_autocomplete_invoked(&self, cx: &mut App) {
// This may be called synchronously from inside a `MessageEditor`
// update (e.g. when pasting a slash command triggers completions),
@ -485,7 +516,6 @@ impl MessageEditor {
},
editor.downgrade(),
mention_set.clone(),
prompt_store.clone(),
workspace.clone(),
));
editor.update(cx, |editor, _cx| {
@ -606,7 +636,7 @@ impl MessageEditor {
let command_name = parsed_command.command?;
let available_command = available_commands
.iter()
.find(|command| command.name == command_name)?;
.find(|available_command| available_command.name == command_name)?;
let acp::AvailableCommandInput::Unstructured(acp::UnstructuredCommandInput {
mut hint,
@ -717,9 +747,13 @@ impl MessageEditor {
fn validate_slash_commands(
text: &str,
available_commands: &[acp::AvailableCommand],
available_skills: &[AvailableSkill],
agent_id: &AgentId,
) -> Result<()> {
if let Some(parsed_command) = SlashCommandCompletion::try_parse(text, 0) {
if parsed_command.source_range.start != 0 {
return Ok(());
}
if let Some(command_name) = parsed_command.command {
// Two acceptance paths:
//
@ -729,7 +763,7 @@ impl MessageEditor {
// (`/github.create_pr`), and skills (whose bare name
// is registered for the unqualified `/<name>` form).
//
// 2. Skill scope qualifier `/<scope>:<name>`. The popup
// 2. Trusted native skill scope qualifier `/<scope>:<name>`. The popup
// inserts this colon-separated form to disambiguate
// same-named skills, so the validator splits on the
// LAST `:` to recover scope + bare name. Skill
@ -740,58 +774,62 @@ impl MessageEditor {
// scope is allowed to be empty: `/:<name>` is the
// qualified form for a global skill (see
// `SkillSource::scope_prefix`). The validator then
// confirms an available command with that bare
// name has a `zed.skill_source` meta tag whose
// value equals the typed scope (including empty
// for globals). Without this branch, every
// autocomplete pick of a same-named skill would be
// rejected as "not supported" before reaching the
// resolver.
// checks the `available_skills` slice for an entry
// whose `skill.name` matches the bare name and
// whose `skill.source` equals the typed scope
// (including empty for globals). Without this
// branch, every autocomplete pick of a same-named
// skill would be rejected as "not supported"
// before reaching the resolver.
let direct_match = available_commands
.iter()
.any(|cmd| cmd.name == command_name);
.any(|available_command| available_command.name == command_name)
|| available_skills
.iter()
.any(|skill| skill.name.as_ref() == command_name);
let scope_match = !direct_match
&& command_name.rsplit_once(':').is_some_and(|(scope, bare)| {
!bare.is_empty()
&& available_commands.iter().any(|cmd| {
cmd.name == bare
&& acp_thread::skill_source_str_from_meta(&cmd.meta)
== Some(scope)
&& available_skills.iter().any(|skill| {
skill.name.as_ref() == bare && skill.source.as_ref() == scope
})
});
if !direct_match && !scope_match {
return Err(anyhow!(
"The /{} command is not supported by {}.\n\nAvailable commands: {}",
command_name,
agent_id,
Self::format_available_commands(available_commands),
));
return Err(anyhow!(indoc::formatdoc!(
"/{command_name} is not a recognized command in {agent_id}. \
Messages that start with `/` are interpreted as commands.
If you are trying to send a message and not run a command, \
try preceding the `/` with a space.
Available commands for {agent_id}: {commands}",
commands =
Self::format_available_commands(available_commands, available_skills),
)));
}
}
}
Ok(())
}
/// Render the available-commands list for error messages. Skills
/// Render the available-commands list for error messages. Trusted native skills
/// are shown in their qualified `/<scope>:<name>` form so users
/// see the exact text the popup would insert — otherwise the
/// listing would contain confusing duplicates like `/foo, /foo`
/// when both a global and a project-local skill share a name.
/// Globals carry an empty scope and so render as `/:<name>`.
fn format_available_commands(commands: &[acp::AvailableCommand]) -> String {
if commands.is_empty() {
fn format_available_commands(
commands: &[acp::AvailableCommand],
skills: &[AvailableSkill],
) -> String {
if commands.is_empty() && skills.is_empty() {
return "none".to_string();
}
commands
skills
.iter()
.map(|cmd| {
if let Some(scope) = acp_thread::skill_source_str_from_meta(&cmd.meta) {
format!("/{}:{}", scope, cmd.name)
} else {
format!("/{}", cmd.name)
}
})
.map(|skill| format!("/{}:{}", skill.source, skill.name))
.chain(commands.iter().map(|command| format!("/{}", command.name)))
.collect::<Vec<_>>()
.join(", ")
}
@ -802,16 +840,23 @@ impl MessageEditor {
cx: &mut Context<Self>,
) -> Task<Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>> {
let text = self.editor.read(cx).text(cx);
let available_commands = self
.session_capabilities
.read()
.available_commands()
.to_vec();
let (available_commands, available_skills) = {
let session_capabilities = self.session_capabilities.read();
(
session_capabilities.available_commands().to_vec(),
session_capabilities.available_skills().to_vec(),
)
};
let agent_id = self.agent_id.clone();
let build_task = self.build_content_blocks(full_mention_content, cx);
cx.spawn(async move |_, _cx| {
Self::validate_slash_commands(&text, &available_commands, &agent_id)?;
Self::validate_slash_commands(
&text,
&available_commands,
&available_skills,
&agent_id,
)?;
build_task.await
})
}
@ -1074,6 +1119,7 @@ impl MessageEditor {
let mention_uri = MentionUri::Selection {
abs_path: Some(file_path.clone()),
line_range: line_range.clone(),
column: None,
};
let mention_text = mention_uri.as_link().to_string();
@ -1089,7 +1135,7 @@ impl MessageEditor {
(text_anchor, mention_text.len())
});
let Some((crease_id, tx)) = insert_crease_for_mention(
let Some((crease_id, tx, crease_entity)) = insert_crease_for_mention(
text_anchor,
content_len,
crease_text.into(),
@ -1136,8 +1182,14 @@ impl MessageEditor {
})
.shared();
self.mention_set.update(cx, |mention_set, _cx| {
mention_set.insert_mention(crease_id, mention_uri.clone(), mention_task)
self.mention_set.update(cx, |mention_set, cx| {
mention_set.insert_mention(
crease_id,
mention_uri.clone(),
mention_task,
crease_entity,
cx,
)
});
}
}
@ -1196,7 +1248,7 @@ impl MessageEditor {
let http_client = workspace.read(cx).client().http_client();
for (anchor, content_len, mention_uri) in all_mentions {
let Some((crease_id, tx)) = insert_crease_for_mention(
let Some((crease_id, tx, crease_entity)) = insert_crease_for_mention(
snapshot.anchor_to_buffer_anchor(anchor).unwrap().0,
content_len,
mention_uri.name().into(),
@ -1226,8 +1278,14 @@ impl MessageEditor {
.spawn(async move |_, _| task.await.map_err(|e| e.to_string()))
.shared();
self.mention_set.update(cx, |mention_set, _cx| {
mention_set.insert_mention(crease_id, mention_uri.clone(), task.clone())
self.mention_set.update(cx, |mention_set, cx| {
mention_set.insert_mention(
crease_id,
mention_uri.clone(),
task.clone(),
crease_entity,
cx,
)
});
// Drop the tx after inserting to signal the crease is ready
@ -1418,7 +1476,7 @@ impl MessageEditor {
(text_anchor, mention_text.len())
});
let Some((crease_id, tx)) = insert_crease_for_mention(
let Some((crease_id, tx, crease_entity)) = insert_crease_for_mention(
text_anchor,
content_len,
mention_uri.name().into(),
@ -1443,14 +1501,75 @@ impl MessageEditor {
.spawn(async move |_cx| confirm_task.await.map_err(|e| e.to_string()))
.shared();
mention_set.update(cx, |mention_set, _| {
mention_set.insert_mention(crease_id, mention_uri, mention_task);
mention_set.update(cx, |mention_set, cx| {
mention_set.insert_mention(
crease_id,
mention_uri,
mention_task,
crease_entity,
cx,
);
});
})
})
.detach_and_log_err(cx);
}
pub fn insert_skill_crease(
&mut self,
skill: &AvailableSkill,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(workspace) = self.workspace.upgrade() else {
return;
};
let mention_uri = MentionUri::Skill {
name: skill.name.to_string(),
source: skill.source.to_string(),
skill_file_path: skill.skill_file_path.clone(),
};
let link_text = mention_uri.as_link().to_string();
let content_len = link_text.len();
let mention_text = format!("{} ", link_text);
let crease_text: SharedString = mention_uri.name().into();
let start_anchor = self.editor.update(cx, |editor, cx| {
let snapshot = editor.buffer().read(cx).snapshot(cx);
let buffer_snapshot = snapshot.as_singleton()?;
let cursor = editor.selections.newest_anchor().start;
let text_anchor = snapshot
.anchor_to_buffer_anchor(cursor)?
.0
.bias_left(buffer_snapshot);
editor.insert(&mention_text, window, cx);
Some(text_anchor)
});
let Some(start_anchor) = start_anchor else {
return;
};
self.mention_set
.update(cx, |mention_set, cx| {
mention_set.confirm_mention_completion(
crease_text,
start_anchor,
content_len,
mention_uri,
false,
self.editor.clone(),
&workspace,
window,
cx,
)
})
.detach();
}
pub(crate) fn insert_selections(
&mut self,
selection: AgentContextSelection,
@ -1699,7 +1818,7 @@ impl MessageEditor {
for (range, mention_uri, mention) in mentions {
let adjusted_start = insertion_start + range.start;
let anchor = snapshot.anchor_before(MultiBufferOffset(adjusted_start));
let Some((crease_id, tx)) = insert_crease_for_mention(
let Some((crease_id, tx, crease_entity)) = insert_crease_for_mention(
snapshot.anchor_to_buffer_anchor(anchor).unwrap().0,
range.end - range.start,
mention_uri.name().into(),
@ -1716,11 +1835,13 @@ impl MessageEditor {
};
drop(tx);
self.mention_set.update(cx, |mention_set, _cx| {
self.mention_set.update(cx, |mention_set, cx| {
mention_set.insert_mention(
crease_id,
mention_uri.clone(),
Task::ready(Ok(mention)).shared(),
crease_entity,
cx,
)
});
}
@ -2113,7 +2234,7 @@ mod tests {
use util::{path, paths::PathStyle, rel_path::rel_path};
use workspace::{AppState, Item, MultiWorkspace, Workspace};
use crate::completion_provider::{AgentContextSelection, PromptContextType};
use crate::completion_provider::{AgentContextSelection, AvailableSkill, PromptContextType};
use crate::{
conversation_view::tests::init_test,
mention_set::insert_crease_for_mention,
@ -2122,57 +2243,86 @@ mod tests {
},
};
#[test]
fn test_session_capabilities_keep_commands_and_skills_separate() {
let skill_file_path = PathBuf::from("/tmp/SKILL.md");
let skill = AvailableSkill {
name: "deploy".into(),
description: "Deploy the app".into(),
source: "".into(),
skill_file_path: skill_file_path.clone(),
};
let session_capabilities = SessionCapabilities::new(
acp::PromptCapabilities::default(),
vec![acp::AvailableCommand::new("help", "Get help")],
vec![skill],
);
assert_eq!(session_capabilities.completion_commands().len(), 1);
let skills = session_capabilities.completion_skills();
assert_eq!(skills.len(), 1);
assert_eq!(skills[0].name.as_ref(), "deploy");
assert_eq!(skills[0].skill_file_path, skill_file_path);
}
#[test]
fn test_validate_slash_commands_accepts_scope_qualified_skill() {
let agent_id = AgentId::from("Zed");
let make_skill_command = |name: &str, scope: &str| {
acp::AvailableCommand::new(name, "desc").meta(acp_thread::meta_with_skill_source(scope))
let make_skill = |name: &str, source: &str| AvailableSkill {
name: name.into(),
description: "desc".into(),
source: source.into(),
skill_file_path: PathBuf::from(format!("/tmp/{source}-{name}/SKILL.md")),
};
// Global skills carry an empty scope (so the popup inserts
// `/:<name>`); project-local skills carry their worktree root
// name. The empty-scope encoding means a worktree literally
// named `global` no longer collides with the global source.
let commands = vec![
make_skill_command("deploy", ""),
make_skill_command("deploy", "zed"),
acp::AvailableCommand::new("help", "Get help"),
];
let commands = vec![acp::AvailableCommand::new("help", "Get help")];
let skills = vec![make_skill("deploy", ""), make_skill("deploy", "zed")];
let no_skills = Vec::new();
// Bare name still works (current behavior — the resolver
// applies project-overrides-global for unqualified commands).
MessageEditor::validate_slash_commands("/deploy", &commands, &agent_id)
MessageEditor::validate_slash_commands("/deploy", &commands, &skills, &agent_id)
.expect("bare /deploy should validate when a skill named `deploy` exists");
MessageEditor::validate_slash_commands("/zed:deploy", &commands, &no_skills, &agent_id)
.expect_err("scope-qualified skills should require a first-class available skill");
// Scope-qualified forms both validate, each pointing at the
// matching source. `/:<name>` is the qualified form for a
// global skill; `/<worktree>:<name>` is the qualified form
// for a project-local skill.
MessageEditor::validate_slash_commands("/:deploy", &commands, &agent_id)
MessageEditor::validate_slash_commands("/:deploy", &commands, &skills, &agent_id)
.expect("/:deploy should validate when a global skill named `deploy` exists");
MessageEditor::validate_slash_commands("/zed:deploy", &commands, &agent_id).expect(
MessageEditor::validate_slash_commands("/zed:deploy", &commands, &skills, &agent_id).expect(
"/zed:deploy should validate when a project skill named `deploy` exists in the `zed` worktree",
);
// Hand-typed `/global:<name>` is NOT an alias for `/:<name>`.
// It looks for a project-local skill from a worktree named
// `global`, and fails when no such worktree skill exists.
MessageEditor::validate_slash_commands("/global:deploy", &commands, &agent_id).expect_err(
"/global:deploy should fail when no worktree named `global` has a `deploy` skill",
);
MessageEditor::validate_slash_commands("/global:deploy", &commands, &skills, &agent_id)
.expect_err(
"/global:deploy should fail when no worktree named `global` has a `deploy` skill",
);
// The `:` separator is what distinguishes a skill scope from
// an MCP server prefix — the dotted form `/zed.deploy` is an
// MCP-style lookup, which doesn't match here.
MessageEditor::validate_slash_commands("/zed.deploy", &commands, &agent_id)
MessageEditor::validate_slash_commands("/zed.deploy", &commands, &skills, &agent_id)
.expect_err("/zed.deploy (dotted) should be treated as an MCP-style prefix and fail");
// Wrong scope is rejected so the resolver doesn't silently
// fall through when the user meant a skill. `zed:help` looks
// like a skill scope qualifier but no skill named `help`
// exists in the `zed` worktree (it's an MCP command).
let err = MessageEditor::validate_slash_commands("/zed:help", &commands, &agent_id)
.expect_err("/zed:help should fail — `help` is an MCP command, not a worktree skill");
let err =
MessageEditor::validate_slash_commands("/zed:help", &commands, &skills, &agent_id)
.expect_err(
"/zed:help should fail — `help` is an MCP command, not a worktree skill",
);
let err_message = err.to_string();
assert!(
err_message.contains("/zed:help"),
@ -2193,6 +2343,24 @@ mod tests {
err_message.contains("/help"),
"error listing should still show bare MCP commands: {err_message}"
);
// Slashes that appear mid-text (paths, URLs, pasted logs)
// should NOT be validated as commands.
MessageEditor::validate_slash_commands(
"check /docs for info",
&commands,
&skills,
&agent_id,
)
.expect("mid-text /docs should not be treated as a slash command");
MessageEditor::validate_slash_commands(
"see /usr/local/bin/foo",
&commands,
&skills,
&agent_id,
)
.expect("file paths containing slashes should not trigger validation");
}
#[test]
@ -2393,7 +2561,7 @@ mod tests {
let project = Project::test(fs.clone(), ["/test".as_ref()], cx).await;
let thread_store = None;
let session_capabilities = Arc::new(RwLock::new(SessionCapabilities::new(
let session_capabilities = Arc::new(RwLock::new(SessionCapabilities::from_acp_commands(
acp::PromptCapabilities::default(),
vec![],
)));
@ -2435,8 +2603,8 @@ mod tests {
// Should fail because available_commands is empty (no commands supported)
assert!(contents_result.is_err());
let error_message = contents_result.unwrap_err().to_string();
assert!(error_message.contains("not supported by Claude Agent"));
assert!(error_message.contains("Available commands: none"));
assert!(error_message.contains("is not a recognized command in Claude Agent"));
assert!(error_message.contains("Available commands for Claude Agent: none"));
// Now simulate Claude providing its list of available commands (which doesn't include file)
session_capabilities
@ -2454,9 +2622,9 @@ mod tests {
assert!(contents_result.is_err());
let error_message = contents_result.unwrap_err().to_string();
assert!(error_message.contains("not supported by Claude Agent"));
assert!(error_message.contains("is not a recognized command in Claude Agent"));
assert!(error_message.contains("/file"));
assert!(error_message.contains("Available commands: /help"));
assert!(error_message.contains("Available commands for Claude Agent: /help"));
// Test that supported commands work fine
editor.update_in(cx, |editor, window, cx| {
@ -2555,7 +2723,7 @@ mod tests {
let mut cx = VisualTestContext::from_window(window.into(), cx);
let thread_store = None;
let session_capabilities = Arc::new(RwLock::new(SessionCapabilities::new(
let session_capabilities = Arc::new(RwLock::new(SessionCapabilities::from_acp_commands(
acp::PromptCapabilities::default(),
vec![
acp::AvailableCommand::new("quick-math", "2 + 2 = 4 - 1 = 3"),
@ -2729,7 +2897,7 @@ mod tests {
let mut cx = VisualTestContext::from_window(window.into(), cx);
let session_capabilities = Arc::new(RwLock::new(SessionCapabilities::new(
let session_capabilities = Arc::new(RwLock::new(SessionCapabilities::from_acp_commands(
acp::PromptCapabilities::default(),
vec![acp::AvailableCommand::new("hello", "Say hello")],
)));
@ -2884,7 +3052,7 @@ mod tests {
}
let thread_store = cx.new(|cx| ThreadStore::new(cx));
let session_capabilities = Arc::new(RwLock::new(SessionCapabilities::new(
let session_capabilities = Arc::new(RwLock::new(SessionCapabilities::from_acp_commands(
acp::PromptCapabilities::default(),
vec![],
)));
@ -4230,10 +4398,12 @@ mod tests {
let first_uri = MentionUri::Selection {
abs_path: Some(path!("/project/file.rs").into()),
line_range: 0..=1,
column: None,
};
let second_uri = MentionUri::Selection {
abs_path: Some(path!("/project/file.rs").into()),
line_range: 2..=3,
column: None,
};
source_message_editor.update_in(&mut cx, |message_editor, window, cx| {
@ -4257,7 +4427,7 @@ mod tests {
"line 3\nline 4\n".to_string(),
),
] {
let Some((crease_id, tx)) = insert_crease_for_mention(
let Some((crease_id, tx, _crease_entity)) = insert_crease_for_mention(
snapshot
.anchor_to_buffer_anchor(
snapshot.anchor_before(MultiBufferOffset(range.start)),
@ -4279,7 +4449,7 @@ mod tests {
};
drop(tx);
message_editor.mention_set.update(cx, |mention_set, _cx| {
message_editor.mention_set.update(cx, |mention_set, cx| {
mention_set.insert_mention(
crease_id,
uri,
@ -4288,6 +4458,8 @@ mod tests {
tracked_buffers: Vec::new(),
}))
.shared(),
None,
cx,
);
});
}
@ -4389,10 +4561,12 @@ mod tests {
let first_uri = MentionUri::Selection {
abs_path: Some(path!("/project/file.rs").into()),
line_range: 0..=1,
column: None,
};
let second_uri = MentionUri::Selection {
abs_path: Some(path!("/project/file.rs").into()),
line_range: 2..=3,
column: None,
};
let buffer_len = message_editor.update_in(&mut cx, |message_editor, window, cx| {
@ -4416,7 +4590,7 @@ mod tests {
"line 3\nline 4\n".to_string(),
),
] {
let Some((crease_id, tx)) = insert_crease_for_mention(
let Some((crease_id, tx, _crease_entity)) = insert_crease_for_mention(
snapshot
.anchor_to_buffer_anchor(
snapshot.anchor_before(MultiBufferOffset(range.start)),
@ -4438,7 +4612,7 @@ mod tests {
};
drop(tx);
message_editor.mention_set.update(cx, |mention_set, _cx| {
message_editor.mention_set.update(cx, |mention_set, cx| {
mention_set.insert_mention(
crease_id,
uri,
@ -4447,6 +4621,8 @@ mod tests {
tracked_buffers: Vec::new(),
}))
.shared(),
None,
cx,
);
});
}

Some files were not shown because too many files have changed in this diff Show more