Compare commits

...

176 Commits

Author SHA1 Message Date
Cole Miller
529fb5ff30 zed 0.204.4 2025-09-20 12:55:44 -04:00
Cole Miller
12bc66e6ed Fix spawning ACP login task (for v0.204.x) (#38565)
Release Notes:

- Fixed a bug that prevented authenticating in the terminal with Gemini
and Claude Code.
2025-09-20 12:54:45 -04:00
Cole Miller
7dc833d932 zed 0.204.3 2025-09-19 10:13:44 -04:00
Cole Miller
85cfd726c8 python: Install basedpyright with npm instead of pip (#38471)
Closes #ISSUE

Release Notes:

- N/A *or* Added/Fixed/Improved ...
2025-09-19 10:05:09 -04:00
Joseph T. Lyons
9ae63f04f0 zed 0.204.2 2025-09-18 16:00:22 -04:00
Cole Miller
9bfe7a1798 acp: Fix agent servers sometimes not being registered when Zed starts (#38330)
In local projects, initialize the list of agents in the agent server
store immediately. Previously we were initializing the list only after a
delay, in an attempt to avoid sending the `ExternalAgentsUpdated`
message to the downstream client (if any) before its handlers were
initialized. But we already have a separate codepath for that situation,
in the `AgentServerStore::shared`, and we can insert the delay in that
place instead.

Release Notes:

- acp: Fixed a bug where starting an external agent thread soon after
Zed starts up would show a "not registered" error.

---------

Co-authored-by: Michael <michael@zed.dev>
Co-authored-by: Agus <agus@zed.dev>
2025-09-18 15:56:39 -04:00
Cole Miller
10f172ddac python: Install basedpyright if the basedpyright-langserver binary is missing (#38426)
Potential fix for #38377

Release Notes:

- N/A

---------

Co-authored-by: Peter Tripp <petertripp@gmail.com>
2025-09-18 15:52:13 -04:00
Ben Brandt
a62514df7a acp: Fix behavior of read_text_file for ACP agents (#38401)
We were incorrectly handling the line number as well as stripping out
line breaks when returning portions of files.

It also makes sure following is updated even when we load a snapshot
from cache, which wasn't the case before.

We also are able to load the text via a range in the snapshot, rather
than allocating a string for the entire file and then another after
iterating over lines in the file.

Release Notes:

- acp: Fix incorrect behavior when ACP agents requested to read portions
of files.
2025-09-18 11:55:45 +02:00
Vladimir Varankin
97d04621de Hide BasedPyright banner in toolbar when dismissed (#38135)
This PR fixes the `BasedPyrightBanner`, making sure the banner is
completely hidden in the toolbar, when it was dismissed, or it's not
installed.

Without the fix, the banner still occupies some space in the toolbar,
making the UI looks inconsistent when editing a Python file. The bug is
**especially prominent** when the toolbar is hidden in the user's
settings (see below).

_Banner is shown_
<img width="1470" height="254" alt="Screenshot 2025-09-14 at 11 36 37"
src="https://github.com/user-attachments/assets/1415b075-0660-41ed-8069-c2318ac3a7cf"
/>

_Banner dismissed_
<img width="1470" height="207" alt="Screenshot 2025-09-14 at 11 36 44"
src="https://github.com/user-attachments/assets/828a3fba-5c50-4aba-832c-3e0cc6ed464b"
/>

_Banner dismissed (and the toolbar is hidden)_
<img width="1470" height="177" alt="Screenshot 2025-09-14 at 12 07 25"
src="https://github.com/user-attachments/assets/41aa5861-87df-491f-ac7e-09fc1558dd84"
/>

Closes n/a

Release Notes:

- Fixed the basedpyright onboarding banner
2025-09-18 00:40:13 +02:00
Joseph T. Lyons
4dc0720741 Adjust release notes Discord webhook name (#37997)
Release Notes:

- N/A
2025-09-17 11:23:33 -04:00
Joseph T. Lyons
8127523d0f v0.204.x stable 2025-09-17 10:10:04 -04:00
Smit Barmase
a1c8e69283 macOS: Disable NSAutoFillHeuristicController on macOS 26 (#38179)
Closes #33182

From
https://github.com/zed-industries/zed/issues/33182#issuecomment-3289846957,
thanks @mitchellh.

Release Notes:

- Fixed an issue where scrolling could sometimes feel choppy on macOS
26.
2025-09-16 21:53:09 +05:30
Ben Brandt
3a79ce7312 agent_servers: Set proxy env for all ACP agents (#38247)
- Use ProxySettings::proxy_url to read from settings or env
- Export HTTP(S)_PROXY and NO_PROXY for agent CLIs
- Add read_no_proxy_from_env and move parsing from main

Closes https://github.com/zed-industries/claude-code-acp/issues/46

Release Notes:

- acp: Pass proxy settings through to all ACP agents
2025-09-16 12:28:05 +02:00
Ben Brandt
06e58c318b agent_servers: Let Gemini CLI know it is running in Zed (#38058)
By passing through Zed as the surface, Gemini can know which editor it
is running in.

Release Notes:

- N/A
2025-09-16 12:26:56 +02:00
Conrad Irwin
64adb6d461 Re-add VSCode syntax node motions (#38208)
Closes #ISSUE

Release Notes:

- (preview only) restored ctrl-shift-{left,right} for Larger/Smaller
syntax node. This is VSCode's default and avoids the breaking change
from #37874
2025-09-15 09:18:34 -06:00
Ben Kunkle
69a7c3e252 Ability to update JSON arrays (#38087)
Closes #ISSUE

Adds the ability to our JSON updating code to update arrays within other
objects. Previously updating of arrays was limited to just top level
arrays (i.e. `keymap.json`) however this PR makes it so nested arrays
are supported as well using `#{index}` syntax as a key.

This PR also fixes an issue with the array updating code that meant that
updating empty json values `""` or an empty `keymap.json` file in the
case of the Keymap Editor would fail instead of creating a new array.

Release Notes:

- Fixed an issue where keybindings would fail to save in the Keymap
Editor if the `keymap.json` file was completely empty
2025-09-14 11:55:59 -05:00
Ben Kunkle
41737efb07 Fix line indicator format setting (#38071)
Closes #ISSUE

Release Notes:

- Fixed an issue where the `line_indicator_format` setting would not
update based on the value in `settings.json`
2025-09-12 16:17:22 -04:00
Anthony
608991db39 zed 0.204.1 2025-09-11 19:14:58 -04:00
Anthony Eid
8e0e2a887c Fix auto update not defaulting to true (#38022)
#37337 Made `AutoUpdateSetting` `FileContent =
AutoUpdateSettingsContent` which caused a deserialization bug to occur
because the field it was wrapping wasn't optional. Thus serde would
deserialize the wrapped type `bool` to its default value `false`
stopping the settings load function from reading the correct default
value from `default.json`

I also added a log message that states when the auto updater struct is
checking for updates to make this easier to test.

Release Notes:

- fix auto update defaulting to false
2025-09-11 19:11:33 -04:00
Michael Sloan
d900f12473 Fix panics from unicode slicing in license detection 2025-09-11 14:44:07 -06:00
Joseph T. Lyons
b3729e0b90 v0.204.x preview 2025-09-10 10:08:23 -04:00
Lukas Wirth
d110d325d4 languages: Remove broken pixi environment activation (#37915)
Closes [#ISSUE](https://github.com/zed-industries/zed/issues/37895)

This needs more thought behind it to be implemented properly

Release Notes:

- N/A
2025-09-10 13:35:16 +00:00
Bennet Bo Fenner
2cf3def716 acp: Add keybindings for authorizing tool calls (#37876)
TODO:
- [x] Double-check if we like the naming of the new actions
- [x] Only show keybinding hint once per option (e.g. if there are two
`allow_once` buttons only show it on the first one)
- [x] If there are multiple tool calls that need authorisation, only
show keybindings on the first tool call
- [x] Figure out which keybindings to use
- [x] Add linux keybindings
- [x] Add windows keybindings
- [x] Bug: long keybindings can make the buttons overflow


Release Notes:

- Add keybindings for authorizing tool calls (`agent: Allow once`,
`agent: Allow always`, `agent: Reject once`) in the agent panel

---------

Co-authored-by: Agus Zubiaga <agus@zed.dev>
2025-09-10 13:23:46 +00:00
Lukas Wirth
df2d097dc5 editor: Fix adjacent custom highlights interfering with each other (#37912)
Release Notes:

- Fixed matching bracket highlighting not highlighting closing brackets
when adjacent to each other

Co-authored-by: Finn Evers <finn@zed.dev>
2025-09-10 13:08:32 +00:00
Kirill Bulatov
fcdd427cf8 Revert "markdown: Add support for inline HTML img tags inside text (#37264)" (#37893)
This reverts commit e1a5d29972.

This have regressed Zed release notes' wrapping which we do not want to
do on a release day:
https://github.com/zed-industries/zed/pull/37264#issuecomment-3265420442

Release Notes:

- N/A
2025-09-10 05:34:42 +00:00
Smit Barmase
9c548a0ec6 workspace: Fix tab bar drop target height when no unpinned tabs present (#37884)
Before:
<img width="846" height="192" alt="Screenshot 2025-09-10 at 4 44 18 AM"
src="https://github.com/user-attachments/assets/3c79e140-e2b2-4e50-9fce-cb182e46d878"
/>

After:
<img width="846" height="192" alt="Screenshot 2025-09-10 at 4 43 13 AM"
src="https://github.com/user-attachments/assets/b5fa853d-ce39-4c81-9773-1d84eebc8cbb"
/>

Release Notes:

- Fixed height of the drop background in the tab bar when no unpinned
tabs are present.
2025-09-10 05:17:36 +05:30
Michael Sloan
bd0a5dd664 Potentially fix welcome banner in agent panel not going away (#37879)
Potentially fixes #37367. Just going ahead with the change even though
it's unclear whether this is the fix, since it is quite low risk.

Release Notes:

- N/A
2025-09-09 21:13:12 +00:00
Michael Sloan
2f40a3bdfa keymap validation: Improve message for action that takes no input (#37877)
See
https://github.com/zed-industries/zed/issues/26370#issuecomment-3200022302

Before (user screenshot):

<img width="650" height="127" alt="Image"
src="https://github.com/user-attachments/assets/9548ce43-657e-46ef-b6be-b95489167ac2"
/>

After (my screenshot):

<img width="616" height="229" alt="image"
src="https://github.com/user-attachments/assets/09028305-e7bb-4a31-bb87-55effbec26f3"
/>

Release Notes:

- N/A
2025-09-09 20:56:29 +00:00
Mitch (a.k.a Voz)
304af661a0 Fix import not working on first column first row of file (#37746)
Closes #26136

Release Notes:

- fixed auto import not working on first column, first row of file
2025-09-09 14:18:27 -06:00
Santiago Bernhardt
d2886d606b ollama: Add mistral-nemo (#37723)
Adding mistral nemo, sorting by name and adding comment about clamp
sizing

Release Notes:

- Added support for mistral-nemo

---------

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2025-09-09 20:08:05 +00:00
Joseph T. Lyons
cffb883108 Consistently map syntax node navigation actions on macOS (#37874)
Skipping Linux and Windows keymaps here, as it's hard to find a
consistent base-binding for all 4 actions across all platforms that
don't break important actions for each keymap. Someone else can think on
that and make a proposal.

Release Notes:

- Added bindings for navigating between sibling nodes in the syntax tree
on macOS (`cmd-ctrl-{up/down}` for `SelectPreviousSyntaxNode` and
`SelectNextSyntaxNode`). Breaking change: the existing syntax tree
parent/child navigation bindings have moved from
`ctrl-shift-{left/right}` to `cmd-ctrl-{left/right}` to create a unified
four-directional navigation pattern where all syntax tree operations use
the same modifier combination. We could not use the previous base
modifiers without breaking more bindings.
2025-09-09 20:07:42 +00:00
Kirill Bulatov
eb7154d099 Skip "open this directory" menu entry in case of errors (#37872)
Follow-up of https://github.com/zed-industries/zed/pull/37564

Release Notes:

- N/A
2025-09-09 19:53:03 +00:00
0xshadow
18c6d9d394 Fix SVG preview not refreshing on external file changes (#37316)
Closes #37208 

## Release Notes:

- Fixed: SVG preview now refreshes automatically when files are modified
by external programs

## Summary

Previously, SVG preview would only refresh when files were saved within
the Zed editor, but not when modified by external programs (like
scripts, other editors, etc.)

## What Changed

The SVG preview now subscribes to file system events through the
worktree system. When an external program modifies an SVG file, the
worktree detects the change and notifies the preview. The preview then
clears its cache and refreshes to show the updated content.

## Before the fix



https://github.com/user-attachments/assets/e7f9a2b2-50f9-4b43-95e9-93a0720749f5


## After the fix


https://github.com/user-attachments/assets/b23511e3-8e59-45a1-b29b-d5105d32bd2c

AI Usage:
Used Cursor for code generation
2025-09-09 13:36:35 -06:00
Mitch (a.k.a Voz)
414d3be437 Set usePlaceholders to match Go default (#37551)
Closes #33629

Release Notes:

- changed gopls default to match what Go specifies
https://github.com/golang/tools/blob/master/gopls/doc/settings.md#useplaceholders-bool
2025-09-09 13:32:45 -06:00
Alvaro Parker
0862a0b666 git: Add uncommit action (#37031)
Closes #36767

Release Notes:

- Add uncommit action for git
2025-09-09 13:29:49 -06:00
Umesh Yadav
2e36e9782e language_models: Make Copilot Chat resilient to new model vendors and add tokenizer-based token counting (#37118)
While working on fixing this: #37116. I reliased the current
implementation of github copilot is not truly resilient to upstream
changes.

This PR enhances GitHub Copilot Chat to be forward-compatible with new
AI model vendors and improves token counting accuracy by using
vendor-specific tokenizers from the GitHub Copilot API. The system
previously failed when GitHub added new model vendors like xAI with
deserialization errors, and token counting wasn't utilizing the
vendor-specific tokenizer information provided by the API. The solution
adds an Unknown variant to the ModelVendor enum with serde other
attribute to gracefully handle any new vendors GitHub introduces,
implements tokenizer-aware token counting that uses the model's
specified tokenizer mapping o200k_base to gpt-4o with fallback, adds
explicit support for xAI models with proper tool input format handling,
and includes comprehensive test coverage for unknown vendor scenarios.
Key changes include adding the tokenizer field to model capabilities,
implementing the tokenizer method on models, updating tool input format
logic to handle unknown vendors, and simplifying token counting to use
the vendor's specified tokenizer or fall back to gpt-4o. This ensures
Zed's Copilot Chat integration remains robust and accurate as GitHub
continues expanding their AI model provider ecosystem.

Release Notes:

- Enhanced model vendor compatibility to automatically support future AI
providers and improved token counting accuracy using vendor-specific
tokenizers from the GitHub Copilot

---------

Signed-off-by: Umesh Yadav <git@umesh.dev>
2025-09-09 13:28:26 -06:00
Mitch (a.k.a Voz)
1751bf4cdb Allow outline modal toggling (#37575)
Closes #37511 

The outline modal seems to have a bug where if it's open and the
`outline::Toggle` is triggered, it would not close if there was another
command with the same keybind. So instead, if the outline modal is open
and an `outline::Toggle` is triggered, we dismiss the modal.

Release Notes:

- Fixed a bug where `outline::Toggle` would sometimes not close outline
modal
2025-09-09 13:26:35 -06:00
Jonathan Hart
2fae4c7c72 vim: Make indenting selected lines with > and < in Helix mode no longer deselect them (#37665)
Improves Helix compatibility by making the Indent keybinds `<` and `>`
no longer deselect lines if they're selected.

Post Indent action current Zed release:
<img width="485" height="271" alt="image"
src="https://github.com/user-attachments/assets/41fd3d94-9c89-49dd-adc5-f696dbd79827"
/>
(Cursor is on the beginning of the first line)

Post Indent action in Helix:
<img width="376" height="144" alt="image"
src="https://github.com/user-attachments/assets/fdd1a489-cf3a-4638-9199-3adffa63ef61"
/>

Post Indent action in this PR:
<img width="463" height="300" alt="image"
src="https://github.com/user-attachments/assets/8edd3b81-e446-4b55-bc90-61cac3661ed7"
/>

Release Notes:

- Fixed selected lines indented with `<` and `>` deselecting in Helix
mode
2025-09-09 13:18:22 -06:00
chbk
1ae3d25aed Improve Markdown highlighting (#37669)
Release Notes:

  - Improved Markdown syntax highlighting
  
  
PR #25330 raised concerns about breaking changes, so I split it into two
PRs:
- This PR improves highlighting without deprecating existing selectors.
- PR #37670 is based on this PR and introduces new Markdown selectors.

| Zed 0.202.7 | With this PR |
| --- | --- |
| <img width="800" height="1080" alt="md-0 202 7"
src="https://github.com/user-attachments/assets/0b0b5920-32ed-454f-bc3b-bf5cd0a9086a"
/> | <img width="800" height="1080" alt="md-pr"
src="https://github.com/user-attachments/assets/a5923a2e-391e-4e09-a60b-1a142f9378f3"
/> |

Changes to include the `markup` selector, conforming to
[Neovim](38e46a6d7a/queries/markdown/highlights.scm (L59)),
[VS
Code](dfad570d15/extensions/markdown-basics/syntaxes/markdown.tmLanguage.json (L60)),
[Atom](6686ac6ccc/grammars/gfm.json (L147)),
and [Zed
itself](1e255e41cc/crates/languages/src/gitcommit/highlights.scm (L1)).

- `paragraph`, `indented_code_block`, `pipe_table`: `text`
- `# Heading`: `title` -> `title.markup`
- `-`, `1.`, `>`, `|`: `punctuation.markup`
- ```` ``` ````: `punctuation.embedded.markup`
- `[1]: url.com`, `[link](url.com)`: `link_text.markup`
- `url.com`: `link_uri` -> `link_uri.markup`
- `*italic*`: `emphasis` -> `emphasis.markup`
- `**bold**`: `emphasis.strong` -> `emphasis.strong.markup`
- ``` `raw` ```: `text.literal` -> `text.literal.markup`
- `~~strikethrough~~`: `strikethrough.markup`

````md

# Heading

Some stylized text:
- `raw`
- *italic*
- ~strike~
- **strong**

> quoted

```python
print("some code")
```

1. Here is an ![image](image.jpg)
2. A [link](https://github.com/zed-industries)
3. And even a [referenced link][1]

[1]: https://zed.dev

| tables | are |
| --- | --- |
| properly | scoped |

````
2025-09-09 13:05:07 -06:00
Ben Brandt
5e58f44d85 Fix auth in edit_agent evals (#37869)
Somehow we have a regression where the auth wasn't being called, so the
model didn't exist.

Looking at the code, it is likely this was relying on some other part of
the code doing the auth, since the order wouldn't have worked before
without that happening. This new order of doing auth before checking for
available models should fix it going forward.

Release Notes:

- N/A
2025-09-09 19:00:24 +00:00
Jakub Konka
d8085d3ac0 zed: Hide Install CLI menu button on Windows (#37843)
The "Install CLI" menu button and `install_cli::Install` action are
effectively no-op on Windows since the CLI is directly available in
Windows Terminal (CMD prompt, PowerShell, etc.) after the user runs Zed
installer package.

Release Notes:

- N/A

Co-authored-by: Peter Tripp <peter@zed.dev>
2025-09-09 20:56:08 +02:00
Anthony Eid
707d0e6ebd settings ui: Add text field support to ui layer (#37868)
This is an initial implementation that isn't used for any settings yet,
but will be used once `Vec<String>` is implemented.

I also updated the window.with_state api to grant access to a
`Context<S>` app reference instead of just an App.

## Example

<img width="603" height="83" alt="Screenshot 2025-09-09 at 2 15 56 PM"
src="https://github.com/user-attachments/assets/7b3fc350-a157-431f-a4bc-80a1806a3147"
/>


Release Notes:

- N/A
2025-09-09 18:48:22 +00:00
Lev Zakharov
46fb521333 git_ui: Show author name on commits in branch picker (#36812)
See related discussion
https://github.com/zed-industries/zed/discussions/36511.

<img alt="zed"
src="https://github.com/user-attachments/assets/da7fc30d-2504-48f4-a392-7c8d5cd8acb1"
/>

Release Notes:

- Added option to show the author name in a branch picker commit
information

---------

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2025-09-09 18:44:46 +00:00
Ivan Trubach
9529cd18d1 project_panel: Add action to open file in split pane (#36973)
Closes #18605

Related:
- https://github.com/zed-industries/zed/discussions/16901
- https://github.com/zed-industries/zed/issues/10549

Adds an action to open file in split pane. Also updates vim keybindings
for better compatibility with netrw:
[“v”](bc461f952d/runtime/pack/dist/opt/netrw/doc/netrw.txt (L1091))
and
[“o”](bc461f952d/runtime/pack/dist/opt/netrw/doc/netrw.txt (L1075))
keys should open file in splits.

<table>
<tr>
<td><video
src="https://github.com/user-attachments/assets/e24c6fd4-4eb0-407a-bdd1-5300908ea2a1">
<td><video
src="https://github.com/user-attachments/assets/fa0b8105-41a9-4421-a3cc-89244a90d67a">
</table>


Release Notes:

- Added `project_panel::OpenSplitVertical` and
`project_panel::OpenSplitHorizontal` actions for opening file in a
splits.
2025-09-10 00:14:15 +05:30
Marco Munizaga
14ffd7b53f editor: Implement Go to next/prev Document Highlight (#35994)
Closes #21193
Closes #14703 

Having the ability to navigate directly to the next
symbolHighlight/reference lets you follow the data flow of a variable.
If you highlight the function itself (depending on the LSP), you can
also navigate to all returns.

Note that this is a different feature from navigating to the next match,
as that is not language-context aware. For example, if you have a var
named foo it would also navigate to an unrelated variable fooBar.

Here's how this patch works:

- The editor struct has a background_highlights.
- Collect all highlights with the keys [DocumentHighlightRead,
DocumentHighlightWrite]
- Depending on the direction, move the cursor to the next or previous
highlight relative to the current position.

Release Notes:

- Added `editor::GoToNextDocumentHighlight` and
`editor::GoToPreviousDocumentHighlight` to navigate to the next LSP
document highlight. Useful for navigating to the next usage of a certain
symbol.
2025-09-09 18:38:38 +00:00
Jacob
9431c65733 git: Improve error messages (#35946)
Release Notes:

- Improved git error messages

Includes stderr in the error message for git commands, provides better
output for things like errors when switching branches.

Before:
<img width="702" height="330" alt="image"
src="https://github.com/user-attachments/assets/f32402ae-b85c-4b0b-aae8-789607e8ec9e"
/>

After:
<img width="650" height="575" alt="image"
src="https://github.com/user-attachments/assets/308dbe3c-1ff9-40b9-a187-1e12d2488c80"
/>

---------

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2025-09-09 18:16:29 +00:00
Paul Sadauskas
b2d7e34e80 Update Editor::select_larger_syntax_node (#36971)
When the cursor was sitting on a syntactically insignificant character,
like a `{` or `,`, this function was selecting only that character, when
what the user likely wanted was to select the next larger syntax node.

Those punctuation characters all seemed to be not "named", in
tree-sitter terminology, so I updated the function to walk up the node
tree until it found a node where `is_named()` is true.

Closes #4555 

Also, while writing the tests, the output of a failing test with the
wrong thing selected was harder to read than it needed to be.

It used to output a diff of ranges, like this:

<img width="217" height="111" alt="image"
src="https://github.com/user-attachments/assets/00de53a8-8776-47aa-8101-5a5b5bc3fa5e"
/>

I leveraged the existing `generate_marked_text` helper function and
updated the assertion to output a diff of the text with the selection
markers:

<img width="211" height="116" alt="image"
src="https://github.com/user-attachments/assets/53b2b882-2676-4c70-8718-e2e2ba6f254e"
/>

Happy to make that a separate PR, if needed.

Release Notes:

- Fixed Editor select_larger_syntax_node to be smart about punctuation.
2025-09-09 12:13:20 -06:00
Antonio Scandurra
61d4718f2b Make it possible to support GPUI in the scheduler crate (#37849)
Added features that weren't needed in our cloud code.

Release Notes:

- N/A

---------

Co-authored-by: Nathan <nathan@zed.dev>
2025-09-09 18:10:03 +00:00
nick-kilian
9e903c9fd1 Add path/status sorting toggle to git panel menu (#35704)
Adds a new menu option to toggle between sorting git entries by path or
status, with settings integration

Release Notes:

- Git Panel: Added toggle to switch between sorting git panel entries by
path or by status (available in git panel ellipsis menu)

---------

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2025-09-09 17:55:25 +00:00
Warpten
d81479ee57 Allow user-defined worktree names in title bar and platform windows (#36713)
Closes #36637 

Release Notes:
- Adds the ability to specify a human-readable project name for each
worktree.


https://github.com/user-attachments/assets/ce980fa6-65cf-46d7-9343-d08c800914fd
2025-09-09 11:50:58 -06:00
Piotr Osiewicz
a2edd56587 python: Add import paths to Pyright/BasedPyright completion items (#37865)
Release Notes:

- python: Added package origin to completions from Pyright/BasedPyright
2025-09-09 17:50:18 +00:00
Agus Zubiaga
d7a9be03d1 acp: Ensure connection subprocess gets killed on drop (#37858)
It appears that in macOS, the `AcpConnection._wait_task` doesn't always
get dropped when quitting the app. In these cases, the subprocess would
be kept alive because we move the `child` into it.

Instead, we will now explicitly kill it when `AcpConnection` is dropped.
It's ok to do this because when the connection is dropped, the thread is
also dropped, so there's no need to report the exit status to it.

Closes #37741

Release Notes:

- Claude Code: Fix subprocess leak on app quit
2025-09-09 17:22:19 +00:00
Conrad Irwin
cdbddc2170 Allow unauthenticated commit models to show (#37857)
Closes #37462
Closes #37814

Release Notes:

- Fixed a bug where the commit generation message would not always show
2025-09-09 17:05:49 +00:00
localcc
f397294640 Fix git staging in a subfolder (#37860)
Closes #37418 

Ideal fix for this would be #37855 but that is a large refactor so
implementing this as a workaround.

Release Notes:

- N/A
2025-09-09 16:50:26 +00:00
Umesh Yadav
8527dcfc65 git_ui: Better handle commit message amend (#35268)
Follow up to this: #35114

* Previously we were still showing the commit message even after
cancelling amend which was the old commit message.
* This PR fixes that by restoring the commit message to the old state
before the amend begin so that in case user typed a commit message it's
shown if not then it's not.

Before:


https://github.com/user-attachments/assets/e0edcfff-863d-4367-a7c4-8a2998e702ca

After:



https://github.com/user-attachments/assets/9daf9be0-8a3d-4914-91a4-567693711b6b




Release Notes:

- Resolved an issue where cancelling an amend commit would incorrectly
leave the old commit message in the input field. The commit message box
now properly reverts to its pre-amend state.
2025-09-09 10:37:53 -06:00
Guillaume Launay
7f607a9b7d git_ui: Show current branch first in branch picker (#35138)
Closes #ISSUE

Release Notes:

- Put current branch first in branch picker
2025-09-09 10:36:26 -06:00
Agus Zubiaga
5e397e85b1 acp: Support session modes (e.g. CC plan mode) (#37632)
Adds support for [ACP session
modes](https://github.com/zed-industries/agent-client-protocol/pull/67)
enabling plan and other permission modes in CC:


https://github.com/user-attachments/assets/dea18d82-4da6-465e-983b-02b77c6dcf15


Release Notes:

- Claude Code: Add support for plan mode, and all other permission modes

---------

Co-authored-by: Bennet Bo Fenner <bennetbo@gmx.de>
Co-authored-by: Richard Feldman <oss@rtfeldman.com>
Co-authored-by: Danilo Leal <daniloleal09@gmail.com>
2025-09-09 13:28:02 -03:00
Marshall Bowers
ad02f6b9e3 cloud_llm_client: Add another Plan variant (#37852)
This PR adds a corresponding `FreeV2` variant to the `Plan`.

Release Notes:

- N/A
2025-09-09 15:51:22 +00:00
Piotr Osiewicz
2e7607c0e7 python: Fix instability of Pyright/BasedPyright code completions (#37850)
Pyright sets different `sortText` based on whether a given completion
item was recently resolved. This probably lines up with VSCode's way of
resolving items, but it's a no-no for us, as it makes completions
unstable.

Closes #9983

Release Notes:

- python: Fixed code completions having arbitrary order when using
Pyright/basedpyright
2025-09-09 15:34:57 +00:00
Joseph Mearman
0ac1752668 terminal: Sanitize trailing periods in URL detection (#37684)
Fixes #12338, related to #37616

This change improves URL detection in the terminal by removing trailing
periods that appear to be sentence punctuation rather than part of the
URL structure. It builds upon the parentheses sanitization work from
#37076 by consolidating both approaches into a unified
`sanitize_url_punctuation` function.

## Changes
- Combines parentheses and period sanitization into a single
`sanitize_url_punctuation` function
- Uses optimized single traversal with `fold()` for parentheses counting
(addressing code review feedback)
- Removes trailing periods using heuristics to distinguish sentence
punctuation from legitimate URL components
- Removes multiple trailing periods (always considered punctuation)
- Removes single trailing periods when they appear after alphanumeric
characters or slashes
- Preserves periods that are part of legitimate URL structure (e.g.,
version numbers, IP addresses, subdomains)
- Maintains existing parentheses balancing logic from #37076

## Implementation Details
- **Parentheses handling**: Counts opening and closing parentheses,
removes trailing `)` when unbalanced
- **Period handling**: Uses `take_while()` iterator for efficient period
counting
- **Performance**: Single pass counting with optimized loop to avoid
redundant work
- **Code clarity**: Uses let-else pattern for readable conditional logic

## Testing
- Added comprehensive test coverage for both parentheses and period
sanitization
- Tests cover balanced vs unbalanced parentheses cases  
- Tests cover various period scenarios including legitimate URL periods
vs sentence punctuation
- All existing tests continue to pass

## Release Notes

- Improved terminal URL detection by further trimming trailing
punctuation. URLs ending with periods (like
`https://example.com.`) and unbalanced parentheses (like
`https://example.com/path)`) are now properly detected without including
the trailing punctuation.
2025-09-09 10:39:09 -04:00
Dave Waggoner
af1875f91c terminal_view: Improve path hyperlink navigation by considering the terminal working directory (#36962)
Closes #34027

Release Notes:

- Improved terminal path hyperlink navigation by considering the
terminal working directory
2025-09-09 10:31:37 -04:00
Smit Barmase
734f94b71c agent_ui: Fix crash when typing multibyte character after mention (#37847)
Closes #36333

Release Notes:

- Fixed a crash that occurred when typing an IME character right after a
mention in the Agent Panel.
2025-09-09 19:16:22 +05:30
Danilo Leal
136468a4df keymap editor: Add some adjustments to the UI (#37819)
- Makes the keymap editor search container more consistent with the
project & file search corresponding elements
- Changes the keymap editor menu item in the user menu be called "Keymap
Editor", as opposed to "Key Binding", to match with the tab and action
name

Design note: Still a bit unsure about the extra space on the right for
the keymap editor. This makes it way more consistent with the other
search views, but it also just feels like space that could be used. On
the other hand, though, it's very unlikely anyone will ever use more
than 30% of the search bar width as search queries here are likely
pretty short; definitely much shorter than project search queries.

<img width="600" height="552" alt="Screenshot 2025-09-09 at 1  02@2x"
src="https://github.com/user-attachments/assets/9825a129-2c5a-4852-9837-c586b88e9332"
/>


Release Notes:

- N/A
2025-09-09 09:36:12 -03:00
Lukas Wirth
adf43d691a project: Remove non searchable buffer entries on buffer close (#37841)
Release Notes:

- N/A
2025-09-09 11:21:51 +00:00
localcc
466a2e22d5 Improve font rendering on macOS (#37622)
Part of https://github.com/zed-industries/zed/issues/7992

Release Notes:

- N/A
2025-09-09 13:46:59 +03:00
Finn Evers
365c5ab45f editor: Remove unnecessary clone (#37833)
The style is taken by reference everywhere, so no need to clone it at
the start of every `prepaint`.

Release Notes:

- N/A
2025-09-09 08:04:27 +00:00
Jakub Konka
11d81b95d4 Revert "git: Use self.git_binary_path instead raw git string" (#37828)
Reverts zed-industries/zed#37757
2025-09-09 06:36:25 +00:00
Michael Sloan
4b3b2acf75 Fix hot reload of builtin TreeSitter queries on Linux (#37825)
`fs.watch` is recursive on mac and non-recursive on Linux.

Release Notes:

- N/A
2025-09-09 05:55:28 +00:00
Danilo Leal
849424740f Fix code action menu items font size in toolbar (#37824)
Closes https://github.com/zed-industries/zed/issues/36478

Release Notes:

- N/A
2025-09-09 02:20:23 -03:00
Danilo Leal
3e605c2c4b docs: Fix casing on mentions to some brand names (#37822)
- MacOS → macOS
- VSCode → VS Code
- SublimeText → Sublime Text
- Javascript/Typescript → JavaScript/TypeScript

Release Notes:

- N/A
2025-09-09 01:45:55 -03:00
Danilo Leal
82b11bf77c docs: Include Cursor in the list of supported base keymaps (#37821)
We were missing that in the /key-bindings page. Also took advantage of
the opportunity to add a bunch of small writing tweaks.

Release Notes:

- N/A
2025-09-09 01:39:52 -03:00
Conrad Irwin
3a437fd888 Remove Chat (#37789)
At RustConf we were demo'ing zed, and it continually popped open the
chat panel.

We're usually inured to this because the Chat panel doesn't open unless
a Guest
is in the channel, but it made me sad that we were showing a long stream
of
vacuous comments and unresponded to questions on every demo screen.

We may bring chat back in the future, but we need more thought on the
UX, and
we need to rebuild the backend to not use the existing collab server
that we're
trying to move off of.

Release Notes:

- Removed the chat feature from Zed (Sorry to the 5 of you who use this
on the regular!)
2025-09-08 21:53:17 -06:00
Conrad Irwin
96c429d2c3 Only reject agent actions, don't restore checkpoint on revert (#37801)
Updates #37623

Release Notes:

- Changed the behaviour when editing an old message in a native agent
thread.
Prior to this, it would automatically restore the checkpoint (which
could
lead to a surprising amount of work being discarded). Now it will just
reject
any unaccepted agent edits, and you can use the "restore checkpoint"
button
  for the original behavior.
2025-09-08 20:18:40 -06:00
Marshall Bowers
ea4073e50e cloud_llm_client: Add new Plan variants (#37810)
This PR adds new variants to the `Plan` enum.

Release Notes:

- N/A
2025-09-09 00:18:43 +00:00
Ben Kunkle
8c93112869 settings_ui: Add Basic Implementation of Language Settings (#37803)
Closes #ISSUE

Release Notes:

- N/A *or* Added/Fixed/Improved ...

---------

Co-authored-by: Anthony <anthony@zed.dev>
2025-09-08 20:14:36 -04:00
Marshall Bowers
1feffad5e8 Remove zed-pro feature flag (#37807)
This PR removes the `zed-pro` feature flag, as it was not being used.

Release Notes:

- N/A
2025-09-08 23:23:16 +00:00
Ivan Danov
ae54a4e1b8 Add commands to select next/previous siblings in the syntax tree (#35053)
Closes #5133 and discussion
https://github.com/zed-industries/zed/discussions/33493

This PR adds two new commands to select next/previous siblings in the
syntax tree. These commands were modelled after the existing ones about
expand/shrink selection. With this PR I've added new key bindings
inspired by `helix` for previous / next / expand / shrink selections.



https://github.com/user-attachments/assets/4ef7fadb-0b82-4897-95c7-1737827bf4ac


Release Notes:

- Add commands to select next/previous siblings in the syntax tree

---------

Co-authored-by: Joseph T. Lyons <JosephTLyons@gmail.com>
2025-09-08 23:11:53 +00:00
Danilo Leal
4a0a7d1d27 Add item for the debugger panel in the app view menu (#37805)
Release Notes:

- Enabled the debugger panel to be opened via the app's "View" menu
option
2025-09-08 19:19:10 -03:00
Danilo Leal
5934d3789b python: Improve Basedpyright banner styles (#37802)
Just tidying this up a bit.

Release Notes:

- N/A
2025-09-08 18:51:13 -03:00
Danilo Leal
acde79dae7 agent: Improve popover trigger styles (#37800)
This PR mostly adds some style treatment to popover button triggers in
the agent panel, either making them better aligned with their trigger or
adjusting the color to better clarify which button is triggering the
currently opened menu.

Moving forward, I think the selected styles at least should probably be
tackled at the component level, whether that's a context menu or a
popover, so we don't have to ever do this manually (and running the risk
of forgetting to do it).

Release Notes:

- N/A
2025-09-08 18:39:49 -03:00
Patsakula Nikita
246c644316 agent_servers: Fix proxy configuration for Gemini (#37790)
Closes #37487 

Proxy settings are now taken from the Zed configuration and passed to
Gemini via the "--proxy" flag.

Release Notes:

- acp: Gemini ACP server now uses proxy settings from Zed configuration.
2025-09-08 20:44:40 +00:00
Marshall Bowers
e4de26e5dc cloud_llm_client: Remove unused code (#37799)
This PR removes some unused code from the `cloud_llm_client`.

This was only used on the server, so we can move it there.

Release Notes:

- N/A
2025-09-08 20:42:42 +00:00
ZhangJun
7091c70a1e open_ai: Trim newline before "data:" prefix and account for the possibility of no space after ":" (#37644)
I'am using an openai compatible model, but got nothing in agent thread
panel, and Zed log has "Model generated an empty summary" line.

I add one log to open_ai.rs:
<img width="2454" height="626" alt="图片"
src="https://github.com/user-attachments/assets/85354c7d-a0cc-4bba-86fd-2a640038a13e"
/>

and got:

<img width="3456" height="278" alt="图片"
src="https://github.com/user-attachments/assets/7746aedd-5d76-44b5-90f2-e129a1507178"
/>

It appear that `let line = line.strip_prefix("data: ")?;` can not handle
correctly.

Release Notes:

- N/A

---------

Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2025-09-08 22:01:55 +02:00
Cole Miller
fa0df6da1c python: Replace pyright with basedpyright (#35362)
Follow-up to #35250. Let's experiment with having this by default on
nightly.

Release Notes:

- Added built-in support for the basedpyright language server for Python
code. basedpyright is now enabled by default, and pyright (previously
the primary Python language server) remains available but is disabled by
default. This supersedes the basedpyright extension, which can be
uninstalled. Advantages of basedpyright over pyright include support for
inlay hints, semantic highlighting, auto-import code actions, and
stricter type checking. To switch back to pyright, add the following
configuration to settings.json:

```json
{
  "languages": {
    "Python": {
      "language_servers": ["pyright", "pylsp", "!basedpyright"]
    }
  }
}
```

---------

Co-authored-by: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com>
Co-authored-by: Lukas Wirth <lukas@zed.dev>
2025-09-08 19:15:17 +00:00
Cole Miller
99102a84fa ACP over SSH (#37725)
This PR adds support for using external agents in SSH projects via ACP,
including automatic installation of Gemini CLI and Claude Code,
authentication with API keys (for Gemini) and CLI login, and custom
agents from user configuration.

Co-authored-by: maan2003 <manmeetmann2003@gmail.com>

Release Notes:

- agent: Gemini CLI, Claude Code, and custom external agents can now be
used in SSH projects.

---------

Co-authored-by: maan2003 <manmeetmann2003@gmail.com>
2025-09-08 14:19:41 -04:00
Cole Miller
5f01f6d75f agent: Make read_file and edit_file tool call titles more specific (#37639)
For read_file and edit_file, show the worktree-relative path if there's
only one visible worktree, and the "full path" otherwise. Also restores
the display of line numbers for read_file calls.

Release Notes:

- N/A
2025-09-08 12:57:22 -04:00
Dave Waggoner
a66cd820b3 Fix line endings in terminal_hyperlinks.rs (#37654)
Fixes Windows line endings in `terminal_hyperlinks.rs`, which was
accidentally originally added with them.

Release Notes:

- N/A
2025-09-08 12:21:47 -04:00
hong jihwan
f07da9d9f2 Correctly parse backslash character on replacement (#37014)
When a keybind contains a backslash character (\\), it is parsed
incorrectly, which results in an invalid keybind configuration.


This patch fixes the issue by ensuring that backslashes are properly
escaped during the parsing process. This allows them to be used as
intended in keybind definitions.

Release Notes:

- Fixed an issue where keybinds containing a backslash character (\\)
failed to be replaced correctly


## Screenshots
<img width="912" height="530" alt="SCR-20250828-borp"
src="https://github.com/user-attachments/assets/561a040f-575b-4222-ac75-17ab4fa71d07"
/>
<img width="912" height="530" alt="SCR-20250828-bosx"
src="https://github.com/user-attachments/assets/b8e0fb99-549e-4fc9-8609-9b9aa2004656"
/>
2025-09-08 12:17:48 -04:00
Iha Shin (신의하)
8d05bb090c Add injections for Isograph function calls in JavaScript and TypeScript (#36320)
Required for https://github.com/isographlabs/isograph/pull/568 to work
properly. Tested with a local build and made sure everything's working
great!

Release Notes:

- JavaScript/TypeScript/JSX: Added support for injecting Isograph language support into `iso`
function calls
2025-09-08 16:04:37 +00:00
Dino
2325f14713 diagnostics: Current file diagnostics view (#34430)
These changes introduce a new command to the Diagnostics panel,
`diagnostics: deploy current file`, which allows the user to view the
diagnostics only for the currently opened file.

Here's a screen recording showing these changes in action 🔽 

[diagnostics: deploy current
file](https://github.com/user-attachments/assets/b0e87eea-3b3a-4888-95f8-9e21aff8ea97)

Closes #4739 

Release Notes:

- Added new `diagnostics: deploy current file` command to view
diagnostics for the currently open file

---------

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2025-09-08 09:14:24 -06:00
Ben Kunkle
fe2aa3f4cb onboarding: Fix font loading frame delay (#37668)
Closes #ISSUE

Fixed an issue where the first frame of the `Editing` page in onboarding
would have a slight delay before rendering the first time it was
navigated to. This was caused by listing the OS fonts on the main
thread, blocking rendering. This PR fixes the issue by adding a new
method to the font family cache to prefill the cache on a background
thread.

Release Notes:

- N/A *or* Added/Fixed/Improved ...

---------

Co-authored-by: Mikayla Maki <mikayla.c.maki@gmail.com>
Co-authored-by: Anthony Eid <hello@anthonyeid.me>
Co-authored-by: Anthony <anthony@zed.dev>
2025-09-08 11:09:54 -04:00
fantacell
10989c702c helix: Add match operator (#34060)
This is an implementation of matching like "m i (", as well as "] (" and
"[ (" in `helix_mode` with a few supported objects and a basis for more.

Release Notes:

- Added helix operators for selecting text objects

---------

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2025-09-08 08:48:47 -06:00
张小白
3f80ac0127 macos: Fix menu bar flickering (#37707)
Closes #37526

Release Notes:

- Fixed menu bar flickering when using some IMEs on macOS.
2025-09-08 10:44:19 -04:00
Bennet Bo Fenner
4f1634f95c Remove unused semantic_index crate (#37780)
Release Notes:

- N/A
2025-09-08 13:38:31 +00:00
Eduardo Alba
40eec32cb8 markdown_preview: Fix trimming of leading whitespace in Markdown lists (#35750)
Closes #35712

Release Notes:

- Fixed white-space trimming leading to disconnect between list items
and content in markdown previews.

---------

Co-authored-by: Bennet Bo Fenner <bennetbo@gmx.de>
2025-09-08 12:37:11 +00:00
张小白
17499453f6 windows: Check required GPU/driver feature StructuredBuffer (#37776)
Check whether the GPU/driver supports the StructuredBuffer feature
required by our shaders. If it doesn’t, log an error and skip that
GPU/driver, so Windows can fall back to the software renderer.

Release Notes:

- N/A
2025-09-08 12:22:57 +00:00
Lukas Wirth
80a4746a46 project: Be explicit about project-searchability for buffers (#37773)
Closes https://github.com/zed-industries/zed/issues/28830

Release Notes:

- Fixed builtin buffers and log views showing up in project search
2025-09-08 11:22:36 +00:00
Jakub Konka
01f5b73e3b cargo: Remove unused -fuse-ld=lld flag from Win config (#37769)
It is unused and generates a warning

```
 LINK : warning LNK4044: unrecognized option '/fuse-ld=lld'; ignored
```

If in the future we want to give `lld-link.exe` a try, we can set

```toml
linker = "lld-link.exe"
```

instead. At the time of writing, my tests have shown that there is no
real difference between `lld-link` and `link` in terms of linking speed.

Release Notes:

- N/A
2025-09-08 10:43:56 +00:00
Lukas Wirth
a0081dd693 project: Consider all worktrees for activation script search (#37764)
Should fix https://github.com/zed-industries/zed/issues/37734

Release Notes:

- Fixed venv not always activating correctly
2025-09-08 10:06:43 +00:00
chbk
f522823988 Highlight shorthand fields in Rust (#37674)
Release Notes:

- Highlight shorthand fields in Rust

| Zed 0.202.7 | With this PR |
| --- | --- |
| <img width="370" height="50" alt="rust-0 202 7"
src="https://github.com/user-attachments/assets/856a4d82-3ad0-4248-ad51-0472a0b6531a"
/> | <img width="370" height="50" alt="rust-pr"
src="https://github.com/user-attachments/assets/25b8e357-8519-4533-9026-3f2874b42ddb"
/> |
2025-09-08 12:32:08 +03:00
Martin Pool
5a8603bebb Install mold from the OS on Debian 13 (Trixie) (#37712)
I ran `scripts/linux` on Debian Trixie 13. It suggested manually
installing Mold, but [mold](http://packages.debian.org/mold) is packaged
on Debian and so we could install it automatically.

The version packaged there seems to work well enough for `cargo t` to
pass, at least.

## Tested

```
; sudo apt remove mold libstdc++-14-dev
... uninstalls them
; ./script/linux
The following NEW packages will be installed:
  build-essential clang clang-19 clang-tools-19 g++ g++-14 g++-14-x86-64-linux-gnu g++-x86-64-linux-gnu libstdc++-14-dev mold
; cargo t
(passes)
```

Release Notes:

- N/A
2025-09-08 12:29:17 +03:00
Martin Pool
abac87c2f8 tests: Fix doctests in crates/component (#37716)
Previously, `cargo test --package component` failed due to missing
imports for a doctest:


```

   Doc-tests component

running 1 test
test crates/component/src/component.rs - Component::description (line 229) ... FAILED

failures:

---- crates/component/src/component.rs - Component::description (line 229) stdout ----
error: cannot find derive macro `Documented` in this scope
 --> crates/component/src/component.rs:231:10
  |
4 | #[derive(Documented)]
  |          ^^^^^^^^^^

error[E0599]: no associated item named `DOCS` found for struct `MyComponent` in the current scope
 --> crates/component/src/component.rs:236:20
  |
5 | struct MyComponent;
  | ------------------ associated item `DOCS` not found for this struct
...
9 |         Some(Self::DOCS)
  |                    ^^^^ associated item not found in `MyComponent`

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0599`.
Couldn't compile the test.

failures:
    crates/component/src/component.rs - Component::description (line 229)

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.29s

error: doctest failed, to rerun pass `-p component --doc`
bobcat ~/src/zed (doctests) 18:33

``` 

This might be unnoticed if you mostly run nextest, as it does not run
doctests.

Release Notes:

- N/A
2025-09-08 12:23:33 +03:00
Jakub Konka
c3d065cecc git: Use self.git_binary_path instead raw git string (#37757)
Release Notes:

- N/A
2025-09-08 11:05:04 +02:00
Remco Smits
e1a5d29972 markdown: Add support for inline HTML img tags inside text (#37264)
Follow-up: #36700

This PR adds basic support for showing images inline inside a text.

As you can see inside the before screenshot, the image was displayed
right below the `Some inline text` text. This was because we didn't
consider the image to be inline with the text (paragraph). Now we do :)

All the test changes are making sure it is not more than 1 element
parsed, instead of only checking for the first parsed element. This
could work out bad when we return more than 1 result.

**Before**
<img width="1717" height="1344" alt="Screenshot 2025-08-31 at 13 49 45"
src="https://github.com/user-attachments/assets/13c5f9dd-0e0a-4e08-b2a6-28e9a4e0cab8"
/>

**After**
<img width="1719" height="1343" alt="Screenshot 2025-08-31 at 13 42 14"
src="https://github.com/user-attachments/assets/bf7aa82f-3743-4fb3-87aa-4a97a550c4d1"
/>


**Code example**:
```markdown
<p>some inline text <img src="https://picsum.photos/200/300" alt="Description of image" style="height: 100px" /> asdjkflsadjfl</p>

# Html Tag
<img src="https://picsum.photos/200/300" alt="Description of image" />

# Html Tag with width and height
<img src="https://picsum.photos/200/300" alt="Description of image" width="100" height="200" />

# Html Tag with style attribute with width and height
<img src="https://picsum.photos/200/300" alt="Description of image" style="width: 100px; height: 200px" />

# Normal Tag
![alt text](https://picsum.photos/200/300)
```

Release Notes:

- Markdown: Added support for inline HTML `img` tags inside paragraphs
2025-09-08 11:49:32 +03:00
HE7086
d342da4e9a docs: Fix typos in language configurations (#37740)
Fixes several typos in the docs. I think there are more but I have only
read what I actually needed :)

Release Notes:

- N/A
2025-09-08 08:44:46 +00:00
Umesh Yadav
7ae8f81d74 language_models: Clear cached credentials when OpenAI and OpenAI Compatible provider api_url change (#37610)
Closes #37093

Also check this: #37099.

So currently in zed for both OpenAI and OpenAI Compatible provider when
the url is changed from settings the api_key stored in the provider
state is not cleared and it is still used. But if you restart zed the
api_key is cleared. Currently zed uses the api_url to store and fetch
the api key from credential provider. The behaviour is not changed
overall, it's just that we have made it consistent it with the zed
restart logic where it re-authenticates and fetches the api_key again. I
have attached the video below to show case before and after of this.

So all in all the problem was we were not re-authenticating the in case
api_url change while zed is still running. Now we trigger a
re-authentication and clear the state in case authentication fails.
 
OpenAI Compatible Provider:

| Before | After |
|--------|--------|
| <video
src="https://github.com/user-attachments/assets/324d2707-ea72-4119-8981-6b596a9f40a3"
/> | <video
src="https://github.com/user-attachments/assets/cc7fdb73-8975-4aaf-a642-809bb03ce319"
/> |

OpenAI Provider:

| Before | After |
|--------|--------|
| <video
src="https://github.com/user-attachments/assets/a1c07d1b-1909-4b49-b33c-fc05123e92e7"
/> | <video
src="https://github.com/user-attachments/assets/d78aeccd-5cd3-4d0c-8b9f-6f98e499d7c8"
/> |

Release Notes:

- Fixed OpenAI and OpenAI Compatible provide API keys being persisted
when changing the API URL setting. Authentication is now properly
revalidated when settings change.

---------

Signed-off-by: Umesh Yadav <git@umesh.dev>
2025-09-08 06:57:16 +02:00
Umesh Yadav
36364b16a0 agent_ui: Clear model selector query on dismiss (#37569)
Closes #36756

| Before | After |
|--------|--------|
| <video src
="https://github.com/user-attachments/assets/1d022ac6-0aea-4e98-a717-9988420c9683"/>
| <video
src="https://github.com/user-attachments/assets/78d19012-1224-4c92-a6c8-47ae4c13ca31"/>
|

Release Notes:

- agent: Clear model selector query on dismiss in agent panel

---------

Signed-off-by: Umesh Yadav <git@umesh.dev>
2025-09-08 06:52:57 +02:00
Umesh Yadav
b35959f4c2 agent_ui: Fix context_server duplication when name is updated (#35403)
Closes #35400

| Before | After |
|--------|--------|
| <video
src="https://github.com/user-attachments/assets/6aae34ca-e022-457a-9b66-47b85c976b23"/>
| <video
src="https://github.com/user-attachments/assets/ae058988-8f70-4605-b537-e045175d2e75"
/> |

Release Notes:

- agent: Fix `context_server` duplication when name is updated

---------

Signed-off-by: Umesh Yadav <git@umesh.dev>
Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2025-09-08 04:50:26 +00:00
marius851000
9450bcad25 ollama: Properly format tool calls fed back to the model (#34750)
Fix an issue that resulted in Ollama models not being able to not being
able to access the input of the commands they executed (only being able
to access the result).

This properly return the function history as shown in
https://github.com/ollama/ollama/blob/main/docs/api.md#chat-request-with-history-with-tools

Previously, function input where not returned and result where returned
as a "user" role.

Release Notes:

- ollama: Improved format when returning tool results to the models
2025-09-08 04:26:01 +00:00
Liu Jinyi
69bdef38ec editor: Fix inconsistent search behavior for untitled/temporary tabs (#37086)
Closes #37597 

Release Notes:

- N/A

---


## Problem

When using "Tab Switcher: Toggle All", temporary files (untitled buffers
without associated file paths) cannot be searched by their displayed
content. This creates an inconsistent user experience where:

- **UI Display**: Shows dynamic titles based on the first line of
content (up to 40 characters)
- **Search Text**: Only searches for the static text "untitled"

### Example
- A temporary file containing `Hello World` is displayed as "Hello
World" in the tab
- However, searching for "Hello" in Tab Switcher returns no results
- Only searching for "untitled" will find this temporary file

## Root Cause

The issue stems from inconsistent title generation logic between display
and search:

1. **Display Title** (`items.rs:724`): Uses `self.title(cx)` →
`MultiBuffer::title()` → `buffer_content_title()`
- Returns the first line of content (max 40 chars) for temporary files
   
2. **Search Text** (`items.rs:650-656`): Uses `tab_content_text()`
method
   - Returns hardcoded "untitled" for files without paths

## Solution

Modified the `tab_content_text()` method in `crates/editor/src/items.rs`
to use the same logic as the displayed title for consistency:

```rust
fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
    if let Some(path) = path_for_buffer(&self.buffer, detail, true, cx) {
        path.to_string_lossy().to_string().into()
    } else {
        // Use the same logic as the displayed title for consistency
        self.buffer.read(cx).title(cx).to_string().into()
    }
}
```
2025-09-07 11:33:17 -07:00
Michael Sloan
0e33a3afe0 zeta: Check whether data collection is allowed for recent edit history (#37680)
Also:

* Adds tests for can_collect_data.
* Temporarily removes collection of diagnostics.

Release Notes:

- Edit Prediction: Fixed a bug where requests were marked eligible for
data collection despite the recent edit history in the request involving
files that may not be open source. The requests affected by this bug
will not be used in training data.
2025-09-07 11:16:49 -06:00
Bruno Taschenbier
76aaf6a8fe Fix docs for tabs.close_position in default.json (#37729)
Minor docs fix.
Seems like 0a4ff2f475 accidentally added
"hidden" to the docs of both – `close_position` and `show_close_button`.

Release Notes:

- N/A

Co-authored-by: tastenbier <>
2025-09-07 17:00:58 +00:00
张小白
0ef7ee172f windows: Remove some unused keys from the keymap (#37722)
AFAIK, we dont handle these keys on Windows.

Release Notes:

- N/A
2025-09-07 06:45:41 +00:00
张小白
29def012a1 windows: Update Windows keymap (#37721)
Pickup the changes from #37009

Release Notes:

- N/A
2025-09-07 06:09:35 +00:00
Smit Barmase
5c30578c49 linux: Fix IME preedit text not showing in Terminal on Wayland (#37701)
Closes https://github.com/zed-industries/zed/issues/37268
 
Release Notes:

- Fixed an issue where IME preedit text was not showing in the Terminal
on Wayland.
2025-09-07 02:01:55 +05:30
Cole Miller
1552afd8bf docs: Use #action throughout configuring-zed.md (#37709)
Release Notes:

- N/A
2025-09-06 19:38:48 +00:00
Kirill Bulatov
e04473dd26 Revert "gpui: Skip test attribute expansion for rust-analyzer (#37611)" (#37705)
This reverts commit 4124bedab7.

With the new annotation, r-a starts to skip the tasks that are marked
with `gpui::test` and when it fully loads, it starts to return
module-only tasks:


https://github.com/user-attachments/assets/5af3e3e4-91b7-4f19-aab0-ed7f186e5f74


Release Notes:

- N/A
2025-09-06 16:51:51 +00:00
Kirill Bulatov
84f166fc85 Tweak word completions more (#37697)
Follow-up of https://github.com/zed-industries/zed/pull/37352
Closes https://github.com/zed-industries/zed/issues/37132

* disabled word completions in the agent panel's editor
* if not disabled, allow to trigger word completions with an action even
if the completions threshold is not reached

Release Notes:

- Fixed word completions appearing in the agent panel's editor and not
appearing when triggered with the action before the completion threshold
is reached
2025-09-06 13:39:21 +00:00
Kirill Bulatov
065518577e Fix the tasks docs (#37699)
Closes https://github.com/zed-industries/zed/issues/37698

Release Notes:

- N/A
2025-09-06 13:37:21 +00:00
Marco Groot
1d828b6ac6 Fix broken link in CONTRIBUTING.md (#37688)
Can see currently the link is dead currently, but this changes fixes
locally


https://github.com/user-attachments/assets/e01d9c47-e91e-4c24-8285-01e3b45583b9


Release Notes:

- N/A
2025-09-06 12:29:34 +02:00
Kirill Bulatov
777ce7cc97 Fixed LSP binary info not being shown in full (#37682)
Follow-up of https://github.com/zed-industries/zed/pull/37083
Closes https://github.com/zed-industries/zed/issues/37677

Release Notes:

- Fixed LSP binary info not being shown in full
2025-09-06 07:37:59 +00:00
Umesh Yadav
1f37fbd051 language_models: Use /models/user for fetching OpenRouter models (#37534)
This PR switches the OpenRouter integration from fetching all models to
fetching only the models specified in the user's account preferences.
This will help improve the experience

**The Problem**

The previous implementation used the `/models` endpoint, which returned
an exhaustive list of all models supported by OpenRouter. This resulted
in a long and cluttered model selection dropdown in Zed, making it
difficult for users to find the models they actually use.

**The Solution**

We now use the `/models/user` endpoint. This API call returns a curated
list based on the models and providers the user has selected in their
[OpenRouter dashboard](https://openrouter.ai/models).

Ref: [OpenRouter API Docs for User-Filtered
Models](https://openrouter.ai/docs/api-reference/list-models-filtered-by-user-provider-preferences)

Release Notes:

- language_models: Support OpenRouter user preferences for available
models
2025-09-06 07:42:15 +02:00
Umesh Yadav
8c9442ad11 language_models: Skip empty delta text content in OpenAI and OpenAI compatible provider (#37626)
Closes #37302 

Related: #37614 

In case of open_ai_compatible providers like Zhipu AI and z.ai they
return empty content along with usage data. below is the example json
captured from z.ai. We now ignore empty content returned by providers
now to avoid this issue where we would return the same empty content
back to provider which would error out.

```
OpenAI Stream Response JSON:
{
  "id": "2025090518465610d80dc21e66426d",
  "created": 1757069216,
  "model": "glm-4.5",
  "choices": [
    {
      "index": 0,
      "finish_reason": "tool_calls",
      "delta": {
        "role": "assistant",
        "content": ""
      }
    }
  ],
  "usage": {
    "prompt_tokens": 7882,
    "completion_tokens": 150,
    "total_tokens": 8032,
    "prompt_tokens_details": {
      "cached_tokens": 7881
    }
  }
}
```

Release Notes:

- Skip empty delta text content in OpenAI and OpenAI compatible provider

Signed-off-by: Umesh Yadav <git@umesh.dev>
2025-09-06 07:16:08 +02:00
Michael Sloan
47a475681f Optimize Chunks::seek when offset is in current chunk (#37659)
Release Notes:

- N/A
2025-09-06 04:22:55 +00:00
Max Brunsfeld
23dc1f5ea4 Disable foreign keys in sqlite when running migrations (#37572)
Closes #37473

### Background

Previously, we enabled foreign keys at all times for our sqlite database
that we use for client-side state.
The problem with this is that In sqlite, `alter table` is somewhat
limited, so for many migrations, you must *recreate* the table: create a
new table called e.g. `workspace__2`, then copy all of the data from
`workspaces` into `workspace__2`, then delete the old `workspaces` table
and rename `workspaces__2` to `workspaces`. The way foreign keys work in
sqlite, when we delete the old table, all of its associated records in
other tables will be deleted due to `on delete cascade` clauses.

Unfortunately, one of the types of associated records that can be
deleted are `editors`, which sometimes store unsaved text. It is very
bad to delete these records, as they are the *only* place that this
unsaved text is stored.

This has already happened multiple times as we have migrated tables as
we develop Zed, but I caused it to happened again in
https://github.com/zed-industries/zed/pull/36714.

### The Fix

The Sqlite docs recommend a multi-step approach to migrations where you:

* disable foreign keys
* start a transaction
* create a new table
* populate the new table with data from the old table
* delete the old table
* rename the new table to the old name
* run a foreign key check
* if it passes, commit the transaction
* enable foreign keys

In this PR, I've adjusted our sqlite migration code path to follow this
pattern more closely. Specifically, we disable foreign key checks before
running migrations, run a foreign key check before committing, and then
enable foreign key checks after the migrations are done.

In addition, I've added a generic query that we run *before* running the
foreign key check that explicitly deletes any rows that have dangling
foreign keys. This way, we avoid failing the migration (and breaking the
app) if a migration deletes data that *does* cause associated records to
need to be deleted.

But now, in the common case where we migrate old data in the new table
and keep the ids, all of the associated data will be preserved.

Release Notes:

- Fixed a bug where workspace state would be lost when upgrading from
Zed 0.201.x. or below.
2025-09-06 01:09:50 +00:00
chbk
a6a111cadd Highlight labels in Go (#37673)
Release Notes:

- Highlight labels in Go

| Zed 0.202.7 | With this PR |
| --- | --- |
| <img width="160" height="50" alt="go-0 202 7"
src="https://github.com/user-attachments/assets/1a1b3b3c-52ae-41e3-a52b-c2a9bb7589d2"
/> | <img width="160" height="50" alt="go-pr"
src="https://github.com/user-attachments/assets/29020b9f-ed03-4298-aa5b-0201a81fd5e6"
/> |
2025-09-06 01:36:36 +02:00
Piotr Osiewicz
6a7b84eb87 toolchains: Allow users to provide custom paths to toolchains (#37009)
- **toolchains: Add new state to toolchain selector**
- **Use toolchain term for Add Toolchain button**
- **Hoist out a meta function for toolchain listers**

Closes #27332

Release Notes:

- python: Users can now specify a custom path to their virtual
environment from within the picker.

---------

Co-authored-by: Danilo Leal <daniloleal09@gmail.com>
2025-09-06 00:47:39 +02:00
Nia
59bdbf5a5d Various fixups to unsafe code (#37651)
A collection of fixups of possibly-unsound code and removing some small
useless writes.

Release Notes:

- N/A
2025-09-06 00:27:14 +02:00
Remco Smits
64b6e8ba0f debugger: Fix allow showing more than 1 compact session item (#37036)
Closes #36978

This PR fixes an issue that we would only show the first `root -> child`
session in compact mode, but the session that came after it, we would
only show the child session label instead of also adding the parent
label due to compact mode.

## Before
<img width="348" height="173" alt="Screenshot 2025-08-27 at 22 18 39"
src="https://github.com/user-attachments/assets/ad6afd3a-196d-497f-812a-00698676ee90"
/>

## After
<img width="563" height="211" alt="Screenshot 2025-08-27 at 21 57 16"
src="https://github.com/user-attachments/assets/a953ef2a-a796-4160-b868-96e96f81c858"
/>

With 3 parent + child sessions and one parent session only.
<img width="484" height="223" alt="Screenshot 2025-08-27 at 22 22 13"
src="https://github.com/user-attachments/assets/a26f79a4-63a5-43d0-a714-d62cb1995e6e"
/>

cc @cole-miller I know we hacked on this some while ago, so figured you
might be the best guy to ask for a review.

Release Notes:

- Debugger: Fix to allow showing more than 1 compact session item

---------

Co-authored-by: Anthony <anthony@zed.dev>
2025-09-05 21:35:28 +00:00
morgankrey
236b3e546e Update Link (#37671)
Documentation fix

Release Notes:

- N/A
2025-09-05 14:34:13 -07:00
Anthony Eid
ea363466aa Fix attach modal showing local processes in SSH sessions (#37608)
Closes #37520

This change makes the attach modal load processes from the remote server
when connecting via SSH, rather than showing local processes from the
client machine.

This works by using the new GetProcessesRequest RPC message to allow
downstream clients to get the correct processes to display. It also only
works with downstream ssh clients because the message handler is only
registered on headless projects.

Release Notes:

- debugger: Fix bug where SSH attach modal showed local processes
instead of processes from the server
2025-09-05 17:03:42 -04:00
Smit Barmase
c45177e296 editor: Fix fold placeholder hover width smaller than marker (#37663)
Bug:
<img width="196" height="95" alt="Screenshot 2025-09-06 at 1 21 39 AM"
src="https://github.com/user-attachments/assets/66ec0fc9-961e-4289-bd75-68b24dad485e"
/>

The fold marker we use, `⋯`, isn’t rendered at the same size as the
editor’s font. Notice how the fold marker appears larger than the same
character typed directly in the editor buffer.

<img width="146" height="82" alt="image"
src="https://github.com/user-attachments/assets/a059d221-6b55-4cf9-bc1e-898ff5444006"
/>

When we shape the line, we use the editor’s font size, and it ends up
determining the element’s width. To fix this, we should treat the
ellipsis as a UI element rather than a buffer character, since current
visual size looks good to me.

<img width="196" height="95" alt="Screenshot 2025-09-06 at 1 29 28 AM"
src="https://github.com/user-attachments/assets/1b766d46-00ab-40c7-b98a-95ea2d4b29bf"
/>

Release Notes:

- Fixed an issue where the fold placeholder’s hover area was smaller
than the marker.
2025-09-06 02:05:42 +05:30
Finn Evers
45fa034107 Restore notification panel settings (#37661)
Follow-up to https://github.com/zed-industries/zed/pull/37489

Notification panel settings were always missing the content, hence this
PR adds it. After #37489, the use of the same content twice broke
things, which currently makes the notification panel non-configurable on
Nightly. This PR fixes this.

There once was an issue about the documentation for the panel being
wrong as well. However, I was just unable to find that sadly.

Release Notes:

- N/A
2025-09-05 21:50:51 +02:00
Conrad Irwin
1c5c8552f2 Show actual error in InvalidBufferView (#37657)
Release Notes:

- Update error view to show the error
2025-09-05 12:03:26 -07:00
Conrad Irwin
5d374193bb Add terminal::Toggle (#37585)
Co-Authored-By: Brandan <b5@n0.computer>

Release Notes:

- Added a new action `terminal::Toggle` that is by default bound to
'ctrl-\`'. This copies the default behaviour from VSCode and Jetbrains
where the terminal opens and closes correctly. If you'd like the old
behaviour you can rebind 'ctrl-\`' to `terminal::ToggleFocus`

Co-authored-by: Brandan <b5@n0.computer>
2025-09-05 17:34:39 +00:00
Dino
b65fb06264 editor: Fix text manipulation on line mode selections (#37646)
This commit updates the implementation for
`editor::Editor.manipulate_text` to use
`editor::selections_collection::SelectionsCollection.all_adjusted`
instead of `editor::selections_collection::SelectionsCollection.all`, as
the former takes into account the selection's `line_mode`, fixing the
issue where, if an user was in vim's visual line mode, running the
`editor: convert to upper case` command would not work as expected.

Closes #36953 

Release Notes:

- Fixed bug where using the editor's convert case commands while in
vim's Visual Line mode would not work as expected
2025-09-05 10:12:51 -07:00
Matin Aniss
b3405c3bd1 Add line ending selector (#35392)
Partially addresses this issue #5294

Adds a selector between `LF` and `CRLF` for the buffer's line endings,
the checkmark denotes the currently selected line ending.

Selector
<img width="487" height="66" alt="image"
src="https://github.com/user-attachments/assets/13f2480f-4d2d-4afe-adf5-385aeb421393"
/>

Release Notes:

- Added line ending selector.

---------

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2025-09-05 09:52:57 -07:00
Peter Tripp
638320b21e Improve macOS version information in telemetry (#37185)
macOS versions are currently reported as `macOS 26.0.0`.
But this makes it impossible to differentiate amongst macOS Beta
releases which have the same version number (`X.0.0`) but are different
builds.

This PR adds build number info to `os_version` for macOS Betas and
[Rapid Security Response](https://support.apple.com/en-us/102657)
release that have identical version numbers to stable release, but have
different builds numbers. We can differentiate them because the build
numbers end with a letter.

| Version | Before | After |
| - | - | - | 
| macOS Sonoma 14.7.8 | 14.7.8 | 14.7.8 |
| macOS Sequoia 15.6.1 | 15.6.1 | 15.6.1 |
| mcOS Ventura 13.3.1 | 13.3.1 | 13.3.1 |
| macOS Ventura 13.3.1 (a) |  13.3.1 | 13.3.1 (Build 22E772610a) |
| macOS Tahoe 26.0.0 (Beta1) | 26.0.0 | 26.0.0 (Build 25A5316a) |
| macOS Tahoe 26.0.0 (Beta5) | 26.0.0 | 26.0.0 (Build 25A5349a) | 

This should cause minimal telemetry changes and only impacting a macOS
betas and a couple specific older macOS versions, but will allow
differentiation between macOS beta releases in GitHub issues.

Alternatives:
1. Leave as-is (can't differentiate between macOS beta builds)
2. Always include build number info (impacts telemetry; more consistent
going forward; differentiates non-final Release Candidates which don't
include a trailing letter)

I couldn't find a cocoa method to retrieve macOS build number, so I
switched dependencies from `cocoa` to `objc2-foundation` in the client
crate. We already depend upon this crate as a dependency of
`blade-graphics` so I matched the features of that and so workspace-hack
doesn't change.

1ebc69a447/tooling/workspace-hack/Cargo.toml (L355)

Release Notes:

- N/A
2025-09-05 12:40:47 -04:00
张小白
91ab0636ec windows: Make sure zed.sh using the correct line ending (#37650)
This got missed in the changes from #37631

Release Notes:

- N/A
2025-09-05 16:25:55 +00:00
Yacine Hmito
fb6cc8794f Fix typo in development docs for macOS (#37607)
Release Notes:

- N/A
2025-09-05 15:56:40 +00:00
Jakub Konka
3d37611b6f cli: Rename script zed-wsl to zed, and enable on non-WSL (#37631)
Closes #23026

With this hotfix, git committing from the built-in Zed terminal (well,
PowerShell), now works.

Release Notes:

- N/A
2025-09-05 17:43:39 +02:00
Peter Tripp
360e372b57 linux: Restore ctrl-escape to keymap (#37636)
Closes: https://github.com/zed-industries/zed/issues/37628
Follow-up to: https://github.com/zed-industries/zed/pull/36712

Release Notes:

- linux: Fix for ctrl-escape not escaping the tab switcher.
2025-09-05 11:09:32 -04:00
Isaac Hales
74e8afe9a8 Fix logic for default values for task variables (#37588)
This is a small fix for default values in task variables. The
[documentation](https://zed.dev/docs/tasks) states

> You can also use verbose syntax that allows specifying a default if a
given variable is not available: ${ZED_FILE:default_value}

I found, however, that this doesn't actually work. Instead, the Zed
variable and the default value are just appended in the output. For
example, if I run a task `echo ${ZED_ROW:100}` the result I get is
`447:100` (in this case it should just be `447`).

This PR fixes that. I also added a new test case for handling default
values.
I also tested the fix in a dev build and it seems to work.

There are no UI adjustments.

AI disclosure: I used Claude Code to write the code, including the fix
and the tests.

This is actually my first open-source PR ever, so if I did something
wrong, I'd appreciate any tips and I'll make it right!


Release Notes:

- Fixed task variable substitution always appending the default
2025-09-05 14:57:58 +00:00
Finn Evers
e30f45cf64 Syntax tree view improvements (#37570)
In an effort to improve the experience while developing extensions and
improving themes, this PR updates the syntax tree views behavior
slightly.

Before, the view would always update to the current active editor whilst
being used. This was quite painful for improving extension scheme files,
as you would always have to change back and forth between editors to
have a view at the relevant syntax tree.

With this PR, the syntax tree view will now stay attached to the editor
it was opened in, similar to preview views. Once the view is shown, the
`UseActiveEditor` will become available in the command palette and
enable the user to update the view to the last focused editor. On file
close, the view will also be updated accordingly.



https://github.com/user-attachments/assets/922075e5-9da0-4c1d-9e1a-51e024bf41ea

A button is also shown whenever switching is possible.

Futhermore, improved the empty state of the view.

Lastly, a drive-by cleanup of the `show_action_types` method so there is
no need to call `iter()` when calling the method.


Release Notes:

- The syntax tree view will now stay attached to the buffer it was
opened in, similar to the Markdown preview. Use the `UseActiveEditor`
action when the view is shown to change it to the last focused editor.
2025-09-05 14:22:32 +02:00
Jakub Konka
16c4fd4fc5 gpui: move Option -> Result conversion out of closure in App::update_window_id (#37624)
Doesn't fix anything, but it seems that we do not need to assert and
convert into an error until after the closure run to completion,
especially since this is the only error we throw.

Release Notes:

- N/A
2025-09-05 13:19:57 +02:00
Lukas Wirth
ec58adca13 languages: Invoke conda activate in conda environments (#37627)
This isn't quite right, but using the env manager path causes conda to
scream and I am not yet sure why, either way this is an improvement over
the status quo

Release Notes:

- N/A\
2025-09-05 11:16:15 +00:00
Lukas Wirth
bed358718b agent_ui: Fix index panic in SlashCommandCompletion::try_parse (#37612)
Release Notes:

- N/A
2025-09-05 07:56:53 +00:00
Lukas Wirth
4124bedab7 gpui: Skip test attribute expansion for rust-analyzer (#37611)
The `test` attribute doesn't really matter to rust-analyzer, so we can
make use of its cfg to have it think its just the standard test
attribute which should make rust-analyzer slightly less resource
intensive in zed. It also should prevent some IDE features from possibly
failing within tests.

Notably this has no effect outside of this repo, as the `rust-analyzer`
cfg only takes effect on workspace member crates.

Ideally we'd use the ignored proc macro config here but rust-analyzer
still doesn't have toml configs working unfortunately.

Release Notes:

- N/A
2025-09-05 06:54:08 +00:00
Smit Barmase
57c6dbd71e linux: Fix IME positioning on scaled display on Wayland (#37600)
Removes IME bounds scaling on Wayland since it uses logical pixels,
unlike X11. We now scale only on X11. Windows and macOS don’t use these
bounds for IME anyway.

Release Notes:

- Fixed an issue where the IME popover could appear outside the window
or fail to show on Wayland.
2025-09-05 09:10:50 +05:30
Michael Sloan
fded3fbcdb zeta: Scope edit prediction event history to current project (#37595)
This change also causes Zeta to not do anything for editors that are not
associated with a project. In practice, this shouldn't affect any
behavior - those editors shouldn't have edit predictions anyway.

Release Notes:

- Edit Prediction: Requests no longer include recent edits from other
projects (other Zed windows).
2025-09-05 01:15:59 +00:00
Michael Sloan
a660527036 Make entry_for_path return a reference instead of cloning (#37591)
Release Notes:

- N/A
2025-09-05 00:26:37 +00:00
Anthony Eid
0cb8a8983c settings ui: Improve setting proc macro and add scroll to UI (#37581)
This PR improves the settings_ui proc macro by taking into account more
serde attributes
1. rename_all
2. rename
3. flatten

We also pass field documentation to the UI layer now too. This allows ui
elements to have more information like the switch field description.

We got the scrollbar working and started getting language settings to
show up.

Release Notes:

- N/A

---------

Co-authored-by: Ben Kunkle <ben@zed.dev>
2025-09-04 22:30:48 +00:00
Cole Miller
c7902478c1 acp: Pass project environment to external agent servers (#37568)
Closes #37469 

Release Notes:

- agent: The project shell environment is now passed to external agent
processes.

Co-authored-by: Richard Feldman <oss@rtfeldman.com>
Co-authored-by: Nia Espera <nia-e@haecceity.cc>
2025-09-04 18:16:25 -04:00
morgankrey
3c0183fa5e Extraneous backtick (#37576)
Release Notes:

- N/A
2025-09-04 16:14:57 -05:00
morgankrey
e982cb824a docs: Claude Authentication (#37573)
Release Notes:

- N/A
2025-09-04 15:57:00 -05:00
Marshall Bowers
1b865a60f8 snippets: Bump to v0.0.6 (#37567)
This PR bumps the snippets extension to v0.0.6.

Changes:

- https://github.com/zed-industries/zed/pull/37565

Release Notes:

- N/A
2025-09-04 20:08:49 +00:00
Marshall Bowers
4c32d5bf13 snippets: Disable feature_paths by default (#37565)
This PR updates the default configuration of the `snippets` extension to
disable suggesting paths (`feature_paths`).

If users want to enable it, it can be done via the settings:

```json
{
  "lsp": {
    "snippet-completion-server": {
      "settings": {
        "feature_paths": true
      }
    }
  }
}
```

Release Notes:

- N/A
2025-09-04 19:35:48 +00:00
Kirill Bulatov
ccae033d85 Make fallback open picker more intuitive (#37564)
Closes https://github.com/zed-industries/zed/issues/34991

Before, the picker did not allow to open the current directory that was
just completed:

<img width="553" height="354" alt="image"
src="https://github.com/user-attachments/assets/e77793c8-763e-416f-9728-18d5a39b467f"
/>

pressing `enter` here would open `assets`; pressing `tab` would append
the `assets/` segment to the query.
Only backspace, removing `/` would allow to open the current directory.

After:
<img width="574" height="349" alt="image"
src="https://github.com/user-attachments/assets/bdbb3e23-7c7a-4e12-8092-51a6a0ea9f87"
/>

The first item is now a placeholder for opening the current directory
with `enter`.
Any time a fuzzy query is appended, the placeholder goes away; `tab`
selects the entry below the placeholder.

Release Notes:

- Made fallback open picker more intuitive

---------

Co-authored-by: Peter Tripp <petertripp@gmail.com>
Co-authored-by: David Kleingeld <davidsk@zed.dev>
2025-09-04 19:34:23 +00:00
Marshall Bowers
c2fa9d7981 docs: Add configuration example for simple-completion-language-server (#37566)
This PR adds a configuration example for the
`simple-completion-language-server`.

We show the user how to re-enable the `feature_paths` option, as we're
now disabling it by default
(https://github.com/zed-industries/zed/pull/37565).

Release Notes:

- N/A
2025-09-04 19:25:52 +00:00
Anthony Eid
5f03202b5c settings ui: Create settings key trait (#37489)
This PR separates out the associated constant `KEY` from the `Settings`
trait into a new trait `SettingsKey`. This allows for the key trait to
be derived using attributes to specify the path so that the new
`SettingsUi` derive macro can use the same attributes to determine top
level settings paths thereby removing the need to duplicate the path in
both `Settings::KEY` and `#[settings_ui(path = "...")]`

Co-authored-by: Ben Kunkle <ben@zed.dev>

Release Notes:

- N/A

---------

Co-authored-by: Ben Kunkle <ben@zed.dev>
2025-09-04 15:19:02 -04:00
Kirill Bulatov
223fda2fe2 Make remote projects to sync in local user settings (#37560)
Closes https://github.com/zed-industries/zed/issues/20024
Closes https://github.com/zed-industries/zed/issues/23489



https://github.com/user-attachments/assets/6466e0c1-4188-4980-8bb6-52ef6e7591c9


Release Notes:

- Made remote projects to sync in local user settings
2025-09-04 19:05:21 +00:00
Marshall Bowers
a85946eba8 docs: Update TOML docs (#37561)
This PR updates the TOML docs to remove references to Taplo and suggest
the Tombi extension for users wanting language server support.

Relates to https://github.com/zed-industries/zed/issues/36766.

Release Notes:

- N/A
2025-09-04 18:54:32 +00:00
Cole Miller
9d94358971 acp: Keep diff editors in sync with AgentFontSize global (#37559)
Release Notes:

- agent: Fixed `cmd-+` and `cmd--` not affecting the font size of diffs.
2025-09-04 18:33:56 +00:00
Marshall Bowers
9e11105483 toml: Extract to zed-extensions/toml repository (#37558)
This PR extracts the TOML extension to the
[zed-extensions/toml](https://github.com/zed-extensions/toml)
repository.

Release Notes:

- N/A
2025-09-04 18:07:50 +00:00
Anthony Eid
caebd0cc4d debugger: Fix stack frame filter crash (#37555)
The crash was caused by not accounting for the fact that a range of
collapse frames only counts as one entry. Causing the filter indices to
overshoot for indices after collapse frames (it was counting all
collapse frames instead of just one).

The test missed this because it all happened in one `cx.update` closure
and didn't render the stack frame list when the filter was applied. The
test has been updated to account for this.


Release Notes:

- N/A

Co-authored-by: Cole Miller <cole@zed.dev>
2025-09-04 17:55:20 +00:00
Marshall Bowers
6e2922367c Use full SHA for blade dependency (#37554)
In https://github.com/zed-industries/zed/pull/37516 we updated the
`blade` dependency, but used a short SHA.

No reason to not use the full SHA.

Release Notes:

- N/A
2025-09-04 17:41:47 +00:00
Jiqing Yang
25ee9b1013 Fix Wayland crash on AMD GPUs by updating Blade (#37516)
Updates blade-graphics from e0ec4e7 to bfa594e to fix GPU crashes on
Wayland with AMD graphics cards.

The crash was caused by incorrect BLAS scratch buffer alignment - the
old version hardcoded 256-byte alignment, but AMD GPUs require different
alignment values. The newer Blade version uses the GPU's actual
alignment requirements instead of hardcoding.

Closes #37448

Release Notes:

- Migrate to newer version of Blade upstream
2025-09-04 17:21:44 +00:00
Ben Brandt
0870a1fe80 acp: Don't share API key with Anthropic provider (#37543)
Since Claude Code has it's own preferred method of grabbing API keys, we
don't want to reuse this one.

Release Notes:

- acp: Don't share Anthropic API key from the Anthropic provider to
allow default Claude Code login options

---------

Co-authored-by: Agus Zubiaga <agus@zed.dev>
2025-09-04 16:01:50 +00:00
Lukas Wirth
e37efc1e9b diagnostics: Fix diagnostics pane clearing up too eagerly on typing (#37546)
Closes https://github.com/zed-industries/zed/issues/30494

Release Notes:

- Fixed diagnostics pane closing buffers too eagerly when typing inside
it
2025-09-04 15:30:23 +00:00
Nathan Sobo
1ae326432e Extract a scheduler crate from GPUI to enable unified integration testing of client and server code (#37326)
Extracts and cleans up GPUI's scheduler code into a new `scheduler`
crate, making it pluggable by external runtimes. This will enable
deterministic integration testing with cloud components by providing a
unified test scheduler across Zed and backend code. In Zed, it will
replace the existing GPUI scheduler for consistent async task management
across platforms.

## Changes

- **Core Implementation**: `TestScheduler` with seed-based
randomization, session tracking (`SessionId`), and foreground/background
task separation for reproducible testing.
- **Executors**: `ForegroundExecutor` (!Send, thread-local) and
`BackgroundExecutor` (Send, with blocking/timeout support) as
GPUI-compatible wrappers.
- **Clock and Timer**: Controllable `TestClock` and future-based `Timer`
for time-sensitive tests.
- **Testing APIs**: `once()`, `with_seed()`, and `many()` methods for
configurable test runs.
- **Dependencies**: Added `async-task`, `chrono`, `futures`, etc., with
updates to `Cargo.toml` and lock file.

## Benefits

- **Integration Testing**: Facilitates reliable async tests involving
cloud sessions, reducing flakiness via deterministic execution.
- **Pluggability**: Trait-based design (`Scheduler`) allows easy
integration into non-GPUI runtimes while maintaining GPUI compatibility.
- **Cleanup**: Refactors GPUI scheduler logic for clarity, correctness
(no `unwrap()`, proper error handling), and extensibility.

Follows Rust guidelines; run `./script/clippy` for verification.

- [x] Define and test a core scheduler that we think can power our cloud
code and GPUI
- [ ] Replace GPUI's scheduler


Release Notes:

- N/A

---------

Co-authored-by: Antonio Scandurra <me@as-cii.com>
2025-09-04 17:14:53 +02:00
张小白
a05f86f97b windows: Don't log error when RedrawWindow (#37542)
Release Notes:

- N/A
2025-09-04 14:47:17 +00:00
Marshall Bowers
473bbd78cc onboarding: Fix typos in comments (#37541)
This PR fixes some grammatical typos in some comments in the
`onboarding` crate.

Release Notes:

- N/A
2025-09-04 13:46:40 +00:00
张小白
28c78d2d85 windows: Keep just one copy of GPU instance (#37445)
Now we only keep a single copy of the GPU device. The GPU lost handling
got broken after #35376, but it’s properly handled again now.

Release Notes:

- N/A
2025-09-04 21:31:12 +08:00
Lukas Wirth
fca44f89c1 languages: Allow installing pre-release of rust-analyzer and clangd (#37530)
Release Notes:

- Added lsp binary config to allow fetching nightly rust-analyzer and
clangd releases
2025-09-04 09:22:19 +00:00
Mitch (a.k.a Voz)
b7ad20773c worktree: Create parent directories on rename (#37437)
Closes https://github.com/zed-industries/zed/issues/37357

Release Notes:

- Allow creating sub-directories when renaming a file in file finder

---------

Co-authored-by: Kirill Bulatov <kirill@zed.dev>
2025-09-04 08:25:47 +00:00
Finn Evers
aa1629b544 Remove some unused events (#37498)
This PR cleans up some emitted events around the codebase. These events
are either never emitted or never listened for.

It seems better to re-implement these at some point should they again be
needed - this ensures that they will actually be fired in the cases
where they are needed as opposed to being there and getting unreliable
and stale (which is already the case for the majority of the events
removed here).

Lastly, this ensures the `CapabilitiesChanged` event is not fired too
often.

Release Notes:

- N/A
2025-09-04 09:09:28 +02:00
459 changed files with 20128 additions and 17096 deletions

View File

@@ -19,8 +19,6 @@ rustflags = [
"windows_slim_errors", # This cfg will reduce the size of `windows::core::Error` from 16 bytes to 4 bytes
"-C",
"target-feature=+crt-static", # This fixes the linking issue when compiling livekit on Windows
"-C",
"link-arg=-fuse-ld=lld",
]
[env]

View File

@@ -41,5 +41,4 @@ workspace-members = [
"slash_commands_example",
"zed_snippets",
"zed_test_extension",
"zed_toml",
]

2
.gitattributes vendored
View File

@@ -2,4 +2,4 @@
*.json linguist-language=JSON-with-Comments
# Ensure the WSL script always has LF line endings, even on Windows
crates/zed/resources/windows/zed-wsl text eol=lf
crates/zed/resources/windows/zed.sh text eol=lf

View File

@@ -32,7 +32,7 @@ jobs:
- name: Discord Webhook Action
uses: tsickert/discord-webhook@c840d45a03a323fbc3f7507ac7769dbd91bfb164 # v5.3.0
with:
webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
webhook-url: ${{ secrets.DISCORD_WEBHOOK_RELEASE_NOTES }}
content: ${{ steps.get-content.outputs.string }}
send_release_notes_email:

13
.rules
View File

@@ -12,6 +12,19 @@
- Example: avoid `let _ = client.request(...).await?;` - use `client.request(...).await?;` instead
* When implementing async operations that may fail, ensure errors propagate to the UI layer so users get meaningful feedback.
* Never create files with `mod.rs` paths - prefer `src/some_module.rs` instead of `src/some_module/mod.rs`.
* When creating new crates, prefer specifying the library root path in `Cargo.toml` using `[lib] path = "...rs"` instead of the default `lib.rs`, to maintain consistent and descriptive naming (e.g., `gpui.rs` or `main.rs`).
* Avoid creative additions unless explicitly requested
* Use full words for variable names (no abbreviations like "q" for "queue")
* Use variable shadowing to scope clones in async contexts for clarity, minimizing the lifetime of borrowed references.
Example:
```rust
executor.spawn({
let task_ran = task_ran.clone();
async move {
*task_ran.borrow_mut() = true;
}
});
```
# GPUI

View File

@@ -65,7 +65,7 @@ If you would like to add a new icon to the Zed icon theme, [open a Discussion](h
## Bird's-eye view of Zed
We suggest you keep the [zed glossary](docs/src/development/GLOSSARY.md) at your side when starting out. It lists and explains some of the structures and terms you will see throughout the codebase.
We suggest you keep the [zed glossary](docs/src/development/glossary.md) at your side when starting out. It lists and explains some of the structures and terms you will see throughout the codebase.
Zed is made up of several smaller crates - let's go over those you're most likely to interact with:

237
Cargo.lock generated
View File

@@ -26,7 +26,7 @@ dependencies = [
"portable-pty",
"project",
"prompt_store",
"rand 0.8.5",
"rand 0.9.1",
"serde",
"serde_json",
"settings",
@@ -79,7 +79,7 @@ dependencies = [
"log",
"pretty_assertions",
"project",
"rand 0.8.5",
"rand 0.9.1",
"serde_json",
"settings",
"text",
@@ -172,7 +172,7 @@ dependencies = [
"pretty_assertions",
"project",
"prompt_store",
"rand 0.8.5",
"rand 0.9.1",
"ref-cast",
"rope",
"schemars",
@@ -196,9 +196,9 @@ dependencies = [
[[package]]
name = "agent-client-protocol"
version = "0.2.0-alpha.6"
version = "0.2.0-alpha.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d02292efd75080932b6466471d428c70e2ac06908ae24792fc7c36ecbaf67ca"
checksum = "08539e8d6b2ccca6cd00afdd42211698f7677adef09108a09414c11f1f45fdaf"
dependencies = [
"anyhow",
"async-broadcast",
@@ -301,6 +301,7 @@ dependencies = [
"futures 0.3.31",
"gpui",
"gpui_tokio",
"http_client",
"indoc",
"language",
"language_model",
@@ -308,22 +309,18 @@ dependencies = [
"libc",
"log",
"nix 0.29.0",
"node_runtime",
"paths",
"project",
"reqwest_client",
"schemars",
"semver",
"serde",
"serde_json",
"settings",
"smol",
"task",
"tempfile",
"thiserror 2.0.12",
"ui",
"util",
"watch",
"which 6.0.3",
"workspace-hack",
]
@@ -359,6 +356,7 @@ dependencies = [
"agent_settings",
"ai_onboarding",
"anyhow",
"arrayvec",
"assistant_context",
"assistant_slash_command",
"assistant_slash_commands",
@@ -408,7 +406,7 @@ dependencies = [
"project",
"prompt_store",
"proto",
"rand 0.8.5",
"rand 0.9.1",
"release_channel",
"rope",
"rules_library",
@@ -486,6 +484,7 @@ dependencies = [
"client",
"cloud_llm_client",
"component",
"feature_flags",
"gpui",
"language_model",
"serde",
@@ -834,7 +833,7 @@ dependencies = [
"project",
"prompt_store",
"proto",
"rand 0.8.5",
"rand 0.9.1",
"regex",
"rpc",
"serde",
@@ -933,7 +932,7 @@ dependencies = [
"parking_lot",
"pretty_assertions",
"project",
"rand 0.8.5",
"rand 0.9.1",
"regex",
"serde",
"serde_json",
@@ -985,7 +984,7 @@ dependencies = [
"pretty_assertions",
"project",
"prompt_store",
"rand 0.8.5",
"rand 0.9.1",
"regex",
"reqwest_client",
"rust-embed",
@@ -2291,7 +2290,7 @@ dependencies = [
[[package]]
name = "blade-graphics"
version = "0.6.0"
source = "git+https://github.com/kvark/blade?rev=e0ec4e720957edd51b945b64dd85605ea54bcfe5#e0ec4e720957edd51b945b64dd85605ea54bcfe5"
source = "git+https://github.com/kvark/blade?rev=bfa594ea697d4b6326ea29f747525c85ecf933b9#bfa594ea697d4b6326ea29f747525c85ecf933b9"
dependencies = [
"ash",
"ash-window",
@@ -2324,7 +2323,7 @@ dependencies = [
[[package]]
name = "blade-macros"
version = "0.3.0"
source = "git+https://github.com/kvark/blade?rev=e0ec4e720957edd51b945b64dd85605ea54bcfe5#e0ec4e720957edd51b945b64dd85605ea54bcfe5"
source = "git+https://github.com/kvark/blade?rev=bfa594ea697d4b6326ea29f747525c85ecf933b9#bfa594ea697d4b6326ea29f747525c85ecf933b9"
dependencies = [
"proc-macro2",
"quote",
@@ -2334,7 +2333,7 @@ dependencies = [
[[package]]
name = "blade-util"
version = "0.2.0"
source = "git+https://github.com/kvark/blade?rev=e0ec4e720957edd51b945b64dd85605ea54bcfe5#e0ec4e720957edd51b945b64dd85605ea54bcfe5"
source = "git+https://github.com/kvark/blade?rev=bfa594ea697d4b6326ea29f747525c85ecf933b9#bfa594ea697d4b6326ea29f747525c85ecf933b9"
dependencies = [
"blade-graphics",
"bytemuck",
@@ -2351,19 +2350,6 @@ dependencies = [
"digest",
]
[[package]]
name = "blake3"
version = "1.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3888aaa89e4b2a40fca9848e400f6a658a5a3978de7be858e209cafa8be9a4a0"
dependencies = [
"arrayref",
"arrayvec",
"cc",
"cfg-if",
"constant_time_eq 0.3.1",
]
[[package]]
name = "block"
version = "0.1.6"
@@ -2478,7 +2464,7 @@ dependencies = [
"language",
"log",
"pretty_assertions",
"rand 0.8.5",
"rand 0.9.1",
"rope",
"serde_json",
"sum_tree",
@@ -2899,11 +2885,9 @@ dependencies = [
"language",
"log",
"postage",
"rand 0.8.5",
"release_channel",
"rpc",
"settings",
"sum_tree",
"text",
"time",
"util",
@@ -3070,7 +3054,6 @@ dependencies = [
"clock",
"cloud_api_client",
"cloud_llm_client",
"cocoa 0.26.0",
"collections",
"credentials_provider",
"derive_more",
@@ -3083,10 +3066,11 @@ dependencies = [
"http_client_tls",
"httparse",
"log",
"objc2-foundation",
"parking_lot",
"paths",
"postage",
"rand 0.8.5",
"rand 0.9.1",
"regex",
"release_channel",
"rpc",
@@ -3335,7 +3319,7 @@ dependencies = [
"prometheus",
"prompt_store",
"prost 0.9.0",
"rand 0.8.5",
"rand 0.9.1",
"recent_projects",
"release_channel",
"remote",
@@ -3391,12 +3375,10 @@ dependencies = [
"collections",
"db",
"editor",
"emojis",
"futures 0.3.31",
"fuzzy",
"gpui",
"http_client",
"language",
"log",
"menu",
"notifications",
@@ -3404,7 +3386,6 @@ dependencies = [
"pretty_assertions",
"project",
"release_channel",
"rich_text",
"rpc",
"schemars",
"serde",
@@ -3515,6 +3496,7 @@ name = "component"
version = "0.1.0"
dependencies = [
"collections",
"documented",
"gpui",
"inventory",
"parking_lot",
@@ -3577,12 +3559,6 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc"
[[package]]
name = "constant_time_eq"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6"
[[package]]
name = "context_server"
version = "0.1.0"
@@ -4697,7 +4673,7 @@ dependencies = [
"markdown",
"pretty_assertions",
"project",
"rand 0.8.5",
"rand 0.9.1",
"serde",
"serde_json",
"settings",
@@ -5068,7 +5044,7 @@ dependencies = [
"parking_lot",
"pretty_assertions",
"project",
"rand 0.8.5",
"rand 0.9.1",
"regex",
"release_channel",
"rpc",
@@ -5563,7 +5539,7 @@ dependencies = [
"parking_lot",
"paths",
"project",
"rand 0.8.5",
"rand 0.9.1",
"release_channel",
"remote",
"reqwest_client",
@@ -6163,17 +6139,6 @@ dependencies = [
"futures-util",
]
[[package]]
name = "futures-batch"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f444c45a1cb86f2a7e301469fd50a82084a60dadc25d94529a8312276ecb71a"
dependencies = [
"futures 0.3.31",
"futures-timer",
"pin-utils",
]
[[package]]
name = "futures-channel"
version = "0.3.31"
@@ -6269,12 +6234,6 @@ version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"
[[package]]
name = "futures-timer"
version = "3.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24"
[[package]]
name = "futures-util"
version = "0.3.31"
@@ -6412,7 +6371,7 @@ dependencies = [
"log",
"parking_lot",
"pretty_assertions",
"rand 0.8.5",
"rand 0.9.1",
"regex",
"rope",
"schemars",
@@ -7465,7 +7424,7 @@ dependencies = [
"pathfinder_geometry",
"postage",
"profiling",
"rand 0.8.5",
"rand 0.9.1",
"raw-window-handle",
"refineable",
"reqwest_client",
@@ -9078,7 +9037,7 @@ dependencies = [
"parking_lot",
"postage",
"pretty_assertions",
"rand 0.8.5",
"rand 0.9.1",
"regex",
"rpc",
"schemars",
@@ -9220,6 +9179,19 @@ dependencies = [
"x_ai",
]
[[package]]
name = "language_onboarding"
version = "0.1.0"
dependencies = [
"db",
"editor",
"gpui",
"project",
"ui",
"workspace",
"workspace-hack",
]
[[package]]
name = "language_selector"
version = "0.1.0"
@@ -9247,6 +9219,7 @@ dependencies = [
"anyhow",
"client",
"collections",
"command_palette_hooks",
"copilot",
"editor",
"futures 0.3.31",
@@ -9281,7 +9254,6 @@ dependencies = [
"chrono",
"collections",
"dap",
"feature_flags",
"futures 0.3.31",
"gpui",
"http_client",
@@ -9517,6 +9489,21 @@ dependencies = [
"vcpkg",
]
[[package]]
name = "line_ending_selector"
version = "0.1.0"
dependencies = [
"editor",
"gpui",
"language",
"picker",
"project",
"ui",
"util",
"workspace",
"workspace-hack",
]
[[package]]
name = "link-cplusplus"
version = "1.0.10"
@@ -10392,7 +10379,7 @@ dependencies = [
"parking_lot",
"pretty_assertions",
"project",
"rand 0.8.5",
"rand 0.9.1",
"rope",
"serde",
"settings",
@@ -12618,12 +12605,13 @@ dependencies = [
"postage",
"prettier",
"pretty_assertions",
"rand 0.8.5",
"rand 0.9.1",
"regex",
"release_channel",
"remote",
"rpc",
"schemars",
"semver",
"serde",
"serde_json",
"settings",
@@ -12643,6 +12631,7 @@ dependencies = [
"unindent",
"url",
"util",
"watch",
"which 6.0.3",
"workspace-hack",
"worktree",
@@ -13892,7 +13881,7 @@ dependencies = [
"ctor",
"gpui",
"log",
"rand 0.8.5",
"rand 0.9.1",
"rayon",
"smallvec",
"sum_tree",
@@ -13921,7 +13910,7 @@ dependencies = [
"gpui",
"parking_lot",
"proto",
"rand 0.8.5",
"rand 0.9.1",
"rsa",
"serde",
"serde_json",
@@ -14356,6 +14345,19 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "scheduler"
version = "0.1.0"
dependencies = [
"async-task",
"backtrace",
"chrono",
"futures 0.3.31",
"parking_lot",
"rand 0.9.1",
"workspace-hack",
]
[[package]]
name = "schema_generator"
version = "0.1.0"
@@ -14658,49 +14660,6 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f7d95a54511e0c7be3f51e8867aa8cf35148d7b9445d44de2f943e2b206e749"
[[package]]
name = "semantic_index"
version = "0.1.0"
dependencies = [
"anyhow",
"arrayvec",
"blake3",
"client",
"clock",
"collections",
"feature_flags",
"fs",
"futures 0.3.31",
"futures-batch",
"gpui",
"heed",
"http_client",
"language",
"language_model",
"languages",
"log",
"open_ai",
"parking_lot",
"project",
"reqwest_client",
"serde",
"serde_json",
"settings",
"sha2",
"smol",
"streaming-iterator",
"tempfile",
"theme",
"tree-sitter",
"ui",
"unindent",
"util",
"workspace",
"workspace-hack",
"worktree",
"zlog",
]
[[package]]
name = "semantic_version"
version = "0.1.0"
@@ -14914,6 +14873,7 @@ dependencies = [
"editor",
"feature_flags",
"gpui",
"menu",
"serde",
"serde_json",
"settings",
@@ -15318,6 +15278,7 @@ dependencies = [
"futures 0.3.31",
"indoc",
"libsqlite3-sys",
"log",
"parking_lot",
"smol",
"sqlformat",
@@ -15655,7 +15616,7 @@ name = "streaming_diff"
version = "0.1.0"
dependencies = [
"ordered-float 2.10.1",
"rand 0.8.5",
"rand 0.9.1",
"rope",
"util",
"workspace-hack",
@@ -15769,7 +15730,7 @@ dependencies = [
"arrayvec",
"ctor",
"log",
"rand 0.8.5",
"rand 0.9.1",
"rayon",
"workspace-hack",
"zlog",
@@ -15911,9 +15872,11 @@ dependencies = [
"editor",
"file_icons",
"gpui",
"project",
"ui",
"workspace",
"workspace-hack",
"worktree",
]
[[package]]
@@ -16360,7 +16323,7 @@ dependencies = [
"futures 0.3.31",
"gpui",
"libc",
"rand 0.8.5",
"rand 0.9.1",
"regex",
"release_channel",
"schemars",
@@ -16408,7 +16371,7 @@ dependencies = [
"language",
"log",
"project",
"rand 0.8.5",
"rand 0.9.1",
"regex",
"schemars",
"search",
@@ -16440,7 +16403,7 @@ dependencies = [
"log",
"parking_lot",
"postage",
"rand 0.8.5",
"rand 0.9.1",
"regex",
"rope",
"smallvec",
@@ -16971,10 +16934,15 @@ checksum = "bfb942dfe1d8e29a7ee7fcbde5bd2b9a25fb89aa70caea2eba3bee836ff41076"
name = "toolchain_selector"
version = "0.1.0"
dependencies = [
"anyhow",
"convert_case 0.8.0",
"editor",
"file_finder",
"futures 0.3.31",
"fuzzy",
"gpui",
"language",
"menu",
"picker",
"project",
"ui",
@@ -17797,7 +17765,7 @@ dependencies = [
"libc",
"log",
"nix 0.29.0",
"rand 0.8.5",
"rand 0.9.1",
"regex",
"rust-embed",
"schemars",
@@ -17982,6 +17950,8 @@ version = "0.1.0"
dependencies = [
"anyhow",
"gpui",
"schemars",
"serde",
"settings",
"workspace-hack",
]
@@ -18588,7 +18558,7 @@ dependencies = [
"futures 0.3.31",
"gpui",
"parking_lot",
"rand 0.8.5",
"rand 0.9.1",
"workspace-hack",
"zlog",
]
@@ -20047,7 +20017,7 @@ dependencies = [
"paths",
"postage",
"pretty_assertions",
"rand 0.8.5",
"rand 0.9.1",
"rpc",
"schemars",
"serde",
@@ -20403,12 +20373,11 @@ dependencies = [
[[package]]
name = "zed"
version = "0.204.0"
version = "0.204.4"
dependencies = [
"acp_tools",
"activity_indicator",
"agent",
"agent_servers",
"agent_settings",
"agent_ui",
"anyhow",
@@ -20472,10 +20441,12 @@ dependencies = [
"language_extension",
"language_model",
"language_models",
"language_onboarding",
"language_selector",
"language_tools",
"languages",
"libc",
"line_ending_selector",
"livekit_client",
"log",
"markdown",
@@ -20627,7 +20598,7 @@ dependencies = [
[[package]]
name = "zed_snippets"
version = "0.0.5"
version = "0.0.6"
dependencies = [
"serde_json",
"zed_extension_api 0.1.0",
@@ -20640,13 +20611,6 @@ dependencies = [
"zed_extension_api 0.6.0",
]
[[package]]
name = "zed_toml"
version = "0.1.4"
dependencies = [
"zed_extension_api 0.1.0",
]
[[package]]
name = "zeno"
version = "0.3.2"
@@ -20810,9 +20774,10 @@ dependencies = [
"language_model",
"log",
"menu",
"parking_lot",
"postage",
"project",
"rand 0.8.5",
"rand 0.9.1",
"regex",
"release_channel",
"reqwest_client",
@@ -20882,7 +20847,7 @@ dependencies = [
"aes",
"byteorder",
"bzip2",
"constant_time_eq 0.1.5",
"constant_time_eq",
"crc32fast",
"crossbeam-utils",
"flate2",

View File

@@ -94,9 +94,11 @@ members = [
"crates/language_extension",
"crates/language_model",
"crates/language_models",
"crates/language_onboarding",
"crates/language_selector",
"crates/language_tools",
"crates/languages",
"crates/line_ending_selector",
"crates/livekit_api",
"crates/livekit_client",
"crates/lmstudio",
@@ -131,6 +133,7 @@ members = [
"crates/refineable",
"crates/refineable/derive_refineable",
"crates/release_channel",
"crates/scheduler",
"crates/remote",
"crates/remote_server",
"crates/repl",
@@ -141,7 +144,6 @@ members = [
"crates/rules_library",
"crates/schema_generator",
"crates/search",
"crates/semantic_index",
"crates/semantic_version",
"crates/session",
"crates/settings",
@@ -210,7 +212,6 @@ members = [
"extensions/slash-commands-example",
"extensions/snippets",
"extensions/test-extension",
"extensions/toml",
#
# Tooling
@@ -320,9 +321,11 @@ language = { path = "crates/language" }
language_extension = { path = "crates/language_extension" }
language_model = { path = "crates/language_model" }
language_models = { path = "crates/language_models" }
language_onboarding = { path = "crates/language_onboarding" }
language_selector = { path = "crates/language_selector" }
language_tools = { path = "crates/language_tools" }
languages = { path = "crates/languages" }
line_ending_selector = { path = "crates/line_ending_selector" }
livekit_api = { path = "crates/livekit_api" }
livekit_client = { path = "crates/livekit_client" }
lmstudio = { path = "crates/lmstudio" }
@@ -360,6 +363,7 @@ proto = { path = "crates/proto" }
recent_projects = { path = "crates/recent_projects" }
refineable = { path = "crates/refineable" }
release_channel = { path = "crates/release_channel" }
scheduler = { path = "crates/scheduler" }
remote = { path = "crates/remote" }
remote_server = { path = "crates/remote_server" }
repl = { path = "crates/repl" }
@@ -370,7 +374,6 @@ rope = { path = "crates/rope" }
rpc = { path = "crates/rpc" }
rules_library = { path = "crates/rules_library" }
search = { path = "crates/search" }
semantic_index = { path = "crates/semantic_index" }
semantic_version = { path = "crates/semantic_version" }
session = { path = "crates/session" }
settings = { path = "crates/settings" }
@@ -430,7 +433,7 @@ zlog_settings = { path = "crates/zlog_settings" }
# External crates
#
agent-client-protocol = { version = "0.2.0-alpha.6", features = ["unstable"]}
agent-client-protocol = { version = "0.2.0-alpha.8", features = ["unstable"] }
aho-corasick = "1.1"
alacritty_terminal = { git = "https://github.com/zed-industries/alacritty.git", branch = "add-hush-login-flag" }
any_vec = "0.14"
@@ -444,6 +447,7 @@ async-fs = "2.1"
async-pipe = { git = "https://github.com/zed-industries/async-pipe-rs", rev = "82d00a04211cf4e1236029aa03e6b6ce2a74c553" }
async-recursion = "1.0.0"
async-tar = "0.5.0"
async-task = "4.7"
async-trait = "0.1"
async-tungstenite = "0.29.1"
async_zip = { version = "0.0.17", features = ["deflate", "deflate64"] }
@@ -456,12 +460,13 @@ aws-sdk-bedrockruntime = { version = "1.80.0", features = [
] }
aws-smithy-runtime-api = { version = "1.7.4", features = ["http-1x", "client"] }
aws-smithy-types = { version = "1.3.0", features = ["http-body-1-x"] }
backtrace = "0.3"
base64 = "0.22"
bincode = "1.2.1"
bitflags = "2.6.0"
blade-graphics = { git = "https://github.com/kvark/blade", rev = "e0ec4e720957edd51b945b64dd85605ea54bcfe5" }
blade-macros = { git = "https://github.com/kvark/blade", rev = "e0ec4e720957edd51b945b64dd85605ea54bcfe5" }
blade-util = { git = "https://github.com/kvark/blade", rev = "e0ec4e720957edd51b945b64dd85605ea54bcfe5" }
blade-graphics = { git = "https://github.com/kvark/blade", rev = "bfa594ea697d4b6326ea29f747525c85ecf933b9" }
blade-macros = { git = "https://github.com/kvark/blade", rev = "bfa594ea697d4b6326ea29f747525c85ecf933b9" }
blade-util = { git = "https://github.com/kvark/blade", rev = "bfa594ea697d4b6326ea29f747525c85ecf933b9" }
blake3 = "1.5.3"
bytes = "1.0"
cargo_metadata = "0.19"
@@ -535,6 +540,31 @@ nbformat = { git = "https://github.com/ConradIrwin/runtimed", rev = "7130c80421
nix = "0.29"
num-format = "0.4.4"
objc = "0.2"
objc2-foundation = { version = "0.3", default-features = false, features = [
"NSArray",
"NSAttributedString",
"NSBundle",
"NSCoder",
"NSData",
"NSDate",
"NSDictionary",
"NSEnumerator",
"NSError",
"NSGeometry",
"NSNotification",
"NSNull",
"NSObjCRuntime",
"NSObject",
"NSProcessInfo",
"NSRange",
"NSRunLoop",
"NSString",
"NSURL",
"NSUndoManager",
"NSValue",
"objc2-core-foundation",
"std"
] }
open = "5.0.0"
ordered-float = "2.1.1"
palette = { version = "0.7.5", default-features = false, features = ["std"] }
@@ -560,7 +590,7 @@ prost-build = "0.9"
prost-types = "0.9"
pulldown-cmark = { version = "0.12.0", default-features = false }
quote = "1.0.9"
rand = "0.8.5"
rand = "0.9"
rayon = "1.8"
ref-cast = "1.0.24"
regex = "1.5"

View File

@@ -16,6 +16,7 @@
"up": "menu::SelectPrevious",
"enter": "menu::Confirm",
"ctrl-enter": "menu::SecondaryConfirm",
"ctrl-escape": "menu::Cancel",
"ctrl-c": "menu::Cancel",
"escape": "menu::Cancel",
"alt-shift-enter": "menu::Restart",
@@ -246,7 +247,10 @@
"ctrl-shift-e": "project_panel::ToggleFocus",
"ctrl-shift-enter": "agent::ContinueThread",
"super-ctrl-b": "agent::ToggleBurnMode",
"alt-enter": "agent::ContinueWithBurnMode"
"alt-enter": "agent::ContinueWithBurnMode",
"ctrl-y": "agent::AllowOnce",
"ctrl-alt-y": "agent::AllowAlways",
"ctrl-d": "agent::RejectOnce"
}
},
{
@@ -327,6 +331,12 @@
"enter": "agent::AcceptSuggestedContext"
}
},
{
"context": "AcpThread > ModeSelector",
"bindings": {
"ctrl-enter": "menu::Confirm"
}
},
{
"context": "AcpThread > Editor && !use_modifier_to_send",
"use_key_equivalents": true,
@@ -344,7 +354,8 @@
"ctrl-enter": "agent::Chat",
"shift-ctrl-r": "agent::OpenAgentDiff",
"ctrl-shift-y": "agent::KeepAll",
"ctrl-shift-n": "agent::RejectAll"
"ctrl-shift-n": "agent::RejectAll",
"shift-tab": "agent::CycleModeSelector"
}
},
{
@@ -485,8 +496,8 @@
"alt-down": "editor::MoveLineDown",
"ctrl-alt-shift-up": "editor::DuplicateLineUp",
"ctrl-alt-shift-down": "editor::DuplicateLineDown",
"alt-shift-right": "editor::SelectLargerSyntaxNode", // Expand Selection
"alt-shift-left": "editor::SelectSmallerSyntaxNode", // Shrink Selection
"alt-shift-right": "editor::SelectLargerSyntaxNode", // Expand selection
"alt-shift-left": "editor::SelectSmallerSyntaxNode", // Shrink selection
"ctrl-shift-l": "editor::SelectAllMatches", // Select all occurrences of current selection
"ctrl-f2": "editor::SelectAllMatches", // Select all occurrences of current word
"ctrl-d": ["editor::SelectNext", { "replace_newest": false }], // editor.action.addSelectionToNextFindMatch / find_under_expand
@@ -582,7 +593,7 @@
"ctrl-n": "workspace::NewFile",
"shift-new": "workspace::NewWindow",
"ctrl-shift-n": "workspace::NewWindow",
"ctrl-`": "terminal_panel::ToggleFocus",
"ctrl-`": "terminal_panel::Toggle",
"f10": ["app_menu::OpenApplicationMenu", "Zed"],
"alt-1": ["workspace::ActivatePane", 0],
"alt-2": ["workspace::ActivatePane", 1],
@@ -627,6 +638,7 @@
"alt-save": "workspace::SaveAll",
"ctrl-alt-s": "workspace::SaveAll",
"ctrl-k m": "language_selector::Toggle",
"ctrl-k ctrl-m": "toolchain::AddToolchain",
"escape": "workspace::Unfollow",
"ctrl-k ctrl-left": "workspace::ActivatePaneLeft",
"ctrl-k ctrl-right": "workspace::ActivatePaneRight",
@@ -1027,6 +1039,13 @@
"tab": "channel_modal::ToggleMode"
}
},
{
"context": "ToolchainSelector",
"use_key_equivalents": true,
"bindings": {
"ctrl-shift-a": "toolchain::AddToolchain"
}
},
{
"context": "FileFinder || (FileFinder > Picker > Editor)",
"bindings": {

View File

@@ -218,7 +218,7 @@
}
},
{
"context": "Editor && !agent_diff",
"context": "Editor && !agent_diff && !AgentPanel",
"use_key_equivalents": true,
"bindings": {
"cmd-alt-z": "git::Restore",
@@ -286,7 +286,10 @@
"cmd-shift-e": "project_panel::ToggleFocus",
"cmd-ctrl-b": "agent::ToggleBurnMode",
"cmd-shift-enter": "agent::ContinueThread",
"alt-enter": "agent::ContinueWithBurnMode"
"alt-enter": "agent::ContinueWithBurnMode",
"cmd-y": "agent::AllowOnce",
"cmd-alt-y": "agent::AllowAlways",
"cmd-d": "agent::RejectOnce"
}
},
{
@@ -378,6 +381,12 @@
"ctrl--": "pane::GoBack"
}
},
{
"context": "AcpThread > ModeSelector",
"bindings": {
"cmd-enter": "menu::Confirm"
}
},
{
"context": "AcpThread > Editor && !use_modifier_to_send",
"use_key_equivalents": true,
@@ -385,7 +394,8 @@
"enter": "agent::Chat",
"shift-ctrl-r": "agent::OpenAgentDiff",
"cmd-shift-y": "agent::KeepAll",
"cmd-shift-n": "agent::RejectAll"
"cmd-shift-n": "agent::RejectAll",
"shift-tab": "agent::CycleModeSelector"
}
},
{
@@ -395,7 +405,8 @@
"cmd-enter": "agent::Chat",
"shift-ctrl-r": "agent::OpenAgentDiff",
"cmd-shift-y": "agent::KeepAll",
"cmd-shift-n": "agent::RejectAll"
"cmd-shift-n": "agent::RejectAll",
"shift-tab": "agent::CycleModeSelector"
}
},
{
@@ -536,8 +547,10 @@
"alt-down": "editor::MoveLineDown",
"alt-shift-up": "editor::DuplicateLineUp",
"alt-shift-down": "editor::DuplicateLineDown",
"ctrl-shift-right": "editor::SelectLargerSyntaxNode", // Expand Selection
"ctrl-shift-left": "editor::SelectSmallerSyntaxNode", // Shrink Selection
"cmd-ctrl-left": "editor::SelectSmallerSyntaxNode", // Shrink selection
"cmd-ctrl-right": "editor::SelectLargerSyntaxNode", // Expand selection
"cmd-ctrl-up": "editor::SelectPreviousSyntaxNode", // Move selection up
"cmd-ctrl-down": "editor::SelectNextSyntaxNode", // Move selection down
"cmd-d": ["editor::SelectNext", { "replace_newest": false }], // editor.action.addSelectionToNextFindMatch / find_under_expand
"cmd-shift-l": "editor::SelectAllMatches", // Select all occurrences of current selection
"cmd-f2": "editor::SelectAllMatches", // Select all occurrences of current word
@@ -649,7 +662,7 @@
"alt-shift-enter": "toast::RunAction",
"cmd-shift-s": "workspace::SaveAs",
"cmd-shift-n": "workspace::NewWindow",
"ctrl-`": "terminal_panel::ToggleFocus",
"ctrl-`": "terminal_panel::Toggle",
"cmd-1": ["workspace::ActivatePane", 0],
"cmd-2": ["workspace::ActivatePane", 1],
"cmd-3": ["workspace::ActivatePane", 2],
@@ -690,6 +703,7 @@
"cmd-?": "agent::ToggleFocus",
"cmd-alt-s": "workspace::SaveAll",
"cmd-k m": "language_selector::Toggle",
"cmd-k cmd-m": "toolchain::AddToolchain",
"escape": "workspace::Unfollow",
"cmd-k cmd-left": "workspace::ActivatePaneLeft",
"cmd-k cmd-right": "workspace::ActivatePaneRight",
@@ -1094,6 +1108,13 @@
"tab": "channel_modal::ToggleMode"
}
},
{
"context": "ToolchainSelector",
"use_key_equivalents": true,
"bindings": {
"cmd-shift-a": "toolchain::AddToolchain"
}
},
{
"context": "FileFinder || (FileFinder > Picker > Editor)",
"use_key_equivalents": true,

View File

@@ -25,7 +25,6 @@
"ctrl-alt-enter": ["picker::ConfirmInput", { "secondary": true }],
"ctrl-shift-w": "workspace::CloseWindow",
"shift-escape": "workspace::ToggleZoom",
"open": "workspace::Open",
"ctrl-o": "workspace::Open",
"ctrl-=": ["zed::IncreaseBufferFontSize", { "persist": false }],
"ctrl-shift-=": ["zed::IncreaseBufferFontSize", { "persist": false }],
@@ -68,18 +67,13 @@
"ctrl-k q": "editor::Rewrap",
"ctrl-backspace": ["editor::DeleteToPreviousWordStart", { "ignore_newlines": false, "ignore_brackets": false }],
"ctrl-delete": ["editor::DeleteToNextWordEnd", { "ignore_newlines": false, "ignore_brackets": false }],
"cut": "editor::Cut",
"shift-delete": "editor::Cut",
"ctrl-x": "editor::Cut",
"copy": "editor::Copy",
"ctrl-insert": "editor::Copy",
"ctrl-c": "editor::Copy",
"paste": "editor::Paste",
"shift-insert": "editor::Paste",
"ctrl-v": "editor::Paste",
"undo": "editor::Undo",
"ctrl-z": "editor::Undo",
"redo": "editor::Redo",
"ctrl-y": "editor::Redo",
"ctrl-shift-z": "editor::Redo",
"up": "editor::MoveUp",
@@ -138,7 +132,6 @@
"ctrl-shift-enter": "editor::NewlineAbove",
"ctrl-k ctrl-z": "editor::ToggleSoftWrap",
"ctrl-k z": "editor::ToggleSoftWrap",
"find": "buffer_search::Deploy",
"ctrl-f": "buffer_search::Deploy",
"ctrl-h": "buffer_search::DeployReplace",
"ctrl-shift-.": "assistant::QuoteSelection",
@@ -177,7 +170,6 @@
"context": "Markdown",
"use_key_equivalents": true,
"bindings": {
"copy": "markdown::Copy",
"ctrl-c": "markdown::Copy"
}
},
@@ -225,7 +217,6 @@
"bindings": {
"ctrl-enter": "assistant::Assist",
"ctrl-s": "workspace::Save",
"save": "workspace::Save",
"ctrl-shift-,": "assistant::InsertIntoEditor",
"shift-enter": "assistant::Split",
"ctrl-r": "assistant::CycleMessageRole",
@@ -258,7 +249,10 @@
"ctrl-shift-e": "project_panel::ToggleFocus",
"ctrl-shift-enter": "agent::ContinueThread",
"super-ctrl-b": "agent::ToggleBurnMode",
"alt-enter": "agent::ContinueWithBurnMode"
"alt-enter": "agent::ContinueWithBurnMode",
"ctrl-y": "agent::AllowOnce",
"ctrl-alt-y": "agent::AllowAlways",
"ctrl-d": "agent::RejectOnce"
}
},
{
@@ -272,7 +266,6 @@
"context": "AgentPanel > Markdown",
"use_key_equivalents": true,
"bindings": {
"copy": "markdown::CopyAsMarkdown",
"ctrl-c": "markdown::CopyAsMarkdown"
}
},
@@ -346,6 +339,12 @@
"enter": "agent::AcceptSuggestedContext"
}
},
{
"context": "AcpThread > ModeSelector",
"bindings": {
"ctrl-enter": "menu::Confirm"
}
},
{
"context": "AcpThread > Editor",
"use_key_equivalents": true,
@@ -353,7 +352,8 @@
"enter": "agent::Chat",
"ctrl-shift-r": "agent::OpenAgentDiff",
"ctrl-shift-y": "agent::KeepAll",
"ctrl-shift-n": "agent::RejectAll"
"ctrl-shift-n": "agent::RejectAll",
"shift-tab": "agent::CycleModeSelector"
}
},
{
@@ -367,7 +367,6 @@
"context": "PromptLibrary",
"use_key_equivalents": true,
"bindings": {
"new": "rules_library::NewRule",
"ctrl-n": "rules_library::NewRule",
"ctrl-shift-s": "rules_library::ToggleDefaultRule"
}
@@ -381,7 +380,6 @@
"enter": "search::SelectNextMatch",
"shift-enter": "search::SelectPreviousMatch",
"alt-enter": "search::SelectAllMatches",
"find": "search::FocusSearch",
"ctrl-f": "search::FocusSearch",
"ctrl-h": "search::ToggleReplace",
"ctrl-l": "search::ToggleSelection"
@@ -408,7 +406,6 @@
"use_key_equivalents": true,
"bindings": {
"escape": "project_search::ToggleFocus",
"shift-find": "search::FocusSearch",
"ctrl-shift-f": "search::FocusSearch",
"ctrl-shift-h": "search::ToggleReplace",
"alt-r": "search::ToggleRegex" // vscode
@@ -472,14 +469,12 @@
"forward": "pane::GoForward",
"f3": "search::SelectNextMatch",
"shift-f3": "search::SelectPreviousMatch",
"shift-find": "project_search::ToggleFocus",
"ctrl-shift-f": "project_search::ToggleFocus",
"shift-alt-h": "search::ToggleReplace",
"alt-l": "search::ToggleSelection",
"alt-enter": "search::SelectAllMatches",
"alt-c": "search::ToggleCaseSensitive",
"alt-w": "search::ToggleWholeWord",
"alt-find": "project_search::ToggleFilters",
"alt-f": "project_search::ToggleFilters",
"alt-r": "search::ToggleRegex",
// "ctrl-shift-alt-x": "search::ToggleRegex",
@@ -500,8 +495,10 @@
"alt-down": "editor::MoveLineDown",
"shift-alt-up": "editor::DuplicateLineUp",
"shift-alt-down": "editor::DuplicateLineDown",
"shift-alt-right": "editor::SelectLargerSyntaxNode", // Expand Selection
"shift-alt-left": "editor::SelectSmallerSyntaxNode", // Shrink Selection
"shift-alt-right": "editor::SelectLargerSyntaxNode", // Expand selection
"shift-alt-left": "editor::SelectSmallerSyntaxNode", // Shrink selection
"ctrl-shift-right": "editor::SelectLargerSyntaxNode", // Expand selection (VSCode version)
"ctrl-shift-left": "editor::SelectSmallerSyntaxNode", // Shrink selection (VSCode version)
"ctrl-shift-l": "editor::SelectAllMatches", // Select all occurrences of current selection
"ctrl-f2": "editor::SelectAllMatches", // Select all occurrences of current word
"ctrl-d": ["editor::SelectNext", { "replace_newest": false }], // editor.action.addSelectionToNextFindMatch / find_under_expand
@@ -579,27 +576,21 @@
"context": "Workspace",
"use_key_equivalents": true,
"bindings": {
"alt-open": ["projects::OpenRecent", { "create_new_window": false }],
// Change the default action on `menu::Confirm` by setting the parameter
// "ctrl-alt-o": ["projects::OpenRecent", { "create_new_window": true }],
"ctrl-r": ["projects::OpenRecent", { "create_new_window": false }],
"shift-alt-open": ["projects::OpenRemote", { "from_existing_connection": false, "create_new_window": false }],
// Change to open path modal for existing remote connection by setting the parameter
// "ctrl-shift-alt-o": "["projects::OpenRemote", { "from_existing_connection": true }]",
"ctrl-shift-alt-o": ["projects::OpenRemote", { "from_existing_connection": false, "create_new_window": false }],
"shift-alt-b": "branches::OpenRecent",
"shift-alt-enter": "toast::RunAction",
"ctrl-shift-`": "workspace::NewTerminal",
"save": "workspace::Save",
"ctrl-s": "workspace::Save",
"ctrl-k ctrl-shift-s": "workspace::SaveWithoutFormat",
"shift-save": "workspace::SaveAs",
"ctrl-shift-s": "workspace::SaveAs",
"new": "workspace::NewFile",
"ctrl-n": "workspace::NewFile",
"shift-new": "workspace::NewWindow",
"ctrl-shift-n": "workspace::NewWindow",
"ctrl-`": "terminal_panel::ToggleFocus",
"ctrl-`": "terminal_panel::Toggle",
"f10": ["app_menu::OpenApplicationMenu", "Zed"],
"alt-1": ["workspace::ActivatePane", 0],
"alt-2": ["workspace::ActivatePane", 1],
@@ -621,7 +612,6 @@
"shift-alt-0": "workspace::ResetOpenDocksSize",
"ctrl-shift-alt--": ["workspace::DecreaseOpenDocksSize", { "px": 0 }],
"ctrl-shift-alt-=": ["workspace::IncreaseOpenDocksSize", { "px": 0 }],
"shift-find": "pane::DeploySearch",
"ctrl-shift-f": "pane::DeploySearch",
"ctrl-shift-h": ["pane::DeploySearch", { "replace_enabled": true }],
"ctrl-shift-t": "pane::ReopenClosedItem",
@@ -641,9 +631,9 @@
"ctrl-shift-g": "git_panel::ToggleFocus",
"ctrl-shift-d": "debug_panel::ToggleFocus",
"ctrl-shift-/": "agent::ToggleFocus",
"alt-save": "workspace::SaveAll",
"ctrl-k s": "workspace::SaveAll",
"ctrl-k m": "language_selector::Toggle",
"ctrl-m ctrl-m": "toolchain::AddToolchain",
"escape": "workspace::Unfollow",
"ctrl-k ctrl-left": "workspace::ActivatePaneLeft",
"ctrl-k ctrl-right": "workspace::ActivatePaneRight",
@@ -848,9 +838,7 @@
"bindings": {
"left": "outline_panel::CollapseSelectedEntry",
"right": "outline_panel::ExpandSelectedEntry",
"alt-copy": "outline_panel::CopyPath",
"shift-alt-c": "outline_panel::CopyPath",
"shift-alt-copy": "workspace::CopyRelativePath",
"ctrl-shift-alt-c": "workspace::CopyRelativePath",
"ctrl-alt-r": "outline_panel::RevealInFileManager",
"space": "outline_panel::OpenSelectedEntry",
@@ -866,21 +854,14 @@
"bindings": {
"left": "project_panel::CollapseSelectedEntry",
"right": "project_panel::ExpandSelectedEntry",
"new": "project_panel::NewFile",
"ctrl-n": "project_panel::NewFile",
"alt-new": "project_panel::NewDirectory",
"alt-n": "project_panel::NewDirectory",
"cut": "project_panel::Cut",
"ctrl-x": "project_panel::Cut",
"copy": "project_panel::Copy",
"ctrl-insert": "project_panel::Copy",
"ctrl-c": "project_panel::Copy",
"paste": "project_panel::Paste",
"shift-insert": "project_panel::Paste",
"ctrl-v": "project_panel::Paste",
"alt-copy": "project_panel::CopyPath",
"shift-alt-c": "project_panel::CopyPath",
"shift-alt-copy": "workspace::CopyRelativePath",
"ctrl-k ctrl-shift-c": "workspace::CopyRelativePath",
"enter": "project_panel::Rename",
"f2": "project_panel::Rename",
@@ -892,7 +873,6 @@
"ctrl-alt-r": "project_panel::RevealInFileManager",
"ctrl-shift-enter": "project_panel::OpenWithSystem",
"alt-d": "project_panel::CompareMarkedFiles",
"shift-find": "project_panel::NewSearchInDirectory",
"ctrl-k ctrl-shift-f": "project_panel::NewSearchInDirectory",
"shift-down": "menu::SelectNext",
"shift-up": "menu::SelectPrevious",
@@ -1075,6 +1055,13 @@
"tab": "channel_modal::ToggleMode"
}
},
{
"context": "ToolchainSelector",
"use_key_equivalents": true,
"bindings": {
"ctrl-shift-a": "toolchain::AddToolchain"
}
},
{
"context": "FileFinder || (FileFinder > Picker > Editor)",
"use_key_equivalents": true,
@@ -1110,10 +1097,8 @@
"use_key_equivalents": true,
"bindings": {
"ctrl-alt-space": "terminal::ShowCharacterPalette",
"copy": "terminal::Copy",
"ctrl-insert": "terminal::Copy",
"ctrl-shift-c": "terminal::Copy",
"paste": "terminal::Paste",
"shift-insert": "terminal::Paste",
"ctrl-shift-v": "terminal::Paste",
"ctrl-enter": "assistant::InlineAssist",
@@ -1129,7 +1114,6 @@
"ctrl-w": ["terminal::SendKeystroke", "ctrl-w"],
"ctrl-backspace": ["terminal::SendKeystroke", "ctrl-w"],
"ctrl-shift-a": "editor::SelectAll",
"find": "buffer_search::Deploy",
"ctrl-shift-f": "buffer_search::Deploy",
"ctrl-shift-l": "terminal::Clear",
"ctrl-shift-w": "pane::CloseActiveItem",
@@ -1210,7 +1194,6 @@
"use_key_equivalents": true,
"bindings": {
"ctrl-f": "search::FocusSearch",
"alt-find": "keymap_editor::ToggleKeystrokeSearch",
"alt-f": "keymap_editor::ToggleKeystrokeSearch",
"alt-c": "keymap_editor::ToggleConflictFilter",
"enter": "keymap_editor::EditBinding",

View File

@@ -125,7 +125,7 @@
{
"context": "Workspace || Editor",
"bindings": {
"alt-f12": "terminal_panel::ToggleFocus",
"alt-f12": "terminal_panel::Toggle",
"ctrl-shift-k": "git::Push"
}
},

View File

@@ -127,7 +127,7 @@
{
"context": "Workspace || Editor",
"bindings": {
"alt-f12": "terminal_panel::ToggleFocus",
"alt-f12": "terminal_panel::Toggle",
"cmd-shift-k": "git::Push"
}
},

View File

@@ -32,34 +32,6 @@
"(": "vim::SentenceBackward",
")": "vim::SentenceForward",
"|": "vim::GoToColumn",
"] ]": "vim::NextSectionStart",
"] [": "vim::NextSectionEnd",
"[ [": "vim::PreviousSectionStart",
"[ ]": "vim::PreviousSectionEnd",
"] m": "vim::NextMethodStart",
"] shift-m": "vim::NextMethodEnd",
"[ m": "vim::PreviousMethodStart",
"[ shift-m": "vim::PreviousMethodEnd",
"[ *": "vim::PreviousComment",
"[ /": "vim::PreviousComment",
"] *": "vim::NextComment",
"] /": "vim::NextComment",
"[ -": "vim::PreviousLesserIndent",
"[ +": "vim::PreviousGreaterIndent",
"[ =": "vim::PreviousSameIndent",
"] -": "vim::NextLesserIndent",
"] +": "vim::NextGreaterIndent",
"] =": "vim::NextSameIndent",
"] b": "pane::ActivateNextItem",
"[ b": "pane::ActivatePreviousItem",
"] shift-b": "pane::ActivateLastItem",
"[ shift-b": ["pane::ActivateItem", 0],
"] space": "vim::InsertEmptyLineBelow",
"[ space": "vim::InsertEmptyLineAbove",
"[ e": "editor::MoveLineUp",
"] e": "editor::MoveLineDown",
"[ f": "workspace::FollowNextCollaborator",
"] f": "workspace::FollowNextCollaborator",
// Word motions
"w": "vim::NextWordStart",
@@ -83,10 +55,6 @@
"n": "vim::MoveToNextMatch",
"shift-n": "vim::MoveToPreviousMatch",
"%": "vim::Matching",
"] }": ["vim::UnmatchedForward", { "char": "}" }],
"[ {": ["vim::UnmatchedBackward", { "char": "{" }],
"] )": ["vim::UnmatchedForward", { "char": ")" }],
"[ (": ["vim::UnmatchedBackward", { "char": "(" }],
"f": ["vim::PushFindForward", { "before": false, "multiline": false }],
"t": ["vim::PushFindForward", { "before": true, "multiline": false }],
"shift-f": ["vim::PushFindBackward", { "after": false, "multiline": false }],
@@ -219,6 +187,46 @@
".": "vim::Repeat"
}
},
{
"context": "vim_mode == normal || vim_mode == visual || vim_mode == operator",
"bindings": {
"] ]": "vim::NextSectionStart",
"] [": "vim::NextSectionEnd",
"[ [": "vim::PreviousSectionStart",
"[ ]": "vim::PreviousSectionEnd",
"] m": "vim::NextMethodStart",
"] shift-m": "vim::NextMethodEnd",
"[ m": "vim::PreviousMethodStart",
"[ shift-m": "vim::PreviousMethodEnd",
"[ *": "vim::PreviousComment",
"[ /": "vim::PreviousComment",
"] *": "vim::NextComment",
"] /": "vim::NextComment",
"[ -": "vim::PreviousLesserIndent",
"[ +": "vim::PreviousGreaterIndent",
"[ =": "vim::PreviousSameIndent",
"] -": "vim::NextLesserIndent",
"] +": "vim::NextGreaterIndent",
"] =": "vim::NextSameIndent",
"] b": "pane::ActivateNextItem",
"[ b": "pane::ActivatePreviousItem",
"] shift-b": "pane::ActivateLastItem",
"[ shift-b": ["pane::ActivateItem", 0],
"] space": "vim::InsertEmptyLineBelow",
"[ space": "vim::InsertEmptyLineAbove",
"[ e": "editor::MoveLineUp",
"] e": "editor::MoveLineDown",
"[ f": "workspace::FollowNextCollaborator",
"] f": "workspace::FollowNextCollaborator",
"] }": ["vim::UnmatchedForward", { "char": "}" }],
"[ {": ["vim::UnmatchedBackward", { "char": "{" }],
"] )": ["vim::UnmatchedForward", { "char": ")" }],
"[ (": ["vim::UnmatchedBackward", { "char": "(" }],
// tree-sitter related commands
"[ x": "vim::SelectLargerSyntaxNode",
"] x": "vim::SelectSmallerSyntaxNode"
}
},
{
"context": "vim_mode == normal",
"bindings": {
@@ -249,9 +257,6 @@
"g w": "vim::PushRewrap",
"g q": "vim::PushRewrap",
"insert": "vim::InsertBefore",
// tree-sitter related commands
"[ x": "vim::SelectLargerSyntaxNode",
"] x": "vim::SelectSmallerSyntaxNode",
"] d": "editor::GoToDiagnostic",
"[ d": "editor::GoToPreviousDiagnostic",
"] c": "editor::GoToHunk",
@@ -317,10 +322,7 @@
"g w": "vim::Rewrap",
"g ?": "vim::ConvertToRot13",
// "g ?": "vim::ConvertToRot47",
"\"": "vim::PushRegister",
// tree-sitter related commands
"[ x": "editor::SelectLargerSyntaxNode",
"] x": "editor::SelectSmallerSyntaxNode"
"\"": "vim::PushRegister"
}
},
{
@@ -397,6 +399,9 @@
"ctrl-[": "editor::Cancel",
";": "vim::HelixCollapseSelection",
":": "command_palette::Toggle",
"m": "vim::PushHelixMatch",
"]": ["vim::PushHelixNext", { "around": true }],
"[": ["vim::PushHelixPrevious", { "around": true }],
"left": "vim::WrappingLeft",
"right": "vim::WrappingRight",
"h": "vim::WrappingLeft",
@@ -419,13 +424,6 @@
"insert": "vim::InsertBefore",
"alt-.": "vim::RepeatFind",
"alt-s": ["editor::SplitSelectionIntoLines", { "keep_selections": true }],
// tree-sitter related commands
"[ x": "editor::SelectLargerSyntaxNode",
"] x": "editor::SelectSmallerSyntaxNode",
"] d": "editor::GoToDiagnostic",
"[ d": "editor::GoToPreviousDiagnostic",
"] c": "editor::GoToHunk",
"[ c": "editor::GoToPreviousHunk",
// Goto mode
"g n": "pane::ActivateNextItem",
"g p": "pane::ActivatePreviousItem",
@@ -469,9 +467,6 @@
"space c": "editor::ToggleComments",
"space y": "editor::Copy",
"space p": "editor::Paste",
// Match mode
"m m": "vim::Matching",
"m i w": ["workspace::SendKeystrokes", "v i w"],
"shift-u": "editor::Redo",
"ctrl-c": "editor::ToggleComments",
"d": "vim::HelixDelete",
@@ -540,7 +535,7 @@
}
},
{
"context": "vim_operator == a || vim_operator == i || vim_operator == cs",
"context": "vim_operator == a || vim_operator == i || vim_operator == cs || vim_operator == helix_next || vim_operator == helix_previous",
"bindings": {
"w": "vim::Word",
"shift-w": ["vim::Word", { "ignore_punctuation": true }],
@@ -577,6 +572,48 @@
"e": "vim::EntireFile"
}
},
{
"context": "vim_operator == helix_m",
"bindings": {
"m": "vim::Matching"
}
},
{
"context": "vim_operator == helix_next",
"bindings": {
"z": "vim::NextSectionStart",
"shift-z": "vim::NextSectionEnd",
"*": "vim::NextComment",
"/": "vim::NextComment",
"-": "vim::NextLesserIndent",
"+": "vim::NextGreaterIndent",
"=": "vim::NextSameIndent",
"b": "pane::ActivateNextItem",
"shift-b": "pane::ActivateLastItem",
"x": "editor::SelectSmallerSyntaxNode",
"d": "editor::GoToDiagnostic",
"c": "editor::GoToHunk",
"space": "vim::InsertEmptyLineBelow"
}
},
{
"context": "vim_operator == helix_previous",
"bindings": {
"z": "vim::PreviousSectionStart",
"shift-z": "vim::PreviousSectionEnd",
"*": "vim::PreviousComment",
"/": "vim::PreviousComment",
"-": "vim::PreviousLesserIndent",
"+": "vim::PreviousGreaterIndent",
"=": "vim::PreviousSameIndent",
"b": "pane::ActivatePreviousItem",
"shift-b": ["pane::ActivateItem", 0],
"x": "editor::SelectLargerSyntaxNode",
"d": "editor::GoToPreviousDiagnostic",
"c": "editor::GoToPreviousHunk",
"space": "vim::InsertEmptyLineAbove"
}
},
{
"context": "vim_operator == c",
"bindings": {
@@ -823,11 +860,11 @@
"j": "menu::SelectNext",
"k": "menu::SelectPrevious",
"l": "project_panel::ExpandSelectedEntry",
"o": "project_panel::OpenPermanent",
"shift-d": "project_panel::Delete",
"shift-r": "project_panel::Rename",
"t": "project_panel::OpenPermanent",
"v": "project_panel::OpenPermanent",
"v": "project_panel::OpenSplitVertical",
"o": "project_panel::OpenSplitHorizontal",
"p": "project_panel::Open",
"x": "project_panel::RevealInFileManager",
"s": "workspace::OpenWithSystem",

View File

@@ -1,4 +1,5 @@
{
"project_name": null,
// The name of the Zed theme to use for the UI.
//
// `mode` is one of:
@@ -740,16 +741,6 @@
// Default width of the collaboration panel.
"default_width": 240
},
"chat_panel": {
// When to show the chat panel button in the status bar.
// Can be 'never', 'always', or 'when_in_call',
// or a boolean (interpreted as 'never'/'always').
"button": "when_in_call",
// Where to dock the chat panel. Can be 'left' or 'right'.
"dock": "right",
// Default width of the chat panel.
"default_width": 240
},
"git_panel": {
// Whether to show the git panel button in the status bar.
"button": true,
@@ -838,6 +829,9 @@
// }
],
// When enabled, the agent can run potentially destructive actions without asking for your confirmation.
//
// 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.
"always_allow_tool_actions": false,
// When enabled, the agent will stream edits.
"stream_edits": false,
@@ -962,7 +956,7 @@
// Show git status colors in the editor tabs.
"git_status": false,
// Position of the close button on the editor tabs.
// One of: ["right", "left", "hidden"]
// One of: ["right", "left"]
"close_position": "right",
// Whether to show the file icon for a tab.
"file_icons": false,
@@ -1205,6 +1199,10 @@
// The minimum column number to show the inline blame information at
"min_column": 0
},
// Control which information is shown in the branch picker.
"branch_picker": {
"show_author_name": true
},
// How git hunks are displayed visually in the editor.
// This setting can take two values:
//

View File

@@ -316,6 +316,11 @@
"font_style": null,
"font_weight": null
},
"punctuation.markup": {
"color": "#a6a5a0ff",
"font_style": null,
"font_weight": null
},
"punctuation.special": {
"color": "#d2a6ffff",
"font_style": null,
@@ -702,6 +707,11 @@
"font_style": null,
"font_weight": null
},
"punctuation.markup": {
"color": "#73777bff",
"font_style": null,
"font_weight": null
},
"punctuation.special": {
"color": "#a37accff",
"font_style": null,
@@ -1088,6 +1098,11 @@
"font_style": null,
"font_weight": null
},
"punctuation.markup": {
"color": "#b4b3aeff",
"font_style": null,
"font_weight": null
},
"punctuation.special": {
"color": "#dfbfffff",
"font_style": null,

View File

@@ -325,6 +325,11 @@
"font_style": null,
"font_weight": null
},
"punctuation.markup": {
"color": "#83a598ff",
"font_style": null,
"font_weight": null
},
"punctuation.special": {
"color": "#e5d5adff",
"font_style": null,
@@ -725,6 +730,11 @@
"font_style": null,
"font_weight": null
},
"punctuation.markup": {
"color": "#83a598ff",
"font_style": null,
"font_weight": null
},
"punctuation.special": {
"color": "#e5d5adff",
"font_style": null,
@@ -1125,6 +1135,11 @@
"font_style": null,
"font_weight": null
},
"punctuation.markup": {
"color": "#83a598ff",
"font_style": null,
"font_weight": null
},
"punctuation.special": {
"color": "#e5d5adff",
"font_style": null,
@@ -1525,6 +1540,11 @@
"font_style": null,
"font_weight": null
},
"punctuation.markup": {
"color": "#066578ff",
"font_style": null,
"font_weight": null
},
"punctuation.special": {
"color": "#413d3aff",
"font_style": null,
@@ -1925,6 +1945,11 @@
"font_style": null,
"font_weight": null
},
"punctuation.markup": {
"color": "#066578ff",
"font_style": null,
"font_weight": null
},
"punctuation.special": {
"color": "#413d3aff",
"font_style": null,
@@ -2325,6 +2350,11 @@
"font_style": null,
"font_weight": null
},
"punctuation.markup": {
"color": "#066578ff",
"font_style": null,
"font_weight": null
},
"punctuation.special": {
"color": "#413d3aff",
"font_style": null,

View File

@@ -321,6 +321,11 @@
"font_style": null,
"font_weight": null
},
"punctuation.markup": {
"color": "#d07277ff",
"font_style": null,
"font_weight": null
},
"punctuation.special": {
"color": "#b1574bff",
"font_style": null,
@@ -715,6 +720,11 @@
"font_style": null,
"font_weight": null
},
"punctuation.markup": {
"color": "#d3604fff",
"font_style": null,
"font_weight": null
},
"punctuation.special": {
"color": "#b92b46ff",
"font_style": null,

View File

@@ -18,8 +18,8 @@ test-support = ["gpui/test-support", "project/test-support", "dep:parking_lot"]
[dependencies]
action_log.workspace = true
agent-client-protocol.workspace = true
anyhow.workspace = true
agent_settings.workspace = true
anyhow.workspace = true
buffer_diff.workspace = true
collections.workspace = true
editor.workspace = true

View File

@@ -805,6 +805,7 @@ pub enum AcpThreadEvent {
PromptCapabilitiesUpdated,
Refusal,
AvailableCommandsUpdated(Vec<acp::AvailableCommand>),
ModeUpdated(acp::SessionModeId),
}
impl EventEmitter<AcpThreadEvent> for AcpThread {}
@@ -812,7 +813,6 @@ impl EventEmitter<AcpThreadEvent> for AcpThread {}
#[derive(PartialEq, Eq, Debug)]
pub enum ThreadStatus {
Idle,
WaitingForToolConfirmation,
Generating,
}
@@ -935,11 +935,7 @@ impl AcpThread {
pub fn status(&self) -> ThreadStatus {
if self.send_task.is_some() {
if self.waiting_for_tool_confirmation() {
ThreadStatus::WaitingForToolConfirmation
} else {
ThreadStatus::Generating
}
ThreadStatus::Generating
} else {
ThreadStatus::Idle
}
@@ -1007,6 +1003,9 @@ impl AcpThread {
acp::SessionUpdate::AvailableCommandsUpdate { available_commands } => {
cx.emit(AcpThreadEvent::AvailableCommandsUpdated(available_commands))
}
acp::SessionUpdate::CurrentModeUpdate { current_mode_id } => {
cx.emit(AcpThreadEvent::ModeUpdated(current_mode_id))
}
}
Ok(())
}
@@ -1303,11 +1302,12 @@ impl AcpThread {
&mut self,
tool_call: acp::ToolCallUpdate,
options: Vec<acp::PermissionOption>,
respect_always_allow_setting: bool,
cx: &mut Context<Self>,
) -> Result<BoxFuture<'static, acp::RequestPermissionOutcome>> {
let (tx, rx) = oneshot::channel();
if AgentSettings::get_global(cx).always_allow_tool_actions {
if respect_always_allow_setting && AgentSettings::get_global(cx).always_allow_tool_actions {
// Don't use AllowAlways, because then if you were to turn off always_allow_tool_actions,
// some tools would (incorrectly) continue to auto-accept.
if let Some(allow_once_option) = options.iter().find_map(|option| {
@@ -1377,26 +1377,27 @@ impl AcpThread {
cx.emit(AcpThreadEvent::EntryUpdated(ix));
}
/// Returns true if the last turn is awaiting tool authorization
pub fn waiting_for_tool_confirmation(&self) -> bool {
pub fn first_tool_awaiting_confirmation(&self) -> Option<&ToolCall> {
let mut first_tool_call = None;
for entry in self.entries.iter().rev() {
match &entry {
AgentThreadEntry::ToolCall(call) => match call.status {
ToolCallStatus::WaitingForConfirmation { .. } => return true,
ToolCallStatus::Pending
| ToolCallStatus::InProgress
| ToolCallStatus::Completed
| ToolCallStatus::Failed
| ToolCallStatus::Rejected
| ToolCallStatus::Canceled => continue,
},
AgentThreadEntry::ToolCall(call) => {
if let ToolCallStatus::WaitingForConfirmation { .. } = call.status {
first_tool_call = Some(call);
} else {
continue;
}
}
AgentThreadEntry::UserMessage(_) | AgentThreadEntry::AssistantMessage(_) => {
// Reached the beginning of the turn
return false;
// Reached the beginning of the turn.
// If we had pending permission requests in the previous turn, they have been cancelled.
break;
}
}
}
false
first_tool_call
}
pub fn plan(&self) -> &Plan {
@@ -1640,13 +1641,13 @@ impl AcpThread {
cx.foreground_executor().spawn(send_task)
}
/// Rewinds this thread to before the entry at `index`, removing it and all
/// subsequent entries while reverting any changes made from that point.
pub fn rewind(&mut self, id: UserMessageId, cx: &mut Context<Self>) -> Task<Result<()>> {
let Some(truncate) = self.connection.truncate(&self.session_id, cx) else {
return Task::ready(Err(anyhow!("not supported")));
};
let Some(message) = self.user_message(&id) else {
/// Restores the git working tree to the state at the given checkpoint (if one exists)
pub fn restore_checkpoint(
&mut self,
id: UserMessageId,
cx: &mut Context<Self>,
) -> Task<Result<()>> {
let Some((_, message)) = self.user_message_mut(&id) else {
return Task::ready(Err(anyhow!("message not found")));
};
@@ -1654,15 +1655,30 @@ impl AcpThread {
.checkpoint
.as_ref()
.map(|c| c.git_checkpoint.clone());
let rewind = self.rewind(id.clone(), cx);
let git_store = self.project.read(cx).git_store().clone();
cx.spawn(async move |this, cx| {
cx.spawn(async move |_, cx| {
rewind.await?;
if let Some(checkpoint) = checkpoint {
git_store
.update(cx, |git, cx| git.restore_checkpoint(checkpoint, cx))?
.await?;
}
Ok(())
})
}
/// Rewinds this thread to before the entry at `index`, removing it and all
/// subsequent entries while rejecting any action_log changes made from that point.
/// Unlike `restore_checkpoint`, this method does not restore from git.
pub fn rewind(&mut self, id: UserMessageId, cx: &mut Context<Self>) -> Task<Result<()>> {
let Some(truncate) = self.connection.truncate(&self.session_id, cx) else {
return Task::ready(Err(anyhow!("not supported")));
};
cx.spawn(async move |this, cx| {
cx.update(|cx| truncate.run(id.clone(), cx))?.await?;
this.update(cx, |this, cx| {
if let Some((ix, _)) = this.user_message_mut(&id) {
@@ -1670,7 +1686,11 @@ impl AcpThread {
this.entries.truncate(ix);
cx.emit(AcpThreadEvent::EntriesRemoved(range));
}
})
this.action_log()
.update(cx, |action_log, cx| action_log.reject_all_edits(cx))
})?
.await;
Ok(())
})
}
@@ -1727,20 +1747,6 @@ impl AcpThread {
})
}
fn user_message(&self, id: &UserMessageId) -> Option<&UserMessage> {
self.entries.iter().find_map(|entry| {
if let AgentThreadEntry::UserMessage(message) = entry {
if message.id.as_ref() == Some(id) {
Some(message)
} else {
None
}
} else {
None
}
})
}
fn user_message_mut(&mut self, id: &UserMessageId) -> Option<(usize, &mut UserMessage)> {
self.entries.iter_mut().enumerate().find_map(|(ix, entry)| {
if let AgentThreadEntry::UserMessage(message) = entry {
@@ -1763,6 +1769,9 @@ impl AcpThread {
reuse_shared_snapshot: bool,
cx: &mut Context<Self>,
) -> Task<Result<String>> {
// Args are 1-based, move to 0-based
let line = line.unwrap_or_default().saturating_sub(1);
let limit = limit.unwrap_or(u32::MAX);
let project = self.project.clone();
let action_log = self.action_log.clone();
cx.spawn(async move |this, cx| {
@@ -1790,44 +1799,37 @@ impl AcpThread {
action_log.update(cx, |action_log, cx| {
action_log.buffer_read(buffer.clone(), cx);
})?;
project.update(cx, |project, cx| {
let position = buffer
.read(cx)
.snapshot()
.anchor_before(Point::new(line.unwrap_or_default(), 0));
project.set_agent_location(
Some(AgentLocation {
buffer: buffer.downgrade(),
position,
}),
cx,
);
})?;
buffer.update(cx, |buffer, _| buffer.snapshot())?
let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot())?;
this.update(cx, |this, _| {
this.shared_buffers.insert(buffer.clone(), snapshot.clone());
})?;
snapshot
};
this.update(cx, |this, _| {
let text = snapshot.text();
this.shared_buffers.insert(buffer.clone(), snapshot);
if line.is_none() && limit.is_none() {
return Ok(text);
}
let limit = limit.unwrap_or(u32::MAX) as usize;
let Some(line) = line else {
return Ok(text.lines().take(limit).collect::<String>());
};
let max_point = snapshot.max_point();
if line >= max_point.row {
anyhow::bail!(
"Attempting to read beyond the end of the file, line {}:{}",
max_point.row + 1,
max_point.column
);
}
let count = text.lines().count();
if count < line as usize {
anyhow::bail!("There are only {} lines", count);
}
Ok(text
.lines()
.skip(line as usize + 1)
.take(limit)
.collect::<String>())
})?
let start = snapshot.anchor_before(Point::new(line, 0));
let end = snapshot.anchor_before(Point::new(line.saturating_add(limit), 0));
project.update(cx, |project, cx| {
project.set_agent_location(
Some(AgentLocation {
buffer: buffer.downgrade(),
position: start,
}),
cx,
);
})?;
Ok(snapshot.text_for_range(start..end).collect::<String>())
})
}
@@ -2114,7 +2116,7 @@ mod tests {
use gpui::{App, AsyncApp, TestAppContext, WeakEntity};
use indoc::indoc;
use project::{FakeFs, Fs};
use rand::Rng as _;
use rand::{distr, prelude::*};
use serde_json::json;
use settings::SettingsStore;
use smol::stream::StreamExt as _;
@@ -2372,6 +2374,82 @@ mod tests {
request.await.unwrap();
}
#[gpui::test]
async fn test_reading_from_line(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(path!("/tmp"), json!({"foo": "one\ntwo\nthree\nfour\n"}))
.await;
let project = Project::test(fs.clone(), [], cx).await;
project
.update(cx, |project, cx| {
project.find_or_create_worktree(path!("/tmp/foo"), true, cx)
})
.await
.unwrap();
let connection = Rc::new(FakeAgentConnection::new());
let thread = cx
.update(|cx| connection.new_thread(project, Path::new(path!("/tmp")), cx))
.await
.unwrap();
// Whole file
let content = thread
.update(cx, |thread, cx| {
thread.read_text_file(path!("/tmp/foo").into(), None, None, false, cx)
})
.await
.unwrap();
assert_eq!(content, "one\ntwo\nthree\nfour\n");
// Only start line
let content = thread
.update(cx, |thread, cx| {
thread.read_text_file(path!("/tmp/foo").into(), Some(3), None, false, cx)
})
.await
.unwrap();
assert_eq!(content, "three\nfour\n");
// Only limit
let content = thread
.update(cx, |thread, cx| {
thread.read_text_file(path!("/tmp/foo").into(), None, Some(2), false, cx)
})
.await
.unwrap();
assert_eq!(content, "one\ntwo\n");
// Range
let content = thread
.update(cx, |thread, cx| {
thread.read_text_file(path!("/tmp/foo").into(), Some(2), Some(2), false, cx)
})
.await
.unwrap();
assert_eq!(content, "two\nthree\n");
// Invalid
let err = thread
.update(cx, |thread, cx| {
thread.read_text_file(path!("/tmp/foo").into(), Some(5), Some(2), false, cx)
})
.await
.unwrap_err();
assert_eq!(
err.to_string(),
"Attempting to read beyond the end of the file, line 5:0"
);
}
#[gpui::test]
async fn test_succeeding_canceled_toolcall(cx: &mut TestAppContext) {
init_test(cx);
@@ -2684,7 +2762,7 @@ mod tests {
let AgentThreadEntry::UserMessage(message) = &thread.entries[2] else {
panic!("unexpected entries {:?}", thread.entries)
};
thread.rewind(message.id.clone().unwrap(), cx)
thread.restore_checkpoint(message.id.clone().unwrap(), cx)
})
.await
.unwrap();
@@ -2758,7 +2836,7 @@ mod tests {
}));
let thread = cx
.update(|cx| connection.new_thread(project, Path::new("/test"), cx))
.update(|cx| connection.new_thread(project, Path::new(path!("/test")), cx))
.await
.unwrap();
@@ -3057,8 +3135,8 @@ mod tests {
cx: &mut App,
) -> Task<gpui::Result<Entity<AcpThread>>> {
let session_id = acp::SessionId(
rand::thread_rng()
.sample_iter(&rand::distributions::Alphanumeric)
rand::rng()
.sample_iter(&distr::Alphanumeric)
.take(7)
.map(char::from)
.collect::<String>()

View File

@@ -75,6 +75,15 @@ pub trait AgentConnection {
fn telemetry(&self) -> Option<Rc<dyn AgentTelemetry>> {
None
}
fn session_modes(
&self,
_session_id: &acp::SessionId,
_cx: &App,
) -> Option<Rc<dyn AgentSessionModes>> {
None
}
fn into_any(self: Rc<Self>) -> Rc<dyn Any>;
}
@@ -109,6 +118,14 @@ pub trait AgentTelemetry {
) -> Task<Result<serde_json::Value>>;
}
pub trait AgentSessionModes {
fn current_mode(&self) -> acp::SessionModeId;
fn all_modes(&self) -> Vec<acp::SessionMode>;
fn set_mode(&self, mode: acp::SessionModeId, cx: &mut App) -> Task<Result<()>>;
}
#[derive(Debug)]
pub struct AuthRequired {
pub description: Option<String>,
@@ -397,6 +414,7 @@ mod test_support {
thread.request_tool_call_authorization(
tool_call.clone().into(),
options.clone(),
false,
cx,
)
})??

View File

@@ -2218,7 +2218,7 @@ mod tests {
action_log.update(cx, |log, cx| log.buffer_read(buffer.clone(), cx));
for _ in 0..operations {
match rng.gen_range(0..100) {
match rng.random_range(0..100) {
0..25 => {
action_log.update(cx, |log, cx| {
let range = buffer.read(cx).random_byte_range(0, &mut rng);
@@ -2237,7 +2237,7 @@ mod tests {
.unwrap();
}
_ => {
let is_agent_edit = rng.gen_bool(0.5);
let is_agent_edit = rng.random_bool(0.5);
if is_agent_edit {
log::info!("agent edit");
} else {
@@ -2252,7 +2252,7 @@ mod tests {
}
}
if rng.gen_bool(0.2) {
if rng.random_bool(0.2) {
quiesce(&action_log, &buffer, cx);
}
}

View File

@@ -84,7 +84,6 @@ impl ActivityIndicator {
) -> Entity<ActivityIndicator> {
let project = workspace.project().clone();
let auto_updater = AutoUpdater::get(cx);
let workspace_handle = cx.entity();
let this = cx.new(|cx| {
let mut status_events = languages.language_server_binary_statuses();
cx.spawn(async move |this, cx| {
@@ -102,20 +101,6 @@ impl ActivityIndicator {
})
.detach();
cx.subscribe_in(
&workspace_handle,
window,
|activity_indicator, _, event, window, cx| {
if let workspace::Event::ClearActivityIndicator = event
&& activity_indicator.statuses.pop().is_some()
{
activity_indicator.dismiss_error_message(&DismissErrorMessage, window, cx);
cx.notify();
}
},
)
.detach();
cx.subscribe(
&project.read(cx).lsp_store(),
|activity_indicator, _, event, cx| {
@@ -227,7 +212,8 @@ impl ActivityIndicator {
server_name,
status,
} => {
let create_buffer = project.update(cx, |project, cx| project.create_buffer(cx));
let create_buffer =
project.update(cx, |project, cx| project.create_buffer(false, cx));
let status = status.clone();
let server_name = server_name.clone();
cx.spawn_in(window, async move |workspace, cx| {

View File

@@ -771,7 +771,9 @@ impl NativeAgentConnection {
response,
}) => {
let outcome_task = acp_thread.update(cx, |thread, cx| {
thread.request_tool_call_authorization(tool_call, options, cx)
thread.request_tool_call_authorization(
tool_call, options, true, cx,
)
})??;
cx.background_spawn(async move {
if let acp::RequestPermissionOutcome::Selected { option_id } =

View File

@@ -35,10 +35,15 @@ impl AgentServer for NativeAgentServer {
fn connect(
&self,
_root_dir: &Path,
_root_dir: Option<&Path>,
delegate: AgentServerDelegate,
cx: &mut App,
) -> Task<Result<Rc<dyn acp_thread::AgentConnection>>> {
) -> Task<
Result<(
Rc<dyn acp_thread::AgentConnection>,
Option<task::SpawnInTerminal>,
)>,
> {
log::debug!(
"NativeAgentServer::connect called for path: {:?}",
_root_dir
@@ -60,7 +65,10 @@ impl AgentServer for NativeAgentServer {
let connection = NativeAgentConnection(agent);
log::debug!("NativeAgentServer connection established successfully");
Ok(Rc::new(connection) as Rc<dyn acp_thread::AgentConnection>)
Ok((
Rc::new(connection) as Rc<dyn acp_thread::AgentConnection>,
None,
))
})
}

View File

@@ -24,7 +24,11 @@ impl AgentTool for EchoTool {
acp::ToolKind::Other
}
fn initial_title(&self, _input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
_input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
"Echo".into()
}
@@ -55,7 +59,11 @@ impl AgentTool for DelayTool {
"delay"
}
fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
if let Ok(input) = input {
format!("Delay {}ms", input.ms).into()
} else {
@@ -100,7 +108,11 @@ impl AgentTool for ToolRequiringPermission {
acp::ToolKind::Other
}
fn initial_title(&self, _input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
_input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
"This tool requires permission".into()
}
@@ -135,7 +147,11 @@ impl AgentTool for InfiniteTool {
acp::ToolKind::Other
}
fn initial_title(&self, _input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
_input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
"Infinite Tool".into()
}
@@ -186,7 +202,11 @@ impl AgentTool for WordListTool {
acp::ToolKind::Other
}
fn initial_title(&self, _input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
_input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
"List of random words".into()
}

View File

@@ -741,7 +741,7 @@ impl Thread {
return;
};
let title = tool.initial_title(tool_use.input.clone());
let title = tool.initial_title(tool_use.input.clone(), cx);
let kind = tool.kind();
stream.send_tool_call(&tool_use.id, title, kind, tool_use.input.clone());
@@ -1062,7 +1062,11 @@ impl Thread {
self.action_log.clone(),
));
self.add_tool(DiagnosticsTool::new(self.project.clone()));
self.add_tool(EditFileTool::new(cx.weak_entity(), language_registry));
self.add_tool(EditFileTool::new(
self.project.clone(),
cx.weak_entity(),
language_registry,
));
self.add_tool(FetchTool::new(self.project.read(cx).client().http_client()));
self.add_tool(FindPathTool::new(self.project.clone()));
self.add_tool(GrepTool::new(self.project.clone()));
@@ -1514,7 +1518,7 @@ impl Thread {
let mut title = SharedString::from(&tool_use.name);
let mut kind = acp::ToolKind::Other;
if let Some(tool) = tool.as_ref() {
title = tool.initial_title(tool_use.input.clone());
title = tool.initial_title(tool_use.input.clone(), cx);
kind = tool.kind();
}
@@ -2148,7 +2152,11 @@ where
fn kind() -> acp::ToolKind;
/// The initial tool title to display. Can be updated during the tool run.
fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString;
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
cx: &mut App,
) -> SharedString;
/// Returns the JSON schema that describes the tool's input.
fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Schema {
@@ -2196,7 +2204,7 @@ pub trait AnyAgentTool {
fn name(&self) -> SharedString;
fn description(&self) -> SharedString;
fn kind(&self) -> acp::ToolKind;
fn initial_title(&self, input: serde_json::Value) -> SharedString;
fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString;
fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
fn supported_provider(&self, _provider: &LanguageModelProviderId) -> bool {
true
@@ -2232,9 +2240,9 @@ where
T::kind()
}
fn initial_title(&self, input: serde_json::Value) -> SharedString {
fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString {
let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
self.0.initial_title(parsed_input)
self.0.initial_title(parsed_input, _cx)
}
fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {

View File

@@ -145,7 +145,7 @@ impl AnyAgentTool for ContextServerTool {
ToolKind::Other
}
fn initial_title(&self, _input: serde_json::Value) -> SharedString {
fn initial_title(&self, _input: serde_json::Value, _cx: &mut App) -> SharedString {
format!("Run MCP tool `{}`", self.tool.name).into()
}
@@ -176,7 +176,7 @@ impl AnyAgentTool for ContextServerTool {
return Task::ready(Err(anyhow!("Context server not found")));
};
let tool_name = self.tool.name.clone();
let authorize = event_stream.authorize(self.initial_title(input.clone()), cx);
let authorize = event_stream.authorize(self.initial_title(input.clone(), cx), cx);
cx.spawn(async move |_cx| {
authorize.await?;

View File

@@ -58,7 +58,11 @@ impl AgentTool for CopyPathTool {
ToolKind::Move
}
fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> ui::SharedString {
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> ui::SharedString {
if let Ok(input) = input {
let src = MarkdownInlineCode(&input.source_path);
let dest = MarkdownInlineCode(&input.destination_path);

View File

@@ -49,7 +49,11 @@ impl AgentTool for CreateDirectoryTool {
ToolKind::Read
}
fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
if let Ok(input) = input {
format!("Create directory {}", MarkdownInlineCode(&input.path)).into()
} else {

View File

@@ -52,7 +52,11 @@ impl AgentTool for DeletePathTool {
ToolKind::Delete
}
fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
if let Ok(input) = input {
format!("Delete “`{}`”", input.path).into()
} else {

View File

@@ -71,7 +71,11 @@ impl AgentTool for DiagnosticsTool {
acp::ToolKind::Read
}
fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
if let Some(path) = input.ok().and_then(|input| match input.path {
Some(path) if !path.is_empty() => Some(path),
_ => None,

View File

@@ -120,11 +120,17 @@ impl From<EditFileToolOutput> for LanguageModelToolResultContent {
pub struct EditFileTool {
thread: WeakEntity<Thread>,
language_registry: Arc<LanguageRegistry>,
project: Entity<Project>,
}
impl EditFileTool {
pub fn new(thread: WeakEntity<Thread>, language_registry: Arc<LanguageRegistry>) -> Self {
pub fn new(
project: Entity<Project>,
thread: WeakEntity<Thread>,
language_registry: Arc<LanguageRegistry>,
) -> Self {
Self {
project,
thread,
language_registry,
}
@@ -195,22 +201,50 @@ impl AgentTool for EditFileTool {
acp::ToolKind::Edit
}
fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
cx: &mut App,
) -> SharedString {
match input {
Ok(input) => input.display_description.into(),
Ok(input) => self
.project
.read(cx)
.find_project_path(&input.path, cx)
.and_then(|project_path| {
self.project
.read(cx)
.short_full_path_for_project_path(&project_path, cx)
})
.unwrap_or(Path::new(&input.path).into())
.to_string_lossy()
.to_string()
.into(),
Err(raw_input) => {
if let Some(input) =
serde_json::from_value::<EditFileToolPartialInput>(raw_input).ok()
{
let path = input.path.trim();
if !path.is_empty() {
return self
.project
.read(cx)
.find_project_path(&input.path, cx)
.and_then(|project_path| {
self.project
.read(cx)
.short_full_path_for_project_path(&project_path, cx)
})
.unwrap_or(Path::new(&input.path).into())
.to_string_lossy()
.to_string()
.into();
}
let description = input.display_description.trim();
if !description.is_empty() {
return description.to_string().into();
}
let path = input.path.trim().to_string();
if !path.is_empty() {
return path.into();
}
}
DEFAULT_UI_TEXT.into()
@@ -545,7 +579,7 @@ mod tests {
let model = Arc::new(FakeLanguageModel::default());
let thread = cx.new(|cx| {
Thread::new(
project,
project.clone(),
cx.new(|_cx| ProjectContext::default()),
context_server_registry,
Templates::new(),
@@ -560,11 +594,12 @@ mod tests {
path: "root/nonexistent_file.txt".into(),
mode: EditFileMode::Edit,
};
Arc::new(EditFileTool::new(thread.downgrade(), language_registry)).run(
input,
ToolCallEventStream::test().0,
cx,
)
Arc::new(EditFileTool::new(
project,
thread.downgrade(),
language_registry,
))
.run(input, ToolCallEventStream::test().0, cx)
})
.await;
assert_eq!(
@@ -743,7 +778,7 @@ mod tests {
let model = Arc::new(FakeLanguageModel::default());
let thread = cx.new(|cx| {
Thread::new(
project,
project.clone(),
cx.new(|_cx| ProjectContext::default()),
context_server_registry,
Templates::new(),
@@ -775,6 +810,7 @@ mod tests {
mode: EditFileMode::Overwrite,
};
Arc::new(EditFileTool::new(
project.clone(),
thread.downgrade(),
language_registry.clone(),
))
@@ -833,11 +869,12 @@ mod tests {
path: "root/src/main.rs".into(),
mode: EditFileMode::Overwrite,
};
Arc::new(EditFileTool::new(thread.downgrade(), language_registry)).run(
input,
ToolCallEventStream::test().0,
cx,
)
Arc::new(EditFileTool::new(
project.clone(),
thread.downgrade(),
language_registry,
))
.run(input, ToolCallEventStream::test().0, cx)
});
// Stream the unformatted content
@@ -885,7 +922,7 @@ mod tests {
let model = Arc::new(FakeLanguageModel::default());
let thread = cx.new(|cx| {
Thread::new(
project,
project.clone(),
cx.new(|_cx| ProjectContext::default()),
context_server_registry,
Templates::new(),
@@ -918,6 +955,7 @@ mod tests {
mode: EditFileMode::Overwrite,
};
Arc::new(EditFileTool::new(
project.clone(),
thread.downgrade(),
language_registry.clone(),
))
@@ -969,11 +1007,12 @@ mod tests {
path: "root/src/main.rs".into(),
mode: EditFileMode::Overwrite,
};
Arc::new(EditFileTool::new(thread.downgrade(), language_registry)).run(
input,
ToolCallEventStream::test().0,
cx,
)
Arc::new(EditFileTool::new(
project.clone(),
thread.downgrade(),
language_registry,
))
.run(input, ToolCallEventStream::test().0, cx)
});
// Stream the content with trailing whitespace
@@ -1012,7 +1051,7 @@ mod tests {
let model = Arc::new(FakeLanguageModel::default());
let thread = cx.new(|cx| {
Thread::new(
project,
project.clone(),
cx.new(|_cx| ProjectContext::default()),
context_server_registry,
Templates::new(),
@@ -1020,7 +1059,11 @@ mod tests {
cx,
)
});
let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
let tool = Arc::new(EditFileTool::new(
project.clone(),
thread.downgrade(),
language_registry,
));
fs.insert_tree("/root", json!({})).await;
// Test 1: Path with .zed component should require confirmation
@@ -1148,7 +1191,7 @@ mod tests {
let model = Arc::new(FakeLanguageModel::default());
let thread = cx.new(|cx| {
Thread::new(
project,
project.clone(),
cx.new(|_cx| ProjectContext::default()),
context_server_registry,
Templates::new(),
@@ -1156,7 +1199,11 @@ mod tests {
cx,
)
});
let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
let tool = Arc::new(EditFileTool::new(
project.clone(),
thread.downgrade(),
language_registry,
));
// Test global config paths - these should require confirmation if they exist and are outside the project
let test_cases = vec![
@@ -1264,7 +1311,11 @@ mod tests {
cx,
)
});
let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
let tool = Arc::new(EditFileTool::new(
project.clone(),
thread.downgrade(),
language_registry,
));
// Test files in different worktrees
let test_cases = vec![
@@ -1344,7 +1395,11 @@ mod tests {
cx,
)
});
let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
let tool = Arc::new(EditFileTool::new(
project.clone(),
thread.downgrade(),
language_registry,
));
// Test edge cases
let test_cases = vec![
@@ -1427,7 +1482,11 @@ mod tests {
cx,
)
});
let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
let tool = Arc::new(EditFileTool::new(
project.clone(),
thread.downgrade(),
language_registry,
));
// Test different EditFileMode values
let modes = vec![
@@ -1507,48 +1566,67 @@ mod tests {
cx,
)
});
let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
let tool = Arc::new(EditFileTool::new(
project,
thread.downgrade(),
language_registry,
));
assert_eq!(
tool.initial_title(Err(json!({
"path": "src/main.rs",
"display_description": "",
"old_string": "old code",
"new_string": "new code"
}))),
"src/main.rs"
);
assert_eq!(
tool.initial_title(Err(json!({
"path": "",
"display_description": "Fix error handling",
"old_string": "old code",
"new_string": "new code"
}))),
"Fix error handling"
);
assert_eq!(
tool.initial_title(Err(json!({
"path": "src/main.rs",
"display_description": "Fix error handling",
"old_string": "old code",
"new_string": "new code"
}))),
"Fix error handling"
);
assert_eq!(
tool.initial_title(Err(json!({
"path": "",
"display_description": "",
"old_string": "old code",
"new_string": "new code"
}))),
DEFAULT_UI_TEXT
);
assert_eq!(
tool.initial_title(Err(serde_json::Value::Null)),
DEFAULT_UI_TEXT
);
cx.update(|cx| {
// ...
assert_eq!(
tool.initial_title(
Err(json!({
"path": "src/main.rs",
"display_description": "",
"old_string": "old code",
"new_string": "new code"
})),
cx
),
"src/main.rs"
);
assert_eq!(
tool.initial_title(
Err(json!({
"path": "",
"display_description": "Fix error handling",
"old_string": "old code",
"new_string": "new code"
})),
cx
),
"Fix error handling"
);
assert_eq!(
tool.initial_title(
Err(json!({
"path": "src/main.rs",
"display_description": "Fix error handling",
"old_string": "old code",
"new_string": "new code"
})),
cx
),
"src/main.rs"
);
assert_eq!(
tool.initial_title(
Err(json!({
"path": "",
"display_description": "",
"old_string": "old code",
"new_string": "new code"
})),
cx
),
DEFAULT_UI_TEXT
);
assert_eq!(
tool.initial_title(Err(serde_json::Value::Null), cx),
DEFAULT_UI_TEXT
);
});
}
#[gpui::test]
@@ -1575,7 +1653,11 @@ mod tests {
// Ensure the diff is finalized after the edit completes.
{
let tool = Arc::new(EditFileTool::new(thread.downgrade(), languages.clone()));
let tool = Arc::new(EditFileTool::new(
project.clone(),
thread.downgrade(),
languages.clone(),
));
let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
let edit = cx.update(|cx| {
tool.run(
@@ -1600,7 +1682,11 @@ mod tests {
// Ensure the diff is finalized if an error occurs while editing.
{
model.forbid_requests();
let tool = Arc::new(EditFileTool::new(thread.downgrade(), languages.clone()));
let tool = Arc::new(EditFileTool::new(
project.clone(),
thread.downgrade(),
languages.clone(),
));
let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
let edit = cx.update(|cx| {
tool.run(
@@ -1623,7 +1709,11 @@ mod tests {
// Ensure the diff is finalized if the tool call gets dropped.
{
let tool = Arc::new(EditFileTool::new(thread.downgrade(), languages.clone()));
let tool = Arc::new(EditFileTool::new(
project.clone(),
thread.downgrade(),
languages.clone(),
));
let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
let edit = cx.update(|cx| {
tool.run(

View File

@@ -126,7 +126,11 @@ impl AgentTool for FetchTool {
acp::ToolKind::Fetch
}
fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
match input {
Ok(input) => format!("Fetch {}", MarkdownEscaped(&input.url)).into(),
Err(_) => "Fetch URL".into(),

View File

@@ -93,7 +93,11 @@ impl AgentTool for FindPathTool {
acp::ToolKind::Search
}
fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
let mut title = "Find paths".to_string();
if let Ok(input) = input {
title.push_str(&format!(" matching “`{}`”", input.glob));

View File

@@ -75,7 +75,11 @@ impl AgentTool for GrepTool {
acp::ToolKind::Search
}
fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
match input {
Ok(input) => {
let page = input.page();

View File

@@ -59,7 +59,11 @@ impl AgentTool for ListDirectoryTool {
ToolKind::Read
}
fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
if let Ok(input) = input {
let path = MarkdownInlineCode(&input.path);
format!("List the {path} directory's contents").into()

View File

@@ -60,7 +60,11 @@ impl AgentTool for MovePathTool {
ToolKind::Move
}
fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
if let Ok(input) = input {
let src = MarkdownInlineCode(&input.source_path);
let dest = MarkdownInlineCode(&input.destination_path);

View File

@@ -41,7 +41,11 @@ impl AgentTool for NowTool {
acp::ToolKind::Other
}
fn initial_title(&self, _input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
_input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
"Get current time".into()
}

View File

@@ -45,7 +45,11 @@ impl AgentTool for OpenTool {
ToolKind::Execute
}
fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
if let Ok(input) = input {
format!("Open `{}`", MarkdownEscaped(&input.path_or_url)).into()
} else {
@@ -61,7 +65,7 @@ impl AgentTool for OpenTool {
) -> Task<Result<Self::Output>> {
// If path_or_url turns out to be a path in the project, make it absolute.
let abs_path = to_absolute_path(&input.path_or_url, self.project.clone(), cx);
let authorize = event_stream.authorize(self.initial_title(Ok(input.clone())), cx);
let authorize = event_stream.authorize(self.initial_title(Ok(input.clone()), cx), cx);
cx.background_spawn(async move {
authorize.await?;

View File

@@ -10,7 +10,7 @@ use project::{AgentLocation, ImageItem, Project, WorktreeSettings, image_store};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use settings::Settings;
use std::{path::Path, sync::Arc};
use std::sync::Arc;
use util::markdown::MarkdownCodeBlock;
use crate::{AgentTool, ToolCallEventStream};
@@ -68,13 +68,31 @@ impl AgentTool for ReadFileTool {
acp::ToolKind::Read
}
fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString {
input
.ok()
.as_ref()
.and_then(|input| Path::new(&input.path).file_name())
.map(|file_name| file_name.to_string_lossy().to_string().into())
.unwrap_or_default()
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
cx: &mut App,
) -> SharedString {
if let Ok(input) = input
&& let Some(project_path) = self.project.read(cx).find_project_path(&input.path, cx)
&& let Some(path) = self
.project
.read(cx)
.short_full_path_for_project_path(&project_path, cx)
{
match (input.start_line, input.end_line) {
(Some(start), Some(end)) => {
format!("Read file `{}` (lines {}-{})", path.display(), start, end,)
}
(Some(start), None) => {
format!("Read file `{}` (from line {})", path.display(), start)
}
_ => format!("Read file `{}`", path.display()),
}
.into()
} else {
"Read file".into()
}
}
fn run(
@@ -86,6 +104,12 @@ impl AgentTool for ReadFileTool {
let Some(project_path) = self.project.read(cx).find_project_path(&input.path, cx) else {
return Task::ready(Err(anyhow!("Path {} not found in project", &input.path)));
};
let Some(abs_path) = self.project.read(cx).absolute_path(&project_path, cx) else {
return Task::ready(Err(anyhow!(
"Failed to convert {} to absolute path",
&input.path
)));
};
// Error out if this path is either excluded or private in global settings
let global_settings = WorktreeSettings::get_global(cx);
@@ -121,6 +145,14 @@ impl AgentTool for ReadFileTool {
let file_path = input.path.clone();
event_stream.update_fields(ToolCallUpdateFields {
locations: Some(vec![acp::ToolCallLocation {
path: abs_path,
line: input.start_line.map(|line| line.saturating_sub(1)),
}]),
..Default::default()
});
if image_store::is_image_file(&self.project, &project_path, cx) {
return cx.spawn(async move |cx| {
let image_entity: Entity<ImageItem> = cx
@@ -229,34 +261,25 @@ impl AgentTool for ReadFileTool {
};
project.update(cx, |project, cx| {
if let Some(abs_path) = project.absolute_path(&project_path, cx) {
project.set_agent_location(
Some(AgentLocation {
buffer: buffer.downgrade(),
position: anchor.unwrap_or(text::Anchor::MIN),
}),
cx,
);
project.set_agent_location(
Some(AgentLocation {
buffer: buffer.downgrade(),
position: anchor.unwrap_or(text::Anchor::MIN),
}),
cx,
);
if let Ok(LanguageModelToolResultContent::Text(text)) = &result {
let markdown = MarkdownCodeBlock {
tag: &input.path,
text,
}
.to_string();
event_stream.update_fields(ToolCallUpdateFields {
locations: Some(vec![acp::ToolCallLocation {
path: abs_path,
line: input.start_line.map(|line| line.saturating_sub(1)),
content: Some(vec![acp::ToolCallContent::Content {
content: markdown.into(),
}]),
..Default::default()
});
if let Ok(LanguageModelToolResultContent::Text(text)) = &result {
let markdown = MarkdownCodeBlock {
tag: &input.path,
text,
}
.to_string();
event_stream.update_fields(ToolCallUpdateFields {
content: Some(vec![acp::ToolCallContent::Content {
content: markdown.into(),
}]),
..Default::default()
})
}
})
}
})?;

View File

@@ -60,7 +60,11 @@ impl AgentTool for TerminalTool {
acp::ToolKind::Execute
}
fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
if let Ok(input) = input {
let mut lines = input.command.lines();
let first_line = lines.next().unwrap_or_default();
@@ -93,7 +97,7 @@ impl AgentTool for TerminalTool {
Err(err) => return Task::ready(Err(err)),
};
let authorize = event_stream.authorize(self.initial_title(Ok(input.clone())), cx);
let authorize = event_stream.authorize(self.initial_title(Ok(input.clone()), cx), cx);
cx.spawn(async move |cx| {
authorize.await?;

View File

@@ -29,7 +29,11 @@ impl AgentTool for ThinkingTool {
acp::ToolKind::Think
}
fn initial_title(&self, _input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
_input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
"Thinking".into()
}

View File

@@ -48,7 +48,11 @@ impl AgentTool for WebSearchTool {
acp::ToolKind::Fetch
}
fn initial_title(&self, _input: Result<Self::Input, serde_json::Value>) -> SharedString {
fn initial_title(
&self,
_input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
"Searching the Web".into()
}

View File

@@ -23,34 +23,31 @@ action_log.workspace = true
agent-client-protocol.workspace = true
agent_settings.workspace = true
anyhow.workspace = true
client = { workspace = true, optional = true }
client.workspace = true
collections.workspace = true
env_logger = { workspace = true, optional = true }
fs.workspace = true
futures.workspace = true
gpui.workspace = true
gpui_tokio = { workspace = true, optional = true }
http_client.workspace = true
indoc.workspace = true
language.workspace = true
language_model.workspace = true
language_models.workspace = true
log.workspace = true
node_runtime.workspace = true
paths.workspace = true
project.workspace = true
reqwest_client = { workspace = true, optional = true }
schemars.workspace = true
semver.workspace = true
serde.workspace = true
serde_json.workspace = true
settings.workspace = true
smol.workspace = true
task.workspace = true
tempfile.workspace = true
thiserror.workspace = true
ui.workspace = true
util.workspace = true
watch.workspace = true
which.workspace = true
workspace-hack.workspace = true
[target.'cfg(unix)'.dependencies]

View File

@@ -1,4 +1,3 @@
use crate::AgentServerCommand;
use acp_thread::AgentConnection;
use acp_tools::AcpConnectionRegistry;
use action_log::ActionLog;
@@ -8,8 +7,11 @@ use collections::HashMap;
use futures::AsyncBufReadExt as _;
use futures::io::BufReader;
use project::Project;
use project::agent_server_store::AgentServerCommand;
use serde::Deserialize;
use util::ResultExt as _;
use std::path::PathBuf;
use std::{any::Any, cell::RefCell};
use std::{path::Path, rc::Rc};
use thiserror::Error;
@@ -29,6 +31,11 @@ pub struct AcpConnection {
sessions: Rc<RefCell<HashMap<acp::SessionId, AcpSession>>>,
auth_methods: Vec<acp::AuthMethod>,
agent_capabilities: acp::AgentCapabilities,
default_mode: Option<acp::SessionModeId>,
root_dir: PathBuf,
// 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).
child: smol::process::Child,
_io_task: Task<Result<()>>,
_wait_task: Task<Result<()>>,
_stderr_task: Task<Result<()>>,
@@ -37,15 +44,26 @@ pub struct AcpConnection {
pub struct AcpSession {
thread: WeakEntity<AcpThread>,
suppress_abort_err: bool,
session_modes: Option<Rc<RefCell<acp::SessionModeState>>>,
}
pub async fn connect(
server_name: SharedString,
command: AgentServerCommand,
root_dir: &Path,
default_mode: Option<acp::SessionModeId>,
is_remote: bool,
cx: &mut AsyncApp,
) -> Result<Rc<dyn AgentConnection>> {
let conn = AcpConnection::stdio(server_name, command.clone(), root_dir, cx).await?;
let conn = AcpConnection::stdio(
server_name,
command.clone(),
root_dir,
default_mode,
is_remote,
cx,
)
.await?;
Ok(Rc::new(conn) as _)
}
@@ -56,17 +74,21 @@ impl AcpConnection {
server_name: SharedString,
command: AgentServerCommand,
root_dir: &Path,
default_mode: Option<acp::SessionModeId>,
is_remote: bool,
cx: &mut AsyncApp,
) -> Result<Self> {
let mut child = util::command::new_smol_command(command.path)
let mut child = util::command::new_smol_command(command.path);
child
.args(command.args.iter().map(|arg| arg.as_str()))
.envs(command.env.iter().flatten())
.current_dir(root_dir)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true)
.spawn()?;
.stderr(std::process::Stdio::piped());
if !is_remote {
child.current_dir(root_dir);
}
let mut child = child.spawn()?;
let stdout = child.stdout.take().context("Failed to take stdout")?;
let stdin = child.stdin.take().context("Failed to take stdin")?;
@@ -102,8 +124,9 @@ impl AcpConnection {
let wait_task = cx.spawn({
let sessions = sessions.clone();
let status_fut = child.status();
async move |cx| {
let status = child.status().await?;
let status = status_fut.await?;
for session in sessions.borrow().values() {
session
@@ -145,19 +168,33 @@ impl AcpConnection {
Ok(Self {
auth_methods: response.auth_methods,
root_dir: root_dir.to_owned(),
connection,
server_name,
sessions,
agent_capabilities: response.agent_capabilities,
default_mode,
_io_task: io_task,
_wait_task: wait_task,
_stderr_task: stderr_task,
child,
})
}
pub fn prompt_capabilities(&self) -> &acp::PromptCapabilities {
&self.agent_capabilities.prompt_capabilities
}
pub fn root_dir(&self) -> &Path {
&self.root_dir
}
}
impl Drop for AcpConnection {
fn drop(&mut self) {
// See the comment on the child field.
self.child.kill().log_err();
}
}
impl AgentConnection for AcpConnection {
@@ -167,33 +204,42 @@ impl AgentConnection for AcpConnection {
cwd: &Path,
cx: &mut App,
) -> Task<Result<Entity<AcpThread>>> {
let name = self.server_name.clone();
let conn = self.connection.clone();
let sessions = self.sessions.clone();
let default_mode = self.default_mode.clone();
let cwd = cwd.to_path_buf();
let context_server_store = project.read(cx).context_server_store().read(cx);
let mcp_servers = context_server_store
.configured_server_ids()
.iter()
.filter_map(|id| {
let configuration = context_server_store.configuration_for_server(id)?;
let command = configuration.command();
Some(acp::McpServer {
name: id.0.to_string(),
command: command.path.clone(),
args: command.args.clone(),
env: if let Some(env) = command.env.as_ref() {
env.iter()
.map(|(name, value)| acp::EnvVariable {
name: name.clone(),
value: value.clone(),
})
.collect()
} else {
vec![]
},
let mcp_servers = if project.read(cx).is_local() {
context_server_store
.configured_server_ids()
.iter()
.filter_map(|id| {
let configuration = context_server_store.configuration_for_server(id)?;
let command = configuration.command();
Some(acp::McpServer::Stdio {
name: id.0.to_string(),
command: command.path.clone(),
args: command.args.clone(),
env: if let Some(env) = command.env.as_ref() {
env.iter()
.map(|(name, value)| acp::EnvVariable {
name: name.clone(),
value: value.clone(),
})
.collect()
} else {
vec![]
},
})
})
})
.collect();
.collect()
} else {
// In SSH projects, the external agent is running on the remote
// machine, and currently we only run MCP servers on the local
// machine. So don't pass any MCP servers to the agent in that case.
Vec::new()
};
cx.spawn(async move |cx| {
let response = conn
@@ -213,6 +259,53 @@ impl AgentConnection for AcpConnection {
}
})?;
let modes = response.modes.map(|modes| Rc::new(RefCell::new(modes)));
if let Some(default_mode) = default_mode {
if let Some(modes) = modes.as_ref() {
let mut modes_ref = modes.borrow_mut();
let has_mode = modes_ref.available_modes.iter().any(|mode| mode.id == default_mode);
if has_mode {
let initial_mode_id = modes_ref.current_mode_id.clone();
cx.spawn({
let default_mode = default_mode.clone();
let session_id = response.session_id.clone();
let modes = modes.clone();
async move |_| {
let result = conn.set_session_mode(acp::SetSessionModeRequest {
session_id,
mode_id: default_mode,
})
.await.log_err();
if result.is_none() {
modes.borrow_mut().current_mode_id = initial_mode_id;
}
}
}).detach();
modes_ref.current_mode_id = default_mode;
} else {
let available_modes = modes_ref
.available_modes
.iter()
.map(|mode| format!("- `{}`: {}", mode.id, mode.name))
.collect::<Vec<_>>()
.join("\n");
log::warn!(
"`{default_mode}` is not valid {name} mode. Available options:\n{available_modes}",
);
}
} else {
log::warn!(
"`{name}` does not support modes, but `default_mode` was set in settings.",
);
}
}
let session_id = response.session_id;
let action_log = cx.new(|_| ActionLog::new(project.clone()))?;
let thread = cx.new(|cx| {
@@ -231,6 +324,7 @@ impl AgentConnection for AcpConnection {
let session = AcpSession {
thread: thread.downgrade(),
suppress_abort_err: false,
session_modes: modes
};
sessions.borrow_mut().insert(session_id, session);
@@ -327,11 +421,77 @@ impl AgentConnection for AcpConnection {
.detach();
}
fn session_modes(
&self,
session_id: &acp::SessionId,
_cx: &App,
) -> Option<Rc<dyn acp_thread::AgentSessionModes>> {
let sessions = self.sessions.clone();
let sessions_ref = sessions.borrow();
let Some(session) = sessions_ref.get(session_id) else {
return None;
};
if let Some(modes) = session.session_modes.as_ref() {
Some(Rc::new(AcpSessionModes {
connection: self.connection.clone(),
session_id: session_id.clone(),
state: modes.clone(),
}) as _)
} else {
None
}
}
fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
self
}
}
struct AcpSessionModes {
session_id: acp::SessionId,
connection: Rc<acp::ClientSideConnection>,
state: Rc<RefCell<acp::SessionModeState>>,
}
impl acp_thread::AgentSessionModes for AcpSessionModes {
fn current_mode(&self) -> acp::SessionModeId {
self.state.borrow().current_mode_id.clone()
}
fn all_modes(&self) -> Vec<acp::SessionMode> {
self.state.borrow().available_modes.clone()
}
fn set_mode(&self, mode_id: acp::SessionModeId, cx: &mut App) -> Task<Result<()>> {
let connection = self.connection.clone();
let session_id = self.session_id.clone();
let old_mode_id;
{
let mut state = self.state.borrow_mut();
old_mode_id = state.current_mode_id.clone();
state.current_mode_id = mode_id.clone();
};
let state = self.state.clone();
cx.foreground_executor().spawn(async move {
let result = connection
.set_session_mode(acp::SetSessionModeRequest {
session_id,
mode_id,
})
.await;
if result.is_err() {
state.borrow_mut().current_mode_id = old_mode_id;
}
result?;
Ok(())
})
}
}
struct ClientDelegate {
sessions: Rc<RefCell<HashMap<acp::SessionId, AcpSession>>>,
cx: AsyncApp,
@@ -342,13 +502,27 @@ impl acp::Client for ClientDelegate {
&self,
arguments: acp::RequestPermissionRequest,
) -> Result<acp::RequestPermissionResponse, acp::Error> {
let respect_always_allow_setting;
let thread;
{
let sessions_ref = self.sessions.borrow();
let session = sessions_ref
.get(&arguments.session_id)
.context("Failed to get session")?;
respect_always_allow_setting = session.session_modes.is_none();
thread = session.thread.clone();
}
let cx = &mut self.cx.clone();
let task = self
.session_thread(&arguments.session_id)?
.update(cx, |thread, cx| {
thread.request_tool_call_authorization(arguments.tool_call, arguments.options, cx)
})??;
let task = thread.update(cx, |thread, cx| {
thread.request_tool_call_authorization(
arguments.tool_call,
arguments.options,
respect_always_allow_setting,
cx,
)
})??;
let outcome = task.await;
@@ -391,10 +565,24 @@ impl acp::Client for ClientDelegate {
&self,
notification: acp::SessionNotification,
) -> Result<(), acp::Error> {
self.session_thread(&notification.session_id)?
.update(&mut self.cx.clone(), |thread, cx| {
thread.handle_session_update(notification.update, cx)
})??;
let sessions = self.sessions.borrow();
let session = sessions
.get(&notification.session_id)
.context("Failed to get session")?;
if let acp::SessionUpdate::CurrentModeUpdate { current_mode_id } = &notification.update {
if let Some(session_modes) = &session.session_modes {
session_modes.borrow_mut().current_mode_id = current_mode_id.clone();
} else {
log::error!(
"Got a `CurrentModeUpdate` notification, but they agent didn't specify `modes` during setting setup."
);
}
}
session.thread.update(&mut self.cx.clone(), |thread, cx| {
thread.handle_session_update(notification.update, cx)
})??;
Ok(())
}

View File

@@ -2,47 +2,30 @@ mod acp;
mod claude;
mod custom;
mod gemini;
mod settings;
#[cfg(any(test, feature = "test-support"))]
pub mod e2e_tests;
use anyhow::Context as _;
pub use claude::*;
use client::ProxySettings;
use collections::HashMap;
pub use custom::*;
use fs::Fs;
use fs::RemoveOptions;
use fs::RenameOptions;
use futures::StreamExt as _;
pub use gemini::*;
use gpui::AppContext;
use node_runtime::NodeRuntime;
pub use settings::*;
use http_client::read_no_proxy_from_env;
use project::agent_server_store::AgentServerStore;
use acp_thread::AgentConnection;
use acp_thread::LoadError;
use anyhow::Result;
use anyhow::anyhow;
use collections::HashMap;
use gpui::{App, AsyncApp, Entity, SharedString, Task};
use gpui::{App, AppContext, Entity, SharedString, Task};
use project::Project;
use schemars::JsonSchema;
use semver::Version;
use serde::{Deserialize, Serialize};
use std::str::FromStr as _;
use std::{
any::Any,
path::{Path, PathBuf},
rc::Rc,
sync::Arc,
};
use util::ResultExt as _;
use settings::SettingsStore;
use std::{any::Any, path::Path, rc::Rc, sync::Arc};
pub fn init(cx: &mut App) {
settings::init(cx);
}
pub use acp::AcpConnection;
pub struct AgentServerDelegate {
store: Entity<AgentServerStore>,
project: Entity<Project>,
status_tx: Option<watch::Sender<SharedString>>,
new_version_available: Option<watch::Sender<Option<String>>>,
@@ -50,11 +33,13 @@ pub struct AgentServerDelegate {
impl AgentServerDelegate {
pub fn new(
store: Entity<AgentServerStore>,
project: Entity<Project>,
status_tx: Option<watch::Sender<SharedString>>,
new_version_tx: Option<watch::Sender<Option<String>>>,
) -> Self {
Self {
store,
project,
status_tx,
new_version_available: new_version_tx,
@@ -64,201 +49,29 @@ impl AgentServerDelegate {
pub fn project(&self) -> &Entity<Project> {
&self.project
}
fn get_or_npm_install_builtin_agent(
self,
binary_name: SharedString,
package_name: SharedString,
entrypoint_path: PathBuf,
ignore_system_version: bool,
minimum_version: Option<Version>,
cx: &mut App,
) -> Task<Result<AgentServerCommand>> {
let project = self.project;
let fs = project.read(cx).fs().clone();
let Some(node_runtime) = project.read(cx).node_runtime().cloned() else {
return Task::ready(Err(anyhow!(
"External agents are not yet available in remote projects."
)));
};
let status_tx = self.status_tx;
let new_version_available = self.new_version_available;
cx.spawn(async move |cx| {
if !ignore_system_version {
if let Some(bin) = find_bin_in_path(binary_name.clone(), &project, cx).await {
return Ok(AgentServerCommand {
path: bin,
args: Vec::new(),
env: Default::default(),
});
}
}
cx.spawn(async move |cx| {
let node_path = node_runtime.binary_path().await?;
let dir = paths::data_dir()
.join("external_agents")
.join(binary_name.as_str());
fs.create_dir(&dir).await?;
let mut stream = fs.read_dir(&dir).await?;
let mut versions = Vec::new();
let mut to_delete = Vec::new();
while let Some(entry) = stream.next().await {
let Ok(entry) = entry else { continue };
let Some(file_name) = entry.file_name() else {
continue;
};
if let Some(name) = file_name.to_str()
&& let Some(version) = semver::Version::from_str(name).ok()
&& fs
.is_file(&dir.join(file_name).join(&entrypoint_path))
.await
{
versions.push((version, file_name.to_owned()));
} else {
to_delete.push(file_name.to_owned())
}
}
versions.sort();
let newest_version = if let Some((version, file_name)) = versions.last().cloned()
&& minimum_version.is_none_or(|minimum_version| version >= minimum_version)
{
versions.pop();
Some(file_name)
} else {
None
};
log::debug!("existing version of {package_name}: {newest_version:?}");
to_delete.extend(versions.into_iter().map(|(_, file_name)| file_name));
cx.background_spawn({
let fs = fs.clone();
let dir = dir.clone();
async move {
for file_name in to_delete {
fs.remove_dir(
&dir.join(file_name),
RemoveOptions {
recursive: true,
ignore_if_not_exists: false,
},
)
.await
.ok();
}
}
})
.detach();
let version = if let Some(file_name) = newest_version {
cx.background_spawn({
let file_name = file_name.clone();
let dir = dir.clone();
let fs = fs.clone();
async move {
let latest_version =
node_runtime.npm_package_latest_version(&package_name).await;
if let Ok(latest_version) = latest_version
&& &latest_version != &file_name.to_string_lossy()
{
Self::download_latest_version(
fs,
dir.clone(),
node_runtime,
package_name,
)
.await
.log_err();
if let Some(mut new_version_available) = new_version_available {
new_version_available.send(Some(latest_version)).ok();
}
}
}
})
.detach();
file_name
} else {
if let Some(mut status_tx) = status_tx {
status_tx.send("Installing…".into()).ok();
}
let dir = dir.clone();
cx.background_spawn(Self::download_latest_version(
fs.clone(),
dir.clone(),
node_runtime,
package_name,
))
.await?
.into()
};
let agent_server_path = dir.join(version).join(entrypoint_path);
let agent_server_path_exists = fs.is_file(&agent_server_path).await;
anyhow::ensure!(
agent_server_path_exists,
"Missing entrypoint path {} after installation",
agent_server_path.to_string_lossy()
);
anyhow::Ok(AgentServerCommand {
path: node_path,
args: vec![agent_server_path.to_string_lossy().to_string()],
env: Default::default(),
})
})
.await
.map_err(|e| LoadError::FailedToInstall(e.to_string().into()).into())
})
}
async fn download_latest_version(
fs: Arc<dyn Fs>,
dir: PathBuf,
node_runtime: NodeRuntime,
package_name: SharedString,
) -> Result<String> {
log::debug!("downloading latest version of {package_name}");
let tmp_dir = tempfile::tempdir_in(&dir)?;
node_runtime
.npm_install_packages(tmp_dir.path(), &[(&package_name, "latest")])
.await?;
let version = node_runtime
.npm_package_installed_version(tmp_dir.path(), &package_name)
.await?
.context("expected package to be installed")?;
fs.rename(
&tmp_dir.keep(),
&dir.join(&version),
RenameOptions {
ignore_if_exists: true,
overwrite: false,
},
)
.await?;
anyhow::Ok(version)
}
}
pub trait AgentServer: Send {
fn logo(&self) -> ui::IconName;
fn name(&self) -> SharedString;
fn telemetry_id(&self) -> &'static str;
fn default_mode(&self, _cx: &mut App) -> Option<agent_client_protocol::SessionModeId> {
None
}
fn set_default_mode(
&self,
_mode_id: Option<agent_client_protocol::SessionModeId>,
_fs: Arc<dyn Fs>,
_cx: &mut App,
) {
}
fn connect(
&self,
root_dir: &Path,
root_dir: Option<&Path>,
delegate: AgentServerDelegate,
cx: &mut App,
) -> Task<Result<Rc<dyn AgentConnection>>>;
) -> Task<Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>>;
fn into_any(self: Rc<Self>) -> Rc<dyn Any>;
}
@@ -269,119 +82,24 @@ impl dyn AgentServer {
}
}
impl std::fmt::Debug for AgentServerCommand {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let filtered_env = self.env.as_ref().map(|env| {
env.iter()
.map(|(k, v)| {
(
k,
if util::redact::should_redact(k) {
"[REDACTED]"
} else {
v
},
)
})
.collect::<Vec<_>>()
});
/// Load the default proxy environment variables to pass through to the agent
pub fn load_proxy_env(cx: &mut App) -> HashMap<String, String> {
let proxy_url = cx
.read_global(|settings: &SettingsStore, _| settings.get::<ProxySettings>(None).proxy_url());
let mut env = HashMap::default();
f.debug_struct("AgentServerCommand")
.field("path", &self.path)
.field("args", &self.args)
.field("env", &filtered_env)
.finish()
}
}
#[derive(Deserialize, Serialize, Clone, PartialEq, Eq, JsonSchema)]
pub struct AgentServerCommand {
#[serde(rename = "command")]
pub path: PathBuf,
#[serde(default)]
pub args: Vec<String>,
pub env: Option<HashMap<String, String>>,
}
impl AgentServerCommand {
pub async fn resolve(
path_bin_name: &'static str,
extra_args: &[&'static str],
fallback_path: Option<&Path>,
settings: Option<BuiltinAgentServerSettings>,
project: &Entity<Project>,
cx: &mut AsyncApp,
) -> Option<Self> {
if let Some(settings) = settings
&& let Some(command) = settings.custom_command()
{
Some(command)
if let Some(proxy_url) = &proxy_url {
let env_var = if proxy_url.scheme() == "https" {
"HTTPS_PROXY"
} else {
match find_bin_in_path(path_bin_name.into(), project, cx).await {
Some(path) => Some(Self {
path,
args: extra_args.iter().map(|arg| arg.to_string()).collect(),
env: None,
}),
None => fallback_path.and_then(|path| {
if path.exists() {
Some(Self {
path: path.to_path_buf(),
args: extra_args.iter().map(|arg| arg.to_string()).collect(),
env: None,
})
} else {
None
}
}),
}
}
"HTTP_PROXY"
};
env.insert(env_var.to_owned(), proxy_url.to_string());
}
}
async fn find_bin_in_path(
bin_name: SharedString,
project: &Entity<Project>,
cx: &mut AsyncApp,
) -> Option<PathBuf> {
let (env_task, root_dir) = project
.update(cx, |project, cx| {
let worktree = project.visible_worktrees(cx).next();
match worktree {
Some(worktree) => {
let env_task = project.environment().update(cx, |env, cx| {
env.get_worktree_environment(worktree.clone(), cx)
});
let path = worktree.read(cx).abs_path();
(env_task, path)
}
None => {
let path: Arc<Path> = paths::home_dir().as_path().into();
let env_task = project.environment().update(cx, |env, cx| {
env.get_directory_environment(path.clone(), cx)
});
(env_task, path)
}
}
})
.log_err()?;
cx.background_executor()
.spawn(async move {
let which_result = if cfg!(windows) {
which::which(bin_name.as_str())
} else {
let env = env_task.await.unwrap_or_default();
let shell_path = env.get("PATH").cloned();
which::which_in(bin_name.as_str(), shell_path.as_ref(), root_dir.as_ref())
};
if let Err(which::Error::CannotFindBinaryPath) = which_result {
return None;
}
which_result.log_err()
})
.await
if let Some(no_proxy) = read_no_proxy_from_env() {
env.insert("NO_PROXY".to_owned(), no_proxy);
}
env
}

View File

@@ -1,61 +1,26 @@
use language_models::provider::anthropic::AnthropicLanguageModelProvider;
use settings::SettingsStore;
use agent_client_protocol as acp;
use fs::Fs;
use settings::{SettingsStore, update_settings_file};
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use std::{any::Any, path::PathBuf};
use anyhow::Result;
use anyhow::{Context as _, Result};
use gpui::{App, AppContext as _, SharedString, Task};
use project::agent_server_store::{AllAgentServersSettings, CLAUDE_CODE_NAME};
use crate::{AgentServer, AgentServerDelegate, AllAgentServersSettings};
use crate::{AgentServer, AgentServerDelegate, load_proxy_env};
use acp_thread::AgentConnection;
#[derive(Clone)]
pub struct ClaudeCode;
pub struct ClaudeCodeLoginCommand {
pub struct AgentServerLoginCommand {
pub path: PathBuf,
pub arguments: Vec<String>,
}
impl ClaudeCode {
const BINARY_NAME: &'static str = "claude-code-acp";
const PACKAGE_NAME: &'static str = "@zed-industries/claude-code-acp";
pub fn login_command(
delegate: AgentServerDelegate,
cx: &mut App,
) -> Task<Result<ClaudeCodeLoginCommand>> {
let settings = cx.read_global(|settings: &SettingsStore, _| {
settings.get::<AllAgentServersSettings>(None).claude.clone()
});
cx.spawn(async move |cx| {
let mut command = if let Some(settings) = settings {
settings.command
} else {
cx.update(|cx| {
delegate.get_or_npm_install_builtin_agent(
Self::BINARY_NAME.into(),
Self::PACKAGE_NAME.into(),
"node_modules/@anthropic-ai/claude-code/cli.js".into(),
true,
Some("0.2.5".parse().unwrap()),
cx,
)
})?
.await?
};
command.args.push("/login".into());
Ok(ClaudeCodeLoginCommand {
path: command.path,
arguments: command.args,
})
})
}
}
impl AgentServer for ClaudeCode {
fn telemetry_id(&self) -> &'static str {
"claude-code"
@@ -69,55 +34,60 @@ impl AgentServer for ClaudeCode {
ui::IconName::AiClaude
}
fn connect(
&self,
root_dir: &Path,
delegate: AgentServerDelegate,
cx: &mut App,
) -> Task<Result<Rc<dyn AgentConnection>>> {
let root_dir = root_dir.to_path_buf();
let fs = delegate.project().read(cx).fs().clone();
let server_name = self.name();
fn default_mode(&self, cx: &mut App) -> Option<acp::SessionModeId> {
let settings = cx.read_global(|settings: &SettingsStore, _| {
settings.get::<AllAgentServersSettings>(None).claude.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::<AllAgentServersSettings>(fs, cx, |settings, _| {
settings.claude.get_or_insert_default().default_mode = mode_id.map(|m| m.to_string())
});
}
fn connect(
&self,
root_dir: Option<&Path>,
delegate: AgentServerDelegate,
cx: &mut App,
) -> Task<Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
let name = self.name();
let root_dir = root_dir.map(|root_dir| root_dir.to_string_lossy().to_string());
let is_remote = delegate.project.read(cx).is_via_remote_server();
let store = delegate.store.downgrade();
let extra_env = load_proxy_env(cx);
let default_mode = self.default_mode(cx);
cx.spawn(async move |cx| {
let mut command = if let Some(settings) = settings {
settings.command
} else {
cx.update(|cx| {
delegate.get_or_npm_install_builtin_agent(
Self::BINARY_NAME.into(),
Self::PACKAGE_NAME.into(),
format!("node_modules/{}/dist/index.js", Self::PACKAGE_NAME).into(),
true,
None,
cx,
)
})?
.await?
};
if let Some(api_key) = cx
.update(AnthropicLanguageModelProvider::api_key)?
.await
.ok()
{
command
.env
.get_or_insert_default()
.insert("ANTHROPIC_API_KEY".to_owned(), api_key.key);
}
let root_dir_exists = fs.is_dir(&root_dir).await;
anyhow::ensure!(
root_dir_exists,
"Session root {} does not exist or is not a directory",
root_dir.to_string_lossy()
);
crate::acp::connect(server_name, command.clone(), &root_dir, cx).await
let (command, root_dir, login) = store
.update(cx, |store, cx| {
let agent = store
.get_external_agent(&CLAUDE_CODE_NAME.into())
.context("Claude Code is not registered")?;
anyhow::Ok(agent.get_command(
root_dir.as_deref(),
extra_env,
delegate.status_tx,
delegate.new_version_available,
&mut cx.to_async(),
))
})??
.await?;
let connection = crate::acp::connect(
name,
command,
root_dir.as_ref(),
default_mode,
is_remote,
cx,
)
.await?;
Ok((connection, login))
})
}

View File

@@ -1,19 +1,22 @@
use crate::{AgentServerCommand, AgentServerDelegate};
use crate::{AgentServerDelegate, load_proxy_env};
use acp_thread::AgentConnection;
use anyhow::Result;
use gpui::{App, SharedString, Task};
use std::{path::Path, rc::Rc};
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, ExternalAgentServerName};
use settings::{SettingsStore, update_settings_file};
use std::{path::Path, rc::Rc, sync::Arc};
use ui::IconName;
/// A generic agent server implementation for custom user-defined agents
pub struct CustomAgentServer {
name: SharedString,
command: AgentServerCommand,
}
impl CustomAgentServer {
pub fn new(name: SharedString, command: AgentServerCommand) -> Self {
Self { name, command }
pub fn new(name: SharedString) -> Self {
Self { name }
}
}
@@ -30,16 +33,68 @@ impl crate::AgentServer for CustomAgentServer {
IconName::Terminal
}
fn default_mode(&self, cx: &mut App) -> Option<acp::SessionModeId> {
let settings = cx.read_global(|settings: &SettingsStore, _| {
settings
.get::<AllAgentServersSettings>(None)
.custom
.get(&self.name())
.cloned()
});
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) {
let name = self.name();
update_settings_file::<AllAgentServersSettings>(fs, cx, move |settings, _| {
settings.custom.get_mut(&name).unwrap().default_mode = mode_id.map(|m| m.to_string())
});
}
fn connect(
&self,
root_dir: &Path,
_delegate: AgentServerDelegate,
root_dir: Option<&Path>,
delegate: AgentServerDelegate,
cx: &mut App,
) -> Task<Result<Rc<dyn AgentConnection>>> {
let server_name = self.name();
let command = self.command.clone();
let root_dir = root_dir.to_path_buf();
cx.spawn(async move |cx| crate::acp::connect(server_name, command, &root_dir, cx).await)
) -> Task<Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
let name = self.name();
let root_dir = root_dir.map(|root_dir| root_dir.to_string_lossy().to_string());
let is_remote = delegate.project.read(cx).is_via_remote_server();
let default_mode = self.default_mode(cx);
let store = delegate.store.downgrade();
let extra_env = load_proxy_env(cx);
cx.spawn(async move |cx| {
let (command, root_dir, login) = store
.update(cx, |store, cx| {
let agent = store
.get_external_agent(&ExternalAgentServerName(name.clone()))
.with_context(|| {
format!("Custom agent server `{}` is not registered", name)
})?;
anyhow::Ok(agent.get_command(
root_dir.as_deref(),
extra_env,
delegate.status_tx,
delegate.new_version_available,
&mut cx.to_async(),
))
})??
.await?;
let connection = crate::acp::connect(
name,
command,
root_dir.as_ref(),
default_mode,
is_remote,
cx,
)
.await?;
Ok((connection, login))
})
}
fn into_any(self: Rc<Self>) -> Rc<dyn std::any::Any> {

View File

@@ -1,12 +1,12 @@
use crate::{AgentServer, AgentServerDelegate};
#[cfg(test)]
use crate::{AgentServerCommand, CustomAgentServerSettings};
use acp_thread::{AcpThread, AgentThreadEntry, ToolCall, ToolCallStatus};
use agent_client_protocol as acp;
use futures::{FutureExt, StreamExt, channel::mpsc, select};
use gpui::{AppContext, Entity, TestAppContext};
use indoc::indoc;
use project::{FakeFs, Project};
#[cfg(test)]
use project::agent_server_store::BuiltinAgentServerSettings;
use project::{FakeFs, Project, agent_server_store::AllAgentServersSettings};
use std::{
path::{Path, PathBuf},
sync::Arc,
@@ -449,7 +449,6 @@ pub use common_e2e_tests;
// Helpers
pub async fn init_test(cx: &mut TestAppContext) -> Arc<FakeFs> {
#[cfg(test)]
use settings::Settings;
env_logger::try_init().ok();
@@ -468,17 +467,17 @@ pub async fn init_test(cx: &mut TestAppContext) -> Arc<FakeFs> {
language_model::init(client.clone(), cx);
language_models::init(user_store, client, cx);
agent_settings::init(cx);
crate::settings::init(cx);
AllAgentServersSettings::register(cx);
#[cfg(test)]
crate::AllAgentServersSettings::override_global(
crate::AllAgentServersSettings {
claude: Some(CustomAgentServerSettings {
command: AgentServerCommand {
path: "claude-code-acp".into(),
args: vec![],
env: None,
},
AllAgentServersSettings::override_global(
AllAgentServersSettings {
claude: Some(BuiltinAgentServerSettings {
path: Some("claude-code-acp".into()),
args: None,
env: None,
ignore_system_version: None,
default_mode: None,
}),
gemini: Some(crate::gemini::tests::local_command().into()),
custom: collections::HashMap::default(),
@@ -498,10 +497,11 @@ pub async fn new_test_thread(
current_dir: impl AsRef<Path>,
cx: &mut TestAppContext,
) -> Entity<AcpThread> {
let delegate = AgentServerDelegate::new(project.clone(), None, None);
let store = project.read_with(cx, |project, _| project.agent_server_store().clone());
let delegate = AgentServerDelegate::new(store, project.clone(), None, None);
let connection = cx
.update(|cx| server.connect(current_dir.as_ref(), delegate, cx))
let (connection, _) = cx
.update(|cx| server.connect(Some(current_dir.as_ref()), delegate, cx))
.await
.unwrap();

View File

@@ -1,21 +1,16 @@
use std::rc::Rc;
use std::{any::Any, path::Path};
use crate::acp::AcpConnection;
use crate::{AgentServer, AgentServerDelegate};
use acp_thread::{AgentConnection, LoadError};
use anyhow::Result;
use gpui::{App, AppContext as _, SharedString, Task};
use crate::{AgentServer, AgentServerDelegate, load_proxy_env};
use acp_thread::AgentConnection;
use anyhow::{Context as _, Result};
use gpui::{App, SharedString, Task};
use language_models::provider::google::GoogleLanguageModelProvider;
use settings::SettingsStore;
use crate::AllAgentServersSettings;
use project::agent_server_store::GEMINI_NAME;
#[derive(Clone)]
pub struct Gemini;
const ACP_ARG: &str = "--experimental-acp";
impl AgentServer for Gemini {
fn telemetry_id(&self) -> &'static str {
"gemini-cli"
@@ -31,120 +26,47 @@ impl AgentServer for Gemini {
fn connect(
&self,
root_dir: &Path,
root_dir: Option<&Path>,
delegate: AgentServerDelegate,
cx: &mut App,
) -> Task<Result<Rc<dyn AgentConnection>>> {
let root_dir = root_dir.to_path_buf();
let fs = delegate.project().read(cx).fs().clone();
let server_name = self.name();
let settings = cx.read_global(|settings: &SettingsStore, _| {
settings.get::<AllAgentServersSettings>(None).gemini.clone()
});
) -> Task<Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
let name = self.name();
let root_dir = root_dir.map(|root_dir| root_dir.to_string_lossy().to_string());
let is_remote = delegate.project.read(cx).is_via_remote_server();
let store = delegate.store.downgrade();
let mut extra_env = load_proxy_env(cx);
let default_mode = self.default_mode(cx);
cx.spawn(async move |cx| {
let ignore_system_version = settings
.as_ref()
.and_then(|settings| settings.ignore_system_version)
.unwrap_or(true);
let mut command = if let Some(settings) = settings
&& let Some(command) = settings.custom_command()
{
command
} else {
cx.update(|cx| {
delegate.get_or_npm_install_builtin_agent(
Self::BINARY_NAME.into(),
Self::PACKAGE_NAME.into(),
format!("node_modules/{}/dist/index.js", Self::PACKAGE_NAME).into(),
ignore_system_version,
Some(Self::MINIMUM_VERSION.parse().unwrap()),
cx,
)
})?
.await?
};
if !command.args.contains(&ACP_ARG.into()) {
command.args.push(ACP_ARG.into());
}
extra_env.insert("SURFACE".to_owned(), "zed".to_owned());
if let Some(api_key) = cx.update(GoogleLanguageModelProvider::api_key)?.await.ok() {
command
.env
.get_or_insert_default()
.insert("GEMINI_API_KEY".to_owned(), api_key.key);
extra_env.insert("GEMINI_API_KEY".into(), api_key.key);
}
let (command, root_dir, login) = store
.update(cx, |store, cx| {
let agent = store
.get_external_agent(&GEMINI_NAME.into())
.context("Gemini CLI is not registered")?;
anyhow::Ok(agent.get_command(
root_dir.as_deref(),
extra_env,
delegate.status_tx,
delegate.new_version_available,
&mut cx.to_async(),
))
})??
.await?;
let root_dir_exists = fs.is_dir(&root_dir).await;
anyhow::ensure!(
root_dir_exists,
"Session root {} does not exist or is not a directory",
root_dir.to_string_lossy()
);
let result = crate::acp::connect(server_name, command.clone(), &root_dir, cx).await;
match &result {
Ok(connection) => {
if let Some(connection) = connection.clone().downcast::<AcpConnection>()
&& !connection.prompt_capabilities().image
{
let version_output = util::command::new_smol_command(&command.path)
.args(command.args.iter())
.arg("--version")
.kill_on_drop(true)
.output()
.await;
let current_version =
String::from_utf8(version_output?.stdout)?.trim().to_owned();
log::error!("connected to gemini, but missing prompt_capabilities.image (version is {current_version})");
return Err(LoadError::Unsupported {
current_version: current_version.into(),
command: (command.path.to_string_lossy().to_string() + " " + &command.args.join(" ")).into(),
minimum_version: Self::MINIMUM_VERSION.into(),
}
.into());
}
}
Err(e) => {
let version_fut = util::command::new_smol_command(&command.path)
.args(command.args.iter())
.arg("--version")
.kill_on_drop(true)
.output();
let help_fut = util::command::new_smol_command(&command.path)
.args(command.args.iter())
.arg("--help")
.kill_on_drop(true)
.output();
let (version_output, help_output) =
futures::future::join(version_fut, help_fut).await;
let Some(version_output) = version_output.ok().and_then(|output| String::from_utf8(output.stdout).ok()) else {
return result;
};
let Some((help_stdout, help_stderr)) = help_output.ok().and_then(|output| String::from_utf8(output.stdout).ok().zip(String::from_utf8(output.stderr).ok())) else {
return result;
};
let current_version = version_output.trim().to_string();
let supported = help_stdout.contains(ACP_ARG) || current_version.parse::<semver::Version>().is_ok_and(|version| version >= Self::MINIMUM_VERSION.parse::<semver::Version>().unwrap());
log::error!("failed to create ACP connection to gemini (version is {current_version}, supported: {supported}): {e}");
log::debug!("gemini --help stdout: {help_stdout:?}");
log::debug!("gemini --help stderr: {help_stderr:?}");
if !supported {
return Err(LoadError::Unsupported {
current_version: current_version.into(),
command: (command.path.to_string_lossy().to_string() + " " + &command.args.join(" ")).into(),
minimum_version: Self::MINIMUM_VERSION.into(),
}
.into());
}
}
}
result
let connection = crate::acp::connect(
name,
command,
root_dir.as_ref(),
default_mode,
is_remote,
cx,
)
.await?;
Ok((connection, login))
})
}
@@ -153,18 +75,11 @@ impl AgentServer for Gemini {
}
}
impl Gemini {
const PACKAGE_NAME: &str = "@google/gemini-cli";
const MINIMUM_VERSION: &str = "0.2.1";
const BINARY_NAME: &str = "gemini";
}
#[cfg(test)]
pub(crate) mod tests {
use project::agent_server_store::AgentServerCommand;
use super::*;
use crate::AgentServerCommand;
use std::path::Path;
crate::common_e2e_tests!(async |_, _, _| Gemini, allow_option_id = "proceed_once");

View File

@@ -1,3 +1,4 @@
use agent_client_protocol as acp;
use std::path::PathBuf;
use crate::AgentServerCommand;
@@ -6,16 +7,17 @@ use collections::HashMap;
use gpui::{App, SharedString};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsSources, SettingsUi};
use settings::{Settings, SettingsKey, SettingsSources, SettingsUi};
pub fn init(cx: &mut App) {
AllAgentServersSettings::register(cx);
}
#[derive(Default, Deserialize, Serialize, Clone, JsonSchema, Debug, SettingsUi)]
#[derive(Default, Deserialize, Serialize, Clone, JsonSchema, Debug, SettingsUi, SettingsKey)]
#[settings_key(key = "agent_servers")]
pub struct AllAgentServersSettings {
pub gemini: Option<BuiltinAgentServerSettings>,
pub claude: Option<CustomAgentServerSettings>,
pub claude: Option<BuiltinAgentServerSettings>,
/// Custom agent servers configured by the user
#[serde(flatten)]
@@ -45,6 +47,13 @@ pub struct BuiltinAgentServerSettings {
///
/// Default: true
pub ignore_system_version: Option<bool>,
/// The default mode for new threads.
///
/// Note: Not all agents support modes.
///
/// Default: None
#[serde(skip_serializing_if = "Option::is_none")]
pub default_mode: Option<acp::SessionModeId>,
}
impl BuiltinAgentServerSettings {
@@ -72,11 +81,16 @@ impl From<AgentServerCommand> for BuiltinAgentServerSettings {
pub struct CustomAgentServerSettings {
#[serde(flatten)]
pub command: AgentServerCommand,
/// The default mode for new threads.
///
/// Note: Not all agents support modes.
///
/// Default: None
#[serde(skip_serializing_if = "Option::is_none")]
pub default_mode: Option<acp::SessionModeId>,
}
impl settings::Settings for AllAgentServersSettings {
const KEY: Option<&'static str> = Some("agent_servers");
type FileContent = Self;
fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {

View File

@@ -8,7 +8,7 @@ use gpui::{App, Pixels, SharedString};
use language_model::LanguageModel;
use schemars::{JsonSchema, json_schema};
use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsSources, SettingsUi};
use settings::{Settings, SettingsKey, SettingsSources, SettingsUi};
use std::borrow::Cow;
pub use crate::agent_profile::*;
@@ -223,7 +223,8 @@ impl AgentSettingsContent {
}
}
#[derive(Clone, Serialize, Deserialize, JsonSchema, Debug, Default, SettingsUi)]
#[derive(Clone, Serialize, Deserialize, JsonSchema, Debug, Default, SettingsUi, SettingsKey)]
#[settings_key(key = "agent", fallback_key = "assistant")]
pub struct AgentSettingsContent {
/// Whether the Agent is enabled.
///
@@ -268,6 +269,10 @@ pub struct AgentSettingsContent {
/// Whenever a tool action would normally wait for your confirmation
/// that you allow it, always choose to allow it.
///
/// This setting has no effect on external agents that support permission modes, such as Claude Code.
///
/// Set `agent_servers.claude.default_mode` to `bypassPermissions`, to disable all permission requests when using Claude Code.
///
/// Default: false
always_allow_tool_actions: Option<bool>,
/// Where to show a popup notification when the agent is waiting for user input.
@@ -399,10 +404,6 @@ pub struct ContextServerPresetContent {
}
impl Settings for AgentSettings {
const KEY: Option<&'static str> = Some("agent");
const FALLBACK_KEY: Option<&'static str> = Some("assistant");
const PRESERVED_KEYS: Option<&'static [&'static str]> = Some(&["version"]);
type FileContent = AgentSettingsContent;

View File

@@ -25,6 +25,7 @@ agent_servers.workspace = true
agent_settings.workspace = true
ai_onboarding.workspace = true
anyhow.workspace = true
arrayvec.workspace = true
assistant_context.workspace = true
assistant_slash_command.workspace = true
assistant_slash_commands.workspace = true

View File

@@ -1,11 +1,13 @@
mod completion_provider;
mod entry_view_state;
mod message_editor;
mod mode_selector;
mod model_selector;
mod model_selector_popover;
mod thread_history;
mod thread_view;
pub use mode_selector::ModeSelector;
pub use model_selector::AcpModelSelector;
pub use model_selector_popover::AcpModelSelectorPopover;
pub use thread_history::*;

View File

@@ -1025,43 +1025,31 @@ impl SlashCommandCompletion {
return None;
}
let last_command_start = line.rfind('/')?;
if last_command_start >= line.len() {
return Some(Self::default());
}
if last_command_start > 0
&& line
.chars()
.nth(last_command_start - 1)
.is_some_and(|c| !c.is_whitespace())
let (prefix, last_command) = line.rsplit_once('/')?;
if prefix.chars().last().is_some_and(|c| !c.is_whitespace())
|| last_command.starts_with(char::is_whitespace)
{
return None;
}
let rest_of_line = &line[last_command_start + 1..];
let mut command = None;
let mut argument = None;
let mut end = last_command_start + 1;
if let Some(command_text) = rest_of_line.split_whitespace().next() {
command = Some(command_text.to_string());
end += command_text.len();
// Find the start of arguments after the command
if let Some(args_start) =
rest_of_line[command_text.len()..].find(|c: char| !c.is_whitespace())
{
let args = &rest_of_line[command_text.len() + args_start..].trim_end();
if !args.is_empty() {
argument = Some(args.to_string());
end += args.len() + 1;
}
let mut command = None;
if let Some((command_text, args)) = last_command.split_once(char::is_whitespace) {
if !args.is_empty() {
argument = Some(args.trim_end().to_string());
}
}
command = Some(command_text.to_string());
} else if !last_command.is_empty() {
command = Some(last_command.to_string());
};
Some(Self {
source_range: last_command_start + offset_to_line..end + offset_to_line,
source_range: prefix.len() + offset_to_line
..line
.rfind(|c: char| !c.is_whitespace())
.unwrap_or_else(|| line.len())
+ 1
+ offset_to_line,
command,
argument,
})
@@ -1078,13 +1066,21 @@ struct MentionCompletion {
impl MentionCompletion {
fn try_parse(allow_non_file_mentions: bool, line: &str, offset_to_line: usize) -> Option<Self> {
let last_mention_start = line.rfind('@')?;
if last_mention_start >= line.len() {
return Some(Self::default());
// No whitespace immediately after '@'
if line[last_mention_start + 1..]
.chars()
.next()
.is_some_and(|c| c.is_whitespace())
{
return None;
}
// Must be a word boundary before '@'
if last_mention_start > 0
&& line
&& line[..last_mention_start]
.chars()
.nth(last_mention_start - 1)
.last()
.is_some_and(|c| !c.is_whitespace())
{
return None;
@@ -1097,7 +1093,9 @@ impl MentionCompletion {
let mut parts = rest_of_line.split_whitespace();
let mut end = last_mention_start + 1;
if let Some(mode_text) = parts.next() {
// Safe since we check no leading whitespace above
end += mode_text.len();
if let Some(parsed_mode) = ContextPickerMode::try_from(mode_text).ok()
@@ -1180,6 +1178,15 @@ mod tests {
})
);
assert_eq!(
SlashCommandCompletion::try_parse("/拿不到命令 拿不到命令 ", 0),
Some(SlashCommandCompletion {
source_range: 0..30,
command: Some("拿不到命令".to_string()),
argument: Some("拿不到命令".to_string()),
})
);
assert_eq!(SlashCommandCompletion::try_parse("Lorem Ipsum", 0), None);
assert_eq!(SlashCommandCompletion::try_parse("Lorem /", 0), None);
@@ -1187,6 +1194,8 @@ mod tests {
assert_eq!(SlashCommandCompletion::try_parse("Lorem /help", 0), None);
assert_eq!(SlashCommandCompletion::try_parse("Lorem/", 0), None);
assert_eq!(SlashCommandCompletion::try_parse("/ ", 0), None);
}
#[test]
@@ -1279,5 +1288,23 @@ mod tests {
argument: Some("main".to_string()),
})
);
assert_eq!(
MentionCompletion::try_parse(true, "Lorem@symbol", 0),
None,
"Should not parse mention inside word"
);
assert_eq!(
MentionCompletion::try_parse(true, "Lorem @ file", 0),
None,
"Should not parse with a space after @"
);
assert_eq!(
MentionCompletion::try_parse(true, "@ file", 0),
None,
"Should not parse with a space after @ at the start of the line"
);
}
}

View File

@@ -207,7 +207,7 @@ impl EntryViewState {
self.entries.drain(range);
}
pub fn settings_changed(&mut self, cx: &mut App) {
pub fn agent_font_size_changed(&mut self, cx: &mut App) {
for entry in self.entries.iter() {
match entry {
Entry::UserMessage { .. } | Entry::AssistantMessage { .. } => {}

View File

@@ -493,14 +493,13 @@ impl MessageEditor {
let Some(entry) = self.project.read(cx).entry_for_path(&project_path, cx) else {
return Task::ready(Err(anyhow!("project entry not found")));
};
let Some(worktree) = self.project.read(cx).worktree_for_entry(entry.id, cx) else {
let directory_path = entry.path.clone();
let worktree_id = project_path.worktree_id;
let Some(worktree) = self.project.read(cx).worktree_for_id(worktree_id, cx) else {
return Task::ready(Err(anyhow!("worktree not found")));
};
let project = self.project.clone();
cx.spawn(async move |_, cx| {
let directory_path = entry.path.clone();
let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id())?;
let file_paths = worktree.read_with(cx, |worktree, _cx| {
collect_files_in_path(worktree, &directory_path)
})?;
@@ -700,10 +699,15 @@ impl MessageEditor {
self.project.read(cx).fs().clone(),
self.history_store.clone(),
));
let delegate = AgentServerDelegate::new(self.project.clone(), None, None);
let connection = server.connect(Path::new(""), delegate, cx);
let delegate = AgentServerDelegate::new(
self.project.read(cx).agent_server_store().clone(),
self.project.clone(),
None,
None,
);
let connection = server.connect(None, delegate, cx);
cx.spawn(async move |_, cx| {
let agent = connection.await?;
let (agent, _) = connection.await?;
let agent = agent.downcast::<agent2::NativeAgentConnection>().unwrap();
let summary = agent
.0

View File

@@ -0,0 +1,230 @@
use acp_thread::AgentSessionModes;
use agent_client_protocol as acp;
use agent_servers::AgentServer;
use fs::Fs;
use gpui::{Context, Entity, FocusHandle, WeakEntity, Window, prelude::*};
use std::{rc::Rc, sync::Arc};
use ui::{
Button, ContextMenu, ContextMenuEntry, KeyBinding, PopoverMenu, PopoverMenuHandle, Tooltip,
prelude::*,
};
use crate::{CycleModeSelector, ToggleProfileSelector};
pub struct ModeSelector {
connection: Rc<dyn AgentSessionModes>,
agent_server: Rc<dyn AgentServer>,
menu_handle: PopoverMenuHandle<ContextMenu>,
focus_handle: FocusHandle,
fs: Arc<dyn Fs>,
setting_mode: bool,
}
impl ModeSelector {
pub fn new(
session_modes: Rc<dyn AgentSessionModes>,
agent_server: Rc<dyn AgentServer>,
fs: Arc<dyn Fs>,
focus_handle: FocusHandle,
) -> Self {
Self {
connection: session_modes,
agent_server,
menu_handle: PopoverMenuHandle::default(),
fs,
setting_mode: false,
focus_handle,
}
}
pub fn menu_handle(&self) -> PopoverMenuHandle<ContextMenu> {
self.menu_handle.clone()
}
pub fn cycle_mode(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
let all_modes = self.connection.all_modes();
let current_mode = self.connection.current_mode();
let current_index = all_modes
.iter()
.position(|mode| mode.id.0 == current_mode.0)
.unwrap_or(0);
let next_index = (current_index + 1) % all_modes.len();
self.set_mode(all_modes[next_index].id.clone(), cx);
}
pub fn set_mode(&mut self, mode: acp::SessionModeId, cx: &mut Context<Self>) {
let task = self.connection.set_mode(mode, cx);
self.setting_mode = true;
cx.notify();
cx.spawn(async move |this: WeakEntity<ModeSelector>, cx| {
if let Err(err) = task.await {
log::error!("Failed to set session mode: {:?}", err);
}
this.update(cx, |this, cx| {
this.setting_mode = false;
cx.notify();
})
.ok();
})
.detach();
}
fn build_context_menu(
&self,
window: &mut Window,
cx: &mut Context<Self>,
) -> Entity<ContextMenu> {
let weak_self = cx.weak_entity();
ContextMenu::build(window, cx, move |mut menu, _window, cx| {
let all_modes = self.connection.all_modes();
let current_mode = self.connection.current_mode();
let default_mode = self.agent_server.default_mode(cx);
for mode in all_modes {
let is_selected = &mode.id == &current_mode;
let is_default = Some(&mode.id) == default_mode.as_ref();
let entry = ContextMenuEntry::new(mode.name.clone())
.toggleable(IconPosition::End, is_selected);
let entry = if let Some(description) = &mode.description {
entry.documentation_aside(ui::DocumentationSide::Left, {
let description = description.clone();
move |cx| {
v_flex()
.gap_1()
.child(Label::new(description.clone()))
.child(
h_flex()
.pt_1()
.border_t_1()
.border_color(cx.theme().colors().border_variant)
.gap_0p5()
.text_sm()
.text_color(Color::Muted.color(cx))
.child("Hold")
.child(div().pt_0p5().children(ui::render_modifiers(
&gpui::Modifiers::secondary_key(),
PlatformStyle::platform(),
None,
Some(ui::TextSize::Default.rems(cx).into()),
true,
)))
.child(div().map(|this| {
if is_default {
this.child("to also unset as default")
} else {
this.child("to also set as default")
}
})),
)
.into_any_element()
}
})
} else {
entry
};
menu.push_item(entry.handler({
let mode_id = mode.id.clone();
let weak_self = weak_self.clone();
move |window, cx| {
weak_self
.update(cx, |this, cx| {
if window.modifiers().secondary() {
this.agent_server.set_default_mode(
if is_default {
None
} else {
Some(mode_id.clone())
},
this.fs.clone(),
cx,
);
}
this.set_mode(mode_id.clone(), cx);
})
.ok();
}
}));
}
menu.key_context("ModeSelector")
})
}
}
impl Render for ModeSelector {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let current_mode_id = self.connection.current_mode();
let current_mode_name = self
.connection
.all_modes()
.iter()
.find(|mode| mode.id == current_mode_id)
.map(|mode| mode.name.clone())
.unwrap_or_else(|| "Unknown".into());
let this = cx.entity();
let trigger_button = Button::new("mode-selector-trigger", current_mode_name)
.label_size(LabelSize::Small)
.style(ButtonStyle::Subtle)
.color(Color::Muted)
.icon(IconName::ChevronDown)
.icon_size(IconSize::XSmall)
.icon_position(IconPosition::End)
.icon_color(Color::Muted)
.disabled(self.setting_mode);
PopoverMenu::new("mode-selector")
.trigger_with_tooltip(
trigger_button,
Tooltip::element({
let focus_handle = self.focus_handle.clone();
move |window, cx| {
v_flex()
.gap_1()
.child(
h_flex()
.pb_1()
.gap_2()
.justify_between()
.border_b_1()
.border_color(cx.theme().colors().border_variant)
.child(Label::new("Cycle Through Modes"))
.children(KeyBinding::for_action_in(
&CycleModeSelector,
&focus_handle,
window,
cx,
)),
)
.child(
h_flex()
.gap_2()
.justify_between()
.child(Label::new("Toggle Mode Menu"))
.children(KeyBinding::for_action_in(
&ToggleProfileSelector,
&focus_handle,
window,
cx,
)),
)
.into_any()
}
}),
)
.anchor(gpui::Corner::BottomRight)
.with_handle(self.menu_handle.clone())
.menu(move |window, cx| {
Some(this.update(cx, |this, cx| this.build_context_menu(window, cx)))
})
}
}

View File

@@ -192,8 +192,10 @@ impl PickerDelegate for AcpModelPickerDelegate {
}
}
fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
cx.emit(DismissEvent);
fn dismissed(&mut self, window: &mut Window, cx: &mut Context<Picker<Self>>) {
cx.defer_in(window, |picker, window, cx| {
picker.set_query("", window, cx);
});
}
fn render_match(

View File

@@ -5,7 +5,8 @@ use agent_client_protocol as acp;
use gpui::{Entity, FocusHandle};
use picker::popover_menu::PickerPopoverMenu;
use ui::{
ButtonLike, Context, IntoElement, PopoverMenuHandle, SharedString, Tooltip, Window, prelude::*,
ButtonLike, Context, IntoElement, PopoverMenuHandle, SharedString, TintColor, Tooltip, Window,
prelude::*,
};
use zed_actions::agent::ToggleModelSelector;
@@ -58,15 +59,22 @@ impl Render for AcpModelSelectorPopover {
let focus_handle = self.focus_handle.clone();
let color = if self.menu_handle.is_deployed() {
Color::Accent
} else {
Color::Muted
};
PickerPopoverMenu::new(
self.selector.clone(),
ButtonLike::new("active-model")
.when_some(model_icon, |this, icon| {
this.child(Icon::new(icon).color(Color::Muted).size(IconSize::XSmall))
this.child(Icon::new(icon).color(color).size(IconSize::XSmall))
})
.selected_style(ButtonStyle::Tinted(TintColor::Accent))
.child(
Label::new(model_name)
.color(Color::Muted)
.color(color)
.size(LabelSize::Small)
.ml_0p5(),
)

File diff suppressed because it is too large Load Diff

View File

@@ -3585,7 +3585,7 @@ pub(crate) fn open_active_thread_as_markdown(
}
let buffer = project.update(cx, |project, cx| {
project.create_local_buffer(&markdown, Some(markdown_language), cx)
project.create_local_buffer(&markdown, Some(markdown_language), true, cx)
});
let buffer =
cx.new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone()));

View File

@@ -5,7 +5,6 @@ mod tool_picker;
use std::{ops::Range, sync::Arc};
use agent_servers::{AgentServerCommand, AllAgentServersSettings, CustomAgentServerSettings};
use agent_settings::AgentSettings;
use anyhow::Result;
use assistant_tool::{ToolSource, ToolWorkingSet};
@@ -26,6 +25,10 @@ use language_model::{
};
use notifications::status_toast::{StatusToast, ToastIcon};
use project::{
agent_server_store::{
AgentServerCommand, AgentServerStore, AllAgentServersSettings, CLAUDE_CODE_NAME,
CustomAgentServerSettings, GEMINI_NAME,
},
context_server_store::{ContextServerConfiguration, ContextServerStatus, ContextServerStore},
project_settings::{ContextServerSettings, ProjectSettings},
};
@@ -45,11 +48,13 @@ pub(crate) use manage_profiles_modal::ManageProfilesModal;
use crate::{
AddContextServer, ExternalAgent, NewExternalAgentThread,
agent_configuration::add_llm_provider_modal::{AddLlmProviderModal, LlmCompatibleProvider},
placeholder_command,
};
pub struct AgentConfiguration {
fs: Arc<dyn Fs>,
language_registry: Arc<LanguageRegistry>,
agent_server_store: Entity<AgentServerStore>,
workspace: WeakEntity<Workspace>,
focus_handle: FocusHandle,
configuration_views_by_provider: HashMap<LanguageModelProviderId, AnyView>,
@@ -66,6 +71,7 @@ pub struct AgentConfiguration {
impl AgentConfiguration {
pub fn new(
fs: Arc<dyn Fs>,
agent_server_store: Entity<AgentServerStore>,
context_server_store: Entity<ContextServerStore>,
tools: Entity<ToolWorkingSet>,
language_registry: Arc<LanguageRegistry>,
@@ -104,6 +110,7 @@ impl AgentConfiguration {
workspace,
focus_handle,
configuration_views_by_provider: HashMap::default(),
agent_server_store,
context_server_store,
expanded_context_server_tools: HashMap::default(),
expanded_provider_configurations: HashMap::default(),
@@ -508,9 +515,11 @@ impl AgentConfiguration {
.blend(cx.theme().colors().text_accent.opacity(0.2));
let (plan_name, label_color, bg_color) = match plan {
Plan::ZedFree => ("Free", Color::Default, free_chip_bg),
Plan::ZedProTrial => ("Pro Trial", Color::Accent, pro_chip_bg),
Plan::ZedPro => ("Pro", Color::Accent, pro_chip_bg),
Plan::ZedFree | Plan::ZedFreeV2 => ("Free", Color::Default, free_chip_bg),
Plan::ZedProTrial | Plan::ZedProTrialV2 => {
("Pro Trial", Color::Accent, pro_chip_bg)
}
Plan::ZedPro | Plan::ZedProV2 => ("Pro", Color::Accent, pro_chip_bg),
};
Chip::new(plan_name.to_string())
@@ -991,17 +1000,30 @@ impl AgentConfiguration {
}
fn render_agent_servers_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
let settings = AllAgentServersSettings::get_global(cx).clone();
let user_defined_agents = settings
let custom_settings = cx
.global::<SettingsStore>()
.get::<AllAgentServersSettings>(None)
.custom
.iter()
.map(|(name, settings)| {
.clone();
let user_defined_agents = self
.agent_server_store
.read(cx)
.external_agents()
.filter(|name| name.0 != GEMINI_NAME && name.0 != CLAUDE_CODE_NAME)
.cloned()
.collect::<Vec<_>>();
let user_defined_agents = user_defined_agents
.into_iter()
.map(|name| {
self.render_agent_server(
IconName::Ai,
name.clone(),
ExternalAgent::Custom {
name: name.clone(),
command: settings.command.clone(),
name: name.clone().into(),
command: custom_settings
.get(&name.0)
.map(|settings| settings.command.clone())
.unwrap_or(placeholder_command()),
},
cx,
)
@@ -1300,6 +1322,7 @@ async fn open_new_agent_servers_entry_in_settings_editor(
args: vec![],
env: Some(HashMap::default()),
},
default_mode: None,
},
);
}

View File

@@ -251,6 +251,7 @@ pub struct ConfigureContextServerModal {
workspace: WeakEntity<Workspace>,
source: ConfigurationSource,
state: State,
original_server_id: Option<ContextServerId>,
}
impl ConfigureContextServerModal {
@@ -348,6 +349,11 @@ impl ConfigureContextServerModal {
context_server_store,
workspace: workspace_handle,
state: State::Idle,
original_server_id: match &target {
ConfigurationTarget::Existing { id, .. } => Some(id.clone()),
ConfigurationTarget::Extension { id, .. } => Some(id.clone()),
ConfigurationTarget::New => None,
},
source: ConfigurationSource::from_target(
target,
language_registry,
@@ -415,9 +421,19 @@ impl ConfigureContextServerModal {
// When we write the settings to the file, the context server will be restarted.
workspace.update(cx, |workspace, cx| {
let fs = workspace.app_state().fs.clone();
update_settings_file::<ProjectSettings>(fs.clone(), cx, |project_settings, _| {
project_settings.context_servers.insert(id.0, settings);
});
let original_server_id = self.original_server_id.clone();
update_settings_file::<ProjectSettings>(
fs.clone(),
cx,
move |project_settings, _| {
if let Some(original_id) = original_server_id {
if original_id != id {
project_settings.context_servers.remove(&original_id.0);
}
}
project_settings.context_servers.insert(id.0, settings);
},
);
});
} else if let Some(existing_server) = existing_server {
self.context_server_store

View File

@@ -1529,7 +1529,8 @@ impl AgentDiff {
| AcpThreadEvent::ToolAuthorizationRequired
| AcpThreadEvent::PromptCapabilitiesUpdated
| AcpThreadEvent::AvailableCommandsUpdated(_)
| AcpThreadEvent::Retry(_) => {}
| AcpThreadEvent::Retry(_)
| AcpThreadEvent::ModeUpdated(_) => {}
}
}

View File

@@ -5,9 +5,11 @@ use std::sync::Arc;
use std::time::Duration;
use acp_thread::AcpThread;
use agent_servers::AgentServerCommand;
use agent2::{DbThreadMetadata, HistoryEntry};
use db::kvp::{Dismissable, KEY_VALUE_STORE};
use project::agent_server_store::{
AgentServerCommand, AllAgentServersSettings, CLAUDE_CODE_NAME, GEMINI_NAME,
};
use serde::{Deserialize, Serialize};
use zed_actions::OpenBrowser;
use zed_actions::agent::{OpenClaudeCodeOnboardingModal, ReauthenticateAgent};
@@ -33,7 +35,9 @@ use crate::{
thread_history::{HistoryEntryElement, ThreadHistory},
ui::{AgentOnboardingModal, EndTrialUpsell},
};
use crate::{ExternalAgent, NewExternalAgentThread, NewNativeAgentThreadFromSummary};
use crate::{
ExternalAgent, NewExternalAgentThread, NewNativeAgentThreadFromSummary, placeholder_command,
};
use agent::{
Thread, ThreadError, ThreadEvent, ThreadId, ThreadSummary, TokenUsageRatio,
context_store::ContextStore,
@@ -62,7 +66,7 @@ use project::{DisableAiSettings, Project, ProjectPath, Worktree};
use prompt_store::{PromptBuilder, PromptStore, UserPromptId};
use rules_library::{RulesLibrary, open_rules_library};
use search::{BufferSearchBar, buffer_search};
use settings::{Settings, update_settings_file};
use settings::{Settings, SettingsStore, update_settings_file};
use theme::ThemeSettings;
use time::UtcOffset;
use ui::utils::WithRemSize;
@@ -1094,7 +1098,7 @@ impl AgentPanel {
let workspace = self.workspace.clone();
let project = self.project.clone();
let fs = self.fs.clone();
let is_not_local = !self.project.read(cx).is_local();
let is_via_collab = self.project.read(cx).is_via_collab();
const LAST_USED_EXTERNAL_AGENT_KEY: &str = "agent_panel__last_used_external_agent";
@@ -1126,7 +1130,7 @@ impl AgentPanel {
agent
}
None => {
if is_not_local {
if is_via_collab {
ExternalAgent::NativeAgent
} else {
cx.background_spawn(async move {
@@ -1503,6 +1507,7 @@ impl AgentPanel {
}
pub(crate) fn open_configuration(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let agent_server_store = self.project.read(cx).agent_server_store().clone();
let context_server_store = self.project.read(cx).context_server_store();
let tools = self.thread_store.read(cx).tools();
let fs = self.fs.clone();
@@ -1511,6 +1516,7 @@ impl AgentPanel {
self.configuration = Some(cx.new(|cx| {
AgentConfiguration::new(
fs,
agent_server_store,
context_server_store,
tools,
self.language_registry.clone(),
@@ -2503,6 +2509,7 @@ impl AgentPanel {
}
fn render_toolbar_new(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let agent_server_store = self.project.read(cx).agent_server_store().clone();
let focus_handle = self.focus_handle(cx);
let active_thread = match &self.active_view {
@@ -2531,12 +2538,14 @@ impl AgentPanel {
}
},
)
.anchor(Corner::TopLeft)
.anchor(Corner::TopRight)
.with_handle(self.new_thread_menu_handle.clone())
.menu({
let workspace = self.workspace.clone();
let is_not_local = workspace
.update(cx, |workspace, cx| !workspace.project().read(cx).is_local())
let is_via_collab = workspace
.update(cx, |workspace, cx| {
workspace.project().read(cx).is_via_collab()
})
.unwrap_or_default();
move |window, cx| {
@@ -2628,7 +2637,7 @@ impl AgentPanel {
ContextMenuEntry::new("New Gemini CLI Thread")
.icon(IconName::AiGemini)
.icon_color(Color::Muted)
.disabled(is_not_local)
.disabled(is_via_collab)
.handler({
let workspace = workspace.clone();
move |window, cx| {
@@ -2655,7 +2664,7 @@ impl AgentPanel {
menu.item(
ContextMenuEntry::new("New Claude Code Thread")
.icon(IconName::AiClaude)
.disabled(is_not_local)
.disabled(is_via_collab)
.icon_color(Color::Muted)
.handler({
let workspace = workspace.clone();
@@ -2680,19 +2689,25 @@ impl AgentPanel {
)
})
.when(cx.has_flag::<GeminiAndNativeFeatureFlag>(), |mut menu| {
// Add custom agents from settings
let settings =
agent_servers::AllAgentServersSettings::get_global(cx);
for (agent_name, agent_settings) in &settings.custom {
let agent_names = agent_server_store
.read(cx)
.external_agents()
.filter(|name| {
name.0 != GEMINI_NAME && name.0 != CLAUDE_CODE_NAME
})
.cloned()
.collect::<Vec<_>>();
let custom_settings = cx.global::<SettingsStore>().get::<AllAgentServersSettings>(None).custom.clone();
for agent_name in agent_names {
menu = menu.item(
ContextMenuEntry::new(format!("New {} Thread", agent_name))
.icon(IconName::Terminal)
.icon_color(Color::Muted)
.disabled(is_not_local)
.disabled(is_via_collab)
.handler({
let workspace = workspace.clone();
let agent_name = agent_name.clone();
let agent_settings = agent_settings.clone();
let custom_settings = custom_settings.clone();
move |window, cx| {
if let Some(workspace) = workspace.upgrade() {
workspace.update(cx, |workspace, cx| {
@@ -2702,11 +2717,13 @@ impl AgentPanel {
panel.update(cx, |panel, cx| {
panel.new_agent_thread(
AgentType::Custom {
name: agent_name
.clone(),
command: agent_settings
.command
.clone(),
name: agent_name.clone().into(),
command: custom_settings
.get(&agent_name.0)
.map(|settings| {
settings.command.clone()
})
.unwrap_or(placeholder_command()),
},
window,
cx,
@@ -2991,6 +3008,9 @@ impl AgentPanel {
_ => {
let history_is_empty = if cx.has_flag::<GeminiAndNativeFeatureFlag>() {
self.acp_history_store.read(cx).is_empty(cx)
&& self
.history_store
.update(cx, |store, cx| store.recent_entries(1, cx).is_empty())
} else {
self.history_store
.update(cx, |store, cx| store.recent_entries(1, cx).is_empty())
@@ -3052,6 +3072,8 @@ impl AgentPanel {
return None;
}
let plan = self.user_store.read(cx).plan()?;
Some(
v_flex()
.absolute()
@@ -3060,15 +3082,18 @@ impl AgentPanel {
.bg(cx.theme().colors().panel_background)
.opacity(0.85)
.block_mouse_except_scroll()
.child(EndTrialUpsell::new(Arc::new({
let this = cx.entity();
move |_, cx| {
this.update(cx, |_this, cx| {
TrialEndUpsell::set_dismissed(true, cx);
cx.notify();
});
}
}))),
.child(EndTrialUpsell::new(
plan,
Arc::new({
let this = cx.entity();
move |_, cx| {
this.update(cx, |_this, cx| {
TrialEndUpsell::set_dismissed(true, cx);
cx.notify();
});
}
}),
)),
)
}
@@ -3504,6 +3529,7 @@ impl AgentPanel {
let error_message = match plan {
Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
Plan::ZedProTrial | Plan::ZedFree => "Upgrade to Zed Pro for more prompts.",
Plan::ZedProV2 | Plan::ZedProTrialV2 | Plan::ZedFreeV2 => "",
};
Callout::new()

View File

@@ -28,7 +28,6 @@ use std::rc::Rc;
use std::sync::Arc;
use agent::{Thread, ThreadId};
use agent_servers::AgentServerCommand;
use agent_settings::{AgentProfileId, AgentSettings, LanguageModelSelection};
use assistant_slash_command::SlashCommandRegistry;
use client::Client;
@@ -41,6 +40,7 @@ use language_model::{
ConfiguredModel, LanguageModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
};
use project::DisableAiSettings;
use project::agent_server_store::AgentServerCommand;
use prompt_store::PromptBuilder;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
@@ -72,8 +72,10 @@ actions!(
ToggleOptionsMenu,
/// Deletes the recently opened thread from history.
DeleteRecentlyOpenThread,
/// Toggles the profile selector for switching between agent profiles.
/// Toggles the profile or mode selector for switching between agent profiles.
ToggleProfileSelector,
/// Cycles through available session modes.
CycleModeSelector,
/// Removes all added context from the current conversation.
RemoveAllContext,
/// Expands the message editor to full size.
@@ -114,6 +116,12 @@ actions!(
RejectAll,
/// Keeps all suggestions or changes.
KeepAll,
/// Allow this operation only this time.
AllowOnce,
/// Allow this operation and remember the choice.
AllowAlways,
/// Reject this operation only this time.
RejectOnce,
/// Follows the agent's suggestions.
Follow,
/// Resets the trial upsell notification.
@@ -174,6 +182,14 @@ enum ExternalAgent {
},
}
fn placeholder_command() -> AgentServerCommand {
AgentServerCommand {
path: "/placeholder".into(),
args: vec![],
env: None,
}
}
impl ExternalAgent {
fn name(&self) -> &'static str {
match self {
@@ -193,10 +209,9 @@ impl ExternalAgent {
Self::Gemini => Rc::new(agent_servers::Gemini),
Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
Self::NativeAgent => Rc::new(agent2::NativeAgentServer::new(fs, history)),
Self::Custom { name, command } => Rc::new(agent_servers::CustomAgentServer::new(
name.clone(),
command.clone(),
)),
Self::Custom { name, command: _ } => {
Rc::new(agent_servers::CustomAgentServer::new(name.clone()))
}
}
}
}
@@ -337,8 +352,7 @@ fn update_command_palette_filter(cx: &mut App) {
];
filter.show_action_types(edit_prediction_actions.iter());
filter
.show_action_types([TypeId::of::<zed_actions::OpenZedPredictOnboarding>()].iter());
filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
}
});
}

View File

@@ -1139,7 +1139,7 @@ mod tests {
);
while !new_text.is_empty() {
let max_len = cmp::min(new_text.len(), 10);
let len = rng.gen_range(1..=max_len);
let len = rng.random_range(1..=max_len);
let (chunk, suffix) = new_text.split_at(len);
chunks_tx.unbounded_send(chunk.to_string()).unwrap();
new_text = suffix;
@@ -1208,7 +1208,7 @@ mod tests {
);
while !new_text.is_empty() {
let max_len = cmp::min(new_text.len(), 10);
let len = rng.gen_range(1..=max_len);
let len = rng.random_range(1..=max_len);
let (chunk, suffix) = new_text.split_at(len);
chunks_tx.unbounded_send(chunk.to_string()).unwrap();
new_text = suffix;
@@ -1277,7 +1277,7 @@ mod tests {
);
while !new_text.is_empty() {
let max_len = cmp::min(new_text.len(), 10);
let len = rng.gen_range(1..=max_len);
let len = rng.random_range(1..=max_len);
let (chunk, suffix) = new_text.split_at(len);
chunks_tx.unbounded_send(chunk.to_string()).unwrap();
new_text = suffix;

View File

@@ -987,7 +987,8 @@ impl MentionLink {
.read(cx)
.project()
.read(cx)
.entry_for_path(&project_path, cx)?;
.entry_for_path(&project_path, cx)?
.clone();
Some(MentionLink::File(project_path, entry))
}
Self::SYMBOL => {

View File

@@ -1,29 +1,18 @@
use crate::agent_model_selector::AgentModelSelector;
use crate::buffer_codegen::BufferCodegen;
use crate::context_picker::{ContextPicker, ContextPickerCompletionProvider};
use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
use crate::message_editor::{ContextCreasesAddon, extract_message_creases, insert_message_creases};
use crate::terminal_codegen::TerminalCodegen;
use crate::{CycleNextInlineAssist, CyclePreviousInlineAssist, ModelUsageContext};
use crate::{RemoveAllContext, ToggleContextPicker};
use agent::{
context_store::ContextStore,
thread_store::{TextThreadStore, ThreadStore},
};
use client::ErrorExt;
use collections::VecDeque;
use db::kvp::Dismissable;
use editor::actions::Paste;
use editor::display_map::EditorMargins;
use editor::{
ContextMenuOptions, Editor, EditorElement, EditorEvent, EditorMode, EditorStyle, MultiBuffer,
actions::{MoveDown, MoveUp},
};
use feature_flags::{FeatureFlagAppExt as _, ZedProFeatureFlag};
use fs::Fs;
use gpui::{
AnyElement, App, ClickEvent, Context, CursorStyle, Entity, EventEmitter, FocusHandle,
Focusable, FontWeight, Subscription, TextStyle, WeakEntity, Window, anchored, deferred, point,
AnyElement, App, Context, CursorStyle, Entity, EventEmitter, FocusHandle, Focusable,
Subscription, TextStyle, WeakEntity, Window,
};
use language_model::{LanguageModel, LanguageModelRegistry};
use parking_lot::Mutex;
@@ -33,12 +22,19 @@ use std::rc::Rc;
use std::sync::Arc;
use theme::ThemeSettings;
use ui::utils::WithRemSize;
use ui::{
CheckboxWithLabel, IconButtonShape, KeyBinding, Popover, PopoverMenuHandle, Tooltip, prelude::*,
};
use ui::{IconButtonShape, KeyBinding, PopoverMenuHandle, Tooltip, prelude::*};
use workspace::Workspace;
use zed_actions::agent::ToggleModelSelector;
use crate::agent_model_selector::AgentModelSelector;
use crate::buffer_codegen::BufferCodegen;
use crate::context_picker::{ContextPicker, ContextPickerCompletionProvider};
use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
use crate::message_editor::{ContextCreasesAddon, extract_message_creases, insert_message_creases};
use crate::terminal_codegen::TerminalCodegen;
use crate::{CycleNextInlineAssist, CyclePreviousInlineAssist, ModelUsageContext};
use crate::{RemoveAllContext, ToggleContextPicker};
pub struct PromptEditor<T> {
pub editor: Entity<Editor>,
mode: PromptEditorMode,
@@ -144,47 +140,16 @@ impl<T: 'static> Render for PromptEditor<T> {
};
let error_message = SharedString::from(error.to_string());
if error.error_code() == proto::ErrorCode::RateLimitExceeded
&& cx.has_flag::<ZedProFeatureFlag>()
{
el.child(
v_flex()
.child(
IconButton::new(
"rate-limit-error",
IconName::XCircle,
)
.toggle_state(self.show_rate_limit_notice)
.shape(IconButtonShape::Square)
.icon_size(IconSize::Small)
.on_click(
cx.listener(Self::toggle_rate_limit_notice),
),
)
.children(self.show_rate_limit_notice.then(|| {
deferred(
anchored()
.position_mode(
gpui::AnchoredPositionMode::Local,
)
.position(point(px(0.), px(24.)))
.anchor(gpui::Corner::TopLeft)
.child(self.render_rate_limit_notice(cx)),
)
})),
)
} else {
el.child(
div()
.id("error")
.tooltip(Tooltip::text(error_message))
.child(
Icon::new(IconName::XCircle)
.size(IconSize::Small)
.color(Color::Error),
),
)
}
el.child(
div()
.id("error")
.tooltip(Tooltip::text(error_message))
.child(
Icon::new(IconName::XCircle)
.size(IconSize::Small)
.color(Color::Error),
),
)
}),
)
.child(
@@ -310,19 +275,6 @@ impl<T: 'static> PromptEditor<T> {
crate::active_thread::attach_pasted_images_as_context(&self.context_store, cx);
}
fn toggle_rate_limit_notice(
&mut self,
_: &ClickEvent,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.show_rate_limit_notice = !self.show_rate_limit_notice;
if self.show_rate_limit_notice {
window.focus(&self.editor.focus_handle(cx));
}
cx.notify();
}
fn handle_prompt_editor_events(
&mut self,
_: &Entity<Editor>,
@@ -707,61 +659,6 @@ impl<T: 'static> PromptEditor<T> {
.into_any_element()
}
fn render_rate_limit_notice(&self, cx: &mut Context<Self>) -> impl IntoElement {
Popover::new().child(
v_flex()
.occlude()
.p_2()
.child(
Label::new("Out of Tokens")
.size(LabelSize::Small)
.weight(FontWeight::BOLD),
)
.child(Label::new(
"Try Zed Pro for higher limits, a wider range of models, and more.",
))
.child(
h_flex()
.justify_between()
.child(CheckboxWithLabel::new(
"dont-show-again",
Label::new("Don't show again"),
if RateLimitNotice::dismissed() {
ui::ToggleState::Selected
} else {
ui::ToggleState::Unselected
},
|selection, _, cx| {
let is_dismissed = match selection {
ui::ToggleState::Unselected => false,
ui::ToggleState::Indeterminate => return,
ui::ToggleState::Selected => true,
};
RateLimitNotice::set_dismissed(is_dismissed, cx);
},
))
.child(
h_flex()
.gap_2()
.child(
Button::new("dismiss", "Dismiss")
.style(ButtonStyle::Transparent)
.on_click(cx.listener(Self::toggle_rate_limit_notice)),
)
.child(Button::new("more-info", "More Info").on_click(
|_event, window, cx| {
window.dispatch_action(
Box::new(zed_actions::OpenAccountSettings),
cx,
)
},
)),
),
),
)
}
fn render_editor(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
let colors = cx.theme().colors();
@@ -978,15 +875,7 @@ impl PromptEditor<BufferCodegen> {
self.editor
.update(cx, |editor, _| editor.set_read_only(false));
}
CodegenStatus::Error(error) => {
if cx.has_flag::<ZedProFeatureFlag>()
&& error.error_code() == proto::ErrorCode::RateLimitExceeded
&& !RateLimitNotice::dismissed()
{
self.show_rate_limit_notice = true;
cx.notify();
}
CodegenStatus::Error(_error) => {
self.edited_since_done = false;
self.editor
.update(cx, |editor, _| editor.set_read_only(false));
@@ -1189,12 +1078,6 @@ impl PromptEditor<TerminalCodegen> {
}
}
struct RateLimitNotice;
impl Dismissable for RateLimitNotice {
const KEY: &'static str = "dismissed-rate-limit-notice";
}
pub enum CodegenStatus {
Idle,
Pending,

View File

@@ -1,8 +1,6 @@
use std::{cmp::Reverse, sync::Arc};
use cloud_llm_client::Plan;
use collections::{HashSet, IndexMap};
use feature_flags::ZedProFeatureFlag;
use fuzzy::{StringMatch, StringMatchCandidate, match_strings};
use gpui::{Action, AnyElement, App, BackgroundExecutor, DismissEvent, Subscription, Task};
use language_model::{
@@ -13,8 +11,6 @@ use ordered_float::OrderedFloat;
use picker::{Picker, PickerDelegate};
use ui::{ListItem, ListItemSpacing, prelude::*};
const TRY_ZED_PRO_URL: &str = "https://zed.dev/pro";
type OnModelChanged = Arc<dyn Fn(Arc<dyn LanguageModel>, &mut App) + 'static>;
type GetActiveModel = Arc<dyn Fn(&App) -> Option<ConfiguredModel> + 'static>;
@@ -531,13 +527,9 @@ impl PickerDelegate for LanguageModelPickerDelegate {
fn render_footer(
&self,
_: &mut Window,
_window: &mut Window,
cx: &mut Context<Picker<Self>>,
) -> Option<gpui::AnyElement> {
use feature_flags::FeatureFlagAppExt;
let plan = Plan::ZedPro;
Some(
h_flex()
.w_full()
@@ -546,28 +538,6 @@ impl PickerDelegate for LanguageModelPickerDelegate {
.p_1()
.gap_4()
.justify_between()
.when(cx.has_flag::<ZedProFeatureFlag>(), |this| {
this.child(match plan {
Plan::ZedPro => Button::new("zed-pro", "Zed Pro")
.icon(IconName::ZedAssistant)
.icon_size(IconSize::Small)
.icon_color(Color::Muted)
.icon_position(IconPosition::Start)
.on_click(|_, window, cx| {
window
.dispatch_action(Box::new(zed_actions::OpenAccountSettings), cx)
}),
Plan::ZedFree | Plan::ZedProTrial => Button::new(
"try-pro",
if plan == Plan::ZedProTrial {
"Upgrade to Pro"
} else {
"Try Pro"
},
)
.on_click(|_, _, cx| cx.open_url(TRY_ZED_PRO_URL)),
})
})
.child(
Button::new("configure", "Configure")
.icon(IconName::Settings)

View File

@@ -125,6 +125,7 @@ pub(crate) fn create_editor(
cx,
);
editor.set_placeholder_text("Message the agent @ to include context", cx);
editor.disable_word_completions();
editor.set_show_indent_guides(false, cx);
editor.set_soft_wrap();
editor.set_use_modal_editing(true);

View File

@@ -6,8 +6,8 @@ use gpui::{Action, Entity, FocusHandle, Subscription, prelude::*};
use settings::{Settings as _, SettingsStore, update_settings_file};
use std::sync::Arc;
use ui::{
ContextMenu, ContextMenuEntry, DocumentationSide, PopoverMenu, PopoverMenuHandle, Tooltip,
prelude::*,
ContextMenu, ContextMenuEntry, DocumentationSide, PopoverMenu, PopoverMenuHandle, TintColor,
Tooltip, prelude::*,
};
/// Trait for types that can provide and manage agent profiles
@@ -170,7 +170,8 @@ impl Render for ProfileSelector {
.icon(IconName::ChevronDown)
.icon_size(IconSize::XSmall)
.icon_position(IconPosition::End)
.icon_color(Color::Muted);
.icon_color(Color::Muted)
.selected_style(ButtonStyle::Tinted(TintColor::Accent));
PopoverMenu::new("profile-selector")
.trigger_with_tooltip(trigger_button, {
@@ -195,6 +196,10 @@ impl Render for ProfileSelector {
.menu(move |window, cx| {
Some(this.update(cx, |this, cx| this.build_context_menu(window, cx)))
})
.offset(gpui::Point {
x: px(0.0),
y: px(-2.0),
})
.into_any_element()
} else {
Button::new("tools-not-supported-button", "Tools Unsupported")

View File

@@ -2,10 +2,11 @@ use anyhow::Result;
use gpui::App;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsSources, SettingsUi};
use settings::{Settings, SettingsKey, SettingsSources, SettingsUi};
/// Settings for slash commands.
#[derive(Deserialize, Serialize, Debug, Default, Clone, JsonSchema, SettingsUi)]
#[derive(Deserialize, Serialize, Debug, Default, Clone, JsonSchema, SettingsUi, SettingsKey)]
#[settings_key(key = "slash_commands")]
pub struct SlashCommandSettings {
/// Settings for the `/cargo-workspace` slash command.
#[serde(default)]
@@ -21,8 +22,6 @@ pub struct CargoWorkspaceCommandSettings {
}
impl Settings for SlashCommandSettings {
const KEY: Option<&'static str> = Some("slash_commands");
type FileContent = Self;
fn load(sources: SettingsSources<Self::FileContent>, _cx: &mut App) -> Result<Self> {

View File

@@ -2,24 +2,27 @@ use std::sync::Arc;
use ai_onboarding::{AgentPanelOnboardingCard, PlanDefinitions};
use client::zed_urls;
use cloud_llm_client::Plan;
use gpui::{AnyElement, App, IntoElement, RenderOnce, Window};
use ui::{Divider, Tooltip, prelude::*};
#[derive(IntoElement, RegisterComponent)]
pub struct EndTrialUpsell {
plan: Plan,
dismiss_upsell: Arc<dyn Fn(&mut Window, &mut App)>,
}
impl EndTrialUpsell {
pub fn new(dismiss_upsell: Arc<dyn Fn(&mut Window, &mut App)>) -> Self {
Self { dismiss_upsell }
pub fn new(plan: Plan, dismiss_upsell: Arc<dyn Fn(&mut Window, &mut App)>) -> Self {
Self {
plan,
dismiss_upsell,
}
}
}
impl RenderOnce for EndTrialUpsell {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let plan_definitions = PlanDefinitions;
let pro_section = v_flex()
.gap_1()
.child(
@@ -33,7 +36,7 @@ impl RenderOnce for EndTrialUpsell {
)
.child(Divider::horizontal()),
)
.child(plan_definitions.pro_plan(false))
.child(PlanDefinitions.pro_plan(self.plan.is_v2(), false))
.child(
Button::new("cta-button", "Upgrade to Zed Pro")
.full_width()
@@ -64,7 +67,7 @@ impl RenderOnce for EndTrialUpsell {
)
.child(Divider::horizontal()),
)
.child(plan_definitions.free_plan());
.child(PlanDefinitions.free_plan(self.plan.is_v2()));
AgentPanelOnboardingCard::new()
.child(Headline::new("Your Zed Pro Trial has expired"))
@@ -109,6 +112,7 @@ impl Component for EndTrialUpsell {
Some(
v_flex()
.child(EndTrialUpsell {
plan: Plan::ZedFree,
dismiss_upsell: Arc::new(|_, _| {}),
})
.into_any_element(),

View File

@@ -38,20 +38,20 @@ impl RenderOnce for UsageCallout {
let (title, message, button_text, url) = if is_limit_reached {
match self.plan {
Plan::ZedFree => (
Plan::ZedFree | Plan::ZedFreeV2 => (
"Out of free prompts",
"Upgrade to continue, wait for the next reset, or switch to API key."
.to_string(),
"Upgrade",
zed_urls::account_url(cx),
),
Plan::ZedProTrial => (
Plan::ZedProTrial | Plan::ZedProTrialV2 => (
"Out of trial prompts",
"Upgrade to Zed Pro to continue, or switch to API key.".to_string(),
"Upgrade",
zed_urls::account_url(cx),
),
Plan::ZedPro => (
Plan::ZedPro | Plan::ZedProV2 => (
"Out of included prompts",
"Enable usage-based billing to continue.".to_string(),
"Manage",

View File

@@ -18,6 +18,7 @@ default = []
client.workspace = true
cloud_llm_client.workspace = true
component.workspace = true
feature_flags.workspace = true
gpui.workspace = true
language_model.workspace = true
serde.workspace = true

View File

@@ -18,6 +18,7 @@ pub use young_account_banner::YoungAccountBanner;
use std::sync::Arc;
use client::{Client, UserStore, zed_urls};
use feature_flags::{BillingV2FeatureFlag, FeatureFlagAppExt as _};
use gpui::{AnyElement, Entity, IntoElement, ParentElement};
use ui::{Divider, RegisterComponent, Tooltip, prelude::*};
@@ -84,9 +85,8 @@ impl ZedAiOnboarding {
self
}
fn render_sign_in_disclaimer(&self, _cx: &mut App) -> AnyElement {
fn render_sign_in_disclaimer(&self, cx: &mut App) -> AnyElement {
let signing_in = matches!(self.sign_in_status, SignInStatus::SigningIn);
let plan_definitions = PlanDefinitions;
v_flex()
.gap_1()
@@ -96,7 +96,7 @@ impl ZedAiOnboarding {
.color(Color::Muted)
.mb_2(),
)
.child(plan_definitions.pro_plan(false))
.child(PlanDefinitions.pro_plan(cx.has_flag::<BillingV2FeatureFlag>(), false))
.child(
Button::new("sign_in", "Try Zed Pro for Free")
.disabled(signing_in)
@@ -113,17 +113,14 @@ impl ZedAiOnboarding {
.into_any_element()
}
fn render_free_plan_state(&self, cx: &mut App) -> AnyElement {
let young_account_banner = YoungAccountBanner;
let plan_definitions = PlanDefinitions;
fn render_free_plan_state(&self, is_v2: bool, cx: &mut App) -> AnyElement {
if self.account_too_young {
v_flex()
.relative()
.max_w_full()
.gap_1()
.child(Headline::new("Welcome to Zed AI"))
.child(young_account_banner)
.child(YoungAccountBanner)
.child(
v_flex()
.mt_2()
@@ -139,7 +136,7 @@ impl ZedAiOnboarding {
)
.child(Divider::horizontal()),
)
.child(plan_definitions.pro_plan(true))
.child(PlanDefinitions.pro_plan(is_v2, true))
.child(
Button::new("pro", "Get Started")
.full_width()
@@ -182,7 +179,7 @@ impl ZedAiOnboarding {
)
.child(Divider::horizontal()),
)
.child(plan_definitions.free_plan()),
.child(PlanDefinitions.free_plan(is_v2)),
)
.when_some(
self.dismiss_onboarding.as_ref(),
@@ -220,7 +217,7 @@ impl ZedAiOnboarding {
)
.child(Divider::horizontal()),
)
.child(plan_definitions.pro_trial(true))
.child(PlanDefinitions.pro_trial(is_v2, true))
.child(
Button::new("pro", "Start Free Trial")
.full_width()
@@ -238,9 +235,7 @@ impl ZedAiOnboarding {
}
}
fn render_trial_state(&self, _cx: &mut App) -> AnyElement {
let plan_definitions = PlanDefinitions;
fn render_trial_state(&self, is_v2: bool, _cx: &mut App) -> AnyElement {
v_flex()
.relative()
.gap_1()
@@ -250,7 +245,7 @@ impl ZedAiOnboarding {
.color(Color::Muted)
.mb_2(),
)
.child(plan_definitions.pro_trial(false))
.child(PlanDefinitions.pro_trial(is_v2, false))
.when_some(
self.dismiss_onboarding.as_ref(),
|this, dismiss_callback| {
@@ -274,9 +269,7 @@ impl ZedAiOnboarding {
.into_any_element()
}
fn render_pro_plan_state(&self, _cx: &mut App) -> AnyElement {
let plan_definitions = PlanDefinitions;
fn render_pro_plan_state(&self, is_v2: bool, _cx: &mut App) -> AnyElement {
v_flex()
.gap_1()
.child(Headline::new("Welcome to Zed Pro"))
@@ -285,7 +278,7 @@ impl ZedAiOnboarding {
.color(Color::Muted)
.mb_2(),
)
.child(plan_definitions.pro_plan(false))
.child(PlanDefinitions.pro_plan(is_v2, false))
.when_some(
self.dismiss_onboarding.as_ref(),
|this, dismiss_callback| {
@@ -314,9 +307,16 @@ impl RenderOnce for ZedAiOnboarding {
fn render(self, _window: &mut ui::Window, cx: &mut App) -> impl IntoElement {
if matches!(self.sign_in_status, SignInStatus::SignedIn) {
match self.plan {
None | Some(Plan::ZedFree) => self.render_free_plan_state(cx),
Some(Plan::ZedProTrial) => self.render_trial_state(cx),
Some(Plan::ZedPro) => self.render_pro_plan_state(cx),
None => self.render_free_plan_state(cx.has_flag::<BillingV2FeatureFlag>(), cx),
Some(plan @ (Plan::ZedFree | Plan::ZedFreeV2)) => {
self.render_free_plan_state(plan.is_v2(), cx)
}
Some(plan @ (Plan::ZedProTrial | Plan::ZedProTrialV2)) => {
self.render_trial_state(plan.is_v2(), cx)
}
Some(plan @ (Plan::ZedPro | Plan::ZedProV2)) => {
self.render_pro_plan_state(plan.is_v2(), cx)
}
}
} else {
self.render_sign_in_disclaimer(cx)

View File

@@ -2,6 +2,7 @@ use std::sync::Arc;
use client::{Client, UserStore, zed_urls};
use cloud_llm_client::Plan;
use feature_flags::{BillingV2FeatureFlag, FeatureFlagAppExt};
use gpui::{AnyElement, App, Entity, IntoElement, RenderOnce, Window};
use ui::{CommonAnimationExt, Divider, Vector, VectorName, prelude::*};
@@ -49,8 +50,9 @@ impl AiUpsellCard {
impl RenderOnce for AiUpsellCard {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let plan_definitions = PlanDefinitions;
let young_account_banner = YoungAccountBanner;
let is_v2_plan = self
.user_plan
.map_or(cx.has_flag::<BillingV2FeatureFlag>(), |plan| plan.is_v2());
let pro_section = v_flex()
.flex_grow()
@@ -67,7 +69,7 @@ impl RenderOnce for AiUpsellCard {
)
.child(Divider::horizontal()),
)
.child(plan_definitions.pro_plan(false));
.child(PlanDefinitions.pro_plan(is_v2_plan, false));
let free_section = v_flex()
.flex_grow()
@@ -84,7 +86,7 @@ impl RenderOnce for AiUpsellCard {
)
.child(Divider::horizontal()),
)
.child(plan_definitions.free_plan());
.child(PlanDefinitions.free_plan(is_v2_plan));
let grid_bg = h_flex()
.absolute()
@@ -169,11 +171,11 @@ impl RenderOnce for AiUpsellCard {
match self.sign_in_status {
SignInStatus::SignedIn => match self.user_plan {
None | Some(Plan::ZedFree) => card
None | Some(Plan::ZedFree | Plan::ZedFreeV2) => card
.child(Label::new("Try Zed AI").size(LabelSize::Large))
.map(|this| {
if self.account_too_young {
this.child(young_account_banner).child(
this.child(YoungAccountBanner).child(
v_flex()
.mt_2()
.gap_1()
@@ -188,7 +190,7 @@ impl RenderOnce for AiUpsellCard {
)
.child(Divider::horizontal()),
)
.child(plan_definitions.pro_plan(true))
.child(PlanDefinitions.pro_plan(is_v2_plan, true))
.child(
Button::new("pro", "Get Started")
.full_width()
@@ -235,7 +237,7 @@ impl RenderOnce for AiUpsellCard {
)
}
}),
Some(Plan::ZedProTrial) => card
Some(plan @ (Plan::ZedProTrial | Plan::ZedProTrialV2)) => card
.child(pro_trial_stamp)
.child(Label::new("You're in the Zed Pro Trial").size(LabelSize::Large))
.child(
@@ -243,8 +245,8 @@ impl RenderOnce for AiUpsellCard {
.color(Color::Muted)
.mb_2(),
)
.child(plan_definitions.pro_trial(false)),
Some(Plan::ZedPro) => card
.child(PlanDefinitions.pro_trial(plan.is_v2(), false)),
Some(plan @ (Plan::ZedPro | Plan::ZedProV2)) => card
.child(certified_user_stamp)
.child(Label::new("You're in the Zed Pro plan").size(LabelSize::Large))
.child(
@@ -252,7 +254,7 @@ impl RenderOnce for AiUpsellCard {
.color(Color::Muted)
.mb_2(),
)
.child(plan_definitions.pro_plan(false)),
.child(PlanDefinitions.pro_plan(plan.is_v2(), false)),
},
// Signed Out State
_ => card

View File

@@ -7,13 +7,13 @@ pub struct PlanDefinitions;
impl PlanDefinitions {
pub const AI_DESCRIPTION: &'static str = "Zed offers a complete agentic experience, with robust editing and reviewing features to collaborate with AI.";
pub fn free_plan(&self) -> impl IntoElement {
pub fn free_plan(&self, _is_v2: bool) -> impl IntoElement {
List::new()
.child(ListBulletItem::new("50 prompts with Claude models"))
.child(ListBulletItem::new("2,000 accepted edit predictions"))
}
pub fn pro_trial(&self, period: bool) -> impl IntoElement {
pub fn pro_trial(&self, _is_v2: bool, period: bool) -> impl IntoElement {
List::new()
.child(ListBulletItem::new("150 prompts with Claude models"))
.child(ListBulletItem::new(
@@ -26,7 +26,7 @@ impl PlanDefinitions {
})
}
pub fn pro_plan(&self, price: bool) -> impl IntoElement {
pub fn pro_plan(&self, _is_v2: bool, price: bool) -> impl IntoElement {
List::new()
.child(ListBulletItem::new("500 prompts with Claude models"))
.child(ListBulletItem::new(

View File

@@ -764,7 +764,7 @@ async fn test_random_context_collaboration(cx: &mut TestAppContext, mut rng: Std
let network = Arc::new(Mutex::new(Network::new(rng.clone())));
let mut contexts = Vec::new();
let num_peers = rng.gen_range(min_peers..=max_peers);
let num_peers = rng.random_range(min_peers..=max_peers);
let context_id = ContextId::new();
let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
for i in 0..num_peers {
@@ -806,10 +806,10 @@ async fn test_random_context_collaboration(cx: &mut TestAppContext, mut rng: Std
|| !network.lock().is_idle()
|| network.lock().contains_disconnected_peers()
{
let context_index = rng.gen_range(0..contexts.len());
let context_index = rng.random_range(0..contexts.len());
let context = &contexts[context_index];
match rng.gen_range(0..100) {
match rng.random_range(0..100) {
0..=29 if mutation_count > 0 => {
log::info!("Context {}: edit buffer", context_index);
context.update(cx, |context, cx| {
@@ -874,10 +874,10 @@ async fn test_random_context_collaboration(cx: &mut TestAppContext, mut rng: Std
merge_same_roles: true,
})];
let num_sections = rng.gen_range(0..=3);
let num_sections = rng.random_range(0..=3);
let mut section_start = 0;
for _ in 0..num_sections {
let mut section_end = rng.gen_range(section_start..=output_text.len());
let mut section_end = rng.random_range(section_start..=output_text.len());
while !output_text.is_char_boundary(section_end) {
section_end += 1;
}
@@ -924,7 +924,7 @@ async fn test_random_context_collaboration(cx: &mut TestAppContext, mut rng: Std
75..=84 if mutation_count > 0 => {
context.update(cx, |context, cx| {
if let Some(message) = context.messages(cx).choose(&mut rng) {
let new_status = match rng.gen_range(0..3) {
let new_status = match rng.random_range(0..3) {
0 => MessageStatus::Done,
1 => MessageStatus::Pending,
_ => MessageStatus::Error(SharedString::from("Random error")),
@@ -971,7 +971,7 @@ async fn test_random_context_collaboration(cx: &mut TestAppContext, mut rng: Std
network.lock().broadcast(replica_id, ops_to_send);
context.update(cx, |context, cx| context.apply_ops(ops_to_receive, cx));
} else if rng.gen_bool(0.1) && replica_id != 0 {
} else if rng.random_bool(0.1) && replica_id != 0 {
log::info!("Context {}: disconnecting", context_index);
network.lock().disconnect_peer(replica_id);
} else if network.lock().has_unreceived(replica_id) {

View File

@@ -1315,17 +1315,17 @@ mod tests {
#[gpui::test(iterations = 100)]
async fn test_random_indents(mut rng: StdRng) {
let len = rng.gen_range(1..=100);
let len = rng.random_range(1..=100);
let new_text = util::RandomCharIter::new(&mut rng)
.with_simple_text()
.take(len)
.collect::<String>();
let new_text = new_text
.split('\n')
.map(|line| format!("{}{}", " ".repeat(rng.gen_range(0..=8)), line))
.map(|line| format!("{}{}", " ".repeat(rng.random_range(0..=8)), line))
.collect::<Vec<_>>()
.join("\n");
let delta = IndentDelta::Spaces(rng.gen_range(-4..=4));
let delta = IndentDelta::Spaces(rng.random_range(-4i8..=4i8) as isize);
let chunks = to_random_chunks(&mut rng, &new_text);
let new_text_chunks = stream::iter(chunks.iter().enumerate().map(|(index, chunk)| {
@@ -1357,7 +1357,7 @@ mod tests {
}
fn to_random_chunks(rng: &mut StdRng, input: &str) -> Vec<String> {
let chunk_count = rng.gen_range(1..=cmp::min(input.len(), 50));
let chunk_count = rng.random_range(1..=cmp::min(input.len(), 50));
let mut chunk_indices = (0..input.len()).choose_multiple(rng, chunk_count);
chunk_indices.sort();
chunk_indices.push(input.len());

View File

@@ -204,7 +204,7 @@ mod tests {
}
fn parse_random_chunks(input: &str, parser: &mut CreateFileParser, rng: &mut StdRng) -> String {
let chunk_count = rng.gen_range(1..=cmp::min(input.len(), 50));
let chunk_count = rng.random_range(1..=cmp::min(input.len(), 50));
let mut chunk_indices = (0..input.len()).choose_multiple(rng, chunk_count);
chunk_indices.sort();
chunk_indices.push(input.len());

View File

@@ -996,7 +996,7 @@ mod tests {
}
fn parse_random_chunks(input: &str, parser: &mut EditParser, rng: &mut StdRng) -> Vec<Edit> {
let chunk_count = rng.gen_range(1..=cmp::min(input.len(), 50));
let chunk_count = rng.random_range(1..=cmp::min(input.len(), 50));
let mut chunk_indices = (0..input.len()).choose_multiple(rng, chunk_count);
chunk_indices.sort();
chunk_indices.push(input.len());

View File

@@ -1399,7 +1399,7 @@ fn eval(
}
fn run_eval(eval: EvalInput, tx: mpsc::Sender<Result<EvalOutput>>) {
let dispatcher = gpui::TestDispatcher::new(StdRng::from_entropy());
let dispatcher = gpui::TestDispatcher::new(StdRng::from_os_rng());
let mut cx = TestAppContext::build(dispatcher, None);
let output = cx.executor().block_test(async {
let test = EditAgentTest::new(&mut cx).await;
@@ -1520,7 +1520,15 @@ impl EditAgentTest {
selected_model: &SelectedModel,
cx: &mut AsyncApp,
) -> Result<Arc<dyn LanguageModel>> {
let (provider, model) = cx.update(|cx| {
cx.update(|cx| {
let registry = LanguageModelRegistry::read_global(cx);
let provider = registry
.provider(&selected_model.provider)
.expect("Provider not found");
provider.authenticate(cx)
})?
.await?;
cx.update(|cx| {
let models = LanguageModelRegistry::read_global(cx);
let model = models
.available_models(cx)
@@ -1529,11 +1537,8 @@ impl EditAgentTest {
&& model.id() == selected_model.model
})
.expect("Model not found");
let provider = models.provider(&model.provider_id()).unwrap();
(provider, model)
})?;
cx.update(|cx| provider.authenticate(cx))?.await?;
Ok(model)
model
})
}
async fn eval(&self, eval: EvalInput, cx: &mut TestAppContext) -> Result<EvalOutput> {
@@ -1707,7 +1712,7 @@ async fn retry_on_rate_limit<R>(mut request: impl AsyncFnMut() -> Result<R>) ->
};
if let Some(retry_after) = retry_delay {
let jitter = retry_after.mul_f64(rand::thread_rng().gen_range(0.0..1.0));
let jitter = retry_after.mul_f64(rand::rng().random_range(0.0..1.0));
eprintln!("Attempt #{attempt}: Retry after {retry_after:?} + jitter of {jitter:?}");
Timer::after(retry_after + jitter).await;
} else {

View File

@@ -771,7 +771,7 @@ mod tests {
}
fn to_random_chunks(rng: &mut StdRng, input: &str) -> Vec<String> {
let chunk_count = rng.gen_range(1..=cmp::min(input.len(), 50));
let chunk_count = rng.random_range(1..=cmp::min(input.len(), 50));
let mut chunk_indices = (0..input.len()).choose_multiple(rng, chunk_count);
chunk_indices.sort();
chunk_indices.push(input.len());

View File

@@ -2,9 +2,9 @@ use anyhow::Result;
use gpui::App;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsSources, SettingsUi};
use settings::{Settings, SettingsKey, SettingsSources, SettingsUi};
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, Debug)]
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, Debug, SettingsUi)]
pub struct AudioSettings {
/// Opt into the new audio system.
#[serde(rename = "experimental.rodio_audio", default)]
@@ -12,8 +12,9 @@ pub struct AudioSettings {
}
/// Configuration of audio in Zed.
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, Debug, SettingsUi)]
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, Debug, SettingsUi, SettingsKey)]
#[serde(default)]
#[settings_key(key = "audio")]
pub struct AudioSettingsContent {
/// Whether to use the experimental audio system
#[serde(rename = "experimental.rodio_audio", default)]
@@ -21,8 +22,6 @@ pub struct AudioSettingsContent {
}
impl Settings for AudioSettings {
const KEY: Option<&'static str> = Some("audio");
type FileContent = AudioSettingsContent;
fn load(sources: SettingsSources<Self::FileContent>, _cx: &mut App) -> Result<Self> {

View File

@@ -10,7 +10,7 @@ use paths::remote_servers_dir;
use release_channel::{AppCommitSha, ReleaseChannel};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsSources, SettingsStore, SettingsUi};
use settings::{Settings, SettingsKey, SettingsSources, SettingsStore, SettingsUi};
use smol::{fs, io::AsyncReadExt};
use smol::{fs::File, process::Command};
use std::{
@@ -118,13 +118,14 @@ struct AutoUpdateSetting(bool);
/// Whether or not to automatically check for updates.
///
/// Default: true
#[derive(Clone, Copy, Default, JsonSchema, Deserialize, Serialize, SettingsUi)]
#[serde(transparent)]
struct AutoUpdateSettingContent(bool);
#[derive(Clone, Copy, Default, JsonSchema, Deserialize, Serialize, SettingsUi, SettingsKey)]
#[settings_key(None)]
#[settings_ui(group = "Auto Update")]
struct AutoUpdateSettingContent {
pub auto_update: Option<bool>,
}
impl Settings for AutoUpdateSetting {
const KEY: Option<&'static str> = Some("auto_update");
type FileContent = AutoUpdateSettingContent;
fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
@@ -135,17 +136,22 @@ impl Settings for AutoUpdateSetting {
sources.user,
]
.into_iter()
.find_map(|value| value.copied())
.unwrap_or(*sources.default);
.find_map(|value| value.and_then(|val| val.auto_update))
.or(sources.default.auto_update)
.ok_or_else(Self::missing_default)?;
Ok(Self(auto_update.0))
Ok(Self(auto_update))
}
fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut Self::FileContent) {
let mut cur = &mut Some(*current);
vscode.enum_setting("update.mode", &mut cur, |s| match s {
"none" | "manual" => Some(AutoUpdateSettingContent(false)),
_ => Some(AutoUpdateSettingContent(true)),
"none" | "manual" => Some(AutoUpdateSettingContent {
auto_update: Some(false),
}),
_ => Some(AutoUpdateSettingContent {
auto_update: Some(true),
}),
});
*current = cur.unwrap();
}
@@ -558,6 +564,7 @@ impl AutoUpdater {
this.update(&mut cx, |this, cx| {
this.status = AutoUpdateStatus::Checking;
log::info!("Auto Update: checking for updates");
cx.notify();
})?;

View File

@@ -1,5 +1,4 @@
use auto_update::AutoUpdater;
use client::proto::UpdateNotification;
use editor::{Editor, MultiBuffer};
use gpui::{App, Context, DismissEvent, Entity, Window, actions, prelude::*};
use http_client::HttpClient;
@@ -88,10 +87,7 @@ fn view_release_notes_locally(
.update_in(cx, |workspace, window, cx| {
let project = workspace.project().clone();
let buffer = project.update(cx, |project, cx| {
let buffer = project.create_local_buffer("", markdown, cx);
project
.mark_buffer_as_non_searchable(buffer.read(cx).remote_id(), cx);
buffer
project.create_local_buffer("", markdown, false, cx)
});
buffer.update(cx, |buffer, cx| {
buffer.edit([(0..0, body.release_notes)], None, cx)
@@ -141,6 +137,8 @@ pub fn notify_if_app_was_updated(cx: &mut App) {
return;
}
struct UpdateNotification;
let should_show_notification = updater.read(cx).should_show_update_notification(cx);
cx.spawn(async move |cx| {
let should_show_notification = should_show_notification.await?;

View File

@@ -2044,10 +2044,10 @@ mod tests {
#[gpui::test(iterations = 100)]
async fn test_staging_and_unstaging_hunks(cx: &mut TestAppContext, mut rng: StdRng) {
fn gen_line(rng: &mut StdRng) -> String {
if rng.gen_bool(0.2) {
if rng.random_bool(0.2) {
"\n".to_owned()
} else {
let c = rng.gen_range('A'..='Z');
let c = rng.random_range('A'..='Z');
format!("{c}{c}{c}\n")
}
}
@@ -2066,7 +2066,7 @@ mod tests {
old_lines.into_iter()
};
let mut result = String::new();
let unchanged_count = rng.gen_range(0..=old_lines.len());
let unchanged_count = rng.random_range(0..=old_lines.len());
result +=
&old_lines
.by_ref()
@@ -2076,14 +2076,14 @@ mod tests {
s
});
while old_lines.len() > 0 {
let deleted_count = rng.gen_range(0..=old_lines.len());
let deleted_count = rng.random_range(0..=old_lines.len());
let _advance = old_lines
.by_ref()
.take(deleted_count)
.map(|line| line.len() + 1)
.sum::<usize>();
let minimum_added = if deleted_count == 0 { 1 } else { 0 };
let added_count = rng.gen_range(minimum_added..=5);
let added_count = rng.random_range(minimum_added..=5);
let addition = (0..added_count).map(|_| gen_line(rng)).collect::<String>();
result += &addition;
@@ -2092,7 +2092,8 @@ mod tests {
if blank_lines == old_lines.len() {
break;
};
let unchanged_count = rng.gen_range((blank_lines + 1).max(1)..=old_lines.len());
let unchanged_count =
rng.random_range((blank_lines + 1).max(1)..=old_lines.len());
result += &old_lines.by_ref().take(unchanged_count).fold(
String::new(),
|mut s, line| {
@@ -2149,7 +2150,7 @@ mod tests {
)
});
let working_copy = working_copy.read_with(cx, |working_copy, _| working_copy.snapshot());
let mut index_text = if rng.r#gen() {
let mut index_text = if rng.random() {
Rope::from(head_text.as_str())
} else {
working_copy.as_rope().clone()
@@ -2165,7 +2166,7 @@ mod tests {
}
for _ in 0..operations {
let i = rng.gen_range(0..hunks.len());
let i = rng.random_range(0..hunks.len());
let hunk = &mut hunks[i];
let hunk_to_change = hunk.clone();
let stage = match hunk.secondary_status {

View File

@@ -2,7 +2,7 @@ use anyhow::Result;
use gpui::App;
use schemars::JsonSchema;
use serde_derive::{Deserialize, Serialize};
use settings::{Settings, SettingsSources, SettingsUi};
use settings::{Settings, SettingsKey, SettingsSources, SettingsUi};
#[derive(Deserialize, Debug)]
pub struct CallSettings {
@@ -11,7 +11,8 @@ pub struct CallSettings {
}
/// Configuration of voice calls in Zed.
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, Debug, SettingsUi)]
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, Debug, SettingsUi, SettingsKey)]
#[settings_key(key = "calls")]
pub struct CallSettingsContent {
/// Whether the microphone should be muted when joining a channel or a call.
///
@@ -25,8 +26,6 @@ pub struct CallSettingsContent {
}
impl Settings for CallSettings {
const KEY: Option<&'static str> = Some("calls");
type FileContent = CallSettingsContent;
fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {

View File

@@ -25,11 +25,9 @@ gpui.workspace = true
language.workspace = true
log.workspace = true
postage.workspace = true
rand.workspace = true
release_channel.workspace = true
rpc.workspace = true
settings.workspace = true
sum_tree.workspace = true
text.workspace = true
time.workspace = true
util.workspace = true

View File

@@ -1,5 +1,4 @@
mod channel_buffer;
mod channel_chat;
mod channel_store;
use client::{Client, UserStore};
@@ -7,10 +6,6 @@ use gpui::{App, Entity};
use std::sync::Arc;
pub use channel_buffer::{ACKNOWLEDGE_DEBOUNCE_INTERVAL, ChannelBuffer, ChannelBufferEvent};
pub use channel_chat::{
ChannelChat, ChannelChatEvent, ChannelMessage, ChannelMessageId, MessageParams,
mentions_to_proto,
};
pub use channel_store::{Channel, ChannelEvent, ChannelMembership, ChannelStore};
#[cfg(test)]
@@ -19,5 +14,4 @@ mod channel_store_tests;
pub fn init(client: &Arc<Client>, user_store: Entity<UserStore>, cx: &mut App) {
channel_store::init(client, user_store, cx);
channel_buffer::init(&client.clone().into());
channel_chat::init(&client.clone().into());
}

View File

@@ -1,861 +0,0 @@
use crate::{Channel, ChannelStore};
use anyhow::{Context as _, Result};
use client::{
ChannelId, Client, Subscription, TypedEnvelope, UserId, proto,
user::{User, UserStore},
};
use collections::HashSet;
use futures::lock::Mutex;
use gpui::{App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Task, WeakEntity};
use rand::prelude::*;
use rpc::AnyProtoClient;
use std::{
ops::{ControlFlow, Range},
sync::Arc,
};
use sum_tree::{Bias, Dimensions, SumTree};
use time::OffsetDateTime;
use util::{ResultExt as _, TryFutureExt, post_inc};
pub struct ChannelChat {
pub channel_id: ChannelId,
messages: SumTree<ChannelMessage>,
acknowledged_message_ids: HashSet<u64>,
channel_store: Entity<ChannelStore>,
loaded_all_messages: bool,
last_acknowledged_id: Option<u64>,
next_pending_message_id: usize,
first_loaded_message_id: Option<u64>,
user_store: Entity<UserStore>,
rpc: Arc<Client>,
outgoing_messages_lock: Arc<Mutex<()>>,
rng: StdRng,
_subscription: Subscription,
}
#[derive(Debug, PartialEq, Eq)]
pub struct MessageParams {
pub text: String,
pub mentions: Vec<(Range<usize>, UserId)>,
pub reply_to_message_id: Option<u64>,
}
#[derive(Clone, Debug)]
pub struct ChannelMessage {
pub id: ChannelMessageId,
pub body: String,
pub timestamp: OffsetDateTime,
pub sender: Arc<User>,
pub nonce: u128,
pub mentions: Vec<(Range<usize>, UserId)>,
pub reply_to_message_id: Option<u64>,
pub edited_at: Option<OffsetDateTime>,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ChannelMessageId {
Saved(u64),
Pending(usize),
}
impl From<ChannelMessageId> for Option<u64> {
fn from(val: ChannelMessageId) -> Self {
match val {
ChannelMessageId::Saved(id) => Some(id),
ChannelMessageId::Pending(_) => None,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct ChannelMessageSummary {
max_id: ChannelMessageId,
count: usize,
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
struct Count(usize);
#[derive(Clone, Debug, PartialEq)]
pub enum ChannelChatEvent {
MessagesUpdated {
old_range: Range<usize>,
new_count: usize,
},
UpdateMessage {
message_id: ChannelMessageId,
message_ix: usize,
},
NewMessage {
channel_id: ChannelId,
message_id: u64,
},
}
impl EventEmitter<ChannelChatEvent> for ChannelChat {}
pub fn init(client: &AnyProtoClient) {
client.add_entity_message_handler(ChannelChat::handle_message_sent);
client.add_entity_message_handler(ChannelChat::handle_message_removed);
client.add_entity_message_handler(ChannelChat::handle_message_updated);
}
impl ChannelChat {
pub async fn new(
channel: Arc<Channel>,
channel_store: Entity<ChannelStore>,
user_store: Entity<UserStore>,
client: Arc<Client>,
cx: &mut AsyncApp,
) -> Result<Entity<Self>> {
let channel_id = channel.id;
let subscription = client.subscribe_to_entity(channel_id.0).unwrap();
let response = client
.request(proto::JoinChannelChat {
channel_id: channel_id.0,
})
.await?;
let handle = cx.new(|cx| {
cx.on_release(Self::release).detach();
Self {
channel_id: channel.id,
user_store: user_store.clone(),
channel_store,
rpc: client.clone(),
outgoing_messages_lock: Default::default(),
messages: Default::default(),
acknowledged_message_ids: Default::default(),
loaded_all_messages: false,
next_pending_message_id: 0,
last_acknowledged_id: None,
rng: StdRng::from_entropy(),
first_loaded_message_id: None,
_subscription: subscription.set_entity(&cx.entity(), &cx.to_async()),
}
})?;
Self::handle_loaded_messages(
handle.downgrade(),
user_store,
client,
response.messages,
response.done,
cx,
)
.await?;
Ok(handle)
}
fn release(&mut self, _: &mut App) {
self.rpc
.send(proto::LeaveChannelChat {
channel_id: self.channel_id.0,
})
.log_err();
}
pub fn channel(&self, cx: &App) -> Option<Arc<Channel>> {
self.channel_store
.read(cx)
.channel_for_id(self.channel_id)
.cloned()
}
pub fn client(&self) -> &Arc<Client> {
&self.rpc
}
pub fn send_message(
&mut self,
message: MessageParams,
cx: &mut Context<Self>,
) -> Result<Task<Result<u64>>> {
anyhow::ensure!(
!message.text.trim().is_empty(),
"message body can't be empty"
);
let current_user = self
.user_store
.read(cx)
.current_user()
.context("current_user is not present")?;
let channel_id = self.channel_id;
let pending_id = ChannelMessageId::Pending(post_inc(&mut self.next_pending_message_id));
let nonce = self.rng.r#gen();
self.insert_messages(
SumTree::from_item(
ChannelMessage {
id: pending_id,
body: message.text.clone(),
sender: current_user,
timestamp: OffsetDateTime::now_utc(),
mentions: message.mentions.clone(),
nonce,
reply_to_message_id: message.reply_to_message_id,
edited_at: None,
},
&(),
),
cx,
);
let user_store = self.user_store.clone();
let rpc = self.rpc.clone();
let outgoing_messages_lock = self.outgoing_messages_lock.clone();
// todo - handle messages that fail to send (e.g. >1024 chars)
Ok(cx.spawn(async move |this, cx| {
let outgoing_message_guard = outgoing_messages_lock.lock().await;
let request = rpc.request(proto::SendChannelMessage {
channel_id: channel_id.0,
body: message.text,
nonce: Some(nonce.into()),
mentions: mentions_to_proto(&message.mentions),
reply_to_message_id: message.reply_to_message_id,
});
let response = request.await?;
drop(outgoing_message_guard);
let response = response.message.context("invalid message")?;
let id = response.id;
let message = ChannelMessage::from_proto(response, &user_store, cx).await?;
this.update(cx, |this, cx| {
this.insert_messages(SumTree::from_item(message, &()), cx);
if this.first_loaded_message_id.is_none() {
this.first_loaded_message_id = Some(id);
}
})?;
Ok(id)
}))
}
pub fn remove_message(&mut self, id: u64, cx: &mut Context<Self>) -> Task<Result<()>> {
let response = self.rpc.request(proto::RemoveChannelMessage {
channel_id: self.channel_id.0,
message_id: id,
});
cx.spawn(async move |this, cx| {
response.await?;
this.update(cx, |this, cx| {
this.message_removed(id, cx);
})?;
Ok(())
})
}
pub fn update_message(
&mut self,
id: u64,
message: MessageParams,
cx: &mut Context<Self>,
) -> Result<Task<Result<()>>> {
self.message_update(
ChannelMessageId::Saved(id),
message.text.clone(),
message.mentions.clone(),
Some(OffsetDateTime::now_utc()),
cx,
);
let nonce: u128 = self.rng.r#gen();
let request = self.rpc.request(proto::UpdateChannelMessage {
channel_id: self.channel_id.0,
message_id: id,
body: message.text,
nonce: Some(nonce.into()),
mentions: mentions_to_proto(&message.mentions),
});
Ok(cx.spawn(async move |_, _| {
request.await?;
Ok(())
}))
}
pub fn load_more_messages(&mut self, cx: &mut Context<Self>) -> Option<Task<Option<()>>> {
if self.loaded_all_messages {
return None;
}
let rpc = self.rpc.clone();
let user_store = self.user_store.clone();
let channel_id = self.channel_id;
let before_message_id = self.first_loaded_message_id()?;
Some(cx.spawn(async move |this, cx| {
async move {
let response = rpc
.request(proto::GetChannelMessages {
channel_id: channel_id.0,
before_message_id,
})
.await?;
Self::handle_loaded_messages(
this,
user_store,
rpc,
response.messages,
response.done,
cx,
)
.await?;
anyhow::Ok(())
}
.log_err()
.await
}))
}
pub fn first_loaded_message_id(&mut self) -> Option<u64> {
self.first_loaded_message_id
}
/// Load a message by its id, if it's already stored locally.
pub fn find_loaded_message(&self, id: u64) -> Option<&ChannelMessage> {
self.messages.iter().find(|message| match message.id {
ChannelMessageId::Saved(message_id) => message_id == id,
ChannelMessageId::Pending(_) => false,
})
}
/// Load all of the chat messages since a certain message id.
///
/// For now, we always maintain a suffix of the channel's messages.
pub async fn load_history_since_message(
chat: Entity<Self>,
message_id: u64,
mut cx: AsyncApp,
) -> Option<usize> {
loop {
let step = chat
.update(&mut cx, |chat, cx| {
if let Some(first_id) = chat.first_loaded_message_id()
&& first_id <= message_id
{
let mut cursor = chat
.messages
.cursor::<Dimensions<ChannelMessageId, Count>>(&());
let message_id = ChannelMessageId::Saved(message_id);
cursor.seek(&message_id, Bias::Left);
return ControlFlow::Break(
if cursor
.item()
.is_some_and(|message| message.id == message_id)
{
Some(cursor.start().1.0)
} else {
None
},
);
}
ControlFlow::Continue(chat.load_more_messages(cx))
})
.log_err()?;
match step {
ControlFlow::Break(ix) => return ix,
ControlFlow::Continue(task) => task?.await?,
}
}
}
pub fn acknowledge_last_message(&mut self, cx: &mut Context<Self>) {
if let ChannelMessageId::Saved(latest_message_id) = self.messages.summary().max_id
&& self
.last_acknowledged_id
.is_none_or(|acknowledged_id| acknowledged_id < latest_message_id)
{
self.rpc
.send(proto::AckChannelMessage {
channel_id: self.channel_id.0,
message_id: latest_message_id,
})
.ok();
self.last_acknowledged_id = Some(latest_message_id);
self.channel_store.update(cx, |store, cx| {
store.acknowledge_message_id(self.channel_id, latest_message_id, cx);
});
}
}
async fn handle_loaded_messages(
this: WeakEntity<Self>,
user_store: Entity<UserStore>,
rpc: Arc<Client>,
proto_messages: Vec<proto::ChannelMessage>,
loaded_all_messages: bool,
cx: &mut AsyncApp,
) -> Result<()> {
let loaded_messages = messages_from_proto(proto_messages, &user_store, cx).await?;
let first_loaded_message_id = loaded_messages.first().map(|m| m.id);
let loaded_message_ids = this.read_with(cx, |this, _| {
let mut loaded_message_ids: HashSet<u64> = HashSet::default();
for message in loaded_messages.iter() {
if let Some(saved_message_id) = message.id.into() {
loaded_message_ids.insert(saved_message_id);
}
}
for message in this.messages.iter() {
if let Some(saved_message_id) = message.id.into() {
loaded_message_ids.insert(saved_message_id);
}
}
loaded_message_ids
})?;
let missing_ancestors = loaded_messages
.iter()
.filter_map(|message| {
if let Some(ancestor_id) = message.reply_to_message_id
&& !loaded_message_ids.contains(&ancestor_id)
{
return Some(ancestor_id);
}
None
})
.collect::<Vec<_>>();
let loaded_ancestors = if missing_ancestors.is_empty() {
None
} else {
let response = rpc
.request(proto::GetChannelMessagesById {
message_ids: missing_ancestors,
})
.await?;
Some(messages_from_proto(response.messages, &user_store, cx).await?)
};
this.update(cx, |this, cx| {
this.first_loaded_message_id = first_loaded_message_id.and_then(|msg_id| msg_id.into());
this.loaded_all_messages = loaded_all_messages;
this.insert_messages(loaded_messages, cx);
if let Some(loaded_ancestors) = loaded_ancestors {
this.insert_messages(loaded_ancestors, cx);
}
})?;
Ok(())
}
pub fn rejoin(&mut self, cx: &mut Context<Self>) {
let user_store = self.user_store.clone();
let rpc = self.rpc.clone();
let channel_id = self.channel_id;
cx.spawn(async move |this, cx| {
async move {
let response = rpc
.request(proto::JoinChannelChat {
channel_id: channel_id.0,
})
.await?;
Self::handle_loaded_messages(
this.clone(),
user_store.clone(),
rpc.clone(),
response.messages,
response.done,
cx,
)
.await?;
let pending_messages = this.read_with(cx, |this, _| {
this.pending_messages().cloned().collect::<Vec<_>>()
})?;
for pending_message in pending_messages {
let request = rpc.request(proto::SendChannelMessage {
channel_id: channel_id.0,
body: pending_message.body,
mentions: mentions_to_proto(&pending_message.mentions),
nonce: Some(pending_message.nonce.into()),
reply_to_message_id: pending_message.reply_to_message_id,
});
let response = request.await?;
let message = ChannelMessage::from_proto(
response.message.context("invalid message")?,
&user_store,
cx,
)
.await?;
this.update(cx, |this, cx| {
this.insert_messages(SumTree::from_item(message, &()), cx);
})?;
}
anyhow::Ok(())
}
.log_err()
.await
})
.detach();
}
pub fn message_count(&self) -> usize {
self.messages.summary().count
}
pub fn messages(&self) -> &SumTree<ChannelMessage> {
&self.messages
}
pub fn message(&self, ix: usize) -> &ChannelMessage {
let mut cursor = self.messages.cursor::<Count>(&());
cursor.seek(&Count(ix), Bias::Right);
cursor.item().unwrap()
}
pub fn acknowledge_message(&mut self, id: u64) {
if self.acknowledged_message_ids.insert(id) {
self.rpc
.send(proto::AckChannelMessage {
channel_id: self.channel_id.0,
message_id: id,
})
.ok();
}
}
pub fn messages_in_range(&self, range: Range<usize>) -> impl Iterator<Item = &ChannelMessage> {
let mut cursor = self.messages.cursor::<Count>(&());
cursor.seek(&Count(range.start), Bias::Right);
cursor.take(range.len())
}
pub fn pending_messages(&self) -> impl Iterator<Item = &ChannelMessage> {
let mut cursor = self.messages.cursor::<ChannelMessageId>(&());
cursor.seek(&ChannelMessageId::Pending(0), Bias::Left);
cursor
}
async fn handle_message_sent(
this: Entity<Self>,
message: TypedEnvelope<proto::ChannelMessageSent>,
mut cx: AsyncApp,
) -> Result<()> {
let user_store = this.read_with(&cx, |this, _| this.user_store.clone())?;
let message = message.payload.message.context("empty message")?;
let message_id = message.id;
let message = ChannelMessage::from_proto(message, &user_store, &mut cx).await?;
this.update(&mut cx, |this, cx| {
this.insert_messages(SumTree::from_item(message, &()), cx);
cx.emit(ChannelChatEvent::NewMessage {
channel_id: this.channel_id,
message_id,
})
})?;
Ok(())
}
async fn handle_message_removed(
this: Entity<Self>,
message: TypedEnvelope<proto::RemoveChannelMessage>,
mut cx: AsyncApp,
) -> Result<()> {
this.update(&mut cx, |this, cx| {
this.message_removed(message.payload.message_id, cx)
})?;
Ok(())
}
async fn handle_message_updated(
this: Entity<Self>,
message: TypedEnvelope<proto::ChannelMessageUpdate>,
mut cx: AsyncApp,
) -> Result<()> {
let user_store = this.read_with(&cx, |this, _| this.user_store.clone())?;
let message = message.payload.message.context("empty message")?;
let message = ChannelMessage::from_proto(message, &user_store, &mut cx).await?;
this.update(&mut cx, |this, cx| {
this.message_update(
message.id,
message.body,
message.mentions,
message.edited_at,
cx,
)
})?;
Ok(())
}
fn insert_messages(&mut self, messages: SumTree<ChannelMessage>, cx: &mut Context<Self>) {
if let Some((first_message, last_message)) = messages.first().zip(messages.last()) {
let nonces = messages
.cursor::<()>(&())
.map(|m| m.nonce)
.collect::<HashSet<_>>();
let mut old_cursor = self
.messages
.cursor::<Dimensions<ChannelMessageId, Count>>(&());
let mut new_messages = old_cursor.slice(&first_message.id, Bias::Left);
let start_ix = old_cursor.start().1.0;
let removed_messages = old_cursor.slice(&last_message.id, Bias::Right);
let removed_count = removed_messages.summary().count;
let new_count = messages.summary().count;
let end_ix = start_ix + removed_count;
new_messages.append(messages, &());
let mut ranges = Vec::<Range<usize>>::new();
if new_messages.last().unwrap().is_pending() {
new_messages.append(old_cursor.suffix(), &());
} else {
new_messages.append(
old_cursor.slice(&ChannelMessageId::Pending(0), Bias::Left),
&(),
);
while let Some(message) = old_cursor.item() {
let message_ix = old_cursor.start().1.0;
if nonces.contains(&message.nonce) {
if ranges.last().is_some_and(|r| r.end == message_ix) {
ranges.last_mut().unwrap().end += 1;
} else {
ranges.push(message_ix..message_ix + 1);
}
} else {
new_messages.push(message.clone(), &());
}
old_cursor.next();
}
}
drop(old_cursor);
self.messages = new_messages;
for range in ranges.into_iter().rev() {
cx.emit(ChannelChatEvent::MessagesUpdated {
old_range: range,
new_count: 0,
});
}
cx.emit(ChannelChatEvent::MessagesUpdated {
old_range: start_ix..end_ix,
new_count,
});
cx.notify();
}
}
fn message_removed(&mut self, id: u64, cx: &mut Context<Self>) {
let mut cursor = self.messages.cursor::<ChannelMessageId>(&());
let mut messages = cursor.slice(&ChannelMessageId::Saved(id), Bias::Left);
if let Some(item) = cursor.item()
&& item.id == ChannelMessageId::Saved(id)
{
let deleted_message_ix = messages.summary().count;
cursor.next();
messages.append(cursor.suffix(), &());
drop(cursor);
self.messages = messages;
// If the message that was deleted was the last acknowledged message,
// replace the acknowledged message with an earlier one.
self.channel_store.update(cx, |store, _| {
let summary = self.messages.summary();
if summary.count == 0 {
store.set_acknowledged_message_id(self.channel_id, None);
} else if deleted_message_ix == summary.count
&& let ChannelMessageId::Saved(id) = summary.max_id
{
store.set_acknowledged_message_id(self.channel_id, Some(id));
}
});
cx.emit(ChannelChatEvent::MessagesUpdated {
old_range: deleted_message_ix..deleted_message_ix + 1,
new_count: 0,
});
}
}
fn message_update(
&mut self,
id: ChannelMessageId,
body: String,
mentions: Vec<(Range<usize>, u64)>,
edited_at: Option<OffsetDateTime>,
cx: &mut Context<Self>,
) {
let mut cursor = self.messages.cursor::<ChannelMessageId>(&());
let mut messages = cursor.slice(&id, Bias::Left);
let ix = messages.summary().count;
if let Some(mut message_to_update) = cursor.item().cloned() {
message_to_update.body = body;
message_to_update.mentions = mentions;
message_to_update.edited_at = edited_at;
messages.push(message_to_update, &());
cursor.next();
}
messages.append(cursor.suffix(), &());
drop(cursor);
self.messages = messages;
cx.emit(ChannelChatEvent::UpdateMessage {
message_ix: ix,
message_id: id,
});
cx.notify();
}
}
async fn messages_from_proto(
proto_messages: Vec<proto::ChannelMessage>,
user_store: &Entity<UserStore>,
cx: &mut AsyncApp,
) -> Result<SumTree<ChannelMessage>> {
let messages = ChannelMessage::from_proto_vec(proto_messages, user_store, cx).await?;
let mut result = SumTree::default();
result.extend(messages, &());
Ok(result)
}
impl ChannelMessage {
pub async fn from_proto(
message: proto::ChannelMessage,
user_store: &Entity<UserStore>,
cx: &mut AsyncApp,
) -> Result<Self> {
let sender = user_store
.update(cx, |user_store, cx| {
user_store.get_user(message.sender_id, cx)
})?
.await?;
let edited_at = message.edited_at.and_then(|t| -> Option<OffsetDateTime> {
if let Ok(a) = OffsetDateTime::from_unix_timestamp(t as i64) {
return Some(a);
}
None
});
Ok(ChannelMessage {
id: ChannelMessageId::Saved(message.id),
body: message.body,
mentions: message
.mentions
.into_iter()
.filter_map(|mention| {
let range = mention.range?;
Some((range.start as usize..range.end as usize, mention.user_id))
})
.collect(),
timestamp: OffsetDateTime::from_unix_timestamp(message.timestamp as i64)?,
sender,
nonce: message.nonce.context("nonce is required")?.into(),
reply_to_message_id: message.reply_to_message_id,
edited_at,
})
}
pub fn is_pending(&self) -> bool {
matches!(self.id, ChannelMessageId::Pending(_))
}
pub async fn from_proto_vec(
proto_messages: Vec<proto::ChannelMessage>,
user_store: &Entity<UserStore>,
cx: &mut AsyncApp,
) -> Result<Vec<Self>> {
let unique_user_ids = proto_messages
.iter()
.map(|m| m.sender_id)
.collect::<HashSet<_>>()
.into_iter()
.collect();
user_store
.update(cx, |user_store, cx| {
user_store.get_users(unique_user_ids, cx)
})?
.await?;
let mut messages = Vec::with_capacity(proto_messages.len());
for message in proto_messages {
messages.push(ChannelMessage::from_proto(message, user_store, cx).await?);
}
Ok(messages)
}
}
pub fn mentions_to_proto(mentions: &[(Range<usize>, UserId)]) -> Vec<proto::ChatMention> {
mentions
.iter()
.map(|(range, user_id)| proto::ChatMention {
range: Some(proto::Range {
start: range.start as u64,
end: range.end as u64,
}),
user_id: *user_id,
})
.collect()
}
impl sum_tree::Item for ChannelMessage {
type Summary = ChannelMessageSummary;
fn summary(&self, _cx: &()) -> Self::Summary {
ChannelMessageSummary {
max_id: self.id,
count: 1,
}
}
}
impl Default for ChannelMessageId {
fn default() -> Self {
Self::Saved(0)
}
}
impl sum_tree::Summary for ChannelMessageSummary {
type Context = ();
fn zero(_cx: &Self::Context) -> Self {
Default::default()
}
fn add_summary(&mut self, summary: &Self, _: &()) {
self.max_id = summary.max_id;
self.count += summary.count;
}
}
impl<'a> sum_tree::Dimension<'a, ChannelMessageSummary> for ChannelMessageId {
fn zero(_cx: &()) -> Self {
Default::default()
}
fn add_summary(&mut self, summary: &'a ChannelMessageSummary, _: &()) {
debug_assert!(summary.max_id > *self);
*self = summary.max_id;
}
}
impl<'a> sum_tree::Dimension<'a, ChannelMessageSummary> for Count {
fn zero(_cx: &()) -> Self {
Default::default()
}
fn add_summary(&mut self, summary: &'a ChannelMessageSummary, _: &()) {
self.0 += summary.count;
}
}
impl<'a> From<&'a str> for MessageParams {
fn from(value: &'a str) -> Self {
Self {
text: value.into(),
mentions: Vec::new(),
reply_to_message_id: None,
}
}
}

View File

@@ -1,6 +1,6 @@
mod channel_index;
use crate::{ChannelMessage, channel_buffer::ChannelBuffer, channel_chat::ChannelChat};
use crate::channel_buffer::ChannelBuffer;
use anyhow::{Context as _, Result, anyhow};
use channel_index::ChannelIndex;
use client::{ChannelId, Client, ClientSettings, Subscription, User, UserId, UserStore};
@@ -41,7 +41,6 @@ pub struct ChannelStore {
outgoing_invites: HashSet<(ChannelId, UserId)>,
update_channels_tx: mpsc::UnboundedSender<proto::UpdateChannels>,
opened_buffers: HashMap<ChannelId, OpenEntityHandle<ChannelBuffer>>,
opened_chats: HashMap<ChannelId, OpenEntityHandle<ChannelChat>>,
client: Arc<Client>,
did_subscribe: bool,
channels_loaded: (watch::Sender<bool>, watch::Receiver<bool>),
@@ -63,10 +62,8 @@ pub struct Channel {
#[derive(Default, Debug)]
pub struct ChannelState {
latest_chat_message: Option<u64>,
latest_notes_version: NotesVersion,
observed_notes_version: NotesVersion,
observed_chat_message: Option<u64>,
role: Option<ChannelRole>,
}
@@ -196,7 +193,6 @@ impl ChannelStore {
channel_participants: Default::default(),
outgoing_invites: Default::default(),
opened_buffers: Default::default(),
opened_chats: Default::default(),
update_channels_tx,
client,
user_store,
@@ -362,89 +358,12 @@ impl ChannelStore {
)
}
pub fn fetch_channel_messages(
&self,
message_ids: Vec<u64>,
cx: &mut Context<Self>,
) -> Task<Result<Vec<ChannelMessage>>> {
let request = if message_ids.is_empty() {
None
} else {
Some(
self.client
.request(proto::GetChannelMessagesById { message_ids }),
)
};
cx.spawn(async move |this, cx| {
if let Some(request) = request {
let response = request.await?;
let this = this.upgrade().context("channel store dropped")?;
let user_store = this.read_with(cx, |this, _| this.user_store.clone())?;
ChannelMessage::from_proto_vec(response.messages, &user_store, cx).await
} else {
Ok(Vec::new())
}
})
}
pub fn has_channel_buffer_changed(&self, channel_id: ChannelId) -> bool {
self.channel_states
.get(&channel_id)
.is_some_and(|state| state.has_channel_buffer_changed())
}
pub fn has_new_messages(&self, channel_id: ChannelId) -> bool {
self.channel_states
.get(&channel_id)
.is_some_and(|state| state.has_new_messages())
}
pub fn set_acknowledged_message_id(&mut self, channel_id: ChannelId, message_id: Option<u64>) {
if let Some(state) = self.channel_states.get_mut(&channel_id) {
state.latest_chat_message = message_id;
}
}
pub fn last_acknowledge_message_id(&self, channel_id: ChannelId) -> Option<u64> {
self.channel_states.get(&channel_id).and_then(|state| {
if let Some(last_message_id) = state.latest_chat_message
&& state
.last_acknowledged_message_id()
.is_some_and(|id| id < last_message_id)
{
return state.last_acknowledged_message_id();
}
None
})
}
pub fn acknowledge_message_id(
&mut self,
channel_id: ChannelId,
message_id: u64,
cx: &mut Context<Self>,
) {
self.channel_states
.entry(channel_id)
.or_default()
.acknowledge_message_id(message_id);
cx.notify();
}
pub fn update_latest_message_id(
&mut self,
channel_id: ChannelId,
message_id: u64,
cx: &mut Context<Self>,
) {
self.channel_states
.entry(channel_id)
.or_default()
.update_latest_message_id(message_id);
cx.notify();
}
pub fn acknowledge_notes_version(
&mut self,
channel_id: ChannelId,
@@ -473,23 +392,6 @@ impl ChannelStore {
cx.notify()
}
pub fn open_channel_chat(
&mut self,
channel_id: ChannelId,
cx: &mut Context<Self>,
) -> Task<Result<Entity<ChannelChat>>> {
let client = self.client.clone();
let user_store = self.user_store.clone();
let this = cx.entity();
self.open_channel_resource(
channel_id,
"chat",
|this| &mut this.opened_chats,
async move |channel, cx| ChannelChat::new(channel, this, user_store, client, cx).await,
cx,
)
}
/// Asynchronously open a given resource associated with a channel.
///
/// Make sure that the resource is only opened once, even if this method
@@ -931,13 +833,6 @@ impl ChannelStore {
cx,
);
}
for message_id in message.payload.observed_channel_message_id {
this.acknowledge_message_id(
ChannelId(message_id.channel_id),
message_id.message_id,
cx,
);
}
for membership in message.payload.channel_memberships {
if let Some(role) = ChannelRole::from_i32(membership.role) {
this.channel_states
@@ -957,16 +852,6 @@ impl ChannelStore {
self.outgoing_invites.clear();
self.disconnect_channel_buffers_task.take();
for chat in self.opened_chats.values() {
if let OpenEntityHandle::Open(chat) = chat
&& let Some(chat) = chat.upgrade()
{
chat.update(cx, |chat, cx| {
chat.rejoin(cx);
});
}
}
let mut buffer_versions = Vec::new();
for buffer in self.opened_buffers.values() {
if let OpenEntityHandle::Open(buffer) = buffer
@@ -1094,7 +979,6 @@ impl ChannelStore {
self.channel_participants.clear();
self.outgoing_invites.clear();
self.opened_buffers.clear();
self.opened_chats.clear();
self.disconnect_channel_buffers_task = None;
self.channel_states.clear();
}
@@ -1131,7 +1015,6 @@ impl ChannelStore {
let channels_changed = !payload.channels.is_empty()
|| !payload.delete_channels.is_empty()
|| !payload.latest_channel_message_ids.is_empty()
|| !payload.latest_channel_buffer_versions.is_empty();
if channels_changed {
@@ -1181,13 +1064,6 @@ impl ChannelStore {
.update_latest_notes_version(latest_buffer_version.epoch, &version)
}
for latest_channel_message in payload.latest_channel_message_ids {
self.channel_states
.entry(ChannelId(latest_channel_message.channel_id))
.or_default()
.update_latest_message_id(latest_channel_message.message_id);
}
self.channels_loaded.0.try_send(true).log_err();
}
@@ -1251,29 +1127,6 @@ impl ChannelState {
.changed_since(&self.observed_notes_version.version))
}
fn has_new_messages(&self) -> bool {
let latest_message_id = self.latest_chat_message;
let observed_message_id = self.observed_chat_message;
latest_message_id.is_some_and(|latest_message_id| {
latest_message_id > observed_message_id.unwrap_or_default()
})
}
fn last_acknowledged_message_id(&self) -> Option<u64> {
self.observed_chat_message
}
fn acknowledge_message_id(&mut self, message_id: u64) {
let observed = self.observed_chat_message.get_or_insert(message_id);
*observed = (*observed).max(message_id);
}
fn update_latest_message_id(&mut self, message_id: u64) {
self.latest_chat_message =
Some(message_id.max(self.latest_chat_message.unwrap_or_default()));
}
fn acknowledge_notes_version(&mut self, epoch: u64, version: &clock::Global) {
if self.observed_notes_version.epoch == epoch {
self.observed_notes_version.version.join(version);

View File

@@ -1,9 +1,7 @@
use crate::channel_chat::ChannelChatEvent;
use super::*;
use client::{Client, UserStore, test::FakeServer};
use client::{Client, UserStore};
use clock::FakeSystemClock;
use gpui::{App, AppContext as _, Entity, SemanticVersion, TestAppContext};
use gpui::{App, AppContext as _, Entity, SemanticVersion};
use http_client::FakeHttpClient;
use rpc::proto::{self};
use settings::SettingsStore;
@@ -235,201 +233,6 @@ fn test_dangling_channel_paths(cx: &mut App) {
assert_channels(&channel_store, &[(0, "a".to_string())], cx);
}
#[gpui::test]
async fn test_channel_messages(cx: &mut TestAppContext) {
let user_id = 5;
let channel_id = 5;
let channel_store = cx.update(init_test);
let client = channel_store.read_with(cx, |s, _| s.client());
let server = FakeServer::for_client(user_id, &client, cx).await;
// Get the available channels.
server.send(proto::UpdateChannels {
channels: vec![proto::Channel {
id: channel_id,
name: "the-channel".to_string(),
visibility: proto::ChannelVisibility::Members as i32,
parent_path: vec![],
channel_order: 1,
}],
..Default::default()
});
cx.executor().run_until_parked();
cx.update(|cx| {
assert_channels(&channel_store, &[(0, "the-channel".to_string())], cx);
});
// Join a channel and populate its existing messages.
let channel = channel_store.update(cx, |store, cx| {
let channel_id = store.ordered_channels().next().unwrap().1.id;
store.open_channel_chat(channel_id, cx)
});
let join_channel = server.receive::<proto::JoinChannelChat>().await.unwrap();
server.respond(
join_channel.receipt(),
proto::JoinChannelChatResponse {
messages: vec![
proto::ChannelMessage {
id: 10,
body: "a".into(),
timestamp: 1000,
sender_id: 5,
mentions: vec![],
nonce: Some(1.into()),
reply_to_message_id: None,
edited_at: None,
},
proto::ChannelMessage {
id: 11,
body: "b".into(),
timestamp: 1001,
sender_id: 6,
mentions: vec![],
nonce: Some(2.into()),
reply_to_message_id: None,
edited_at: None,
},
],
done: false,
},
);
cx.executor().start_waiting();
// Client requests all users for the received messages
let mut get_users = server.receive::<proto::GetUsers>().await.unwrap();
get_users.payload.user_ids.sort();
assert_eq!(get_users.payload.user_ids, vec![6]);
server.respond(
get_users.receipt(),
proto::UsersResponse {
users: vec![proto::User {
id: 6,
github_login: "maxbrunsfeld".into(),
avatar_url: "http://avatar.com/maxbrunsfeld".into(),
name: None,
}],
},
);
let channel = channel.await.unwrap();
channel.update(cx, |channel, _| {
assert_eq!(
channel
.messages_in_range(0..2)
.map(|message| (message.sender.github_login.clone(), message.body.clone()))
.collect::<Vec<_>>(),
&[
("user-5".into(), "a".into()),
("maxbrunsfeld".into(), "b".into())
]
);
});
// Receive a new message.
server.send(proto::ChannelMessageSent {
channel_id,
message: Some(proto::ChannelMessage {
id: 12,
body: "c".into(),
timestamp: 1002,
sender_id: 7,
mentions: vec![],
nonce: Some(3.into()),
reply_to_message_id: None,
edited_at: None,
}),
});
// Client requests user for message since they haven't seen them yet
let get_users = server.receive::<proto::GetUsers>().await.unwrap();
assert_eq!(get_users.payload.user_ids, vec![7]);
server.respond(
get_users.receipt(),
proto::UsersResponse {
users: vec![proto::User {
id: 7,
github_login: "as-cii".into(),
avatar_url: "http://avatar.com/as-cii".into(),
name: None,
}],
},
);
assert_eq!(
channel.next_event(cx).await,
ChannelChatEvent::MessagesUpdated {
old_range: 2..2,
new_count: 1,
}
);
channel.update(cx, |channel, _| {
assert_eq!(
channel
.messages_in_range(2..3)
.map(|message| (message.sender.github_login.clone(), message.body.clone()))
.collect::<Vec<_>>(),
&[("as-cii".into(), "c".into())]
)
});
// Scroll up to view older messages.
channel.update(cx, |channel, cx| {
channel.load_more_messages(cx).unwrap().detach();
});
let get_messages = server.receive::<proto::GetChannelMessages>().await.unwrap();
assert_eq!(get_messages.payload.channel_id, 5);
assert_eq!(get_messages.payload.before_message_id, 10);
server.respond(
get_messages.receipt(),
proto::GetChannelMessagesResponse {
done: true,
messages: vec![
proto::ChannelMessage {
id: 8,
body: "y".into(),
timestamp: 998,
sender_id: 5,
nonce: Some(4.into()),
mentions: vec![],
reply_to_message_id: None,
edited_at: None,
},
proto::ChannelMessage {
id: 9,
body: "z".into(),
timestamp: 999,
sender_id: 6,
nonce: Some(5.into()),
mentions: vec![],
reply_to_message_id: None,
edited_at: None,
},
],
},
);
assert_eq!(
channel.next_event(cx).await,
ChannelChatEvent::MessagesUpdated {
old_range: 0..0,
new_count: 2,
}
);
channel.update(cx, |channel, _| {
assert_eq!(
channel
.messages_in_range(0..2)
.map(|message| (message.sender.github_login.clone(), message.body.clone()))
.collect::<Vec<_>>(),
&[
("user-5".into(), "y".into()),
("maxbrunsfeld".into(), "z".into())
]
);
});
}
fn init_test(cx: &mut App) -> Entity<ChannelStore> {
let settings_store = SettingsStore::test(cx);
cx.set_global(settings_store);

View File

@@ -75,7 +75,7 @@ util = { workspace = true, features = ["test-support"] }
windows.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
cocoa.workspace = true
objc2-foundation.workspace = true
[target.'cfg(any(target_os = "windows", target_os = "macos"))'.dependencies]
tokio-native-tls = "0.3"

View File

@@ -22,7 +22,7 @@ use futures::{
channel::oneshot, future::BoxFuture,
};
use gpui::{App, AsyncApp, Entity, Global, Task, WeakEntity, actions};
use http_client::{HttpClient, HttpClientWithUrl, http};
use http_client::{HttpClient, HttpClientWithUrl, http, read_proxy_from_env};
use parking_lot::RwLock;
use postage::watch;
use proxy::connect_proxy_stream;
@@ -31,7 +31,7 @@ use release_channel::{AppVersion, ReleaseChannel};
use rpc::proto::{AnyTypedEnvelope, EnvelopedMessage, PeerId, RequestMessage};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsSources, SettingsUi};
use settings::{Settings, SettingsKey, SettingsSources, SettingsUi};
use std::{
any::TypeId,
convert::TryFrom,
@@ -96,7 +96,8 @@ actions!(
]
);
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, SettingsUi)]
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, SettingsUi, SettingsKey)]
#[settings_key(None)]
pub struct ClientSettingsContent {
server_url: Option<String>,
}
@@ -107,8 +108,6 @@ pub struct ClientSettings {
}
impl Settings for ClientSettings {
const KEY: Option<&'static str> = None;
type FileContent = ClientSettingsContent;
fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
@@ -122,7 +121,8 @@ impl Settings for ClientSettings {
fn import_from_vscode(_vscode: &settings::VsCodeSettings, _current: &mut Self::FileContent) {}
}
#[derive(Default, Clone, Serialize, Deserialize, JsonSchema, SettingsUi)]
#[derive(Default, Clone, Serialize, Deserialize, JsonSchema, SettingsUi, SettingsKey)]
#[settings_key(None)]
pub struct ProxySettingsContent {
proxy: Option<String>,
}
@@ -132,9 +132,21 @@ pub struct ProxySettings {
pub proxy: Option<String>,
}
impl Settings for ProxySettings {
const KEY: Option<&'static str> = None;
impl ProxySettings {
pub fn proxy_url(&self) -> Option<Url> {
self.proxy
.as_ref()
.and_then(|input| {
input
.parse::<Url>()
.inspect_err(|e| log::error!("Error parsing proxy settings: {}", e))
.ok()
})
.or_else(read_proxy_from_env)
}
}
impl Settings for ProxySettings {
type FileContent = ProxySettingsContent;
fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
@@ -527,7 +539,8 @@ pub struct TelemetrySettings {
}
/// Control what info is collected by Zed.
#[derive(Default, Clone, Serialize, Deserialize, JsonSchema, Debug, SettingsUi)]
#[derive(Default, Clone, Serialize, Deserialize, JsonSchema, Debug, SettingsUi, SettingsKey)]
#[settings_key(key = "telemetry")]
pub struct TelemetrySettingsContent {
/// Send debug info like crash reports.
///
@@ -540,8 +553,6 @@ pub struct TelemetrySettingsContent {
}
impl settings::Settings for TelemetrySettings {
const KEY: Option<&'static str> = Some("telemetry");
type FileContent = TelemetrySettingsContent;
fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
@@ -691,7 +702,7 @@ impl Client {
#[cfg(any(test, feature = "test-support"))]
let mut rng = StdRng::seed_from_u64(0);
#[cfg(not(any(test, feature = "test-support")))]
let mut rng = StdRng::from_entropy();
let mut rng = StdRng::from_os_rng();
let mut delay = INITIAL_RECONNECTION_DELAY;
loop {
@@ -721,8 +732,9 @@ impl Client {
},
cx,
);
let jitter =
Duration::from_millis(rng.gen_range(0..delay.as_millis() as u64));
let jitter = Duration::from_millis(
rng.random_range(0..delay.as_millis() as u64),
);
cx.background_executor().timer(delay + jitter).await;
delay = cmp::min(delay * 2, MAX_RECONNECTION_DELAY);
} else {

View File

@@ -84,6 +84,10 @@ static DOTNET_PROJECT_FILES_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"^(global\.json|Directory\.Build\.props|.*\.(csproj|fsproj|vbproj|sln))$").unwrap()
});
#[cfg(target_os = "macos")]
static MACOS_VERSION_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(\s*\(Build [^)]*[0-9]\))").unwrap());
pub fn os_name() -> String {
#[cfg(target_os = "macos")]
{
@@ -108,19 +112,16 @@ pub fn os_name() -> String {
pub fn os_version() -> String {
#[cfg(target_os = "macos")]
{
use cocoa::base::nil;
use cocoa::foundation::NSProcessInfo;
unsafe {
let process_info = cocoa::foundation::NSProcessInfo::processInfo(nil);
let version = process_info.operatingSystemVersion();
gpui::SemanticVersion::new(
version.majorVersion as usize,
version.minorVersion as usize,
version.patchVersion as usize,
)
use objc2_foundation::NSProcessInfo;
let process_info = NSProcessInfo::processInfo();
let version_nsstring = unsafe { process_info.operatingSystemVersionString() };
// "Version 15.6.1 (Build 24G90)" -> "15.6.1 (Build 24G90)"
let version_string = version_nsstring.to_string().replace("Version ", "");
// "15.6.1 (Build 24G90)" -> "15.6.1"
// "26.0.0 (Build 25A5349a)" -> unchanged (Beta or Rapid Security Response; ends with letter)
MACOS_VERSION_REGEX
.replace_all(&version_string, "")
.to_string()
}
}
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
{

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