Compare commits

..

9 Commits

Author SHA1 Message Date
Anthony
2d77a2377d add element id in item render_page items instead 2025-10-09 12:43:24 -04:00
Anthony
9e1f9c74c0 upper case all lsp references in titles and descriptions 2025-10-09 12:33:41 -04:00
Anthony
e0be758308 Fix some settings ui elements having duplicate ids 2025-10-09 12:29:21 -04:00
Anthony
bb31a97e22 Deduplicate terminal settings and fix dropdown toggle bug 2025-10-09 12:02:56 -04:00
Anthony
08b73d0943 Merge remote-tracking branch 'origin/main' into settings-ui-elements 2025-10-09 11:16:43 -04:00
Anthony
f2b1dd262c Merge conflicts 2025-10-09 11:12:09 -04:00
Anthony
898af2e75d Merge remote-tracking branch 'origin/main' into settings-ui-elements 2025-10-07 22:08:14 -04:00
Anthony
e34526534f Add Cursor Shape 2025-10-07 22:07:53 -04:00
Anthony
e3f4fee4d5 Add more terminal settings 2025-10-07 17:37:37 -04:00
1041 changed files with 51534 additions and 47430 deletions

View File

@@ -5,16 +5,12 @@
# Arrays are merged together though. See: https://doc.rust-lang.org/cargo/reference/config.html#hierarchical-structure # Arrays are merged together though. See: https://doc.rust-lang.org/cargo/reference/config.html#hierarchical-structure
# The intent for this file is to configure CI build process with a divergance from Zed developers experience; for example, in this config file # The intent for this file is to configure CI build process with a divergance from Zed developers experience; for example, in this config file
# we use `-D warnings` for rustflags (which makes compilation fail in presence of warnings during build process). Placing that in developers `config.toml` # we use `-D warnings` for rustflags (which makes compilation fail in presence of warnings during build process). Placing that in developers `config.toml`
# would be inconvenient. # would be incovenient.
# The reason for not using the RUSTFLAGS environment variable is that doing so would override all the settings in the config.toml file, even if the contents of the latter are completely nonsensical. See: https://github.com/rust-lang/cargo/issues/5376 # The reason for not using the RUSTFLAGS environment variable is that doing so would override all the settings in the config.toml file, even if the contents of the latter are completely nonsensical. See: https://github.com/rust-lang/cargo/issues/5376
# Here, we opted to use `[target.'cfg(all())']` instead of `[build]` because `[target.'**']` is guaranteed to be cumulative. # Here, we opted to use `[target.'cfg(all())']` instead of `[build]` because `[target.'**']` is guaranteed to be cumulative.
[target.'cfg(all())'] [target.'cfg(all())']
rustflags = ["-D", "warnings"] rustflags = ["-D", "warnings"]
# We don't need fullest debug information for dev stuff (tests etc.) in CI.
[profile.dev]
debug = "limited"
# Use Mold on Linux, because it's faster than GNU ld and LLD. # Use Mold on Linux, because it's faster than GNU ld and LLD.
# #
# We no longer set this in the default `config.toml` so that developers can opt in to Wild, which # We no longer set this in the default `config.toml` so that developers can opt in to Wild, which

42
.config/hakari.toml Normal file
View File

@@ -0,0 +1,42 @@
# This file contains settings for `cargo hakari`.
# See https://docs.rs/cargo-hakari/latest/cargo_hakari/config for a full list of options.
hakari-package = "workspace-hack"
resolver = "2"
dep-format-version = "4"
workspace-hack-line-style = "workspace-dotted"
# this should be the same list as "targets" in ../rust-toolchain.toml
platforms = [
"x86_64-apple-darwin",
"aarch64-apple-darwin",
"x86_64-unknown-linux-gnu",
"aarch64-unknown-linux-gnu",
"x86_64-pc-windows-msvc",
"x86_64-unknown-linux-musl", # remote server
]
[traversal-excludes]
workspace-members = [
"remote_server",
]
third-party = [
{ name = "reqwest", version = "0.11.27" },
# build of remote_server should not include scap / its x11 dependency
{ name = "zed-scap", git = "https://github.com/zed-industries/scap", rev = "4afea48c3b002197176fb19cd0f9b180dd36eaac", version = "0.0.8-zed" },
# build of remote_server should not need to include on libalsa through rodio
{ name = "rodio", git = "https://github.com/RustAudio/rodio" },
]
[final-excludes]
workspace-members = [
"zed_extension_api",
# exclude all extensions
"zed_glsl",
"zed_html",
"zed_proto",
"slash_commands_example",
"zed_test_extension",
]

View File

@@ -4,17 +4,3 @@ sequential-db-tests = { max-threads = 1 }
[[profile.default.overrides]] [[profile.default.overrides]]
filter = 'package(db)' filter = 'package(db)'
test-group = 'sequential-db-tests' test-group = 'sequential-db-tests'
# Run slowest tests first.
#
[[profile.default.overrides]]
filter = 'package(worktree) and test(test_random_worktree_changes)'
priority = 100
[[profile.default.overrides]]
filter = 'package(collab) and (test(random_project_collaboration_tests) or test(random_channel_buffer_tests) or test(test_contact_requests) or test(test_basic_following))'
priority = 99
[[profile.default.overrides]]
filter = 'package(extension_host) and test(test_extension_store_with_test_extension)'
priority = 99

View File

@@ -1,35 +0,0 @@
name: Bug Report (Git)
description: Zed Git Related Bugs
type: "Bug"
labels: ["git"]
title: "Git: <a short description of the Git bug>"
body:
- type: textarea
attributes:
label: Summary
description: Describe the bug with a one-line summary, and provide detailed reproduction steps
value: |
<!-- Please insert a one-line summary of the issue below -->
SUMMARY_SENTENCE_HERE
### Description
<!-- Describe with sufficient detail to reproduce from a clean Zed install. -->
Steps to trigger the problem:
1.
2.
3.
**Expected Behavior**:
**Actual Behavior**:
validations:
required: true
- type: textarea
id: environment
attributes:
label: Zed Version and System Specs
description: 'Open Zed, and in the command palette select "zed: copy system specs into clipboard"'
placeholder: |
Output of "zed: copy system specs into clipboard"
validations:
required: true

View File

@@ -1,8 +1,8 @@
name: Bug Report (Windows) name: Bug Report (Windows Beta)
description: Zed Windows Related Bugs description: Zed Windows Beta Related Bugs
type: "Bug" type: "Bug"
labels: ["windows"] labels: ["windows"]
title: "Windows: <a short description of the Windows bug>" title: "Windows Beta: <a short description of the Windows bug>"
body: body:
- type: textarea - type: textarea
attributes: attributes:

View File

@@ -33,10 +33,9 @@ body:
required: true required: true
- type: textarea - type: textarea
attributes: attributes:
label: If applicable, attach your `Zed.log` file to this issue. label: If applicable, attach your `~/Library/Logs/Zed/Zed.log` file to this issue.
description: | description: |
macOS: `~/Library/Logs/Zed/Zed.log` macOS: `~/Library/Logs/Zed/Zed.log`
Windows: `C:\Users\YOU\AppData\Local\Zed\logs\Zed.log`
Linux: `~/.local/share/zed/logs/Zed.log` or $XDG_DATA_HOME Linux: `~/.local/share/zed/logs/Zed.log` or $XDG_DATA_HOME
If you only need the most recent lines, you can run the `zed: open log` command palette action to see the last 1000. If you only need the most recent lines, you can run the `zed: open log` command palette action to see the last 1000.
value: | value: |

View File

@@ -15,11 +15,8 @@ runs:
node-version: "18" node-version: "18"
- name: Limit target directory size - name: Limit target directory size
env:
MAX_SIZE: ${{ runner.os == 'macOS' && 300 || 100 }}
shell: bash -euxo pipefail {0} shell: bash -euxo pipefail {0}
# Use the variable in the run command run: script/clear-target-dir-if-larger-than 100
run: script/clear-target-dir-if-larger-than ${{ env.MAX_SIZE }}
- name: Run tests - name: Run tests
shell: bash -euxo pipefail {0} shell: bash -euxo pipefail {0}

View File

@@ -130,6 +130,39 @@ jobs:
input: "crates/proto/proto/" input: "crates/proto/proto/"
against: "https://github.com/${GITHUB_REPOSITORY}.git#branch=${BUF_BASE_BRANCH},subdir=crates/proto/proto/" against: "https://github.com/${GITHUB_REPOSITORY}.git#branch=${BUF_BASE_BRANCH},subdir=crates/proto/proto/"
workspace_hack:
timeout-minutes: 60
name: Check workspace-hack crate
needs: [job_spec]
if: |
github.repository_owner == 'zed-industries' &&
needs.job_spec.outputs.run_tests == 'true'
runs-on:
- namespace-profile-8x16-ubuntu-2204
steps:
- name: Checkout repo
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Add Rust to the PATH
run: echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Install cargo-hakari
uses: clechasseur/rs-cargo@8435b10f6e71c2e3d4d3b7573003a8ce4bfc6386 # v2
with:
command: install
args: cargo-hakari@0.9.35
- name: Check workspace-hack Cargo.toml is up-to-date
run: |
cargo hakari generate --diff || {
echo "To fix, run script/update-workspace-hack or script/update-workspace-hack.ps1";
false
}
- name: Check all crates depend on workspace-hack
run: |
cargo hakari manage-deps --dry-run || {
echo "To fix, run script/update-workspace-hack or script/update-workspace-hack.ps1"
false
}
style: style:
timeout-minutes: 60 timeout-minutes: 60
name: Check formatting and spelling name: Check formatting and spelling
@@ -177,7 +210,7 @@ jobs:
uses: ./.github/actions/check_style uses: ./.github/actions/check_style
- name: Check for typos - name: Check for typos
uses: crate-ci/typos@80c8a4945eec0f6d464eaf9e65ed98ef085283d1 # v1.38.1 uses: crate-ci/typos@8e6a4285bcbde632c5d79900a7779746e8b7ea3f # v1.24.6
with: with:
config: ./typos.toml config: ./typos.toml
@@ -296,53 +329,49 @@ jobs:
github.repository_owner == 'zed-industries' && github.repository_owner == 'zed-industries' &&
needs.job_spec.outputs.run_tests == 'true' needs.job_spec.outputs.run_tests == 'true'
runs-on: runs-on:
- namespace-profile-ubuntu22-x86-16x32-custom - namespace-profile-16x32-ubuntu-2204
steps: steps:
- name: Add Rust to the PATH - name: Add Rust to the PATH
run: | run: echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
echo "$HOME/.cargo-nextest/bin" >> "$GITHUB_PATH"
- name: Checkout repo - name: Checkout repo
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
with: with:
clean: false clean: false
- name: Configure Go and Rust cache - name: Cache dependencies
uses: namespacelabs/nscloud-cache-action@v1 uses: swatinem/rust-cache@9d47c6ad4b02e050fd481d890b2ea34778fd09d6 # v2
with: with:
path: | save-if: ${{ github.ref == 'refs/heads/main' }}
/home/runner/.cargo-nextest # cache-provider: "buildjet"
/home/runner/.rustup
./target - name: Install Linux dependencies
run: ./script/linux
- name: Configure CI - name: Configure CI
run: | run: |
mkdir -p ./../.cargo mkdir -p ./../.cargo
cp ./.cargo/ci-config.toml ./../.cargo/config.toml cp ./.cargo/ci-config.toml ./../.cargo/config.toml
- name: Install cargo nextest - name: cargo clippy
shell: bash -euxo pipefail {0} run: ./script/clippy
run: |
cargo install cargo-nextest --locked --root ~/.cargo-nextest
- name: Limit target directory size
env:
MAX_SIZE: ${{ runner.os == 'macOS' && 300 || 100 }}
shell: bash -euxo pipefail {0}
# Use the variable in the run command
run: script/clear-target-dir-if-larger-than ${{ env.MAX_SIZE }}
- name: Run tests - name: Run tests
shell: bash -euxo pipefail {0} uses: ./.github/actions/run_tests
run: cargo nextest run --workspace --no-fail-fast --failure-output immediate-final
- name: Build other binaries and features - name: Build other binaries and features
run: | run: |
cargo build -p zed cargo build -p zed
cargo check -p workspace
cargo check -p gpui --examples
- name: cargo clippy # Even the Linux runner is not stateful, in theory there is no need to do this cleanup.
run: ./script/clippy # But, to avoid potential issues in the future if we choose to use a stateful Linux runner and forget to add code
# to clean up the config file, Ive included the cleanup code here as a precaution.
# While its not strictly necessary at this moment, I believe its better to err on the side of caution.
- name: Clean CI config file
if: always()
run: rm -rf ./../.cargo
doctests: doctests:
# Nextest currently doesn't support doctests, so run them separately and in parallel. # Nextest currently doesn't support doctests, so run them separately and in parallel.
@@ -478,6 +507,7 @@ jobs:
- actionlint - actionlint
- migration_checks - migration_checks
# run_tests: If adding required tests, add them here and to script below. # run_tests: If adding required tests, add them here and to script below.
- workspace_hack
- linux_tests - linux_tests
- build_remote_server - build_remote_server
- macos_tests - macos_tests
@@ -503,6 +533,7 @@ jobs:
# Only check test jobs if they were supposed to run # Only check test jobs if they were supposed to run
if [[ "${{ needs.job_spec.outputs.run_tests }}" == "true" ]]; then if [[ "${{ needs.job_spec.outputs.run_tests }}" == "true" ]]; then
[[ "${{ needs.workspace_hack.result }}" != 'success' ]] && { RET_CODE=1; echo "Workspace Hack failed"; }
[[ "${{ needs.macos_tests.result }}" != 'success' ]] && { RET_CODE=1; echo "macOS tests failed"; } [[ "${{ needs.macos_tests.result }}" != 'success' ]] && { RET_CODE=1; echo "macOS tests failed"; }
[[ "${{ needs.linux_tests.result }}" != 'success' ]] && { RET_CODE=1; echo "Linux tests failed"; } [[ "${{ needs.linux_tests.result }}" != 'success' ]] && { RET_CODE=1; echo "Linux tests failed"; }
[[ "${{ needs.windows_tests.result }}" != 'success' ]] && { RET_CODE=1; echo "Windows tests failed"; } [[ "${{ needs.windows_tests.result }}" != 'success' ]] && { RET_CODE=1; echo "Windows tests failed"; }
@@ -835,7 +866,7 @@ jobs:
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
if: contains(github.event.pull_request.labels.*.name, 'run-bundling') if: contains(github.event.pull_request.labels.*.name, 'run-bundling')
with: with:
name: Zed_${{ github.event.pull_request.head.sha || github.sha }}-x86_64.exe name: ZedEditorUserSetup-x64-${{ github.event.pull_request.head.sha || github.sha }}.exe
path: ${{ env.SETUP_PATH }} path: ${{ env.SETUP_PATH }}
- name: Upload Artifacts to release - name: Upload Artifacts to release
@@ -851,8 +882,7 @@ jobs:
auto-release-preview: auto-release-preview:
name: Auto release preview name: Auto release preview
if: | if: |
false startsWith(github.ref, 'refs/tags/v')
&& startsWith(github.ref, 'refs/tags/v')
&& endsWith(github.ref, '-pre') && !endsWith(github.ref, '.0-pre') && endsWith(github.ref, '-pre') && !endsWith(github.ref, '.0-pre')
needs: [bundle-mac, bundle-linux-x86_x64, bundle-linux-aarch64, bundle-windows-x64] needs: [bundle-mac, bundle-linux-x86_x64, bundle-linux-aarch64, bundle-windows-x64]
runs-on: runs-on:

View File

@@ -38,26 +38,6 @@ jobs:
webhook-url: ${{ secrets.DISCORD_WEBHOOK_RELEASE_NOTES }} webhook-url: ${{ secrets.DISCORD_WEBHOOK_RELEASE_NOTES }}
content: ${{ steps.get-content.outputs.string }} content: ${{ steps.get-content.outputs.string }}
publish-winget:
runs-on:
- ubuntu-latest
steps:
- name: Set Package Name
id: set-package-name
run: |
if [ "${{ github.event.release.prerelease }}" == "true" ]; then
PACKAGE_NAME=ZedIndustries.Zed.Preview
else
PACKAGE_NAME=ZedIndustries.Zed
fi
echo "PACKAGE_NAME=$PACKAGE_NAME" >> "$GITHUB_OUTPUT"
- uses: vedantmgoyal9/winget-releaser@19e706d4c9121098010096f9c495a70a7518b30f # v2
with:
identifier: ${{ steps.set-package-name.outputs.PACKAGE_NAME }}
max-versions-to-keep: 5
token: ${{ secrets.WINGET_TOKEN }}
send_release_notes_email: send_release_notes_email:
if: false && github.repository_owner == 'zed-industries' && !github.event.release.prerelease if: false && github.repository_owner == 'zed-industries' && !github.event.release.prerelease
runs-on: ubuntu-latest runs-on: ubuntu-latest

View File

@@ -22,8 +22,6 @@ jobs:
- name: Build docs - name: Build docs
uses: ./.github/actions/build_docs uses: ./.github/actions/build_docs
env:
DOCS_AMPLITUDE_API_KEY: ${{ secrets.DOCS_AMPLITUDE_API_KEY }}
- name: Deploy Docs - name: Deploy Docs
uses: cloudflare/wrangler-action@da0e0dfe58b7a431659754fdf3f186c529afbe65 # v3 uses: cloudflare/wrangler-action@da0e0dfe58b7a431659754fdf3f186c529afbe65 # v3

1
.gitignore vendored
View File

@@ -25,7 +25,6 @@
/crates/collab/seed.json /crates/collab/seed.json
/crates/theme/schemas/theme.json /crates/theme/schemas/theme.json
/crates/zed/resources/flatpak/flatpak-cargo-sources.json /crates/zed/resources/flatpak/flatpak-cargo-sources.json
/crates/project_panel/benches/linux_repo_snapshot.txt
/dev.zed.Zed*.json /dev.zed.Zed*.json
/node_modules/ /node_modules/
/plugins/bin /plugins/bin

View File

@@ -48,7 +48,7 @@
"remove_trailing_whitespace_on_save": true, "remove_trailing_whitespace_on_save": true,
"ensure_final_newline_on_save": true, "ensure_final_newline_on_save": true,
"file_scan_exclusions": [ "file_scan_exclusions": [
"crates/agent/src/edit_agent/evals/fixtures", "crates/assistant_tools/src/edit_agent/evals/fixtures",
"crates/eval/worktrees/", "crates/eval/worktrees/",
"crates/eval/repos/", "crates/eval/repos/",
"**/.git", "**/.git",

6626
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -6,6 +6,7 @@ members = [
"crates/action_log", "crates/action_log",
"crates/activity_indicator", "crates/activity_indicator",
"crates/agent", "crates/agent",
"crates/agent2",
"crates/agent_servers", "crates/agent_servers",
"crates/agent_settings", "crates/agent_settings",
"crates/agent_ui", "crates/agent_ui",
@@ -13,9 +14,11 @@ members = [
"crates/anthropic", "crates/anthropic",
"crates/askpass", "crates/askpass",
"crates/assets", "crates/assets",
"crates/assistant_text_thread", "crates/assistant_context",
"crates/assistant_slash_command", "crates/assistant_slash_command",
"crates/assistant_slash_commands", "crates/assistant_slash_commands",
"crates/assistant_tool",
"crates/assistant_tools",
"crates/audio", "crates/audio",
"crates/auto_update", "crates/auto_update",
"crates/auto_update_helper", "crates/auto_update_helper",
@@ -70,7 +73,6 @@ members = [
"crates/file_finder", "crates/file_finder",
"crates/file_icons", "crates/file_icons",
"crates/fs", "crates/fs",
"crates/fs_benchmarks",
"crates/fsevent", "crates/fsevent",
"crates/fuzzy", "crates/fuzzy",
"crates/git", "crates/git",
@@ -219,6 +221,7 @@ members = [
# #
"tooling/perf", "tooling/perf",
"tooling/workspace-hack",
"tooling/xtask", "tooling/xtask",
] ]
default-members = ["crates/zed"] default-members = ["crates/zed"]
@@ -237,6 +240,7 @@ acp_tools = { path = "crates/acp_tools" }
acp_thread = { path = "crates/acp_thread" } acp_thread = { path = "crates/acp_thread" }
action_log = { path = "crates/action_log" } action_log = { path = "crates/action_log" }
agent = { path = "crates/agent" } agent = { path = "crates/agent" }
agent2 = { path = "crates/agent2" }
activity_indicator = { path = "crates/activity_indicator" } activity_indicator = { path = "crates/activity_indicator" }
agent_ui = { path = "crates/agent_ui" } agent_ui = { path = "crates/agent_ui" }
agent_settings = { path = "crates/agent_settings" } agent_settings = { path = "crates/agent_settings" }
@@ -246,9 +250,11 @@ ai_onboarding = { path = "crates/ai_onboarding" }
anthropic = { path = "crates/anthropic" } anthropic = { path = "crates/anthropic" }
askpass = { path = "crates/askpass" } askpass = { path = "crates/askpass" }
assets = { path = "crates/assets" } assets = { path = "crates/assets" }
assistant_text_thread = { path = "crates/assistant_text_thread" } assistant_context = { path = "crates/assistant_context" }
assistant_slash_command = { path = "crates/assistant_slash_command" } assistant_slash_command = { path = "crates/assistant_slash_command" }
assistant_slash_commands = { path = "crates/assistant_slash_commands" } assistant_slash_commands = { path = "crates/assistant_slash_commands" }
assistant_tool = { path = "crates/assistant_tool" }
assistant_tools = { path = "crates/assistant_tools" }
audio = { path = "crates/audio" } audio = { path = "crates/audio" }
auto_update = { path = "crates/auto_update" } auto_update = { path = "crates/auto_update" }
auto_update_helper = { path = "crates/auto_update_helper" } auto_update_helper = { path = "crates/auto_update_helper" }
@@ -268,7 +274,7 @@ cloud_llm_client = { path = "crates/cloud_llm_client" }
cloud_zeta2_prompt = { path = "crates/cloud_zeta2_prompt" } cloud_zeta2_prompt = { path = "crates/cloud_zeta2_prompt" }
collab = { path = "crates/collab" } collab = { path = "crates/collab" }
collab_ui = { path = "crates/collab_ui" } collab_ui = { path = "crates/collab_ui" }
collections = { path = "crates/collections", version = "0.1.0" } collections = { path = "crates/collections", package = "zed-collections", version = "0.1.0" }
command_palette = { path = "crates/command_palette" } command_palette = { path = "crates/command_palette" }
command_palette_hooks = { path = "crates/command_palette_hooks" } command_palette_hooks = { path = "crates/command_palette_hooks" }
component = { path = "crates/component" } component = { path = "crates/component" }
@@ -284,7 +290,7 @@ debug_adapter_extension = { path = "crates/debug_adapter_extension" }
debugger_tools = { path = "crates/debugger_tools" } debugger_tools = { path = "crates/debugger_tools" }
debugger_ui = { path = "crates/debugger_ui" } debugger_ui = { path = "crates/debugger_ui" }
deepseek = { path = "crates/deepseek" } deepseek = { path = "crates/deepseek" }
derive_refineable = { path = "crates/refineable/derive_refineable" } derive_refineable = { path = "crates/refineable/derive_refineable", package = "zed-derive-refineable", version = "0.1.0" }
diagnostics = { path = "crates/diagnostics" } diagnostics = { path = "crates/diagnostics" }
editor = { path = "crates/editor" } editor = { path = "crates/editor" }
extension = { path = "crates/extension" } extension = { path = "crates/extension" }
@@ -303,10 +309,10 @@ git_ui = { path = "crates/git_ui" }
go_to_line = { path = "crates/go_to_line" } go_to_line = { path = "crates/go_to_line" }
google_ai = { path = "crates/google_ai" } google_ai = { path = "crates/google_ai" }
gpui = { path = "crates/gpui", default-features = false } gpui = { path = "crates/gpui", default-features = false }
gpui_macros = { path = "crates/gpui_macros" } gpui_macros = { path = "crates/gpui_macros", package = "gpui-macros", version = "0.1.0" }
gpui_tokio = { path = "crates/gpui_tokio" } gpui_tokio = { path = "crates/gpui_tokio" }
html_to_markdown = { path = "crates/html_to_markdown" } html_to_markdown = { path = "crates/html_to_markdown" }
http_client = { path = "crates/http_client" } http_client = { path = "crates/http_client", package = "zed-http-client", version = "0.1.0" }
http_client_tls = { path = "crates/http_client_tls" } http_client_tls = { path = "crates/http_client_tls" }
icons = { path = "crates/icons" } icons = { path = "crates/icons" }
image_viewer = { path = "crates/image_viewer" } image_viewer = { path = "crates/image_viewer" }
@@ -335,7 +341,7 @@ lsp = { path = "crates/lsp" }
markdown = { path = "crates/markdown" } markdown = { path = "crates/markdown" }
markdown_preview = { path = "crates/markdown_preview" } markdown_preview = { path = "crates/markdown_preview" }
svg_preview = { path = "crates/svg_preview" } svg_preview = { path = "crates/svg_preview" }
media = { path = "crates/media" } media = { path = "crates/media", package = "zed-media", version = "0.1.0" }
menu = { path = "crates/menu" } menu = { path = "crates/menu" }
migrator = { path = "crates/migrator" } migrator = { path = "crates/migrator" }
mistral = { path = "crates/mistral" } mistral = { path = "crates/mistral" }
@@ -352,7 +358,7 @@ outline = { path = "crates/outline" }
outline_panel = { path = "crates/outline_panel" } outline_panel = { path = "crates/outline_panel" }
panel = { path = "crates/panel" } panel = { path = "crates/panel" }
paths = { path = "crates/paths" } paths = { path = "crates/paths" }
perf = { path = "tooling/perf" } perf = { path = "tooling/perf", package = "zed-perf", version = "0.1.0" }
picker = { path = "crates/picker" } picker = { path = "crates/picker" }
plugin = { path = "crates/plugin" } plugin = { path = "crates/plugin" }
plugin_macros = { path = "crates/plugin_macros" } plugin_macros = { path = "crates/plugin_macros" }
@@ -364,7 +370,7 @@ project_symbols = { path = "crates/project_symbols" }
prompt_store = { path = "crates/prompt_store" } prompt_store = { path = "crates/prompt_store" }
proto = { path = "crates/proto" } proto = { path = "crates/proto" }
recent_projects = { path = "crates/recent_projects" } recent_projects = { path = "crates/recent_projects" }
refineable = { path = "crates/refineable" } refineable = { path = "crates/refineable", package = "zed-refineable", version = "0.1.0" }
release_channel = { path = "crates/release_channel" } release_channel = { path = "crates/release_channel" }
scheduler = { path = "crates/scheduler" } scheduler = { path = "crates/scheduler" }
remote = { path = "crates/remote" } remote = { path = "crates/remote" }
@@ -372,12 +378,12 @@ remote_server = { path = "crates/remote_server" }
repl = { path = "crates/repl" } repl = { path = "crates/repl" }
reqwest_client = { path = "crates/reqwest_client" } reqwest_client = { path = "crates/reqwest_client" }
rich_text = { path = "crates/rich_text" } rich_text = { path = "crates/rich_text" }
rodio = { git = "https://github.com/RustAudio/rodio", rev ="e2074c6c2acf07b57cf717e076bdda7a9ac6e70b", features = ["wav", "playback", "wav_output", "recording"] } rodio = { git = "https://github.com/RustAudio/rodio" }
rope = { path = "crates/rope" } rope = { path = "crates/rope" }
rpc = { path = "crates/rpc" } rpc = { path = "crates/rpc" }
rules_library = { path = "crates/rules_library" } rules_library = { path = "crates/rules_library" }
search = { path = "crates/search" } search = { path = "crates/search" }
semantic_version = { path = "crates/semantic_version" } semantic_version = { path = "crates/semantic_version", package = "zed-semantic-version", version = "0.1.0" }
session = { path = "crates/session" } session = { path = "crates/session" }
settings = { path = "crates/settings" } settings = { path = "crates/settings" }
settings_macros = { path = "crates/settings_macros" } settings_macros = { path = "crates/settings_macros" }
@@ -390,7 +396,7 @@ sqlez_macros = { path = "crates/sqlez_macros" }
story = { path = "crates/story" } story = { path = "crates/story" }
storybook = { path = "crates/storybook" } storybook = { path = "crates/storybook" }
streaming_diff = { path = "crates/streaming_diff" } streaming_diff = { path = "crates/streaming_diff" }
sum_tree = { path = "crates/sum_tree" } sum_tree = { path = "crates/sum_tree", package = "zed-sum-tree", version = "0.1.0" }
supermaven = { path = "crates/supermaven" } supermaven = { path = "crates/supermaven" }
supermaven_api = { path = "crates/supermaven_api" } supermaven_api = { path = "crates/supermaven_api" }
codestral = { path = "crates/codestral" } codestral = { path = "crates/codestral" }
@@ -414,8 +420,8 @@ ui = { path = "crates/ui" }
ui_input = { path = "crates/ui_input" } ui_input = { path = "crates/ui_input" }
ui_macros = { path = "crates/ui_macros" } ui_macros = { path = "crates/ui_macros" }
ui_prompt = { path = "crates/ui_prompt" } ui_prompt = { path = "crates/ui_prompt" }
util = { path = "crates/util" } util = { path = "crates/util", package = "zed-util", version = "0.1.0" }
util_macros = { path = "crates/util_macros" } util_macros = { path = "crates/util_macros", package = "zed-util-macros", version = "0.1.0" }
vercel = { path = "crates/vercel" } vercel = { path = "crates/vercel" }
vim = { path = "crates/vim" } vim = { path = "crates/vim" }
vim_mode_setting = { path = "crates/vim_mode_setting" } vim_mode_setting = { path = "crates/vim_mode_setting" }
@@ -438,7 +444,7 @@ zlog_settings = { path = "crates/zlog_settings" }
# External crates # External crates
# #
agent-client-protocol = { version = "0.5.0", features = ["unstable"] } agent-client-protocol = { version = "0.4.3", features = ["unstable"] }
aho-corasick = "1.1" aho-corasick = "1.1"
alacritty_terminal = "0.25.1-rc1" alacritty_terminal = "0.25.1-rc1"
any_vec = "0.14" any_vec = "0.14"
@@ -449,13 +455,12 @@ async-compat = "0.2.1"
async-compression = { version = "0.4", features = ["gzip", "futures-io"] } async-compression = { version = "0.4", features = ["gzip", "futures-io"] }
async-dispatcher = "0.1" async-dispatcher = "0.1"
async-fs = "2.1" async-fs = "2.1"
async-lock = "2.1"
async-pipe = { git = "https://github.com/zed-industries/async-pipe-rs", rev = "82d00a04211cf4e1236029aa03e6b6ce2a74c553" } async-pipe = { git = "https://github.com/zed-industries/async-pipe-rs", rev = "82d00a04211cf4e1236029aa03e6b6ce2a74c553" }
async-recursion = "1.0.0" async-recursion = "1.0.0"
async-tar = "0.5.1" async-tar = "0.5.0"
async-task = "4.7" async-task = "4.7"
async-trait = "0.1" async-trait = "0.1"
async-tungstenite = "0.31.0" async-tungstenite = "0.29.1"
async_zip = { version = "0.0.17", features = ["deflate", "deflate64"] } async_zip = { version = "0.0.17", features = ["deflate", "deflate64"] }
aws-config = { version = "1.6.1", features = ["behavior-version-latest"] } aws-config = { version = "1.6.1", features = ["behavior-version-latest"] }
aws-credential-types = { version = "1.2.2", features = [ aws-credential-types = { version = "1.2.2", features = [
@@ -481,10 +486,10 @@ chrono = { version = "0.4", features = ["serde"] }
ciborium = "0.2" ciborium = "0.2"
circular-buffer = "1.0" circular-buffer = "1.0"
clap = { version = "4.4", features = ["derive"] } clap = { version = "4.4", features = ["derive"] }
cocoa = "=0.26.0" cocoa = "0.26"
cocoa-foundation = "=0.2.0" cocoa-foundation = "0.2.0"
convert_case = "0.8.0" convert_case = "0.8.0"
core-foundation = "=0.10.0" core-foundation = "0.10.0"
core-foundation-sys = "0.8.6" core-foundation-sys = "0.8.6"
core-video = { version = "0.4.3", features = ["metal"] } core-video = { version = "0.4.3", features = ["metal"] }
cpal = "0.16" cpal = "0.16"
@@ -506,7 +511,6 @@ fork = "0.2.0"
futures = "0.3" futures = "0.3"
futures-batch = "0.6.1" futures-batch = "0.6.1"
futures-lite = "1.13" futures-lite = "1.13"
gh-workflow = "0.8.0"
git2 = { version = "0.20.1", default-features = false } git2 = { version = "0.20.1", default-features = false }
globset = "0.4" globset = "0.4"
handlebars = "4.3" handlebars = "4.3"
@@ -548,7 +552,7 @@ nix = "0.29"
num-format = "0.4.4" num-format = "0.4.4"
num-traits = "0.2" num-traits = "0.2"
objc = "0.2" objc = "0.2"
objc2-foundation = { version = "=0.3.1", default-features = false, features = [ objc2-foundation = { version = "0.3", default-features = false, features = [
"NSArray", "NSArray",
"NSAttributedString", "NSAttributedString",
"NSBundle", "NSBundle",
@@ -581,14 +585,14 @@ partial-json-fixer = "0.5.3"
parse_int = "0.9" parse_int = "0.9"
pciid-parser = "0.8.0" pciid-parser = "0.8.0"
pathdiff = "0.2" pathdiff = "0.2"
pet = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "e97b9508befa0062929da65a01054d25c4be861c" } pet = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "845945b830297a50de0e24020b980a65e4820559" }
pet-conda = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "e97b9508befa0062929da65a01054d25c4be861c" } pet-conda = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "845945b830297a50de0e24020b980a65e4820559" }
pet-core = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "e97b9508befa0062929da65a01054d25c4be861c" } pet-core = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "845945b830297a50de0e24020b980a65e4820559" }
pet-fs = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "e97b9508befa0062929da65a01054d25c4be861c" } pet-fs = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "845945b830297a50de0e24020b980a65e4820559" }
pet-pixi = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "e97b9508befa0062929da65a01054d25c4be861c" } pet-pixi = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "845945b830297a50de0e24020b980a65e4820559" }
pet-poetry = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "e97b9508befa0062929da65a01054d25c4be861c" } pet-poetry = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "845945b830297a50de0e24020b980a65e4820559" }
pet-reporter = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "e97b9508befa0062929da65a01054d25c4be861c" } pet-reporter = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "845945b830297a50de0e24020b980a65e4820559" }
pet-virtualenv = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "e97b9508befa0062929da65a01054d25c4be861c" } pet-virtualenv = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "845945b830297a50de0e24020b980a65e4820559" }
portable-pty = "0.9.0" portable-pty = "0.9.0"
postage = { version = "0.5", features = ["futures-traits"] } postage = { version = "0.5", features = ["futures-traits"] }
pretty_assertions = { version = "1.3.0", features = ["unstable"] } pretty_assertions = { version = "1.3.0", features = ["unstable"] }
@@ -646,11 +650,11 @@ sqlformat = "0.2"
stacksafe = "0.1" stacksafe = "0.1"
streaming-iterator = "0.1" streaming-iterator = "0.1"
strsim = "0.11" strsim = "0.11"
strum = { version = "0.27.2", features = ["derive"] } strum = { version = "0.27.0", features = ["derive"] }
subtle = "2.5.0" subtle = "2.5.0"
syn = { version = "2.0.101", features = ["full", "extra-traits", "visit-mut"] } syn = { version = "2.0.101", features = ["full", "extra-traits", "visit-mut"] }
sys-locale = "0.3.1" sys-locale = "0.3.1"
sysinfo = "0.37.0" sysinfo = "0.31.0"
take-until = "0.2.0" take-until = "0.2.0"
tempfile = "3.20.0" tempfile = "3.20.0"
thiserror = "2.0.12" thiserror = "2.0.12"
@@ -714,6 +718,7 @@ wasmtime-wasi = "29"
which = "6.0.0" which = "6.0.0"
windows-core = "0.61" windows-core = "0.61"
wit-component = "0.221" wit-component = "0.221"
workspace-hack = "0.1.0"
yawc = "0.2.5" yawc = "0.2.5"
zeroize = "1.8" zeroize = "1.8"
zstd = "0.11" zstd = "0.11"
@@ -774,6 +779,9 @@ notify = { git = "https://github.com/zed-industries/notify.git", rev = "bbb9ea5a
notify-types = { git = "https://github.com/zed-industries/notify.git", rev = "bbb9ea5ae52b253e095737847e367c30653a2e96" } notify-types = { git = "https://github.com/zed-industries/notify.git", rev = "bbb9ea5ae52b253e095737847e367c30653a2e96" }
windows-capture = { git = "https://github.com/zed-industries/windows-capture.git", rev = "f0d6c1b6691db75461b732f6d5ff56eed002eeb9" } windows-capture = { git = "https://github.com/zed-industries/windows-capture.git", rev = "f0d6c1b6691db75461b732f6d5ff56eed002eeb9" }
# Makes the workspace hack crate refer to the local one, but only when you're building locally
workspace-hack = { path = "tooling/workspace-hack" }
[profile.dev] [profile.dev]
split-debuginfo = "unpacked" split-debuginfo = "unpacked"
codegen-units = 16 codegen-units = 16
@@ -797,7 +805,7 @@ wasmtime = { opt-level = 3 }
activity_indicator = { codegen-units = 1 } activity_indicator = { codegen-units = 1 }
assets = { codegen-units = 1 } assets = { codegen-units = 1 }
breadcrumbs = { codegen-units = 1 } breadcrumbs = { codegen-units = 1 }
collections = { codegen-units = 1 } zed-collections = { codegen-units = 1 }
command_palette = { codegen-units = 1 } command_palette = { codegen-units = 1 }
command_palette_hooks = { codegen-units = 1 } command_palette_hooks = { codegen-units = 1 }
extension_cli = { codegen-units = 1 } extension_cli = { codegen-units = 1 }
@@ -817,11 +825,11 @@ outline = { codegen-units = 1 }
paths = { codegen-units = 1 } paths = { codegen-units = 1 }
prettier = { codegen-units = 1 } prettier = { codegen-units = 1 }
project_symbols = { codegen-units = 1 } project_symbols = { codegen-units = 1 }
refineable = { codegen-units = 1 } zed-refineable = { codegen-units = 1 }
release_channel = { codegen-units = 1 } release_channel = { codegen-units = 1 }
reqwest_client = { codegen-units = 1 } reqwest_client = { codegen-units = 1 }
rich_text = { codegen-units = 1 } rich_text = { codegen-units = 1 }
semantic_version = { codegen-units = 1 } zed-semantic-version = { codegen-units = 1 }
session = { codegen-units = 1 } session = { codegen-units = 1 }
snippet = { codegen-units = 1 } snippet = { codegen-units = 1 }
snippets_ui = { codegen-units = 1 } snippets_ui = { codegen-units = 1 }
@@ -901,5 +909,5 @@ ignored = [
"serde", "serde",
"component", "component",
"documented", "documented",
"sea-orm-macros", "workspace-hack",
] ]

2
Cross.toml Normal file
View File

@@ -0,0 +1,2 @@
[build]
dockerfile = "Dockerfile-cross"

17
Dockerfile-cross Normal file
View File

@@ -0,0 +1,17 @@
# syntax=docker/dockerfile:1
ARG CROSS_BASE_IMAGE
FROM ${CROSS_BASE_IMAGE}
WORKDIR /app
ARG TZ=Etc/UTC \
LANG=C.UTF-8 \
LC_ALL=C.UTF-8 \
DEBIAN_FRONTEND=noninteractive
ENV CARGO_TERM_COLOR=always
COPY script/install-mold script/
RUN ./script/install-mold "2.34.0"
COPY script/remote-server script/
RUN ./script/remote-server
COPY . .

View File

@@ -9,10 +9,11 @@ Welcome to Zed, a high-performance, multiplayer code editor from the creators of
### Installation ### Installation
On macOS, Linux, and Windows you can [download Zed directly](https://zed.dev/download) or [install Zed via your local package manager](https://zed.dev/docs/linux#installing-via-a-package-manager). On macOS and Linux you can [download Zed directly](https://zed.dev/download) or [install Zed via your local package manager](https://zed.dev/docs/linux#installing-via-a-package-manager).
Other platforms are not yet available: Other platforms are not yet available:
- Windows ([tracking issue](https://github.com/zed-industries/zed/issues/5394))
- Web ([tracking issue](https://github.com/zed-industries/zed/issues/5396)) - Web ([tracking issue](https://github.com/zed-industries/zed/issues/5396))
### Developing Zed ### Developing Zed

View File

@@ -1,3 +1,9 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <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 opacity="0.6" d="M3.5 11V5.5L8.5 8L3.5 11Z" fill="black"/>
<path opacity="0.4" d="M8.5 14L3.5 11L8.5 8V14Z" fill="black"/>
<path opacity="0.6" d="M8.5 5.5H3.5L8.5 2.5L8.5 5.5Z" fill="black"/>
<path opacity="0.8" d="M8.5 5.5V2.5L13.5 5.5H8.5Z" fill="black"/>
<path opacity="0.2" d="M13.5 11L8.5 14L11 9.5L13.5 11Z" fill="black"/>
<path opacity="0.5" d="M13.5 11L11 9.5L13.5 5V11Z" fill="black"/>
<path d="M3.5 11V5L8.5 2.11325L13.5 5V11L8.5 13.8868L3.5 11Z" stroke="black"/>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 769 B

After

Width:  |  Height:  |  Size: 583 B

View File

@@ -1,4 +1 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none"><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2" d="M2.6 5v3.6h3.6"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2" d="M13.4 11A5.4 5.4 0 0 0 8 5.6a5.4 5.4 0 0 0-3.6 1.38L2.6 8.6"/></svg>
<path d="M6.125 9.25001L3 6.125L6.125 3" stroke="#C4CAD4" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M3 6.125H9.56251C10.0139 6.125 10.4609 6.21391 10.878 6.38666C11.295 6.55942 11.674 6.81262 11.9932 7.13182C12.3124 7.45102 12.5656 7.82997 12.7383 8.24703C12.9111 8.66408 13 9.11108 13 9.5625C13 10.0139 12.9111 10.4609 12.7383 10.878C12.5656 11.295 12.3124 11.674 11.9932 11.9932C11.674 12.3124 11.295 12.5656 10.878 12.7383C10.4609 12.9111 10.0139 13 9.56251 13H7.375" stroke="black" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 692 B

After

Width:  |  Height:  |  Size: 339 B

View File

@@ -30,8 +30,8 @@
"ctrl-+": ["zed::IncreaseBufferFontSize", { "persist": false }], "ctrl-+": ["zed::IncreaseBufferFontSize", { "persist": false }],
"ctrl--": ["zed::DecreaseBufferFontSize", { "persist": false }], "ctrl--": ["zed::DecreaseBufferFontSize", { "persist": false }],
"ctrl-0": ["zed::ResetBufferFontSize", { "persist": false }], "ctrl-0": ["zed::ResetBufferFontSize", { "persist": false }],
"ctrl-,": "zed::OpenSettings", "ctrl-,": "zed::OpenSettingsEditor",
"ctrl-alt-,": "zed::OpenSettingsFile", "ctrl-alt-,": "zed::OpenSettings",
"ctrl-q": "zed::Quit", "ctrl-q": "zed::Quit",
"f4": "debugger::Start", "f4": "debugger::Start",
"shift-f5": "debugger::Stop", "shift-f5": "debugger::Stop",
@@ -139,7 +139,7 @@
"find": "buffer_search::Deploy", "find": "buffer_search::Deploy",
"ctrl-f": "buffer_search::Deploy", "ctrl-f": "buffer_search::Deploy",
"ctrl-h": "buffer_search::DeployReplace", "ctrl-h": "buffer_search::DeployReplace",
"ctrl->": "agent::AddSelectionToThread", "ctrl->": "agent::QuoteSelection",
"ctrl-<": "assistant::InsertIntoEditor", "ctrl-<": "assistant::InsertIntoEditor",
"ctrl-alt-e": "editor::SelectEnclosingSymbol", "ctrl-alt-e": "editor::SelectEnclosingSymbol",
"ctrl-shift-backspace": "editor::GoToPreviousChange", "ctrl-shift-backspace": "editor::GoToPreviousChange",
@@ -243,7 +243,7 @@
"ctrl-shift-i": "agent::ToggleOptionsMenu", "ctrl-shift-i": "agent::ToggleOptionsMenu",
"ctrl-alt-shift-n": "agent::ToggleNewThreadMenu", "ctrl-alt-shift-n": "agent::ToggleNewThreadMenu",
"shift-alt-escape": "agent::ExpandMessageEditor", "shift-alt-escape": "agent::ExpandMessageEditor",
"ctrl->": "agent::AddSelectionToThread", "ctrl->": "agent::QuoteSelection",
"ctrl-alt-e": "agent::RemoveAllContext", "ctrl-alt-e": "agent::RemoveAllContext",
"ctrl-shift-e": "project_panel::ToggleFocus", "ctrl-shift-e": "project_panel::ToggleFocus",
"ctrl-shift-enter": "agent::ContinueThread", "ctrl-shift-enter": "agent::ContinueThread",
@@ -269,14 +269,14 @@
} }
}, },
{ {
"context": "AgentPanel && text_thread", "context": "AgentPanel && prompt_editor",
"bindings": { "bindings": {
"ctrl-n": "agent::NewTextThread", "ctrl-n": "agent::NewTextThread",
"ctrl-alt-t": "agent::NewThread" "ctrl-alt-t": "agent::NewThread"
} }
}, },
{ {
"context": "AgentPanel && acp_thread", "context": "AgentPanel && external_agent_thread",
"use_key_equivalents": true, "use_key_equivalents": true,
"bindings": { "bindings": {
"ctrl-n": "agent::NewExternalAgentThread", "ctrl-n": "agent::NewExternalAgentThread",
@@ -366,7 +366,7 @@
} }
}, },
{ {
"context": "RulesLibrary", "context": "PromptLibrary",
"bindings": { "bindings": {
"new": "rules_library::NewRule", "new": "rules_library::NewRule",
"ctrl-n": "rules_library::NewRule", "ctrl-n": "rules_library::NewRule",
@@ -491,8 +491,8 @@
"bindings": { "bindings": {
"ctrl-[": "editor::Outdent", "ctrl-[": "editor::Outdent",
"ctrl-]": "editor::Indent", "ctrl-]": "editor::Indent",
"shift-alt-up": ["editor::AddSelectionAbove", { "skip_soft_wrap": true }], // Insert Cursor Above "shift-alt-up": "editor::AddSelectionAbove", // Insert Cursor Above
"shift-alt-down": ["editor::AddSelectionBelow", { "skip_soft_wrap": true }], // Insert Cursor Below "shift-alt-down": "editor::AddSelectionBelow", // Insert Cursor Below
"ctrl-shift-k": "editor::DeleteLine", "ctrl-shift-k": "editor::DeleteLine",
"alt-up": "editor::MoveLineUp", "alt-up": "editor::MoveLineUp",
"alt-down": "editor::MoveLineDown", "alt-down": "editor::MoveLineDown",
@@ -621,7 +621,7 @@
"ctrl-shift-f": "pane::DeploySearch", "ctrl-shift-f": "pane::DeploySearch",
"ctrl-shift-h": ["pane::DeploySearch", { "replace_enabled": true }], "ctrl-shift-h": ["pane::DeploySearch", { "replace_enabled": true }],
"ctrl-shift-t": "pane::ReopenClosedItem", "ctrl-shift-t": "pane::ReopenClosedItem",
"ctrl-k ctrl-s": "zed::OpenKeymap", "ctrl-k ctrl-s": "zed::OpenKeymapEditor",
"ctrl-k ctrl-t": "theme_selector::Toggle", "ctrl-k ctrl-t": "theme_selector::Toggle",
"ctrl-alt-super-p": "settings_profile_selector::Toggle", "ctrl-alt-super-p": "settings_profile_selector::Toggle",
"ctrl-t": "project_symbols::Toggle", "ctrl-t": "project_symbols::Toggle",
@@ -1080,8 +1080,7 @@
{ {
"context": "StashList || (StashList > Picker > Editor)", "context": "StashList || (StashList > Picker > Editor)",
"bindings": { "bindings": {
"ctrl-shift-backspace": "stash_picker::DropStashItem", "ctrl-shift-backspace": "stash_picker::DropStashItem"
"ctrl-shift-v": "stash_picker::ShowStashItem"
} }
}, },
{ {
@@ -1250,7 +1249,6 @@
"escape": "workspace::CloseWindow", "escape": "workspace::CloseWindow",
"ctrl-m": "settings_editor::Minimize", "ctrl-m": "settings_editor::Minimize",
"ctrl-f": "search::FocusSearch", "ctrl-f": "search::FocusSearch",
"left": "settings_editor::ToggleFocusNav",
"ctrl-shift-e": "settings_editor::ToggleFocusNav", "ctrl-shift-e": "settings_editor::ToggleFocusNav",
// todo(settings_ui): cut this down based on the max files and overflow UI // todo(settings_ui): cut this down based on the max files and overflow UI
"ctrl-1": ["settings_editor::FocusFile", 0], "ctrl-1": ["settings_editor::FocusFile", 0],
@@ -1267,22 +1265,10 @@
"ctrl-pagedown": "settings_editor::FocusNextFile" "ctrl-pagedown": "settings_editor::FocusNextFile"
} }
}, },
{
"context": "StashDiff > Editor",
"bindings": {
"ctrl-space": "git::ApplyCurrentStash",
"ctrl-shift-space": "git::PopCurrentStash",
"ctrl-shift-backspace": "git::DropCurrentStash"
}
},
{ {
"context": "SettingsWindow > NavigationMenu", "context": "SettingsWindow > NavigationMenu",
"use_key_equivalents": true, "use_key_equivalents": true,
"bindings": { "bindings": {
"up": "settings_editor::FocusPreviousNavEntry",
"shift-tab": "settings_editor::FocusPreviousNavEntry",
"down": "settings_editor::FocusNextNavEntry",
"tab": "settings_editor::FocusNextNavEntry",
"right": "settings_editor::ExpandNavEntry", "right": "settings_editor::ExpandNavEntry",
"left": "settings_editor::CollapseNavEntry", "left": "settings_editor::CollapseNavEntry",
"pageup": "settings_editor::FocusPreviousRootNavEntry", "pageup": "settings_editor::FocusPreviousRootNavEntry",
@@ -1290,13 +1276,5 @@
"home": "settings_editor::FocusFirstNavEntry", "home": "settings_editor::FocusFirstNavEntry",
"end": "settings_editor::FocusLastNavEntry" "end": "settings_editor::FocusLastNavEntry"
} }
},
{
"context": "Zeta2Feedback > Editor",
"bindings": {
"enter": "editor::Newline",
"ctrl-enter up": "dev::Zeta2RatePredictionPositive",
"ctrl-enter down": "dev::Zeta2RatePredictionNegative"
}
} }
] ]

View File

@@ -39,8 +39,8 @@
"cmd-+": ["zed::IncreaseBufferFontSize", { "persist": false }], "cmd-+": ["zed::IncreaseBufferFontSize", { "persist": false }],
"cmd--": ["zed::DecreaseBufferFontSize", { "persist": false }], "cmd--": ["zed::DecreaseBufferFontSize", { "persist": false }],
"cmd-0": ["zed::ResetBufferFontSize", { "persist": false }], "cmd-0": ["zed::ResetBufferFontSize", { "persist": false }],
"cmd-,": "zed::OpenSettings", "cmd-,": "zed::OpenSettingsEditor",
"cmd-alt-,": "zed::OpenSettingsFile", "cmd-alt-,": "zed::OpenSettings",
"cmd-q": "zed::Quit", "cmd-q": "zed::Quit",
"cmd-h": "zed::Hide", "cmd-h": "zed::Hide",
"alt-cmd-h": "zed::HideOthers", "alt-cmd-h": "zed::HideOthers",
@@ -163,7 +163,7 @@
"cmd-alt-f": "buffer_search::DeployReplace", "cmd-alt-f": "buffer_search::DeployReplace",
"cmd-alt-l": ["buffer_search::Deploy", { "selection_search_enabled": true }], "cmd-alt-l": ["buffer_search::Deploy", { "selection_search_enabled": true }],
"cmd-e": ["buffer_search::Deploy", { "focus": false }], "cmd-e": ["buffer_search::Deploy", { "focus": false }],
"cmd->": "agent::AddSelectionToThread", "cmd->": "agent::QuoteSelection",
"cmd-<": "assistant::InsertIntoEditor", "cmd-<": "assistant::InsertIntoEditor",
"cmd-alt-e": "editor::SelectEnclosingSymbol", "cmd-alt-e": "editor::SelectEnclosingSymbol",
"alt-enter": "editor::OpenSelectionsInMultibuffer" "alt-enter": "editor::OpenSelectionsInMultibuffer"
@@ -282,7 +282,7 @@
"cmd-shift-i": "agent::ToggleOptionsMenu", "cmd-shift-i": "agent::ToggleOptionsMenu",
"cmd-alt-shift-n": "agent::ToggleNewThreadMenu", "cmd-alt-shift-n": "agent::ToggleNewThreadMenu",
"shift-alt-escape": "agent::ExpandMessageEditor", "shift-alt-escape": "agent::ExpandMessageEditor",
"cmd->": "agent::AddSelectionToThread", "cmd->": "agent::QuoteSelection",
"cmd-alt-e": "agent::RemoveAllContext", "cmd-alt-e": "agent::RemoveAllContext",
"cmd-shift-e": "project_panel::ToggleFocus", "cmd-shift-e": "project_panel::ToggleFocus",
"cmd-ctrl-b": "agent::ToggleBurnMode", "cmd-ctrl-b": "agent::ToggleBurnMode",
@@ -307,7 +307,7 @@
} }
}, },
{ {
"context": "AgentPanel && text_thread", "context": "AgentPanel && prompt_editor",
"use_key_equivalents": true, "use_key_equivalents": true,
"bindings": { "bindings": {
"cmd-n": "agent::NewTextThread", "cmd-n": "agent::NewTextThread",
@@ -315,7 +315,7 @@
} }
}, },
{ {
"context": "AgentPanel && acp_thread", "context": "AgentPanel && external_agent_thread",
"use_key_equivalents": true, "use_key_equivalents": true,
"bindings": { "bindings": {
"cmd-n": "agent::NewExternalAgentThread", "cmd-n": "agent::NewExternalAgentThread",
@@ -423,7 +423,7 @@
} }
}, },
{ {
"context": "RulesLibrary", "context": "PromptLibrary",
"use_key_equivalents": true, "use_key_equivalents": true,
"bindings": { "bindings": {
"cmd-n": "rules_library::NewRule", "cmd-n": "rules_library::NewRule",
@@ -539,10 +539,10 @@
"bindings": { "bindings": {
"cmd-[": "editor::Outdent", "cmd-[": "editor::Outdent",
"cmd-]": "editor::Indent", "cmd-]": "editor::Indent",
"cmd-ctrl-p": ["editor::AddSelectionAbove", { "skip_soft_wrap": false }], // Insert cursor above "cmd-ctrl-p": "editor::AddSelectionAbove", // Insert cursor above
"cmd-alt-up": ["editor::AddSelectionAbove", { "skip_soft_wrap": true }], "cmd-alt-up": "editor::AddSelectionAbove",
"cmd-ctrl-n": ["editor::AddSelectionBelow", { "skip_soft_wrap": false }], // Insert cursor below "cmd-ctrl-n": "editor::AddSelectionBelow", // Insert cursor below
"cmd-alt-down": ["editor::AddSelectionBelow", { "skip_soft_wrap": true }], "cmd-alt-down": "editor::AddSelectionBelow",
"cmd-shift-k": "editor::DeleteLine", "cmd-shift-k": "editor::DeleteLine",
"alt-up": "editor::MoveLineUp", "alt-up": "editor::MoveLineUp",
"alt-down": "editor::MoveLineDown", "alt-down": "editor::MoveLineDown",
@@ -690,7 +690,7 @@
"cmd-shift-f": "pane::DeploySearch", "cmd-shift-f": "pane::DeploySearch",
"cmd-shift-h": ["pane::DeploySearch", { "replace_enabled": true }], "cmd-shift-h": ["pane::DeploySearch", { "replace_enabled": true }],
"cmd-shift-t": "pane::ReopenClosedItem", "cmd-shift-t": "pane::ReopenClosedItem",
"cmd-k cmd-s": "zed::OpenKeymap", "cmd-k cmd-s": "zed::OpenKeymapEditor",
"cmd-k cmd-t": "theme_selector::Toggle", "cmd-k cmd-t": "theme_selector::Toggle",
"ctrl-alt-cmd-p": "settings_profile_selector::Toggle", "ctrl-alt-cmd-p": "settings_profile_selector::Toggle",
"cmd-t": "project_symbols::Toggle", "cmd-t": "project_symbols::Toggle",
@@ -1153,8 +1153,7 @@
"context": "StashList || (StashList > Picker > Editor)", "context": "StashList || (StashList > Picker > Editor)",
"use_key_equivalents": true, "use_key_equivalents": true,
"bindings": { "bindings": {
"ctrl-shift-backspace": "stash_picker::DropStashItem", "ctrl-shift-backspace": "stash_picker::DropStashItem"
"ctrl-shift-v": "stash_picker::ShowStashItem"
} }
}, },
{ {
@@ -1355,7 +1354,6 @@
"escape": "workspace::CloseWindow", "escape": "workspace::CloseWindow",
"cmd-m": "settings_editor::Minimize", "cmd-m": "settings_editor::Minimize",
"cmd-f": "search::FocusSearch", "cmd-f": "search::FocusSearch",
"left": "settings_editor::ToggleFocusNav",
"cmd-shift-e": "settings_editor::ToggleFocusNav", "cmd-shift-e": "settings_editor::ToggleFocusNav",
// todo(settings_ui): cut this down based on the max files and overflow UI // todo(settings_ui): cut this down based on the max files and overflow UI
"ctrl-1": ["settings_editor::FocusFile", 0], "ctrl-1": ["settings_editor::FocusFile", 0],
@@ -1372,23 +1370,10 @@
"cmd-}": "settings_editor::FocusNextFile" "cmd-}": "settings_editor::FocusNextFile"
} }
}, },
{
"context": "StashDiff > Editor",
"use_key_equivalents": true,
"bindings": {
"ctrl-space": "git::ApplyCurrentStash",
"ctrl-shift-space": "git::PopCurrentStash",
"ctrl-shift-backspace": "git::DropCurrentStash"
}
},
{ {
"context": "SettingsWindow > NavigationMenu", "context": "SettingsWindow > NavigationMenu",
"use_key_equivalents": true, "use_key_equivalents": true,
"bindings": { "bindings": {
"up": "settings_editor::FocusPreviousNavEntry",
"shift-tab": "settings_editor::FocusPreviousNavEntry",
"down": "settings_editor::FocusNextNavEntry",
"tab": "settings_editor::FocusNextNavEntry",
"right": "settings_editor::ExpandNavEntry", "right": "settings_editor::ExpandNavEntry",
"left": "settings_editor::CollapseNavEntry", "left": "settings_editor::CollapseNavEntry",
"pageup": "settings_editor::FocusPreviousRootNavEntry", "pageup": "settings_editor::FocusPreviousRootNavEntry",
@@ -1396,13 +1381,5 @@
"home": "settings_editor::FocusFirstNavEntry", "home": "settings_editor::FocusFirstNavEntry",
"end": "settings_editor::FocusLastNavEntry" "end": "settings_editor::FocusLastNavEntry"
} }
},
{
"context": "Zeta2Feedback > Editor",
"bindings": {
"enter": "editor::Newline",
"cmd-enter up": "dev::Zeta2RatePredictionPositive",
"cmd-enter down": "dev::Zeta2RatePredictionNegative"
}
} }
] ]

View File

@@ -29,8 +29,8 @@
"ctrl-shift-=": ["zed::IncreaseBufferFontSize", { "persist": false }], "ctrl-shift-=": ["zed::IncreaseBufferFontSize", { "persist": false }],
"ctrl--": ["zed::DecreaseBufferFontSize", { "persist": false }], "ctrl--": ["zed::DecreaseBufferFontSize", { "persist": false }],
"ctrl-0": ["zed::ResetBufferFontSize", { "persist": false }], "ctrl-0": ["zed::ResetBufferFontSize", { "persist": false }],
"ctrl-,": "zed::OpenSettings", "ctrl-,": "zed::OpenSettingsEditor",
"ctrl-alt-,": "zed::OpenSettingsFile", "ctrl-alt-,": "zed::OpenSettings",
"ctrl-q": "zed::Quit", "ctrl-q": "zed::Quit",
"f4": "debugger::Start", "f4": "debugger::Start",
"shift-f5": "debugger::Stop", "shift-f5": "debugger::Stop",
@@ -134,7 +134,7 @@
"ctrl-k z": "editor::ToggleSoftWrap", "ctrl-k z": "editor::ToggleSoftWrap",
"ctrl-f": "buffer_search::Deploy", "ctrl-f": "buffer_search::Deploy",
"ctrl-h": "buffer_search::DeployReplace", "ctrl-h": "buffer_search::DeployReplace",
"ctrl-shift-.": "agent::AddSelectionToThread", "ctrl-shift-.": "assistant::QuoteSelection",
"ctrl-shift-,": "assistant::InsertIntoEditor", "ctrl-shift-,": "assistant::InsertIntoEditor",
"shift-alt-e": "editor::SelectEnclosingSymbol", "shift-alt-e": "editor::SelectEnclosingSymbol",
"ctrl-shift-backspace": "editor::GoToPreviousChange", "ctrl-shift-backspace": "editor::GoToPreviousChange",
@@ -244,7 +244,7 @@
"ctrl-shift-i": "agent::ToggleOptionsMenu", "ctrl-shift-i": "agent::ToggleOptionsMenu",
// "ctrl-shift-alt-n": "agent::ToggleNewThreadMenu", // "ctrl-shift-alt-n": "agent::ToggleNewThreadMenu",
"shift-alt-escape": "agent::ExpandMessageEditor", "shift-alt-escape": "agent::ExpandMessageEditor",
"ctrl-shift-.": "agent::AddSelectionToThread", "ctrl-shift-.": "assistant::QuoteSelection",
"shift-alt-e": "agent::RemoveAllContext", "shift-alt-e": "agent::RemoveAllContext",
"ctrl-shift-e": "project_panel::ToggleFocus", "ctrl-shift-e": "project_panel::ToggleFocus",
"ctrl-shift-enter": "agent::ContinueThread", "ctrl-shift-enter": "agent::ContinueThread",
@@ -270,7 +270,7 @@
} }
}, },
{ {
"context": "AgentPanel && text_thread", "context": "AgentPanel && prompt_editor",
"use_key_equivalents": true, "use_key_equivalents": true,
"bindings": { "bindings": {
"ctrl-n": "agent::NewTextThread", "ctrl-n": "agent::NewTextThread",
@@ -278,7 +278,7 @@
} }
}, },
{ {
"context": "AgentPanel && acp_thread", "context": "AgentPanel && external_agent_thread",
"use_key_equivalents": true, "use_key_equivalents": true,
"bindings": { "bindings": {
"ctrl-n": "agent::NewExternalAgentThread", "ctrl-n": "agent::NewExternalAgentThread",
@@ -375,7 +375,7 @@
} }
}, },
{ {
"context": "RulesLibrary", "context": "PromptLibrary",
"use_key_equivalents": true, "use_key_equivalents": true,
"bindings": { "bindings": {
"ctrl-n": "rules_library::NewRule", "ctrl-n": "rules_library::NewRule",
@@ -500,8 +500,8 @@
"bindings": { "bindings": {
"ctrl-[": "editor::Outdent", "ctrl-[": "editor::Outdent",
"ctrl-]": "editor::Indent", "ctrl-]": "editor::Indent",
"ctrl-shift-alt-up": ["editor::AddSelectionAbove", { "skip_soft_wrap": true }], // Insert Cursor Above "ctrl-shift-alt-up": "editor::AddSelectionAbove", // Insert Cursor Above
"ctrl-shift-alt-down": ["editor::AddSelectionBelow", { "skip_soft_wrap": true }], // Insert Cursor Below "ctrl-shift-alt-down": "editor::AddSelectionBelow", // Insert Cursor Below
"ctrl-shift-k": "editor::DeleteLine", "ctrl-shift-k": "editor::DeleteLine",
"alt-up": "editor::MoveLineUp", "alt-up": "editor::MoveLineUp",
"alt-down": "editor::MoveLineDown", "alt-down": "editor::MoveLineDown",
@@ -623,7 +623,7 @@
"ctrl-shift-f": "pane::DeploySearch", "ctrl-shift-f": "pane::DeploySearch",
"ctrl-shift-h": ["pane::DeploySearch", { "replace_enabled": true }], "ctrl-shift-h": ["pane::DeploySearch", { "replace_enabled": true }],
"ctrl-shift-t": "pane::ReopenClosedItem", "ctrl-shift-t": "pane::ReopenClosedItem",
"ctrl-k ctrl-s": "zed::OpenKeymap", "ctrl-k ctrl-s": "zed::OpenKeymapEditor",
"ctrl-k ctrl-t": "theme_selector::Toggle", "ctrl-k ctrl-t": "theme_selector::Toggle",
"ctrl-alt-super-p": "settings_profile_selector::Toggle", "ctrl-alt-super-p": "settings_profile_selector::Toggle",
"ctrl-t": "project_symbols::Toggle", "ctrl-t": "project_symbols::Toggle",
@@ -1106,8 +1106,7 @@
"context": "StashList || (StashList > Picker > Editor)", "context": "StashList || (StashList > Picker > Editor)",
"use_key_equivalents": true, "use_key_equivalents": true,
"bindings": { "bindings": {
"ctrl-shift-backspace": "stash_picker::DropStashItem", "ctrl-shift-backspace": "stash_picker::DropStashItem"
"ctrl-shift-v": "stash_picker::ShowStashItem"
} }
}, },
{ {
@@ -1118,7 +1117,6 @@
"ctrl-insert": "terminal::Copy", "ctrl-insert": "terminal::Copy",
"ctrl-shift-c": "terminal::Copy", "ctrl-shift-c": "terminal::Copy",
"shift-insert": "terminal::Paste", "shift-insert": "terminal::Paste",
"ctrl-v": "terminal::Paste",
"ctrl-shift-v": "terminal::Paste", "ctrl-shift-v": "terminal::Paste",
"ctrl-enter": "assistant::InlineAssist", "ctrl-enter": "assistant::InlineAssist",
"alt-b": ["terminal::SendText", "\u001bb"], "alt-b": ["terminal::SendText", "\u001bb"],
@@ -1155,12 +1153,6 @@
"alt-t": "terminal::RerunTask" "alt-t": "terminal::RerunTask"
} }
}, },
{
"context": "Terminal && selection",
"bindings": {
"ctrl-c": "terminal::Copy"
}
},
{ {
"context": "ZedPredictModal", "context": "ZedPredictModal",
"use_key_equivalents": true, "use_key_equivalents": true,
@@ -1278,7 +1270,6 @@
"escape": "workspace::CloseWindow", "escape": "workspace::CloseWindow",
"ctrl-m": "settings_editor::Minimize", "ctrl-m": "settings_editor::Minimize",
"ctrl-f": "search::FocusSearch", "ctrl-f": "search::FocusSearch",
"left": "settings_editor::ToggleFocusNav",
"ctrl-shift-e": "settings_editor::ToggleFocusNav", "ctrl-shift-e": "settings_editor::ToggleFocusNav",
// todo(settings_ui): cut this down based on the max files and overflow UI // todo(settings_ui): cut this down based on the max files and overflow UI
"ctrl-1": ["settings_editor::FocusFile", 0], "ctrl-1": ["settings_editor::FocusFile", 0],
@@ -1295,23 +1286,10 @@
"ctrl-pagedown": "settings_editor::FocusNextFile" "ctrl-pagedown": "settings_editor::FocusNextFile"
} }
}, },
{
"context": "StashDiff > Editor",
"use_key_equivalents": true,
"bindings": {
"ctrl-space": "git::ApplyCurrentStash",
"ctrl-shift-space": "git::PopCurrentStash",
"ctrl-shift-backspace": "git::DropCurrentStash"
}
},
{ {
"context": "SettingsWindow > NavigationMenu", "context": "SettingsWindow > NavigationMenu",
"use_key_equivalents": true, "use_key_equivalents": true,
"bindings": { "bindings": {
"up": "settings_editor::FocusPreviousNavEntry",
"shift-tab": "settings_editor::FocusPreviousNavEntry",
"down": "settings_editor::FocusNextNavEntry",
"tab": "settings_editor::FocusNextNavEntry",
"right": "settings_editor::ExpandNavEntry", "right": "settings_editor::ExpandNavEntry",
"left": "settings_editor::CollapseNavEntry", "left": "settings_editor::CollapseNavEntry",
"pageup": "settings_editor::FocusPreviousRootNavEntry", "pageup": "settings_editor::FocusPreviousRootNavEntry",
@@ -1319,13 +1297,5 @@
"home": "settings_editor::FocusFirstNavEntry", "home": "settings_editor::FocusFirstNavEntry",
"end": "settings_editor::FocusLastNavEntry" "end": "settings_editor::FocusLastNavEntry"
} }
},
{
"context": "Zeta2Feedback > Editor",
"bindings": {
"enter": "editor::Newline",
"ctrl-enter up": "dev::Zeta2RatePredictionPositive",
"ctrl-enter down": "dev::Zeta2RatePredictionNegative"
}
} }
] ]

View File

@@ -24,8 +24,8 @@
"ctrl-<": "editor::ScrollCursorCenter", // editor:scroll-to-cursor "ctrl-<": "editor::ScrollCursorCenter", // editor:scroll-to-cursor
"f3": ["editor::SelectNext", { "replace_newest": true }], // find-and-replace:find-next "f3": ["editor::SelectNext", { "replace_newest": true }], // find-and-replace:find-next
"shift-f3": ["editor::SelectPrevious", { "replace_newest": true }], //find-and-replace:find-previous "shift-f3": ["editor::SelectPrevious", { "replace_newest": true }], //find-and-replace:find-previous
"alt-shift-down": ["editor::AddSelectionBelow", { "skip_soft_wrap": true }], // editor:add-selection-below "alt-shift-down": "editor::AddSelectionBelow", // editor:add-selection-below
"alt-shift-up": ["editor::AddSelectionAbove", { "skip_soft_wrap": true }], // editor:add-selection-above "alt-shift-up": "editor::AddSelectionAbove", // editor:add-selection-above
"ctrl-j": "editor::JoinLines", // editor:join-lines "ctrl-j": "editor::JoinLines", // editor:join-lines
"ctrl-shift-d": "editor::DuplicateLineDown", // editor:duplicate-lines "ctrl-shift-d": "editor::DuplicateLineDown", // editor:duplicate-lines
"ctrl-up": "editor::MoveLineUp", // editor:move-line-up "ctrl-up": "editor::MoveLineUp", // editor:move-line-up

View File

@@ -17,8 +17,8 @@
"bindings": { "bindings": {
"ctrl-i": "agent::ToggleFocus", "ctrl-i": "agent::ToggleFocus",
"ctrl-shift-i": "agent::ToggleFocus", "ctrl-shift-i": "agent::ToggleFocus",
"ctrl-shift-l": "agent::AddSelectionToThread", // In cursor uses "Ask" mode "ctrl-shift-l": "agent::QuoteSelection", // In cursor uses "Ask" mode
"ctrl-l": "agent::AddSelectionToThread", // In cursor uses "Agent" mode "ctrl-l": "agent::QuoteSelection", // In cursor uses "Agent" mode
"ctrl-k": "assistant::InlineAssist", "ctrl-k": "assistant::InlineAssist",
"ctrl-shift-k": "assistant::InsertIntoEditor" "ctrl-shift-k": "assistant::InsertIntoEditor"
} }

View File

@@ -8,23 +8,11 @@
"ctrl-g": "menu::Cancel" "ctrl-g": "menu::Cancel"
} }
}, },
{
// Workaround to avoid falling back to default bindings.
// Unbind so Zed ignores these keys and lets emacs handle them.
// NOTE: must be declared before the `Editor` override.
// NOTE: in macos the 'ctrl-x' 'ctrl-p' and 'ctrl-n' rebindings are not needed, since they default to 'cmd'.
"context": "Editor",
"bindings": {
"ctrl-g": null, // currently activates `go_to_line::Toggle` when there is nothing to cancel
"ctrl-x": null, // currently activates `editor::Cut` if no following key is pressed for 1 second
"ctrl-p": null, // currently activates `file_finder::Toggle` when the cursor is on the first character of the buffer
"ctrl-n": null // currently activates `workspace::NewFile` when the cursor is on the last character of the buffer
}
},
{ {
"context": "Editor", "context": "Editor",
"bindings": { "bindings": {
"ctrl-g": "editor::Cancel", "ctrl-g": "editor::Cancel",
"ctrl-x b": "tab_switcher::Toggle", // switch-to-buffer
"alt-g g": "go_to_line::Toggle", // goto-line "alt-g g": "go_to_line::Toggle", // goto-line
"alt-g alt-g": "go_to_line::Toggle", // goto-line "alt-g alt-g": "go_to_line::Toggle", // goto-line
"ctrl-space": "editor::SetMark", // set-mark "ctrl-space": "editor::SetMark", // set-mark
@@ -41,10 +29,8 @@
"shift-home": ["editor::SelectToBeginningOfLine", { "stop_at_soft_wraps": false }], // move-beginning-of-line "shift-home": ["editor::SelectToBeginningOfLine", { "stop_at_soft_wraps": false }], // move-beginning-of-line
"shift-end": ["editor::SelectToEndOfLine", { "stop_at_soft_wraps": false }], // move-end-of-line "shift-end": ["editor::SelectToEndOfLine", { "stop_at_soft_wraps": false }], // move-end-of-line
"alt-m": ["editor::MoveToBeginningOfLine", { "stop_at_soft_wraps": false, "stop_at_indent": true }], // back-to-indentation "alt-m": ["editor::MoveToBeginningOfLine", { "stop_at_soft_wraps": false, "stop_at_indent": true }], // back-to-indentation
"alt-left": "editor::MoveToPreviousWordStart", // left-word "alt-f": "editor::MoveToNextSubwordEnd", // forward-word
"alt-right": "editor::MoveToNextWordEnd", // right-word "alt-b": "editor::MoveToPreviousSubwordStart", // backward-word
"alt-f": "editor::MoveToNextWordEnd", // forward-word
"alt-b": "editor::MoveToPreviousWordStart", // backward-word
"alt-u": "editor::ConvertToUpperCase", // upcase-word "alt-u": "editor::ConvertToUpperCase", // upcase-word
"alt-l": "editor::ConvertToLowerCase", // downcase-word "alt-l": "editor::ConvertToLowerCase", // downcase-word
"alt-c": "editor::ConvertToUpperCamelCase", // capitalize-word "alt-c": "editor::ConvertToUpperCamelCase", // capitalize-word
@@ -57,8 +43,6 @@
"ctrl-x h": "editor::SelectAll", // mark-whole-buffer "ctrl-x h": "editor::SelectAll", // mark-whole-buffer
"ctrl-d": "editor::Delete", // delete-char "ctrl-d": "editor::Delete", // delete-char
"alt-d": ["editor::DeleteToNextWordEnd", { "ignore_newlines": false, "ignore_brackets": false }], // kill-word "alt-d": ["editor::DeleteToNextWordEnd", { "ignore_newlines": false, "ignore_brackets": false }], // kill-word
"alt-backspace": "editor::DeleteToPreviousWordStart", // backward-kill-word
"alt-delete": "editor::DeleteToPreviousWordStart", // backward-kill-word
"ctrl-k": "editor::KillRingCut", // kill-line "ctrl-k": "editor::KillRingCut", // kill-line
"ctrl-w": "editor::Cut", // kill-region "ctrl-w": "editor::Cut", // kill-region
"alt-w": "editor::Copy", // kill-ring-save "alt-w": "editor::Copy", // kill-ring-save
@@ -68,19 +52,14 @@
"ctrl-x u": "editor::Undo", // undo "ctrl-x u": "editor::Undo", // undo
"alt-{": "editor::MoveToStartOfParagraph", // backward-paragraph "alt-{": "editor::MoveToStartOfParagraph", // backward-paragraph
"alt-}": "editor::MoveToEndOfParagraph", // forward-paragraph "alt-}": "editor::MoveToEndOfParagraph", // forward-paragraph
"ctrl-up": "editor::MoveToStartOfParagraph", // backward-paragraph
"ctrl-down": "editor::MoveToEndOfParagraph", // forward-paragraph
"ctrl-v": "editor::MovePageDown", // scroll-up "ctrl-v": "editor::MovePageDown", // scroll-up
"alt-v": "editor::MovePageUp", // scroll-down "alt-v": "editor::MovePageUp", // scroll-down
"ctrl-x [": "editor::MoveToBeginning", // beginning-of-buffer "ctrl-x [": "editor::MoveToBeginning", // beginning-of-buffer
"ctrl-x ]": "editor::MoveToEnd", // end-of-buffer "ctrl-x ]": "editor::MoveToEnd", // end-of-buffer
"alt-<": "editor::MoveToBeginning", // beginning-of-buffer "alt-<": "editor::MoveToBeginning", // beginning-of-buffer
"alt->": "editor::MoveToEnd", // end-of-buffer "alt->": "editor::MoveToEnd", // end-of-buffer
"ctrl-home": "editor::MoveToBeginning", // beginning-of-buffer
"ctrl-end": "editor::MoveToEnd", // end-of-buffer
"ctrl-l": "editor::ScrollCursorCenterTopBottom", // recenter-top-bottom "ctrl-l": "editor::ScrollCursorCenterTopBottom", // recenter-top-bottom
"ctrl-s": "buffer_search::Deploy", // isearch-forward "ctrl-s": "buffer_search::Deploy", // isearch-forward
"ctrl-r": "buffer_search::Deploy", // isearch-backward
"alt-^": "editor::JoinLines", // join-line "alt-^": "editor::JoinLines", // join-line
"alt-q": "editor::Rewrap" // fill-paragraph "alt-q": "editor::Rewrap" // fill-paragraph
} }
@@ -106,19 +85,10 @@
"end": ["editor::SelectToEndOfLine", { "stop_at_soft_wraps": false }], "end": ["editor::SelectToEndOfLine", { "stop_at_soft_wraps": false }],
"ctrl-a": ["editor::SelectToBeginningOfLine", { "stop_at_soft_wraps": false }], "ctrl-a": ["editor::SelectToBeginningOfLine", { "stop_at_soft_wraps": false }],
"ctrl-e": ["editor::SelectToEndOfLine", { "stop_at_soft_wraps": false }], "ctrl-e": ["editor::SelectToEndOfLine", { "stop_at_soft_wraps": false }],
"alt-m": ["editor::SelectToBeginningOfLine", { "stop_at_soft_wraps": false, "stop_at_indent": true }],
"alt-f": "editor::SelectToNextWordEnd", "alt-f": "editor::SelectToNextWordEnd",
"alt-b": "editor::SelectToPreviousWordStart", "alt-b": "editor::SelectToPreviousSubwordStart",
"alt-{": "editor::SelectToStartOfParagraph",
"alt-}": "editor::SelectToEndOfParagraph",
"ctrl-up": "editor::SelectToStartOfParagraph",
"ctrl-down": "editor::SelectToEndOfParagraph",
"ctrl-x [": "editor::SelectToBeginning",
"ctrl-x ]": "editor::SelectToEnd",
"alt-<": "editor::SelectToBeginning", "alt-<": "editor::SelectToBeginning",
"alt->": "editor::SelectToEnd", "alt->": "editor::SelectToEnd",
"ctrl-home": "editor::SelectToBeginning",
"ctrl-end": "editor::SelectToEnd",
"ctrl-g": "editor::Cancel" "ctrl-g": "editor::Cancel"
} }
}, },
@@ -136,28 +106,15 @@
"ctrl-n": "editor::SignatureHelpNext" "ctrl-n": "editor::SignatureHelpNext"
} }
}, },
// Example setting for using emacs-style tab
// (i.e. indent the current line / selection or perform symbol completion depending on context)
// {
// "context": "Editor && !showing_code_actions && !showing_completions",
// "bindings": {
// "tab": "editor::AutoIndent" // indent-for-tab-command
// }
// },
{ {
"context": "Workspace", "context": "Workspace",
"bindings": { "bindings": {
"alt-x": "command_palette::Toggle", // execute-extended-command
"ctrl-x b": "tab_switcher::Toggle", // switch-to-buffer
"ctrl-x ctrl-b": "tab_switcher::Toggle", // list-buffers
// "ctrl-x ctrl-c": "workspace::CloseWindow" // in case you only want to exit the current Zed instance
"ctrl-x ctrl-c": "zed::Quit", // save-buffers-kill-terminal "ctrl-x ctrl-c": "zed::Quit", // save-buffers-kill-terminal
"ctrl-x 5 0": "workspace::CloseWindow", // delete-frame "ctrl-x 5 0": "workspace::CloseWindow", // delete-frame
"ctrl-x 5 2": "workspace::NewWindow", // make-frame-command "ctrl-x 5 2": "workspace::NewWindow", // make-frame-command
"ctrl-x o": "workspace::ActivateNextPane", // other-window "ctrl-x o": "workspace::ActivateNextPane", // other-window
"ctrl-x k": "pane::CloseActiveItem", // kill-buffer "ctrl-x k": "pane::CloseActiveItem", // kill-buffer
"ctrl-x 0": "pane::CloseActiveItem", // delete-window "ctrl-x 0": "pane::CloseActiveItem", // delete-window
// "ctrl-x 1": "pane::JoinAll", // in case you prefer to delete the splits but keep the buffers open
"ctrl-x 1": "pane::CloseOtherItems", // delete-other-windows "ctrl-x 1": "pane::CloseOtherItems", // delete-other-windows
"ctrl-x 2": "pane::SplitDown", // split-window-below "ctrl-x 2": "pane::SplitDown", // split-window-below
"ctrl-x 3": "pane::SplitRight", // split-window-right "ctrl-x 3": "pane::SplitRight", // split-window-right
@@ -168,19 +125,10 @@
} }
}, },
{ {
// Workaround to enable using native emacs from the Zed terminal. // Workaround to enable using emacs in the Zed terminal.
// Unbind so Zed ignores these keys and lets emacs handle them. // Unbind so Zed ignores these keys and lets emacs handle them.
// NOTE:
// "terminal::SendKeystroke" only works for a single key stroke (e.g. ctrl-x),
// so override with null for compound sequences (e.g. ctrl-x ctrl-c).
"context": "Terminal", "context": "Terminal",
"bindings": { "bindings": {
// If you want to perfect your emacs-in-zed setup, also consider the following.
// You may need to enable "option_as_meta" from the Zed settings for "alt-x" to work.
// "alt-x": ["terminal::SendKeystroke", "alt-x"],
// "ctrl-x": ["terminal::SendKeystroke", "ctrl-x"],
// "ctrl-n": ["terminal::SendKeystroke", "ctrl-n"],
// ...
"ctrl-x ctrl-c": null, // save-buffers-kill-terminal "ctrl-x ctrl-c": null, // save-buffers-kill-terminal
"ctrl-x ctrl-f": null, // find-file "ctrl-x ctrl-f": null, // find-file
"ctrl-x ctrl-s": null, // save-buffer "ctrl-x ctrl-s": null, // save-buffer

View File

@@ -1,7 +1,7 @@
[ [
{ {
"bindings": { "bindings": {
"ctrl-alt-s": "zed::OpenSettingsFile", "ctrl-alt-s": "zed::OpenSettings",
"ctrl-{": "pane::ActivatePreviousItem", "ctrl-{": "pane::ActivatePreviousItem",
"ctrl-}": "pane::ActivateNextItem", "ctrl-}": "pane::ActivateNextItem",
"shift-escape": null, // Unmap workspace::zoom "shift-escape": null, // Unmap workspace::zoom

View File

@@ -28,8 +28,8 @@
{ {
"context": "Editor", "context": "Editor",
"bindings": { "bindings": {
"ctrl-alt-up": ["editor::AddSelectionAbove", { "skip_soft_wrap": false }], "ctrl-alt-up": "editor::AddSelectionAbove",
"ctrl-alt-down": ["editor::AddSelectionBelow", { "skip_soft_wrap": false }], "ctrl-alt-down": "editor::AddSelectionBelow",
"ctrl-shift-up": "editor::MoveLineUp", "ctrl-shift-up": "editor::MoveLineUp",
"ctrl-shift-down": "editor::MoveLineDown", "ctrl-shift-down": "editor::MoveLineDown",
"ctrl-shift-m": "editor::SelectLargerSyntaxNode", "ctrl-shift-m": "editor::SelectLargerSyntaxNode",

View File

@@ -25,8 +25,8 @@
"cmd-<": "editor::ScrollCursorCenter", "cmd-<": "editor::ScrollCursorCenter",
"cmd-g": ["editor::SelectNext", { "replace_newest": true }], "cmd-g": ["editor::SelectNext", { "replace_newest": true }],
"cmd-shift-g": ["editor::SelectPrevious", { "replace_newest": true }], "cmd-shift-g": ["editor::SelectPrevious", { "replace_newest": true }],
"ctrl-shift-down": ["editor::AddSelectionBelow", { "skip_soft_wrap": true }], "ctrl-shift-down": "editor::AddSelectionBelow",
"ctrl-shift-up": ["editor::AddSelectionAbove", { "skip_soft_wrap": true }], "ctrl-shift-up": "editor::AddSelectionAbove",
"alt-enter": "editor::Newline", "alt-enter": "editor::Newline",
"cmd-shift-d": "editor::DuplicateLineDown", "cmd-shift-d": "editor::DuplicateLineDown",
"ctrl-cmd-up": "editor::MoveLineUp", "ctrl-cmd-up": "editor::MoveLineUp",

View File

@@ -17,8 +17,8 @@
"bindings": { "bindings": {
"cmd-i": "agent::ToggleFocus", "cmd-i": "agent::ToggleFocus",
"cmd-shift-i": "agent::ToggleFocus", "cmd-shift-i": "agent::ToggleFocus",
"cmd-shift-l": "agent::AddSelectionToThread", // In cursor uses "Ask" mode "cmd-shift-l": "agent::QuoteSelection", // In cursor uses "Ask" mode
"cmd-l": "agent::AddSelectionToThread", // In cursor uses "Agent" mode "cmd-l": "agent::QuoteSelection", // In cursor uses "Agent" mode
"cmd-k": "assistant::InlineAssist", "cmd-k": "assistant::InlineAssist",
"cmd-shift-k": "assistant::InsertIntoEditor" "cmd-shift-k": "assistant::InsertIntoEditor"
} }

View File

@@ -9,19 +9,11 @@
"ctrl-g": "menu::Cancel" "ctrl-g": "menu::Cancel"
} }
}, },
{
// Workaround to avoid falling back to default bindings.
// Unbind so Zed ignores these keys and lets emacs handle them.
// NOTE: must be declared before the `Editor` override.
"context": "Editor",
"bindings": {
"ctrl-g": null // currently activates `go_to_line::Toggle` when there is nothing to cancel
}
},
{ {
"context": "Editor", "context": "Editor",
"bindings": { "bindings": {
"ctrl-g": "editor::Cancel", "ctrl-g": "editor::Cancel",
"ctrl-x b": "tab_switcher::Toggle", // switch-to-buffer
"alt-g g": "go_to_line::Toggle", // goto-line "alt-g g": "go_to_line::Toggle", // goto-line
"alt-g alt-g": "go_to_line::Toggle", // goto-line "alt-g alt-g": "go_to_line::Toggle", // goto-line
"ctrl-space": "editor::SetMark", // set-mark "ctrl-space": "editor::SetMark", // set-mark
@@ -38,10 +30,8 @@
"shift-home": ["editor::SelectToBeginningOfLine", { "stop_at_soft_wraps": false }], // move-beginning-of-line "shift-home": ["editor::SelectToBeginningOfLine", { "stop_at_soft_wraps": false }], // move-beginning-of-line
"shift-end": ["editor::SelectToEndOfLine", { "stop_at_soft_wraps": false }], // move-end-of-line "shift-end": ["editor::SelectToEndOfLine", { "stop_at_soft_wraps": false }], // move-end-of-line
"alt-m": ["editor::MoveToBeginningOfLine", { "stop_at_soft_wraps": false, "stop_at_indent": true }], // back-to-indentation "alt-m": ["editor::MoveToBeginningOfLine", { "stop_at_soft_wraps": false, "stop_at_indent": true }], // back-to-indentation
"alt-left": "editor::MoveToPreviousWordStart", // left-word "alt-f": "editor::MoveToNextSubwordEnd", // forward-word
"alt-right": "editor::MoveToNextWordEnd", // right-word "alt-b": "editor::MoveToPreviousSubwordStart", // backward-word
"alt-f": "editor::MoveToNextWordEnd", // forward-word
"alt-b": "editor::MoveToPreviousWordStart", // backward-word
"alt-u": "editor::ConvertToUpperCase", // upcase-word "alt-u": "editor::ConvertToUpperCase", // upcase-word
"alt-l": "editor::ConvertToLowerCase", // downcase-word "alt-l": "editor::ConvertToLowerCase", // downcase-word
"alt-c": "editor::ConvertToUpperCamelCase", // capitalize-word "alt-c": "editor::ConvertToUpperCamelCase", // capitalize-word
@@ -54,8 +44,6 @@
"ctrl-x h": "editor::SelectAll", // mark-whole-buffer "ctrl-x h": "editor::SelectAll", // mark-whole-buffer
"ctrl-d": "editor::Delete", // delete-char "ctrl-d": "editor::Delete", // delete-char
"alt-d": ["editor::DeleteToNextWordEnd", { "ignore_newlines": false, "ignore_brackets": false }], // kill-word "alt-d": ["editor::DeleteToNextWordEnd", { "ignore_newlines": false, "ignore_brackets": false }], // kill-word
"alt-backspace": "editor::DeleteToPreviousWordStart", // backward-kill-word
"alt-delete": "editor::DeleteToPreviousWordStart", // backward-kill-word
"ctrl-k": "editor::KillRingCut", // kill-line "ctrl-k": "editor::KillRingCut", // kill-line
"ctrl-w": "editor::Cut", // kill-region "ctrl-w": "editor::Cut", // kill-region
"alt-w": "editor::Copy", // kill-ring-save "alt-w": "editor::Copy", // kill-ring-save
@@ -65,19 +53,14 @@
"ctrl-x u": "editor::Undo", // undo "ctrl-x u": "editor::Undo", // undo
"alt-{": "editor::MoveToStartOfParagraph", // backward-paragraph "alt-{": "editor::MoveToStartOfParagraph", // backward-paragraph
"alt-}": "editor::MoveToEndOfParagraph", // forward-paragraph "alt-}": "editor::MoveToEndOfParagraph", // forward-paragraph
"ctrl-up": "editor::MoveToStartOfParagraph", // backward-paragraph
"ctrl-down": "editor::MoveToEndOfParagraph", // forward-paragraph
"ctrl-v": "editor::MovePageDown", // scroll-up "ctrl-v": "editor::MovePageDown", // scroll-up
"alt-v": "editor::MovePageUp", // scroll-down "alt-v": "editor::MovePageUp", // scroll-down
"ctrl-x [": "editor::MoveToBeginning", // beginning-of-buffer "ctrl-x [": "editor::MoveToBeginning", // beginning-of-buffer
"ctrl-x ]": "editor::MoveToEnd", // end-of-buffer "ctrl-x ]": "editor::MoveToEnd", // end-of-buffer
"alt-<": "editor::MoveToBeginning", // beginning-of-buffer "alt-<": "editor::MoveToBeginning", // beginning-of-buffer
"alt->": "editor::MoveToEnd", // end-of-buffer "alt->": "editor::MoveToEnd", // end-of-buffer
"ctrl-home": "editor::MoveToBeginning", // beginning-of-buffer
"ctrl-end": "editor::MoveToEnd", // end-of-buffer
"ctrl-l": "editor::ScrollCursorCenterTopBottom", // recenter-top-bottom "ctrl-l": "editor::ScrollCursorCenterTopBottom", // recenter-top-bottom
"ctrl-s": "buffer_search::Deploy", // isearch-forward "ctrl-s": "buffer_search::Deploy", // isearch-forward
"ctrl-r": "buffer_search::Deploy", // isearch-backward
"alt-^": "editor::JoinLines", // join-line "alt-^": "editor::JoinLines", // join-line
"alt-q": "editor::Rewrap" // fill-paragraph "alt-q": "editor::Rewrap" // fill-paragraph
} }
@@ -103,19 +86,10 @@
"end": ["editor::SelectToEndOfLine", { "stop_at_soft_wraps": false }], "end": ["editor::SelectToEndOfLine", { "stop_at_soft_wraps": false }],
"ctrl-a": ["editor::SelectToBeginningOfLine", { "stop_at_soft_wraps": false }], "ctrl-a": ["editor::SelectToBeginningOfLine", { "stop_at_soft_wraps": false }],
"ctrl-e": ["editor::SelectToEndOfLine", { "stop_at_soft_wraps": false }], "ctrl-e": ["editor::SelectToEndOfLine", { "stop_at_soft_wraps": false }],
"alt-m": ["editor::SelectToBeginningOfLine", { "stop_at_soft_wraps": false, "stop_at_indent": true }],
"alt-f": "editor::SelectToNextWordEnd", "alt-f": "editor::SelectToNextWordEnd",
"alt-b": "editor::SelectToPreviousWordStart", "alt-b": "editor::SelectToPreviousSubwordStart",
"alt-{": "editor::SelectToStartOfParagraph",
"alt-}": "editor::SelectToEndOfParagraph",
"ctrl-up": "editor::SelectToStartOfParagraph",
"ctrl-down": "editor::SelectToEndOfParagraph",
"ctrl-x [": "editor::SelectToBeginning",
"ctrl-x ]": "editor::SelectToEnd",
"alt-<": "editor::SelectToBeginning", "alt-<": "editor::SelectToBeginning",
"alt->": "editor::SelectToEnd", "alt->": "editor::SelectToEnd",
"ctrl-home": "editor::SelectToBeginning",
"ctrl-end": "editor::SelectToEnd",
"ctrl-g": "editor::Cancel" "ctrl-g": "editor::Cancel"
} }
}, },
@@ -133,28 +107,15 @@
"ctrl-n": "editor::SignatureHelpNext" "ctrl-n": "editor::SignatureHelpNext"
} }
}, },
// Example setting for using emacs-style tab
// (i.e. indent the current line / selection or perform symbol completion depending on context)
// {
// "context": "Editor && !showing_code_actions && !showing_completions",
// "bindings": {
// "tab": "editor::AutoIndent" // indent-for-tab-command
// }
// },
{ {
"context": "Workspace", "context": "Workspace",
"bindings": { "bindings": {
"alt-x": "command_palette::Toggle", // execute-extended-command
"ctrl-x b": "tab_switcher::Toggle", // switch-to-buffer
"ctrl-x ctrl-b": "tab_switcher::Toggle", // list-buffers
// "ctrl-x ctrl-c": "workspace::CloseWindow" // in case you only want to exit the current Zed instance
"ctrl-x ctrl-c": "zed::Quit", // save-buffers-kill-terminal "ctrl-x ctrl-c": "zed::Quit", // save-buffers-kill-terminal
"ctrl-x 5 0": "workspace::CloseWindow", // delete-frame "ctrl-x 5 0": "workspace::CloseWindow", // delete-frame
"ctrl-x 5 2": "workspace::NewWindow", // make-frame-command "ctrl-x 5 2": "workspace::NewWindow", // make-frame-command
"ctrl-x o": "workspace::ActivateNextPane", // other-window "ctrl-x o": "workspace::ActivateNextPane", // other-window
"ctrl-x k": "pane::CloseActiveItem", // kill-buffer "ctrl-x k": "pane::CloseActiveItem", // kill-buffer
"ctrl-x 0": "pane::CloseActiveItem", // delete-window "ctrl-x 0": "pane::CloseActiveItem", // delete-window
// "ctrl-x 1": "pane::JoinAll", // in case you prefer to delete the splits but keep the buffers open
"ctrl-x 1": "pane::CloseOtherItems", // delete-other-windows "ctrl-x 1": "pane::CloseOtherItems", // delete-other-windows
"ctrl-x 2": "pane::SplitDown", // split-window-below "ctrl-x 2": "pane::SplitDown", // split-window-below
"ctrl-x 3": "pane::SplitRight", // split-window-right "ctrl-x 3": "pane::SplitRight", // split-window-right
@@ -165,19 +126,10 @@
} }
}, },
{ {
// Workaround to enable using native emacs from the Zed terminal. // Workaround to enable using emacs in the Zed terminal.
// Unbind so Zed ignores these keys and lets emacs handle them. // Unbind so Zed ignores these keys and lets emacs handle them.
// NOTE:
// "terminal::SendKeystroke" only works for a single key stroke (e.g. ctrl-x),
// so override with null for compound sequences (e.g. ctrl-x ctrl-c).
"context": "Terminal", "context": "Terminal",
"bindings": { "bindings": {
// If you want to perfect your emacs-in-zed setup, also consider the following.
// You may need to enable "option_as_meta" from the Zed settings for "alt-x" to work.
// "alt-x": ["terminal::SendKeystroke", "alt-x"],
// "ctrl-x": ["terminal::SendKeystroke", "ctrl-x"],
// "ctrl-n": ["terminal::SendKeystroke", "ctrl-n"],
// ...
"ctrl-x ctrl-c": null, // save-buffers-kill-terminal "ctrl-x ctrl-c": null, // save-buffers-kill-terminal
"ctrl-x ctrl-f": null, // find-file "ctrl-x ctrl-f": null, // find-file
"ctrl-x ctrl-s": null, // save-buffer "ctrl-x ctrl-s": null, // save-buffer

View File

@@ -28,8 +28,8 @@
{ {
"context": "Editor", "context": "Editor",
"bindings": { "bindings": {
"ctrl-shift-up": ["editor::AddSelectionAbove", { "skip_soft_wrap": false }], "ctrl-shift-up": "editor::AddSelectionAbove",
"ctrl-shift-down": ["editor::AddSelectionBelow", { "skip_soft_wrap": false }], "ctrl-shift-down": "editor::AddSelectionBelow",
"cmd-ctrl-up": "editor::MoveLineUp", "cmd-ctrl-up": "editor::MoveLineUp",
"cmd-ctrl-down": "editor::MoveLineDown", "cmd-ctrl-down": "editor::MoveLineDown",
"cmd-shift-space": "editor::SelectAll", "cmd-shift-space": "editor::SelectAll",

View File

@@ -95,6 +95,8 @@
"g g": "vim::StartOfDocument", "g g": "vim::StartOfDocument",
"g h": "editor::Hover", "g h": "editor::Hover",
"g B": "editor::BlameHover", "g B": "editor::BlameHover",
"g t": "vim::GoToTab",
"g shift-t": "vim::GoToPreviousTab",
"g d": "editor::GoToDefinition", "g d": "editor::GoToDefinition",
"g shift-d": "editor::GoToDeclaration", "g shift-d": "editor::GoToDeclaration",
"g y": "editor::GoToTypeDefinition", "g y": "editor::GoToTypeDefinition",
@@ -422,66 +424,56 @@
{ {
"context": "(vim_mode == helix_normal || vim_mode == helix_select) && !menu", "context": "(vim_mode == helix_normal || vim_mode == helix_select) && !menu",
"bindings": { "bindings": {
// Movement ";": "vim::HelixCollapseSelection",
"h": "vim::WrappingLeft", ":": "command_palette::Toggle",
"m": "vim::PushHelixMatch",
"s": "vim::HelixSelectRegex",
"]": ["vim::PushHelixNext", { "around": true }],
"[": ["vim::PushHelixPrevious", { "around": true }],
"left": "vim::WrappingLeft", "left": "vim::WrappingLeft",
"l": "vim::WrappingRight",
"right": "vim::WrappingRight", "right": "vim::WrappingRight",
"t": ["vim::PushFindForward", { "before": true, "multiline": true }], "h": "vim::WrappingLeft",
"f": ["vim::PushFindForward", { "before": false, "multiline": true }], "l": "vim::WrappingRight",
"shift-t": ["vim::PushFindBackward", { "after": true, "multiline": true }],
"shift-f": ["vim::PushFindBackward", { "after": false, "multiline": true }],
"alt-.": "vim::RepeatFind",
// Changes
"shift-r": "editor::Paste",
"`": "vim::ConvertToLowerCase",
"alt-`": "vim::ConvertToUpperCase",
"insert": "vim::InsertBefore",
"shift-u": "editor::Redo",
"ctrl-r": "vim::Redo",
"y": "vim::HelixYank", "y": "vim::HelixYank",
"p": "vim::HelixPaste", "p": "vim::HelixPaste",
"shift-p": ["vim::HelixPaste", { "before": true }], "shift-p": ["vim::HelixPaste", { "before": true }],
"alt-;": "vim::OtherEnd",
"ctrl-r": "vim::Redo",
"f": ["vim::PushFindForward", { "before": false, "multiline": true }],
"t": ["vim::PushFindForward", { "before": true, "multiline": true }],
"shift-f": ["vim::PushFindBackward", { "after": false, "multiline": true }],
"shift-t": ["vim::PushFindBackward", { "after": true, "multiline": true }],
">": "vim::Indent", ">": "vim::Indent",
"<": "vim::Outdent", "<": "vim::Outdent",
"=": "vim::AutoIndent", "=": "vim::AutoIndent",
"d": "vim::HelixDelete", "`": "vim::ConvertToLowerCase",
"c": "vim::HelixSubstitute", "alt-`": "vim::ConvertToUpperCase",
"alt-c": "vim::HelixSubstituteNoYank", "g q": "vim::PushRewrap",
"g w": "vim::PushRewrap",
// Selection manipulation "insert": "vim::InsertBefore",
"s": "vim::HelixSelectRegex", "alt-.": "vim::RepeatFind",
"alt-s": ["editor::SplitSelectionIntoLines", { "keep_selections": true }], "alt-s": ["editor::SplitSelectionIntoLines", { "keep_selections": true }],
";": "vim::HelixCollapseSelection",
"alt-;": "vim::OtherEnd",
",": "vim::HelixKeepNewestSelection",
"shift-c": "vim::HelixDuplicateBelow",
"alt-shift-c": "vim::HelixDuplicateAbove",
"%": "editor::SelectAll",
"x": "vim::HelixSelectLine",
"shift-x": "editor::SelectLine",
"ctrl-c": "editor::ToggleComments",
"alt-o": "editor::SelectLargerSyntaxNode",
"alt-i": "editor::SelectSmallerSyntaxNode",
"alt-p": "editor::SelectPreviousSyntaxNode",
"alt-n": "editor::SelectNextSyntaxNode",
// Goto mode // Goto mode
"g e": "vim::EndOfDocument", "g n": "pane::ActivateNextItem",
"g h": "vim::StartOfLine", "g p": "pane::ActivatePreviousItem",
// "tab": "pane::ActivateNextItem",
// "shift-tab": "pane::ActivatePrevItem",
"shift-h": "pane::ActivatePreviousItem",
"shift-l": "pane::ActivateNextItem",
"g l": "vim::EndOfLine", "g l": "vim::EndOfLine",
"g h": "vim::StartOfLine",
"g s": "vim::FirstNonWhitespace", // "g s" default behavior is "space s" "g s": "vim::FirstNonWhitespace", // "g s" default behavior is "space s"
"g e": "vim::EndOfDocument",
"g .": "vim::HelixGotoLastModification", // go to last modification
"g r": "editor::FindAllReferences", // zed specific
"g t": "vim::WindowTop", "g t": "vim::WindowTop",
"g c": "vim::WindowMiddle", "g c": "vim::WindowMiddle",
"g b": "vim::WindowBottom", "g b": "vim::WindowBottom",
"g r": "editor::FindAllReferences", // zed specific
"g n": "pane::ActivateNextItem", "shift-r": "editor::Paste",
"shift-l": "pane::ActivateNextItem", "x": "vim::HelixSelectLine",
"g p": "pane::ActivatePreviousItem", "shift-x": "editor::SelectLine",
"shift-h": "pane::ActivatePreviousItem", "%": "editor::SelectAll",
"g .": "vim::HelixGotoLastModification", // go to last modification
// Window mode // Window mode
"space w h": "workspace::ActivatePaneLeft", "space w h": "workspace::ActivatePaneLeft",
"space w l": "workspace::ActivatePaneRight", "space w l": "workspace::ActivatePaneRight",
@@ -492,7 +484,6 @@
"space w r": "pane::SplitRight", "space w r": "pane::SplitRight",
"space w v": "pane::SplitDown", "space w v": "pane::SplitDown",
"space w d": "pane::SplitDown", "space w d": "pane::SplitDown",
// Space mode // Space mode
"space f": "file_finder::Toggle", "space f": "file_finder::Toggle",
"space k": "editor::Hover", "space k": "editor::Hover",
@@ -503,18 +494,14 @@
"space a": "editor::ToggleCodeActions", "space a": "editor::ToggleCodeActions",
"space h": "editor::SelectAllMatches", "space h": "editor::SelectAllMatches",
"space c": "editor::ToggleComments", "space c": "editor::ToggleComments",
"space p": "editor::Paste",
"space y": "editor::Copy", "space y": "editor::Copy",
"space p": "editor::Paste",
// Other "shift-u": "editor::Redo",
":": "command_palette::Toggle", "ctrl-c": "editor::ToggleComments",
"m": "vim::PushHelixMatch", "d": "vim::HelixDelete",
"]": ["vim::PushHelixNext", { "around": true }], "c": "vim::Substitute",
"[": ["vim::PushHelixPrevious", { "around": true }], "shift-c": "editor::AddSelectionBelow",
"g q": "vim::PushRewrap", "alt-shift-c": "editor::AddSelectionAbove"
"g w": "vim::PushRewrap",
// "tab": "pane::ActivateNextItem",
// "shift-tab": "pane::ActivatePrevItem",
} }
}, },
{ {
@@ -824,7 +811,7 @@
} }
}, },
{ {
"context": "VimControl && !menu || !Editor && !Terminal", "context": "VimControl || !Editor && !Terminal",
"bindings": { "bindings": {
// window related commands (ctrl-w X) // window related commands (ctrl-w X)
"ctrl-w": null, "ctrl-w": null,
@@ -844,10 +831,10 @@
"ctrl-w shift-right": "workspace::SwapPaneRight", "ctrl-w shift-right": "workspace::SwapPaneRight",
"ctrl-w shift-up": "workspace::SwapPaneUp", "ctrl-w shift-up": "workspace::SwapPaneUp",
"ctrl-w shift-down": "workspace::SwapPaneDown", "ctrl-w shift-down": "workspace::SwapPaneDown",
"ctrl-w shift-h": "workspace::MovePaneLeft", "ctrl-w shift-h": "workspace::SwapPaneLeft",
"ctrl-w shift-l": "workspace::MovePaneRight", "ctrl-w shift-l": "workspace::SwapPaneRight",
"ctrl-w shift-k": "workspace::MovePaneUp", "ctrl-w shift-k": "workspace::SwapPaneUp",
"ctrl-w shift-j": "workspace::MovePaneDown", "ctrl-w shift-j": "workspace::SwapPaneDown",
"ctrl-w >": "vim::ResizePaneRight", "ctrl-w >": "vim::ResizePaneRight",
"ctrl-w <": "vim::ResizePaneLeft", "ctrl-w <": "vim::ResizePaneLeft",
"ctrl-w -": "vim::ResizePaneDown", "ctrl-w -": "vim::ResizePaneDown",
@@ -878,9 +865,7 @@
"ctrl-w ctrl-o": "workspace::CloseInactiveTabsAndPanes", "ctrl-w ctrl-o": "workspace::CloseInactiveTabsAndPanes",
"ctrl-w o": "workspace::CloseInactiveTabsAndPanes", "ctrl-w o": "workspace::CloseInactiveTabsAndPanes",
"ctrl-w ctrl-n": "workspace::NewFileSplitHorizontal", "ctrl-w ctrl-n": "workspace::NewFileSplitHorizontal",
"ctrl-w n": "workspace::NewFileSplitHorizontal", "ctrl-w n": "workspace::NewFileSplitHorizontal"
"g t": "vim::GoToTab",
"g shift-t": "vim::GoToPreviousTab"
} }
}, },
{ {
@@ -983,9 +968,7 @@
"bindings": { "bindings": {
"ctrl-h": "editor::Backspace", "ctrl-h": "editor::Backspace",
"ctrl-u": "editor::DeleteToBeginningOfLine", "ctrl-u": "editor::DeleteToBeginningOfLine",
"ctrl-w": "editor::DeleteToPreviousWordStart", "ctrl-w": "editor::DeleteToPreviousWordStart"
"ctrl-p": "menu::SelectPrevious",
"ctrl-n": "menu::SelectNext"
} }
}, },
{ {

View File

@@ -1,8 +1,7 @@
{ {
"$schema": "zed://schemas/settings", /// The displayed name of this project. If not set or empty, the root directory name
/// The displayed name of this project. If not set or null, the root directory name
/// will be displayed. /// will be displayed.
"project_name": null, "project_name": "",
// The name of the Zed theme to use for the UI. // The name of the Zed theme to use for the UI.
// //
// `mode` is one of: // `mode` is one of:
@@ -311,11 +310,11 @@
"use_on_type_format": true, "use_on_type_format": true,
// Whether to automatically add matching closing characters when typing // Whether to automatically add matching closing characters when typing
// opening parenthesis, bracket, brace, single or double quote characters. // opening parenthesis, bracket, brace, single or double quote characters.
// For example, when you type '(', Zed will add a closing ) at the correct position. // For example, when you type (, Zed will add a closing ) at the correct position.
"use_autoclose": true, "use_autoclose": true,
// Whether to automatically surround selected text when typing opening parenthesis, // Whether to automatically surround selected text when typing opening parenthesis,
// bracket, brace, single or double quote characters. // bracket, brace, single or double quote characters.
// For example, when you select text and type '(', Zed will surround the text with (). // For example, when you select text and type (, Zed will surround the text with ().
"use_auto_surround": true, "use_auto_surround": true,
// Whether indentation should be adjusted based on the context whilst typing. // Whether indentation should be adjusted based on the context whilst typing.
"auto_indent": true, "auto_indent": true,
@@ -722,11 +721,7 @@
// Whether to enable drag-and-drop operations in the project panel. // Whether to enable drag-and-drop operations in the project panel.
"drag_and_drop": true, "drag_and_drop": true,
// Whether to hide the root entry when only one folder is open in the window. // Whether to hide the root entry when only one folder is open in the window.
"hide_root": false, "hide_root": false
// Whether to hide the hidden entries in the project panel.
"hide_hidden": false,
// Whether to automatically open files when pasting them in the project panel.
"open_file_on_paste": true
}, },
"outline_panel": { "outline_panel": {
// Whether to show the outline panel button in the status bar // Whether to show the outline panel button in the status bar
@@ -884,6 +879,8 @@
// Note: This setting has no effect on external agents that support permission modes, such as Claude Code. // Note: This setting has no effect on external agents that support permission modes, such as Claude Code.
// You can set `agent_servers.claude.default_mode` to `bypassPermissions` to skip all permission requests. // You can set `agent_servers.claude.default_mode` to `bypassPermissions` to skip all permission requests.
"always_allow_tool_actions": false, "always_allow_tool_actions": false,
// When enabled, the agent will stream edits.
"stream_edits": false,
// When enabled, agent edits will be displayed in single-file editors for review // When enabled, agent edits will be displayed in single-file editors for review
"single_file_review": true, "single_file_review": true,
// When enabled, show voting thumbs for feedback on agent edits. // When enabled, show voting thumbs for feedback on agent edits.
@@ -906,7 +903,6 @@
"now": true, "now": true,
"find_path": true, "find_path": true,
"read_file": true, "read_file": true,
"open": true,
"grep": true, "grep": true,
"terminal": true, "terminal": true,
"thinking": true, "thinking": true,
@@ -918,6 +914,7 @@
// We don't know which of the context server tools are safe for the "Ask" profile, so we don't enable them by default. // We don't know which of the context server tools are safe for the "Ask" profile, so we don't enable them by default.
// "enable_all_context_servers": true, // "enable_all_context_servers": true,
"tools": { "tools": {
"contents": true,
"diagnostics": true, "diagnostics": true,
"fetch": true, "fetch": true,
"list_directory": true, "list_directory": true,
@@ -1091,10 +1088,10 @@
// Only the file Zed had indexed will be used, not necessary all the gitignored files. // Only the file Zed had indexed will be used, not necessary all the gitignored files.
// //
// Can accept 3 values: // Can accept 3 values:
// * "all": Use all gitignored files // * `true`: Use all gitignored files
// * "indexed": Use only the files Zed had indexed // * `false`: Use only the files Zed had indexed
// * "smart": Be smart and search for ignored when called from a gitignored worktree // * `null`: Be smart and search for ignored when called from a gitignored worktree
"include_ignored": "smart" "include_ignored": null
}, },
// Whether or not to remove any trailing whitespace from lines of a buffer // Whether or not to remove any trailing whitespace from lines of a buffer
// before saving it. // before saving it.
@@ -1104,31 +1101,25 @@
// Removes any lines containing only whitespace at the end of the file and // Removes any lines containing only whitespace at the end of the file and
// ensures just one newline at the end. // ensures just one newline at the end.
"ensure_final_newline_on_save": true, "ensure_final_newline_on_save": true,
// Whether or not to perform a buffer format before saving: [on, off] // Whether or not to perform a buffer format before saving: [on, off, prettier, language_server]
// Keep in mind, if the autosave with delay is enabled, format_on_save will be ignored // Keep in mind, if the autosave with delay is enabled, format_on_save will be ignored
"format_on_save": "on", "format_on_save": "on",
// How to perform a buffer format. This setting can take multiple values: // How to perform a buffer format. This setting can take 4 values:
// //
// 1. Default. Format files using Zed's Prettier integration (if applicable), // 1. Format code using the current language server:
// or falling back to formatting via language server:
// "formatter": "auto"
// 2. Format code using the current language server:
// "formatter": "language_server" // "formatter": "language_server"
// 3. Format code using a specific language server: // 2. Format code using an external command:
// "formatter": {"language_server": {"name": "ruff"}}
// 4. Format code using an external command:
// "formatter": { // "formatter": {
// "external": { // "external": {
// "command": "prettier", // "command": "prettier",
// "arguments": ["--stdin-filepath", "{buffer_path}"] // "arguments": ["--stdin-filepath", "{buffer_path}"]
// } // }
// } // }
// 5. Format code using Zed's Prettier integration: // 3. Format code using Zed's Prettier integration:
// "formatter": "prettier" // "formatter": "prettier"
// 6. Format code using a code action // 4. Default. Format files using Zed's Prettier integration (if applicable),
// "formatter": {"code_action": "source.fixAll.eslint"} // or falling back to formatting via language server:
// 7. An array of any format step specified above to apply in order // "formatter": "auto"
// "formatter": [{"code_action": "source.fixAll.eslint"}, "prettier"]
"formatter": "auto", "formatter": "auto",
// How to soft-wrap long lines of text. // How to soft-wrap long lines of text.
// Possible values: // Possible values:
@@ -1350,9 +1341,7 @@
// Whether to show the active language button in the status bar. // Whether to show the active language button in the status bar.
"active_language_button": true, "active_language_button": true,
// Whether to show the cursor position button in the status bar. // Whether to show the cursor position button in the status bar.
"cursor_position_button": true, "cursor_position_button": true
// Whether to show active line endings button in the status bar.
"line_endings_button": false
}, },
// Settings specific to the terminal // Settings specific to the terminal
"terminal": { "terminal": {
@@ -1559,7 +1548,6 @@
// //
"file_types": { "file_types": {
"JSONC": ["**/.zed/**/*.json", "**/zed/**/*.json", "**/Zed/**/*.json", "**/.vscode/**/*.json", "tsconfig*.json"], "JSONC": ["**/.zed/**/*.json", "**/zed/**/*.json", "**/Zed/**/*.json", "**/.vscode/**/*.json", "tsconfig*.json"],
"Markdown": [".rules", ".cursorrules", ".windsurfrules", ".clinerules"],
"Shell Script": [".env.*"] "Shell Script": [".env.*"]
}, },
// Settings for which version of Node.js and NPM to use when installing // Settings for which version of Node.js and NPM to use when installing
@@ -1741,7 +1729,7 @@
} }
}, },
"Kotlin": { "Kotlin": {
"language_servers": ["!kotlin-language-server", "kotlin-lsp", "..."] "language_servers": ["kotlin-language-server", "!kotlin-lsp", "..."]
}, },
"LaTeX": { "LaTeX": {
"formatter": "language_server", "formatter": "language_server",
@@ -1777,8 +1765,7 @@
"name": "ruff" "name": "ruff"
} }
}, },
"debuggers": ["Debugpy"], "debuggers": ["Debugpy"]
"language_servers": ["basedpyright", "ruff", "!ty", "!pyrefly", "!pyright", "!pylsp", "..."]
}, },
"Ruby": { "Ruby": {
"language_servers": ["solargraph", "!ruby-lsp", "!rubocop", "!sorbet", "!steep", "..."] "language_servers": ["solargraph", "!ruby-lsp", "!rubocop", "!sorbet", "!steep", "..."]
@@ -1820,11 +1807,10 @@
}, },
"SystemVerilog": { "SystemVerilog": {
"format_on_save": "off", "format_on_save": "off",
"language_servers": ["!slang", "..."],
"use_on_type_format": false "use_on_type_format": false
}, },
"Vue.js": { "Vue.js": {
"language_servers": ["vue-language-server", "vtsls", "..."], "language_servers": ["vue-language-server", "..."],
"prettier": { "prettier": {
"allowed": true "allowed": true
} }
@@ -1928,11 +1914,6 @@
// DAP Specific settings. // DAP Specific settings.
"dap": { "dap": {
// Specify the DAP name as a key here. // Specify the DAP name as a key here.
"CodeLLDB": {
"env": {
"RUST_LOG": "info"
}
}
}, },
// Common language server settings. // Common language server settings.
"global_lsp_settings": { "global_lsp_settings": {
@@ -2073,7 +2054,7 @@
// } // }
// } // }
// } // }
"profiles": {}, "profiles": [],
// A map of log scopes to the desired log level. // A map of log scopes to the desired log level.
// Useful for filtering out noisy logs or enabling more verbose logging. // Useful for filtering out noisy logs or enabling more verbose logging.

View File

@@ -49,9 +49,8 @@
"panel.background": "#3a3735ff", "panel.background": "#3a3735ff",
"panel.focused_border": "#83a598ff", "panel.focused_border": "#83a598ff",
"pane.focused_border": null, "pane.focused_border": null,
"scrollbar.thumb.active_background": "#83a598ac", "scrollbar.thumb.background": "#fbf1c74c",
"scrollbar.thumb.hover_background": "#fbf1c74c", "scrollbar.thumb.hover_background": "#494340ff",
"scrollbar.thumb.background": "#a899844c",
"scrollbar.thumb.border": "#494340ff", "scrollbar.thumb.border": "#494340ff",
"scrollbar.track.background": "#00000000", "scrollbar.track.background": "#00000000",
"scrollbar.track.border": "#373432ff", "scrollbar.track.border": "#373432ff",
@@ -455,9 +454,8 @@
"panel.background": "#393634ff", "panel.background": "#393634ff",
"panel.focused_border": "#83a598ff", "panel.focused_border": "#83a598ff",
"pane.focused_border": null, "pane.focused_border": null,
"scrollbar.thumb.active_background": "#83a598ac", "scrollbar.thumb.background": "#fbf1c74c",
"scrollbar.thumb.hover_background": "#fbf1c74c", "scrollbar.thumb.hover_background": "#494340ff",
"scrollbar.thumb.background": "#a899844c",
"scrollbar.thumb.border": "#494340ff", "scrollbar.thumb.border": "#494340ff",
"scrollbar.track.background": "#00000000", "scrollbar.track.background": "#00000000",
"scrollbar.track.border": "#343130ff", "scrollbar.track.border": "#343130ff",
@@ -861,9 +859,8 @@
"panel.background": "#3b3735ff", "panel.background": "#3b3735ff",
"panel.focused_border": null, "panel.focused_border": null,
"pane.focused_border": null, "pane.focused_border": null,
"scrollbar.thumb.active_background": "#83a598ac", "scrollbar.thumb.background": "#fbf1c74c",
"scrollbar.thumb.hover_background": "#fbf1c74c", "scrollbar.thumb.hover_background": "#494340ff",
"scrollbar.thumb.background": "#a899844c",
"scrollbar.thumb.border": "#494340ff", "scrollbar.thumb.border": "#494340ff",
"scrollbar.track.background": "#00000000", "scrollbar.track.background": "#00000000",
"scrollbar.track.border": "#393634ff", "scrollbar.track.border": "#393634ff",
@@ -1267,9 +1264,8 @@
"panel.background": "#ecddb4ff", "panel.background": "#ecddb4ff",
"panel.focused_border": null, "panel.focused_border": null,
"pane.focused_border": null, "pane.focused_border": null,
"scrollbar.thumb.active_background": "#458588ac", "scrollbar.thumb.background": "#2828284c",
"scrollbar.thumb.hover_background": "#2828284c", "scrollbar.thumb.hover_background": "#ddcca7ff",
"scrollbar.thumb.background": "#7c6f644c",
"scrollbar.thumb.border": "#ddcca7ff", "scrollbar.thumb.border": "#ddcca7ff",
"scrollbar.track.background": "#00000000", "scrollbar.track.background": "#00000000",
"scrollbar.track.border": "#eee0b7ff", "scrollbar.track.border": "#eee0b7ff",
@@ -1673,9 +1669,8 @@
"panel.background": "#ecddb5ff", "panel.background": "#ecddb5ff",
"panel.focused_border": null, "panel.focused_border": null,
"pane.focused_border": null, "pane.focused_border": null,
"scrollbar.thumb.active_background": "#458588ac", "scrollbar.thumb.background": "#2828284c",
"scrollbar.thumb.hover_background": "#2828284c", "scrollbar.thumb.hover_background": "#ddcca7ff",
"scrollbar.thumb.background": "#7c6f644c",
"scrollbar.thumb.border": "#ddcca7ff", "scrollbar.thumb.border": "#ddcca7ff",
"scrollbar.track.background": "#00000000", "scrollbar.track.background": "#00000000",
"scrollbar.track.border": "#eee1bbff", "scrollbar.track.border": "#eee1bbff",
@@ -2079,9 +2074,8 @@
"panel.background": "#ecdcb3ff", "panel.background": "#ecdcb3ff",
"panel.focused_border": null, "panel.focused_border": null,
"pane.focused_border": null, "pane.focused_border": null,
"scrollbar.thumb.active_background": "#458588ac", "scrollbar.thumb.background": "#2828284c",
"scrollbar.thumb.hover_background": "#2828284c", "scrollbar.thumb.hover_background": "#ddcca7ff",
"scrollbar.thumb.background": "#7c6f644c",
"scrollbar.thumb.border": "#ddcca7ff", "scrollbar.thumb.border": "#ddcca7ff",
"scrollbar.track.background": "#00000000", "scrollbar.track.background": "#00000000",
"scrollbar.track.border": "#eddeb5ff", "scrollbar.track.border": "#eddeb5ff",

View File

@@ -3,14 +3,12 @@ avoid-breaking-exported-api = false
ignore-interior-mutability = [ ignore-interior-mutability = [
# Suppresses clippy::mutable_key_type, which is a false positive as the Eq # Suppresses clippy::mutable_key_type, which is a false positive as the Eq
# and Hash impls do not use fields with interior mutability. # and Hash impls do not use fields with interior mutability.
"agent_ui::context::AgentContextKey" "agent::context::AgentContextKey"
] ]
disallowed-methods = [ disallowed-methods = [
{ path = "std::process::Command::spawn", reason = "Spawning `std::process::Command` can block the current thread for an unknown duration", replacement = "smol::process::Command::spawn" }, { path = "std::process::Command::spawn", reason = "Spawning `std::process::Command` can block the current thread for an unknown duration", replacement = "smol::process::Command::spawn" },
{ path = "std::process::Command::output", reason = "Spawning `std::process::Command` can block the current thread for an unknown duration", replacement = "smol::process::Command::output" }, { path = "std::process::Command::output", reason = "Spawning `std::process::Command` can block the current thread for an unknown duration", replacement = "smol::process::Command::output" },
{ path = "std::process::Command::status", reason = "Spawning `std::process::Command` can block the current thread for an unknown duration", replacement = "smol::process::Command::status" }, { path = "std::process::Command::status", reason = "Spawning `std::process::Command` can block the current thread for an unknown duration", replacement = "smol::process::Command::status" },
{ path = "serde_json::from_reader", reason = "Parsing from a buffer is much slower than first reading the buffer into a Vec/String, see https://github.com/serde-rs/json/issues/160#issuecomment-253446892. Use `serde_json::from_slice` instead." },
{ path = "serde_json_lenient::from_reader", reason = "Parsing from a buffer is much slower than first reading the buffer into a Vec/String, see https://github.com/serde-rs/json/issues/160#issuecomment-253446892, Use `serde_json_lenient::from_slice` instead." },
] ]
disallowed-types = [ disallowed-types = [
# { path = "std::collections::HashMap", replacement = "collections::HashMap" }, # { path = "std::collections::HashMap", replacement = "collections::HashMap" },

View File

@@ -45,6 +45,7 @@ url.workspace = true
util.workspace = true util.workspace = true
uuid.workspace = true uuid.workspace = true
watch.workspace = true watch.workspace = true
workspace-hack.workspace = true
[dev-dependencies] [dev-dependencies]
env_logger.workspace = true env_logger.workspace = true

View File

@@ -328,7 +328,7 @@ impl ToolCall {
location: acp::ToolCallLocation, location: acp::ToolCallLocation,
project: WeakEntity<Project>, project: WeakEntity<Project>,
cx: &mut AsyncApp, cx: &mut AsyncApp,
) -> Option<ResolvedLocation> { ) -> Option<AgentLocation> {
let buffer = project let buffer = project
.update(cx, |project, cx| { .update(cx, |project, cx| {
project project
@@ -350,14 +350,17 @@ impl ToolCall {
}) })
.ok()?; .ok()?;
Some(ResolvedLocation { buffer, position }) Some(AgentLocation {
buffer: buffer.downgrade(),
position,
})
} }
fn resolve_locations( fn resolve_locations(
&self, &self,
project: Entity<Project>, project: Entity<Project>,
cx: &mut App, cx: &mut App,
) -> Task<Vec<Option<ResolvedLocation>>> { ) -> Task<Vec<Option<AgentLocation>>> {
let locations = self.locations.clone(); let locations = self.locations.clone();
project.update(cx, |_, cx| { project.update(cx, |_, cx| {
cx.spawn(async move |project, cx| { cx.spawn(async move |project, cx| {
@@ -371,23 +374,6 @@ impl ToolCall {
} }
} }
// Separate so we can hold a strong reference to the buffer
// for saving on the thread
#[derive(Clone, Debug, PartialEq, Eq)]
struct ResolvedLocation {
buffer: Entity<Buffer>,
position: Anchor,
}
impl From<&ResolvedLocation> for AgentLocation {
fn from(value: &ResolvedLocation) -> Self {
Self {
buffer: value.buffer.downgrade(),
position: value.position,
}
}
}
#[derive(Debug)] #[derive(Debug)]
pub enum ToolCallStatus { pub enum ToolCallStatus {
/// The tool call hasn't started running yet, but we start showing it to /// The tool call hasn't started running yet, but we start showing it to
@@ -1407,46 +1393,35 @@ impl AcpThread {
let task = tool_call.resolve_locations(project, cx); let task = tool_call.resolve_locations(project, cx);
cx.spawn(async move |this, cx| { cx.spawn(async move |this, cx| {
let resolved_locations = task.await; let resolved_locations = task.await;
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
let project = this.project.clone(); let project = this.project.clone();
for location in resolved_locations.iter().flatten() {
this.shared_buffers
.insert(location.buffer.clone(), location.buffer.read(cx).snapshot());
}
let Some((ix, tool_call)) = this.tool_call_mut(&id) else { let Some((ix, tool_call)) = this.tool_call_mut(&id) else {
return; return;
}; };
if let Some(Some(location)) = resolved_locations.last() { if let Some(Some(location)) = resolved_locations.last() {
project.update(cx, |project, cx| { project.update(cx, |project, cx| {
let should_ignore = if let Some(agent_location) = project if let Some(agent_location) = project.agent_location() {
.agent_location() let should_ignore = agent_location.buffer == location.buffer
.filter(|agent_location| agent_location.buffer == location.buffer) && location
{ .buffer
let snapshot = location.buffer.read(cx).snapshot(); .update(cx, |buffer, _| {
let old_position = agent_location.position.to_point(&snapshot); let snapshot = buffer.snapshot();
let new_position = location.position.to_point(&snapshot); let old_position =
agent_location.position.to_point(&snapshot);
// ignore this so that when we get updates from the edit tool let new_position = location.position.to_point(&snapshot);
// the position doesn't reset to the startof line // ignore this so that when we get updates from the edit tool
old_position.row == new_position.row // the position doesn't reset to the startof line
&& old_position.column > new_position.column old_position.row == new_position.row
} else { && old_position.column > new_position.column
false })
}; .ok()
if !should_ignore { .unwrap_or_default();
project.set_agent_location(Some(location.into()), cx); if !should_ignore {
project.set_agent_location(Some(location.clone()), cx);
}
} }
}); });
} }
let resolved_locations = resolved_locations
.iter()
.map(|l| l.as_ref().map(|l| AgentLocation::from(l)))
.collect::<Vec<_>>();
if tool_call.resolved_locations != resolved_locations { if tool_call.resolved_locations != resolved_locations {
tool_call.resolved_locations = resolved_locations; tool_call.resolved_locations = resolved_locations;
cx.emit(AcpThreadEvent::EntryUpdated(ix)); cx.emit(AcpThreadEvent::EntryUpdated(ix));
@@ -2137,7 +2112,6 @@ impl AcpThread {
let project = self.project.clone(); let project = self.project.clone();
let language_registry = project.read(cx).languages().clone(); let language_registry = project.read(cx).languages().clone();
let is_windows = project.read(cx).path_style(cx).is_windows();
let terminal_id = acp::TerminalId(Uuid::new_v4().to_string().into()); let terminal_id = acp::TerminalId(Uuid::new_v4().to_string().into());
let terminal_task = cx.spawn({ let terminal_task = cx.spawn({
@@ -2151,10 +2125,9 @@ impl AcpThread {
.and_then(|r| r.read(cx).default_system_shell()) .and_then(|r| r.read(cx).default_system_shell())
})? })?
.unwrap_or_else(|| get_default_system_shell_preferring_bash()); .unwrap_or_else(|| get_default_system_shell_preferring_bash());
let (task_command, task_args) = let (task_command, task_args) = ShellBuilder::new(&Shell::Program(shell))
ShellBuilder::new(&Shell::Program(shell), is_windows) .redirect_stdin_to_dev_null()
.redirect_stdin_to_dev_null() .build(Some(command.clone()), &args);
.build(Some(command.clone()), &args);
let terminal = project let terminal = project
.update(cx, |project, cx| { .update(cx, |project, cx| {
project.create_terminal_task( project.create_terminal_task(

View File

@@ -236,21 +236,21 @@ impl PendingDiff {
fn finalize(&self, cx: &mut Context<Diff>) -> FinalizedDiff { fn finalize(&self, cx: &mut Context<Diff>) -> FinalizedDiff {
let ranges = self.excerpt_ranges(cx); let ranges = self.excerpt_ranges(cx);
let base_text = self.base_text.clone(); let base_text = self.base_text.clone();
let new_buffer = self.new_buffer.read(cx); let language_registry = self.new_buffer.read(cx).language_registry();
let language_registry = new_buffer.language_registry();
let path = new_buffer let path = self
.new_buffer
.read(cx)
.file() .file()
.map(|file| file.path().display(file.path_style(cx))) .map(|file| file.path().display(file.path_style(cx)))
.unwrap_or("untitled".into()) .unwrap_or("untitled".into())
.into(); .into();
let replica_id = new_buffer.replica_id();
// Replace the buffer in the multibuffer with the snapshot // Replace the buffer in the multibuffer with the snapshot
let buffer = cx.new(|cx| { let buffer = cx.new(|cx| {
let language = self.new_buffer.read(cx).language().cloned(); let language = self.new_buffer.read(cx).language().cloned();
let buffer = TextBuffer::new_normalized( let buffer = TextBuffer::new_normalized(
replica_id, 0,
cx.entity_id().as_non_zero_u64().into(), cx.entity_id().as_non_zero_u64().into(),
self.new_buffer.read(cx).line_ending(), self.new_buffer.read(cx).line_ending(),
self.new_buffer.read(cx).as_rope().clone(), self.new_buffer.read(cx).as_rope().clone(),

View File

@@ -1,15 +1,10 @@
use agent_client_protocol as acp; use agent_client_protocol as acp;
use anyhow::Result;
use futures::{FutureExt as _, future::Shared}; use futures::{FutureExt as _, future::Shared};
use gpui::{App, AppContext, AsyncApp, Context, Entity, Task}; use gpui::{App, AppContext, Context, Entity, Task};
use language::LanguageRegistry; use language::LanguageRegistry;
use markdown::Markdown; use markdown::Markdown;
use project::Project;
use settings::{Settings as _, SettingsLocation};
use std::{path::PathBuf, process::ExitStatus, sync::Arc, time::Instant}; use std::{path::PathBuf, process::ExitStatus, sync::Arc, time::Instant};
use task::Shell;
use terminal::terminal_settings::TerminalSettings;
use util::get_default_system_shell_preferring_bash;
pub struct Terminal { pub struct Terminal {
id: acp::TerminalId, id: acp::TerminalId,
@@ -175,68 +170,3 @@ impl Terminal {
) )
} }
} }
pub async fn create_terminal_entity(
command: String,
args: &[String],
env_vars: Vec<(String, String)>,
cwd: Option<PathBuf>,
project: &Entity<Project>,
cx: &mut AsyncApp,
) -> Result<Entity<terminal::Terminal>> {
let mut env = if let Some(dir) = &cwd {
project
.update(cx, |project, cx| {
let worktree = project.find_worktree(dir.as_path(), cx);
let shell = TerminalSettings::get(
worktree.as_ref().map(|(worktree, path)| SettingsLocation {
worktree_id: worktree.read(cx).id(),
path: &path,
}),
cx,
)
.shell
.clone();
project.directory_environment(&shell, dir.clone().into(), cx)
})?
.await
.unwrap_or_default()
} else {
Default::default()
};
// Disables paging for `git` and hopefully other commands
env.insert("PAGER".into(), "".into());
env.extend(env_vars);
// Use remote shell or default system shell, as appropriate
let shell = project
.update(cx, |project, cx| {
project
.remote_client()
.and_then(|r| r.read(cx).default_system_shell())
.map(Shell::Program)
})?
.unwrap_or_else(|| Shell::Program(get_default_system_shell_preferring_bash()));
let is_windows = project
.read_with(cx, |project, cx| project.path_style(cx).is_windows())
.unwrap_or(cfg!(windows));
let (task_command, task_args) = task::ShellBuilder::new(&shell, is_windows)
.redirect_stdin_to_dev_null()
.build(Some(command.clone()), &args);
project
.update(cx, |project, cx| {
project.create_terminal_task(
task::SpawnInTerminal {
command: Some(task_command),
args: task_args,
cwd,
env,
..Default::default()
},
cx,
)
})?
.await
}

View File

@@ -26,4 +26,5 @@ settings.workspace = true
theme.workspace = true theme.workspace = true
ui.workspace = true ui.workspace = true
util.workspace = true util.workspace = true
workspace-hack.workspace = true
workspace.workspace = true workspace.workspace = true

View File

@@ -4,26 +4,22 @@ use std::{
fmt::Display, fmt::Display,
rc::{Rc, Weak}, rc::{Rc, Weak},
sync::Arc, sync::Arc,
time::Duration,
}; };
use agent_client_protocol as acp; use agent_client_protocol as acp;
use collections::HashMap; use collections::HashMap;
use gpui::{ use gpui::{
App, ClipboardItem, Empty, Entity, EventEmitter, FocusHandle, Focusable, Global, ListAlignment, App, Empty, Entity, EventEmitter, FocusHandle, Focusable, Global, ListAlignment, ListState,
ListState, StyleRefinement, Subscription, Task, TextStyleRefinement, Window, actions, list, StyleRefinement, Subscription, Task, TextStyleRefinement, Window, actions, list, prelude::*,
prelude::*,
}; };
use language::LanguageRegistry; use language::LanguageRegistry;
use markdown::{CodeBlockRenderer, Markdown, MarkdownElement, MarkdownStyle}; use markdown::{CodeBlockRenderer, Markdown, MarkdownElement, MarkdownStyle};
use project::Project; use project::Project;
use settings::Settings; use settings::Settings;
use theme::ThemeSettings; use theme::ThemeSettings;
use ui::{Tooltip, prelude::*}; use ui::prelude::*;
use util::ResultExt as _; use util::ResultExt as _;
use workspace::{ use workspace::{Item, Workspace};
Item, ItemHandle, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace,
};
actions!(dev, [OpenAcpLogs]); actions!(dev, [OpenAcpLogs]);
@@ -93,8 +89,8 @@ struct WatchedConnection {
messages: Vec<WatchedConnectionMessage>, messages: Vec<WatchedConnectionMessage>,
list_state: ListState, list_state: ListState,
connection: Weak<acp::ClientSideConnection>, connection: Weak<acp::ClientSideConnection>,
incoming_request_methods: HashMap<acp::RequestId, Arc<str>>, incoming_request_methods: HashMap<i32, Arc<str>>,
outgoing_request_methods: HashMap<acp::RequestId, Arc<str>>, outgoing_request_methods: HashMap<i32, Arc<str>>,
_task: Task<()>, _task: Task<()>,
} }
@@ -175,7 +171,7 @@ impl AcpTools {
} }
}; };
method_map.insert(id.clone(), method.clone()); method_map.insert(id, method.clone());
(Some(id), method.into(), MessageType::Request, Ok(params)) (Some(id), method.into(), MessageType::Request, Ok(params))
} }
acp::StreamMessageContent::Response { id, result } => { acp::StreamMessageContent::Response { id, result } => {
@@ -231,34 +227,6 @@ impl AcpTools {
cx.notify(); cx.notify();
} }
fn serialize_observed_messages(&self) -> Option<String> {
let connection = self.watched_connection.as_ref()?;
let messages: Vec<serde_json::Value> = connection
.messages
.iter()
.filter_map(|message| {
let params = match &message.params {
Ok(Some(params)) => params.clone(),
Ok(None) => serde_json::Value::Null,
Err(err) => serde_json::to_value(err).ok()?,
};
Some(serde_json::json!({
"_direction": match message.direction {
acp::StreamMessageDirection::Incoming => "incoming",
acp::StreamMessageDirection::Outgoing => "outgoing",
},
"_type": message.message_type.to_string().to_lowercase(),
"id": message.request_id,
"method": message.name.to_string(),
"params": params,
}))
})
.collect();
serde_json::to_string_pretty(&messages).ok()
}
fn render_message( fn render_message(
&mut self, &mut self,
index: usize, index: usize,
@@ -338,7 +306,6 @@ impl AcpTools {
.children( .children(
message message
.request_id .request_id
.as_ref()
.map(|req_id| div().child(ui::Chip::new(req_id.to_string()))), .map(|req_id| div().child(ui::Chip::new(req_id.to_string()))),
), ),
) )
@@ -390,7 +357,7 @@ impl AcpTools {
struct WatchedConnectionMessage { struct WatchedConnectionMessage {
name: SharedString, name: SharedString,
request_id: Option<acp::RequestId>, request_id: Option<i32>,
direction: acp::StreamMessageDirection, direction: acp::StreamMessageDirection,
message_type: MessageType, message_type: MessageType,
params: Result<Option<serde_json::Value>, acp::Error>, params: Result<Option<serde_json::Value>, acp::Error>,
@@ -525,92 +492,3 @@ impl Render for AcpTools {
}) })
} }
} }
pub struct AcpToolsToolbarItemView {
acp_tools: Option<Entity<AcpTools>>,
just_copied: bool,
}
impl AcpToolsToolbarItemView {
pub fn new() -> Self {
Self {
acp_tools: None,
just_copied: false,
}
}
}
impl Render for AcpToolsToolbarItemView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let Some(acp_tools) = self.acp_tools.as_ref() else {
return Empty.into_any_element();
};
let acp_tools = acp_tools.clone();
h_flex()
.gap_2()
.child(
IconButton::new(
"copy_all_messages",
if self.just_copied {
IconName::Check
} else {
IconName::Copy
},
)
.icon_size(IconSize::Small)
.tooltip(Tooltip::text(if self.just_copied {
"Copied!"
} else {
"Copy All Messages"
}))
.disabled(
acp_tools
.read(cx)
.watched_connection
.as_ref()
.is_none_or(|connection| connection.messages.is_empty()),
)
.on_click(cx.listener(move |this, _, _window, cx| {
if let Some(content) = acp_tools.read(cx).serialize_observed_messages() {
cx.write_to_clipboard(ClipboardItem::new_string(content));
this.just_copied = true;
cx.spawn(async move |this, cx| {
cx.background_executor().timer(Duration::from_secs(2)).await;
this.update(cx, |this, cx| {
this.just_copied = false;
cx.notify();
})
})
.detach();
}
})),
)
.into_any()
}
}
impl EventEmitter<ToolbarItemEvent> for AcpToolsToolbarItemView {}
impl ToolbarItemView for AcpToolsToolbarItemView {
fn set_active_pane_item(
&mut self,
active_pane_item: Option<&dyn ItemHandle>,
_window: &mut Window,
cx: &mut Context<Self>,
) -> ToolbarItemLocation {
if let Some(item) = active_pane_item
&& let Some(acp_tools) = item.downcast::<AcpTools>()
{
self.acp_tools = Some(acp_tools);
cx.notify();
return ToolbarItemLocation::PrimaryRight;
}
if self.acp_tools.take().is_some() {
cx.notify();
}
ToolbarItemLocation::Hidden
}
}

View File

@@ -23,6 +23,7 @@ project.workspace = true
text.workspace = true text.workspace = true
util.workspace = true util.workspace = true
watch.workspace = true watch.workspace = true
workspace-hack.workspace = true
[dev-dependencies] [dev-dependencies]

View File

@@ -25,6 +25,7 @@ proto.workspace = true
smallvec.workspace = true smallvec.workspace = true
ui.workspace = true ui.workspace = true
util.workspace = true util.workspace = true
workspace-hack.workspace = true
workspace.workspace = true workspace.workspace = true
[dev-dependencies] [dev-dependencies]

View File

@@ -11,7 +11,8 @@ use language::{
LanguageServerStatusUpdate, ServerHealth, LanguageServerStatusUpdate, ServerHealth,
}; };
use project::{ use project::{
LanguageServerProgress, LspStoreEvent, Project, ProjectEnvironmentEvent, EnvironmentErrorMessage, LanguageServerProgress, LspStoreEvent, Project,
ProjectEnvironmentEvent,
git_store::{GitStoreEvent, Repository}, git_store::{GitStoreEvent, Repository},
}; };
use smallvec::SmallVec; use smallvec::SmallVec;
@@ -19,6 +20,7 @@ use std::{
cmp::Reverse, cmp::Reverse,
collections::HashSet, collections::HashSet,
fmt::Write, fmt::Write,
path::Path,
sync::Arc, sync::Arc,
time::{Duration, Instant}, time::{Duration, Instant},
}; };
@@ -326,23 +328,27 @@ impl ActivityIndicator {
.flatten() .flatten()
} }
fn pending_environment_error<'a>(&'a self, cx: &'a App) -> Option<&'a String> { fn pending_environment_errors<'a>(
self.project.read(cx).peek_environment_error(cx) &'a self,
cx: &'a App,
) -> impl Iterator<Item = (&'a Arc<Path>, &'a EnvironmentErrorMessage)> {
self.project.read(cx).shell_environment_errors(cx)
} }
fn content_to_render(&mut self, cx: &mut Context<Self>) -> Option<Content> { fn content_to_render(&mut self, cx: &mut Context<Self>) -> Option<Content> {
// Show if any direnv calls failed // Show if any direnv calls failed
if let Some(message) = self.pending_environment_error(cx) { if let Some((abs_path, error)) = self.pending_environment_errors(cx).next() {
let abs_path = abs_path.clone();
return Some(Content { return Some(Content {
icon: Some( icon: Some(
Icon::new(IconName::Warning) Icon::new(IconName::Warning)
.size(IconSize::Small) .size(IconSize::Small)
.into_any_element(), .into_any_element(),
), ),
message: message.clone(), message: error.0.clone(),
on_click: Some(Arc::new(move |this, window, cx| { on_click: Some(Arc::new(move |this, window, cx| {
this.project.update(cx, |project, cx| { this.project.update(cx, |project, cx| {
project.pop_environment_error(cx); project.remove_environment_error(&abs_path, cx);
}); });
window.dispatch_action(Box::new(workspace::OpenLog), cx); window.dispatch_action(Box::new(workspace::OpenLog), cx);
})), })),

View File

@@ -5,101 +5,75 @@ edition.workspace = true
publish.workspace = true publish.workspace = true
license = "GPL-3.0-or-later" license = "GPL-3.0-or-later"
[lib]
path = "src/agent.rs"
[features]
test-support = ["db/test-support"]
eval = []
edit-agent-eval = []
e2e = []
[lints] [lints]
workspace = true workspace = true
[lib]
path = "src/agent.rs"
doctest = false
[features]
test-support = [
"gpui/test-support",
"language/test-support",
]
[dependencies] [dependencies]
acp_thread.workspace = true
action_log.workspace = true action_log.workspace = true
agent-client-protocol.workspace = true
agent_servers.workspace = true
agent_settings.workspace = true agent_settings.workspace = true
anyhow.workspace = true anyhow.workspace = true
assistant_text_thread.workspace = true assistant_context.workspace = true
assistant_tool.workspace = true
chrono.workspace = true chrono.workspace = true
client.workspace = true client.workspace = true
cloud_llm_client.workspace = true cloud_llm_client.workspace = true
collections.workspace = true collections.workspace = true
component.workspace = true
context_server.workspace = true context_server.workspace = true
db.workspace = true convert_case.workspace = true
derive_more.workspace = true
fs.workspace = true fs.workspace = true
futures.workspace = true futures.workspace = true
git.workspace = true git.workspace = true
gpui.workspace = true gpui.workspace = true
handlebars = { workspace = true, features = ["rust-embed"] } heed.workspace = true
html_to_markdown.workspace = true
http_client.workspace = true http_client.workspace = true
icons.workspace = true
indoc.workspace = true indoc.workspace = true
itertools.workspace = true itertools.workspace = true
language.workspace = true language.workspace = true
language_model.workspace = true language_model.workspace = true
language_models.workspace = true
log.workspace = true log.workspace = true
open.workspace = true
parking_lot.workspace = true
paths.workspace = true paths.workspace = true
postage.workspace = true
project.workspace = true project.workspace = true
prompt_store.workspace = true prompt_store.workspace = true
regex.workspace = true ref-cast.workspace = true
rust-embed.workspace = true rope.workspace = true
schemars.workspace = true schemars.workspace = true
serde.workspace = true serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
settings.workspace = true settings.workspace = true
smallvec.workspace = true
smol.workspace = true smol.workspace = true
sqlez.workspace = true sqlez.workspace = true
streaming_diff.workspace = true
strsim.workspace = true
task.workspace = true
telemetry.workspace = true telemetry.workspace = true
terminal.workspace = true
text.workspace = true text.workspace = true
theme.workspace = true
thiserror.workspace = true thiserror.workspace = true
ui.workspace = true time.workspace = true
util.workspace = true util.workspace = true
uuid.workspace = true uuid.workspace = true
watch.workspace = true workspace-hack.workspace = true
web_search.workspace = true
zed_env_vars.workspace = true zed_env_vars.workspace = true
zstd.workspace = true zstd.workspace = true
[dev-dependencies] [dev-dependencies]
agent_servers = { workspace = true, "features" = ["test-support"] } assistant_tools.workspace = true
assistant_text_thread = { workspace = true, "features" = ["test-support"] }
client = { workspace = true, "features" = ["test-support"] }
clock = { workspace = true, "features" = ["test-support"] }
context_server = { workspace = true, "features" = ["test-support"] }
ctor.workspace = true
db = { workspace = true, "features" = ["test-support"] }
editor = { workspace = true, "features" = ["test-support"] }
env_logger.workspace = true
fs = { workspace = true, "features" = ["test-support"] }
git = { workspace = true, "features" = ["test-support"] }
gpui = { workspace = true, "features" = ["test-support"] } gpui = { workspace = true, "features" = ["test-support"] }
gpui_tokio.workspace = true indoc.workspace = true
language = { workspace = true, "features" = ["test-support"] } language = { workspace = true, "features" = ["test-support"] }
language_model = { workspace = true, "features" = ["test-support"] } language_model = { workspace = true, "features" = ["test-support"] }
lsp = { workspace = true, "features" = ["test-support"] } parking_lot.workspace = true
pretty_assertions.workspace = true pretty_assertions.workspace = true
project = { workspace = true, "features" = ["test-support"] } project = { workspace = true, features = ["test-support"] }
workspace = { workspace = true, features = ["test-support"] }
rand.workspace = true rand.workspace = true
reqwest_client.workspace = true
settings = { workspace = true, "features" = ["test-support"] }
tempfile.workspace = true
terminal = { workspace = true, "features" = ["test-support"] }
theme = { workspace = true, "features" = ["test-support"] }
tree-sitter-rust.workspace = true
unindent = { workspace = true }
worktree = { workspace = true, "features" = ["test-support"] }
zlog.workspace = true

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,341 @@
use std::sync::Arc;
use agent_settings::{AgentProfileId, AgentProfileSettings, AgentSettings};
use assistant_tool::{Tool, ToolSource, ToolWorkingSet, UniqueToolName};
use collections::IndexMap;
use convert_case::{Case, Casing};
use fs::Fs;
use gpui::{App, Entity, SharedString};
use settings::{Settings, update_settings_file};
use util::ResultExt;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AgentProfile {
id: AgentProfileId,
tool_set: Entity<ToolWorkingSet>,
}
pub type AvailableProfiles = IndexMap<AgentProfileId, SharedString>;
impl AgentProfile {
pub fn new(id: AgentProfileId, tool_set: Entity<ToolWorkingSet>) -> Self {
Self { id, tool_set }
}
/// Saves a new profile to the settings.
pub fn create(
name: String,
base_profile_id: Option<AgentProfileId>,
fs: Arc<dyn Fs>,
cx: &App,
) -> AgentProfileId {
let id = AgentProfileId(name.to_case(Case::Kebab).into());
let base_profile =
base_profile_id.and_then(|id| AgentSettings::get_global(cx).profiles.get(&id).cloned());
let profile_settings = AgentProfileSettings {
name: name.into(),
tools: base_profile
.as_ref()
.map(|profile| profile.tools.clone())
.unwrap_or_default(),
enable_all_context_servers: base_profile
.as_ref()
.map(|profile| profile.enable_all_context_servers)
.unwrap_or_default(),
context_servers: base_profile
.map(|profile| profile.context_servers)
.unwrap_or_default(),
};
update_settings_file(fs, cx, {
let id = id.clone();
move |settings, _cx| {
profile_settings.save_to_settings(id, settings).log_err();
}
});
id
}
/// Returns a map of AgentProfileIds to their names
pub fn available_profiles(cx: &App) -> AvailableProfiles {
let mut profiles = AvailableProfiles::default();
for (id, profile) in AgentSettings::get_global(cx).profiles.iter() {
profiles.insert(id.clone(), profile.name.clone());
}
profiles
}
pub fn id(&self) -> &AgentProfileId {
&self.id
}
pub fn enabled_tools(&self, cx: &App) -> Vec<(UniqueToolName, Arc<dyn Tool>)> {
let Some(settings) = AgentSettings::get_global(cx).profiles.get(&self.id) else {
return Vec::new();
};
self.tool_set
.read(cx)
.tools(cx)
.into_iter()
.filter(|(_, tool)| Self::is_enabled(settings, tool.source(), tool.name()))
.collect()
}
pub fn is_tool_enabled(&self, source: ToolSource, tool_name: String, cx: &App) -> bool {
let Some(settings) = AgentSettings::get_global(cx).profiles.get(&self.id) else {
return false;
};
Self::is_enabled(settings, source, tool_name)
}
fn is_enabled(settings: &AgentProfileSettings, source: ToolSource, name: String) -> bool {
match source {
ToolSource::Native => *settings.tools.get(name.as_str()).unwrap_or(&false),
ToolSource::ContextServer { id } => settings
.context_servers
.get(id.as_ref())
.and_then(|preset| preset.tools.get(name.as_str()).copied())
.unwrap_or(settings.enable_all_context_servers),
}
}
}
#[cfg(test)]
mod tests {
use agent_settings::ContextServerPreset;
use assistant_tool::ToolRegistry;
use collections::IndexMap;
use gpui::SharedString;
use gpui::{AppContext, TestAppContext};
use http_client::FakeHttpClient;
use project::Project;
use settings::{Settings, SettingsStore};
use super::*;
#[gpui::test]
async fn test_enabled_built_in_tools_for_profile(cx: &mut TestAppContext) {
init_test_settings(cx);
let id = AgentProfileId::default();
let profile_settings = cx.read(|cx| {
AgentSettings::get_global(cx)
.profiles
.get(&id)
.unwrap()
.clone()
});
let tool_set = default_tool_set(cx);
let profile = AgentProfile::new(id, tool_set);
let mut enabled_tools = cx
.read(|cx| profile.enabled_tools(cx))
.into_iter()
.map(|(_, tool)| tool.name())
.collect::<Vec<_>>();
enabled_tools.sort();
let mut expected_tools = profile_settings
.tools
.into_iter()
.filter_map(|(tool, enabled)| enabled.then_some(tool.to_string()))
// Provider dependent
.filter(|tool| tool != "web_search")
.collect::<Vec<_>>();
// Plus all registered MCP tools
expected_tools.extend(["enabled_mcp_tool".into(), "disabled_mcp_tool".into()]);
expected_tools.sort();
assert_eq!(enabled_tools, expected_tools);
}
#[gpui::test]
async fn test_custom_mcp_settings(cx: &mut TestAppContext) {
init_test_settings(cx);
let id = AgentProfileId("custom_mcp".into());
let profile_settings = cx.read(|cx| {
AgentSettings::get_global(cx)
.profiles
.get(&id)
.unwrap()
.clone()
});
let tool_set = default_tool_set(cx);
let profile = AgentProfile::new(id, tool_set);
let mut enabled_tools = cx
.read(|cx| profile.enabled_tools(cx))
.into_iter()
.map(|(_, tool)| tool.name())
.collect::<Vec<_>>();
enabled_tools.sort();
let mut expected_tools = profile_settings.context_servers["mcp"]
.tools
.iter()
.filter_map(|(key, enabled)| enabled.then(|| key.to_string()))
.collect::<Vec<_>>();
expected_tools.sort();
assert_eq!(enabled_tools, expected_tools);
}
#[gpui::test]
async fn test_only_built_in(cx: &mut TestAppContext) {
init_test_settings(cx);
let id = AgentProfileId("write_minus_mcp".into());
let profile_settings = cx.read(|cx| {
AgentSettings::get_global(cx)
.profiles
.get(&id)
.unwrap()
.clone()
});
let tool_set = default_tool_set(cx);
let profile = AgentProfile::new(id, tool_set);
let mut enabled_tools = cx
.read(|cx| profile.enabled_tools(cx))
.into_iter()
.map(|(_, tool)| tool.name())
.collect::<Vec<_>>();
enabled_tools.sort();
let mut expected_tools = profile_settings
.tools
.into_iter()
.filter_map(|(tool, enabled)| enabled.then_some(tool.to_string()))
// Provider dependent
.filter(|tool| tool != "web_search")
.collect::<Vec<_>>();
expected_tools.sort();
assert_eq!(enabled_tools, expected_tools);
}
fn init_test_settings(cx: &mut TestAppContext) {
cx.update(|cx| {
let settings_store = SettingsStore::test(cx);
cx.set_global(settings_store);
Project::init_settings(cx);
AgentSettings::register(cx);
language_model::init_settings(cx);
ToolRegistry::default_global(cx);
assistant_tools::init(FakeHttpClient::with_404_response(), cx);
});
cx.update(|cx| {
let mut agent_settings = AgentSettings::get_global(cx).clone();
agent_settings.profiles.insert(
AgentProfileId("write_minus_mcp".into()),
AgentProfileSettings {
name: "write_minus_mcp".into(),
enable_all_context_servers: false,
..agent_settings.profiles[&AgentProfileId::default()].clone()
},
);
agent_settings.profiles.insert(
AgentProfileId("custom_mcp".into()),
AgentProfileSettings {
name: "mcp".into(),
tools: IndexMap::default(),
enable_all_context_servers: false,
context_servers: IndexMap::from_iter([("mcp".into(), context_server_preset())]),
},
);
AgentSettings::override_global(agent_settings, cx);
})
}
fn context_server_preset() -> ContextServerPreset {
ContextServerPreset {
tools: IndexMap::from_iter([
("enabled_mcp_tool".into(), true),
("disabled_mcp_tool".into(), false),
]),
}
}
fn default_tool_set(cx: &mut TestAppContext) -> Entity<ToolWorkingSet> {
cx.new(|cx| {
let mut tool_set = ToolWorkingSet::default();
tool_set.insert(Arc::new(FakeTool::new("enabled_mcp_tool", "mcp")), cx);
tool_set.insert(Arc::new(FakeTool::new("disabled_mcp_tool", "mcp")), cx);
tool_set
})
}
struct FakeTool {
name: String,
source: SharedString,
}
impl FakeTool {
fn new(name: impl Into<String>, source: impl Into<SharedString>) -> Self {
Self {
name: name.into(),
source: source.into(),
}
}
}
impl Tool for FakeTool {
fn name(&self) -> String {
self.name.clone()
}
fn source(&self) -> ToolSource {
ToolSource::ContextServer {
id: self.source.clone(),
}
}
fn description(&self) -> String {
unimplemented!()
}
fn icon(&self) -> icons::IconName {
unimplemented!()
}
fn needs_confirmation(
&self,
_input: &serde_json::Value,
_project: &Entity<Project>,
_cx: &App,
) -> bool {
unimplemented!()
}
fn ui_text(&self, _input: &serde_json::Value) -> String {
unimplemented!()
}
fn run(
self: Arc<Self>,
_input: serde_json::Value,
_request: Arc<language_model::LanguageModelRequest>,
_project: Entity<Project>,
_action_log: Entity<action_log::ActionLog>,
_model: Arc<dyn language_model::LanguageModel>,
_window: Option<gpui::AnyWindowHandle>,
_cx: &mut App,
) -> assistant_tool::ToolResult {
unimplemented!()
}
fn may_perform_edits(&self) -> bool {
unimplemented!()
}
}
}

View File

@@ -1,8 +1,11 @@
use agent::outline; use crate::thread::Thread;
use assistant_text_thread::TextThread; use assistant_context::AssistantContext;
use assistant_tool::outline;
use collections::HashSet;
use futures::future; use futures::future;
use futures::{FutureExt, future::Shared}; use futures::{FutureExt, future::Shared};
use gpui::{App, AppContext as _, ElementId, Entity, SharedString, Task}; use gpui::{App, AppContext as _, ElementId, Entity, SharedString, Task};
use icons::IconName;
use language::Buffer; use language::Buffer;
use language_model::{LanguageModelImage, LanguageModelRequestMessage, MessageContent}; use language_model::{LanguageModelImage, LanguageModelRequestMessage, MessageContent};
use project::{Project, ProjectEntryId, ProjectPath, Worktree}; use project::{Project, ProjectEntryId, ProjectPath, Worktree};
@@ -14,7 +17,6 @@ use std::hash::{Hash, Hasher};
use std::path::PathBuf; use std::path::PathBuf;
use std::{ops::Range, path::Path, sync::Arc}; use std::{ops::Range, path::Path, sync::Arc};
use text::{Anchor, OffsetRangeExt as _}; use text::{Anchor, OffsetRangeExt as _};
use ui::IconName;
use util::markdown::MarkdownCodeBlock; use util::markdown::MarkdownCodeBlock;
use util::rel_path::RelPath; use util::rel_path::RelPath;
use util::{ResultExt as _, post_inc}; use util::{ResultExt as _, post_inc};
@@ -179,7 +181,7 @@ impl FileContextHandle {
}) })
} }
fn load(self, cx: &App) -> Task<Option<AgentContext>> { fn load(self, cx: &App) -> Task<Option<(AgentContext, Vec<Entity<Buffer>>)>> {
let buffer_ref = self.buffer.read(cx); let buffer_ref = self.buffer.read(cx);
let Some(file) = buffer_ref.file() else { let Some(file) = buffer_ref.file() else {
log::error!("file context missing path"); log::error!("file context missing path");
@@ -204,7 +206,7 @@ impl FileContextHandle {
text: buffer_content.text.into(), text: buffer_content.text.into(),
is_outline: buffer_content.is_outline, is_outline: buffer_content.is_outline,
}); });
Some(context) Some((context, vec![buffer]))
}) })
} }
} }
@@ -254,7 +256,11 @@ impl DirectoryContextHandle {
self.entry_id.hash(state) self.entry_id.hash(state)
} }
fn load(self, project: Entity<Project>, cx: &mut App) -> Task<Option<AgentContext>> { fn load(
self,
project: Entity<Project>,
cx: &mut App,
) -> Task<Option<(AgentContext, Vec<Entity<Buffer>>)>> {
let Some(worktree) = project.read(cx).worktree_for_entry(self.entry_id, cx) else { let Some(worktree) = project.read(cx).worktree_for_entry(self.entry_id, cx) else {
return Task::ready(None); return Task::ready(None);
}; };
@@ -301,7 +307,7 @@ impl DirectoryContextHandle {
}); });
cx.background_spawn(async move { cx.background_spawn(async move {
let (rope, _buffer) = rope_task.await?; let (rope, buffer) = rope_task.await?;
let fenced_codeblock = MarkdownCodeBlock { let fenced_codeblock = MarkdownCodeBlock {
tag: &codeblock_tag(&full_path, None), tag: &codeblock_tag(&full_path, None),
text: &rope.to_string(), text: &rope.to_string(),
@@ -312,22 +318,18 @@ impl DirectoryContextHandle {
rel_path, rel_path,
fenced_codeblock, fenced_codeblock,
}; };
Some(descendant) Some((descendant, buffer))
}) })
})); }));
cx.background_spawn(async move { cx.background_spawn(async move {
let descendants = descendants_future let (descendants, buffers) = descendants_future.await.into_iter().flatten().unzip();
.await
.into_iter()
.flatten()
.collect::<Vec<_>>();
let context = AgentContext::Directory(DirectoryContext { let context = AgentContext::Directory(DirectoryContext {
handle: self, handle: self,
full_path: directory_full_path, full_path: directory_full_path,
descendants, descendants,
}); });
Some(context) Some((context, buffers))
}) })
} }
} }
@@ -395,7 +397,7 @@ impl SymbolContextHandle {
.into() .into()
} }
fn load(self, cx: &App) -> Task<Option<AgentContext>> { fn load(self, cx: &App) -> Task<Option<(AgentContext, Vec<Entity<Buffer>>)>> {
let buffer_ref = self.buffer.read(cx); let buffer_ref = self.buffer.read(cx);
let Some(file) = buffer_ref.file() else { let Some(file) = buffer_ref.file() else {
log::error!("symbol context's file has no path"); log::error!("symbol context's file has no path");
@@ -404,13 +406,14 @@ impl SymbolContextHandle {
let full_path = file.full_path(cx).to_string_lossy().into_owned(); let full_path = file.full_path(cx).to_string_lossy().into_owned();
let line_range = self.enclosing_range.to_point(&buffer_ref.snapshot()); let line_range = self.enclosing_range.to_point(&buffer_ref.snapshot());
let text = self.text(cx); let text = self.text(cx);
let buffer = self.buffer.clone();
let context = AgentContext::Symbol(SymbolContext { let context = AgentContext::Symbol(SymbolContext {
handle: self, handle: self,
full_path, full_path,
line_range, line_range,
text, text,
}); });
Task::ready(Some(context)) Task::ready(Some((context, vec![buffer])))
} }
} }
@@ -465,12 +468,13 @@ impl SelectionContextHandle {
.into() .into()
} }
fn load(self, cx: &App) -> Task<Option<AgentContext>> { fn load(self, cx: &App) -> Task<Option<(AgentContext, Vec<Entity<Buffer>>)>> {
let Some(full_path) = self.full_path(cx) else { let Some(full_path) = self.full_path(cx) else {
log::error!("selection context's file has no path"); log::error!("selection context's file has no path");
return Task::ready(None); return Task::ready(None);
}; };
let text = self.text(cx); let text = self.text(cx);
let buffer = self.buffer.clone();
let context = AgentContext::Selection(SelectionContext { let context = AgentContext::Selection(SelectionContext {
full_path: full_path.to_string_lossy().into_owned(), full_path: full_path.to_string_lossy().into_owned(),
line_range: self.line_range(cx), line_range: self.line_range(cx),
@@ -478,7 +482,7 @@ impl SelectionContextHandle {
handle: self, handle: self,
}); });
Task::ready(Some(context)) Task::ready(Some((context, vec![buffer])))
} }
} }
@@ -519,8 +523,8 @@ impl FetchedUrlContext {
})) }))
} }
pub fn load(self) -> Task<Option<AgentContext>> { pub fn load(self) -> Task<Option<(AgentContext, Vec<Entity<Buffer>>)>> {
Task::ready(Some(AgentContext::FetchedUrl(self))) Task::ready(Some((AgentContext::FetchedUrl(self), vec![])))
} }
} }
@@ -533,7 +537,7 @@ impl Display for FetchedUrlContext {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ThreadContextHandle { pub struct ThreadContextHandle {
pub thread: Entity<agent::Thread>, pub thread: Entity<Thread>,
pub context_id: ContextId, pub context_id: ContextId,
} }
@@ -554,20 +558,22 @@ impl ThreadContextHandle {
} }
pub fn title(&self, cx: &App) -> SharedString { pub fn title(&self, cx: &App) -> SharedString {
self.thread.read(cx).title() self.thread.read(cx).summary().or_default()
} }
fn load(self, cx: &mut App) -> Task<Option<AgentContext>> { fn load(self, cx: &App) -> Task<Option<(AgentContext, Vec<Entity<Buffer>>)>> {
let task = self.thread.update(cx, |thread, cx| thread.summary(cx)); cx.spawn(async move |cx| {
let title = self.title(cx); let text = Thread::wait_for_detailed_summary_or_text(&self.thread, cx).await?;
cx.background_spawn(async move { let title = self
let text = task.await?; .thread
.read_with(cx, |thread, _cx| thread.summary().or_default())
.ok()?;
let context = AgentContext::Thread(ThreadContext { let context = AgentContext::Thread(ThreadContext {
title, title,
text, text,
handle: self, handle: self,
}); });
Some(context) Some((context, vec![]))
}) })
} }
} }
@@ -581,7 +587,7 @@ impl Display for ThreadContext {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct TextThreadContextHandle { pub struct TextThreadContextHandle {
pub text_thread: Entity<TextThread>, pub context: Entity<AssistantContext>,
pub context_id: ContextId, pub context_id: ContextId,
} }
@@ -595,26 +601,26 @@ pub struct TextThreadContext {
impl TextThreadContextHandle { impl TextThreadContextHandle {
// pub fn lookup_key() -> // pub fn lookup_key() ->
pub fn eq_for_key(&self, other: &Self) -> bool { pub fn eq_for_key(&self, other: &Self) -> bool {
self.text_thread == other.text_thread self.context == other.context
} }
pub fn hash_for_key<H: Hasher>(&self, state: &mut H) { pub fn hash_for_key<H: Hasher>(&self, state: &mut H) {
self.text_thread.hash(state) self.context.hash(state)
} }
pub fn title(&self, cx: &App) -> SharedString { pub fn title(&self, cx: &App) -> SharedString {
self.text_thread.read(cx).summary().or_default() self.context.read(cx).summary().or_default()
} }
fn load(self, cx: &App) -> Task<Option<AgentContext>> { fn load(self, cx: &App) -> Task<Option<(AgentContext, Vec<Entity<Buffer>>)>> {
let title = self.title(cx); let title = self.title(cx);
let text = self.text_thread.read(cx).to_xml(cx); let text = self.context.read(cx).to_xml(cx);
let context = AgentContext::TextThread(TextThreadContext { let context = AgentContext::TextThread(TextThreadContext {
title, title,
text: text.into(), text: text.into(),
handle: self, handle: self,
}); });
Task::ready(Some(context)) Task::ready(Some((context, vec![])))
} }
} }
@@ -660,7 +666,7 @@ impl RulesContextHandle {
self, self,
prompt_store: &Option<Entity<PromptStore>>, prompt_store: &Option<Entity<PromptStore>>,
cx: &App, cx: &App,
) -> Task<Option<AgentContext>> { ) -> Task<Option<(AgentContext, Vec<Entity<Buffer>>)>> {
let Some(prompt_store) = prompt_store.as_ref() else { let Some(prompt_store) = prompt_store.as_ref() else {
return Task::ready(None); return Task::ready(None);
}; };
@@ -679,7 +685,7 @@ impl RulesContextHandle {
title, title,
text, text,
}); });
Some(context) Some((context, vec![]))
}) })
} }
} }
@@ -742,21 +748,32 @@ impl ImageContext {
} }
} }
pub fn load(self, cx: &App) -> Task<Option<AgentContext>> { pub fn load(self, cx: &App) -> Task<Option<(AgentContext, Vec<Entity<Buffer>>)>> {
cx.background_spawn(async move { cx.background_spawn(async move {
self.image_task.clone().await; self.image_task.clone().await;
Some(AgentContext::Image(self)) Some((AgentContext::Image(self), vec![]))
}) })
} }
} }
#[derive(Debug, Clone, Default)]
pub struct ContextLoadResult {
pub loaded_context: LoadedContext,
pub referenced_buffers: HashSet<Entity<Buffer>>,
}
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct LoadedContext { pub struct LoadedContext {
pub contexts: Vec<AgentContext>,
pub text: String, pub text: String,
pub images: Vec<LanguageModelImage>, pub images: Vec<LanguageModelImage>,
} }
impl LoadedContext { impl LoadedContext {
pub fn is_empty(&self) -> bool {
self.text.is_empty() && self.images.is_empty()
}
pub fn add_to_request_message(&self, request_message: &mut LanguageModelRequestMessage) { pub fn add_to_request_message(&self, request_message: &mut LanguageModelRequestMessage) {
if !self.text.is_empty() { if !self.text.is_empty() {
request_message request_message
@@ -787,7 +804,7 @@ pub fn load_context(
project: &Entity<Project>, project: &Entity<Project>,
prompt_store: &Option<Entity<PromptStore>>, prompt_store: &Option<Entity<PromptStore>>,
cx: &mut App, cx: &mut App,
) -> Task<LoadedContext> { ) -> Task<ContextLoadResult> {
let load_tasks: Vec<_> = contexts let load_tasks: Vec<_> = contexts
.into_iter() .into_iter()
.map(|context| match context { .map(|context| match context {
@@ -806,7 +823,16 @@ pub fn load_context(
cx.background_spawn(async move { cx.background_spawn(async move {
let load_results = future::join_all(load_tasks).await; let load_results = future::join_all(load_tasks).await;
let mut contexts = Vec::new();
let mut text = String::new(); let mut text = String::new();
let mut referenced_buffers = HashSet::default();
for context in load_results {
let Some((context, buffers)) = context else {
continue;
};
contexts.push(context);
referenced_buffers.extend(buffers);
}
let mut file_context = Vec::new(); let mut file_context = Vec::new();
let mut directory_context = Vec::new(); let mut directory_context = Vec::new();
@@ -817,7 +843,7 @@ pub fn load_context(
let mut text_thread_context = Vec::new(); let mut text_thread_context = Vec::new();
let mut rules_context = Vec::new(); let mut rules_context = Vec::new();
let mut images = Vec::new(); let mut images = Vec::new();
for context in load_results.into_iter().flatten() { for context in &contexts {
match context { match context {
AgentContext::File(context) => file_context.push(context), AgentContext::File(context) => file_context.push(context),
AgentContext::Directory(context) => directory_context.push(context), AgentContext::Directory(context) => directory_context.push(context),
@@ -842,7 +868,14 @@ pub fn load_context(
&& text_thread_context.is_empty() && text_thread_context.is_empty()
&& rules_context.is_empty() && rules_context.is_empty()
{ {
return LoadedContext { text, images }; return ContextLoadResult {
loaded_context: LoadedContext {
contexts,
text,
images,
},
referenced_buffers,
};
} }
text.push_str( text.push_str(
@@ -928,7 +961,14 @@ pub fn load_context(
text.push_str("</context>\n"); text.push_str("</context>\n");
LoadedContext { text, images } ContextLoadResult {
loaded_context: LoadedContext {
contexts,
text,
images,
},
referenced_buffers,
}
}) })
} }
@@ -1091,13 +1131,11 @@ mod tests {
assert!(content_len > outline::AUTO_OUTLINE_SIZE); assert!(content_len > outline::AUTO_OUTLINE_SIZE);
let file_context = load_context_for("file.txt", large_content, cx).await; let file_context = file_context_for(large_content, cx).await;
assert!( assert!(
file_context file_context.is_outline,
.text "Large file should use outline format"
.contains(&format!("# File outline for {}", path!("test/file.txt"))),
"Large files should not get an outline"
); );
assert!( assert!(
@@ -1115,38 +1153,29 @@ mod tests {
assert!(content_len < outline::AUTO_OUTLINE_SIZE); assert!(content_len < outline::AUTO_OUTLINE_SIZE);
let file_context = load_context_for("file.txt", small_content.to_string(), cx).await; let file_context = file_context_for(small_content.to_string(), cx).await;
assert!( assert!(
!file_context !file_context.is_outline,
.text
.contains(&format!("# File outline for {}", path!("test/file.txt"))),
"Small files should not get an outline" "Small files should not get an outline"
); );
assert!( assert_eq!(file_context.text, small_content);
file_context.text.contains(small_content),
"Small files should use full content"
);
} }
async fn load_context_for( async fn file_context_for(content: String, cx: &mut TestAppContext) -> FileContext {
filename: &str,
content: String,
cx: &mut TestAppContext,
) -> LoadedContext {
// Create a test project with the file // Create a test project with the file
let project = create_test_project( let project = create_test_project(
cx, cx,
json!({ json!({
filename: content, "file.txt": content,
}), }),
) )
.await; .await;
// Open the buffer // Open the buffer
let buffer_path = project let buffer_path = project
.read_with(cx, |project, cx| project.find_project_path(filename, cx)) .read_with(cx, |project, cx| project.find_project_path("file.txt", cx))
.unwrap(); .unwrap();
let buffer = project let buffer = project
@@ -1161,5 +1190,16 @@ mod tests {
cx.update(|cx| load_context(vec![context_handle], &project, &None, cx)) cx.update(|cx| load_context(vec![context_handle], &project, &None, cx))
.await .await
.loaded_context
.contexts
.into_iter()
.find_map(|ctx| {
if let AgentContext::File(file_ctx) = ctx {
Some(file_ctx)
} else {
None
}
})
.expect("Should have found a file context")
} }
} }

View File

@@ -0,0 +1,140 @@
use std::sync::Arc;
use action_log::ActionLog;
use anyhow::{Result, anyhow, bail};
use assistant_tool::{Tool, ToolResult, ToolSource};
use context_server::{ContextServerId, types};
use gpui::{AnyWindowHandle, App, Entity, Task};
use icons::IconName;
use language_model::{LanguageModel, LanguageModelRequest, LanguageModelToolSchemaFormat};
use project::{Project, context_server_store::ContextServerStore};
pub struct ContextServerTool {
store: Entity<ContextServerStore>,
server_id: ContextServerId,
tool: types::Tool,
}
impl ContextServerTool {
pub fn new(
store: Entity<ContextServerStore>,
server_id: ContextServerId,
tool: types::Tool,
) -> Self {
Self {
store,
server_id,
tool,
}
}
}
impl Tool for ContextServerTool {
fn name(&self) -> String {
self.tool.name.clone()
}
fn description(&self) -> String {
self.tool.description.clone().unwrap_or_default()
}
fn icon(&self) -> IconName {
IconName::ToolHammer
}
fn source(&self) -> ToolSource {
ToolSource::ContextServer {
id: self.server_id.clone().0.into(),
}
}
fn needs_confirmation(&self, _: &serde_json::Value, _: &Entity<Project>, _: &App) -> bool {
true
}
fn may_perform_edits(&self) -> bool {
true
}
fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
let mut schema = self.tool.input_schema.clone();
assistant_tool::adapt_schema_to_format(&mut schema, format)?;
Ok(match schema {
serde_json::Value::Null => {
serde_json::json!({ "type": "object", "properties": [] })
}
serde_json::Value::Object(map) if map.is_empty() => {
serde_json::json!({ "type": "object", "properties": [] })
}
_ => schema,
})
}
fn ui_text(&self, _input: &serde_json::Value) -> String {
format!("Run MCP tool `{}`", self.tool.name)
}
fn run(
self: Arc<Self>,
input: serde_json::Value,
_request: Arc<LanguageModelRequest>,
_project: Entity<Project>,
_action_log: Entity<ActionLog>,
_model: Arc<dyn LanguageModel>,
_window: Option<AnyWindowHandle>,
cx: &mut App,
) -> ToolResult {
if let Some(server) = self.store.read(cx).get_running_server(&self.server_id) {
let tool_name = self.tool.name.clone();
cx.spawn(async move |_cx| {
let Some(protocol) = server.client() else {
bail!("Context server not initialized");
};
let arguments = if let serde_json::Value::Object(map) = input {
Some(map.into_iter().collect())
} else {
None
};
log::trace!(
"Running tool: {} with arguments: {:?}",
tool_name,
arguments
);
let response = protocol
.request::<context_server::types::requests::CallTool>(
context_server::types::CallToolParams {
name: tool_name,
arguments,
meta: None,
},
)
.await?;
let mut result = String::new();
for content in response.content {
match content {
types::ToolResponseContent::Text { text } => {
result.push_str(&text);
}
types::ToolResponseContent::Image { .. } => {
log::warn!("Ignoring image content from tool response");
}
types::ToolResponseContent::Audio { .. } => {
log::warn!("Ignoring audio content from tool response");
}
types::ToolResponseContent::Resource { .. } => {
log::warn!("Ignoring resource content from tool response");
}
}
}
Ok(result.into())
})
.into()
} else {
Task::ready(Err(anyhow!("Context server not found"))).into()
}
}
}

View File

@@ -1,11 +1,14 @@
use crate::context::{ use crate::{
AgentContextHandle, AgentContextKey, ContextId, ContextKind, DirectoryContextHandle, context::{
FetchedUrlContext, FileContextHandle, ImageContext, RulesContextHandle, SelectionContextHandle, AgentContextHandle, AgentContextKey, ContextId, ContextKind, DirectoryContextHandle,
SymbolContextHandle, TextThreadContextHandle, ThreadContextHandle, FetchedUrlContext, FileContextHandle, ImageContext, RulesContextHandle,
SelectionContextHandle, SymbolContextHandle, TextThreadContextHandle, ThreadContextHandle,
},
thread::{MessageId, Thread, ThreadId},
thread_store::ThreadStore,
}; };
use agent_client_protocol as acp;
use anyhow::{Context as _, Result, anyhow}; use anyhow::{Context as _, Result, anyhow};
use assistant_text_thread::TextThread; use assistant_context::AssistantContext;
use collections::{HashSet, IndexSet}; use collections::{HashSet, IndexSet};
use futures::{self, FutureExt}; use futures::{self, FutureExt};
use gpui::{App, Context, Entity, EventEmitter, Image, SharedString, Task, WeakEntity}; use gpui::{App, Context, Entity, EventEmitter, Image, SharedString, Task, WeakEntity};
@@ -26,9 +29,10 @@ use text::{Anchor, OffsetRangeExt};
pub struct ContextStore { pub struct ContextStore {
project: WeakEntity<Project>, project: WeakEntity<Project>,
thread_store: Option<WeakEntity<ThreadStore>>,
next_context_id: ContextId, next_context_id: ContextId,
context_set: IndexSet<AgentContextKey>, context_set: IndexSet<AgentContextKey>,
context_thread_ids: HashSet<acp::SessionId>, context_thread_ids: HashSet<ThreadId>,
context_text_thread_paths: HashSet<Arc<Path>>, context_text_thread_paths: HashSet<Arc<Path>>,
} }
@@ -39,9 +43,13 @@ pub enum ContextStoreEvent {
impl EventEmitter<ContextStoreEvent> for ContextStore {} impl EventEmitter<ContextStoreEvent> for ContextStore {}
impl ContextStore { impl ContextStore {
pub fn new(project: WeakEntity<Project>) -> Self { pub fn new(
project: WeakEntity<Project>,
thread_store: Option<WeakEntity<ThreadStore>>,
) -> Self {
Self { Self {
project, project,
thread_store,
next_context_id: ContextId::zero(), next_context_id: ContextId::zero(),
context_set: IndexSet::default(), context_set: IndexSet::default(),
context_thread_ids: HashSet::default(), context_thread_ids: HashSet::default(),
@@ -59,6 +67,29 @@ impl ContextStore {
cx.notify(); cx.notify();
} }
pub fn new_context_for_thread(
&self,
thread: &Thread,
exclude_messages_from_id: Option<MessageId>,
) -> Vec<AgentContextHandle> {
let existing_context = thread
.messages()
.take_while(|message| exclude_messages_from_id.is_none_or(|id| message.id != id))
.flat_map(|message| {
message
.loaded_context
.contexts
.iter()
.map(|context| AgentContextKey(context.handle()))
})
.collect::<HashSet<_>>();
self.context_set
.iter()
.filter(|context| !existing_context.contains(context))
.map(|entry| entry.0.clone())
.collect::<Vec<_>>()
}
pub fn add_file_from_path( pub fn add_file_from_path(
&mut self, &mut self,
project_path: ProjectPath, project_path: ProjectPath,
@@ -178,7 +209,7 @@ impl ContextStore {
pub fn add_thread( pub fn add_thread(
&mut self, &mut self,
thread: Entity<agent::Thread>, thread: Entity<Thread>,
remove_if_exists: bool, remove_if_exists: bool,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Option<AgentContextHandle> { ) -> Option<AgentContextHandle> {
@@ -200,13 +231,13 @@ impl ContextStore {
pub fn add_text_thread( pub fn add_text_thread(
&mut self, &mut self,
text_thread: Entity<TextThread>, context: Entity<AssistantContext>,
remove_if_exists: bool, remove_if_exists: bool,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Option<AgentContextHandle> { ) -> Option<AgentContextHandle> {
let context_id = self.next_context_id.post_inc(); let context_id = self.next_context_id.post_inc();
let context = AgentContextHandle::TextThread(TextThreadContextHandle { let context = AgentContextHandle::TextThread(TextThreadContextHandle {
text_thread, context,
context_id, context_id,
}); });
@@ -353,15 +384,21 @@ impl ContextStore {
); );
}; };
} }
SuggestedContext::TextThread { SuggestedContext::Thread { thread, name: _ } => {
text_thread, if let Some(thread) = thread.upgrade() {
name: _, let context_id = self.next_context_id.post_inc();
} => { self.insert_context(
if let Some(text_thread) = text_thread.upgrade() { AgentContextHandle::Thread(ThreadContextHandle { thread, context_id }),
cx,
);
}
}
SuggestedContext::TextThread { context, name: _ } => {
if let Some(context) = context.upgrade() {
let context_id = self.next_context_id.post_inc(); let context_id = self.next_context_id.post_inc();
self.insert_context( self.insert_context(
AgentContextHandle::TextThread(TextThreadContextHandle { AgentContextHandle::TextThread(TextThreadContextHandle {
text_thread, context,
context_id, context_id,
}), }),
cx, cx,
@@ -373,20 +410,20 @@ impl ContextStore {
fn insert_context(&mut self, context: AgentContextHandle, cx: &mut Context<Self>) -> bool { fn insert_context(&mut self, context: AgentContextHandle, cx: &mut Context<Self>) -> bool {
match &context { match &context {
// AgentContextHandle::Thread(thread_context) => { AgentContextHandle::Thread(thread_context) => {
// if let Some(thread_store) = self.thread_store.clone() { if let Some(thread_store) = self.thread_store.clone() {
// thread_context.thread.update(cx, |thread, cx| { thread_context.thread.update(cx, |thread, cx| {
// thread.start_generating_detailed_summary_if_needed(thread_store, cx); thread.start_generating_detailed_summary_if_needed(thread_store, cx);
// }); });
// self.context_thread_ids self.context_thread_ids
// .insert(thread_context.thread.read(cx).id().clone()); .insert(thread_context.thread.read(cx).id().clone());
// } else { } else {
// return false; return false;
// } }
// } }
AgentContextHandle::TextThread(text_thread_context) => { AgentContextHandle::TextThread(text_thread_context) => {
self.context_text_thread_paths self.context_text_thread_paths
.extend(text_thread_context.text_thread.read(cx).path().cloned()); .extend(text_thread_context.context.read(cx).path().cloned());
} }
_ => {} _ => {}
} }
@@ -408,7 +445,7 @@ impl ContextStore {
.remove(thread_context.thread.read(cx).id()); .remove(thread_context.thread.read(cx).id());
} }
AgentContextHandle::TextThread(text_thread_context) => { AgentContextHandle::TextThread(text_thread_context) => {
if let Some(path) = text_thread_context.text_thread.read(cx).path() { if let Some(path) = text_thread_context.context.read(cx).path() {
self.context_text_thread_paths.remove(path); self.context_text_thread_paths.remove(path);
} }
} }
@@ -477,7 +514,7 @@ impl ContextStore {
}) })
} }
pub fn includes_thread(&self, thread_id: &acp::SessionId) -> bool { pub fn includes_thread(&self, thread_id: &ThreadId) -> bool {
self.context_thread_ids.contains(thread_id) self.context_thread_ids.contains(thread_id)
} }
@@ -510,9 +547,9 @@ impl ContextStore {
} }
AgentContextHandle::Directory(_) AgentContextHandle::Directory(_)
| AgentContextHandle::Symbol(_) | AgentContextHandle::Symbol(_)
| AgentContextHandle::Thread(_)
| AgentContextHandle::Selection(_) | AgentContextHandle::Selection(_)
| AgentContextHandle::FetchedUrl(_) | AgentContextHandle::FetchedUrl(_)
| AgentContextHandle::Thread(_)
| AgentContextHandle::TextThread(_) | AgentContextHandle::TextThread(_)
| AgentContextHandle::Rules(_) | AgentContextHandle::Rules(_)
| AgentContextHandle::Image(_) => None, | AgentContextHandle::Image(_) => None,
@@ -520,7 +557,7 @@ impl ContextStore {
.collect() .collect()
} }
pub fn thread_ids(&self) -> &HashSet<acp::SessionId> { pub fn thread_ids(&self) -> &HashSet<ThreadId> {
&self.context_thread_ids &self.context_thread_ids
} }
} }
@@ -532,9 +569,13 @@ pub enum SuggestedContext {
icon_path: Option<SharedString>, icon_path: Option<SharedString>,
buffer: WeakEntity<Buffer>, buffer: WeakEntity<Buffer>,
}, },
Thread {
name: SharedString,
thread: WeakEntity<Thread>,
},
TextThread { TextThread {
name: SharedString, name: SharedString,
text_thread: WeakEntity<TextThread>, context: WeakEntity<AssistantContext>,
}, },
} }
@@ -542,6 +583,7 @@ impl SuggestedContext {
pub fn name(&self) -> &SharedString { pub fn name(&self) -> &SharedString {
match self { match self {
Self::File { name, .. } => name, Self::File { name, .. } => name,
Self::Thread { name, .. } => name,
Self::TextThread { name, .. } => name, Self::TextThread { name, .. } => name,
} }
} }
@@ -549,6 +591,7 @@ impl SuggestedContext {
pub fn icon_path(&self) -> Option<SharedString> { pub fn icon_path(&self) -> Option<SharedString> {
match self { match self {
Self::File { icon_path, .. } => icon_path.clone(), Self::File { icon_path, .. } => icon_path.clone(),
Self::Thread { .. } => None,
Self::TextThread { .. } => None, Self::TextThread { .. } => None,
} }
} }
@@ -556,6 +599,7 @@ impl SuggestedContext {
pub fn kind(&self) -> ContextKind { pub fn kind(&self) -> ContextKind {
match self { match self {
Self::File { .. } => ContextKind::File, Self::File { .. } => ContextKind::File,
Self::Thread { .. } => ContextKind::Thread,
Self::TextThread { .. } => ContextKind::TextThread, Self::TextThread { .. } => ContextKind::TextThread,
} }
} }

View File

@@ -1,128 +1,64 @@
use crate::{DbThread, DbThreadMetadata, ThreadsDatabase}; use crate::{ThreadId, thread_store::SerializedThreadMetadata};
use acp_thread::MentionUri; use anyhow::{Context as _, Result};
use agent_client_protocol as acp; use assistant_context::SavedContextMetadata;
use anyhow::{Context as _, Result, anyhow};
use assistant_text_thread::{SavedTextThreadMetadata, TextThread};
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use db::kvp::KEY_VALUE_STORE;
use gpui::{App, AsyncApp, Entity, SharedString, Task, prelude::*}; use gpui::{App, AsyncApp, Entity, SharedString, Task, prelude::*};
use itertools::Itertools; use itertools::Itertools;
use paths::text_threads_dir; use paths::contexts_dir;
use project::Project;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{collections::VecDeque, path::Path, rc::Rc, sync::Arc, time::Duration}; use std::{collections::VecDeque, path::Path, sync::Arc, time::Duration};
use ui::ElementId;
use util::ResultExt as _; use util::ResultExt as _;
const MAX_RECENTLY_OPENED_ENTRIES: usize = 6; const MAX_RECENTLY_OPENED_ENTRIES: usize = 6;
const RECENTLY_OPENED_THREADS_KEY: &str = "recent-agent-threads"; const NAVIGATION_HISTORY_PATH: &str = "agent-navigation-history.json";
const SAVE_RECENTLY_OPENED_ENTRIES_DEBOUNCE: Duration = Duration::from_millis(50); const SAVE_RECENTLY_OPENED_ENTRIES_DEBOUNCE: Duration = Duration::from_millis(50);
const DEFAULT_TITLE: &SharedString = &SharedString::new_static("New Thread");
//todo: We should remove this function once we support loading all acp thread
pub fn load_agent_thread(
session_id: acp::SessionId,
history_store: Entity<HistoryStore>,
project: Entity<Project>,
cx: &mut App,
) -> Task<Result<Entity<crate::Thread>>> {
use agent_servers::{AgentServer, AgentServerDelegate};
let server = Rc::new(crate::NativeAgentServer::new(
project.read(cx).fs().clone(),
history_store,
));
let delegate = AgentServerDelegate::new(
project.read(cx).agent_server_store().clone(),
project.clone(),
None,
None,
);
let connection = server.connect(None, delegate, cx);
cx.spawn(async move |cx| {
let (agent, _) = connection.await?;
let agent = agent.downcast::<crate::NativeAgentConnection>().unwrap();
cx.update(|cx| agent.load_thread(session_id, cx))?.await
})
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum HistoryEntry { pub enum HistoryEntry {
AcpThread(DbThreadMetadata), Thread(SerializedThreadMetadata),
TextThread(SavedTextThreadMetadata), Context(SavedContextMetadata),
} }
impl HistoryEntry { impl HistoryEntry {
pub fn updated_at(&self) -> DateTime<Utc> { pub fn updated_at(&self) -> DateTime<Utc> {
match self { match self {
HistoryEntry::AcpThread(thread) => thread.updated_at, HistoryEntry::Thread(thread) => thread.updated_at,
HistoryEntry::TextThread(text_thread) => text_thread.mtime.to_utc(), HistoryEntry::Context(context) => context.mtime.to_utc(),
} }
} }
pub fn id(&self) -> HistoryEntryId { pub fn id(&self) -> HistoryEntryId {
match self { match self {
HistoryEntry::AcpThread(thread) => HistoryEntryId::AcpThread(thread.id.clone()), HistoryEntry::Thread(thread) => HistoryEntryId::Thread(thread.id.clone()),
HistoryEntry::TextThread(text_thread) => { HistoryEntry::Context(context) => HistoryEntryId::Context(context.path.clone()),
HistoryEntryId::TextThread(text_thread.path.clone())
}
}
}
pub fn mention_uri(&self) -> MentionUri {
match self {
HistoryEntry::AcpThread(thread) => MentionUri::Thread {
id: thread.id.clone(),
name: thread.title.to_string(),
},
HistoryEntry::TextThread(text_thread) => MentionUri::TextThread {
path: text_thread.path.as_ref().to_owned(),
name: text_thread.title.to_string(),
},
} }
} }
pub fn title(&self) -> &SharedString { pub fn title(&self) -> &SharedString {
match self { match self {
HistoryEntry::AcpThread(thread) => { HistoryEntry::Thread(thread) => &thread.summary,
if thread.title.is_empty() { HistoryEntry::Context(context) => &context.title,
DEFAULT_TITLE
} else {
&thread.title
}
}
HistoryEntry::TextThread(text_thread) => &text_thread.title,
} }
} }
} }
/// Generic identifier for a history entry. /// Generic identifier for a history entry.
#[derive(Clone, PartialEq, Eq, Debug, Hash)] #[derive(Clone, PartialEq, Eq, Debug)]
pub enum HistoryEntryId { pub enum HistoryEntryId {
AcpThread(acp::SessionId), Thread(ThreadId),
TextThread(Arc<Path>), Context(Arc<Path>),
} }
impl Into<ElementId> for HistoryEntryId { #[derive(Serialize, Deserialize)]
fn into(self) -> ElementId {
match self {
HistoryEntryId::AcpThread(session_id) => ElementId::Name(session_id.0.into()),
HistoryEntryId::TextThread(path) => ElementId::Path(path),
}
}
}
#[derive(Serialize, Deserialize, Debug)]
enum SerializedRecentOpen { enum SerializedRecentOpen {
AcpThread(String), Thread(String),
TextThread(String), ContextName(String),
/// Old format which stores the full path
Context(String),
} }
pub struct HistoryStore { pub struct HistoryStore {
threads: Vec<DbThreadMetadata>, context_store: Entity<assistant_context::ContextStore>,
entries: Vec<HistoryEntry>,
text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
recently_opened_entries: VecDeque<HistoryEntryId>, recently_opened_entries: VecDeque<HistoryEntryId>,
_subscriptions: Vec<gpui::Subscription>, _subscriptions: Vec<gpui::Subscription>,
_save_recently_opened_entries_task: Task<()>, _save_recently_opened_entries_task: Task<()>,
@@ -130,133 +66,57 @@ pub struct HistoryStore {
impl HistoryStore { impl HistoryStore {
pub fn new( pub fn new(
text_thread_store: Entity<assistant_text_thread::TextThreadStore>, context_store: Entity<assistant_context::ContextStore>,
initial_recent_entries: impl IntoIterator<Item = HistoryEntryId>,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Self { ) -> Self {
let subscriptions = let subscriptions = vec![cx.observe(&context_store, |_, _, cx| cx.notify())];
vec![cx.observe(&text_thread_store, |this, _, cx| this.update_entries(cx))];
cx.spawn(async move |this, cx| { cx.spawn(async move |this, cx| {
let entries = Self::load_recently_opened_entries(cx).await; let entries = Self::load_recently_opened_entries(cx).await.log_err()?;
this.update(cx, |this, cx| { this.update(cx, |this, _| {
if let Some(entries) = entries.log_err() { this.recently_opened_entries
this.recently_opened_entries = entries; .extend(
} entries.into_iter().take(
MAX_RECENTLY_OPENED_ENTRIES
this.reload(cx); .saturating_sub(this.recently_opened_entries.len()),
),
);
}) })
.ok(); .ok()
}) })
.detach(); .detach();
Self { Self {
text_thread_store, context_store,
recently_opened_entries: VecDeque::default(), recently_opened_entries: initial_recent_entries.into_iter().collect(),
threads: Vec::default(),
entries: Vec::default(),
_subscriptions: subscriptions, _subscriptions: subscriptions,
_save_recently_opened_entries_task: Task::ready(()), _save_recently_opened_entries_task: Task::ready(()),
} }
} }
pub fn thread_from_session_id(&self, session_id: &acp::SessionId) -> Option<&DbThreadMetadata> { pub fn entries(&self, cx: &mut Context<Self>) -> Vec<HistoryEntry> {
self.threads.iter().find(|thread| &thread.id == session_id) let mut history_entries = Vec::new();
}
pub fn load_thread(
&mut self,
id: acp::SessionId,
cx: &mut Context<Self>,
) -> Task<Result<Option<DbThread>>> {
let database_future = ThreadsDatabase::connect(cx);
cx.background_spawn(async move {
let database = database_future.await.map_err(|err| anyhow!(err))?;
database.load_thread(id).await
})
}
pub fn delete_thread(
&mut self,
id: acp::SessionId,
cx: &mut Context<Self>,
) -> Task<Result<()>> {
let database_future = ThreadsDatabase::connect(cx);
cx.spawn(async move |this, cx| {
let database = database_future.await.map_err(|err| anyhow!(err))?;
database.delete_thread(id.clone()).await?;
this.update(cx, |this, cx| this.reload(cx))
})
}
pub fn delete_text_thread(
&mut self,
path: Arc<Path>,
cx: &mut Context<Self>,
) -> Task<Result<()>> {
self.text_thread_store
.update(cx, |store, cx| store.delete_local(path, cx))
}
pub fn load_text_thread(
&self,
path: Arc<Path>,
cx: &mut Context<Self>,
) -> Task<Result<Entity<TextThread>>> {
self.text_thread_store
.update(cx, |store, cx| store.open_local(path, cx))
}
pub fn reload(&self, cx: &mut Context<Self>) {
let database_future = ThreadsDatabase::connect(cx);
cx.spawn(async move |this, cx| {
let threads = database_future
.await
.map_err(|err| anyhow!(err))?
.list_threads()
.await?;
this.update(cx, |this, cx| {
if this.recently_opened_entries.len() < MAX_RECENTLY_OPENED_ENTRIES {
for thread in threads
.iter()
.take(MAX_RECENTLY_OPENED_ENTRIES - this.recently_opened_entries.len())
.rev()
{
this.push_recently_opened_entry(
HistoryEntryId::AcpThread(thread.id.clone()),
cx,
)
}
}
this.threads = threads;
this.update_entries(cx);
})
})
.detach_and_log_err(cx);
}
fn update_entries(&mut self, cx: &mut Context<Self>) {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
if std::env::var("ZED_SIMULATE_NO_THREAD_HISTORY").is_ok() { if std::env::var("ZED_SIMULATE_NO_THREAD_HISTORY").is_ok() {
return; return history_entries;
} }
let mut history_entries = Vec::new();
history_entries.extend(self.threads.iter().cloned().map(HistoryEntry::AcpThread));
history_entries.extend( history_entries.extend(
self.text_thread_store self.context_store
.read(cx) .read(cx)
.unordered_text_threads() .unordered_contexts()
.cloned() .cloned()
.map(HistoryEntry::TextThread), .map(HistoryEntry::Context),
); );
history_entries.sort_unstable_by_key(|entry| std::cmp::Reverse(entry.updated_at())); history_entries.sort_unstable_by_key(|entry| std::cmp::Reverse(entry.updated_at()));
self.entries = history_entries; history_entries
cx.notify()
} }
pub fn is_empty(&self, _cx: &App) -> bool { pub fn recent_entries(&self, limit: usize, cx: &mut Context<Self>) -> Vec<HistoryEntry> {
self.entries.is_empty() self.entries(cx).into_iter().take(limit).collect()
} }
pub fn recently_opened_entries(&self, cx: &App) -> Vec<HistoryEntry> { pub fn recently_opened_entries(&self, cx: &App) -> Vec<HistoryEntry> {
@@ -265,36 +125,23 @@ impl HistoryStore {
return Vec::new(); return Vec::new();
} }
let thread_entries = self.threads.iter().flat_map(|thread| { let context_entries =
self.recently_opened_entries self.context_store
.iter() .read(cx)
.enumerate() .unordered_contexts()
.flat_map(|(index, entry)| match entry { .flat_map(|context| {
HistoryEntryId::AcpThread(id) if &thread.id == id => { self.recently_opened_entries
Some((index, HistoryEntry::AcpThread(thread.clone()))) .iter()
} .enumerate()
_ => None, .flat_map(|(index, entry)| match entry {
}) HistoryEntryId::Context(path) if &context.path == path => {
}); Some((index, HistoryEntry::Context(context.clone())))
}
_ => None,
})
});
let context_entries = self context_entries
.text_thread_store
.read(cx)
.unordered_text_threads()
.flat_map(|text_thread| {
self.recently_opened_entries
.iter()
.enumerate()
.flat_map(|(index, entry)| match entry {
HistoryEntryId::TextThread(path) if &text_thread.path == path => {
Some((index, HistoryEntry::TextThread(text_thread.clone())))
}
_ => None,
})
});
thread_entries
.chain(context_entries)
// optimization to halt iteration early // optimization to halt iteration early
.take(self.recently_opened_entries.len()) .take(self.recently_opened_entries.len())
.sorted_unstable_by_key(|(index, _)| *index) .sorted_unstable_by_key(|(index, _)| *index)
@@ -307,52 +154,59 @@ impl HistoryStore {
.recently_opened_entries .recently_opened_entries
.iter() .iter()
.filter_map(|entry| match entry { .filter_map(|entry| match entry {
HistoryEntryId::TextThread(path) => path.file_name().map(|file| { HistoryEntryId::Context(path) => path.file_name().map(|file| {
SerializedRecentOpen::TextThread(file.to_string_lossy().into_owned()) SerializedRecentOpen::ContextName(file.to_string_lossy().into_owned())
}), }),
HistoryEntryId::AcpThread(id) => { HistoryEntryId::Thread(id) => Some(SerializedRecentOpen::Thread(id.to_string())),
Some(SerializedRecentOpen::AcpThread(id.to_string()))
}
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
self._save_recently_opened_entries_task = cx.spawn(async move |_, cx| { self._save_recently_opened_entries_task = cx.spawn(async move |_, cx| {
let content = serde_json::to_string(&serialized_entries).unwrap();
cx.background_executor() cx.background_executor()
.timer(SAVE_RECENTLY_OPENED_ENTRIES_DEBOUNCE) .timer(SAVE_RECENTLY_OPENED_ENTRIES_DEBOUNCE)
.await; .await;
cx.background_spawn(async move {
if cfg!(any(feature = "test-support", test)) { let path = paths::data_dir().join(NAVIGATION_HISTORY_PATH);
return; let content = serde_json::to_string(&serialized_entries)?;
} std::fs::write(path, content)?;
KEY_VALUE_STORE anyhow::Ok(())
.write_kvp(RECENTLY_OPENED_THREADS_KEY.to_owned(), content) })
.await .await
.log_err(); .log_err();
}); });
} }
fn load_recently_opened_entries(cx: &AsyncApp) -> Task<Result<VecDeque<HistoryEntryId>>> { fn load_recently_opened_entries(cx: &AsyncApp) -> Task<Result<Vec<HistoryEntryId>>> {
cx.background_spawn(async move { cx.background_spawn(async move {
if cfg!(any(feature = "test-support", test)) { let path = paths::data_dir().join(NAVIGATION_HISTORY_PATH);
anyhow::bail!("history store does not persist in tests"); let contents = match smol::fs::read_to_string(path).await {
} Ok(it) => it,
let json = KEY_VALUE_STORE Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
.read_kvp(RECENTLY_OPENED_THREADS_KEY)? return Ok(Vec::new());
.unwrap_or("[]".to_string()); }
let entries = serde_json::from_str::<Vec<SerializedRecentOpen>>(&json) Err(e) => {
return Err(e)
.context("deserializing persisted agent panel navigation history");
}
};
let entries = serde_json::from_str::<Vec<SerializedRecentOpen>>(&contents)
.context("deserializing persisted agent panel navigation history")? .context("deserializing persisted agent panel navigation history")?
.into_iter() .into_iter()
.take(MAX_RECENTLY_OPENED_ENTRIES) .take(MAX_RECENTLY_OPENED_ENTRIES)
.flat_map(|entry| match entry { .flat_map(|entry| match entry {
SerializedRecentOpen::AcpThread(id) => Some(HistoryEntryId::AcpThread( SerializedRecentOpen::Thread(id) => {
acp::SessionId(id.as_str().into()), Some(HistoryEntryId::Thread(id.as_str().into()))
}
SerializedRecentOpen::ContextName(file_name) => Some(HistoryEntryId::Context(
contexts_dir().join(file_name).into(),
)), )),
SerializedRecentOpen::TextThread(file_name) => Some( SerializedRecentOpen::Context(path) => {
HistoryEntryId::TextThread(text_threads_dir().join(file_name).into()), Path::new(&path).file_name().map(|file_name| {
), HistoryEntryId::Context(contexts_dir().join(file_name).into())
})
}
}) })
.collect(); .collect::<Vec<_>>();
Ok(entries) Ok(entries)
}) })
} }
@@ -366,9 +220,9 @@ impl HistoryStore {
self.save_recently_opened_entries(cx); self.save_recently_opened_entries(cx);
} }
pub fn remove_recently_opened_thread(&mut self, id: acp::SessionId, cx: &mut Context<Self>) { pub fn remove_recently_opened_thread(&mut self, id: ThreadId, cx: &mut Context<Self>) {
self.recently_opened_entries.retain( self.recently_opened_entries.retain(
|entry| !matches!(entry, HistoryEntryId::AcpThread(thread_id) if thread_id == &id), |entry| !matches!(entry, HistoryEntryId::Thread(thread_id) if thread_id == &id),
); );
self.save_recently_opened_entries(cx); self.save_recently_opened_entries(cx);
} }
@@ -381,8 +235,8 @@ impl HistoryStore {
) { ) {
for entry in &mut self.recently_opened_entries { for entry in &mut self.recently_opened_entries {
match entry { match entry {
HistoryEntryId::TextThread(path) if path.as_ref() == old_path => { HistoryEntryId::Context(path) if path.as_ref() == old_path => {
*entry = HistoryEntryId::TextThread(new_path.clone()); *entry = HistoryEntryId::Context(new_path.clone());
break; break;
} }
_ => {} _ => {}
@@ -396,8 +250,4 @@ impl HistoryStore {
.retain(|old_entry| old_entry != entry); .retain(|old_entry| old_entry != entry);
self.save_recently_opened_entries(cx); self.save_recently_opened_entries(cx);
} }
pub fn entries(&self) -> impl Iterator<Item = HistoryEntry> {
self.entries.iter().cloned()
}
} }

View File

@@ -1,402 +0,0 @@
use crate::ProjectSnapshot;
use agent_settings::{AgentProfileId, CompletionMode};
use anyhow::Result;
use chrono::{DateTime, Utc};
use gpui::SharedString;
use language_model::{LanguageModelToolResultContent, LanguageModelToolUseId, Role, TokenUsage};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub enum DetailedSummaryState {
#[default]
NotGenerated,
Generating,
Generated {
text: SharedString,
},
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
pub struct MessageId(pub usize);
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct SerializedThread {
pub version: String,
pub summary: SharedString,
pub updated_at: DateTime<Utc>,
pub messages: Vec<SerializedMessage>,
#[serde(default)]
pub initial_project_snapshot: Option<Arc<ProjectSnapshot>>,
#[serde(default)]
pub cumulative_token_usage: TokenUsage,
#[serde(default)]
pub request_token_usage: Vec<TokenUsage>,
#[serde(default)]
pub detailed_summary_state: DetailedSummaryState,
#[serde(default)]
pub model: Option<SerializedLanguageModel>,
#[serde(default)]
pub completion_mode: Option<CompletionMode>,
#[serde(default)]
pub tool_use_limit_reached: bool,
#[serde(default)]
pub profile: Option<AgentProfileId>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct SerializedLanguageModel {
pub provider: String,
pub model: String,
}
impl SerializedThread {
pub const VERSION: &'static str = "0.2.0";
pub fn from_json(json: &[u8]) -> Result<Self> {
let saved_thread_json = serde_json::from_slice::<serde_json::Value>(json)?;
match saved_thread_json.get("version") {
Some(serde_json::Value::String(version)) => match version.as_str() {
SerializedThreadV0_1_0::VERSION => {
let saved_thread =
serde_json::from_value::<SerializedThreadV0_1_0>(saved_thread_json)?;
Ok(saved_thread.upgrade())
}
SerializedThread::VERSION => Ok(serde_json::from_value::<SerializedThread>(
saved_thread_json,
)?),
_ => anyhow::bail!("unrecognized serialized thread version: {version:?}"),
},
None => {
let saved_thread =
serde_json::from_value::<LegacySerializedThread>(saved_thread_json)?;
Ok(saved_thread.upgrade())
}
version => anyhow::bail!("unrecognized serialized thread version: {version:?}"),
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct SerializedThreadV0_1_0(
// The structure did not change, so we are reusing the latest SerializedThread.
// When making the next version, make sure this points to SerializedThreadV0_2_0
SerializedThread,
);
impl SerializedThreadV0_1_0 {
pub const VERSION: &'static str = "0.1.0";
pub fn upgrade(self) -> SerializedThread {
debug_assert_eq!(SerializedThread::VERSION, "0.2.0");
let mut messages: Vec<SerializedMessage> = Vec::with_capacity(self.0.messages.len());
for message in self.0.messages {
if message.role == Role::User
&& !message.tool_results.is_empty()
&& let Some(last_message) = messages.last_mut()
{
debug_assert!(last_message.role == Role::Assistant);
last_message.tool_results = message.tool_results;
continue;
}
messages.push(message);
}
SerializedThread {
messages,
version: SerializedThread::VERSION.to_string(),
..self.0
}
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct SerializedMessage {
pub id: MessageId,
pub role: Role,
#[serde(default)]
pub segments: Vec<SerializedMessageSegment>,
#[serde(default)]
pub tool_uses: Vec<SerializedToolUse>,
#[serde(default)]
pub tool_results: Vec<SerializedToolResult>,
#[serde(default)]
pub context: String,
#[serde(default)]
pub creases: Vec<SerializedCrease>,
#[serde(default)]
pub is_hidden: bool,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type")]
pub enum SerializedMessageSegment {
#[serde(rename = "text")]
Text {
text: String,
},
#[serde(rename = "thinking")]
Thinking {
text: String,
#[serde(skip_serializing_if = "Option::is_none")]
signature: Option<String>,
},
RedactedThinking {
data: String,
},
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct SerializedToolUse {
pub id: LanguageModelToolUseId,
pub name: SharedString,
pub input: serde_json::Value,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct SerializedToolResult {
pub tool_use_id: LanguageModelToolUseId,
pub is_error: bool,
pub content: LanguageModelToolResultContent,
pub output: Option<serde_json::Value>,
}
#[derive(Serialize, Deserialize)]
struct LegacySerializedThread {
pub summary: SharedString,
pub updated_at: DateTime<Utc>,
pub messages: Vec<LegacySerializedMessage>,
#[serde(default)]
pub initial_project_snapshot: Option<Arc<ProjectSnapshot>>,
}
impl LegacySerializedThread {
pub fn upgrade(self) -> SerializedThread {
SerializedThread {
version: SerializedThread::VERSION.to_string(),
summary: self.summary,
updated_at: self.updated_at,
messages: self.messages.into_iter().map(|msg| msg.upgrade()).collect(),
initial_project_snapshot: self.initial_project_snapshot,
cumulative_token_usage: TokenUsage::default(),
request_token_usage: Vec::new(),
detailed_summary_state: DetailedSummaryState::default(),
model: None,
completion_mode: None,
tool_use_limit_reached: false,
profile: None,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
struct LegacySerializedMessage {
pub id: MessageId,
pub role: Role,
pub text: String,
#[serde(default)]
pub tool_uses: Vec<SerializedToolUse>,
#[serde(default)]
pub tool_results: Vec<SerializedToolResult>,
}
impl LegacySerializedMessage {
fn upgrade(self) -> SerializedMessage {
SerializedMessage {
id: self.id,
role: self.role,
segments: vec![SerializedMessageSegment::Text { text: self.text }],
tool_uses: self.tool_uses,
tool_results: self.tool_results,
context: String::new(),
creases: Vec::new(),
is_hidden: false,
}
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct SerializedCrease {
pub start: usize,
pub end: usize,
pub icon_path: SharedString,
pub label: SharedString,
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Utc;
use language_model::{Role, TokenUsage};
use pretty_assertions::assert_eq;
#[test]
fn test_legacy_serialized_thread_upgrade() {
let updated_at = Utc::now();
let legacy_thread = LegacySerializedThread {
summary: "Test conversation".into(),
updated_at,
messages: vec![LegacySerializedMessage {
id: MessageId(1),
role: Role::User,
text: "Hello, world!".to_string(),
tool_uses: vec![],
tool_results: vec![],
}],
initial_project_snapshot: None,
};
let upgraded = legacy_thread.upgrade();
assert_eq!(
upgraded,
SerializedThread {
summary: "Test conversation".into(),
updated_at,
messages: vec![SerializedMessage {
id: MessageId(1),
role: Role::User,
segments: vec![SerializedMessageSegment::Text {
text: "Hello, world!".to_string()
}],
tool_uses: vec![],
tool_results: vec![],
context: "".to_string(),
creases: vec![],
is_hidden: false
}],
version: SerializedThread::VERSION.to_string(),
initial_project_snapshot: None,
cumulative_token_usage: TokenUsage::default(),
request_token_usage: vec![],
detailed_summary_state: DetailedSummaryState::default(),
model: None,
completion_mode: None,
tool_use_limit_reached: false,
profile: None
}
)
}
#[test]
fn test_serialized_threadv0_1_0_upgrade() {
let updated_at = Utc::now();
let thread_v0_1_0 = SerializedThreadV0_1_0(SerializedThread {
summary: "Test conversation".into(),
updated_at,
messages: vec![
SerializedMessage {
id: MessageId(1),
role: Role::User,
segments: vec![SerializedMessageSegment::Text {
text: "Use tool_1".to_string(),
}],
tool_uses: vec![],
tool_results: vec![],
context: "".to_string(),
creases: vec![],
is_hidden: false,
},
SerializedMessage {
id: MessageId(2),
role: Role::Assistant,
segments: vec![SerializedMessageSegment::Text {
text: "I want to use a tool".to_string(),
}],
tool_uses: vec![SerializedToolUse {
id: "abc".into(),
name: "tool_1".into(),
input: serde_json::Value::Null,
}],
tool_results: vec![],
context: "".to_string(),
creases: vec![],
is_hidden: false,
},
SerializedMessage {
id: MessageId(1),
role: Role::User,
segments: vec![SerializedMessageSegment::Text {
text: "Here is the tool result".to_string(),
}],
tool_uses: vec![],
tool_results: vec![SerializedToolResult {
tool_use_id: "abc".into(),
is_error: false,
content: LanguageModelToolResultContent::Text("abcdef".into()),
output: Some(serde_json::Value::Null),
}],
context: "".to_string(),
creases: vec![],
is_hidden: false,
},
],
version: SerializedThreadV0_1_0::VERSION.to_string(),
initial_project_snapshot: None,
cumulative_token_usage: TokenUsage::default(),
request_token_usage: vec![],
detailed_summary_state: DetailedSummaryState::default(),
model: None,
completion_mode: None,
tool_use_limit_reached: false,
profile: None,
});
let upgraded = thread_v0_1_0.upgrade();
assert_eq!(
upgraded,
SerializedThread {
summary: "Test conversation".into(),
updated_at,
messages: vec![
SerializedMessage {
id: MessageId(1),
role: Role::User,
segments: vec![SerializedMessageSegment::Text {
text: "Use tool_1".to_string()
}],
tool_uses: vec![],
tool_results: vec![],
context: "".to_string(),
creases: vec![],
is_hidden: false
},
SerializedMessage {
id: MessageId(2),
role: Role::Assistant,
segments: vec![SerializedMessageSegment::Text {
text: "I want to use a tool".to_string(),
}],
tool_uses: vec![SerializedToolUse {
id: "abc".into(),
name: "tool_1".into(),
input: serde_json::Value::Null,
}],
tool_results: vec![SerializedToolResult {
tool_use_id: "abc".into(),
is_error: false,
content: LanguageModelToolResultContent::Text("abcdef".into()),
output: Some(serde_json::Value::Null),
}],
context: "".to_string(),
creases: vec![],
is_hidden: false,
},
],
version: SerializedThread::VERSION.to_string(),
initial_project_snapshot: None,
cumulative_token_usage: TokenUsage::default(),
request_token_usage: vec![],
detailed_summary_state: DetailedSummaryState::default(),
model: None,
completion_mode: None,
tool_use_limit_reached: false,
profile: None
}
)
}
}

View File

@@ -0,0 +1,3 @@
[The following is an auto-generated notification; do not reply]
These files have changed since the last read:

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,575 @@
use crate::{
thread::{MessageId, PromptId, ThreadId},
thread_store::SerializedMessage,
};
use agent_settings::CompletionMode;
use anyhow::Result;
use assistant_tool::{
AnyToolCard, Tool, ToolResultContent, ToolResultOutput, ToolUseStatus, ToolWorkingSet,
};
use collections::HashMap;
use futures::{FutureExt as _, future::Shared};
use gpui::{App, Entity, SharedString, Task, Window};
use icons::IconName;
use language_model::{
ConfiguredModel, LanguageModel, LanguageModelExt, LanguageModelRequest,
LanguageModelToolResult, LanguageModelToolResultContent, LanguageModelToolUse,
LanguageModelToolUseId, Role,
};
use project::Project;
use std::sync::Arc;
use util::truncate_lines_to_byte_limit;
#[derive(Debug)]
pub struct ToolUse {
pub id: LanguageModelToolUseId,
pub name: SharedString,
pub ui_text: SharedString,
pub status: ToolUseStatus,
pub input: serde_json::Value,
pub icon: icons::IconName,
pub needs_confirmation: bool,
}
pub struct ToolUseState {
tools: Entity<ToolWorkingSet>,
tool_uses_by_assistant_message: HashMap<MessageId, Vec<LanguageModelToolUse>>,
tool_results: HashMap<LanguageModelToolUseId, LanguageModelToolResult>,
pending_tool_uses_by_id: HashMap<LanguageModelToolUseId, PendingToolUse>,
tool_result_cards: HashMap<LanguageModelToolUseId, AnyToolCard>,
tool_use_metadata_by_id: HashMap<LanguageModelToolUseId, ToolUseMetadata>,
}
impl ToolUseState {
pub fn new(tools: Entity<ToolWorkingSet>) -> Self {
Self {
tools,
tool_uses_by_assistant_message: HashMap::default(),
tool_results: HashMap::default(),
pending_tool_uses_by_id: HashMap::default(),
tool_result_cards: HashMap::default(),
tool_use_metadata_by_id: HashMap::default(),
}
}
/// Constructs a [`ToolUseState`] from the given list of [`SerializedMessage`]s.
///
/// Accepts a function to filter the tools that should be used to populate the state.
///
/// If `window` is `None` (e.g., when in headless mode or when running evals),
/// tool cards won't be deserialized
pub fn from_serialized_messages(
tools: Entity<ToolWorkingSet>,
messages: &[SerializedMessage],
project: Entity<Project>,
window: Option<&mut Window>, // None in headless mode
cx: &mut App,
) -> Self {
let mut this = Self::new(tools);
let mut tool_names_by_id = HashMap::default();
let mut window = window;
for message in messages {
match message.role {
Role::Assistant => {
if !message.tool_uses.is_empty() {
let tool_uses = message
.tool_uses
.iter()
.map(|tool_use| LanguageModelToolUse {
id: tool_use.id.clone(),
name: tool_use.name.clone().into(),
raw_input: tool_use.input.to_string(),
input: tool_use.input.clone(),
is_input_complete: true,
})
.collect::<Vec<_>>();
tool_names_by_id.extend(
tool_uses
.iter()
.map(|tool_use| (tool_use.id.clone(), tool_use.name.clone())),
);
this.tool_uses_by_assistant_message
.insert(message.id, tool_uses);
for tool_result in &message.tool_results {
let tool_use_id = tool_result.tool_use_id.clone();
let Some(tool_use) = tool_names_by_id.get(&tool_use_id) else {
log::warn!("no tool name found for tool use: {tool_use_id:?}");
continue;
};
this.tool_results.insert(
tool_use_id.clone(),
LanguageModelToolResult {
tool_use_id: tool_use_id.clone(),
tool_name: tool_use.clone(),
is_error: tool_result.is_error,
content: tool_result.content.clone(),
output: tool_result.output.clone(),
},
);
if let Some(window) = &mut window
&& let Some(tool) = this.tools.read(cx).tool(tool_use, cx)
&& let Some(output) = tool_result.output.clone()
&& let Some(card) =
tool.deserialize_card(output, project.clone(), window, cx)
{
this.tool_result_cards.insert(tool_use_id, card);
}
}
}
}
Role::System | Role::User => {}
}
}
this
}
pub fn cancel_pending(&mut self) -> Vec<PendingToolUse> {
let mut canceled_tool_uses = Vec::new();
self.pending_tool_uses_by_id
.retain(|tool_use_id, tool_use| {
if matches!(tool_use.status, PendingToolUseStatus::Error { .. }) {
return true;
}
let content = "Tool canceled by user".into();
self.tool_results.insert(
tool_use_id.clone(),
LanguageModelToolResult {
tool_use_id: tool_use_id.clone(),
tool_name: tool_use.name.clone(),
content,
output: None,
is_error: true,
},
);
canceled_tool_uses.push(tool_use.clone());
false
});
canceled_tool_uses
}
pub fn pending_tool_uses(&self) -> Vec<&PendingToolUse> {
self.pending_tool_uses_by_id.values().collect()
}
pub fn tool_uses_for_message(
&self,
id: MessageId,
project: &Entity<Project>,
cx: &App,
) -> Vec<ToolUse> {
let Some(tool_uses_for_message) = &self.tool_uses_by_assistant_message.get(&id) else {
return Vec::new();
};
let mut tool_uses = Vec::new();
for tool_use in tool_uses_for_message.iter() {
let tool_result = self.tool_results.get(&tool_use.id);
let status = (|| {
if let Some(tool_result) = tool_result {
let content = tool_result
.content
.to_str()
.map(|str| str.to_owned().into())
.unwrap_or_default();
return if tool_result.is_error {
ToolUseStatus::Error(content)
} else {
ToolUseStatus::Finished(content)
};
}
if let Some(pending_tool_use) = self.pending_tool_uses_by_id.get(&tool_use.id) {
match pending_tool_use.status {
PendingToolUseStatus::Idle => ToolUseStatus::Pending,
PendingToolUseStatus::NeedsConfirmation { .. } => {
ToolUseStatus::NeedsConfirmation
}
PendingToolUseStatus::Running { .. } => ToolUseStatus::Running,
PendingToolUseStatus::Error(ref err) => {
ToolUseStatus::Error(err.clone().into())
}
PendingToolUseStatus::InputStillStreaming => {
ToolUseStatus::InputStillStreaming
}
}
} else {
ToolUseStatus::Pending
}
})();
let (icon, needs_confirmation) =
if let Some(tool) = self.tools.read(cx).tool(&tool_use.name, cx) {
(
tool.icon(),
tool.needs_confirmation(&tool_use.input, project, cx),
)
} else {
(IconName::Cog, false)
};
tool_uses.push(ToolUse {
id: tool_use.id.clone(),
name: tool_use.name.clone().into(),
ui_text: self.tool_ui_label(
&tool_use.name,
&tool_use.input,
tool_use.is_input_complete,
cx,
),
input: tool_use.input.clone(),
status,
icon,
needs_confirmation,
})
}
tool_uses
}
pub fn tool_ui_label(
&self,
tool_name: &str,
input: &serde_json::Value,
is_input_complete: bool,
cx: &App,
) -> SharedString {
if let Some(tool) = self.tools.read(cx).tool(tool_name, cx) {
if is_input_complete {
tool.ui_text(input).into()
} else {
tool.still_streaming_ui_text(input).into()
}
} else {
format!("Unknown tool {tool_name:?}").into()
}
}
pub fn tool_results_for_message(
&self,
assistant_message_id: MessageId,
) -> Vec<&LanguageModelToolResult> {
let Some(tool_uses) = self
.tool_uses_by_assistant_message
.get(&assistant_message_id)
else {
return Vec::new();
};
tool_uses
.iter()
.filter_map(|tool_use| self.tool_results.get(&tool_use.id))
.collect()
}
pub fn message_has_tool_results(&self, assistant_message_id: MessageId) -> bool {
self.tool_uses_by_assistant_message
.get(&assistant_message_id)
.is_some_and(|results| !results.is_empty())
}
pub fn tool_result(
&self,
tool_use_id: &LanguageModelToolUseId,
) -> Option<&LanguageModelToolResult> {
self.tool_results.get(tool_use_id)
}
pub fn tool_result_card(&self, tool_use_id: &LanguageModelToolUseId) -> Option<&AnyToolCard> {
self.tool_result_cards.get(tool_use_id)
}
pub fn insert_tool_result_card(
&mut self,
tool_use_id: LanguageModelToolUseId,
card: AnyToolCard,
) {
self.tool_result_cards.insert(tool_use_id, card);
}
pub fn request_tool_use(
&mut self,
assistant_message_id: MessageId,
tool_use: LanguageModelToolUse,
metadata: ToolUseMetadata,
cx: &App,
) -> Arc<str> {
let tool_uses = self
.tool_uses_by_assistant_message
.entry(assistant_message_id)
.or_default();
let mut existing_tool_use_found = false;
for existing_tool_use in tool_uses.iter_mut() {
if existing_tool_use.id == tool_use.id {
*existing_tool_use = tool_use.clone();
existing_tool_use_found = true;
}
}
if !existing_tool_use_found {
tool_uses.push(tool_use.clone());
}
let status = if tool_use.is_input_complete {
self.tool_use_metadata_by_id
.insert(tool_use.id.clone(), metadata);
PendingToolUseStatus::Idle
} else {
PendingToolUseStatus::InputStillStreaming
};
let ui_text: Arc<str> = self
.tool_ui_label(
&tool_use.name,
&tool_use.input,
tool_use.is_input_complete,
cx,
)
.into();
let may_perform_edits = self
.tools
.read(cx)
.tool(&tool_use.name, cx)
.is_some_and(|tool| tool.may_perform_edits());
self.pending_tool_uses_by_id.insert(
tool_use.id.clone(),
PendingToolUse {
assistant_message_id,
id: tool_use.id,
name: tool_use.name.clone(),
ui_text: ui_text.clone(),
input: tool_use.input,
may_perform_edits,
status,
},
);
ui_text
}
pub fn run_pending_tool(
&mut self,
tool_use_id: LanguageModelToolUseId,
ui_text: SharedString,
task: Task<()>,
) {
if let Some(tool_use) = self.pending_tool_uses_by_id.get_mut(&tool_use_id) {
tool_use.ui_text = ui_text.into();
tool_use.status = PendingToolUseStatus::Running {
_task: task.shared(),
};
}
}
pub fn confirm_tool_use(
&mut self,
tool_use_id: LanguageModelToolUseId,
ui_text: impl Into<Arc<str>>,
input: serde_json::Value,
request: Arc<LanguageModelRequest>,
tool: Arc<dyn Tool>,
) {
if let Some(tool_use) = self.pending_tool_uses_by_id.get_mut(&tool_use_id) {
let ui_text = ui_text.into();
tool_use.ui_text = ui_text.clone();
let confirmation = Confirmation {
tool_use_id,
input,
request,
tool,
ui_text,
};
tool_use.status = PendingToolUseStatus::NeedsConfirmation(Arc::new(confirmation));
}
}
pub fn insert_tool_output(
&mut self,
tool_use_id: LanguageModelToolUseId,
tool_name: Arc<str>,
output: Result<ToolResultOutput>,
configured_model: Option<&ConfiguredModel>,
completion_mode: CompletionMode,
) -> Option<PendingToolUse> {
let metadata = self.tool_use_metadata_by_id.remove(&tool_use_id);
telemetry::event!(
"Agent Tool Finished",
model = metadata
.as_ref()
.map(|metadata| metadata.model.telemetry_id()),
model_provider = metadata
.as_ref()
.map(|metadata| metadata.model.provider_id().to_string()),
thread_id = metadata.as_ref().map(|metadata| metadata.thread_id.clone()),
prompt_id = metadata.as_ref().map(|metadata| metadata.prompt_id.clone()),
tool_name,
success = output.is_ok()
);
match output {
Ok(output) => {
let tool_result = output.content;
const BYTES_PER_TOKEN_ESTIMATE: usize = 3;
let old_use = self.pending_tool_uses_by_id.remove(&tool_use_id);
// Protect from overly large output
let tool_output_limit = configured_model
.map(|model| {
model.model.max_token_count_for_mode(completion_mode.into()) as usize
* BYTES_PER_TOKEN_ESTIMATE
})
.unwrap_or(usize::MAX);
let content = match tool_result {
ToolResultContent::Text(text) => {
let text = if text.len() < tool_output_limit {
text
} else {
let truncated = truncate_lines_to_byte_limit(&text, tool_output_limit);
format!(
"Tool result too long. The first {} bytes:\n\n{}",
truncated.len(),
truncated
)
};
LanguageModelToolResultContent::Text(text.into())
}
ToolResultContent::Image(language_model_image) => {
if language_model_image.estimate_tokens() < tool_output_limit {
LanguageModelToolResultContent::Image(language_model_image)
} else {
self.tool_results.insert(
tool_use_id.clone(),
LanguageModelToolResult {
tool_use_id: tool_use_id.clone(),
tool_name,
content: "Tool responded with an image that would exceeded the remaining tokens".into(),
is_error: true,
output: None,
},
);
return old_use;
}
}
};
self.tool_results.insert(
tool_use_id.clone(),
LanguageModelToolResult {
tool_use_id: tool_use_id.clone(),
tool_name,
content,
is_error: false,
output: output.output,
},
);
old_use
}
Err(err) => {
self.tool_results.insert(
tool_use_id.clone(),
LanguageModelToolResult {
tool_use_id: tool_use_id.clone(),
tool_name,
content: LanguageModelToolResultContent::Text(err.to_string().into()),
is_error: true,
output: None,
},
);
if let Some(tool_use) = self.pending_tool_uses_by_id.get_mut(&tool_use_id) {
tool_use.status = PendingToolUseStatus::Error(err.to_string().into());
}
self.pending_tool_uses_by_id.get(&tool_use_id).cloned()
}
}
}
pub fn has_tool_results(&self, assistant_message_id: MessageId) -> bool {
self.tool_uses_by_assistant_message
.contains_key(&assistant_message_id)
}
pub fn tool_results(
&self,
assistant_message_id: MessageId,
) -> impl Iterator<Item = (&LanguageModelToolUse, Option<&LanguageModelToolResult>)> {
self.tool_uses_by_assistant_message
.get(&assistant_message_id)
.into_iter()
.flatten()
.map(|tool_use| (tool_use, self.tool_results.get(&tool_use.id)))
}
}
#[derive(Debug, Clone)]
pub struct PendingToolUse {
pub id: LanguageModelToolUseId,
/// The ID of the Assistant message in which the tool use was requested.
#[allow(unused)]
pub assistant_message_id: MessageId,
pub name: Arc<str>,
pub ui_text: Arc<str>,
pub input: serde_json::Value,
pub status: PendingToolUseStatus,
pub may_perform_edits: bool,
}
#[derive(Debug, Clone)]
pub struct Confirmation {
pub tool_use_id: LanguageModelToolUseId,
pub input: serde_json::Value,
pub ui_text: Arc<str>,
pub request: Arc<LanguageModelRequest>,
pub tool: Arc<dyn Tool>,
}
#[derive(Debug, Clone)]
pub enum PendingToolUseStatus {
InputStillStreaming,
Idle,
NeedsConfirmation(Arc<Confirmation>),
Running { _task: Shared<Task<()>> },
Error(#[allow(unused)] Arc<str>),
}
impl PendingToolUseStatus {
pub fn is_idle(&self) -> bool {
matches!(self, PendingToolUseStatus::Idle)
}
pub fn is_error(&self) -> bool {
matches!(self, PendingToolUseStatus::Error(_))
}
pub fn needs_confirmation(&self) -> bool {
matches!(self, PendingToolUseStatus::NeedsConfirmation { .. })
}
}
#[derive(Clone)]
pub struct ToolUseMetadata {
pub model: Arc<dyn LanguageModel>,
pub thread_id: ThreadId,
pub prompt_id: PromptId,
}

View File

@@ -1,94 +0,0 @@
mod context_server_registry;
mod copy_path_tool;
mod create_directory_tool;
mod delete_path_tool;
mod diagnostics_tool;
mod edit_file_tool;
mod fetch_tool;
mod find_path_tool;
mod grep_tool;
mod list_directory_tool;
mod move_path_tool;
mod now_tool;
mod open_tool;
mod read_file_tool;
mod terminal_tool;
mod thinking_tool;
mod web_search_tool;
use crate::AgentTool;
use language_model::{LanguageModelRequestTool, LanguageModelToolSchemaFormat};
pub use context_server_registry::*;
pub use copy_path_tool::*;
pub use create_directory_tool::*;
pub use delete_path_tool::*;
pub use diagnostics_tool::*;
pub use edit_file_tool::*;
pub use fetch_tool::*;
pub use find_path_tool::*;
pub use grep_tool::*;
pub use list_directory_tool::*;
pub use move_path_tool::*;
pub use now_tool::*;
pub use open_tool::*;
pub use read_file_tool::*;
pub use terminal_tool::*;
pub use thinking_tool::*;
pub use web_search_tool::*;
macro_rules! tools {
($($tool:ty),* $(,)?) => {
/// A list of all built-in tool names
pub fn supported_built_in_tool_names(provider: Option<language_model::LanguageModelProviderId>) -> impl Iterator<Item = String> {
[
$(
(if let Some(provider) = provider.as_ref() {
<$tool>::supports_provider(provider)
} else {
true
})
.then(|| <$tool>::name().to_string()),
)*
]
.into_iter()
.flatten()
}
/// A list of all built-in tools
pub fn built_in_tools() -> impl Iterator<Item = LanguageModelRequestTool> {
fn language_model_tool<T: AgentTool>() -> LanguageModelRequestTool {
LanguageModelRequestTool {
name: T::name().to_string(),
description: T::description().to_string(),
input_schema: T::input_schema(LanguageModelToolSchemaFormat::JsonSchema).to_value(),
}
}
[
$(
language_model_tool::<$tool>(),
)*
]
.into_iter()
}
};
}
tools! {
CopyPathTool,
CreateDirectoryTool,
DeletePathTool,
DiagnosticsTool,
EditFileTool,
FetchTool,
FindPathTool,
GrepTool,
ListDirectoryTool,
MovePathTool,
NowTool,
OpenTool,
ReadFileTool,
TerminalTool,
ThinkingTool,
WebSearchTool,
}

102
crates/agent2/Cargo.toml Normal file
View File

@@ -0,0 +1,102 @@
[package]
name = "agent2"
version = "0.1.0"
edition.workspace = true
publish.workspace = true
license = "GPL-3.0-or-later"
[lib]
path = "src/agent2.rs"
[features]
test-support = ["db/test-support"]
e2e = []
[lints]
workspace = true
[dependencies]
acp_thread.workspace = true
action_log.workspace = true
agent.workspace = true
agent-client-protocol.workspace = true
agent_servers.workspace = true
agent_settings.workspace = true
anyhow.workspace = true
assistant_context.workspace = true
assistant_tool.workspace = true
assistant_tools.workspace = true
chrono.workspace = true
client.workspace = true
cloud_llm_client.workspace = true
collections.workspace = true
context_server.workspace = true
db.workspace = true
fs.workspace = true
futures.workspace = true
git.workspace = true
gpui.workspace = true
handlebars = { workspace = true, features = ["rust-embed"] }
html_to_markdown.workspace = true
http_client.workspace = true
indoc.workspace = true
itertools.workspace = true
language.workspace = true
language_model.workspace = true
language_models.workspace = true
log.workspace = true
open.workspace = true
parking_lot.workspace = true
paths.workspace = true
project.workspace = true
prompt_store.workspace = true
rust-embed.workspace = true
schemars.workspace = true
serde.workspace = true
serde_json.workspace = true
settings.workspace = true
smol.workspace = true
sqlez.workspace = true
task.workspace = true
telemetry.workspace = true
terminal.workspace = true
thiserror.workspace = true
text.workspace = true
ui.workspace = true
util.workspace = true
uuid.workspace = true
watch.workspace = true
web_search.workspace = true
workspace-hack.workspace = true
zed_env_vars.workspace = true
zstd.workspace = true
[dev-dependencies]
agent = { workspace = true, "features" = ["test-support"] }
agent_servers = { workspace = true, "features" = ["test-support"] }
assistant_context = { workspace = true, "features" = ["test-support"] }
ctor.workspace = true
client = { workspace = true, "features" = ["test-support"] }
clock = { workspace = true, "features" = ["test-support"] }
context_server = { workspace = true, "features" = ["test-support"] }
db = { workspace = true, "features" = ["test-support"] }
editor = { workspace = true, "features" = ["test-support"] }
env_logger.workspace = true
fs = { workspace = true, "features" = ["test-support"] }
git = { workspace = true, "features" = ["test-support"] }
gpui = { workspace = true, "features" = ["test-support"] }
gpui_tokio.workspace = true
language = { workspace = true, "features" = ["test-support"] }
language_model = { workspace = true, "features" = ["test-support"] }
lsp = { workspace = true, "features" = ["test-support"] }
pretty_assertions.workspace = true
project = { workspace = true, "features" = ["test-support"] }
reqwest_client.workspace = true
settings = { workspace = true, "features" = ["test-support"] }
tempfile.workspace = true
terminal = { workspace = true, "features" = ["test-support"] }
theme = { workspace = true, "features" = ["test-support"] }
tree-sitter-rust.workspace = true
unindent = { workspace = true }
worktree = { workspace = true, "features" = ["test-support"] }
zlog.workspace = true

1588
crates/agent2/src/agent.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,19 @@
mod agent;
mod db;
mod history_store;
mod native_agent_server;
mod templates;
mod thread;
mod tool_schema;
mod tools;
#[cfg(test)]
mod tests;
pub use agent::*;
pub use db::*;
pub use history_store::*;
pub use native_agent_server::NativeAgentServer;
pub use templates::*;
pub use thread::*;
pub use tools::*;

View File

@@ -1,5 +1,6 @@
use crate::{AgentMessage, AgentMessageContent, UserMessage, UserMessageContent}; use crate::{AgentMessage, AgentMessageContent, UserMessage, UserMessageContent};
use acp_thread::UserMessageId; use acp_thread::UserMessageId;
use agent::{thread::DetailedSummaryState, thread_store};
use agent_client_protocol as acp; use agent_client_protocol as acp;
use agent_settings::{AgentProfileId, CompletionMode}; use agent_settings::{AgentProfileId, CompletionMode};
use anyhow::{Result, anyhow}; use anyhow::{Result, anyhow};
@@ -20,8 +21,8 @@ use ui::{App, SharedString};
use zed_env_vars::ZED_STATELESS; use zed_env_vars::ZED_STATELESS;
pub type DbMessage = crate::Message; pub type DbMessage = crate::Message;
pub type DbSummary = crate::legacy_thread::DetailedSummaryState; pub type DbSummary = DetailedSummaryState;
pub type DbLanguageModel = crate::legacy_thread::SerializedLanguageModel; pub type DbLanguageModel = thread_store::SerializedLanguageModel;
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DbThreadMetadata { pub struct DbThreadMetadata {
@@ -39,7 +40,7 @@ pub struct DbThread {
#[serde(default)] #[serde(default)]
pub detailed_summary: Option<SharedString>, pub detailed_summary: Option<SharedString>,
#[serde(default)] #[serde(default)]
pub initial_project_snapshot: Option<Arc<crate::ProjectSnapshot>>, pub initial_project_snapshot: Option<Arc<agent::thread::ProjectSnapshot>>,
#[serde(default)] #[serde(default)]
pub cumulative_token_usage: language_model::TokenUsage, pub cumulative_token_usage: language_model::TokenUsage,
#[serde(default)] #[serde(default)]
@@ -60,17 +61,13 @@ impl DbThread {
match saved_thread_json.get("version") { match saved_thread_json.get("version") {
Some(serde_json::Value::String(version)) => match version.as_str() { Some(serde_json::Value::String(version)) => match version.as_str() {
Self::VERSION => Ok(serde_json::from_value(saved_thread_json)?), Self::VERSION => Ok(serde_json::from_value(saved_thread_json)?),
_ => Self::upgrade_from_agent_1(crate::legacy_thread::SerializedThread::from_json( _ => Self::upgrade_from_agent_1(agent::SerializedThread::from_json(json)?),
json,
)?),
}, },
_ => { _ => Self::upgrade_from_agent_1(agent::SerializedThread::from_json(json)?),
Self::upgrade_from_agent_1(crate::legacy_thread::SerializedThread::from_json(json)?)
}
} }
} }
fn upgrade_from_agent_1(thread: crate::legacy_thread::SerializedThread) -> Result<Self> { fn upgrade_from_agent_1(thread: agent::SerializedThread) -> Result<Self> {
let mut messages = Vec::new(); let mut messages = Vec::new();
let mut request_token_usage = HashMap::default(); let mut request_token_usage = HashMap::default();
@@ -83,19 +80,14 @@ impl DbThread {
// Convert segments to content // Convert segments to content
for segment in msg.segments { for segment in msg.segments {
match segment { match segment {
crate::legacy_thread::SerializedMessageSegment::Text { text } => { thread_store::SerializedMessageSegment::Text { text } => {
content.push(UserMessageContent::Text(text)); content.push(UserMessageContent::Text(text));
} }
crate::legacy_thread::SerializedMessageSegment::Thinking { thread_store::SerializedMessageSegment::Thinking { text, .. } => {
text,
..
} => {
// User messages don't have thinking segments, but handle gracefully // User messages don't have thinking segments, but handle gracefully
content.push(UserMessageContent::Text(text)); content.push(UserMessageContent::Text(text));
} }
crate::legacy_thread::SerializedMessageSegment::RedactedThinking { thread_store::SerializedMessageSegment::RedactedThinking { .. } => {
..
} => {
// User messages don't have redacted thinking, skip. // User messages don't have redacted thinking, skip.
} }
} }
@@ -121,18 +113,16 @@ impl DbThread {
// Convert segments to content // Convert segments to content
for segment in msg.segments { for segment in msg.segments {
match segment { match segment {
crate::legacy_thread::SerializedMessageSegment::Text { text } => { thread_store::SerializedMessageSegment::Text { text } => {
content.push(AgentMessageContent::Text(text)); content.push(AgentMessageContent::Text(text));
} }
crate::legacy_thread::SerializedMessageSegment::Thinking { thread_store::SerializedMessageSegment::Thinking {
text, text,
signature, signature,
} => { } => {
content.push(AgentMessageContent::Thinking { text, signature }); content.push(AgentMessageContent::Thinking { text, signature });
} }
crate::legacy_thread::SerializedMessageSegment::RedactedThinking { thread_store::SerializedMessageSegment::RedactedThinking { data } => {
data,
} => {
content.push(AgentMessageContent::RedactedThinking(data)); content.push(AgentMessageContent::RedactedThinking(data));
} }
} }
@@ -197,9 +187,10 @@ impl DbThread {
messages, messages,
updated_at: thread.updated_at, updated_at: thread.updated_at,
detailed_summary: match thread.detailed_summary_state { detailed_summary: match thread.detailed_summary_state {
crate::legacy_thread::DetailedSummaryState::NotGenerated DetailedSummaryState::NotGenerated | DetailedSummaryState::Generating { .. } => {
| crate::legacy_thread::DetailedSummaryState::Generating => None, None
crate::legacy_thread::DetailedSummaryState::Generated { text, .. } => Some(text), }
DetailedSummaryState::Generated { text, .. } => Some(text),
}, },
initial_project_snapshot: thread.initial_project_snapshot, initial_project_snapshot: thread.initial_project_snapshot,
cumulative_token_usage: thread.cumulative_token_usage, cumulative_token_usage: thread.cumulative_token_usage,
@@ -423,3 +414,84 @@ impl ThreadsDatabase {
}) })
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use agent::MessageSegment;
use agent::context::LoadedContext;
use client::Client;
use fs::{FakeFs, Fs};
use gpui::AppContext;
use gpui::TestAppContext;
use http_client::FakeHttpClient;
use language_model::Role;
use project::Project;
use settings::SettingsStore;
fn init_test(fs: Arc<dyn Fs>, cx: &mut TestAppContext) {
env_logger::try_init().ok();
cx.update(|cx| {
let settings_store = SettingsStore::test(cx);
cx.set_global(settings_store);
Project::init_settings(cx);
language::init(cx);
let http_client = FakeHttpClient::with_404_response();
let clock = Arc::new(clock::FakeSystemClock::new());
let client = Client::new(clock, http_client, cx);
agent::init(fs, cx);
agent_settings::init(cx);
language_model::init(client, cx);
});
}
#[gpui::test]
async fn test_retrieving_old_thread(cx: &mut TestAppContext) {
let fs = FakeFs::new(cx.executor());
init_test(fs.clone(), cx);
let project = Project::test(fs, [], cx).await;
// Save a thread using the old agent.
let thread_store = cx.new(|cx| agent::ThreadStore::fake(project, cx));
let thread = thread_store.update(cx, |thread_store, cx| thread_store.create_thread(cx));
thread.update(cx, |thread, cx| {
thread.insert_message(
Role::User,
vec![MessageSegment::Text("Hey!".into())],
LoadedContext::default(),
vec![],
false,
cx,
);
thread.insert_message(
Role::Assistant,
vec![MessageSegment::Text("How're you doing?".into())],
LoadedContext::default(),
vec![],
false,
cx,
)
});
thread_store
.update(cx, |thread_store, cx| thread_store.save_thread(&thread, cx))
.await
.unwrap();
// Open that same thread using the new agent.
let db = cx.update(ThreadsDatabase::connect).await.unwrap();
let threads = db.list_threads().await.unwrap();
assert_eq!(threads.len(), 1);
let thread = db
.load_thread(threads[0].id.clone())
.await
.unwrap()
.unwrap();
assert_eq!(thread.messages[0].to_markdown(), "## User\n\nHey!\n");
assert_eq!(
thread.messages[1].to_markdown(),
"## Assistant\n\nHow're you doing?\n"
);
}
}

View File

@@ -0,0 +1,357 @@
use crate::{DbThreadMetadata, ThreadsDatabase};
use acp_thread::MentionUri;
use agent_client_protocol as acp;
use anyhow::{Context as _, Result, anyhow};
use assistant_context::{AssistantContext, SavedContextMetadata};
use chrono::{DateTime, Utc};
use db::kvp::KEY_VALUE_STORE;
use gpui::{App, AsyncApp, Entity, SharedString, Task, prelude::*};
use itertools::Itertools;
use paths::contexts_dir;
use serde::{Deserialize, Serialize};
use std::{collections::VecDeque, path::Path, sync::Arc, time::Duration};
use ui::ElementId;
use util::ResultExt as _;
const MAX_RECENTLY_OPENED_ENTRIES: usize = 6;
const RECENTLY_OPENED_THREADS_KEY: &str = "recent-agent-threads";
const SAVE_RECENTLY_OPENED_ENTRIES_DEBOUNCE: Duration = Duration::from_millis(50);
const DEFAULT_TITLE: &SharedString = &SharedString::new_static("New Thread");
#[derive(Clone, Debug)]
pub enum HistoryEntry {
AcpThread(DbThreadMetadata),
TextThread(SavedContextMetadata),
}
impl HistoryEntry {
pub fn updated_at(&self) -> DateTime<Utc> {
match self {
HistoryEntry::AcpThread(thread) => thread.updated_at,
HistoryEntry::TextThread(context) => context.mtime.to_utc(),
}
}
pub fn id(&self) -> HistoryEntryId {
match self {
HistoryEntry::AcpThread(thread) => HistoryEntryId::AcpThread(thread.id.clone()),
HistoryEntry::TextThread(context) => HistoryEntryId::TextThread(context.path.clone()),
}
}
pub fn mention_uri(&self) -> MentionUri {
match self {
HistoryEntry::AcpThread(thread) => MentionUri::Thread {
id: thread.id.clone(),
name: thread.title.to_string(),
},
HistoryEntry::TextThread(context) => MentionUri::TextThread {
path: context.path.as_ref().to_owned(),
name: context.title.to_string(),
},
}
}
pub fn title(&self) -> &SharedString {
match self {
HistoryEntry::AcpThread(thread) if thread.title.is_empty() => DEFAULT_TITLE,
HistoryEntry::AcpThread(thread) => &thread.title,
HistoryEntry::TextThread(context) => &context.title,
}
}
}
/// Generic identifier for a history entry.
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub enum HistoryEntryId {
AcpThread(acp::SessionId),
TextThread(Arc<Path>),
}
impl Into<ElementId> for HistoryEntryId {
fn into(self) -> ElementId {
match self {
HistoryEntryId::AcpThread(session_id) => ElementId::Name(session_id.0.into()),
HistoryEntryId::TextThread(path) => ElementId::Path(path),
}
}
}
#[derive(Serialize, Deserialize, Debug)]
enum SerializedRecentOpen {
AcpThread(String),
TextThread(String),
}
pub struct HistoryStore {
threads: Vec<DbThreadMetadata>,
entries: Vec<HistoryEntry>,
context_store: Entity<assistant_context::ContextStore>,
recently_opened_entries: VecDeque<HistoryEntryId>,
_subscriptions: Vec<gpui::Subscription>,
_save_recently_opened_entries_task: Task<()>,
}
impl HistoryStore {
pub fn new(
context_store: Entity<assistant_context::ContextStore>,
cx: &mut Context<Self>,
) -> Self {
let subscriptions = vec![cx.observe(&context_store, |this, _, cx| this.update_entries(cx))];
cx.spawn(async move |this, cx| {
let entries = Self::load_recently_opened_entries(cx).await;
this.update(cx, |this, cx| {
if let Some(entries) = entries.log_err() {
this.recently_opened_entries = entries;
}
this.reload(cx);
})
.ok();
})
.detach();
Self {
context_store,
recently_opened_entries: VecDeque::default(),
threads: Vec::default(),
entries: Vec::default(),
_subscriptions: subscriptions,
_save_recently_opened_entries_task: Task::ready(()),
}
}
pub fn thread_from_session_id(&self, session_id: &acp::SessionId) -> Option<&DbThreadMetadata> {
self.threads.iter().find(|thread| &thread.id == session_id)
}
pub fn delete_thread(
&mut self,
id: acp::SessionId,
cx: &mut Context<Self>,
) -> Task<Result<()>> {
let database_future = ThreadsDatabase::connect(cx);
cx.spawn(async move |this, cx| {
let database = database_future.await.map_err(|err| anyhow!(err))?;
database.delete_thread(id.clone()).await?;
this.update(cx, |this, cx| this.reload(cx))
})
}
pub fn delete_text_thread(
&mut self,
path: Arc<Path>,
cx: &mut Context<Self>,
) -> Task<Result<()>> {
self.context_store.update(cx, |context_store, cx| {
context_store.delete_local_context(path, cx)
})
}
pub fn load_text_thread(
&self,
path: Arc<Path>,
cx: &mut Context<Self>,
) -> Task<Result<Entity<AssistantContext>>> {
self.context_store.update(cx, |context_store, cx| {
context_store.open_local_context(path, cx)
})
}
pub fn reload(&self, cx: &mut Context<Self>) {
let database_future = ThreadsDatabase::connect(cx);
cx.spawn(async move |this, cx| {
let threads = database_future
.await
.map_err(|err| anyhow!(err))?
.list_threads()
.await?;
this.update(cx, |this, cx| {
if this.recently_opened_entries.len() < MAX_RECENTLY_OPENED_ENTRIES {
for thread in threads
.iter()
.take(MAX_RECENTLY_OPENED_ENTRIES - this.recently_opened_entries.len())
.rev()
{
this.push_recently_opened_entry(
HistoryEntryId::AcpThread(thread.id.clone()),
cx,
)
}
}
this.threads = threads;
this.update_entries(cx);
})
})
.detach_and_log_err(cx);
}
fn update_entries(&mut self, cx: &mut Context<Self>) {
#[cfg(debug_assertions)]
if std::env::var("ZED_SIMULATE_NO_THREAD_HISTORY").is_ok() {
return;
}
let mut history_entries = Vec::new();
history_entries.extend(self.threads.iter().cloned().map(HistoryEntry::AcpThread));
history_entries.extend(
self.context_store
.read(cx)
.unordered_contexts()
.cloned()
.map(HistoryEntry::TextThread),
);
history_entries.sort_unstable_by_key(|entry| std::cmp::Reverse(entry.updated_at()));
self.entries = history_entries;
cx.notify()
}
pub fn is_empty(&self, _cx: &App) -> bool {
self.entries.is_empty()
}
pub fn recently_opened_entries(&self, cx: &App) -> Vec<HistoryEntry> {
#[cfg(debug_assertions)]
if std::env::var("ZED_SIMULATE_NO_THREAD_HISTORY").is_ok() {
return Vec::new();
}
let thread_entries = self.threads.iter().flat_map(|thread| {
self.recently_opened_entries
.iter()
.enumerate()
.flat_map(|(index, entry)| match entry {
HistoryEntryId::AcpThread(id) if &thread.id == id => {
Some((index, HistoryEntry::AcpThread(thread.clone())))
}
_ => None,
})
});
let context_entries =
self.context_store
.read(cx)
.unordered_contexts()
.flat_map(|context| {
self.recently_opened_entries
.iter()
.enumerate()
.flat_map(|(index, entry)| match entry {
HistoryEntryId::TextThread(path) if &context.path == path => {
Some((index, HistoryEntry::TextThread(context.clone())))
}
_ => None,
})
});
thread_entries
.chain(context_entries)
// optimization to halt iteration early
.take(self.recently_opened_entries.len())
.sorted_unstable_by_key(|(index, _)| *index)
.map(|(_, entry)| entry)
.collect()
}
fn save_recently_opened_entries(&mut self, cx: &mut Context<Self>) {
let serialized_entries = self
.recently_opened_entries
.iter()
.filter_map(|entry| match entry {
HistoryEntryId::TextThread(path) => path.file_name().map(|file| {
SerializedRecentOpen::TextThread(file.to_string_lossy().into_owned())
}),
HistoryEntryId::AcpThread(id) => {
Some(SerializedRecentOpen::AcpThread(id.to_string()))
}
})
.collect::<Vec<_>>();
self._save_recently_opened_entries_task = cx.spawn(async move |_, cx| {
let content = serde_json::to_string(&serialized_entries).unwrap();
cx.background_executor()
.timer(SAVE_RECENTLY_OPENED_ENTRIES_DEBOUNCE)
.await;
if cfg!(any(feature = "test-support", test)) {
return;
}
KEY_VALUE_STORE
.write_kvp(RECENTLY_OPENED_THREADS_KEY.to_owned(), content)
.await
.log_err();
});
}
fn load_recently_opened_entries(cx: &AsyncApp) -> Task<Result<VecDeque<HistoryEntryId>>> {
cx.background_spawn(async move {
if cfg!(any(feature = "test-support", test)) {
anyhow::bail!("history store does not persist in tests");
}
let json = KEY_VALUE_STORE
.read_kvp(RECENTLY_OPENED_THREADS_KEY)?
.unwrap_or("[]".to_string());
let entries = serde_json::from_str::<Vec<SerializedRecentOpen>>(&json)
.context("deserializing persisted agent panel navigation history")?
.into_iter()
.take(MAX_RECENTLY_OPENED_ENTRIES)
.flat_map(|entry| match entry {
SerializedRecentOpen::AcpThread(id) => Some(HistoryEntryId::AcpThread(
acp::SessionId(id.as_str().into()),
)),
SerializedRecentOpen::TextThread(file_name) => Some(
HistoryEntryId::TextThread(contexts_dir().join(file_name).into()),
),
})
.collect();
Ok(entries)
})
}
pub fn push_recently_opened_entry(&mut self, entry: HistoryEntryId, cx: &mut Context<Self>) {
self.recently_opened_entries
.retain(|old_entry| old_entry != &entry);
self.recently_opened_entries.push_front(entry);
self.recently_opened_entries
.truncate(MAX_RECENTLY_OPENED_ENTRIES);
self.save_recently_opened_entries(cx);
}
pub fn remove_recently_opened_thread(&mut self, id: acp::SessionId, cx: &mut Context<Self>) {
self.recently_opened_entries.retain(
|entry| !matches!(entry, HistoryEntryId::AcpThread(thread_id) if thread_id == &id),
);
self.save_recently_opened_entries(cx);
}
pub fn replace_recently_opened_text_thread(
&mut self,
old_path: &Path,
new_path: &Arc<Path>,
cx: &mut Context<Self>,
) {
for entry in &mut self.recently_opened_entries {
match entry {
HistoryEntryId::TextThread(path) if path.as_ref() == old_path => {
*entry = HistoryEntryId::TextThread(new_path.clone());
break;
}
_ => {}
}
}
self.save_recently_opened_entries(cx);
}
pub fn remove_recently_opened_entry(&mut self, entry: &HistoryEntryId, cx: &mut Context<Self>) {
self.recently_opened_entries
.retain(|old_entry| old_entry != entry);
self.save_recently_opened_entries(cx);
}
pub fn entries(&self) -> impl Iterator<Item = HistoryEntry> {
self.entries.iter().cloned()
}
}

View File

@@ -81,7 +81,7 @@ impl AgentServer for NativeAgentServer {
mod tests { mod tests {
use super::*; use super::*;
use assistant_text_thread::TextThreadStore; use assistant_context::ContextStore;
use gpui::AppContext; use gpui::AppContext;
agent_servers::e2e_tests::common_e2e_tests!( agent_servers::e2e_tests::common_e2e_tests!(
@@ -116,9 +116,8 @@ mod tests {
}); });
let history = cx.update(|cx| { let history = cx.update(|cx| {
let text_thread_store = let context_store = cx.new(move |cx| ContextStore::fake(project.clone(), cx));
cx.new(move |cx| TextThreadStore::fake(project.clone(), cx)); cx.new(move |cx| HistoryStore::new(context_store, cx))
cx.new(move |cx| HistoryStore::new(text_thread_store, cx))
}); });
NativeAgentServer::new(fs.clone(), history) NativeAgentServer::new(fs.clone(), history)

View File

@@ -975,9 +975,9 @@ async fn test_mcp_tools(cx: &mut TestAppContext) {
vec![context_server::types::Tool { vec![context_server::types::Tool {
name: "echo".into(), name: "echo".into(),
description: None, description: None,
input_schema: serde_json::to_value(EchoTool::input_schema( input_schema: serde_json::to_value(
LanguageModelToolSchemaFormat::JsonSchema, EchoTool.input_schema(LanguageModelToolSchemaFormat::JsonSchema),
)) )
.unwrap(), .unwrap(),
output_schema: None, output_schema: None,
annotations: None, annotations: None,
@@ -1149,9 +1149,9 @@ async fn test_mcp_tool_truncation(cx: &mut TestAppContext) {
context_server::types::Tool { context_server::types::Tool {
name: "echo".into(), // Conflicts with native EchoTool name: "echo".into(), // Conflicts with native EchoTool
description: None, description: None,
input_schema: serde_json::to_value(EchoTool::input_schema( input_schema: serde_json::to_value(
LanguageModelToolSchemaFormat::JsonSchema, EchoTool.input_schema(LanguageModelToolSchemaFormat::JsonSchema),
)) )
.unwrap(), .unwrap(),
output_schema: None, output_schema: None,
annotations: None, annotations: None,
@@ -1174,9 +1174,9 @@ async fn test_mcp_tool_truncation(cx: &mut TestAppContext) {
context_server::types::Tool { context_server::types::Tool {
name: "echo".into(), // Also conflicts with native EchoTool name: "echo".into(), // Also conflicts with native EchoTool
description: None, description: None,
input_schema: serde_json::to_value(EchoTool::input_schema( input_schema: serde_json::to_value(
LanguageModelToolSchemaFormat::JsonSchema, EchoTool.input_schema(LanguageModelToolSchemaFormat::JsonSchema),
)) )
.unwrap(), .unwrap(),
output_schema: None, output_schema: None,
annotations: None, annotations: None,
@@ -1834,9 +1834,8 @@ async fn test_agent_connection(cx: &mut TestAppContext) {
fake_fs.insert_tree(path!("/test"), json!({})).await; fake_fs.insert_tree(path!("/test"), json!({})).await;
let project = Project::test(fake_fs.clone(), [Path::new("/test")], cx).await; let project = Project::test(fake_fs.clone(), [Path::new("/test")], cx).await;
let cwd = Path::new("/test"); let cwd = Path::new("/test");
let text_thread_store = let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
cx.new(|cx| assistant_text_thread::TextThreadStore::fake(project.clone(), cx)); let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx));
// Create agent and connection // Create agent and connection
let agent = NativeAgent::new( let agent = NativeAgent::new(
@@ -1865,7 +1864,7 @@ async fn test_agent_connection(cx: &mut TestAppContext) {
let selector_opt = connection.model_selector(&session_id); let selector_opt = connection.model_selector(&session_id);
assert!( assert!(
selector_opt.is_some(), selector_opt.is_some(),
"agent should always support ModelSelector" "agent2 should always support ModelSelector"
); );
let selector = selector_opt.unwrap(); let selector = selector_opt.unwrap();
@@ -1996,7 +1995,7 @@ async fn test_tool_updates_to_completion(cx: &mut TestAppContext) {
locations: vec![], locations: vec![],
raw_input: Some(json!({})), raw_input: Some(json!({})),
raw_output: None, raw_output: None,
meta: Some(json!({ "tool_name": "thinking" })), meta: None,
} }
); );
let update = expect_tool_call_update_fields(&mut events).await; let update = expect_tool_call_update_fields(&mut events).await;

2663
crates/agent2/src/thread.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,43 @@
use language_model::LanguageModelToolSchemaFormat;
use schemars::{
JsonSchema, Schema,
generate::SchemaSettings,
transform::{Transform, transform_subschemas},
};
pub(crate) fn root_schema_for<T: JsonSchema>(format: LanguageModelToolSchemaFormat) -> Schema {
let mut generator = match format {
LanguageModelToolSchemaFormat::JsonSchema => SchemaSettings::draft07().into_generator(),
LanguageModelToolSchemaFormat::JsonSchemaSubset => SchemaSettings::openapi3()
.with(|settings| {
settings.meta_schema = None;
settings.inline_subschemas = true;
})
.with_transform(ToJsonSchemaSubsetTransform)
.into_generator(),
};
generator.root_schema_for::<T>()
}
#[derive(Debug, Clone)]
struct ToJsonSchemaSubsetTransform;
impl Transform for ToJsonSchemaSubsetTransform {
fn transform(&mut self, schema: &mut Schema) {
// Ensure that the type field is not an array, this happens when we use
// Option<T>, the type will be [T, "null"].
if let Some(type_field) = schema.get_mut("type")
&& let Some(types) = type_field.as_array()
&& let Some(first_type) = types.first()
{
*type_field = first_type.clone();
}
// oneOf is not supported, use anyOf instead
if let Some(one_of) = schema.remove("oneOf") {
schema.insert("anyOf".to_string(), one_of);
}
transform_subschemas(self, schema);
}
}

View File

@@ -0,0 +1,60 @@
mod context_server_registry;
mod copy_path_tool;
mod create_directory_tool;
mod delete_path_tool;
mod diagnostics_tool;
mod edit_file_tool;
mod fetch_tool;
mod find_path_tool;
mod grep_tool;
mod list_directory_tool;
mod move_path_tool;
mod now_tool;
mod open_tool;
mod read_file_tool;
mod terminal_tool;
mod thinking_tool;
mod web_search_tool;
/// A list of all built in tool names, for use in deduplicating MCP tool names
pub fn default_tool_names() -> impl Iterator<Item = &'static str> {
[
CopyPathTool::name(),
CreateDirectoryTool::name(),
DeletePathTool::name(),
DiagnosticsTool::name(),
EditFileTool::name(),
FetchTool::name(),
FindPathTool::name(),
GrepTool::name(),
ListDirectoryTool::name(),
MovePathTool::name(),
NowTool::name(),
OpenTool::name(),
ReadFileTool::name(),
TerminalTool::name(),
ThinkingTool::name(),
WebSearchTool::name(),
]
.into_iter()
}
pub use context_server_registry::*;
pub use copy_path_tool::*;
pub use create_directory_tool::*;
pub use delete_path_tool::*;
pub use diagnostics_tool::*;
pub use edit_file_tool::*;
pub use fetch_tool::*;
pub use find_path_tool::*;
pub use grep_tool::*;
pub use list_directory_tool::*;
pub use move_path_tool::*;
pub use now_tool::*;
pub use open_tool::*;
pub use read_file_tool::*;
pub use terminal_tool::*;
pub use thinking_tool::*;
pub use web_search_tool::*;
use crate::AgentTool;

View File

@@ -32,17 +32,6 @@ impl ContextServerRegistry {
this this
} }
pub fn tools_for_server(
&self,
server_id: &ContextServerId,
) -> impl Iterator<Item = &Arc<dyn AnyAgentTool>> {
self.registered_servers
.get(server_id)
.map(|server| server.tools.values())
.into_iter()
.flatten()
}
pub fn servers( pub fn servers(
&self, &self,
) -> impl Iterator< ) -> impl Iterator<
@@ -165,7 +154,7 @@ impl AnyAgentTool for ContextServerTool {
format: language_model::LanguageModelToolSchemaFormat, format: language_model::LanguageModelToolSchemaFormat,
) -> Result<serde_json::Value> { ) -> Result<serde_json::Value> {
let mut schema = self.tool.input_schema.clone(); let mut schema = self.tool.input_schema.clone();
crate::tool_schema::adapt_schema_to_format(&mut schema, format)?; assistant_tool::adapt_schema_to_format(&mut schema, format)?;
Ok(match schema { Ok(match schema {
serde_json::Value::Null => { serde_json::Value::Null => {
serde_json::json!({ "type": "object", "properties": [] }) serde_json::json!({ "type": "object", "properties": [] })

View File

@@ -1,10 +1,8 @@
use crate::{ use crate::{AgentTool, Thread, ToolCallEventStream};
AgentTool, Templates, Thread, ToolCallEventStream,
edit_agent::{EditAgent, EditAgentOutput, EditAgentOutputEvent, EditFormat},
};
use acp_thread::Diff; use acp_thread::Diff;
use agent_client_protocol::{self as acp, ToolCallLocation, ToolCallUpdateFields}; use agent_client_protocol::{self as acp, ToolCallLocation, ToolCallUpdateFields};
use anyhow::{Context as _, Result, anyhow}; use anyhow::{Context as _, Result, anyhow};
use assistant_tools::edit_agent::{EditAgent, EditAgentOutput, EditAgentOutputEvent, EditFormat};
use cloud_llm_client::CompletionIntent; use cloud_llm_client::CompletionIntent;
use collections::HashSet; use collections::HashSet;
use gpui::{App, AppContext, AsyncApp, Entity, Task, WeakEntity}; use gpui::{App, AppContext, AsyncApp, Entity, Task, WeakEntity};
@@ -36,7 +34,7 @@ const DEFAULT_UI_TEXT: &str = "Editing file";
/// ///
/// 2. Verify the directory path is correct (only applicable when creating new files): /// 2. 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 /// - Use the `list_directory` tool to verify the parent directory exists and is the correct location
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] #[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct EditFileToolInput { pub struct EditFileToolInput {
/// A one-line, user-friendly markdown description of the edit. This will be shown in the UI and also passed to another model to perform the edit. /// A one-line, user-friendly markdown description of the edit. This will be shown in the UI and also passed to another model to perform the edit.
/// ///
@@ -77,7 +75,7 @@ pub struct EditFileToolInput {
pub mode: EditFileMode, pub mode: EditFileMode,
} }
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] #[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct EditFileToolPartialInput { struct EditFileToolPartialInput {
#[serde(default)] #[serde(default)]
path: String, path: String,
@@ -125,7 +123,6 @@ pub struct EditFileTool {
thread: WeakEntity<Thread>, thread: WeakEntity<Thread>,
language_registry: Arc<LanguageRegistry>, language_registry: Arc<LanguageRegistry>,
project: Entity<Project>, project: Entity<Project>,
templates: Arc<Templates>,
} }
impl EditFileTool { impl EditFileTool {
@@ -133,13 +130,11 @@ impl EditFileTool {
project: Entity<Project>, project: Entity<Project>,
thread: WeakEntity<Thread>, thread: WeakEntity<Thread>,
language_registry: Arc<LanguageRegistry>, language_registry: Arc<LanguageRegistry>,
templates: Arc<Templates>,
) -> Self { ) -> Self {
Self { Self {
project, project,
thread, thread,
language_registry, language_registry,
templates,
} }
} }
@@ -299,7 +294,8 @@ impl AgentTool for EditFileTool {
model, model,
project.clone(), project.clone(),
action_log.clone(), action_log.clone(),
self.templates.clone(), // TODO: move edit agent to this crate so we can use our templates
assistant_tools::templates::Templates::new(),
edit_format, edit_format,
); );
@@ -603,7 +599,6 @@ mod tests {
project, project,
thread.downgrade(), thread.downgrade(),
language_registry, language_registry,
Templates::new(),
)) ))
.run(input, ToolCallEventStream::test().0, cx) .run(input, ToolCallEventStream::test().0, cx)
}) })
@@ -795,7 +790,7 @@ mod tests {
store.update_user_settings(cx, |settings| { store.update_user_settings(cx, |settings| {
settings.project.all_languages.defaults.format_on_save = Some(FormatOnSave::On); settings.project.all_languages.defaults.format_on_save = Some(FormatOnSave::On);
settings.project.all_languages.defaults.formatter = settings.project.all_languages.defaults.formatter =
Some(language::language_settings::FormatterList::default()); Some(language::language_settings::SelectedFormatter::Auto);
}); });
}); });
}); });
@@ -812,7 +807,6 @@ mod tests {
project.clone(), project.clone(),
thread.downgrade(), thread.downgrade(),
language_registry.clone(), language_registry.clone(),
Templates::new(),
)) ))
.run(input, ToolCallEventStream::test().0, cx) .run(input, ToolCallEventStream::test().0, cx)
}); });
@@ -871,7 +865,6 @@ mod tests {
project.clone(), project.clone(),
thread.downgrade(), thread.downgrade(),
language_registry, language_registry,
Templates::new(),
)) ))
.run(input, ToolCallEventStream::test().0, cx) .run(input, ToolCallEventStream::test().0, cx)
}); });
@@ -958,7 +951,6 @@ mod tests {
project.clone(), project.clone(),
thread.downgrade(), thread.downgrade(),
language_registry.clone(), language_registry.clone(),
Templates::new(),
)) ))
.run(input, ToolCallEventStream::test().0, cx) .run(input, ToolCallEventStream::test().0, cx)
}); });
@@ -1013,7 +1005,6 @@ mod tests {
project.clone(), project.clone(),
thread.downgrade(), thread.downgrade(),
language_registry, language_registry,
Templates::new(),
)) ))
.run(input, ToolCallEventStream::test().0, cx) .run(input, ToolCallEventStream::test().0, cx)
}); });
@@ -1066,7 +1057,6 @@ mod tests {
project.clone(), project.clone(),
thread.downgrade(), thread.downgrade(),
language_registry, language_registry,
Templates::new(),
)); ));
fs.insert_tree("/root", json!({})).await; fs.insert_tree("/root", json!({})).await;
@@ -1207,7 +1197,6 @@ mod tests {
project.clone(), project.clone(),
thread.downgrade(), thread.downgrade(),
language_registry, language_registry,
Templates::new(),
)); ));
// Test global config paths - these should require confirmation if they exist and are outside the project // Test global config paths - these should require confirmation if they exist and are outside the project
@@ -1320,7 +1309,6 @@ mod tests {
project.clone(), project.clone(),
thread.downgrade(), thread.downgrade(),
language_registry, language_registry,
Templates::new(),
)); ));
// Test files in different worktrees // Test files in different worktrees
@@ -1405,7 +1393,6 @@ mod tests {
project.clone(), project.clone(),
thread.downgrade(), thread.downgrade(),
language_registry, language_registry,
Templates::new(),
)); ));
// Test edge cases // Test edge cases
@@ -1495,7 +1482,6 @@ mod tests {
project.clone(), project.clone(),
thread.downgrade(), thread.downgrade(),
language_registry, language_registry,
Templates::new(),
)); ));
// Test different EditFileMode values // Test different EditFileMode values
@@ -1580,7 +1566,6 @@ mod tests {
project, project,
thread.downgrade(), thread.downgrade(),
language_registry, language_registry,
Templates::new(),
)); ));
cx.update(|cx| { cx.update(|cx| {
@@ -1668,7 +1653,6 @@ mod tests {
project.clone(), project.clone(),
thread.downgrade(), thread.downgrade(),
languages.clone(), languages.clone(),
Templates::new(),
)); ));
let (stream_tx, mut stream_rx) = ToolCallEventStream::test(); let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
let edit = cx.update(|cx| { let edit = cx.update(|cx| {
@@ -1698,7 +1682,6 @@ mod tests {
project.clone(), project.clone(),
thread.downgrade(), thread.downgrade(),
languages.clone(), languages.clone(),
Templates::new(),
)); ));
let (stream_tx, mut stream_rx) = ToolCallEventStream::test(); let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
let edit = cx.update(|cx| { let edit = cx.update(|cx| {
@@ -1726,7 +1709,6 @@ mod tests {
project.clone(), project.clone(),
thread.downgrade(), thread.downgrade(),
languages.clone(), languages.clone(),
Templates::new(),
)); ));
let (stream_tx, mut stream_rx) = ToolCallEventStream::test(); let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
let edit = cx.update(|cx| { let edit = cx.update(|cx| {

View File

@@ -1,6 +1,7 @@
use action_log::ActionLog; use action_log::ActionLog;
use agent_client_protocol::{self as acp, ToolCallUpdateFields}; use agent_client_protocol::{self as acp, ToolCallUpdateFields};
use anyhow::{Context as _, Result, anyhow}; use anyhow::{Context as _, Result, anyhow};
use assistant_tool::outline;
use gpui::{App, Entity, SharedString, Task}; use gpui::{App, Entity, SharedString, Task};
use indoc::formatdoc; use indoc::formatdoc;
use language::Point; use language::Point;
@@ -12,7 +13,7 @@ use settings::Settings;
use std::sync::Arc; use std::sync::Arc;
use util::markdown::MarkdownCodeBlock; use util::markdown::MarkdownCodeBlock;
use crate::{AgentTool, ToolCallEventStream, outline}; use crate::{AgentTool, ToolCallEventStream};
/// Reads the content of the given file in the project. /// Reads the content of the given file in the project.
/// ///

View File

@@ -57,7 +57,7 @@ impl AgentTool for WebSearchTool {
} }
/// We currently only support Zed Cloud as a provider. /// We currently only support Zed Cloud as a provider.
fn supports_provider(provider: &LanguageModelProviderId) -> bool { fn supported_provider(&self, provider: &LanguageModelProviderId) -> bool {
provider == &ZED_CLOUD_PROVIDER_ID provider == &ZED_CLOUD_PROVIDER_ID
} }

View File

@@ -51,6 +51,7 @@ terminal.workspace = true
uuid.workspace = true uuid.workspace = true
util.workspace = true util.workspace = true
watch.workspace = true watch.workspace = true
workspace-hack.workspace = true
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
libc.workspace = true libc.workspace = true

View File

@@ -9,6 +9,7 @@ use futures::io::BufReader;
use project::Project; use project::Project;
use project::agent_server_store::AgentServerCommand; use project::agent_server_store::AgentServerCommand;
use serde::Deserialize; use serde::Deserialize;
use task::Shell;
use util::ResultExt as _; use util::ResultExt as _;
use std::path::PathBuf; use std::path::PathBuf;
@@ -38,7 +39,7 @@ pub struct AcpConnection {
// NB: Don't move this into the wait_task, since we need to ensure the process is // NB: Don't move this into the wait_task, since we need to ensure the process is
// killed on drop (setting kill_on_drop on the command seems to not always work). // killed on drop (setting kill_on_drop on the command seems to not always work).
child: smol::process::Child, child: smol::process::Child,
_io_task: Task<Result<(), acp::Error>>, _io_task: Task<Result<()>>,
_wait_task: Task<Result<()>>, _wait_task: Task<Result<()>>,
_stderr_task: Task<Result<()>>, _stderr_task: Task<Result<()>>,
} }
@@ -96,7 +97,7 @@ impl AcpConnection {
let stdout = child.stdout.take().context("Failed to take stdout")?; let stdout = child.stdout.take().context("Failed to take stdout")?;
let stdin = child.stdin.take().context("Failed to take stdin")?; let stdin = child.stdin.take().context("Failed to take stdin")?;
let stderr = child.stderr.take().context("Failed to take stderr")?; let stderr = child.stderr.take().context("Failed to take stderr")?;
log::debug!( log::info!(
"Spawning external agent server: {:?}, {:?}", "Spawning external agent server: {:?}, {:?}",
command.path, command.path,
command.args command.args
@@ -167,10 +168,7 @@ impl AcpConnection {
meta: None, meta: None,
}, },
terminal: true, terminal: true,
meta: Some(serde_json::json!({ meta: None,
// Experimental: Allow for rendering terminal output from the agents
"terminal_output": true,
})),
}, },
meta: None, meta: None,
}) })
@@ -814,18 +812,47 @@ impl acp::Client for ClientDelegate {
let thread = self.session_thread(&args.session_id)?; let thread = self.session_thread(&args.session_id)?;
let project = thread.read_with(&self.cx, |thread, _cx| thread.project().clone())?; let project = thread.read_with(&self.cx, |thread, _cx| thread.project().clone())?;
let terminal_entity = acp_thread::create_terminal_entity( let mut env = if let Some(dir) = &args.cwd {
args.command.clone(), project
&args.args, .update(&mut self.cx.clone(), |project, cx| {
args.env project.directory_environment(&task::Shell::System, dir.clone().into(), cx)
.into_iter() })?
.map(|env| (env.name, env.value)) .await
.collect(), .unwrap_or_default()
args.cwd.clone(), } else {
&project, Default::default()
&mut self.cx.clone(), };
) for var in args.env {
.await?; env.insert(var.name, var.value);
}
// Use remote shell or default system shell, as appropriate
let shell = project
.update(&mut self.cx.clone(), |project, cx| {
project
.remote_client()
.and_then(|r| r.read(cx).default_system_shell())
.map(Shell::Program)
})?
.unwrap_or(task::Shell::System);
let (task_command, task_args) = task::ShellBuilder::new(&shell)
.redirect_stdin_to_dev_null()
.build(Some(args.command.clone()), &args.args);
let terminal_entity = project
.update(&mut self.cx.clone(), |project, cx| {
project.create_terminal_task(
task::SpawnInTerminal {
command: Some(task_command),
args: task_args,
cwd: args.cwd.clone(),
env,
..Default::default()
},
cx,
)
})?
.await?;
// Register with renderer // Register with renderer
let terminal_entity = thread.update(&mut self.cx.clone(), |thread, cx| { let terminal_entity = thread.update(&mut self.cx.clone(), |thread, cx| {

View File

@@ -1,16 +1,11 @@
use std::rc::Rc; use std::rc::Rc;
use std::sync::Arc;
use std::{any::Any, path::Path}; use std::{any::Any, path::Path};
use acp_thread::AgentConnection;
use agent_client_protocol as acp;
use anyhow::{Context as _, Result};
use fs::Fs;
use gpui::{App, AppContext as _, SharedString, Task};
use project::agent_server_store::{AllAgentServersSettings, CODEX_NAME};
use settings::{SettingsStore, update_settings_file};
use crate::{AgentServer, AgentServerDelegate, load_proxy_env}; use crate::{AgentServer, AgentServerDelegate, load_proxy_env};
use acp_thread::AgentConnection;
use anyhow::{Context as _, Result};
use gpui::{App, SharedString, Task};
use project::agent_server_store::CODEX_NAME;
#[derive(Clone)] #[derive(Clone)]
pub struct Codex; pub struct Codex;
@@ -35,27 +30,6 @@ impl AgentServer for Codex {
ui::IconName::AiOpenAi ui::IconName::AiOpenAi
} }
fn default_mode(&self, cx: &mut App) -> Option<acp::SessionModeId> {
let settings = cx.read_global(|settings: &SettingsStore, _| {
settings.get::<AllAgentServersSettings>(None).codex.clone()
});
settings
.as_ref()
.and_then(|s| s.default_mode.clone().map(|m| acp::SessionModeId(m.into())))
}
fn set_default_mode(&self, mode_id: Option<acp::SessionModeId>, fs: Arc<dyn Fs>, cx: &mut App) {
update_settings_file(fs, cx, |settings, _| {
settings
.agent_servers
.get_or_insert_default()
.codex
.get_or_insert_default()
.default_mode = mode_id.map(|m| m.to_string())
});
}
fn connect( fn connect(
&self, &self,
root_dir: Option<&Path>, root_dir: Option<&Path>,

View File

@@ -24,6 +24,7 @@ schemars.workspace = true
serde.workspace = true serde.workspace = true
settings.workspace = true settings.workspace = true
util.workspace = true util.workspace = true
workspace-hack.workspace = true
[dev-dependencies] [dev-dependencies]
fs.workspace = true fs.workspace = true

View File

@@ -10,14 +10,15 @@ use schemars::JsonSchema;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use settings::{ use settings::{
DefaultAgentView, DockPosition, LanguageModelParameters, LanguageModelSelection, DefaultAgentView, DockPosition, LanguageModelParameters, LanguageModelSelection,
NotifyWhenAgentWaiting, Settings, NotifyWhenAgentWaiting, Settings, SettingsContent,
}; };
pub use crate::agent_profile::*; pub use crate::agent_profile::*;
pub const SUMMARIZE_THREAD_PROMPT: &str = include_str!("prompts/summarize_thread_prompt.txt"); pub const SUMMARIZE_THREAD_PROMPT: &str =
include_str!("../../agent/src/prompts/summarize_thread_prompt.txt");
pub const SUMMARIZE_THREAD_DETAILED_PROMPT: &str = pub const SUMMARIZE_THREAD_DETAILED_PROMPT: &str =
include_str!("prompts/summarize_thread_detailed_prompt.txt"); include_str!("../../agent/src/prompts/summarize_thread_detailed_prompt.txt");
pub fn init(cx: &mut App) { pub fn init(cx: &mut App) {
AgentSettings::register(cx); AgentSettings::register(cx);
@@ -41,6 +42,7 @@ pub struct AgentSettings {
pub always_allow_tool_actions: bool, pub always_allow_tool_actions: bool,
pub notify_when_agent_waiting: NotifyWhenAgentWaiting, pub notify_when_agent_waiting: NotifyWhenAgentWaiting,
pub play_sound_when_agent_done: bool, pub play_sound_when_agent_done: bool,
pub stream_edits: bool,
pub single_file_review: bool, pub single_file_review: bool,
pub model_parameters: Vec<LanguageModelParameters>, pub model_parameters: Vec<LanguageModelParameters>,
pub preferred_completion_mode: CompletionMode, pub preferred_completion_mode: CompletionMode,
@@ -173,6 +175,7 @@ impl Settings for AgentSettings {
always_allow_tool_actions: agent.always_allow_tool_actions.unwrap(), always_allow_tool_actions: agent.always_allow_tool_actions.unwrap(),
notify_when_agent_waiting: agent.notify_when_agent_waiting.unwrap(), notify_when_agent_waiting: agent.notify_when_agent_waiting.unwrap(),
play_sound_when_agent_done: agent.play_sound_when_agent_done.unwrap(), play_sound_when_agent_done: agent.play_sound_when_agent_done.unwrap(),
stream_edits: agent.stream_edits.unwrap(),
single_file_review: agent.single_file_review.unwrap(), single_file_review: agent.single_file_review.unwrap(),
model_parameters: agent.model_parameters, model_parameters: agent.model_parameters,
preferred_completion_mode: agent.preferred_completion_mode.unwrap().into(), preferred_completion_mode: agent.preferred_completion_mode.unwrap().into(),
@@ -183,4 +186,14 @@ impl Settings for AgentSettings {
message_editor_min_lines: agent.message_editor_min_lines.unwrap(), message_editor_min_lines: agent.message_editor_min_lines.unwrap(),
} }
} }
fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut SettingsContent) {
if let Some(b) = vscode
.read_value("chat.agent.enabled")
.and_then(|b| b.as_bool())
{
current.agent.get_or_insert_default().enabled = Some(b);
current.agent.get_or_insert_default().button = Some(b);
}
}
} }

View File

@@ -20,14 +20,16 @@ acp_thread.workspace = true
action_log.workspace = true action_log.workspace = true
agent-client-protocol.workspace = true agent-client-protocol.workspace = true
agent.workspace = true agent.workspace = true
agent2.workspace = true
agent_servers.workspace = true agent_servers.workspace = true
agent_settings.workspace = true agent_settings.workspace = true
ai_onboarding.workspace = true ai_onboarding.workspace = true
anyhow.workspace = true anyhow.workspace = true
arrayvec.workspace = true arrayvec.workspace = true
assistant_text_thread.workspace = true assistant_context.workspace = true
assistant_slash_command.workspace = true assistant_slash_command.workspace = true
assistant_slash_commands.workspace = true assistant_slash_commands.workspace = true
assistant_tool.workspace = true
audio.workspace = true audio.workspace = true
buffer_diff.workspace = true buffer_diff.workspace = true
chrono.workspace = true chrono.workspace = true
@@ -69,7 +71,6 @@ postage.workspace = true
project.workspace = true project.workspace = true
prompt_store.workspace = true prompt_store.workspace = true
proto.workspace = true proto.workspace = true
ref-cast.workspace = true
release_channel.workspace = true release_channel.workspace = true
rope.workspace = true rope.workspace = true
rules_library.workspace = true rules_library.workspace = true
@@ -96,13 +97,16 @@ url.workspace = true
urlencoding.workspace = true urlencoding.workspace = true
util.workspace = true util.workspace = true
watch.workspace = true watch.workspace = true
workspace-hack.workspace = true
workspace.workspace = true workspace.workspace = true
zed_actions.workspace = true zed_actions.workspace = true
[dev-dependencies] [dev-dependencies]
acp_thread = { workspace = true, features = ["test-support"] } acp_thread = { workspace = true, features = ["test-support"] }
agent = { workspace = true, features = ["test-support"] } agent = { workspace = true, features = ["test-support"] }
assistant_text_thread = { workspace = true, features = ["test-support"] } agent2 = { workspace = true, features = ["test-support"] }
assistant_context = { workspace = true, features = ["test-support"] }
assistant_tools.workspace = true
buffer_diff = { workspace = true, features = ["test-support"] } buffer_diff = { workspace = true, features = ["test-support"] }
db = { workspace = true, features = ["test-support"] } db = { workspace = true, features = ["test-support"] }
editor = { workspace = true, features = ["test-support"] } editor = { workspace = true, features = ["test-support"] }

View File

@@ -6,13 +6,13 @@ use std::sync::Arc;
use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicBool;
use acp_thread::MentionUri; use acp_thread::MentionUri;
use agent::{HistoryEntry, HistoryStore};
use agent_client_protocol as acp; use agent_client_protocol as acp;
use agent2::{HistoryEntry, HistoryStore};
use anyhow::Result; use anyhow::Result;
use editor::{CompletionProvider, Editor, ExcerptId}; use editor::{CompletionProvider, Editor, ExcerptId};
use fuzzy::{StringMatch, StringMatchCandidate}; use fuzzy::{StringMatch, StringMatchCandidate};
use gpui::{App, Entity, Task, WeakEntity}; use gpui::{App, Entity, Task, WeakEntity};
use language::{Buffer, CodeLabel, CodeLabelBuilder, HighlightId}; use language::{Buffer, CodeLabel, HighlightId};
use lsp::CompletionContext; use lsp::CompletionContext;
use project::lsp_store::{CompletionDocumentation, SymbolLocation}; use project::lsp_store::{CompletionDocumentation, SymbolLocation};
use project::{ use project::{
@@ -27,12 +27,11 @@ use util::rel_path::RelPath;
use workspace::Workspace; use workspace::Workspace;
use crate::AgentPanel; use crate::AgentPanel;
use crate::acp::message_editor::MessageEditor; use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
use crate::context_picker::file_context_picker::{FileMatch, search_files}; use crate::context_picker::file_context_picker::{FileMatch, search_files};
use crate::context_picker::rules_context_picker::{RulesContextEntry, search_rules}; use crate::context_picker::rules_context_picker::{RulesContextEntry, search_rules};
use crate::context_picker::symbol_context_picker::SymbolMatch; use crate::context_picker::symbol_context_picker::SymbolMatch;
use crate::context_picker::symbol_context_picker::search_symbols; use crate::context_picker::symbol_context_picker::search_symbols;
use crate::context_picker::thread_context_picker::search_threads;
use crate::context_picker::{ use crate::context_picker::{
ContextPickerAction, ContextPickerEntry, ContextPickerMode, selection_ranges, ContextPickerAction, ContextPickerEntry, ContextPickerMode, selection_ranges,
}; };
@@ -652,9 +651,7 @@ impl ContextPickerCompletionProvider {
.active_item(cx) .active_item(cx)
.and_then(|item| item.downcast::<Editor>()) .and_then(|item| item.downcast::<Editor>())
.is_some_and(|editor| { .is_some_and(|editor| {
editor.update(cx, |editor, cx| { editor.update(cx, |editor, cx| editor.has_non_empty_selection(cx))
editor.has_non_empty_selection(&editor.display_snapshot(cx))
})
}); });
if has_selection { if has_selection {
entries.push(ContextPickerEntry::Action( entries.push(ContextPickerEntry::Action(
@@ -676,7 +673,7 @@ impl ContextPickerCompletionProvider {
fn build_code_label_for_full_path(file_name: &str, directory: Option<&str>, cx: &App) -> CodeLabel { fn build_code_label_for_full_path(file_name: &str, directory: Option<&str>, cx: &App) -> CodeLabel {
let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId); let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
let mut label = CodeLabelBuilder::default(); let mut label = CodeLabel::default();
label.push_str(file_name, None); label.push_str(file_name, None);
label.push_str(" ", None); label.push_str(" ", None);
@@ -685,7 +682,9 @@ fn build_code_label_for_full_path(file_name: &str, directory: Option<&str>, cx:
label.push_str(directory, comment_id); label.push_str(directory, comment_id);
} }
label.build() label.filter_range = 0..label.text().len();
label
} }
impl CompletionProvider for ContextPickerCompletionProvider { impl CompletionProvider for ContextPickerCompletionProvider {
@@ -760,13 +759,13 @@ impl CompletionProvider for ContextPickerCompletionProvider {
let editor = editor.clone(); let editor = editor.clone();
move |cx| { move |cx| {
editor editor
.update(cx, |editor, cx| { .update(cx, |_editor, cx| {
match intent { match intent {
CompletionIntent::Complete CompletionIntent::Complete
| CompletionIntent::CompleteWithInsert | CompletionIntent::CompleteWithInsert
| CompletionIntent::CompleteWithReplace => { | CompletionIntent::CompleteWithReplace => {
if !is_missing_argument { if !is_missing_argument {
editor.send(cx); cx.emit(MessageEditorEvent::Send);
} }
} }
CompletionIntent::Compose => {} CompletionIntent::Compose => {}
@@ -776,7 +775,7 @@ impl CompletionProvider for ContextPickerCompletionProvider {
} }
}); });
} }
false is_missing_argument
} }
})), })),
} }
@@ -911,17 +910,6 @@ impl CompletionProvider for ContextPickerCompletionProvider {
offset_to_line, offset_to_line,
self.prompt_capabilities.borrow().embedded_context, self.prompt_capabilities.borrow().embedded_context,
) )
.filter(|completion| {
// Right now we don't support completing arguments of slash commands
let is_slash_command_with_argument = matches!(
completion,
ContextCompletion::SlashCommand(SlashCommandCompletion {
argument: Some(_),
..
})
);
!is_slash_command_with_argument
})
.map(|completion| { .map(|completion| {
completion.source_range().start <= offset_to_line + position.column as usize completion.source_range().start <= offset_to_line + position.column as usize
&& completion.source_range().end >= offset_to_line + position.column as usize && completion.source_range().end >= offset_to_line + position.column as usize
@@ -941,6 +929,42 @@ impl CompletionProvider for ContextPickerCompletionProvider {
} }
} }
pub(crate) fn search_threads(
query: String,
cancellation_flag: Arc<AtomicBool>,
history_store: &Entity<HistoryStore>,
cx: &mut App,
) -> Task<Vec<HistoryEntry>> {
let threads = history_store.read(cx).entries().collect();
if query.is_empty() {
return Task::ready(threads);
}
let executor = cx.background_executor().clone();
cx.background_spawn(async move {
let candidates = threads
.iter()
.enumerate()
.map(|(id, thread)| StringMatchCandidate::new(id, thread.title()))
.collect::<Vec<_>>();
let matches = fuzzy::match_strings(
&candidates,
&query,
false,
true,
100,
&cancellation_flag,
executor,
)
.await;
matches
.into_iter()
.map(|mat| threads[mat.candidate_id].clone())
.collect()
})
}
fn confirm_completion_callback( fn confirm_completion_callback(
crease_text: SharedString, crease_text: SharedString,
start: Anchor, start: Anchor,

View File

@@ -1,8 +1,8 @@
use std::{cell::RefCell, ops::Range, rc::Rc}; use std::{cell::RefCell, ops::Range, rc::Rc};
use acp_thread::{AcpThread, AgentThreadEntry}; use acp_thread::{AcpThread, AgentThreadEntry};
use agent::HistoryStore;
use agent_client_protocol::{self as acp, ToolCallId}; use agent_client_protocol::{self as acp, ToolCallId};
use agent2::HistoryStore;
use collections::HashMap; use collections::HashMap;
use editor::{Editor, EditorMode, MinimapVisibility}; use editor::{Editor, EditorMode, MinimapVisibility};
use gpui::{ use gpui::{
@@ -399,10 +399,10 @@ mod tests {
use std::{path::Path, rc::Rc}; use std::{path::Path, rc::Rc};
use acp_thread::{AgentConnection, StubAgentConnection}; use acp_thread::{AgentConnection, StubAgentConnection};
use agent::HistoryStore;
use agent_client_protocol as acp; use agent_client_protocol as acp;
use agent_settings::AgentSettings; use agent_settings::AgentSettings;
use assistant_text_thread::TextThreadStore; use agent2::HistoryStore;
use assistant_context::ContextStore;
use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind}; use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
use editor::{EditorSettings, RowInfo}; use editor::{EditorSettings, RowInfo};
use fs::FakeFs; use fs::FakeFs;
@@ -466,8 +466,8 @@ mod tests {
connection.send_update(session_id, acp::SessionUpdate::ToolCall(tool_call), cx) connection.send_update(session_id, acp::SessionUpdate::ToolCall(tool_call), cx)
}); });
let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx)); let context_store = cx.new(|cx| ContextStore::fake(project.clone(), cx));
let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx)); let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
let view_state = cx.new(|_cx| { let view_state = cx.new(|_cx| {
EntryViewState::new( EntryViewState::new(

View File

@@ -3,18 +3,19 @@ use crate::{
context_picker::{ContextPickerAction, fetch_context_picker::fetch_url_content}, context_picker::{ContextPickerAction, fetch_context_picker::fetch_url_content},
}; };
use acp_thread::{MentionUri, selection_name}; use acp_thread::{MentionUri, selection_name};
use agent::{HistoryStore, outline};
use agent_client_protocol as acp; use agent_client_protocol as acp;
use agent_servers::{AgentServer, AgentServerDelegate}; use agent_servers::{AgentServer, AgentServerDelegate};
use agent2::HistoryStore;
use anyhow::{Result, anyhow}; use anyhow::{Result, anyhow};
use assistant_slash_commands::codeblock_fence_for_path; use assistant_slash_commands::codeblock_fence_for_path;
use assistant_tool::outline;
use collections::{HashMap, HashSet}; use collections::{HashMap, HashSet};
use editor::{ use editor::{
Addon, Anchor, AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, Addon, Anchor, AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement,
EditorEvent, EditorMode, EditorSnapshot, EditorStyle, ExcerptId, FoldPlaceholder, Inlay, EditorEvent, EditorMode, EditorSnapshot, EditorStyle, ExcerptId, FoldPlaceholder, InlayId,
MultiBuffer, ToOffset, MultiBuffer, ToOffset,
actions::Paste, actions::Paste,
display_map::{Crease, CreaseId, FoldId}, display_map::{Crease, CreaseId, FoldId, Inlay},
}; };
use futures::{ use futures::{
FutureExt as _, FutureExt as _,
@@ -29,8 +30,7 @@ use language::{Buffer, Language, language_settings::InlayHintKind};
use language_model::LanguageModelImage; use language_model::LanguageModelImage;
use postage::stream::Stream as _; use postage::stream::Stream as _;
use project::{ use project::{
CompletionIntent, InlayHint, InlayHintLabel, InlayId, Project, ProjectItem, ProjectPath, CompletionIntent, InlayHint, InlayHintLabel, Project, ProjectItem, ProjectPath, Worktree,
Worktree,
}; };
use prompt_store::{PromptId, PromptStore}; use prompt_store::{PromptId, PromptStore};
use rope::Point; use rope::Point;
@@ -76,7 +76,7 @@ pub enum MessageEditorEvent {
impl EventEmitter<MessageEditorEvent> for MessageEditor {} impl EventEmitter<MessageEditorEvent> for MessageEditor {}
const COMMAND_HINT_INLAY_ID: InlayId = InlayId::Hint(0); const COMMAND_HINT_INLAY_ID: u32 = 0;
impl MessageEditor { impl MessageEditor {
pub fn new( pub fn new(
@@ -141,9 +141,7 @@ impl MessageEditor {
subscriptions.push(cx.subscribe_in(&editor, window, { subscriptions.push(cx.subscribe_in(&editor, window, {
move |this, editor, event, window, cx| { move |this, editor, event, window, cx| {
if let EditorEvent::Edited { .. } = event if let EditorEvent::Edited { .. } = event {
&& !editor.read(cx).read_only(cx)
{
let snapshot = editor.update(cx, |editor, cx| { let snapshot = editor.update(cx, |editor, cx| {
let new_hints = this let new_hints = this
.command_hint(editor.buffer(), cx) .command_hint(editor.buffer(), cx)
@@ -152,7 +150,7 @@ impl MessageEditor {
let has_new_hint = !new_hints.is_empty(); let has_new_hint = !new_hints.is_empty();
editor.splice_inlays( editor.splice_inlays(
if has_hint { if has_hint {
&[COMMAND_HINT_INLAY_ID] &[InlayId::Hint(COMMAND_HINT_INLAY_ID)]
} else { } else {
&[] &[]
}, },
@@ -230,7 +228,7 @@ impl MessageEditor {
pub fn insert_thread_summary( pub fn insert_thread_summary(
&mut self, &mut self,
thread: agent::DbThreadMetadata, thread: agent2::DbThreadMetadata,
window: &mut Window, window: &mut Window,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) { ) {
@@ -292,10 +290,15 @@ impl MessageEditor {
let snapshot = self let snapshot = self
.editor .editor
.update(cx, |editor, cx| editor.snapshot(window, cx)); .update(cx, |editor, cx| editor.snapshot(window, cx));
let Some(start_anchor) = snapshot.buffer_snapshot().as_singleton_anchor(start) else { let Some((excerpt_id, _, _)) = snapshot.buffer_snapshot().as_singleton() else {
return Task::ready(());
};
let Some(start_anchor) = snapshot
.buffer_snapshot()
.anchor_in_excerpt(*excerpt_id, start)
else {
return Task::ready(()); return Task::ready(());
}; };
let excerpt_id = start_anchor.excerpt_id;
let end_anchor = snapshot let end_anchor = snapshot
.buffer_snapshot() .buffer_snapshot()
.anchor_before(start_anchor.to_offset(&snapshot.buffer_snapshot()) + content_len + 1); .anchor_before(start_anchor.to_offset(&snapshot.buffer_snapshot()) + content_len + 1);
@@ -327,7 +330,7 @@ impl MessageEditor {
}) })
.shared(); .shared();
insert_crease_for_mention( insert_crease_for_mention(
excerpt_id, *excerpt_id,
start, start,
content_len, content_len,
mention_uri.name().into(), mention_uri.name().into(),
@@ -339,7 +342,7 @@ impl MessageEditor {
) )
} else { } else {
insert_crease_for_mention( insert_crease_for_mention(
excerpt_id, *excerpt_id,
start, start,
content_len, content_len,
crease_text, crease_text,
@@ -541,7 +544,10 @@ impl MessageEditor {
cx: &mut Context<Self>, cx: &mut Context<Self>,
) { ) {
let snapshot = self.editor.read(cx).buffer().read(cx).snapshot(cx); let snapshot = self.editor.read(cx).buffer().read(cx).snapshot(cx);
let Some(start) = snapshot.as_singleton_anchor(source_range.start) else { let Some((&excerpt_id, _, _)) = snapshot.as_singleton() else {
return;
};
let Some(start) = snapshot.anchor_in_excerpt(excerpt_id, source_range.start) else {
return; return;
}; };
@@ -599,7 +605,7 @@ impl MessageEditor {
id: acp::SessionId, id: acp::SessionId,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Task<Result<Mention>> { ) -> Task<Result<Mention>> {
let server = Rc::new(agent::NativeAgentServer::new( let server = Rc::new(agent2::NativeAgentServer::new(
self.project.read(cx).fs().clone(), self.project.read(cx).fs().clone(),
self.history_store.clone(), self.history_store.clone(),
)); ));
@@ -612,7 +618,7 @@ impl MessageEditor {
let connection = server.connect(None, delegate, cx); let connection = server.connect(None, delegate, cx);
cx.spawn(async move |_, cx| { cx.spawn(async move |_, cx| {
let (agent, _) = connection.await?; let (agent, _) = connection.await?;
let agent = agent.downcast::<agent::NativeAgentConnection>().unwrap(); let agent = agent.downcast::<agent2::NativeAgentConnection>().unwrap();
let summary = agent let summary = agent
.0 .0
.update(cx, |agent, cx| agent.thread_summary(id, cx))? .update(cx, |agent, cx| agent.thread_summary(id, cx))?
@@ -629,12 +635,12 @@ impl MessageEditor {
path: PathBuf, path: PathBuf,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Task<Result<Mention>> { ) -> Task<Result<Mention>> {
let text_thread_task = self.history_store.update(cx, |store, cx| { let context = self.history_store.update(cx, |text_thread_store, cx| {
store.load_text_thread(path.as_path().into(), cx) text_thread_store.load_text_thread(path.as_path().into(), cx)
}); });
cx.spawn(async move |_, cx| { cx.spawn(async move |_, cx| {
let text_thread = text_thread_task.await?; let context = context.await?;
let xml = text_thread.update(cx, |text_thread, cx| text_thread.to_xml(cx))?; let xml = context.update(cx, |context, cx| context.to_xml(cx))?;
Ok(Mention::Text { Ok(Mention::Text {
content: xml, content: xml,
tracked_buffers: Vec::new(), tracked_buffers: Vec::new(),
@@ -817,20 +823,13 @@ impl MessageEditor {
}); });
} }
pub fn send(&mut self, cx: &mut Context<Self>) { fn send(&mut self, _: &Chat, _: &mut Window, cx: &mut Context<Self>) {
if self.is_empty(cx) { if self.is_empty(cx) {
return; return;
} }
self.editor.update(cx, |editor, cx| {
editor.clear_inlay_hints(cx);
});
cx.emit(MessageEditorEvent::Send) cx.emit(MessageEditorEvent::Send)
} }
fn chat(&mut self, _: &Chat, _: &mut Window, cx: &mut Context<Self>) {
self.send(cx);
}
fn cancel(&mut self, _: &editor::actions::Cancel, _: &mut Window, cx: &mut Context<Self>) { fn cancel(&mut self, _: &editor::actions::Cancel, _: &mut Window, cx: &mut Context<Self>) {
cx.emit(MessageEditorEvent::Cancel) cx.emit(MessageEditorEvent::Cancel)
} }
@@ -1031,7 +1030,6 @@ impl MessageEditor {
) else { ) else {
return; return;
}; };
self.editor.update(cx, |message_editor, cx| { self.editor.update(cx, |message_editor, cx| {
message_editor.edit([(cursor_anchor..cursor_anchor, completion.new_text)], cx); message_editor.edit([(cursor_anchor..cursor_anchor, completion.new_text)], cx);
}); });
@@ -1289,7 +1287,7 @@ impl Render for MessageEditor {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div() div()
.key_context("MessageEditor") .key_context("MessageEditor")
.on_action(cx.listener(Self::chat)) .on_action(cx.listener(Self::send))
.on_action(cx.listener(Self::cancel)) .on_action(cx.listener(Self::cancel))
.capture_action(cx.listener(Self::paste)) .capture_action(cx.listener(Self::paste))
.flex_1() .flex_1()
@@ -1589,9 +1587,10 @@ mod tests {
use std::{cell::RefCell, ops::Range, path::Path, rc::Rc, sync::Arc}; use std::{cell::RefCell, ops::Range, path::Path, rc::Rc, sync::Arc};
use acp_thread::MentionUri; use acp_thread::MentionUri;
use agent::{HistoryStore, outline};
use agent_client_protocol as acp; use agent_client_protocol as acp;
use assistant_text_thread::TextThreadStore; use agent2::HistoryStore;
use assistant_context::ContextStore;
use assistant_tool::outline;
use editor::{AnchorRangeExt as _, Editor, EditorMode}; use editor::{AnchorRangeExt as _, Editor, EditorMode};
use fs::FakeFs; use fs::FakeFs;
use futures::StreamExt as _; use futures::StreamExt as _;
@@ -1622,8 +1621,8 @@ mod tests {
let (workspace, cx) = let (workspace, cx) =
cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx)); cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx)); let context_store = cx.new(|cx| ContextStore::fake(project.clone(), cx));
let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx)); let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
let message_editor = cx.update(|window, cx| { let message_editor = cx.update(|window, cx| {
cx.new(|cx| { cx.new(|cx| {
@@ -1685,10 +1684,13 @@ mod tests {
editor.update_in(cx, |editor, window, cx| { editor.update_in(cx, |editor, window, cx| {
let snapshot = editor.buffer().read(cx).snapshot(cx); let snapshot = editor.buffer().read(cx).snapshot(cx);
let range = snapshot let start = snapshot
.anchor_range_in_excerpt(excerpt_id, completion.replace_range) .anchor_in_excerpt(excerpt_id, completion.replace_range.start)
.unwrap(); .unwrap();
editor.edit([(range, completion.new_text)], cx); let end = snapshot
.anchor_in_excerpt(excerpt_id, completion.replace_range.end)
.unwrap();
editor.edit([(start..end, completion.new_text)], cx);
(completion.confirm.unwrap())(CompletionIntent::Complete, window, cx); (completion.confirm.unwrap())(CompletionIntent::Complete, window, cx);
}); });
@@ -1727,8 +1729,8 @@ mod tests {
.await; .await;
let project = Project::test(fs.clone(), ["/test".as_ref()], cx).await; let project = Project::test(fs.clone(), ["/test".as_ref()], cx).await;
let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx)); let context_store = cx.new(|cx| ContextStore::fake(project.clone(), cx));
let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx)); let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default())); let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
// Start with no available commands - simulating Claude which doesn't support slash commands // Start with no available commands - simulating Claude which doesn't support slash commands
let available_commands = Rc::new(RefCell::new(vec![])); let available_commands = Rc::new(RefCell::new(vec![]));
@@ -1891,8 +1893,8 @@ mod tests {
let mut cx = VisualTestContext::from_window(*window, cx); let mut cx = VisualTestContext::from_window(*window, cx);
let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx)); let context_store = cx.new(|cx| ContextStore::fake(project.clone(), cx));
let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx)); let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default())); let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
let available_commands = Rc::new(RefCell::new(vec![ let available_commands = Rc::new(RefCell::new(vec![
acp::AvailableCommand { acp::AvailableCommand {
@@ -2009,11 +2011,21 @@ mod tests {
editor.update_in(&mut cx, |editor, _window, cx| { editor.update_in(&mut cx, |editor, _window, cx| {
assert_eq!(editor.text(cx), "/say-hello "); assert_eq!(editor.text(cx), "/say-hello ");
assert_eq!(editor.display_text(cx), "/say-hello <name>"); assert_eq!(editor.display_text(cx), "/say-hello <name>");
assert!(!editor.has_visible_completions_menu()); assert!(editor.has_visible_completions_menu());
assert_eq!(
current_completion_labels_with_documentation(editor),
&[("say-hello".into(), "Say hello to whoever you want".into())]
);
}); });
cx.simulate_input("GPT5"); cx.simulate_input("GPT5");
editor.update_in(&mut cx, |editor, window, cx| {
assert!(editor.has_visible_completions_menu());
editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
});
cx.run_until_parked(); cx.run_until_parked();
editor.update_in(&mut cx, |editor, window, cx| { editor.update_in(&mut cx, |editor, window, cx| {
@@ -2022,7 +2034,7 @@ mod tests {
assert!(!editor.has_visible_completions_menu()); assert!(!editor.has_visible_completions_menu());
// Delete argument // Delete argument
for _ in 0..5 { for _ in 0..4 {
editor.backspace(&editor::actions::Backspace, window, cx); editor.backspace(&editor::actions::Backspace, window, cx);
} }
}); });
@@ -2030,12 +2042,13 @@ mod tests {
cx.run_until_parked(); cx.run_until_parked();
editor.update_in(&mut cx, |editor, window, cx| { editor.update_in(&mut cx, |editor, window, cx| {
assert_eq!(editor.text(cx), "/say-hello"); assert_eq!(editor.text(cx), "/say-hello ");
// Hint is visible because argument was deleted // Hint is visible because argument was deleted
assert_eq!(editor.display_text(cx), "/say-hello <name>"); assert_eq!(editor.display_text(cx), "/say-hello <name>");
// Delete last command letter // Delete last command letter
editor.backspace(&editor::actions::Backspace, window, cx); editor.backspace(&editor::actions::Backspace, window, cx);
editor.backspace(&editor::actions::Backspace, window, cx);
}); });
cx.run_until_parked(); cx.run_until_parked();
@@ -2131,8 +2144,8 @@ mod tests {
opened_editors.push(buffer); opened_editors.push(buffer);
} }
let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx)); let context_store = cx.new(|cx| ContextStore::fake(project.clone(), cx));
let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx)); let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default())); let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
let (message_editor, editor) = workspace.update_in(&mut cx, |workspace, window, cx| { let (message_editor, editor) = workspace.update_in(&mut cx, |workspace, window, cx| {
@@ -2658,8 +2671,8 @@ mod tests {
let (workspace, cx) = let (workspace, cx) =
cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx)); cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx)); let context_store = cx.new(|cx| ContextStore::fake(project.clone(), cx));
let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx)); let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
let message_editor = cx.update(|window, cx| { let message_editor = cx.update(|window, cx| {
cx.new(|cx| { cx.new(|cx| {

View File

@@ -174,16 +174,11 @@ impl Render for ModeSelector {
let this = cx.entity(); let this = cx.entity();
let icon = if self.menu_handle.is_deployed() {
IconName::ChevronUp
} else {
IconName::ChevronDown
};
let trigger_button = Button::new("mode-selector-trigger", current_mode_name) let trigger_button = Button::new("mode-selector-trigger", current_mode_name)
.label_size(LabelSize::Small) .label_size(LabelSize::Small)
.style(ButtonStyle::Subtle)
.color(Color::Muted) .color(Color::Muted)
.icon(icon) .icon(IconName::ChevronDown)
.icon_size(IconSize::XSmall) .icon_size(IconSize::XSmall)
.icon_position(IconPosition::End) .icon_position(IconPosition::End)
.icon_color(Color::Muted) .icon_color(Color::Muted)
@@ -194,7 +189,7 @@ impl Render for ModeSelector {
trigger_button, trigger_button,
Tooltip::element({ Tooltip::element({
let focus_handle = self.focus_handle.clone(); let focus_handle = self.focus_handle.clone();
move |_window, cx| { move |window, cx| {
v_flex() v_flex()
.gap_1() .gap_1()
.child( .child(
@@ -205,9 +200,10 @@ impl Render for ModeSelector {
.border_b_1() .border_b_1()
.border_color(cx.theme().colors().border_variant) .border_color(cx.theme().colors().border_variant)
.child(Label::new("Cycle Through Modes")) .child(Label::new("Cycle Through Modes"))
.child(KeyBinding::for_action_in( .children(KeyBinding::for_action_in(
&CycleModeSelector, &CycleModeSelector,
&focus_handle, &focus_handle,
window,
cx, cx,
)), )),
) )
@@ -216,9 +212,10 @@ impl Render for ModeSelector {
.gap_2() .gap_2()
.justify_between() .justify_between()
.child(Label::new("Toggle Mode Menu")) .child(Label::new("Toggle Mode Menu"))
.child(KeyBinding::for_action_in( .children(KeyBinding::for_action_in(
&ToggleProfileSelector, &ToggleProfileSelector,
&focus_handle, &focus_handle,
window,
cx, cx,
)), )),
) )

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