Compare commits

..

311 Commits

Author SHA1 Message Date
Richard Feldman
20c2a78510 Record some timings 2024-07-25 00:21:47 -04:00
Richard Feldman
f4c994d212 Reorganize indexing 2024-07-25 00:08:50 -04:00
Richard Feldman
c261e1011b Use db.clone() to fix a lifetime issue 2024-07-23 22:24:59 -04:00
Richard Feldman
0edb105d1e Split out more modules in semantic_index crate 2024-07-23 22:17:45 -04:00
Richard Feldman
3cef55d89f About to split out embedding index 2024-07-23 15:29:38 -04:00
Richard Feldman
678b6120fd Add a bunch of debug logging 2024-07-23 09:36:55 -04:00
Richard Feldman
533aa2719c Get summaries compiling 2024-07-23 08:01:41 -04:00
Richard Feldman
a07385e2a9 Trying futures::select! 2024-07-23 00:29:08 -04:00
Richard Feldman
4e5d6fa435 wip 2024-07-22 22:58:45 -04:00
Richard Feldman
31738f39f5 wip 2024-07-22 11:58:23 -04:00
Richard Feldman
cede792786 Add summaries crate 2024-07-22 09:47:17 -04:00
Richard Feldman
1be22b5f17 Summaries, but with cx problems 2024-07-22 09:12:26 -04:00
Richard Feldman
030a2ae77b wip 2024-07-22 09:10:51 -04:00
Floyd Wang
1ea363b020 Fix typo in font-weight setting story (#14958)
Release Notes:

- N/A
2024-07-22 07:49:27 -04:00
Antonio Scandurra
0155435142 Allow using a custom model when using zed.dev (#14933)
Release Notes:

- N/A
2024-07-22 12:25:53 +02:00
YeonGyu-Kim
a334c69e05 Add instructions for configuring linting in the Python documentation using Ruff extension (#14896)
Added documentation for #14198

I also suggest replacing format guides from `black` to `ruff` to unify
the tooling in the document.

Ruff is now widely used in the Python community, including
[fastapi](cd6e9db065/pyproject.toml (L213)).
It's compatible with black but a lot faster.

Release Notes:

- N/A
2024-07-22 11:59:42 +02:00
Kirill Bulatov
31d283932c Allow to input spaces in the outline panel filter input (#14951)
Release Notes:

- Fixed outline panel's filter not accepting spaces
2024-07-22 12:02:25 +03:00
Luke Naylor
0ef19dedd2 Correct escaping in snippets (#14912)
## Release Notes:

- Fixed issue with backslashes not appearing in snippets
([#14721](https://github.com/zed-industries/zed/issues/14721)),
motivated by a snippet provided by the latex LSP
([texlab](https://github.com/latex-lsp/texlab)) not working as intended
in Zed ([extension
issue](https://github.com/rzukic/zed-latex/issues/5)).

[Screencast from 2024-07-21
14-57-19.webm](https://github.com/user-attachments/assets/3c95a987-16e5-4132-8c96-15553966d4ac)

## Fix details:

Only $, }, \ can be escaped by a backslash as per [LSP spec (under
grammar
section)](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/\#snippet_syntax).
Technically, commas and pipes can also be escaped only in "choice"
tabstops but it does not look like they are implemented in Zed yet.

## Additional tests added for cases currently not covered:
- backslash not being used to escape anything (so just a normal
backslash)
- backslash escaping a backslash (so that the second does not escape
what follows it)

---------

Co-authored-by: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com>
2024-07-22 00:57:34 +02:00
Marshall Bowers
83f6a7f228 assistant: Use square buttons for the inline assist model selector (#14928)
This PR updates the model selector buttons in the inline assistant to
use `IconButtonShape::Square`.

Release Notes:

- N/A
2024-07-21 13:59:21 -04:00
Marshall Bowers
2d96bba61f assistant: Respect ui_font_weight setting for inline assist in the terminal (#14924)
This PR updates the terminal inline assist to respect the
`ui_font_weight` setting.

Release Notes:

- N/A
2024-07-21 13:09:25 -04:00
Marshall Bowers
54039162ac erlang: Add support for installing elp language server (#14923)
This PR updates the Erlang extension with support for installing the
[Erlang Language
Platform](https://github.com/WhatsApp/erlang-language-platform) (`elp`)
language server from the GitHub Release assets.

Release Notes:

- N/A
2024-07-21 12:42:21 -04:00
Marshall Bowers
45b45155d4 Treat tsconfig.json as JSONC (#14920)
This PR updates the default settings to treat `tsconfig.json` files as
JSONC.

Resolves https://github.com/zed-industries/zed/issues/14906.

Release Notes:

- TypeScript's `tsconfig.json` files are now treated as JSONC.
2024-07-21 12:17:16 -04:00
Ryan Hawkins
a4baba7edd Add button to copy SHA from Git blame (#14883)
The git blame dialog doesn't give the user a way to quickly copy the SHA
of the associated commit for a line. Adding an option for users to
quickly access this SHA is helpful for user's to do any more git-fu they
might need, such as viewing the full changes themselves within git,
checking the commit out, bisecting off the commit, etc.

This is also very handy for user's of self-hosted git providers.
Determining what provider a self-hosted repository is using could be
quite difficult and this presents an easy option to allow users to look
up more about a commit without having to memorize the short SHA.

Release Notes:

- Added a button to copy the SHA from a Git blame entry.

<img width="1552" alt="A screenshot showing the new copy SHA button
within the Zed editor's inline blame "
src="https://github.com/user-attachments/assets/9365950d-3a3f-4c11-b119-ab02654f5669">

---------

Co-authored-by: Marshall Bowers <elliott.codes@gmail.com>
2024-07-21 12:02:16 -04:00
Marshall Bowers
cb2c334358 Use defaults for unchanged TextStyle fields (#14918)
This PR updates a number of spots where we were setting all of the
`TextStyle` fields even if we were not changing the values from the
defaults.

We now use `..Default::default()`.

Release Notes:

- N/A
2024-07-21 11:55:45 -04:00
Max Brunsfeld
e8bcc412b5 Fix usability issues with ssh connection modal (#14917)
Release Notes:

- N/A
2024-07-21 08:43:59 -07:00
Fabian Bergström
7b88fc5cda erlang: Add Erlang Language Platform support (#14879)
Added support for the [Erlang Language
Platform](https://whatsapp.github.io/erlang-language-platform/) language
server to the Erlang extension.

Release Notes:

- N/A

Co-authored-by: Marshall Bowers <elliott.codes@gmail.com>
2024-07-21 11:38:24 -04:00
Marshall Bowers
2f3df9fd93 erlang: Update structure to accommodate multiple language servers (#14915)
This PR updates the structure of the Erlang extension to accommodate
multiple language servers.

Release Notes:

- N/A
2024-07-21 11:21:52 -04:00
Marshall Bowers
7d063aa10b erlang: Upgrade zed_extension_api to v0.0.6 (#14914)
This PR upgrades the Erlang extension to use v0.0.6 of the
`zed_extension_api`.

Release Notes:

- N/A
2024-07-21 10:59:05 -04:00
张小白
9c26d07f7a Ensure ExtensionBuilder respects the proxy settings (#14899)
Release Notes:

- N/A

---------

Co-authored-by: Marshall Bowers <elliott.codes@gmail.com>
2024-07-21 10:46:43 -04:00
Marshall Bowers
0a9d50bf01 http: Refactor construction of HTTP clients with a proxy (#14911)
This PR refactors the `http` crate to expose a better way of
constructing an `HttpClient` that contains a proxy.

Release Notes:

- N/A
2024-07-21 10:15:38 -04:00
Marshall Bowers
c7331b41e9 gpui: Include image URI in ImageCacheError::BadStatus (#14910)
This PR updates the `ImageCacheError::BadStatus` variant to include the
URI of the image that failed to load.

This helps contextualize the resulting error logs.

Release Notes:

- N/A
2024-07-21 10:13:31 -04:00
Mag Mell
70f7f2d2da theme_importer: Output logs to stderr (#14890)
Will allow writing directly to a file without logging via `cargo run -p
theme_importer -- /path/to/file`

Release Notes:

- N/A
2024-07-21 08:53:37 -04:00
Kyle Kelley
cd9b25d827 repl: Increase accuracy of error output line height (#14880) 2024-07-20 15:59:54 -07:00
Kyle Kelley
781633fb1a repl: Ensure that the output's computed line height is at least 1 (#14877) 2024-07-20 15:59:28 -07:00
Kyle Kelley
6dfb0a4a70 repl: Push button to clear outputs (#14873) 2024-07-20 11:32:03 -07:00
claytonrcarter
a1670551bf Fix description of -l flag in bundle-mac (#14864)
This removes mention of "copy bundle to `/Applications`" from the help
text for `bundle-mac` because, as far as I can tell, the `-l` flag only
controls the build, not the copy/install. (The copy/install is
controlled by using the `-i` flag in conjunction with `-l`.)


Release Notes:

- N/A
2024-07-20 19:16:54 +03:00
Piotr Osiewicz
71cbfc65b1 Ruff: pass initialization_options from settings (#14866)
No version bump, as the extension is not out yet.
Release Notes:

- N/A
2024-07-20 16:09:53 +02:00
Piotr Osiewicz
1218a846c1 extensions: Add Ruff extension (#14198)
Release Notes:

- Added extension for [Ruff](https://docs.astral.sh/ruff/), an extremely fast Python linter and code formatter, written in Rust.
2024-07-20 15:18:02 +02:00
versecafe
48c253feb8 Expand terminal menu actions (#14828)
<img width="422" alt="image"
src="https://github.com/user-attachments/assets/73195894-81a7-4b8e-b5cf-ae60bf5b1fb9">

Release Notes:

- Added `Copy`, `Paste`, `Select All`, & `New Terminal` into terminal's context menu
2024-07-20 12:20:53 +03:00
Kevin Wang
46b7fa9bcb Add Sign Out link for Supermaven (#14834)
Adds a menu item to sign out from a linked Supermaven account.


![image](https://github.com/user-attachments/assets/6af3c39f-9ca4-4ac2-a5c0-c7cb3c3aaac2)


Release Notes:

- Added the ability to sign out of a Supermaven account ([#12715(https://github.com/zed-industries/zed/issues/12715))
2024-07-20 03:53:24 +03:00
Max Brunsfeld
022e662815 Start work on showing progress when initializing ssh remoting 2024-07-19 17:25:28 -07:00
Max Brunsfeld
d89e2592a1 Fix file name conflict when downloading app update (#14847)
This fixes broken auto-updates on nightly. Unfortunately, nightly users
will need to re-download.

Release Notes:

- N/A
2024-07-19 16:33:41 -07:00
Fabian
a072caab0b node_runtime: Bump downloaded Node.js version to Current (Jod) (#14687)
This PR bumps the hard-coded Node.js version from v18.x (Hydrogen), which was LTS until October 2023, to v22.x (Jod) which will be the next LTS release in October 2024.

Release Notes:

- Updated Zed's node version (v18.x -> v22.x)
2024-07-20 01:18:56 +03:00
Max Brunsfeld
fbe30c6f2e Fixes for SSH remoting infrastructure (#14844)
* Fixed mis-named macOS remote server archives in actions and packaging
scripts
* Fixed an issue with the ask pass script on linux
* Download nightly versions of remote servers in dev mode (not stable)

Release Notes:

- N/A
2024-07-19 15:08:10 -07:00
Marshall Bowers
a5b8094082 editor: Implement From instead of Into for converting BlockIds to ElementIds (#14839)
This PR replaces the `Into<ElementId> for BlockId` implementation with
`From<BlockId> for ElementId`.

This keeps in line with Rust's guidance for preferring implementing
`From`, and gives us more flexibility when converting.

Release Notes:

- N/A
2024-07-19 16:24:12 -04:00
Conrad Irwin
d2efa12e16 vim: Fix gv after actions (#14829)
Fixes: #13720

Co-Authored-By: <tobbe@tlundberg.com>



Release Notes:

- vim: Fixed `gv` after `y`, `d`, etc.
([#13760](https://github.com/zed-industries/zed/issues/13760)).
2024-07-19 13:26:55 -06:00
Marshall Bowers
5e635b8914 ui: Remove absolute positioning for tab slots (#14836)
This PR reworks the `Tab` component to not use absolute positioning in
order to position the tab slots.

This should make any further adjustments we want to make to the spacing
easier to do.

Release Notes:

- N/A
2024-07-19 15:11:27 -04:00
Jason Lee
0a02691778 Fix tooltips sometimes continuously displaying when the button is selected (#14832)
Release Notes:

- Fixed sometime tooltip will continuously display when the button is
selected.

---

@mrnugget The #13857 This change has led into a bug, the selected item
before tooltip will continuous display if there are no other tooltips.



https://github.com/user-attachments/assets/06b4a9a4-dede-4c18-b020-e20b6090341f
2024-07-19 12:49:08 -06:00
Conrad Irwin
1dc4d4200f Add command aliases (#14826)
Co-Authored-By: <tobbe@tlundberg.com>

Release Notes:

- Added `"command_aliases"` setting to let you abbreviate commands
2024-07-19 12:48:48 -06:00
Max Brunsfeld
b22718e643 Fix log file path for dsymutil in bundle-mac 2024-07-19 11:35:31 -07:00
Max Brunsfeld
bc16c2f85d Fix error in bundle-mac 2024-07-19 11:22:46 -07:00
Max Brunsfeld
1805986d82 Suppress noisy output from dsymutil in bundle-mac 2024-07-19 11:22:46 -07:00
Marshall Bowers
ee0dfe9c44 elixir: Make start_lexical.sh executable (#14831)
This PR fixes an issue in the Lexical language server installation where
the `start_lexical.sh` script was not being made executable when
installed from GitHub.

Release Notes:

- N/A
2024-07-19 14:17:04 -04:00
Max Brunsfeld
f4074d784c Remove spurious self-hosted label for bundle-linux-arm job 2024-07-19 11:08:20 -07:00
Max Brunsfeld
e58db43ed8 Remove stray step from release nightly workflow 2024-07-19 10:49:34 -07:00
Richard Feldman
ec487d8f64 Extract completion provider crate (#14823)
We will soon need `semantic_index` to be able to use
`CompletionProvider`. This is currently impossible due to a cyclic crate
dependency, because `CompletionProvider` lives in the `assistant` crate,
which depends on `semantic_index`.

This PR breaks the dependency cycle by extracting two crates out of
`assistant`: `language_model` and `completion`.

Only one piece of logic changed: [this
code](922fcaf5a6 (diff-3857b3707687a4d585f1200eec4c34a7a079eae8d303b4ce5b4fce46234ace9fR61-R69)).
* As of https://github.com/zed-industries/zed/pull/13276, whenever we
ask a given completion provider for its available models, OpenAI
providers would go and ask the global assistant settings whether the
user had configured an `available_models` setting, and if so, return
that.
* This PR changes it so that instead of eagerly asking the assistant
settings for this info (the new crate must not depend on `assistant`, or
else the dependency cycle would be back), OpenAI completion providers
now store the user-configured settings as part of their struct, and
whenever the settings change, we update the provider.

In theory, this change should not change user-visible behavior...but
since it's the only change in this large PR that's more than just moving
code around, I'm mentioning it here in case there's an unexpected
regression in practice! (cc @amtoaer in case you'd like to try out this
branch and verify that the feature is still working the way you expect.)

Release Notes:

- N/A

---------

Co-authored-by: Marshall Bowers <elliott.codes@gmail.com>
2024-07-19 13:35:34 -04:00
Max Brunsfeld
b9a53ffa0b Add the ability to edit remote directories over SSH (#14530)
This is a first step towards allowing you to edit remote projects
directly over SSH. We'll start with a pretty bare-bones feature set, and
incrementally add further features.

### Todo

Distribution
* [x] Build nightly releases of `zed-remote-server` binaries
    * [x] linux (arm + x86)
    * [x] mac (arm + x86)
* [x] Build stable + preview releases of `zed-remote-server`
* [x] download and cache remote server binaries as needed when opening
ssh project
* [x] ensure server has the latest version of the binary


Auth
* [x] allow specifying password at the command line
* [x] auth via ssh keys
* [x] UI password prompt

Features
* [x] upload remote server binary to server automatically
* [x] opening directories
* [x] tracking file system updates
* [x] opening, editing, saving buffers
* [ ] file operations (rename, delete, create)
* [ ] git diffs
* [ ] project search

Release Notes:

- N/A

---------

Co-authored-by: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com>
2024-07-19 10:27:26 -07:00
Kyle Kelley
7733bf686b Repl reorder keybinding (#14824)
Ensures that the assistant keybinding for cmd-enter takes precedence
over `repl::Run`.

On Linux, `ctrl-enter` (the equivalent), issues `repl::Run` when in a
jupyter context.

Release Notes:

- N/A
2024-07-19 10:05:08 -07:00
Marshall Bowers
edddc68da6 client: Remove leftover http.rs file (#14822)
This PR removes an empty `http.rs` file that was leftover from a
previous PR.

Release Notes:

- N/A
2024-07-19 12:22:31 -04:00
Thorsten Ball
5de5d5bc56 go: Fix quoting of targeting expression for non-fish shells (#14821)
This fixes #14818.

The change in #14055 broke the tasks in `zsh` (and I suspect in `bash`,
`sh` too), because what was executed was NOT

    $ go test . -run '^TestThis$'

but instead this:

    $ go test . -run \'^TestThis$\'

And in `zsh` this means that `'` is part of the argument passed to `go`,
which means the targeting string is wrong.

Since the problem in `fish` doesn't seem to be the `^` but the `$`, we
can only escape that, which makes the escaped string work in `zsh` and
`fish` and `bash` (in which I've tested this change here)

Release Notes:

- go: Fix running single tests by changing the quoted expression in the
`go test` command to work again in `bash`, `zsh`, etc.
([#14818](https://github.com/zed-industries/zed/issues/14818))
2024-07-19 18:05:31 +02:00
Kyle Kelley
5467e18a5b repl: Refactor editor registration (#14819)
Cleans up action registration with the editors and also fixes a major
bug where only one workspace's panel was getting session info (due to my
not understanding that `cx.observe_new_views` is for the whole app).

Release Notes:

- N/A

Co-authored-by: Conrad <conrad@zed.dev>
2024-07-19 08:58:57 -07:00
Antonio Scandurra
4c7f1032a4 Allow an initial prompt to be associated with inline assist (#14816)
Release Notes:

- Added the ability to create custom inline assist bindings that
pre-fill a prompt from your keymap, e.g.:
    ```json
    [
        {
            "context": "Editor && mode == full",
            "bindings": {
                "ctrl-shift-enter": [
                    "assistant::InlineAssist",
                    { "prompt": "Build a snake game" }
                ]
            }
        }
    ]
    ```

---------

Co-authored-by: Nathan <nathan@zed.dev>
2024-07-19 17:13:48 +02:00
Antonio Scandurra
d61eaea4b9 Avoid losing focus when block decorations go offscreen (#14815)
Release Notes:

- Fixed a bug that caused focus to be lost when renames and inline
assists were scrolled offscreen.

---------

Co-authored-by: Nathan <nathan@zed.dev>
2024-07-19 17:04:18 +02:00
Richard Feldman
f5d50f2b1e Delete obsolete and unused remote_projects.rs (#14811)
See
https://github.com/zed-industries/zed/pull/11301#issuecomment-2234239630
for context

Release Notes:

- N/A
2024-07-19 08:50:49 -06:00
Kyle Kelley
be4b19babb repl: Create action to refresh kernelspecs (#14786)
Adds a command to refresh kernelspecs. Also added the kernelspecs to the
runtime panel when none are running. That's just for now until we move
out of the panel completely.

Release Notes:

- N/A
2024-07-19 07:42:18 -07:00
Marshall Bowers
272be98ec8 php: Bump to v0.1.2 (#14808)
This PR bumps the PHP extension to v0.1.2.

Changes:

- #14806

Release Notes:

- N/A
2024-07-19 09:13:23 -04:00
Marshall Bowers
e3d5eff858 Use ui::prelude::* in a few more spots (#14807)
This PR updates a couple files to make use of the `ui::prelude::*`
import.

Release Notes:

- N/A
2024-07-19 08:57:51 -04:00
Marshall Bowers
9cb17ac630 php: Respect LSP settings for Intelephense (#14806)
This PR updates the PHP extension with support for reading LSP settings
when using Intelephense as the language server.

Addresses #4258.

Release Notes:

- N/A
2024-07-19 08:51:44 -04:00
Jason Lee
fb541accb2 gpui: Update Menu name to use SharedString type to support more types (#14791)
Release Notes:

- N/A
2024-07-19 08:51:31 -04:00
Marshall Bowers
836f623800 Update icon positioning in tabs (#14804)
This PR updates the icon positioning in tabs to make give them even
spacing on either side.

Without file icons:

<img width="901" alt="Screenshot 2024-07-19 at 7 55 39 AM"
src="https://github.com/user-attachments/assets/89cc80cd-1323-424e-90a5-79d8586e8725">

With file icons:

<img width="956" alt="Screenshot 2024-07-19 at 7 55 52 AM"
src="https://github.com/user-attachments/assets/c5b47b4e-e6c3-4dbd-aeb3-fb09a0032105">

Release Notes:

- N/A
2024-07-19 08:04:57 -04:00
Kirill Bulatov
18c2e8f6ca Rework mouse handling of git hunks diff (#14727)
Closes https://github.com/zed-industries/zed/issues/12404

![Screenshot 2024-07-18 at 14 02
31](https://github.com/user-attachments/assets/a8addd22-0ed9-4f4b-852a-f347314c27ce)

![Screenshot 2024-07-18 at 14 02
43](https://github.com/user-attachments/assets/0daaed10-b9f3-4d4b-b8d7-189aa7e013b9)

Video:


https://github.com/user-attachments/assets/58e62527-da75-4017-a43e-a37803bd7b49


* now shows a context menu on left click instead of expanding the hunk
diff
* hunk diffs can be toggled with a single cmd-click still
* adds a X mark into gutter for every hunk expanded
* makes `editor::ToggleDiffHunk` to work inside the deleted hunk editors

Additionally, changes the way editor context menus behave when the
editor is scrolled — right click and diff hunks context menu now will
stick to the place it was invoked at, instead of staying onscreen at the
same pixel positions.

Release Notes:

- Improved the way git hunks diff can be toggled with mouse
([#12404](https://github.com/zed-industries/zed/issues/12404))

---------

Co-authored-by: Nate Butler <nate@zed.dev>
Co-authored-by: Conrad Irwin <conrad@zed.dev>
2024-07-19 13:48:04 +03:00
0x2CA
bf4645b1fe Fix vim <CTRL-J> slines downward linewise, Not Join Lines (#14796)
https://vimhelp.org/motion.txt.html#CTRL-J

Release Notes:

- vim: Added `ctrl-j` as a new binding that's equivalent to `j`.
2024-07-19 11:52:37 +02:00
Antonio Scandurra
4d177918c1 Start on adding support for editing via the assistant panel (#14795)
Note that this shouldn't have any visible user-facing behavior yet. The
feature is incomplete but we wanna merge early to avoid a long-running
branch.

Release Notes:

- N/A

---------

Co-authored-by: Nathan <nathan@zed.dev>
2024-07-19 11:13:15 +02:00
Conrad Irwin
87457f9ae8 Fix off-by-one errors in syntax highlighting (#14780)
In the case that a line ended with a 0-length run, we would get our
highlights offset by one position.

Release Notes:

- Fixed syntax highlights being offset from syntax in diagnostics
popovers.
2024-07-18 22:37:30 -06:00
Vishal Bhavsar
be45f32753 vim: Fix 'Y' to yank to end of line (#14783)
Instead of yanking the entire line.

Release Notes:

- vim: Updated `Y` to yank to end of line (like neovim)
https://github.com/zed-industries/zed/issues/14771
2024-07-18 22:34:40 -06:00
versecafe
18b5a87298 Add gpt-4o-mini as an available model (#14770)
Release Notes:

- Fixes #14769
2024-07-18 22:32:56 -06:00
Kyle Kelley
48211e8ce2 repl: Check process status and propagate to output (#14782)
<img width="582" alt="image"
src="https://github.com/user-attachments/assets/14bd321d-f5fc-4cc0-9386-f435423057ad">

Release Notes:

- N/A
2024-07-18 19:35:05 -07:00
Conrad Irwin
5008a388e6 Use -f in ssh remoting too (#14773)
Release Notes:

- N/A
2024-07-18 19:24:59 -06:00
versecafe
3c417864e6 typescript: Highlight using keyword (#14772)
Release Notes:

- Added syntax highlighting for the `using` keyword in TypeScript
([#14762](https://github.com/zed-industries/zed/issues/14762)).
2024-07-18 17:33:13 -04:00
Marshall Bowers
ad3055076d assistant: Allow /docs to perform JIT indexing when run (#14768)
This PR updates the `/docs` slash command with the ability to
just-in-time index a package when there are not yet any results in the
index.

When running a `/docs` slash command, we fist check to see if there are
any results in the index that would match the search.

If there are, we go ahead and return them, as we do today.

However, if there are not yet any results we kick off an indexing task
as part of the command execution to fetch the results.

Release Notes:

- N/A
2024-07-18 17:01:48 -04:00
Peter Tripp
7c63f26aa9 Add duplicate and support as core github issue labels (#14735) 2024-07-18 16:21:30 -04:00
Conrad Irwin
f15a441c9d Fix video rendering on docs (#14764)
Release Notes:

- N/A
2024-07-18 13:34:25 -06:00
Kyle Kelley
cb217381ce repl: Scroll down after running code (#14759)
Go to the next line after running code. Allows for fluid coding and
running.


https://github.com/user-attachments/assets/d11ac05d-7801-4191-b275-3b20302e54c5

Release Notes:

- N/A
2024-07-18 11:22:43 -07:00
Kevin Wang
862f5a0561 Handle supermaven account status messages (#14749)
Sets the account status state to allow the Supermaven button to move out
of the "Supermaven is initializing..." state. We also need to add the
ability to sign out and change tiers but I will do that in a separate
PR.

Release Notes:

- Improved Supermaven status messages
([#12715](https://github.com/zed-industries/zed/issues/12715)).
2024-07-18 11:22:30 -07:00
Hans
7d30175527 vim: Add repeat support for add_surround (#14746)
Fix: #14242

At present, we don't trigger the method `start_recording(cx)` to start
recording when typing add_surround, so it can't be repeated well, delete
and change actually don't increase, but when entering `d` and `c`, it
happens that these two operations are recorded, I think maybe we also
need to call `start_recording(cx)` when calling delete_surround and
change_surround, otherwise when the user modifies their shortcuts, these
two functions may not be supported by repeat

Release Notes:

- N/A
2024-07-18 11:54:59 -06:00
Hans
d044685706 vim: Adjust surrounding_markers method (#14752)
At present, when calculating some ranges, we take the `tuple_windows` to
iterate forward, which will cause some problems when the cursor is being
front, because `tuple_windows` iteration cannot iterate to the very
beginning, so there will be some cases that cannot be calculated, adjust
this method, and now it can calculate more perfectly, and the execution
speed is about the same

Release Notes:

- N/A
2024-07-18 11:53:51 -06:00
Joseph T. Lyons
0496d0db9a Add multibuffer edit video (#14757)
Release Notes:

- N/A
2024-07-18 13:45:06 -04:00
Marshall Bowers
c19e71f51e languages: Remove lingering Elm file (#14754)
This PR removes a leftover file from when Elm support was done natively.

Elm was extracted into an extension in #10432.

Release Notes:

- N/A
2024-07-18 12:41:18 -04:00
Marshall Bowers
f7ff9b0811 vue: Bump to v0.1.0 (#14748)
This PR bumps the Vue extension to v0.1.0.

Changes:

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

Release Notes:

- N/A
2024-07-18 11:39:30 -04:00
Marshall Bowers
be1ff8aee9 vue: Install a global version of TypeScript if not present in the project (#14747)
This PR updates the Vue extension with support for installing and using
its own copy of TypeScript if it can't find one in the project.

The way we resolve `typescript` is as follows:

- We check the project's `package.json` for `typescript` in either the
`devDependencies` or `dependencies`
- If found, we set the `typescript.tsdk` to
`node_modules/typescript/lib` to use the project's copy of TypeScript
- If not found, we install the latest version of `typescript` (if not
already downloaded) to the extension's `package.json` and use that
version for `typescript.tsdk`

This should resolve instances where Vue projects that do not have an
explicit `typescript` dependency—such as those using Vue with plain
JavaScript—fail to load the language server due to TypeScript not being
found.

Release Notes:

- N/A
2024-07-18 11:32:46 -04:00
Thorsten Ball
3a83fecea9 gpui: Prefer removable over integrated Metal devices (#14744)
For context, see:

-
https://github.com/zed-industries/zed/issues/5124#issuecomment-2227743811
-
https://github.com/zed-industries/zed/pull/14738#issuecomment-2236613976

Short version: on Intel MacBooks it's better to prefer integrated
(`is_low_poer()`) GPUs, except when a user has an eGPU plugged-in, in
which case they very likely want to prefer that.

Before this change, we'd always prefer the integrated GPU, even if an
eGPU was available.

Now, with this change, if a user has

- eGPU
- integrated GPU
- discrete GPU

We'd first prefer eGPU, then integrated, then discrete.



Release Notes:

- Changed preference for GPUs on macOS so that eGPUs are now preferred
over integrated ones (and both of which are preferred over discrete
GPUs) on Intel Macs.
2024-07-18 16:52:38 +02:00
CharlesChen0823
bac4a0428d project_panel: Select the newly created file when copy/pasting a file (#14705)
Closes: #14361 

Release Notes:

- Improved project panel to select newly created file on copy/paste ([#14361](https://github.com/zed-industries/zed/issues/14361))
2024-07-18 17:26:33 +03:00
Kirill Bulatov
ed3d3dc690 Improve same line diagnostic rendering (#14741)
Follow-up of https://github.com/zed-industries/zed/pull/14515

Fixed certain visual artifacts, related to multi line diagnostics and
block toggle rendering.
Also enabled diagnostics toolbar controls for the experimental view too.


Release Notes:

- N/A
2024-07-18 17:22:38 +03:00
Marshall Bowers
24d9374744 Add text_color helper for tab contents (#14737)
This PR adds a `text_color` method to `TabContentParams` to more easily
compute the text color to be used for tab contents.

This consolidates a number of conditionals that were scattered all over
the place to give us a singular source of truth for these colors.

Release Notes:

- N/A
2024-07-18 09:27:05 -04:00
Marshall Bowers
5d751f232c collab_ui: Refine channel tab appearance (#14736)
This PR refines the appearance of the channel tabs.

We now display the channel icon in the tab's icon slot. We also now
adjust the icon based on whether the channel is public or members-only
(the same we do in the channel list):

<img width="214" alt="Screenshot 2024-07-18 at 9 02 00 AM"
src="https://github.com/user-attachments/assets/973d83c5-f045-4282-a43a-18e12ce93f78">

The `read-only` and `disconnected` states are now also shown in a
visually different style than the channel name:

<img width="247" alt="Screenshot 2024-07-18 at 9 01 13 AM"
src="https://github.com/user-attachments/assets/359f61cf-3b80-4a3f-8948-d705f6c24695">

Release Notes:

- Refined the appearance of channel tabs.
2024-07-18 09:18:09 -04:00
Piotr Osiewicz
3fb3148995 lsp: Use CompletionTriggerKind::TRIGGER_CHARACTER only for characters allowlisted by the server (#14734)
Fixes #13823


Release Notes:

- N/A
2024-07-18 14:53:31 +02:00
Thorsten Ball
76ce1a8f50 lsp: Use LspCommand.check_capabilities consistently (#14733)
This is a follow-up to #14666 in which I noticed that we don't need that
additional check, since each request will check whether it's supported
via the call to `check_capabilities` before sending the request.


Release Notes:

- N/A
2024-07-18 14:38:27 +02:00
Vitaly Slobodin
80558a3986 ruby: Bump to v0.0.8 (#14707)
Bump version of the Ruby extension to 0.0.8.

Changes:

- https://github.com/zed-industries/zed/pull/12642
- https://github.com/zed-industries/zed/pull/13216
- https://github.com/zed-industries/zed/pull/14661
- https://github.com/zed-industries/zed/pull/14693

Release Notes:

- N/A
2024-07-18 08:13:36 -04:00
Buzz
cdfadcc582 docs: Introduce command palette earlier (#14467)
Can't get to many of the settings on linux without opening it, and can't
know the default keystroke to get to it without knowing where to look
first, so its a chicken-n-egg problem of needing to use a
default-keystroke to set the key bindings, esp on linux.


Release Notes:

- N/A

---------

Co-authored-by: Thorsten Ball <mrnugget@gmail.com>
2024-07-18 14:09:43 +02:00
apricotbucket28
013c9f0420 linux: Implement local time zone support (#14610)
I decided to remove the GPUI APIs since `chrono` already provides this
functionality, and is already been used for this purpose in other parts
of the code (e.g.
[here](80402a6840/crates/zed/src/main.rs (L756))
or
[here](80402a6840/crates/ui/src/utils/format_distance.rs (L258)))

These usages end up calling the `time_format` crate, which takes in a
`UtcOffset`. It's probably cleaner to rewrite the crate to take in
`chrono` types, but that would require rewriting most of the code there.

Release Notes:

- linux: Use local time zone in chat and Git blame
2024-07-18 13:42:18 +02:00
Thorsten Ball
22a2cc6950 lsp: Check which code actions are supported before request (#14666)
This fixes https://github.com/zed-industries/zed/issues/13633 by not
sending `source.organizeImports` to the ESLint language server anymore.

Turns out that ESLint tells us through its capabilities that it doesn't
support that code action kind, but we ignored that.

What this code does is to check whether a given server supports specific
code action kinds.

It does this in two places:

1. When constructing the request: we now filter down the list of
   requested `kinds`, in case we can do so. If we can't filter down the
   list, we keep the previous behavior of sending the
   `language_server.code_action_kinds()`
2. Before sending the request: we now check whether the server even
   supports sending the request.

This fixes the issue by only sending actions to servers that support it.

I tested this with various language servers and setups and everything
still works (or works better). But of course there are a ton of
different combinations of language servers and code actions and file
types, so I couldn't test them all.

Release Notes:

- Fix ESLint language server adding comments on save if the
`source.organizeImports` code action was used on save. Zed now filters
out code actions sent to the language servers by checking whether they
are supported first.
([#13633](https://github.com/zed-industries/zed/issues/13633)).
2024-07-18 13:40:06 +02:00
Thorsten Ball
49effeb7ba assistant: Fixed "quote selection" with Vim visual line mode (#14713)
Previously, when using Vim mode and doing a line-wise visual selection,
the `assistant: quote selection` action would not work correctly, since
it would ignore that these were line-wise selections.

With this change, one can now select lines using visual line mode and
"quote selection works"

Release Notes:

- Fixes `assistant: quote selection` not working correctly when making
visual-line-mode selections in Vim mode.
2024-07-18 10:30:01 +02:00
rimuy
edda634ca5 typescript: Highlight infer keyword (#14696)
This PR adds syntax highlighting to TypeScript's
[`infer`](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#inferring-within-conditional-types)
keyword.

Theme used: Sandcastle

**Before:**

![image](https://github.com/user-attachments/assets/e082cc8c-2e12-4cfa-a641-40324dd93f31)

**After:**

![image](https://github.com/user-attachments/assets/6263b5b2-19c8-4b64-87b6-ceead947bc03)



Release Notes:

- Added syntax highlighting to TypeScript's `infer` keyword
([#14696](https://github.com/zed-industries/zed/pull/14696))
2024-07-18 10:42:17 +03:00
Elliot Thomas
75948e536f Fix worktree order serialization (#14676)
Fixes an issue in the serialization of workspaces that lead to incorrect
ordering of worktrees and refactors some other parts of the code to use
the new method.

Release Notes:

- N/A
2024-07-18 10:41:29 +03:00
Peter Tripp
eb7fe57453 Auto detect some DSLs (#14693)
- Brewfile, Vagrantfile, Puppetfile (ruby)
- Pipfile (toml)
2024-07-18 04:38:44 +00:00
Chung Wei Leong
6e08e49d30 docs: Fix tabs.file_icons default value (#14701)
Release Notes:

- Fixed `tabs.file_icons` default value in documentation, changed from
`true` to `false`
2024-07-17 23:03:57 -04:00
Marshall Bowers
2c8ead4423 Simplify constructing tab content that is purely textual (#14695)
This PR adds a streamlined way to consistently construct tab content for
items that only have textual content in the tabs.

The `Item` trait now has a new `tab_content_text` method that can be
used to return the textual content for the tab.

The `tab_content` method now has a default implementation that—unless
overridden—will construct a `Label` out of the text. This default
implementation also takes care of setting the label color based on the
active state of the tab, something that previously had to be repeated in
each `tab_content` implementation.

The majority of our tabs are now using `tab_content_text`.

Release Notes:

- N/A
2024-07-17 20:11:05 -04:00
Michael Angerman
ca2976559e docs: Fix jupyter spelling in the command jupyter kernelspec list (#14694)
jupyter was spelled wrong in the repl docs

Release Notes:

- N/A
2024-07-17 20:03:04 -04:00
Marshall Bowers
457da7b27c breadcrumbs: Use early return in set_active_pane_item (#14691)
This PR refactors the `set_active_pane_item` implementation for
`Breadcrumbs` to use an early return to avoid indenting the method body
more than necessary.

Release Notes:

- N/A
2024-07-17 18:58:44 -04:00
Marshall Bowers
a2424638f5 Improve multibuffer hints (#14690)
This PR improves the multibuffer hints added in #14668 to fix a few
issues.

The original implementation relied on bailing out early in `render` by
returning an `Empty` element. However, this had the unintended
side-effect that when initially opening a multibuffer (such as the
project search) there would be additional whitespace increasing the
height of the toolbar due to the empty element.

The reason we were doing this in the first place was because the hints
weren't updating when the item's breadcrumbs changed.

We're able to address this properly by using a subscription to the
item's events and recompute the visibility of the hint when the active
item's breadcrumbs change.

This also has the benefit of making the hints re-appear right away when
running the `welcome: reset hints` command with a multibuffer open.

Release Notes:

- N/A
2024-07-17 18:51:30 -04:00
Kyle Kelley
ba4fa17b83 Set the working directory according to the editor file path (#14688)
Kernels now launch in the same directory as the script invoking them,
similar to notebook behavior.


![image](https://github.com/user-attachments/assets/def86308-bea4-4fa3-8211-132a282a5ecc)


Release Notes:

- N/A
2024-07-17 15:37:47 -07:00
Conrad Irwin
f5f4578422 Tweak wording (#14686)
Co-Authored-By: Danilo <danilo@zed.dev>

Release Notes:

- N/A

Co-authored-by: Danilo <danilo@zed.dev>
2024-07-17 16:02:43 -06:00
Vitaly Slobodin
75775292b3 ruby: Add support for "rubocop" language server (#14661)
Hi, this pull request adds support for `rubocop` language server. I
noticed that `ruby-lsp` LS is becoming more popular but it still lacks
diagnostics support in Zed. To cover that missing feature, it could be
good to use `rubocop` LS to show diagnostics alongside with the running
Ruby LSP.

Release Notes:

- N/A

---------

Co-authored-by: Marshall Bowers <elliott.codes@gmail.com>
2024-07-17 17:29:42 -04:00
Justin Su
344e315174 Add -f to curl commands (#14667)
Release Notes:

- Updated curl commands with `-f` for improved error handling
([#14346](https://github.com/zed-industries/zed/issues/14346)).
2024-07-17 15:27:32 -06:00
Marshall Bowers
8ef53aafa2 Have Danger check the format of GitHub issue links (#14684)
This PR updates the Danger rules to check for GitHub issue links that
aren't in the desired format:

<img width="916" alt="Screenshot 2024-07-17 at 5 11 48 PM"
src="https://github.com/user-attachments/assets/c77d3c28-3b09-44aa-a97f-03c2400df2e6">

We don't yet check that the links are exactly formatted as expected,
just that they aren't incorrectly formatted in the way that people
typically get it wrong.

Release Notes:

- N/A
2024-07-17 17:15:47 -04:00
Marshall Bowers
00c3c02f7d Render other tab icons in the start slot (#14683)
This PR reworks the rendering for tab icons to allow us to render all of
the tab icons—not just file icons—in the tab's start slot.

The `Item` trait now has a separate `tab_icon` method that can be used
to indicate what icon should be shown for the tab.

Release Notes:

- N/A
2024-07-17 16:59:41 -04:00
Nazar Matus
2edf224599 docs: Add openSUSE Tumbleweed to Linux installation options (#14642)
Add openSUSE Tumbleweed to the list

Release Notes:

- N/A
2024-07-17 14:22:55 -06:00
Congyu
16a4c59be0 Fix right clicks changing vim mode (#14626)
Release Notes:

- Fixed right clicks changing vim mode (#14625).

before:


https://github.com/user-attachments/assets/97f4c971-6b59-412d-844a-23e0bc4289aa

after:


https://github.com/user-attachments/assets/3fc9adf3-2572-428d-8674-b3c8317e457e
2024-07-17 14:19:35 -06:00
Conrad Irwin
90a46b0463 linux: Fix autoupdate in non-standard locations (#14624)
Release Notes:

- linux: Fixed auto-update into custom tarball locations (#14291)
2024-07-17 14:15:28 -06:00
Conrad Irwin
09b216cf5e Make project search feel better (#14674)
Release Notes:

- Improved UX of project search

---------

Co-authored-by: Marshall <marshall@zed.dev>
2024-07-17 14:14:46 -06:00
Marshall Bowers
84b34677e2 Exclude dev extensions from auto-updates (#14680)
This PR makes it so dev extensions that are installed are excluded when
checking for extension updates.

We don't want to accidentally clobber dev extensions if the upstream
extension is deemed more "up-to-date".

Release Notes:

- Changed dev extensions to be excluded from extension auto-updates.
2024-07-17 15:35:09 -04:00
Marshall Bowers
5a090bc3f3 Dim the shared screen tab's icon when it is inactive (#14678)
This PR makes it so the icon of the shared screen tab is properly dimmed
when the tab is inactive.

Release Notes:

- Fixed an issue where the shared screen tab's icon would not render as
dimmed when the tab was inactive.
2024-07-17 15:25:56 -04:00
Conrad Irwin
4852e170ff Introducing multibuffers (#14668)
Co-Authored-By: Marshall <marshall@zed.dev>

Release Notes:

- Added a hint the first few times you open a multibuffer to explain
what is going on.

Co-authored-by: Marshall <marshall@zed.dev>
2024-07-17 13:54:52 -04:00
Joseph T Lyons
53bcc3649a Add PR author to release notes scraper script 2024-07-17 13:20:19 -04:00
Thorsten Ball
9241b11e1f Restore unsaved buffers on restart (#13546)
This adds the ability for Zed to restore unsaved buffers on restart. The
user is no longer prompted to save/discard/cancel when trying to close a
Zed window with dirty buffers in it. Instead those dirty buffers are
stored and restored on restart.

It does this by saving the contents of dirty buffers to the internal
SQLite database in which Zed stores other data too. On restart, if there
are dirty buffers in the database, they are restored.

On certain events (buffer changed, file saved, ...) Zed will serialize
these buffers, throttled to a 100ms, so that we don't overload the
machine by saving on every keystroke. When Zed quits, it waits until all
the buffers are serialized.


### Current limitations
- It does not persist undo-history (right now we don't persist/restore
undo-history regardless of dirty buffers or not)
- It does not restore buffers in windows without projects/worktrees.
Example: if you open a new window with `cmd-shift-n` and type something
in a buffer, this will _not_ be stored and you will be asked whether to
save/discard on quit. In the future, we want to fix this by also
restoring windows without projects/worktrees.

### Demo



https://github.com/user-attachments/assets/45c63237-8848-471f-8575-ac05496bba19



### Related tickets

I'm unsure about closing them, without also fixing the 2nd limitation:
restoring of worktree-less windows. So let's wait until that.

- https://github.com/zed-industries/zed/issues/4985
- https://github.com/zed-industries/zed/issues/4683

### Note on performance

- Serializing editing buffer (asynchronously on background thread) with
500k lines takes ~200ms on M3 Max. That's an extreme case and that
performance seems acceptable.

Release Notes:

- Added automatic restoring of unsaved buffers. Zed can now be closed
even if there are unsaved changes in buffers. One current limitation is
that this only works when having projects open, not single files or
empty windows with unsaved buffers. The feature can be turned off by
setting `{"session": {"restore_unsaved_buffers": false}}`.

---------

Co-authored-by: Bennet <bennet@zed.dev>
Co-authored-by: Antonio <antonio@zed.dev>
2024-07-17 18:10:20 +02:00
Joseph T Lyons
8e9e94de22 v0.146.x dev 2024-07-17 11:29:16 -04:00
Marshall Bowers
1607e4e0e1 elixir: Bump to v0.0.6 (#14657)
This PR bumps the Elixir extension to v0.0.6.

Changes:

- #14655

Release Notes:

- N/A
2024-07-17 11:14:52 -04:00
Marshall Bowers
ceffc7e1cf elixir: Respect LSP settings for Lexical (#14655)
This PR updates the Elixir extension with support for reading the LSP
settings when using Lexical as the language server.

Release Notes:

- N/A
2024-07-17 11:04:34 -04:00
Thorsten Ball
e69b995a3b zig: Bump to v0.1.4 (#14651)
This PR bumps the Zig extension to v0.1.4.

Changes:

- #14379

Release Notes:

- N/A
2024-07-17 10:41:12 -04:00
Marshall Bowers
f19b51c0b2 zig: Revert changes dependent on new zed_extension_api (#14652)
This PR reverts the changes to the Zig extension dependent on the new
`zed_extension_api` version so that we can publish the Zig extension.

Release Notes:

- N/A
2024-07-17 10:40:25 -04:00
Marshall Bowers
1d2d3b209e svelte: Bump to v0.0.3 (#14650)
This PR bumps the Svelte extension to v0.0.3.

Changes:

- #14614

Release Notes:

- N/A
2024-07-17 10:20:50 -04:00
Marshall Bowers
959fbd5e45 docs: Fix typo in Svelte docs (#14649)
This PR fixes a typo in the Svelte docs to reflect the fixes from
#14614.

Release Notes:

- N/A
2024-07-17 10:08:20 -04:00
Nemo
ff85f1d608 Fix default sublime tab navigation (#14427)
Co-authored-by: Peter Tripp <peter@zed.dev>
2024-07-17 10:07:46 -04:00
Peter Tripp
d1300b7a66 Linux Keybinding Improvements (#14600)
- Fixed ctrl-shift-d (duplicate line) conflict.
- Fixes #14458
- Remove some duplicated definitions
- Fix Expand/Shrink selection (was ctrl-shift-up/down, now alt-shift-left/right)
- Add `ctrl-f2` / `cmd-f2` as alias for `editor::SelectAllMatches` matching VSCode
- Moved multi-cursor (Insert cursor above / below) from ctrl-shift-up/down to alt-shift-up/down
2024-07-17 10:06:47 -04:00
Mathias
62f5503e93 svelte: Fix typo in LSP config for inlayHints (#14614)
9b51c5b177/packages/service/configuration.schema.json (L158)

Before:
![Screenshot from 2024-07-17
02-45-37](https://github.com/user-attachments/assets/15f67b7b-ed29-418a-b6a5-23601c1ad820)

After:
![Screenshot from 2024-07-17
02-38-37](https://github.com/user-attachments/assets/c6cb71fc-70f4-4ea3-91d4-a184342163b4)

Release Notes:

- N/A
2024-07-17 09:59:21 -04:00
Kyle Kelley
738d079aa7 docs: Remove extra backtick within repl docs (#14611) 2024-07-17 06:59:05 -07:00
Marshall Bowers
4feb994ad8 php: Bump to v0.1.1 (#14647)
This PR bumps the PHP extension to v0.1.1.

Changes:

- #14643

Release Notes:

- N/A
2024-07-17 09:40:00 -04:00
Marshall Bowers
40ed3b6977 php: Allow using intelephense from PATH (#14643)
This PR updates the PHP extension to use `intelephense` from the PATH,
if it exists.

Tested using the following Nix shell:

```sh
NIXPKGS_ALLOW_UNFREE=1 nix-shell -p php nodePackages_latest.intelephense
```

Resolves #11994.

Release Notes:

- N/A
2024-07-17 09:20:31 -04:00
Mathias
bd02f4fe28 Respect user preference for JS/TS on_type formatting (#14536)
Release Notes:

- Fix user preferences for JS/TS on_type formatting not being respected by VTSLS.
([#13733](https://github.com/zed-industries/zed/issues/13733),
[#14499](https://github.com/zed-industries/zed/issues/14499))
2024-07-17 11:11:00 +02:00
Conrad Irwin
85bc233920 vim: Add :bd/:bp/:bn (#14623)
Also refactor command to be less wierd

Release Notes:

- vim: Added :bd/:bn/:bp (#14457)
2024-07-16 23:06:08 -06:00
Conrad Irwin
33f68882c1 vim: Fix ctrl-d/u going to top bottom (#14620)
Release Notes:

- vim: Fixed ctrl-d/ctrl-u getting to top/bottom of buffer (#13250)
2024-07-16 22:56:44 -06:00
Conrad Irwin
acc9c2421b Vim rename via menu too? (#14617)
Follow up to #14320

Release Notes:

- N/A
2024-07-16 21:00:00 -06:00
Conrad Irwin
2cdfae9ce3 Show an initial empty keymap (#14609)
Release Notes:

- Added default content for the user keymap file.
2024-07-16 20:24:13 -06:00
Soroush Mirzaei
cf92b83c04 Update install CLI message for linux (#14616)
This PR updates the `cli: install` message for Linux. It initially threw
me off thinking that because `path_for_auxiliary_executable` is not
implemented for Linux it's failing and I thought it's a bug. Turns out
the CLI gets installed by the package manager and it's just named
something else.

I ended up only updating the message so it's more clear. If you don't
like the message, let me know :)

The old message:

![image](https://github.com/zed-industries/zed/assets/829535/1a02d08d-2c7a-452a-bfee-dc55d29c0c10)

The new message:

![image](https://github.com/user-attachments/assets/82052a43-1cf5-4b86-88e8-1c1f01a0ae3c)

@ConradIrwin thank you for taking the time and explaining it to me.

closes: #14118

Release Notes:

- N/A
2024-07-16 20:23:10 -06:00
Kyle Kelley
252737aef4 Provide installation instructions for the R extension (#14601)
Release Notes:

- N/A
2024-07-16 15:51:40 -07:00
Kyle Kelley
9c43450fef repl: Don't send KernelInfoRequest on launch (#14608)
Closes #14146. This is just for the time being before a networking
refactoring to split reads and writes on the ROUTER/DEALER ZeroMQ
sockets. Some kernels have not been responding with `kernel_info_reply`,
which ends up hanging our shell socket.

Release Notes:

- N/A

Release notes for the REPL feature will be part of its official launch.
2024-07-16 15:51:23 -07:00
Marshall Bowers
f8cfb50bb4 php: Bump to v0.1.0 (#14607)
This PR bumps the PHP extension to v0.1.0.

Changes:

- #14603
- #14604

Release Notes:

- N/A
2024-07-16 18:49:58 -04:00
Danilo Leal
9499adf50d docs: Adjust the note and warning callout design (#14605)
So they're more consistent and polished. Felt like they could be a bit more refined.

---

Release Notes:

- N/A
2024-07-16 19:48:02 -03:00
Marshall Bowers
696591ca55 php: Add Phpactor support (#14604)
This PR extends the PHP extension with
[Phpactor](https://github.com/phpactor/phpactor) support.

Phpactor seems to provide a better feature set out-of-the-box for free,
so it has been made the default PHP language server.

Thank you to @xtrasmal for informing us of Phpactor's existence!

Release Notes:

- N/A
2024-07-16 18:39:13 -04:00
Alexander Mankuta
f9b0792aa0 Update Configuration docs (#14029)
Release Notes:

- N/A

---

I'd like to help improve Configuration documentation.

Currently I'm often confused by the configuration doc. It's incomplete:
not all settings are documented. It's disorganized: some options are
grouped together but overall there's not much structure or logic to it.
It's inconsistent: some examples show only key and value, some—just the
closes object, and others full nesting. It's confusing: individual keys
are listed but it's hard to understand where in the config structure
they belong.

I suggest the following changes:

- Always specify the full path of the setting
- Document all settings Zed recognises
- List settings in alphabetical order of their full path
- Always use full nesting in examples 

This is an example, of what it might look like. It's first draft, too.
So I'm open to suggestions.

Please let me know if you're interested in this. The whole thing might
need a bit of effort so I'd like to know if this is something you might
want before doing all the work.

---------

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2024-07-16 16:11:55 -06:00
Marshall Bowers
60b22cf029 php: Upgrade zed_extension_api to v0.0.6 (#14603)
This PR upgrades the PHP extension to use v0.0.6 of the
`zed_extension_api`.

Release Notes:

- N/A
2024-07-16 17:53:43 -04:00
Conrad Irwin
1fe16f42ea Fix context in command palette from application menu (#14599)
Supercedes #14468

Release Notes:

- linux: Fixed the command palette when opened from the application menu
2024-07-16 15:14:18 -06:00
Peter Tripp
448ef538b3 More ignorable commits (#14596)
- More of https://github.com/zed-industries/zed/pull/13889
2024-07-16 17:09:50 -04:00
Kyle Kelley
f612c40bee repl: Don't run empty code submission (#14598)
Closes #14565.

Release Notes:

- N/A
2024-07-16 13:51:46 -07:00
Cappy Ishihara
0c6105992c Open URIs from the CLI, support for the zed:// URI scheme on Linux (#14104)
Allows Zed to open custom `zed://` links (redirects from
https://zed.dev/channels) on Linux used XDG MIME types.

This PR also allows the CLI to be able to open Zed (`zed://`) URIs
directly instead of executing the main executable in
`/usr/libexec/zed-editor`.


Release Notes:

- Linux: Allow `zed.dev/channel` (`zed://`) URIs to open on Linux
- CLI: Ability to open URIs from the command line

---------

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2024-07-16 14:49:15 -06:00
Congyu
64a796d436 Fix renaming sometimes not working in vim mode (#14320)
Disable vim key contexts during renaming, to fix renaming being
interfered with vim commands.

Release Notes:

- Fixed renaming sometimes not working in vim mode
[#14292](https://github.com/zed-industries/zed/issues/14292)
[#11882](https://github.com/zed-industries/zed/issues/11882).
- Fixed inline assistant sometimes not working in vim mode #11559

---------

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2024-07-16 14:46:03 -06:00
Conrad Irwin
76594ae5cd vim: fix escape while waiting (#14595)
Follow up from #14233

Release Notes:

- N/A
2024-07-16 14:08:05 -06:00
Robert Sturla
05de1dc8d2 Rename Linux desktop icon to match application name (#14437)
Release Notes:

- Updated the Linux manual installation docs to fix windows not matching
with desktop icons
([#14435](https://github.com/zed-industries/zed/issues/14435)).

The automated `curl | bash` installation script already renames the
`zed.desktop` file to match the window, so most users will not be facing
this issue. This is only affecting users who have downloaded and
extracted the files following the manual instructions.

Since the app ID and the desktop file name are not the same, open
windows are not being matched with the desktop icons, therefore showing
a default one. This PR changes the documentation to tell users they
should rename the `.desktop` file to `dev.zed.Zed.desktop`, and
therefore match the automated install script.

Before:

![image](https://github.com/user-attachments/assets/324b91e6-dae1-4902-b59c-b4f124a29820)

After:

![image](https://github.com/user-attachments/assets/169a4e8c-5c84-4400-8f0d-30cf478ca272)
2024-07-16 13:42:16 -06:00
Marshall Bowers
ef5305869f collab: Fix exact extension filtering (#14591)
This PR fixes the exact extension filtering introduced in #14588.

As we traversed the extensions we were always updating `exact_match`,
regardless of whether it matched the extension ID from the filter.

Release Notes:

- N/A
2024-07-16 15:18:48 -04:00
Kyle Kelley
8028e7f1b6 Refactor repl context menu (#14587) 2024-07-16 12:18:06 -07:00
Conrad Irwin
cb6fc11abc Rank exact extension ID matches higher in search results (#14588)
Release Notes:

- Improved relevance of extension search results

Co-authored-by: Marshall <marshall@zed.dev>
2024-07-16 12:33:28 -06:00
Conrad Irwin
cf8bd4a90a Remoting public alpha (#14541)
Release Notes:

- remoting: An alpha version of remote development is now available to
everyone. For more information on how to use it, and limitations see
https://zed.dev/docs/remote-development.
2024-07-16 12:05:55 -06:00
Conrad Irwin
62ab6e1a11 remoting: Allow Add/Remove remote folder (#14532)
Release Notes:

- remoting (alpha only): Allow add/remove folders to projects

---------

Co-authored-by: Max <max@zed.dev>
2024-07-16 12:01:59 -06:00
aohanhongzhi
be1387fee6 Fix text appearing twice after Chinese character input (#14558)
Release Notes:

- Fixed the issue where text appears twice in the editor after Chinese
Character input.([linux: Fix IME on
fcitx](https://github.com/zed-industries/zed/pull/14508)).

Before:

![zed2](https://github.com/user-attachments/assets/e387d70b-ca91-49c8-93e4-850f9e3ef227)

After Fixed:

![zed](https://github.com/user-attachments/assets/8307c12f-30a7-4e82-8c65-d0b53bb8cf44)
2024-07-16 10:54:53 -07:00
apricotbucket28
09459fa3a4 wayland: Fix drag and drop for paths with spaces (#14574)
This wasn't doing any proper parsing before, so `%20` or similar encoded
characters weren't handled correctly.

Release Notes:

- N/A
2024-07-16 10:42:57 -07:00
Marshall Bowers
400ae9c650 extensions_ui: Add feature upsell for Go (#14586)
This PR adds a feature upsell for Go when searching for it in the
extensions view.

Release Notes:

- N/A
2024-07-16 13:33:03 -04:00
Marshall Bowers
f9472ce90b extensions_ui: Add telemetry for docs click-throughs from feature upsells (#14583)
This PR adds some telemetry when the "View docs" button is clicked on a
feature upsell.

The goal here is to get a sense for how effective these upsells are at
getting users to click through if they can't find what they're looking
for.

Release Notes:

- N/A
2024-07-16 12:59:51 -04:00
Marshall Bowers
0556eddc21 docs: Add Git page (#14582)
This PR adds a basic Git page to the docs so that we have somewhere to
link to from the Git upsell within Zed.

Release Notes:

- N/A
2024-07-16 12:47:18 -04:00
Piotr Osiewicz
09c497f744 editor: Ensure allocation reuse (#14577)
In #14567 I claimed that the underlying allocation is reused. And it
was. At the time I've submitted a PR I was using `.filter_map(|x| x)`,
which got flagged by clippy as something that could be simplified to
`.flatten()` - that however broke the allocation reuse promise.

Thus, this PR goes back to using `filter_map` and additionally in debug
builds it performs checks for allocation reuse. With .flatten in place,
a bunch of unit test fail on that branch, so the checks do work.



Release Notes:

- N/A
2024-07-16 18:29:45 +02:00
Marshall Bowers
1b85438df9 docs: Fix casing of "REPL" in sidebar (#14579)
This PR fixes the casing of the REPL link in the sidebar.

Release Notes:

- N/A
2024-07-16 12:17:45 -04:00
Kyle Kelley
b3d0ac3e3c Show how to switch out kernels and discover them (#14531)
A few new doc changes for the repl feature.

Release Notes:

- N/A
2024-07-16 09:12:50 -07:00
Mag Mell
a51a9b0354 docs: Add AOSC OS Installation (#14575)
Added AOSC OS Installation docs

Release Notes:

- N/A
2024-07-16 12:07:17 -04:00
Conrad Irwin
6cf6614c48 Fix xkbcommon overflow more (#14571)
Release Notes:

- linux: Fixed overflow in xkbcommon-rs
2024-07-16 09:06:38 -06:00
Peter Tripp
0bf0152b74 Fix GoForward shortcut on non-US keyboard layouts (#14570)
- Fixes #14418. Originally broken by #13946
2024-07-16 11:00:15 -04:00
Piotr Osiewicz
d338e4a8a6 editor: Improve performance of edit coalescing (#14567)
# Background
In https://github.com/zed-industries/zed/issues/14408 we received a
repro for "Replace all" being slow, even after the work I did
https://github.com/zed-industries/zed/pull/13654. Admittedly #13654 was
a pretty straightforward change.
Under the profiler it turned out that we're spending *10 seconds* in
`memmove` on main thread. Ugh. Not great. The direct ancestor of the
memmove call was
66f0c390a8/crates/editor/src/display_map/tab_map.rs (L108-L119)

What?

# Accidental O(n^2)
We have a bunch of `consolidate_*_edits` functions which take a list of
Fold/Tab/Inlay/Wrap edits and merge consecutive edits if their ranges
overlap/are next to one another. The loop usually goes as follows:
```
while ix < edits.len() {
    let (prev_edits, next_edits) = edits.split_at_mut(ix);
    let prev_edit = prev_edits.last_mut().unwrap();
    let edit = &next_edits[0];
    if PREV_EDIT_CAN_BE_MERGED_WITH_CURRENT_ONE {
        MERGE_EDITS(prev_edit, edit);
        edits.remove(ix); // !!
    } else {
        ix += 1;
    }
}
```
The problem is the call to `.remove` - it has to shift all of the
consecutive elements in the `edits` vector! Thus, when processing the
edits from the original repro (where consolidation shrinks the edit list
from 210k entries to 30k), we mostly spend time moving entries in memory
around.

Thus, the original repro isn't really an issue with replace_all; it's
just that replace_all is one of the few tools available to the end user
that can apply large # of edits in a single transaction.

# Solution
In this PR I address the issue by rewriting the loop in a way that does
not throw items away via `.remove`. Instead, `Iterator::scan` is used,
which lets us achieve the same logic without having the pitfalls of
`.remove`s.
Crucially, **this code does not allocate a new backing buffer for
edits** (see [this article for
rationale](https://blog.polybdenum.com/2024/01/17/identifying-the-collect-vec-memory-leak-footgun.html));
with `vec.into_iter().scan().filter_map().collect()` we still use the
same underlying buffer as the one that's passed into `consolidate_*`
functions. In development I verified that by checking whether the
pointers to backing storage of a Vec are the same before and after the
consolidation.

# Results

### Before
Nightly 0.145.0
[66f0c390a8](66f0c390a8)


https://github.com/user-attachments/assets/8b0ad3bc-86d6-4f8a-850c-ebb86e8b3bfc

(~13s end-to-end)
### After


https://github.com/user-attachments/assets/366835db-1d84-4f95-8c74-b1506a9fabec

(~2s end-to-end)

The remaining lag is (I think) lies in `TextSummary` calculation and not
the consolidation itself. Thus, for the purposes of scoping this PR,
I'll tackle it separately.

Release Notes:

- Significantly improved performance of applying large quantities of
concurrent edits (e.g. when running "Replace all").
2024-07-16 15:53:29 +02:00
Thorsten Ball
751508b6a2 linux: Install dependencies when bundling nightly (#14566)
Release Notes:

- N/A
2024-07-16 15:44:24 +02:00
Thorsten Ball
f54f5dff65 linux: Build Nightly for ARM too (#14562)
Release Notes:

- N/A
2024-07-16 15:19:38 +02:00
Thorsten Ball
66f0c390a8 linux: Fix missing licenses in binary causing panics (#14561)
Turns out that the existing CI step for Nightly did create the licenses
and they have been baked into X86 builds ever since, because our
builders are stateful.

On ARM machines, the licenses wouldn't exist in the binary because we
called `script/generate-licenses` too late in `scripts/bundle-linux`,
after the binary had been created.

This removes the duplication and generates the licenses once, before the
binary is created.

Fixes #14302.

Release Notes:

- Fixed "View Dependency Licenses" (or `zed: open licenses`) crashing on
Linux ARM machines.
([#14302](https://github.com/zed-industries/zed/issues/14302)
2024-07-16 14:55:30 +02:00
Danilo Leal
fdd233eea9 Change the context menu and Copilot settings icon (#14501)
Felt the link we were using for menu items that open a browser page was
not the best. That one is most typically used for attachments within
scope, as opposed to opening external links. Noticed that via the
"Copilot Settings" menu, which also felt like it could have a bit more
descriptive label. Also reduced the size of the rendered icon in this
component.

---

Release Notes:

- N/A
2024-07-16 09:40:40 -03:00
Kirill Bulatov
bf7e474bbc Properly fix the tab icons 2024-07-16 14:46:16 +03:00
Kirill Bulatov
2a8cee57c9 Keep initial tab config without the icons (#14553)
Based on
https://zed-industries.slack.com/archives/C04S5TU0RSN/p1721125498461089

Release Notes:
- N/A
2024-07-16 13:43:17 +03:00
CharlesChen0823
ef20afa9a4 project_panel: Fixed open in split not working in project panel (#14535)
Release Notes:

- Fixed `cmd-double click` in project panel not opening a split view ([14465](https://github.com/zed-industries/zed/issues/14465))
2024-07-16 09:17:58 +03:00
Conrad Irwin
e413823ae7 Headless extensions (#14538)
Release Notes:

- remoting (alpha only): Fix extension installation
2024-07-16 00:08:56 -06:00
Kyle Kelley
e68d9f4625 Switch to muted color for kernel output labels (#14529)
Sets the text for "Executing...", "Queued", etc. to be `Color::Muted`

<img width="442" alt="image"
src="https://github.com/user-attachments/assets/10c27ce2-b804-41a3-a50e-0778b7e6cd09">


Release Notes:

- N/A
2024-07-15 18:20:45 -07:00
apricotbucket28
3407256aa3 linux: Tweak file chooser dialogs (#14526)
Mostly some small tweaks to the file chooser dialogs.

Fixes https://github.com/zed-industries/zed/issues/14127 (along with the
`ashpd` update in https://github.com/zed-industries/zed/pull/14401)

Also included a fix
(971d67c994)
for an issue that made multiple file chooser dialogs pop up on Wayland
when doing CTRL + O and quickly pressing the escape key.

Release Notes:

- N/A
2024-07-15 17:27:46 -07:00
Conrad Irwin
abc5abcd8b open picker (#14524)
Release Notes:

- linux: Added a fallback Open picker for when XDG is not working
- Added a new setting `use_system_path_prompts` (default true) that can
be disabled to use Zed's builtin keyboard-driven prompts.

---------

Co-authored-by: Max <max@zed.dev>
2024-07-15 17:04:15 -06:00
Marshall Bowers
da33aac156 extensions_ui: Remove commented-out code (#14525)
This PR removes some commented-out code from the `extensions_ui`.

Release Notes:

- N/A
2024-07-15 19:00:49 -04:00
Marshall Bowers
1818fef32f Display file icons in tabs (#14523)
This PR adds support for displaying file icons in tabs.

The `tabs.file_icons` setting controls whether the icons are displayed:

```json
{
  "tabs": {
    "file_icons": false
  }
}
```

This setting defaults to `true`.

<img width="1566" alt="Screenshot 2024-07-15 at 6 17 26 PM"
src="https://github.com/user-attachments/assets/86dfc8c9-764c-453d-95e4-2ec95d6fe715">

<img width="1566" alt="Screenshot 2024-07-15 at 6 24 26 PM"
src="https://github.com/user-attachments/assets/4b4e8489-49d3-41bf-b4cb-59365bdd3e9d">

Release Notes:

- Added file icons to buffer tabs
([#12138](https://github.com/zed-industries/zed/issues/12138)).
- If desired, these icons can be removed using `"tabs": { "file_icons":
false }`.
2024-07-15 18:33:08 -04:00
Marshall Bowers
2ae1a472e4 Upsell built-in features on the extensions page (#14516)
This PR extends the extensions page with support for upselling built-in
Zed features when certain keywords are searched for.

This should help inform users about features that Zed has out-of-the-box
when they go looking for them as extensions.

For example, when someone searches "vim":

<img width="1341" alt="Screenshot 2024-07-15 at 4 58 44 PM"
src="https://github.com/user-attachments/assets/b256d07a-559a-43c2-b491-3eca5bff436e">

Here are more examples of what the upsells can look like:

<img width="1341" alt="Screenshot 2024-07-15 at 4 54 39 PM"
src="https://github.com/user-attachments/assets/1f453132-ac14-4884-afc4-7c12db47ad1d">

Release Notes:

- Added banners for built-in Zed features when corresponding keywords
are used in the extension search.
2024-07-15 17:10:01 -04:00
Kirill Bulatov
d7a25c1696 Add an experimental, WIP diagnostics grouping panel (#14515)
Provide a current, broken state as an experimental way to browse
diagnostics.
The diagnostics are grouped by lines and reduced into a block that, in
case of multiple diagnostics per line, could be toggled back and forth
to show more diagnostics on the line.
Use `grouped_diagnostics::Deploy` to show the panel.

Issues remaining:
* panic on warnings toggle due to incorrect excerpt manipulation
* badly styled blocks
* no key bindings to navigate between blocks and toggle them
* overall odd usability gains for certain groups of people

Due to all above, the thing is feature-gated and not exposed to regular
people.


Release Notes:

- N/A
2024-07-15 22:58:18 +03:00
Eric Skogen
2c6cb4ec16 Fix Cmd+\ for workspace::ToggleLeftDock for Atom base keymap (#14098)
Release Notes:

- Fixed Left Dock in Atom keymap on Mac/Linux (`cmd-\`, `ctrl-\`) 
 ([#14098](https://github.com/zed-industries/zed/pull/14098), thanks [@audionerd](https://github.com/audionerd)).

---------

Co-authored-by: Peter Tripp <peter@zed.dev>
2024-07-15 15:56:10 -04:00
Marshall Bowers
143035b1ed gpui_macros: Extract border_style_methods macro (#14514)
This PR extracts a separate `border_style_methods` macro so that it can
be used independently from `style_helpers!`.

Release Notes:

- N/A
2024-07-15 15:51:29 -04:00
Nate Butler
fa3d29087d Add REPL dropdown menu to toolbar (#14493)
TODO: 


- [x] Actions run from menu not firing
- [x] Menu differentiates idle and busy for running kernel

Menu States:
- [x] No session && no support known

No session && no kernel installed for languages of known support
- (TODO after) Intro to REPL
- [x] Link to docs

No session but can start one
- [x] Start REPL
- (TODO after) More info -> Docs?

Yes Session

- [x] Info: Kernel name, language
  example: chatlab-3.7-adsf87fsa (Python)
  example: condapy-3.7 (Python)
- [x] Change Kernel -> https://zed.dev/docs/repl#change-kernel
- ---
- [x] Run
- [x] Interrupt
- [x] Clear Outputs
- ---
- [x] Shutdown


(Release notes left empty as the change will be documented in the REPL
release!)

Reserved for a follow on PR:

```
- [ ] Status should update when the menu is open (missing `cx.notify`?)
- [ ] Shutdown all kernels action
- [ ] Restart action
- [ ] [Default kernel changed - restart (this kernel) to apply] // todo!(kyle): need some kind of state thing that says if this has happened
```


Release Notes:

- N/A

---------

Co-authored-by: Marshall Bowers <elliott.codes@gmail.com>
Co-authored-by: Kyle Kelley <rgbkrk@gmail.com>
Co-authored-by: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com>
2024-07-15 11:55:49 -07:00
Conrad Irwin
1856320516 Add mouse handling to gpui input example (#14350)
Release Notes:

- N/A

---------

Co-authored-by: Jason Lee <huacnlee@gmail.com>
2024-07-15 12:10:25 -06:00
Conrad Irwin
b58abb171f linux: Hide Install CLI from welcome (#14506)
Release Notes:

- linux: Remove "Install CLI" from welcome, it is not necessary
2024-07-15 12:08:37 -06:00
Conrad Irwin
868455f978 linux: Fix IME on fcitx5 (#14508)
Release Notes:

- linux: Fix IME under fcitx5 (#14192)
2024-07-15 12:07:19 -06:00
Conrad Irwin
c27c41274a linux: re-add open fallback (#14359)
Release Notes:

- linux: Fixed opening urls/directories on systems where the xdg desktop
portal doesn't handle those requests.
2024-07-15 11:11:38 -06:00
makeProjectGreatAgain
0b0de8ca83 Display hint to add PATH for Fish shell too (#14504)
tested on `fish 3.7.1 (released March 19, 2024)`
___

Release Notes:

- N/A
2024-07-15 11:11:09 -06:00
apricotbucket28
f3ddd18201 linux: Show warning if file picker portal is missing (#14401)
This PR adds a warning when the file chooser couldn't be opened on Linux

It's quite confusing when trying to open a file and apparently nothing
happens:

fixes https://github.com/zed-industries/zed/issues/11089,
https://github.com/zed-industries/zed/issues/14328,
https://github.com/zed-industries/zed/issues/13753#issuecomment-2225812703,
https://github.com/zed-industries/zed/issues/13766,
https://github.com/zed-industries/zed/issues/14384,
https://github.com/zed-industries/zed/issues/14353,
https://github.com/zed-industries/zed/issues/9209


![image](https://github.com/user-attachments/assets/5acabdaa-7a9d-4225-9480-e371d20387c3)


Release Notes:

- N/A
2024-07-15 09:36:39 -07:00
Ephram
5d860e2286 Fix selectable popover dismissing on key press (#14368)
Release Notes:

- Fixed dismissal bug included in #12918
2024-07-15 09:11:14 -06:00
Peter Tripp
e26dbe2c5b Add linux Zed log location to crash report github issue template (#14373)
Release Notes:

- N/A
2024-07-15 09:27:12 -04:00
Peter Tripp
3c38be59b5 Add keyboard shortcuts to center scrolling around current line (#14385)
- MacOS: Center the cursor in the visible area. `ctrl-l` (matches MacOS)
- Linux JetBrains: Scroll so cursor is at the Middle `ctrl-m`
- `editor::NextScreen` is not longer bound in any keymap by default (was
`ctrl-l` on MacOS)

Fixes #5247
2024-07-15 09:26:53 -04:00
Danilo Leal
e50811c425 Adjust list item & pickers spacing (#14250) 2024-07-15 10:23:18 -03:00
Piotr Osiewicz
c1aa4d939c rust: Expose import names in completions for modules and functions (#14490)
Release Notes:

- Improved accuracy of completion lists for Rust functions and modules.
2024-07-15 14:26:39 +02:00
Antonio Scandurra
e8d674dc04 Show cursors for shared contexts (#14484)
Release Notes:

- N/A

Co-authored-by: Nathan <nathan@zed.dev>
2024-07-15 12:42:10 +02:00
Nathan Sobo
f0279e672a Add Gemini models to cloud enum (#14482)
Release Notes:

- N/A
2024-07-15 12:21:58 +02:00
Max Brunsfeld
98b95d9a51 Introduce /symbols command in assistant panel (#14360)
Release Notes:

- Added `/symbols` command in assistant panel.

---------

Co-authored-by: Antonio <antonio@zed.dev>
Co-authored-by: Antonio Scandurra <me@as-cii.com>
Co-authored-by: Nathan <nathan@zed.dev>
2024-07-15 11:51:32 +02:00
Antonio Scandurra
decdd3b6ac Introduce following for assistant panel (#14479)
Release Notes:

- Added support for following into the assistant panel.

---------

Co-authored-by: Max <max@zed.dev>
Co-authored-by: Max Brunsfeld <maxbrunsfeld@gmail.com>
Co-authored-by: Nathan <nathan@zed.dev>
2024-07-15 11:36:27 +02:00
Kirill Bulatov
977a1b7a82 Support dynamic formatting capabilities [un]registration (#14478)
Closes https://github.com/zed-industries/zed/issues/12661

Release Notes:

- Added dynamic [un]registration for LSP formatting capabilities
([#12661](https://github.com/zed-industries/zed/issues/12661))
2024-07-15 12:27:33 +03:00
llogick
684d9dde56 zig: Wire up LSP settings and binary.{path/arguments} for zls (#14379)
Enables the  LSP `settings` and `binary.{path/arguments}` functionality

Example:
```
"lsp": {
    "zls": {
      "settings": {
        "semantic_tokens": "none"
      },
      "binary": {
        "path": "/home/user/zls/zig-out/bin/zls",
        "arguments": ["--enable-debug-log"]
      }
    }
  },
```

Release Notes:

- N/A
2024-07-15 09:35:03 +02:00
张小白
315692d112 windows: Refactor clipboard implementation (#14347)
This PR provides a similar implementation to the macOS clipboard
implementation, adds support for metadata and includes tests.

Release Notes:

- N/A
2024-07-14 19:40:41 -07:00
张小白
ba09eabfba windows: Make window creation failable (#14395)
Release Notes:

- N/A
2024-07-14 19:37:46 -07:00
lea
70d983abe3 Include stable package in docs, mention UM, and link to sources for the Fedora package (#14432)
Hello, I'm one of the maintainers of the Zed package on Terra. I made
the following changes:

- Mention the Terra stable package, instead of only preview and nightly.
- Link to sources for Terra packages instead of pkgs.org.
- Mention Ultramarine in addition to Fedora (one of Terra's targets).

Release Notes:

- N/A
2024-07-14 19:34:08 -07:00
Fernando Tagawa
4a3097d4dd x11: Fix capitalization with neo 2 (#14466)
Fixed #14282

Release Notes:

- N/A
2024-07-14 18:19:20 -07:00
Kirill Bulatov
59ce3535d3 Turn off use_on_type_format too, for languages that have format_on_save disabled (#14413)
Based on the discussion in
https://github.com/zed-industries/zed/issues/14400


Release Notes:

- N/A
2024-07-13 22:04:15 +03:00
Kirill Bulatov
f8b5e42070 Do not send textDocument/didSave message if server does not declare its support (#14412)
Release Notes:

- Improved Zed logic for sending `textDocument/didSave` request
([14286](https://github.com/zed-industries/zed/issues/14286))
2024-07-13 21:59:21 +03:00
Kirill Bulatov
88c5eb550e Lookup prettier more leniently (#14403)
Do not require the `prettier` dependency name to be in package.json's
[dev]Dependencies, instead just checking the `node_modules` contents.

Release Notes:

- Improved `prettier` detection to pick up its installation from
transitive dependencies
([12731](https://github.com/zed-industries/zed/issues/12731)
2024-07-13 21:59:14 +03:00
Bedis Nbiba
e5dc6beace deno: wire up LSP settings (#14410)
Currently deno lsp only works because deno have a workaround when it
detects deno.json it gets activated, but without a deno.json it won't
work
With this change now it works correctly regardless of a deno.json
presence, it only require enable:true:


```json
{
  "lsp": {
    "deno": {
      "settings": {
        "deno": {
          "enable": true
        }
      }
    }
  }
}
```


Release Notes:

- Improved initial Deno set-up to enable it without explicit deno.json present in the file system
2024-07-13 21:10:36 +03:00
Zak Johnson
3a410942b4 Apply terminal.foreground and terminal.background from theme (#14281)
Release Notes:

- Fixed terminal colors not respecting the theme
([#11418](https://github.com/zed-industries/zed/discussions/11418)).
2024-07-13 14:41:44 +03:00
Kirill Bulatov
89fbd6528f Do not fold excerpts by default in the outline panel (#14378)
Release Notes:

- N/A
2024-07-13 04:08:21 +03:00
Kirill Bulatov
9ce989a704 Tidy up collab-related signature help data (#14377)
Follow-up of https://github.com/zed-industries/zed/pull/12909

* Fully preserve LSP data when sending it via collab, and only strip it
on the client.
* Avoid extra custom request handlers, and extend multi LSP server query
protocol instead.


Release Notes:

- N/A
2024-07-13 04:06:01 +03:00
Kirill Bulatov
dd63e25f23 Revert hold: true for macOS tasks (#14376)
Otherwise, ctrl-c makes them stuck being held from time to time

Follow-up of https://github.com/zed-industries/zed/pull/13898 that
reverts the macOS-related part of the PR.

Release Notes:

- N/A
2024-07-13 04:02:38 +03:00
Max Brunsfeld
489077befc Extract a BufferStore object from Project (#14037)
This is a ~small~ pure refactor that's a step toward SSH remoting. I've
extracted the Project's buffer state management into a smaller, separate
struct called `BufferStore`, currently in the same crate. I did this as
a separate PR to reduce conflicts between main and `remoting-over-ssh`.

The idea is to make use of this struct (and other smaller structs that
make up `Project`) in a dedicated, simpler `HeadlessProject` type that
we will use in the SSH server to model the remote end of a project. With
this approach, as we develop the headless project, we can avoid adding
more conditional logic to `Project` itself (which is already very
complex), and actually make `Project` a bit smaller by extracting out
helper objects.

Release Notes:

- N/A
2024-07-12 15:25:54 -07:00
FilipeBisinella
21c5ce2bbd Add pyright workspace configuration (#14265)
Release Notes:

- Added support for pyright workspace configuration, as described in
https://microsoft.github.io/pyright/#/settings .
2024-07-12 15:13:09 -07:00
Marshall Bowers
3deb000f70 assistant: Add basic glob support for expanding items in /docs (#14370)
This PR updates the `/docs` slash command with basic globbing support
for expanding docs.

A `*` can be added to the item path to signify the end of a prefix
match.

For example:

```
# This will match any documentation items starting with `auk::`.
# In this case, it will pull in the docs for each item in the crate.
/docs docs-rs auk::*

# This will match any documentation items starting with `auk::visitor::`,
# which will pull in docs for the `visitor` module.
/docs docs-rs auk::visitor::*
```


https://github.com/user-attachments/assets/5e1e21f1-241b-483f-9cd1-facc3aa76365

Release Notes:

- N/A
2024-07-12 17:57:50 -04:00
Mikayla Maki
fe3fe945a9 linux: Indicate when the window is focused (#14266)
fixes #14202

Release Notes:

- Added a representation of the current focus state to Zed's window
style ([#14202](https://github.com/zed-industries/zed/issues/14202))
2024-07-12 14:20:58 -07:00
Stanislav Alekseev
11178eacc7 Fix diagnostic popover not overflowing when necessary (#14322)
It was broken after #13996 moved rendering text one level deeper,
causing `max_h` and `overflow_y_scroll` to apply to different widgets
Release Notes:

- Fixed large diagnostic popovers not overflowing when nessesary

Before:
<img width="814" alt="Screenshot 2024-07-12 at 15 25 46"
src="https://github.com/user-attachments/assets/4f615600-2857-4470-8b77-864e3a9e38d5">

After:
<img width="813" alt="Screenshot 2024-07-12 at 15 26 10"
src="https://github.com/user-attachments/assets/83c1f344-b3b1-4929-8197-4b24a0e9c65e">
2024-07-12 14:14:11 -07:00
Stanislav Alekseev
59bc027750 Fix direnv option being named direnv and not load_direnv in the docs (#14309)
This is a quick followup to #13902 that fixes a mistake with the setting
naming in the docs, I accidentally made
Release Notes:

- N/A
2024-07-12 14:12:02 -07:00
张小白
0a718c65e2 windows: Return client size and position from window_bounds (#14228)
This is a follow up of #14218 , since we open the window based on the
size of the client area, `window_bounds` should also return the size of
the client area to maintain consistency.

Release Notes:

- N/A
2024-07-12 13:19:36 -07:00
Marshall Bowers
85d77a3eec Clarify /docs error message when target/doc does not exist (#14364)
This PR improves the error message shown by the `/docs` slash command
when indexing fails due to the absence of `target/doc`.

We now distinguish between the overall `target/doc` directory missing
and an individual crate directory missing beneath it.

Release Notes:

- N/A
2024-07-12 16:09:16 -04:00
Marshall Bowers
ca80343486 assistant: Add docs provider for docs.rs (#14356)
This PR adds an indexed docs provider for retrieving docs from `docs.rs`
using the `/docs` slash command.

Release Notes:

- N/A
2024-07-12 13:22:52 -04:00
Semen Fomchenkov
739038ddaf docs: Add ALT Linux (Sisyphus) (#14351)
Added ALT Linux (Sisyphus) as one of the ways to install via the package
manager in linux.md.

Release Notes:

- N/A
2024-07-12 12:59:17 -04:00
Peter Tripp
106e0623dd PlainText language: Default to SoftWrap::EditorWidth (#14331)
- Remove wrap guide / vertical ruler in untitled buffers
- Fixes https://github.com/zed-industries/zed/issues/12473
2024-07-12 11:10:59 -04:00
Peter Tripp
607ad6de3c zig: Improve indentation (#14332)
- Fixes https://github.com/zed-industries/zed/issues/14140
2024-07-12 10:24:07 -04:00
Kirill Bulatov
ea26a01f5f Do not render a signature popover when its location is before the visible range (#14307)
Follow-up of https://github.com/zed-industries/zed/pull/12909

Release Notes:

- N/A
2024-07-12 11:31:52 +03:00
Stanislav Alekseev
8abc000553 Fix nushell local env detection by using direnv export (#13902)
I don't intend fully on getting this merged, this is just an experiment
on using `direnv` directly without relying on shell-specific behaviours.
It works though, so this finally closes #8633
Release Notes:

- Fixed nushell not picking up `direnv` environments by directly
interfacing with it using `direnv export`

---------

Co-authored-by: Thorsten Ball <mrnugget@gmail.com>
2024-07-12 10:29:32 +02:00
Kirill Bulatov
9f5309cedd Remove non-default wrap setting for markdown (#14304)
With this setting, markdown files are one of the few that get a line
wrap indicator, a vertical line on the right, which confuses people.

Release Notes:

- N/A
2024-07-12 11:15:57 +03:00
Conrad Irwin
adf74fdc14 linux: Fix panic handling unknown keys (#14274)
Pulls in https://github.com/rust-x-bindings/xkbcommon-rs/pull/54 to
avoid
panicking.

Release Notes:

- linux: Fix a panic in keyboard handling
2024-07-11 17:03:19 -06:00
sherwyn
e402d7e96a vim: Add support for vim::PreviousLineStart motion (#14193)
Release Notes:

- vim: Added `-`/`+` to go to beginning of line above/below
([#14183](https://github.com/zed-industries/zed/issues/14183)).
- vim: (Breaking) Removed non-standard builtin binding from `-` to open
the project panel. You can re-add it to your keymap file with:
`{"context":"VimControl", "bindings":{ "-":
"pane::RevealInProjectPanel"}}`


Optionally, include screenshots / media showcasing your addition that
can be included in the release notes.


https://github.com/zed-industries/zed/assets/32429059/0e9e9348-265e-4a81-a45a-4739034dc5d9

---------

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2024-07-11 16:36:07 -06:00
Conrad Irwin
12dfd4a2c2 Don't panic on unknown cursor style on x11 (#14264)
Release Notes:

- linux: Fixed a panic if we request a cursor style your system doesn't
support
2024-07-11 16:05:01 -06:00
Conrad Irwin
b87d1eabcc linux: Panic less on window init (#14255)
This change pulls in https://github.com/kvark/blade/pull/135 and updates
the simplelog dependency for compatibility with that.


Release Notes:

- linux: Show link to troubleshooting docs when we can't open a window
2024-07-11 16:04:46 -06:00
Max Brunsfeld
ac528dda64 Fix panic when evaluating a code snippet containing multi-byte characters (#14269)
Also, don't retrieve code snippets when rendering the repl quick action
button

Release Notes:

- N/A

---------

Co-authored-by: Kyle Kelley <kylek@zed.dev>
Co-authored-by: Kyle Kelley <rgbkrk@gmail.com>
2024-07-11 15:04:13 -07:00
Marshall Bowers
906688f012 assistant: Show a warning indicator when the user needs to run cargo doc (#14262)
This PR updates the `/docs` slash command to show a warning to the user
if a crate's docs cannot be indexed due to the target directory not
containing docs:

<img width="782" alt="Screenshot 2024-07-11 at 5 11 46 PM"
src="https://github.com/user-attachments/assets/2f54f7a1-97f4-4d2d-b51f-57ba31e50a2f">

Release Notes:

- N/A
2024-07-11 17:37:31 -04:00
Nate Butler
c18e9aedcd Add items_baseline to Styled (#14238)
Add support for aligning items to the baseline.

Release Notes:

- N/A

---------

Co-authored-by: Danilo Leal <67129314+danilo-leal@users.noreply.github.com>
2024-07-11 16:38:21 -04:00
Marshall Bowers
cd4847ca22 assistant: Use a more generic icon for the /docs command (#14247)
This PR updates the `/docs` slash command to use a more generic icon to
convey docs.

It was still using the Rust icon, a relic of when it was still
`/rustdoc`.

Release Notes:

- N/A
2024-07-11 15:46:33 -04:00
Brad Pitcher
4c63e8b203 docs: Fix Linux aarch64 tarball links (#14245)
Fixed tarball documentation links for linux aarch64 (they were pointing
at x86_64 tarballs)

Release Notes:

- N/A
2024-07-11 15:43:10 -04:00
TC
d9d8c1f6d9 assistant: Handle http:// links in /fetch (#14243)
Previously http://google.com would get modified to
https://http://google.com which doesn't work. I assume http links should
be supported.

Release Notes:

- N/A
2024-07-11 15:30:45 -04:00
Conrad Irwin
b0dbc80575 vim: (BREAKING) clean up keymap contexts (#14233)
Release Notes:

- vim: (BREAKING) Improved vim keymap contexts.

Previously `vim_mode == normal` was true even when operators were
pending, which led to bugs like #13789 and a requirement for custom
keymaps to exclude various conditions like (`!VimObject` and
`!VimWaiting`) to avoid bugs.

Now `vim_mode` will be set to `operator` or `waiting` in these cases as
described in [the docs](https://zed.dev/docs/vim#keybindings). For most
custom keymaps this change will be a no-op or an improvement, but if you
were deliberately relying on the old behaviour (if you were relying on
`VimObject` or `VimWaiting` becoming true) you will need to update your
keymap.

---------

Co-authored-by: Thorsten <thorsten@zed.dev>
2024-07-11 13:16:26 -06:00
Mikayla Maki
8e853e2b56 Update linux.md 2024-07-11 12:05:59 -07:00
Mikayla Maki
47a78907d6 Update system-requirements.md 2024-07-11 11:59:52 -07:00
Mikayla Maki
0c1a3db87d Update getting-started.md 2024-07-11 11:50:36 -07:00
Omer Tuchfeld
3541a1175f Disrupt blink for immediate feedback on cursor shape changes (#14177)
# Issue

When a user does something that changes the cursor shape, such as when
switching between vim modes, there may be an up to 500ms (cursor blink
interval) delay until the user receives feedback for their action. This
happens when the shape change happens during the invisible phase of a
blink - the user will not see the cursor shape change until the next
phase, which could be 500ms away.

# Solution

Cursor shape changes should disrupt blinking by forcing the cursor to be
shown, this results in immediate feedback for shape changes. This is in
line with the behavior of other editors I've tried.

Release Notes:

- Improved visual feedback when changing cursor shape
2024-07-11 12:47:10 -06:00
Kyle Kelley
e51d469025 Invalidate anchors when they get deleted (#14116)
Allows deleting the outputs directly within the editor. This also fixes
the overlap logic to make sure that the ends and the starts are
compared.


https://github.com/zed-industries/zed/assets/836375/84f5f582-95f3-4c6a-a3c9-54da6009e34d

Release Notes:

- N/A

---------

Co-authored-by: Antonio <antonio@zed.dev>
2024-07-11 11:21:41 -07:00
Conrad Irwin
018a2a29ea vim: Fix c when range ends in a multibyte character (#14139)
Release Notes:

- vim: Fixed `c <motion>` omitting trailing multibyte characters
([#13909](https://github.com/zed-industries/zed/issues/13909)).
2024-07-11 12:01:56 -06:00
Donough Liu
d49727ff10 terminal: Set TERM_PROGRAM and TERM_PROGRAM_VERSION environment variables in integrated terminal (#14213)
![image](https://github.com/zed-industries/zed/assets/31354274/9d1c5410-897b-40a1-8256-2d7e207f69ff)

These two environment variables are essential when people need to detect
terminal type and do something. Many popular terminals set them.

fixes https://github.com/zed-industries/zed/issues/4571

Release Notes:

- Set `TERM_PROGRAM` and `TERM_PROGRAM_VERSION` environment variables in
the integrated terminal
([#4571](https://github.com/zed-industries/zed/issues/4571)).
2024-07-11 20:48:46 +03:00
oliverpool
c195c4ddff docs: Document buffer_line_height (#14168)
`buffer_line_height` has been requested in #5590 and implemented in
#2718, however the documentation was still lacking.

Release Notes:

- N/A
2024-07-11 13:42:27 -04:00
Stanislav Alekseev
fd03454540 Fix reverse selections always being cleared (#14150)
When I implemented #13701, I kinda messed up with the reversed
selections, thinking that their anchors are flipped, so I flipped them
again. This caused the reverse selections to always be cleared

Release Notes:

- Fix reverse selections always being cleared, even if the right click
was performed inside
2024-07-11 11:35:18 -06:00
张小白
6eeec9b403 windows: Create window with correct size (#14218)
The `Bounds<DevicePixels>` we use to create a window represents the size
of the drawable area.

### Before:



https://github.com/zed-industries/zed/assets/14981363/52f0d196-b113-4b64-a0d1-407972674990

### After



https://github.com/zed-industries/zed/assets/14981363/83298b6c-5e5f-4a47-b051-35b4a02404ac



Release Notes:

- N/A
2024-07-11 09:54:59 -07:00
Marshall Bowers
b558e8da1e svelte: Bump to v0.0.2 (#14220)
This PR bumps the Svelte extension to v0.0.2.

Changes:

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

Release Notes:

- N/A
2024-07-11 11:47:44 -04:00
Peter Tripp
1d7b28c658 Add Upper/LowerCase binds to Linux Sublime Text keybinds (#14155) 2024-07-11 11:15:49 -04:00
Peter Tripp
de78eb44b1 Keymap changes for editor::JoinLines (#14136)
- Linux (default) add ctrl-shift-j
- Linux (default) remove ctrl-j
  - Conflicted with: `"ctrl-j": "workspace::ToggleBottomDock",`
- MacOS (sublime) add cmd-shift-j
2024-07-11 11:14:25 -04:00
Danilo Leal
c071e19899 docs: Add stray design tweaks (#14205)
- Mostly just tweaking some design (colors & spacing) stuff
- Some small accessibility things—e.g., underline decoration for links
and one h1 only per page
- Most of the other captured changes are really just Prettier indenting
stuff

Release Notes:

- N/A
2024-07-11 11:57:22 -03:00
Marshall Bowers
37fc4ce09d Allow Zed Nightly to use v0.0.7 of the Zed extension API (#14209)
This PR updates the Wasm API compatibility check to allow Nightly to
load extensions using v0.0.7 of the Zed extension API.

Release Notes:

- N/A
2024-07-11 10:54:15 -04:00
Danilo Leal
99f56252be docs: Tiny formatting tweaks on the Linux page (#14208)
Release Notes:

- N/A
2024-07-11 11:53:34 -03:00
Aleksei Gusev
f61abe0247 Pass hold: true to Alacritty for tasks (#13898)
It seems `hold: false` causes alacritty to close the channel earlier,
without waiting for the output from the child command to go to Zed.

Fixes [#13683](https://github.com/zed-industries/zed/issues/13683)

Release Notes:

- Fixed loosing output of a spawned task
([#13683](https://github.com/zed-industries/zed/issues/13683)).

[Screencast from 2024-07-06
18-28-56.webm](https://github.com/zed-industries/zed/assets/39293/4ebef8b5-7c0d-46be-9341-4ac0d809458d)
2024-07-11 17:50:00 +03:00
Marshall Bowers
45c54d189a assistant: Show a message when no docs providers are available (#14207)
This PR updates the `/docs` slash command to show a message to more
clearly indicate when there are no available docs providers.

<img width="379" alt="Screenshot 2024-07-11 at 10 31 53 AM"
src="https://github.com/zed-industries/zed/assets/1486634/d079f87c-4933-4da9-ad82-34dbfe6a284c">

Release Notes:

- N/A
2024-07-11 10:49:13 -04:00
Piotr Osiewicz
2727f55772 Add support for projects managed with Yarn (#13644)
TODO:
- [ ] File a PR with Yarn to add Zed to the list of supported IDEs.

Fixes: https://github.com/zed-industries/zed/issues/10107
Fixes: https://github.com/zed-industries/zed/issues/13706
Release Notes:

- Improved experience in projects using Yarn. Run `yarn dlx
@yarnpkg/sdks base` in the root of your project in order to elevate your
experience.

---------

Co-authored-by: Saurabh <79586784+m4saurabh@users.noreply.github.com>
2024-07-11 14:56:07 +02:00
tomoikey
291d64c803 lsp: Implement textDocument/signatureHelp for ProjectClientState::Local environment (#12909)
Closes https://github.com/zed-industries/zed/issues/5155
Closes https://github.com/zed-industries/zed/issues/4879


# Purpose
There was no way to know what to put in function signatures or struct
fields other than hovering at the moment. Therefore, it was necessary to
implement LSP's `textDocument/signatureHelp`.

I tried my best to match the surrounding coding style, but since this is
my first contribution, I believe there are various aspects that may be
lacking. I would greatly appreciate your code review.

# Description
When the window is displayed, the current argument or field at the
cursor's position is automatically bolded. If the cursor moves and there
is nothing to display, the window closes automatically.
To minimize changes and reduce the burden of review and debugging, the
SignatureHelp feature is implemented only when `is_local` is `true`.
Some `unimplemented!()` macros are embedded, but rest assured that they
are not called in this implementation.

# How to try it out
Press `cmd + i` (MacOS), `ctrl + i` (Linux).

# Enable auto signature help (2 ways)
### Add `"auto_signature_help": true` to `settings.json`
<img width="426" alt="image"
src="https://github.com/zed-industries/zed/assets/55743826/61310c39-47f9-4586-94b0-ae519dc3b37c">

Or

### Press `Auto Signature Help`. (Default `false`)
<img width="226" alt="image"
src="https://github.com/zed-industries/zed/assets/55743826/34155215-1eb5-4621-b09b-55df2f1ab6a8">

# Disable to show signature help after completion
### Add `"show_signature_help_after_completion": false` to
`settings.json`
<img width="438" alt="image"
src="https://github.com/zed-industries/zed/assets/55743826/5e5bacac-62e0-4921-9243-17e1e72d5eb6">

# Movie

https://github.com/zed-industries/zed/assets/55743826/77c12d51-b0a5-415d-8901-f93ef92098e7

# Screen Shot
<img width="628" alt="image"
src="https://github.com/zed-industries/zed/assets/55743826/3ebcf4b6-2b94-4dea-97f9-ac4f33e0291e">

<img width="637" alt="image"
src="https://github.com/zed-industries/zed/assets/55743826/6dc3eb4d-beee-460b-8dbe-d6eec6379b76">

Release Notes:

- Show function signature popovers
([4879](https://github.com/zed-industries/zed/issues/4879),
[5155](https://github.com/zed-industries/zed/issues/5155))

---------

Co-authored-by: Kirill Bulatov <kirill@zed.dev>
2024-07-11 13:38:33 +03:00
Piotr Osiewicz
6a11184ea3 dart: Release 0.0.3 (#14176)
Includes: https://github.com/zed-industries/zed/pull/13686

Release Notes:

- Added Flutter tasks to Dart extension.
2024-07-11 11:48:04 +02:00
Thorsten Ball
ff1dcff2fb gpui example: Add reset button to Input example (#14163)
Extracted from #14051 which I don't want to merge in its current state.


Release Notes:

- N/A
2024-07-11 11:46:47 +02:00
张小白
bef2586eed windows: Fix rust tasks (#13413)
https://github.com/zed-industries/zed/assets/14981363/56c208da-132c-438a-92b3-e31505859262


Release Notes:

- N/A
2024-07-11 10:47:25 +02:00
Abdullah Alsigar
bdba8b23fa dart: Add Flutter runnables and tasks (#13686)
Release Notes:

- Added runnable tasks for Flutter
2024-07-11 10:46:53 +02:00
Piotr Osiewicz
22900554d5 Project panel: Prevent scrollbar size from scaling with rem size (#14167)
The underlying container had width of 0.75 rem, which was equal to 12px
at default ui_font_size. However, with larger values of ui_font_size the
scrollbar would drift towards the center of a project panel, as the
scrollbar itself has a fixed width of 12 pixels. This commit moves
towards using a fixed width of 12px for scrollbar container. The
alternative was to make the scrollbar scale with ui_font_size, but that
isn't what the Editor scrollbar does, so I decided against it.



Release Notes:

- Fixed position of scrollbar in project panel with non-default
`ui_font_size` values.
2024-07-11 10:34:15 +02:00
Denis Washington
6db0b6c5ad terminal: Prevent extra character on handled meta keystrokes (#14151)
On macOS, when `terminal.option_as_meta` is enabled, pressing key
combinations like `option+b` and `option+f` would lead to both an escape
sequence being sent to the terminal (the expected behavior with
`option_as_meta == true`) AND a character being inserted (the behavior
when `option_as_meta == false`). Prevent the latter by stopping
propagation of the key-down event if it corresponds to a terminal escape
sequence and `option_as_meta` is enabled.

Fixes #7728

Release Notes:

- Fixed insertion of extra characters for some keystrokes if
`terminal.option_as_meta` is enabled
([#7728](https://github.com/zed-industries/zed/issues/7728)).
2024-07-11 11:20:54 +03:00
Aaron Cunnington
ba11e9a9a8 Fix SystemUIFont typo in default settings (#14158)
Release Notes:

- N/A
2024-07-11 11:20:38 +03:00
Peter Tripp
de570133ff Docs: Fix theme.mode default settings (#14153)
- Updated docs to match the changes made in
https://github.com/zed-industries/zed/pull/13621
- Fixes: #14084.
2024-07-11 03:20:12 -04:00
Peter Tripp
f1b1a9fd5e Ignore whitespace commits (#13889)
This let's GitHub and the Git cli optionally "skip" certain revs when
generating `git blame`.

Co-authored-by: Gilles Peiffer <gilles.peiffer.yt@gmail.com>
2024-07-11 02:45:40 -04:00
Chris​‌​‮ ‬Hayes‌​​​
1b08f14c54 Document how to enable vim_mode in /docs/vim (#14138)
## Documents:

- **Added** instructions on how to enable "Vim mode" to the
["Settings"](https://zed.dev/docs/vim#settings) of
[/docs/vim](https://zed.dev/docs/vim).

While [/docs/configuring-zed](https://zed.dev/docs/configuring-zed)
_does_ mention the `vim_mode` setting,
[/docs/vim](https://zed.dev/docs/vim) does not.

This can be confusing for users like me who went straight to the vim
doc, and could not figure out how to enable vim.

## Release Notes:

- N/A
2024-07-10 21:59:03 -06:00
Sensational Code
36d3b16279 Add toggle hunk diff and expand all hunk diffs key bindings (#14130)
Noticed these were missing when I was reading through the docs.

Release Notes:

- Add toggle hunk diff and expand all hunk diffs key bindings
2024-07-10 21:22:52 -06:00
Ephram
945764e409 Selectable popover text (#12918)
Release Notes:

- Fixed #5236
- Added the ability to select and copy text from information popovers



https://github.com/zed-industries/zed/assets/50590465/d5c86623-342b-474b-913e-d07cc3f76de4

---------

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
Co-authored-by: Antonio <ascii@zed.dev>
2024-07-10 21:14:34 -06:00
Jason Lee
f1281c14dd Revert Windows normal window title style to WS_EX_APPWINDOW (#14132)
Release Notes:

- N/A

@ConradIrwin we must revert this little change.

https://github.com/zed-industries/zed/pull/14063#issuecomment-2221867379
2024-07-10 20:49:55 -06:00
Hans
3b823d4a0b Add simple support for wrapscan (#13497)
For: #13417 

This is a simple version, I'm not sure if we just need to limit this
feature to vim mode, or maybe in normal editor mode, which involves
other logic like the location of the setting

Release Notes:

- N/A

---------

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2024-07-10 20:42:37 -06:00
Xiaoguang Wang
46645b552f Remove unused variable query_editor_was_focused (#14128)
Fix
https://github.com/zed-industries/zed/pull/14128

Release Notes:

- N/A
2024-07-10 20:40:36 -06:00
Jason Lee
5bc3846d59 Fix #14106 Windows title bar broken (#14122)
Release Notes:

- N/A

----

Fix #14106 

Sorry, the previous change in #14063 I have made a mistake. I shouldn't
have changed the previous logic.

```diff
- if !state_ptr.hide_title_bar {
+ if state_ptr.hide_title_bar {
```

## Test


https://github.com/zed-industries/zed/assets/5518/e03fbcac-be6b-4a9d-8937-d3b5e236b564

And the popup window limit is still works.
2024-07-10 18:55:51 -06:00
jansol
e6d608fa05 linux: Add NewWorkspace to the Actions list in .desktop (#14097)
Fix
https://github.com/zed-industries/zed/pull/13807#issuecomment-2221324262


Release Notes:

- N/A
2024-07-10 16:16:21 -06:00
Peter Tripp
e106a39620 AlpineLinux: Fix install.sh and docs typo (#14105)
- AlpineLinux uses busybox `mktemp` which requires `mktemp -d` end with six XXXXXX (not five).
- Fixes #14082
2024-07-10 17:41:43 -04:00
Sören Meier
d32e9f759c svelte: Improve syntax highlighting (#12788)
This PR fixes `<script context="module">` not being highlighted.  
It also adds support for scss.

Release Notes:

- N/A
2024-07-10 15:42:50 -04:00
Jason Lee
15662f105e gpui: Fix TextStyle default font_family crash on Windows, use Segoe UI for Windows (#14040)
Release Notes:

- Fixed default font_family crash on Windows, use `Segoe UI`.

## Crash error message

```
thread 'main' panicked at crates\gpui\src\text_system.rs:150:9:
failed to resolve font 'Helvetica' or any of the fallbacks: 
Zed Plex Mono, Helvetica, Cantarell, Ubuntu, Noto Sans, DejaVu Sans
```
2024-07-10 13:40:42 -06:00
Jason Lee
1887a6db53 gpui: Fix popup kind window support on Windows (#14063)
Release Notes:

- N/A

----

Continue #14044 for Windows 

## The problem

The `cx.open_window` method has provided us a `window_kind` option to
allows creating a Popup kind. This behavior can work on macOS, the popup
kind window have no-border, no-shadow, no-resize, and followed the
`is_movable` if present true it can't move.

This PR to fix those supports on Windows.

The border and shadow still exist, I have tried to use WS_POPUP
window_style, but it will crash:

> This is looks like complex, it is out of my known.

```
    Blocking waiting for file lock on build directory
   Compiling gpui v0.1.0 (F:\work\zed\crates\gpui)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 13.96s
     Running `target\debug\examples\window_positioning.exe`
thread 'main' panicked at F:\Users\jason\.cargo\git\checkouts\blade-b2bcd1de1cf7ab6a\21a56f7\blade-graphics\src\vulkan\init.rs:864:18:
called `Result::unwrap()` on an `Err` value: ERROR_OUT_OF_DEVICE_MEMORY
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\examples\window_positioning.exe` (exit code: 0xc0000409, STATUS_STACK_BUFFER_OVERRUN)
```

So I just make a simple change, to use `WS_EX_TOOLWINDOW` this can
disable resize, and connect `is_movable` to `handle_hit_test_msg` to
disable move, and also no Status Bar icon.

## Before



https://github.com/zed-industries/zed/assets/5518/76740a71-e0ba-401f-958d-f4afdeb417c6

## After



https://github.com/zed-industries/zed/assets/5518/dca49f13-914c-425a-b8b6-b9fc15f8d208
2024-07-10 13:39:54 -06:00
张小白
fa9360f78d windows: Work around font rendering clipping issue (#14075)
Release Notes:

- N/A
2024-07-10 13:38:49 -06:00
Conrad Irwin
3ff738fa03 Fix panic clicking on multibyte chars (#14086)
Fixes: #12011

When hovering over a multibyte character in a debug build, Zed would
panic.
Follow up to #11296 

Release Notes:

- N/A
2024-07-10 13:38:26 -06:00
Nathan Sobo
77b31d1845 Allow rpc_url to be assigned on Client with test-support feature (#13430)
Also, allow proto messages to be deserialized. This is to support
translating these messages JS types in a new server implementation based
on CloudFlare durable objects.

Release Notes:

- N/A
2024-07-10 13:36:22 -06:00
Ephram
15b8790a2c Update One Light modified color (#12143)
Release Notes:

- Changed the `modified` color on the one-light color theme to a more
readable value

The current color in the file tree for modified files is basically
unreadable in the default light mode
<img width="238" alt="image"
src="https://github.com/zed-industries/zed/assets/50590465/e553673f-1c24-41d9-b1b9-1dbbb7419d1e">

This change just changes the color to match that of the one-light theme
present in vscode
~~old proposal:
https://github.com/zed-industries/zed/assets/50590465/b4dc4030-bcd8-429a-84b8-2744e213e492~~
new proposal:
<img width="378" alt="image"
src="https://github.com/zed-industries/zed/assets/50590465/41c53019-8cf3-4927-9879-47937388cde8">

This does have a side-effect of changing the modified color on the side
in the editor, but personally I think this change is negligable.
2024-07-10 15:33:35 -04:00
Jason Lee
b693cbfcb7 Fix line wrap for CJK characters (#11296)
Release Notes:

- Fixed line wrap for CJK characters. 

## Demo


https://github.com/zed-industries/zed/assets/5518/c6695bb4-b170-4ce0-9a84-c36b051de438


![diff](https://github.com/zed-industries/zed/assets/5518/318bc815-1018-485c-aa16-49c775a9f402)

Fix issues: #4623 #11202

### Render case

```
## fr

Bien démarrer avec la documentation GitHub Découvrez comment commencer à créer, à livrer et à gérer des logiciels avec GitHub. Explorez nos produits, inscrivez-vous pour obtenir un compte et connectez-vous à la plus grande communauté de développement du monde.

## zh

GitHub 入门文档 了解如何开始构建、运输和维护具有 GitHub 的软件。 了解我们的产品,注册一个帐户,与世界上最大的发展社区建立联系。

## es

Documentación sobre la introducción a GitHub Aprende cómo comenzar a crear, enviar y mantener software con GitHub. Explora nuestros productos, regístrate para una cuenta y conéctate con la comunidad de desarrollo más grande del mundo.

## kr

GitHub 설명서 시작 GitHub를 사용하여 소프트웨어 빌드, 납품 및 유지 관리를 시작하는 방법을 알아봅니다. 제품을 탐색하고, 계정에 등록하고, 세계 최대의 개발 커뮤니티와 연결합니다.

## ja

GitHub の概要に関するドキュメント GitHub を使用してソフトウェアの構築、出荷、および保守を始める方法を学びます。 当社の製品を探索し、アカウントにサインアップして、世界最大の開発コミュニティと繋がりましょう。

## pt

Documentação de introdução ao GitHub Aprenda a começar a criar, enviar e manter um software com a GitHub. Explore nossos produtos, inscreva-se em uma conta e conecte-se com a maior comunidade de desenvolvimento do mundo.

## ru

Начало работы с документацией по GitHub Узнайте, как начать создание, доставку и обслуживание программного обеспечения с помощью GitHub. Изучите наши продукты, зарегистрируйте учетную запись и присоединитесь к крупнейшему в мире сообществу разработчиков.
```
2024-07-10 13:10:19 -06:00
Aidan Harris
73d7f70ff6 Flatpak fixes (#14083)
The Flatpak was failing to build because of AppStream metadata linting
errors. It also complained about the hyphen in the cid.

Release Notes:
 
     * N/A
2024-07-10 12:51:08 -06:00
Conrad Irwin
be5b7b2e70 Reduce the need to read the shell script to figure out what's going on (#14077)
Release Notes:

- N/A
2024-07-10 12:08:54 -06:00
Tim Whitbeck
4434353f73 docs: Correct ln command in linux install steps (#14078)
Release Notes:

- N/A
2024-07-10 12:08:42 -06:00
Nate Butler
95637a0320 Minor breadcrumb style updates (#14070)
Minor breadcrumb style updates

Before:

![CleanShot 2024-07-10 at 12 42
46@2x](https://github.com/zed-industries/zed/assets/1714999/9e1d4fb7-7549-4749-85f8-797f59d06c4d)

After:

![CleanShot 2024-07-10 at 12 42
36@2x](https://github.com/zed-industries/zed/assets/1714999/f448eb0a-deac-4a8e-b26e-67d559c4c679)


Release Notes:

- N/A
2024-07-10 14:04:17 -04:00
Thorsten Ball
ee623f77c1 linux/x11: Restore differentiation of mouse/keyboard focus (#13995)
This restores https://github.com/zed-industries/zed/pull/13943 which was
reverted in #13974 because it was possible to get in a state where focus
could not be restored on a window.

In this PR there's an additional change: `FocusIn` and `FocusOut` events
are always handled, even if the `event.mode` is not "NORMAL". In my
testing, `alt-tabbing` between windows didn't produce `FocusIn` and
`FocusOut` events when we had that check. Now, with the check removed,
it's possible to switch focus between two windows again with `alt-tab`.


Release Notes:

- N/A

---------

Co-authored-by: Conrad <conrad@zed.dev>
Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2024-07-10 19:54:26 +02:00
Conrad Irwin
c732865fc5 Build x86 linux too :/ (#14068)
Release Notes:

- N/A
2024-07-10 11:04:32 -06:00
sgj123456
8a659af82c gpui_macros: Enable extra-traits feature for syn (#14067)
Must enable extra-traits of syn feature to enable Debug trait of
Visibility

Release Notes:

- N/A

---------

Co-authored-by: Marshall Bowers <elliott.codes@gmail.com>
2024-07-10 12:32:46 -04:00
Kyle Kelley
07dc4050bf Do not bind cmd-enter for repl::Run when in AssistantContext (#14066)
Don't pollute cmd-enter in the Assistant's `ContextEditor`.

Release Notes:

- N/A
2024-07-10 09:25:07 -07:00
Kyle Kelley
896b9bda23 Stick REPL icon in quick action bar (#14064)
REPL Quick Actions

<img width="325" alt="image"
src="https://github.com/zed-industries/zed/assets/836375/faaf4c8f-ef12-4417-a9dd-158d5beae8ba">

When the Jupyter REPL is enabled and a kernel is available, show the
status in the editor bar:

![quick action bar
repl](https://github.com/zed-industries/zed/assets/836375/f3445283-f1fc-4714-895b-7aa842d4ab76)


Release Notes:

- N/A

---------

Co-authored-by: Nate Butler <iamnbutler@gmail.com>
2024-07-10 09:20:52 -07:00
Conrad Irwin
9282bf97ae Default linux to stable (#14061)
Release Notes:

- linux: default install.sh to stable
2024-07-10 10:10:16 -06:00
Piotr Osiewicz
33a67ad6b9 chore: Clippy fixes for 1.80 (#13987)
The biggest hurdle turned out to be use of `Arc<Language>` in maps, as
`clippy::mutable_key_type` started triggering on it (due to - I suppose
- internal mutability on `HighlightMap`?). I switched over to using
`LanguageId` as the key type in some of the callsites, as that's what
`Language` uses anyways for it's hash/eq, though I've still had to
suppress the lint outside of language crate.

/cc @maxdeviant , le clippy guru.

Release Notes:

- N/A
2024-07-10 17:53:17 +02:00
Jason Lee
d4ddc4c62c gpui: Fix cx.bounds, cx.open_window position on macOS (#14044)
Release Notes:

- gpui: Fixed `cx.bounds` method to get correct `y` position on macOS.
- gpui: Fixed `cx.open_window` position when macOS Dock is existed.
- Fixed call notification and reopen window position.

## Before


![image](https://github.com/zed-industries/zed/assets/5518/4a435ffd-d7ef-4de7-a7de-44d21db4a719)


https://github.com/zed-industries/zed/assets/5518/ab925779-4253-4b27-9084-01023888087f


## After

<img width="533" alt="image"
src="https://github.com/zed-industries/zed/assets/5518/142e9aaa-ae82-4a72-9acf-04097c545bf0">


https://github.com/zed-industries/zed/assets/5518/8793824a-8b74-4913-8204-7b39649aeeed


---

The case is I have made a Popover by use child window, the coordinate of
the window is always can't placement a right position.

So, I make this example to test the `cx.bounds` and set bounds to
window.

---

By this test, is the `cx.bounds` have a bug?

For example the **Top Left** window, we give it origin (150,150), but it
`cx.bounds()` returns (150,262)

> On the window label, middle line is the `bounds` that we set to the
window, last line is `cx.bounds()` result.

Display 1:

<img width="1512" alt="CleanShot 2024-07-10 at 14 52 26@2x"
src="https://github.com/zed-industries/zed/assets/5518/3adf9e79-f237-431a-a72b-02face7b2361">


---

Or is there something I missed. Is it correct to use `cx.bounds` method
to get the bounds of the current window?

At the same time, I also found that when there are multiple screens, the
information obtained by cx.bounds is very different on different
screens, and it seems that the origin is not relative to the screen.

Display 2:

<img width="2560" alt="SCR-20240710-nkmq"
src="https://github.com/zed-industries/zed/assets/5518/d87d4151-0562-4bf8-b3b3-5da3b4d09d82">
2024-07-10 09:52:33 -06:00
Antonio Scandurra
8944af7406 Lay the groundwork for collaborating on assistant panel (#13991)
This pull request introduces collaboration for the assistant panel by
turning `Context` into a CRDT. `ContextStore` is responsible for sending
and applying operations, as well as synchronizing missed changes while
the connection was lost.

Contexts are shared on a per-project basis, and only the host can share
them for now. Shared contexts can be accessed via the `History` tab in
the assistant panel.

<img width="1819" alt="image"
src="https://github.com/zed-industries/zed/assets/482957/c7ae46d2-cde3-4b03-b74a-6e9b1555c154">


Please note that this doesn't implement following yet, which is
scheduled for a subsequent pull request.

Release Notes:

- N/A
2024-07-10 17:36:22 +02:00
张小白
1662993811 windows: Revert "windows: Fix font clipping issue" (#14045)
The implemetation of that PR is totally wrong, sorry for that!

Release Notes:

- N/A
2024-07-10 08:19:29 -07:00
Thorsten Ball
7ef64fe6db vim: Add ctrl-m binding (equivalent to <CR>) (#14057)
Now that we have macros I noticed how much I rely on this.

Release Notes:

- vim: `ctrl-m` now is equivalent to `enter` in editor.
2024-07-10 16:31:54 +02:00
Joseph T Lyons
f147722fe0 v0.145.x dev 2024-07-10 10:12:35 -04:00
Daniel Schmidt
e1a6efa609 go: Quote targeting expression on runnables (#14055)
Release Notes:

- Go: fix test runnables in fish shell.
2024-07-10 16:02:29 +02:00
448 changed files with 30196 additions and 12068 deletions

28
.git-blame-ignore-revs Normal file
View File

@@ -0,0 +1,28 @@
# .git-blame-ignore-revs
#
# This file consists of a list of commits that should be ignored for
# `git blame` purposes. This is useful for ignoring commits that only
# changed whitespace / indentation / formatting, but did not change
# the underlying syntax tree.
#
# GitHub will pick this up automatically for blame views:
# https://docs.github.com/en/repositories/working-with-files/using-files/viewing-a-file#ignore-commits-in-the-blame-view
# To use this file locally, run:
# git blame --ignore-revs-file .git-blame-ignore-revs
# To always use this file by default, run:
# git config --local blame.ignoreRevsFile .git-blame-ignore-revs
# To disable this functionality, run:
# git config --local blame.ignoreRevsFile ""
# Comments are optional, but may provide helpful context.
# 2023-04-20 Set default tab_size for JSON to 2 and apply new formatting
# https://github.com/zed-industries/zed/pull/2394
eca93c124a488b4e538946cd2d313bd571aa2b86
# 2024-02-25 Format JSON files in assets/
# https://github.com/zed-industries/zed/pull/8405
ffdda588b41f7d9d270ffe76cab116f828ad545e
# 2024-07-05 Improved formatting of default keymaps (single line per bind)
# https://github.com/zed-industries/zed/pull/13887
813cc3f5e537372fc86720b5e71b6e1c815440ab

View File

@@ -27,7 +27,8 @@ body:
attributes:
label: If applicable, attach your `~/Library/Logs/Zed/Zed.log` file to this issue.
description: |
Drag Zed.log into the text input below.
macOS: `~/Library/Logs/Zed/Zed.log`
Linux: `~/.local/share/zed/logs/Zed.log` or $XDG_DATA_HOME
If you only need the most recent lines, you can run the `zed: open log` command palette action to see the last 1000.
value: |
<details><summary>Zed.log</summary><pre>

View File

@@ -251,6 +251,8 @@ jobs:
draft: true
prerelease: ${{ env.RELEASE_CHANNEL == 'preview' }}
files: |
target/zed-remote-server-macos-x86_64.gz
target/zed-remote-server-macos-aarch64.gz
target/aarch64-apple-darwin/release/Zed-aarch64.dmg
target/x86_64-apple-darwin/release/Zed-x86_64.dmg
target/release/Zed.dmg
@@ -319,11 +321,12 @@ jobs:
- name: Upload app bundle to release
uses: softprops/action-gh-release@v1
if: ${{ env.RELEASE_CHANNEL == 'preview' }}
with:
draft: true
prerelease: ${{ env.RELEASE_CHANNEL == 'preview' }}
files: target/release/zed-linux-x86_64.tar.gz
files: |
target/zed-remote-server-linux-x86_64.gz
target/release/zed-linux-x86_64.tar.gz
body: ""
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -406,7 +409,9 @@ jobs:
with:
draft: true
prerelease: ${{ env.RELEASE_CHANNEL == 'preview' }}
files: target/release/zed-linux-aarch64.tar.gz
files: |
target/zed-remote-server-linux-aarch64.gz
target/release/zed-linux-aarch64.tar.gz
body: ""
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -33,6 +33,7 @@ jobs:
- name: Run clippy
run: ./script/clippy
tests:
timeout-minutes: 60
name: Run tests
@@ -93,9 +94,9 @@ jobs:
- name: Upload Zed Nightly
run: script/upload-nightly macos
bundle-deb:
bundle-linux-x86:
timeout-minutes: 60
name: Create a Linux *.tar.gz bundle
name: Create a Linux *.tar.gz bundle for x86
if: github.repository_owner == 'zed-industries'
runs-on:
- self-hosted
@@ -121,8 +122,56 @@ jobs:
echo "Publishing version: ${version} on release channel nightly"
echo "nightly" > crates/zed/RELEASE_CHANNEL
- name: Generate license file
run: script/generate-licenses
- name: Create Linux .tar.gz bundle
run: script/bundle-linux
- name: Upload Zed Nightly
run: script/upload-nightly linux-targz
bundle-linux-arm:
timeout-minutes: 60
name: Create a Linux *.tar.gz bundle for ARM
if: github.repository_owner == 'zed-industries'
runs-on:
- hosted-linux-arm-1
needs: tests
env:
DIGITALOCEAN_SPACES_ACCESS_KEY: ${{ secrets.DIGITALOCEAN_SPACES_ACCESS_KEY }}
DIGITALOCEAN_SPACES_SECRET_KEY: ${{ secrets.DIGITALOCEAN_SPACES_SECRET_KEY }}
ZED_CLIENT_CHECKSUM_SEED: ${{ secrets.ZED_CLIENT_CHECKSUM_SEED }}
steps:
- name: Checkout repo
uses: actions/checkout@v4
with:
clean: false
- name: "Setup jq"
uses: dcarbone/install-jq-action@v2
- name: Set up Clang
run: |
sudo apt-get update
sudo apt-get install -y llvm-10 clang-10 build-essential cmake pkg-config libasound2-dev libfontconfig-dev libwayland-dev libxkbcommon-x11-dev libssl-dev libsqlite3-dev libzstd-dev libvulkan1 libgit2-dev
echo "/usr/lib/llvm-10/bin" >> $GITHUB_PATH
- uses: rui314/setup-mold@v1
with:
mold-version: 2.32.0
- name: rustup
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
- name: Limit target directory size
run: script/clear-target-dir-if-larger-than 100
- name: Set release channel to nightly
run: |
set -euo pipefail
version=$(git rev-parse --short HEAD)
echo "Publishing version: ${version} on release channel nightly"
echo "nightly" > crates/zed/RELEASE_CHANNEL
- name: Create Linux .tar.gz bundle
run: script/bundle-linux

434
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -19,6 +19,7 @@ members = [
"crates/collections",
"crates/command_palette",
"crates/command_palette_hooks",
"crates/completion",
"crates/copilot",
"crates/db",
"crates/dev_server_projects",
@@ -50,6 +51,7 @@ members = [
"crates/install_cli",
"crates/journal",
"crates/language",
"crates/language_model",
"crates/language_selector",
"crates/language_tools",
"crates/languages",
@@ -79,6 +81,8 @@ members = [
"crates/refineable",
"crates/refineable/derive_refineable",
"crates/release_channel",
"crates/remote",
"crates/remote_server",
"crates/repl",
"crates/rich_text",
"crates/rope",
@@ -137,6 +141,7 @@ members = [
"extensions/php",
"extensions/prisma",
"extensions/purescript",
"extensions/ruff",
"extensions/ruby",
"extensions/snippets",
"extensions/svelte",
@@ -160,6 +165,7 @@ assets = { path = "crates/assets" }
assistant = { path = "crates/assistant" }
assistant_slash_command = { path = "crates/assistant_slash_command" }
assistant_tooling = { path = "crates/assistant_tooling" }
async-pipe = { git = "https://github.com/zed-industries/async-pipe-rs", rev = "82d00a04211cf4e1236029aa03e6b6ce2a74c553" }
audio = { path = "crates/audio" }
auto_update = { path = "crates/auto_update" }
breadcrumbs = { path = "crates/breadcrumbs" }
@@ -173,6 +179,7 @@ collab_ui = { path = "crates/collab_ui" }
collections = { path = "crates/collections" }
command_palette = { path = "crates/command_palette" }
command_palette_hooks = { path = "crates/command_palette_hooks" }
completion = { path = "crates/completion" }
copilot = { path = "crates/copilot" }
db = { path = "crates/db" }
dev_server_projects = { path = "crates/dev_server_projects" }
@@ -202,6 +209,7 @@ inline_completion_button = { path = "crates/inline_completion_button" }
install_cli = { path = "crates/install_cli" }
journal = { path = "crates/journal" }
language = { path = "crates/language" }
language_model = { path = "crates/language_model" }
language_selector = { path = "crates/language_selector" }
language_tools = { path = "crates/language_tools" }
languages = { path = "crates/languages" }
@@ -231,6 +239,8 @@ proto = { path = "crates/proto" }
quick_action_bar = { path = "crates/quick_action_bar" }
recent_projects = { path = "crates/recent_projects" }
release_channel = { path = "crates/release_channel" }
remote = { path = "crates/remote" }
remote_server = { path = "crates/remote_server" }
repl = { path = "crates/repl" }
rich_text = { path = "crates/rich_text" }
rope = { path = "crates/rope" }
@@ -274,7 +284,8 @@ zed_actions = { path = "crates/zed_actions" }
alacritty_terminal = "0.23"
any_vec = "0.13"
anyhow = "1.0.57"
ashpd = { git = "https://github.com/bilelmoussaoui/ashpd", rev = "29f2e1a" }
arrayvec = { version = "0.7.4", features = ["serde"] }
ashpd = "0.9.1"
async-compression = { version = "0.4", features = ["gzip", "futures-io"] }
async-dispatcher = { version = "0.1" }
async-fs = "1.6"
@@ -284,10 +295,11 @@ async-trait = "0.1"
async-watch = "0.3.1"
async_zip = { version = "0.0.17", features = ["deflate", "deflate64"] }
base64 = "0.13"
bitflags = "2.4.2"
blade-graphics = { git = "https://github.com/kvark/blade", rev = "21a56f780e21e4cb42c70a1dcf4b59842d1ad7f7" }
blade-macros = { git = "https://github.com/kvark/blade", rev = "21a56f780e21e4cb42c70a1dcf4b59842d1ad7f7" }
blade-util = { git = "https://github.com/kvark/blade", rev = "21a56f780e21e4cb42c70a1dcf4b59842d1ad7f7" }
bitflags = "2.6.0"
blade-graphics = { git = "https://github.com/zed-industries/blade", rev = "a477c2008db27db0b9f745715e119b3ee7ab7818" }
blade-macros = { git = "https://github.com/zed-industries/blade", rev = "a477c2008db27db0b9f745715e119b3ee7ab7818" }
blade-util = { git = "https://github.com/zed-industries/blade", rev = "a477c2008db27db0b9f745715e119b3ee7ab7818" }
blake3 = "1.5.3"
cap-std = "3.0"
cargo_toml = "0.20"
chrono = { version = "0.4", features = ["serde"] }
@@ -365,6 +377,7 @@ shellexpand = "2.1.0"
shlex = "1.3.0"
signal-hook = "0.3.17"
similar = "1.3"
simplelog = "0.12.2"
smallvec = { version = "1.6", features = ["union"] }
smol = "1.2"
strum = { version = "0.25.0", features = ["derive"] }
@@ -380,6 +393,7 @@ time = { version = "0.3", features = [
"serde-well-known",
"formatting",
] }
tiny_http = "0.8"
toml = "0.8"
tokio = { version = "1", features = ["full"] }
tower-http = "0.4.4"
@@ -451,11 +465,11 @@ features = [
"Win32_System_Com_StructuredStorage",
"Win32_System_DataExchange",
"Win32_System_LibraryLoader",
"Win32_System_Memory",
"Win32_System_Ole",
"Win32_System_SystemInformation",
"Win32_System_SystemServices",
"Win32_System_Threading",
"Win32_System_Time",
"Win32_System_WinRT",
"Win32_UI_Controls",
"Win32_UI_HiDpi",
@@ -518,7 +532,7 @@ single_range_in_vec_init = "allow"
# There are a bunch of rules currently failing in the `style` group, so
# allow all of those, for now.
style = "allow"
style = { level = "allow", priority = -1 }
# Individual rules that have violations in the codebase:
almost_complete_range = "allow"

View File

@@ -0,0 +1,3 @@
<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3.49574 4.74787L5.99574 7.25214L8.49574 4.74787" stroke="black" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 246 B

View File

@@ -0,0 +1,13 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_62_95)">
<path d="M4.5 6C3.67157 6 3 5.32843 3 4.5C3 3.67157 3.67157 3 4.5 3C5.32843 3 6 3.67157 6 4.5C6 5.32843 5.32843 6 4.5 6Z" stroke="white" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M6.54433 13.4334C6.87775 13.5227 7.22046 13.3249 7.3098 12.9914C7.39914 12.658 7.20127 12.3153 6.86786 12.226L6.54433 13.4334ZM3.77426 6.86772L3.93603 6.26401L2.72862 5.94049L2.56686 6.54419L3.77426 6.86772ZM6.86786 12.226C4.53394 11.6006 3.14889 9.20163 3.77426 6.86772L2.56686 6.54419C1.76281 9.54494 3.54359 12.6293 6.54433 13.4334L6.86786 12.226Z" fill="white"/>
<path d="M11.5 13C10.6716 13 10 12.3284 10 11.5C10 10.6716 10.6716 10 11.5 10C12.3284 10 13 10.6716 13 11.5C13 12.3284 12.3284 13 11.5 13Z" stroke="white" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10.1875 4.21113C9.88852 4.03854 9.7861 3.65629 9.95869 3.35736C10.1313 3.05843 10.5135 2.95601 10.8125 3.12859L10.1875 4.21113ZM11.7888 10.1875C12.9969 8.09496 12.28 5.41925 10.1875 4.21113L10.8125 3.12859C13.5028 4.6819 14.4246 8.12209 12.8713 10.8125L11.7888 10.1875Z" fill="white"/>
</g>
<defs>
<clipPath id="clip0_62_95">
<rect width="16" height="16" fill="white" transform="matrix(-1 0 0 1 16 0)"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

20
assets/icons/repl_off.svg Normal file
View File

@@ -0,0 +1,20 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_39_129)">
<path d="M22.0209 11.9553C22.0059 10.0068 21.4219 8.10512 20.3408 6.48401" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10.1001 2.18C11.355 1.93537 12.1493 1.93674 13.5027 2.10594" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M21.8198 10.1C22.0644 11.3548 22.0644 12.6451 21.8198 13.9" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M20.2898 17.6C19.5716 18.6622 18.6548 19.5757 17.5898 20.29" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M13.9008 21.82C12.6459 22.0644 11.6432 22.1543 10.3883 21.91" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M2.18005 13.9C1.93543 12.6451 1.93543 11.3548 2.18005 10.1" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M3.70996 6.40002C4.42822 5.33775 5.34503 4.42433 6.40996 3.71002" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 13C12.5523 13 13 12.5523 13 12C13 11.4477 12.5523 11 12 11C11.4477 11 11 11.4477 11 12C11 12.5523 11.4477 13 12 13Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M19 7C20.1046 7 21 6.10457 21 5C21 3.89543 20.1046 3 19 3C17.8954 3 17 3.89543 17 5C17 6.10457 17.8954 7 19 7Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5 21C6.10457 21 7 20.1046 7 19C7 17.8954 6.10457 17 5 17C3.89543 17 3 17.8954 3 19C3 20.1046 3.89543 21 5 21Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M1.99072 12.0748C2.00804 14.0118 2.58758 15.9021 3.65891 17.516" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</g>
<defs>
<clipPath id="clip0_39_129">
<rect width="24" height="24" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

@@ -0,0 +1,15 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_32_70)">
<path d="M19 7C20.1046 7 21 6.10457 21 5C21 3.89543 20.1046 3 19 3C17.8954 3 17 3.89543 17 5C17 6.10457 17.8954 7 19 7Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5 21C6.10457 21 7 20.1046 7 19C7 17.8954 6.10457 17 5 17C3.89543 17 3 17.8954 3 19C3 20.1046 3.89543 21 5 21Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10.3999 21.9C12.3227 22.2159 14.2958 21.9632 16.0769 21.173C17.858 20.3827 19.3694 19.0893 20.4254 17.4517C21.4814 15.8142 22.036 13.9037 22.021 11.9553C22.006 10.0068 21.422 8.10512 20.3409 6.48401" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M13.4998 2.10002C11.5849 1.8076 9.62631 2.07763 7.86198 2.87732C6.09765 3.677 4.60356 4.9719 3.56126 6.60468C2.51896 8.23745 1.97332 10.1378 1.99063 12.0748C2.00795 14.0118 2.58749 15.9021 3.65882 17.516" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10 15V9" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M14 15V9" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</g>
<defs>
<clipPath id="clip0_32_70">
<rect width="24" height="24" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@@ -0,0 +1,14 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_32_64)">
<path d="M19 7C20.1046 7 21 6.10457 21 5C21 3.89543 20.1046 3 19 3C17.8954 3 17 3.89543 17 5C17 6.10457 17.8954 7 19 7Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5 21C6.10457 21 7 20.1046 7 19C7 17.8954 6.10457 17 5 17C3.89543 17 3 17.8954 3 19C3 20.1046 3.89543 21 5 21Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10.3999 21.9C12.3227 22.2159 14.2958 21.9632 16.0769 21.173C17.858 20.3827 19.3694 19.0893 20.4254 17.4517C21.4814 15.8142 22.036 13.9037 22.021 11.9553C22.006 10.0068 21.422 8.10512 20.3409 6.48401" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M13.4998 2.10002C11.5849 1.8076 9.62631 2.07763 7.86198 2.87732C6.09765 3.677 4.60356 4.9719 3.56126 6.60468C2.51896 8.23745 1.97332 10.1378 1.99063 12.0748C2.00795 14.0118 2.58749 15.9021 3.65882 17.516" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10 8.56055C10 8.32095 10.267 8.17803 10.4664 8.31094L15.6256 11.7504C15.8037 11.8691 15.8037 12.1309 15.6256 12.2496L10.4664 15.6891C10.267 15.822 10 15.6791 10 15.4394V8.56055Z" fill="white" stroke="white" stroke-linecap="round" stroke-linejoin="round"/>
</g>
<defs>
<clipPath id="clip0_32_64">
<rect width="24" height="24" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -19,7 +19,6 @@
"escape": "menu::Cancel",
"ctrl-escape": "menu::Cancel",
"ctrl-c": "menu::Cancel",
"shift-enter": "picker::UseSelectedQuery",
"alt-enter": ["picker::ConfirmInput", { "secondary": false }],
"ctrl-alt-enter": ["picker::ConfirmInput", { "secondary": true }],
"ctrl-shift-w": "workspace::CloseWindow",
@@ -79,10 +78,8 @@
"shift-down": "editor::SelectDown",
"shift-left": "editor::SelectLeft",
"shift-right": "editor::SelectRight",
"ctrl-shift-left": "editor::SelectToPreviousWordStart",
"ctrl-shift-right": "editor::SelectToNextWordEnd",
"ctrl-shift-up": "editor::AddSelectionAbove",
"ctrl-shift-down": "editor::AddSelectionBelow",
"ctrl-shift-left": "editor::SelectToPreviousWordStart", // cursorWordLeftSelect
"ctrl-shift-right": "editor::SelectToNextWordEnd", // cursorWordRightSelect
"ctrl-shift-home": "editor::SelectToBeginning",
"ctrl-shift-end": "editor::SelectToEnd",
"ctrl-a": "editor::SelectAll",
@@ -100,6 +97,7 @@
"ctrl-k ctrl-r": "editor::RevertSelectedHunks",
"ctrl-'": "editor::ToggleHunkDiff",
"ctrl-\"": "editor::ExpandAllHunkDiffs",
"ctrl-i": "editor::ShowSignatureHelp",
"alt-g b": "editor::ToggleGitBlame"
}
},
@@ -109,7 +107,6 @@
"enter": "editor::Newline",
"shift-enter": "editor::Newline",
"ctrl-shift-enter": "editor::NewlineBelow",
"ctrl-enter": "editor::NewlineAbove",
"alt-z": "editor::ToggleSoftWrap",
"ctrl-f": "buffer_search::Deploy",
"ctrl-h": ["buffer_search::Deploy", { "replace_enabled": true }],
@@ -119,6 +116,12 @@
"ctrl-alt-e": "editor::SelectEnclosingSymbol"
}
},
{
"context": "Editor && mode == full && !jupyter",
"bindings": {
"ctrl-enter": "editor::NewlineAbove"
}
},
{
"context": "Editor && mode == full && inline_completion",
"bindings": {
@@ -207,7 +210,7 @@
}
},
{
"context": "ProjectSearchBar && in_replace",
"context": "ProjectSearchBar && in_replace > Editor",
"bindings": {
"enter": "search::ReplaceNext",
"ctrl-alt-enter": "search::ReplaceAll"
@@ -260,20 +263,19 @@
"bindings": {
"ctrl-[": "editor::Outdent",
"ctrl-]": "editor::Indent",
"shift-alt-up": "editor::AddSelectionAbove",
"shift-alt-down": "editor::AddSelectionBelow",
"shift-alt-up": "editor::AddSelectionAbove", // Insert Cursor Above
"shift-alt-down": "editor::AddSelectionBelow", // Insert Cursor Below
"ctrl-shift-k": "editor::DeleteLine",
"alt-up": "editor::MoveLineUp",
"alt-down": "editor::MoveLineDown",
"ctrl-alt-shift-up": "editor::DuplicateLineUp",
"ctrl-alt-shift-down": "editor::DuplicateLineDown",
"ctrl-shift-left": "editor::SelectToPreviousWordStart",
"ctrl-shift-right": "editor::SelectToNextWordEnd",
"ctrl-shift-up": "editor::SelectLargerSyntaxNode", //todo(linux) tmp keybinding
"ctrl-shift-down": "editor::SelectSmallerSyntaxNode", //todo(linux) tmp keybinding
"ctrl-d": ["editor::SelectNext", { "replace_newest": false }],
"ctrl-shift-l": "editor::SelectAllMatches",
"ctrl-shift-d": ["editor::SelectPrevious", { "replace_newest": false }],
"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-shift-down": ["editor::SelectNext", { "replace_newest": false }], // Add selection to Next Find Match
"ctrl-shift-up": ["editor::SelectPrevious", { "replace_newest": false }],
"ctrl-k ctrl-d": ["editor::SelectNext", { "replace_newest": true }],
"ctrl-k ctrl-shift-d": ["editor::SelectPrevious", { "replace_newest": true }],
"ctrl-k ctrl-i": "editor::Hover",
@@ -326,7 +328,7 @@
"alt-9": ["pane::ActivateItem", 8],
"alt-0": "pane::ActivateLastItem",
"ctrl-alt--": "pane::GoBack",
"ctrl-alt-shift--": "pane::GoForward",
"ctrl-alt-_": "pane::GoForward",
"ctrl-shift-t": "pane::ReopenClosedItem",
"f3": "search::SelectNextMatch",
"shift-f3": "search::SelectPrevMatch",
@@ -397,7 +399,7 @@
"bindings": {
"ctrl-shift-k": "editor::DeleteLine",
"ctrl-shift-d": "editor::DuplicateLineDown",
"ctrl-j": "editor::JoinLines",
"ctrl-shift-j": "editor::JoinLines",
"ctrl-alt-backspace": "editor::DeleteToPreviousSubwordStart",
"ctrl-alt-h": "editor::DeleteToPreviousSubwordStart",
"ctrl-alt-delete": "editor::DeleteToNextSubwordEnd",
@@ -480,6 +482,12 @@
"ctrl-enter": "assistant::InlineAssist"
}
},
{
"context": "Editor && jupyter && !ContextEditor",
"bindings": {
"ctrl-enter": "repl::Run"
}
},
{
"context": "ContextEditor > Editor",
"bindings": {
@@ -566,6 +574,13 @@
"tab": "channel_modal::ToggleMode"
}
},
{
"context": "Picker > Editor",
"bindings": {
"tab": "picker::ConfirmCompletion",
"alt-enter": ["picker::ConfirmInput", { "secondary": false }]
}
},
{
"context": "ChannelModal > Picker > Editor",
"bindings": {
@@ -591,6 +606,7 @@
"ctrl-alt-space": "terminal::ShowCharacterPalette",
"shift-ctrl-c": "terminal::Copy",
"ctrl-insert": "terminal::Copy",
"ctrl-a": "editor::SelectAll",
"shift-ctrl-v": "terminal::Paste",
"shift-insert": "terminal::Paste",
"ctrl-enter": "assistant::InlineAssist",

View File

@@ -83,7 +83,7 @@
"ctrl-n": "editor::MoveDown",
"ctrl-b": "editor::MoveLeft",
"ctrl-f": "editor::MoveRight",
"ctrl-l": "editor::NextScreen",
"ctrl-l": "editor::ScrollCursorCenter",
"alt-left": "editor::MoveToPreviousWordStart",
"alt-b": "editor::MoveToPreviousWordStart",
"alt-right": "editor::MoveToNextWordEnd",
@@ -102,9 +102,9 @@
"ctrl-shift-b": "editor::SelectLeft",
"shift-right": "editor::SelectRight",
"ctrl-shift-f": "editor::SelectRight",
"alt-shift-left": "editor::SelectToPreviousWordStart",
"alt-shift-left": "editor::SelectToPreviousWordStart", // cursorWordLeftSelect
"alt-shift-b": "editor::SelectToPreviousWordStart",
"alt-shift-right": "editor::SelectToNextWordEnd",
"alt-shift-right": "editor::SelectToNextWordEnd", // cursorWordRightSelect
"alt-shift-f": "editor::SelectToNextWordEnd",
"ctrl-shift-up": "editor::SelectToStartOfParagraph",
"ctrl-shift-down": "editor::SelectToEndOfParagraph",
@@ -126,7 +126,8 @@
"cmd-alt-z": "editor::RevertSelectedHunks",
"cmd-'": "editor::ToggleHunkDiff",
"cmd-\"": "editor::ExpandAllHunkDiffs",
"cmd-alt-g b": "editor::ToggleGitBlame"
"cmd-alt-g b": "editor::ToggleGitBlame",
"cmd-i": "editor::ShowSignatureHelp"
}
},
{
@@ -179,6 +180,12 @@
"cmd-c": "markdown::Copy"
}
},
{
"context": "Editor && jupyter && !ContextEditor",
"bindings": {
"cmd-enter": "repl::Run"
}
},
{
"context": "AssistantPanel",
"bindings": {
@@ -254,7 +261,7 @@
}
},
{
"context": "ProjectSearchBar && in_replace",
"context": "ProjectSearchBar && in_replace > Editor",
"bindings": {
"enter": "search::ReplaceNext",
"cmd-enter": "search::ReplaceAll"
@@ -301,19 +308,20 @@
"bindings": {
"cmd-[": "editor::Outdent",
"cmd-]": "editor::Indent",
"cmd-alt-up": "editor::AddSelectionAbove",
"cmd-alt-up": "editor::AddSelectionAbove", // Insert cursor above
"cmd-ctrl-p": "editor::AddSelectionAbove",
"cmd-alt-down": "editor::AddSelectionBelow",
"cmd-alt-down": "editor::AddSelectionBelow", // Insert cursor below
"cmd-ctrl-n": "editor::AddSelectionBelow",
"cmd-shift-k": "editor::DeleteLine",
"alt-up": "editor::MoveLineUp",
"alt-down": "editor::MoveLineDown",
"alt-shift-up": "editor::DuplicateLineUp",
"alt-shift-down": "editor::DuplicateLineDown",
"ctrl-shift-right": "editor::SelectLargerSyntaxNode",
"ctrl-shift-left": "editor::SelectSmallerSyntaxNode",
"cmd-d": ["editor::SelectNext", { "replace_newest": false }],
"cmd-shift-l": "editor::SelectAllMatches",
"ctrl-shift-right": "editor::SelectLargerSyntaxNode", // Expand Selection
"ctrl-shift-left": "editor::SelectSmallerSyntaxNode", // Shrink Selection
"cmd-d": ["editor::SelectNext", { "replace_newest": false }], // Add selection to Next Find Match
"cmd-shift-l": "editor::SelectAllMatches", // Select all occurrences of current selection
"cmd-f2": "editor::SelectAllMatches", // Select all occurrences of current word
"ctrl-cmd-d": ["editor::SelectPrevious", { "replace_newest": false }],
"cmd-k cmd-d": ["editor::SelectNext", { "replace_newest": true }],
"cmd-k ctrl-cmd-d": ["editor::SelectPrevious", { "replace_newest": true }],
@@ -568,12 +576,6 @@
"space": "project_panel::Open"
}
},
{
"context": "Editor && jupyter",
"bindings": {
"cmd-enter": "repl::Run"
}
},
{
"context": "CollabPanel && not_editing",
"bindings": {
@@ -593,6 +595,14 @@
"tab": "channel_modal::ToggleMode"
}
},
{
"context": "Picker > Editor",
"bindings": {
"tab": "picker::ConfirmCompletion",
"alt-enter": ["picker::ConfirmInput", { "secondary": false }],
"cmd-alt-enter": ["picker::ConfirmInput", { "secondary": true }]
}
},
{
"context": "ChannelModal > Picker > Editor",
"bindings": {
@@ -612,20 +622,13 @@
"ctrl-backspace": "tab_switcher::CloseSelectedItem"
}
},
{
"context": "Picker",
"bindings": {
"f2": "picker::UseSelectedQuery",
"alt-enter": ["picker::ConfirmInput", { "secondary": false }],
"cmd-alt-enter": ["picker::ConfirmInput", { "secondary": true }]
}
},
{
"context": "Terminal",
"bindings": {
"ctrl-cmd-space": "terminal::ShowCharacterPalette",
"cmd-c": "terminal::Copy",
"cmd-v": "terminal::Paste",
"cmd-a": "editor::SelectAll",
"cmd-k": "terminal::Clear",
"ctrl-enter": "assistant::InlineAssist",
// Some nice conveniences

View File

@@ -0,0 +1,21 @@
// Zed keymap
//
// For information on binding keys, see the Zed
// documentation: https://zed.dev/docs/key-bindings
//
// To see the default key bindings run `zed: Open Default Keymap`
// from the command palette.
[
{
"context": "Workspace",
"bindings": {
// "shift shift": "file_finder::Toggle"
}
},
{
"context": "Editor",
"bindings": {
// "j k": ["workspace::SendKeystrokes", "escape"]
}
}
]

View File

@@ -25,6 +25,7 @@
"ctrl-shift-d": "editor::DuplicateLineDown", // editor:duplicate-lines
"ctrl-up": "editor::MoveLineUp", // editor:move-line-up
"ctrl-down": "editor::MoveLineDown", // editor:move-line-down
"ctrl-\\": "workspace::ToggleLeftDock", // tree-view:toggle
"ctrl-shift-m": "markdown::OpenPreviewToTheSide" // markdown-preview:toggle
}
},

View File

@@ -13,6 +13,7 @@
"ctrl-shift-j": "editor::JoinLines",
"ctrl-d": "editor::DuplicateLineDown",
"ctrl-y": "editor::DeleteLine",
"ctrl-m": "editor::ScrollCursorCenter",
"ctrl-pagedown": "editor::MovePageDown",
"ctrl-pageup": "editor::MovePageUp",
// "ctrl-alt-shift-b": "editor::SelectToPreviousWordStart",

View File

@@ -3,10 +3,10 @@
"bindings": {
"ctrl-shift-[": "pane::ActivatePrevItem",
"ctrl-shift-]": "pane::ActivateNextItem",
"ctrl-pagedown": "pane::ActivatePrevItem",
"ctrl-pageup": "pane::ActivateNextItem",
"ctrl-shift-tab": "pane::ActivateNextItem",
"ctrl-tab": "pane::ActivatePrevItem"
"ctrl-pageup": "pane::ActivatePrevItem",
"ctrl-pagedown": "pane::ActivateNextItem",
"ctrl-tab": "pane::ActivateNextItem",
"ctrl-shift-tab": "pane::ActivatePrevItem"
}
},
{
@@ -24,6 +24,8 @@
"ctrl-shift-f12": "editor::FindAllReferences",
"ctrl-.": "editor::GoToHunk",
"ctrl-,": "editor::GoToPrevHunk",
"ctrl-k ctrl-u": "editor::ConvertToUpperCase",
"ctrl-k ctrl-l": "editor::ConvertToLowerCase",
"shift-alt-m": "markdown::OpenPreviewToTheSide",
"ctrl-backspace": "editor::DeleteToPreviousWordStart",
"ctrl-delete": "editor::DeleteToNextWordEnd"

View File

@@ -26,6 +26,7 @@
"cmd-shift-d": "editor::DuplicateLineDown",
"ctrl-cmd-up": "editor::MoveLineUp",
"ctrl-cmd-down": "editor::MoveLineDown",
"cmd-\\": "workspace::ToggleLeftDock",
"ctrl-shift-m": "markdown::OpenPreviewToTheSide"
}
},

View File

@@ -3,10 +3,10 @@
"bindings": {
"cmd-shift-[": "pane::ActivatePrevItem",
"cmd-shift-]": "pane::ActivateNextItem",
"ctrl-pagedown": "pane::ActivatePrevItem",
"ctrl-pageup": "pane::ActivateNextItem",
"ctrl-shift-tab": "pane::ActivateNextItem",
"ctrl-tab": "pane::ActivatePrevItem"
"ctrl-pageup": "pane::ActivatePrevItem",
"ctrl-pagedown": "pane::ActivateNextItem",
"ctrl-tab": "pane::ActivateNextItem",
"ctrl-shift-tab": "pane::ActivatePrevItem"
}
},
{
@@ -27,6 +27,7 @@
"ctrl-,": "editor::GoToPrevHunk",
"cmd-k cmd-u": "editor::ConvertToUpperCase",
"cmd-k cmd-l": "editor::ConvertToLowerCase",
"cmd-shift-j": "editor::JoinLines",
"shift-alt-m": "markdown::OpenPreviewToTheSide",
"ctrl-backspace": "editor::DeleteToPreviousWordStart",
"ctrl-delete": "editor::DeleteToNextWordEnd"

View File

@@ -1,12 +1,6 @@
[
{
"context": "ProjectPanel || Editor",
"bindings": {
"ctrl-6": "pane::AlternateFile"
}
},
{
"context": "Editor && VimControl && !VimWaiting && !menu",
"context": "VimControl && !menu",
"bindings": {
"i": ["vim::PushOperator", { "Object": { "around": false } }],
"a": ["vim::PushOperator", { "Object": { "around": true } }],
@@ -16,7 +10,11 @@
"backspace": "vim::Backspace",
"j": "vim::Down",
"down": "vim::Down",
"ctrl-j": "vim::Down",
"enter": "vim::NextLineStart",
"ctrl-m": "vim::NextLineStart",
"+": "vim::NextLineStart",
"-": "vim::PreviousLineStart",
"tab": "vim::Tab",
"shift-tab": "vim::Tab",
"k": "vim::Up",
@@ -197,20 +195,20 @@
"ctrl-w g shift-d": "editor::GoToTypeDefinitionSplit",
"ctrl-w space": "editor::OpenExcerptsSplit",
"ctrl-w g space": "editor::OpenExcerptsSplit",
"-": "pane::RevealInProjectPanel"
"ctrl-6": "pane::AlternateFile"
}
},
{
// escape is in its own section so that it cancels a pending count.
"context": "Editor && vim_mode == normal && vim_operator == none && !VimWaiting",
"context": "VimControl && VimCount",
"bindings": {
"0": ["vim::Number", 0]
}
},
{
"context": "vim_mode == normal",
"bindings": {
"escape": "editor::Cancel",
"ctrl-[": "editor::Cancel"
}
},
{
"context": "Editor && vim_mode == normal && vim_operator == none && !VimWaiting",
"bindings": {
"ctrl-[": "editor::Cancel",
".": "vim::Repeat",
"c": ["vim::PushOperator", "Change"],
"shift-c": "vim::ChangeToEndOfLine",
@@ -218,7 +216,7 @@
"shift-d": "vim::DeleteToEndOfLine",
"shift-j": "vim::JoinLines",
"y": ["vim::PushOperator", "Yank"],
"shift-y": "vim::YankLine",
"shift-y": "vim::YankToEndOfLine",
"i": "vim::InsertBefore",
"shift-i": "vim::InsertFirstNonWhitespace",
"a": "vim::InsertAfter",
@@ -254,127 +252,12 @@
"] d": "editor::GoToDiagnostic",
"[ d": "editor::GoToPrevDiagnostic",
"] c": "editor::GoToHunk",
"[ c": "editor::GoToPrevHunk"
"[ c": "editor::GoToPrevHunk",
"g c c": "vim::ToggleComments"
}
},
{
"context": "Editor && vim_mode == visual && vim_operator == none && !VimWaiting",
"bindings": {
"\"": ["vim::PushOperator", "Register"],
// tree-sitter related commands
"[ x": "editor::SelectLargerSyntaxNode",
"] x": "editor::SelectSmallerSyntaxNode"
}
},
{
"context": "Editor && VimCount && vim_mode != insert",
"bindings": {
"0": ["vim::Number", 0]
}
},
{
"context": "Editor && vim_operator == c",
"bindings": {
"c": "vim::CurrentLine",
"d": "editor::Rename" // zed specific
}
},
{
"context": "Editor && vim_mode == normal && vim_operator == c",
"bindings": {
"s": ["vim::PushOperator", { "ChangeSurrounds": {} }]
}
},
{
"context": "Editor && vim_operator == d",
"bindings": {
"d": "vim::CurrentLine"
}
},
{
"context": "Editor && vim_operator == gu",
"bindings": {
"g u": "vim::CurrentLine",
"u": "vim::CurrentLine"
}
},
{
"context": "Editor && vim_operator == gU",
"bindings": {
"g shift-u": "vim::CurrentLine",
"shift-u": "vim::CurrentLine"
}
},
{
"context": "Editor && vim_operator == g~",
"bindings": {
"g ~": "vim::CurrentLine",
"~": "vim::CurrentLine"
}
},
{
"context": "Editor && vim_mode == normal && vim_operator == d",
"bindings": {
"s": ["vim::PushOperator", "DeleteSurrounds"]
}
},
{
"context": "Editor && vim_operator == y",
"bindings": {
"y": "vim::CurrentLine"
}
},
{
"context": "Editor && vim_mode == normal && vim_operator == y",
"bindings": {
"s": ["vim::PushOperator", { "AddSurrounds": {} }]
}
},
{
"context": "Editor && vim_operator == ys",
"bindings": {
"s": "vim::CurrentLine"
}
},
{
"context": "Editor && vim_operator == >",
"bindings": {
">": "vim::CurrentLine"
}
},
{
"context": "Editor && vim_operator == <",
"bindings": {
"<": "vim::CurrentLine"
}
},
{
"context": "Editor && VimObject",
"bindings": {
"w": "vim::Word",
"shift-w": ["vim::Word", { "ignorePunctuation": true }],
"t": "vim::Tag",
"s": "vim::Sentence",
"p": "vim::Paragraph",
"'": "vim::Quotes",
"`": "vim::BackQuotes",
"\"": "vim::DoubleQuotes",
"|": "vim::VerticalBars",
"(": "vim::Parentheses",
")": "vim::Parentheses",
"b": "vim::Parentheses",
"[": "vim::SquareBrackets",
"]": "vim::SquareBrackets",
"{": "vim::CurlyBrackets",
"}": "vim::CurlyBrackets",
"shift-b": "vim::CurlyBrackets",
"<": "vim::AngleBrackets",
">": "vim::AngleBrackets",
"a": "vim::Argument"
}
},
{
"context": "Editor && vim_mode == visual && !VimWaiting && !VimObject",
"context": "vim_mode == visual",
"bindings": {
"u": "vim::ConvertToLowerCase",
"U": "vim::ConvertToUpperCase",
@@ -409,23 +292,16 @@
">": "vim::Indent",
"<": "vim::Outdent",
"i": ["vim::PushOperator", { "Object": { "around": false } }],
"a": ["vim::PushOperator", { "Object": { "around": true } }]
"a": ["vim::PushOperator", { "Object": { "around": true } }],
"g c": "vim::ToggleComments",
"\"": ["vim::PushOperator", "Register"],
// tree-sitter related commands
"[ x": "editor::SelectLargerSyntaxNode",
"] x": "editor::SelectSmallerSyntaxNode"
}
},
{
"context": "Editor && vim_mode == normal && !VimWaiting",
"bindings": {
"g c c": "vim::ToggleComments"
}
},
{
"context": "Editor && vim_mode == visual",
"bindings": {
"g c": "vim::ToggleComments"
}
},
{
"context": "Editor && vim_mode == insert",
"context": "vim_mode == insert",
"bindings": {
"escape": "vim::NormalBefore",
"ctrl-c": "vim::NormalBefore",
@@ -444,30 +320,118 @@
}
},
{
"context": "Editor && vim_mode == replace",
"context": "vim_mode == replace",
"bindings": {
"escape": "vim::NormalBefore",
"ctrl-c": "vim::NormalBefore",
"ctrl-[": "vim::NormalBefore",
"backspace": "vim::UndoReplace",
"tab": "vim::Tab",
"enter": "vim::Enter",
"backspace": "vim::UndoReplace"
"enter": "vim::Enter"
}
},
{
"context": "Editor && vim_mode != replace && VimWaiting",
"context": "vim_mode == waiting",
"bindings": {
"tab": "vim::Tab",
"enter": "vim::Enter",
"escape": ["vim::SwitchMode", "Normal"],
"ctrl-[": ["vim::SwitchMode", "Normal"]
"escape": "vim::ClearOperators",
"ctrl-c": "vim::ClearOperators",
"ctrl-[": "vim::ClearOperators"
}
},
{
"context": "Editor && vim_mode == insert && VimWaiting",
"context": "vim_mode == operator",
"bindings": {
"escape": "vim::NormalBefore",
"ctrl-[": "vim::NormalBefore"
"escape": "vim::ClearOperators",
"ctrl-c": "vim::ClearOperators",
"ctrl-[": "vim::ClearOperators"
}
},
{
"context": "vim_operator == a || vim_operator == i || vim_operator == cs",
"bindings": {
"w": "vim::Word",
"shift-w": ["vim::Word", { "ignorePunctuation": true }],
"t": "vim::Tag",
"s": "vim::Sentence",
"p": "vim::Paragraph",
"'": "vim::Quotes",
"`": "vim::BackQuotes",
"\"": "vim::DoubleQuotes",
"|": "vim::VerticalBars",
"(": "vim::Parentheses",
")": "vim::Parentheses",
"b": "vim::Parentheses",
"[": "vim::SquareBrackets",
"]": "vim::SquareBrackets",
"{": "vim::CurlyBrackets",
"}": "vim::CurlyBrackets",
"shift-b": "vim::CurlyBrackets",
"<": "vim::AngleBrackets",
">": "vim::AngleBrackets",
"a": "vim::Argument"
}
},
{
"context": "vim_operator == c",
"bindings": {
"c": "vim::CurrentLine",
"d": "editor::Rename", // zed specific
"s": ["vim::PushOperator", { "ChangeSurrounds": {} }]
}
},
{
"context": "vim_operator == d",
"bindings": {
"d": "vim::CurrentLine",
"s": ["vim::PushOperator", "DeleteSurrounds"]
}
},
{
"context": "vim_operator == gu",
"bindings": {
"g u": "vim::CurrentLine",
"u": "vim::CurrentLine"
}
},
{
"context": "vim_operator == gU",
"bindings": {
"g shift-u": "vim::CurrentLine",
"shift-u": "vim::CurrentLine"
}
},
{
"context": "vim_operator == g~",
"bindings": {
"g ~": "vim::CurrentLine",
"~": "vim::CurrentLine"
}
},
{
"context": "vim_operator == y",
"bindings": {
"y": "vim::CurrentLine",
"s": ["vim::PushOperator", { "AddSurrounds": {} }]
}
},
{
"context": "vim_operator == ys",
"bindings": {
"s": "vim::CurrentLine"
}
},
{
"context": "vim_operator == >",
"bindings": {
">": "vim::CurrentLine"
}
},
{
"context": "vim_operator == <",
"bindings": {
"<": "vim::CurrentLine"
}
},
{
@@ -507,7 +471,8 @@
"x": "project_panel::RevealInFileManager",
"shift-g": "menu::SelectLast",
"g g": "menu::SelectFirst",
"-": "project_panel::SelectParent"
"-": "project_panel::SelectParent",
"ctrl-6": "pane::AlternateFile"
}
},
{

View File

@@ -0,0 +1,241 @@
Your task is to map a step from the conversation above to operations on symbols inside the provided source files.
Guidelines:
- There's no need to describe *what* to do, just *where* to do it.
- If creating a file, assume any subsequent updates are included at the time of creation.
- Don't create and then update a file.
- We'll create it in one shot.
- Prefer updating symbols lower in the syntax tree if possible.
- Never include operations on a parent symbol and one of its children in the same <operations> block.
- Never nest an operation with another operation or include CDATA or other content. All operations are leaf nodes.
- Include a description attribute for each operation with a brief, one-line description of the change to perform.
- Descriptions are required for all operations except delete.
- When generating multiple operations, ensure the descriptions are specific to each individual operation.
- Avoid referring to the location in the description. Focus on the change to be made, not the location where it's made. That's implicit with the symbol you provide.
- Don't generate multiple operations at the same location. Instead, combine them together in a single operation with a succinct combined description.
The available operation types are:
1. <update>: Modify an existing symbol in a file.
2. <create_file>: Create a new file.
3. <insert_sibling_after>: Add a new symbol as sibling after an existing symbol in a file.
4. <append_child>: Add a new symbol as the last child of an existing symbol in a file.
5. <prepend_child>: Add a new symbol as the first child of an existing symbol in a file.
6. <delete>: Remove an existing symbol from a file. The `description` attribute is invalid for delete, but required for other ops.
All operations *require* a path.
Operations that *require* a symbol: <update>, <insert_sibling_after>, <delete>
Operations that don't allow a symbol: <create>
Operations that have an *optional* symbol: <prepend_child>, <append_child>
Example 1:
User:
```rs src/rectangle.rs
struct Rectangle {
width: f64,
height: f64,
}
impl Rectangle {
fn new(width: f64, height: f64) -> Self {
Rectangle { width, height }
}
}
```
Symbols for src/rectangle.rs:
- struct Rectangle
- impl Rectangle
- impl Rectangle fn new
<step>Add new methods 'calculate_area' and 'calculate_perimeter' to the Rectangle struct</step>
<step>Implement the 'Display' trait for the Rectangle struct</step>
What are the operations for the step: <step>Add a new method 'calculate_area' to the Rectangle struct</step>
Assistant (wrong):
<operations>
<append_child path="src/shapes.rs" symbol="impl Rectangle" description="Add calculate_area method" />
<append_child path="src/shapes.rs" symbol="impl Rectangle" description="Add calculate_perimeter method" />
</operations>
This demonstrates what NOT to do. NEVER append multiple children at the same location.
Assistant (corrected):
<operations>
<append_child path="src/shapes.rs" symbol="impl Rectangle" description="Add calculate area and perimeter methods" />
</operations>
User:
What are the operations for the step: <step>Implement the 'Display' trait for the Rectangle struct</step>
Assistant:
<operations>
<insert_sibling_after path="src/shapes.rs" symbol="impl Rectangle" description="Implement Display trait for Rectangle"/>
</operations>
Example 2:
User:
```rs src/user.rs
struct User {
pub name: String,
age: u32,
email: String,
}
impl User {
fn new(name: String, age: u32, email: String) -> Self {
User { name, age, email }
}
pub fn print_info(&self) {
println!("Name: {}, Age: {}, Email: {}", self.name, self.age, self.email);
}
}
```
Symbols for src/user.rs:
- struct User
- struct User pub name
- struct User age
- struct User email
- impl User
- impl User fn new
- impl User pub fn print_info
<step>Update the 'print_info' method to use formatted output</step>
<step>Remove the 'email' field from the User struct</step>
What are the operations for the step: <step>Update the 'print_info' method to use formatted output</step>
Assistant:
<operations>
<update path="src/user.rs" symbol="impl User fn print_info" description="Use formatted output" />
</operations>
User:
What are the operations for the step: <step>Remove the 'email' field from the User struct</step>
Assistant:
<operations>
<delete path="src/user.rs" symbol="struct User email" description="Remove the email field" />
</operations>
Example 3:
User:
```rs src/vehicle.rs
struct Vehicle {
make: String,
model: String,
year: u32,
}
impl Vehicle {
fn new(make: String, model: String, year: u32) -> Self {
Vehicle { make, model, year }
}
fn print_year(&self) {
println!("Year: {}", self.year);
}
}
```
Symbols for src/vehicle.rs:
- struct Vehicle
- struct Vehicle make
- struct Vehicle model
- struct Vehicle year
- impl Vehicle
- impl Vehicle fn new
- impl Vehicle fn print_year
<step>Add a 'use std::fmt;' statement at the beginning of the file</step>
<step>Add a new method 'start_engine' in the Vehicle impl block</step>
What are the operations for the step: <step>Add a 'use std::fmt;' statement at the beginning of the file</step>
Assistant:
<operations>
<prepend_child path="src/vehicle.rs" description="Add 'use std::fmt' statement" />
</operations>
User:
What are the operations for the step: <step>Add a new method 'start_engine' in the Vehicle impl block</step>
Assistant:
<operations>
<insert_sibling_after path="src/vehicle.rs" symbol="impl Vehicle fn new" description="Add start_engine method"/>
</operations>
Example 4:
User:
```rs src/employee.rs
struct Employee {
name: String,
position: String,
salary: u32,
department: String,
}
impl Employee {
fn new(name: String, position: String, salary: u32, department: String) -> Self {
Employee { name, position, salary, department }
}
fn print_details(&self) {
println!("Name: {}, Position: {}, Salary: {}, Department: {}",
self.name, self.position, self.salary, self.department);
}
fn give_raise(&mut self, amount: u32) {
self.salary += amount;
}
}
```
Symbols for src/employee.rs:
- struct Employee
- struct Employee name
- struct Employee position
- struct Employee salary
- struct Employee department
- impl Employee
- impl Employee fn new
- impl Employee fn print_details
- impl Employee fn give_raise
<step>Make salary an f32</step>
What are the operations for the step: <step>Make salary an f32</step>
A (wrong):
<operations>
<update path="src/employee.rs" symbol="struct Employee" description="Change the type of salary to an f32" />
<update path="src/employee.rs" symbol="struct Employee salary" description="Change the type to an f32" />
</operations>
This example demonstrates what not to do. `struct Employee salary` is a child of `struct Employee`.
A (corrected):
<operations>
<update path="src/employee.rs" symbol="struct Employee salary" description="Change the type to an f32" />
</operations>
User:
What are the correct operations for the step: <step>Remove the 'department' field and update the 'print_details' method</step>
A:
<operations>
<delete path="src/employee.rs" symbol="struct Employee department" />
<update path="src/employee.rs" symbol="impl Employee fn print_details" description="Don't print the 'department' field" />
</operations>
Now generate the operations for the following step.
Output only valid XML containing valid operations with their required attributes.
NEVER output code or any other text inside <operation> tags. If you do, you will replaced with another model.
Your response *MUST* begin with <operations> and end with </operations>:

View File

@@ -47,7 +47,7 @@
// },
"buffer_line_height": "comfortable",
// The name of a font to use for rendering text in the UI
// (On macOS) You can set this to ".SysmtemUIFont" to use the system font
// (On macOS) You can set this to ".SystemUIFont" to use the system font
"ui_font_family": "Zed Plex Sans",
// The OpenType features to enable for text in the UI
"ui_font_features": {
@@ -94,6 +94,9 @@
// 3. Never close the window
// "when_closing_with_no_tabs": "keep_window_open",
"when_closing_with_no_tabs": "platform_default",
// Whether to use the system provided dialogs for Open and Save As.
// When set to false, Zed will use the built-in keyboard-first pickers.
"use_system_path_prompts": true,
// Whether the cursor blinks in the editor.
"cursor_blink": true,
// How to highlight the current line in the editor.
@@ -116,6 +119,11 @@
// The debounce delay before re-querying the language server for completion
// documentation when not included in original completion list.
"completion_documentation_secondary_query_debounce": 300,
// Show method signatures in the editor, when inside parentheses.
"auto_signature_help": false,
/// Whether to show the signature help after completion or a bracket pair inserted.
/// If `auto_signature_help` is enabled, this setting will be treated as enabled also.
"show_signature_help_after_edits": true,
// Whether to show wrap guides (vertical rulers) in the editor.
// Setting this to true will show a guide at the 'preferred_line_length' value
// if softwrap is set to 'preferred_line_length', and will show any
@@ -128,14 +136,7 @@
// The default number of lines to expand excerpts in the multibuffer by.
"expand_excerpt_lines": 3,
// Globs to match against file paths to determine if a file is private.
"private_files": [
"**/.env*",
"**/*.pem",
"**/*.key",
"**/*.cert",
"**/*.crt",
"**/secrets.yml"
],
"private_files": ["**/.env*", "**/*.pem", "**/*.key", "**/*.cert", "**/*.crt", "**/secrets.yml"],
// Whether to use additional LSP queries to format (and amend) the code after
// every "trigger" symbol input, defined by LSP server capabilities.
"use_on_type_format": true,
@@ -262,6 +263,8 @@
// to both the horizontal and vertical delta values while scrolling.
"scroll_sensitivity": 1.0,
"relative_line_numbers": false,
// If 'search_wrap' is disabled, search result do not wrap around the end of the file.
"search_wrap": true,
// When to populate a new search's query based on the text under the cursor.
// This setting can take the following three values:
//
@@ -393,6 +396,7 @@
// 2. "gpt-4"
// 3. "gpt-4-turbo-preview"
// 4. "gpt-4o"
// 5. "gpt-4o-mini"
"default_model": "gpt-4o"
}
},
@@ -431,7 +435,9 @@
// Show git status colors in the editor tabs.
"git_status": false,
// Position of the close button on the editor tabs.
"close_position": "right"
"close_position": "right",
// Whether to show the file icon for a tab.
"file_icons": false
},
// Settings related to preview tabs.
"preview_tabs": {
@@ -539,6 +545,14 @@
// "delay_ms": 600
}
},
// Configuration for how direnv configuration should be loaded. May take 2 values:
// 1. Load direnv configuration through the shell hook, works for POSIX shells and fish.
// "load_direnv": "shell_hook"
// 2. Load direnv configuration using `direnv export json` directly.
// This can help with some shells that otherwise would not detect
// the direnv environment, such as nushell or elvish.
// "load_direnv": "direct"
"load_direnv": "shell_hook",
"inline_completions": {
// A list of globs representing files that inline completions should be disabled for.
"disabled_globs": [".env"]
@@ -691,7 +705,7 @@
//
"file_types": {
"JSON": ["flake.lock"],
"JSONC": ["**/.zed/**/*.json", "**/zed/**/*.json"]
"JSONC": ["**/.zed/**/*.json", "**/zed/**/*.json", "tsconfig.json"]
},
// The extensions that Zed should automatically install on startup.
//
@@ -714,10 +728,12 @@
}
},
"C": {
"format_on_save": "off"
"format_on_save": "off",
"use_on_type_format": false
},
"C++": {
"format_on_save": "off"
"format_on_save": "off",
"use_on_type_format": false
},
"CSS": {
"prettier": {
@@ -727,6 +743,9 @@
"Elixir": {
"language_servers": ["elixir-ls", "!next-ls", "!lexical", "..."]
},
"Erlang": {
"language_servers": ["erlang-ls", "!elp", "..."]
},
"Go": {
"code_actions_on_format": {
"source.organizeImports": true
@@ -769,11 +788,13 @@
},
"Markdown": {
"format_on_save": "off",
"use_on_type_format": false,
"prettier": {
"allowed": true
}
},
"PHP": {
"language_servers": ["phpactor", "!intelephense", "..."],
"prettier": {
"allowed": true,
"plugins": ["@prettier/plugin-php"],
@@ -781,7 +802,7 @@
}
},
"Ruby": {
"language_servers": ["solargraph", "!ruby-lsp", "..."]
"language_servers": ["solargraph", "!ruby-lsp", "!rubocop", "..."]
},
"SCSS": {
"prettier": {
@@ -918,5 +939,13 @@
// Examples:
// - "proxy": "socks5://localhost:10808"
// - "proxy": "http://127.0.0.1:10809"
"proxy": null
"proxy": null,
// Set to configure aliases for the command palette.
// When typing a query which is a key of this object, the value will be used instead.
//
// Examples:
// {
// "W": "workspace::Save"
// }
"command_aliases": {}
}

View File

@@ -4,8 +4,8 @@
// documentation: https://zed.dev/docs/configuring-zed
//
// To see all of Zed's default settings without changing your
// custom settings, run the `open default settings` command
// from the command palette or from `Zed` application menu.
// custom settings, run the `zed: Open Default Settings` command
// from the command palette
{
"ui_font_size": 16,
"buffer_font_size": 16,

View File

@@ -38,6 +38,7 @@
"icon.accent": "#10a793ff",
"status_bar.background": "#262933ff",
"title_bar.background": "#262933ff",
"title_bar.inactive_background": "#21242bff",
"toolbar.background": "#1e2025ff",
"tab_bar.background": "#21242bff",
"tab.inactive_background": "#21242bff",

View File

@@ -38,6 +38,7 @@
"icon.accent": "#566ddaff",
"status_bar.background": "#3a353fff",
"title_bar.background": "#3a353fff",
"title_bar.inactive_background": "#221f26ff",
"toolbar.background": "#19171cff",
"tab_bar.background": "#221f26ff",
"tab.inactive_background": "#221f26ff",
@@ -422,6 +423,7 @@
"icon.accent": "#586cdaff",
"status_bar.background": "#bfbcc5ff",
"title_bar.background": "#bfbcc5ff",
"title_bar.inactive_background": "#e6e3ebff",
"toolbar.background": "#efecf4ff",
"tab_bar.background": "#e6e3ebff",
"tab.inactive_background": "#e6e3ebff",
@@ -806,6 +808,7 @@
"icon.accent": "#6684e0ff",
"status_bar.background": "#45433bff",
"title_bar.background": "#45433bff",
"title_bar.inactive_background": "#262622ff",
"toolbar.background": "#20201dff",
"tab_bar.background": "#262622ff",
"tab.inactive_background": "#262622ff",
@@ -1190,6 +1193,7 @@
"icon.accent": "#6684dfff",
"status_bar.background": "#cecab4ff",
"title_bar.background": "#cecab4ff",
"title_bar.inactive_background": "#eeebd7ff",
"toolbar.background": "#fefbecff",
"tab_bar.background": "#eeebd7ff",
"tab.inactive_background": "#eeebd7ff",
@@ -1574,6 +1578,7 @@
"icon.accent": "#36a165ff",
"status_bar.background": "#424136ff",
"title_bar.background": "#424136ff",
"title_bar.inactive_background": "#2c2b23ff",
"toolbar.background": "#22221bff",
"tab_bar.background": "#2c2b23ff",
"tab.inactive_background": "#2c2b23ff",
@@ -1958,6 +1963,7 @@
"icon.accent": "#37a165ff",
"status_bar.background": "#c5c4b9ff",
"title_bar.background": "#c5c4b9ff",
"title_bar.inactive_background": "#ebeae3ff",
"toolbar.background": "#f4f3ecff",
"tab_bar.background": "#ebeae3ff",
"tab.inactive_background": "#ebeae3ff",
@@ -2342,6 +2348,7 @@
"icon.accent": "#407ee6ff",
"status_bar.background": "#443c39ff",
"title_bar.background": "#443c39ff",
"title_bar.inactive_background": "#27211eff",
"toolbar.background": "#1b1918ff",
"tab_bar.background": "#27211eff",
"tab.inactive_background": "#27211eff",
@@ -2726,6 +2733,7 @@
"icon.accent": "#407ee6ff",
"status_bar.background": "#ccc7c5ff",
"title_bar.background": "#ccc7c5ff",
"title_bar.inactive_background": "#e9e6e4ff",
"toolbar.background": "#f0eeedff",
"tab_bar.background": "#e9e6e4ff",
"tab.inactive_background": "#e9e6e4ff",
@@ -3110,6 +3118,7 @@
"icon.accent": "#5169ebff",
"status_bar.background": "#433a43ff",
"title_bar.background": "#433a43ff",
"title_bar.inactive_background": "#252025ff",
"toolbar.background": "#1b181bff",
"tab_bar.background": "#252025ff",
"tab.inactive_background": "#252025ff",
@@ -3494,6 +3503,7 @@
"icon.accent": "#5169ebff",
"status_bar.background": "#c6b8c6ff",
"title_bar.background": "#c6b8c6ff",
"title_bar.inactive_background": "#e0d5e0ff",
"toolbar.background": "#f7f3f7ff",
"tab_bar.background": "#e0d5e0ff",
"tab.inactive_background": "#e0d5e0ff",
@@ -3878,6 +3888,7 @@
"icon.accent": "#267eadff",
"status_bar.background": "#33444dff",
"title_bar.background": "#33444dff",
"title_bar.inactive_background": "#1c2529ff",
"toolbar.background": "#161b1dff",
"tab_bar.background": "#1c2529ff",
"tab.inactive_background": "#1c2529ff",
@@ -4262,6 +4273,7 @@
"icon.accent": "#267eadff",
"status_bar.background": "#a6cadcff",
"title_bar.background": "#a6cadcff",
"title_bar.inactive_background": "#cdeaf9ff",
"toolbar.background": "#ebf8ffff",
"tab_bar.background": "#cdeaf9ff",
"tab.inactive_background": "#cdeaf9ff",
@@ -4646,6 +4658,7 @@
"icon.accent": "#7272caff",
"status_bar.background": "#3b3535ff",
"title_bar.background": "#3b3535ff",
"title_bar.inactive_background": "#252020ff",
"toolbar.background": "#1b1818ff",
"tab_bar.background": "#252020ff",
"tab.inactive_background": "#252020ff",
@@ -5030,6 +5043,7 @@
"icon.accent": "#7272caff",
"status_bar.background": "#c1bbbbff",
"title_bar.background": "#c1bbbbff",
"title_bar.inactive_background": "#ebe3e3ff",
"toolbar.background": "#f4ececff",
"tab_bar.background": "#ebe3e3ff",
"tab.inactive_background": "#ebe3e3ff",
@@ -5414,6 +5428,7 @@
"icon.accent": "#468b8fff",
"status_bar.background": "#353f39ff",
"title_bar.background": "#353f39ff",
"title_bar.inactive_background": "#1f2621ff",
"toolbar.background": "#171c19ff",
"tab_bar.background": "#1f2621ff",
"tab.inactive_background": "#1f2621ff",
@@ -5798,6 +5813,7 @@
"icon.accent": "#488b90ff",
"status_bar.background": "#bcc5bfff",
"title_bar.background": "#bcc5bfff",
"title_bar.inactive_background": "#e3ebe6ff",
"toolbar.background": "#ecf4eeff",
"tab_bar.background": "#e3ebe6ff",
"tab.inactive_background": "#e3ebe6ff",
@@ -6182,6 +6198,7 @@
"icon.accent": "#3e62f4ff",
"status_bar.background": "#3b453bff",
"title_bar.background": "#3b453bff",
"title_bar.inactive_background": "#1f231fff",
"toolbar.background": "#131513ff",
"tab_bar.background": "#1f231fff",
"tab.inactive_background": "#1f231fff",
@@ -6566,6 +6583,7 @@
"icon.accent": "#3e61f4ff",
"status_bar.background": "#b4ceb4ff",
"title_bar.background": "#b4ceb4ff",
"title_bar.inactive_background": "#daeedaff",
"toolbar.background": "#f3faf3ff",
"tab_bar.background": "#daeedaff",
"tab.inactive_background": "#daeedaff",
@@ -6950,6 +6968,7 @@
"icon.accent": "#3e8ed0ff",
"status_bar.background": "#3e4769ff",
"title_bar.background": "#3e4769ff",
"title_bar.inactive_background": "#262f51ff",
"toolbar.background": "#202646ff",
"tab_bar.background": "#262f51ff",
"tab.inactive_background": "#262f51ff",
@@ -7334,6 +7353,7 @@
"icon.accent": "#3e8fd0ff",
"status_bar.background": "#c1c5d8ff",
"title_bar.background": "#c1c5d8ff",
"title_bar.inactive_background": "#e5e8f5ff",
"toolbar.background": "#f5f7ffff",
"tab_bar.background": "#e5e8f5ff",
"tab.inactive_background": "#e5e8f5ff",

View File

@@ -38,6 +38,7 @@
"icon.accent": "#5ac1feff",
"status_bar.background": "#313337ff",
"title_bar.background": "#313337ff",
"title_bar.inactive_background": "#1f2127ff",
"toolbar.background": "#0d1016ff",
"tab_bar.background": "#1f2127ff",
"tab.inactive_background": "#1f2127ff",
@@ -407,6 +408,7 @@
"icon.accent": "#3b9ee5ff",
"status_bar.background": "#dcdddeff",
"title_bar.background": "#dcdddeff",
"title_bar.inactive_background": "#ececedff",
"toolbar.background": "#fcfcfcff",
"tab_bar.background": "#ececedff",
"tab.inactive_background": "#ececedff",
@@ -776,6 +778,7 @@
"icon.accent": "#72cffeff",
"status_bar.background": "#464a52ff",
"title_bar.background": "#464a52ff",
"title_bar.inactive_background": "#353944ff",
"toolbar.background": "#242835ff",
"tab_bar.background": "#353944ff",
"tab.inactive_background": "#353944ff",

View File

@@ -47,6 +47,7 @@
"icon.accent": "#83a598ff",
"status_bar.background": "#4c4642ff",
"title_bar.background": "#4c4642ff",
"title_bar.inactive_background": "#3a3735ff",
"toolbar.background": "#282828ff",
"tab_bar.background": "#3a3735ff",
"tab.inactive_background": "#3a3735ff",
@@ -430,6 +431,7 @@
"icon.accent": "#83a598ff",
"status_bar.background": "#4c4642ff",
"title_bar.background": "#4c4642ff",
"title_bar.inactive_background": "#393634ff",
"toolbar.background": "#1d2021ff",
"tab_bar.background": "#393634ff",
"tab.inactive_background": "#393634ff",
@@ -813,6 +815,7 @@
"icon.accent": "#83a598ff",
"status_bar.background": "#4c4642ff",
"title_bar.background": "#4c4642ff",
"title_bar.inactive_background": "#3b3735ff",
"toolbar.background": "#32302fff",
"tab_bar.background": "#3b3735ff",
"tab.inactive_background": "#3b3735ff",
@@ -1196,6 +1199,7 @@
"icon.accent": "#0b6678ff",
"status_bar.background": "#d9c8a4ff",
"title_bar.background": "#d9c8a4ff",
"title_bar.inactive_background": "#ecddb4ff",
"toolbar.background": "#fbf1c7ff",
"tab_bar.background": "#ecddb4ff",
"tab.inactive_background": "#ecddb4ff",
@@ -1579,6 +1583,7 @@
"icon.accent": "#0b6678ff",
"status_bar.background": "#d9c8a4ff",
"title_bar.background": "#d9c8a4ff",
"title_bar.inactive_background": "#ecddb5ff",
"toolbar.background": "#f9f5d7ff",
"tab_bar.background": "#ecddb5ff",
"tab.inactive_background": "#ecddb5ff",
@@ -1962,6 +1967,7 @@
"icon.accent": "#0b6678ff",
"status_bar.background": "#d9c8a4ff",
"title_bar.background": "#d9c8a4ff",
"title_bar.inactive_background": "#ecdcb3ff",
"toolbar.background": "#f2e5bcff",
"tab_bar.background": "#ecdcb3ff",
"tab.inactive_background": "#ecdcb3ff",

View File

@@ -38,6 +38,7 @@
"icon.accent": "#74ade8ff",
"status_bar.background": "#3b414dff",
"title_bar.background": "#3b414dff",
"title_bar.inactive_background": "#2e343eff",
"toolbar.background": "#282c33ff",
"tab_bar.background": "#2f343eff",
"tab.inactive_background": "#2f343eff",
@@ -412,6 +413,7 @@
"icon.accent": "#5c78e2ff",
"status_bar.background": "#dcdcddff",
"title_bar.background": "#dcdcddff",
"title_bar.inactive_background": "#ebebecff",
"toolbar.background": "#fafafaff",
"tab_bar.background": "#ebebecff",
"tab.inactive_background": "#ebebecff",
@@ -491,7 +493,7 @@
"info": "#5c78e2ff",
"info.background": "#e2e2faff",
"info.border": "#cbcdf6ff",
"modified": "#dec184ff",
"modified": "#a47a23ff",
"modified.background": "#faf2e6ff",
"modified.border": "#f4e7d1ff",
"predictive": "#9b9ec6ff",

View File

@@ -38,6 +38,7 @@
"icon.accent": "#9bced6ff",
"status_bar.background": "#292738ff",
"title_bar.background": "#292738ff",
"title_bar.inactive_background": "#1c1b2aff",
"toolbar.background": "#191724ff",
"tab_bar.background": "#1c1b2aff",
"tab.inactive_background": "#1c1b2aff",
@@ -417,6 +418,7 @@
"icon.accent": "#57949fff",
"status_bar.background": "#dcd8d8ff",
"title_bar.background": "#dcd8d8ff",
"title_bar.inactive_background": "#fef9f2ff",
"toolbar.background": "#faf4edff",
"tab_bar.background": "#fef9f2ff",
"tab.inactive_background": "#fef9f2ff",
@@ -796,6 +798,7 @@
"icon.accent": "#9bced6ff",
"status_bar.background": "#38354eff",
"title_bar.background": "#38354eff",
"title_bar.inactive_background": "#28253cff",
"toolbar.background": "#232136ff",
"tab_bar.background": "#28253cff",
"tab.inactive_background": "#28253cff",

View File

@@ -38,6 +38,7 @@
"icon.accent": "#518b8bff",
"status_bar.background": "#333944ff",
"title_bar.background": "#333944ff",
"title_bar.inactive_background": "#2b3038ff",
"toolbar.background": "#282c33ff",
"tab_bar.background": "#2b3038ff",
"tab.inactive_background": "#2b3038ff",

View File

@@ -38,6 +38,7 @@
"icon.accent": "#278ad1ff",
"status_bar.background": "#073743ff",
"title_bar.background": "#073743ff",
"title_bar.inactive_background": "#04313bff",
"toolbar.background": "#002a35ff",
"tab_bar.background": "#04313bff",
"tab.inactive_background": "#04313bff",
@@ -407,6 +408,7 @@
"icon.accent": "#288bd1ff",
"status_bar.background": "#cfd0c4ff",
"title_bar.background": "#cfd0c4ff",
"title_bar.inactive_background": "#f3eddaff",
"toolbar.background": "#fdf6e3ff",
"tab_bar.background": "#f3eddaff",
"tab.inactive_background": "#f3eddaff",

View File

@@ -38,6 +38,7 @@
"icon.accent": "#499befff",
"status_bar.background": "#2a261cff",
"title_bar.background": "#2a261cff",
"title_bar.inactive_background": "#231f16ff",
"toolbar.background": "#1b1810ff",
"tab_bar.background": "#231f16ff",
"tab.inactive_background": "#231f16ff",

View File

@@ -107,6 +107,7 @@ impl ActivityIndicator {
Editor::for_buffer(buffer, Some(project.clone()), cx)
})),
None,
true,
cx,
);
})?;

View File

@@ -20,6 +20,12 @@ pub enum Model {
Claude3Sonnet,
#[serde(alias = "claude-3-haiku", rename = "claude-3-haiku-20240307")]
Claude3Haiku,
#[serde(rename = "custom")]
Custom {
name: String,
#[serde(default)]
max_tokens: Option<usize>,
},
}
impl Model {
@@ -33,30 +39,41 @@ impl Model {
} else if id.starts_with("claude-3-haiku") {
Ok(Self::Claude3Haiku)
} else {
Err(anyhow!("Invalid model id: {}", id))
Ok(Self::Custom {
name: id.to_string(),
max_tokens: None,
})
}
}
pub fn id(&self) -> &'static str {
pub fn id(&self) -> &str {
match self {
Model::Claude3_5Sonnet => "claude-3-5-sonnet-20240620",
Model::Claude3Opus => "claude-3-opus-20240229",
Model::Claude3Sonnet => "claude-3-sonnet-20240229",
Model::Claude3Haiku => "claude-3-opus-20240307",
Model::Custom { name, .. } => name,
}
}
pub fn display_name(&self) -> &'static str {
pub fn display_name(&self) -> &str {
match self {
Self::Claude3_5Sonnet => "Claude 3.5 Sonnet",
Self::Claude3Opus => "Claude 3 Opus",
Self::Claude3Sonnet => "Claude 3 Sonnet",
Self::Claude3Haiku => "Claude 3 Haiku",
Self::Custom { name, .. } => name,
}
}
pub fn max_token_count(&self) -> usize {
200_000
match self {
Self::Claude3_5Sonnet
| Self::Claude3Opus
| Self::Claude3Sonnet
| Self::Claude3Haiku => 200_000,
Self::Custom { max_tokens, .. } => max_tokens.unwrap_or(200_000),
}
}
}
@@ -90,6 +107,7 @@ impl From<Role> for String {
#[derive(Debug, Serialize)]
pub struct Request {
#[serde(serialize_with = "serialize_request_model")]
pub model: Model,
pub messages: Vec<RequestMessage>,
pub stream: bool,
@@ -97,6 +115,13 @@ pub struct Request {
pub max_tokens: u32,
}
fn serialize_request_model<S>(model: &Model, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&model.id())
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct RequestMessage {
pub role: Role,

View File

@@ -12,17 +12,28 @@ workspace = true
path = "src/assistant.rs"
doctest = false
[features]
test-support = [
"editor/test-support",
"language/test-support",
"project/test-support",
"text/test-support",
]
[dependencies]
anthropic = { workspace = true, features = ["schemars"] }
anyhow.workspace = true
assets.workspace = true
assistant_slash_command.workspace = true
async-watch.workspace = true
breadcrumbs.workspace = true
cargo_toml.workspace = true
chrono.workspace = true
client.workspace = true
clock.workspace = true
collections.workspace = true
command_palette_hooks.workspace = true
completion.workspace = true
editor.workspace = true
feature_flags.workspace = true
fs.workspace = true
@@ -35,6 +46,7 @@ http.workspace = true
indexed_docs.workspace = true
indoc.workspace = true
language.workspace = true
language_model.workspace = true
log.workspace = true
menu.workspace = true
multi_buffer.workspace = true
@@ -54,25 +66,26 @@ serde_json.workspace = true
settings.workspace = true
similar.workspace = true
smol.workspace = true
strsim = "0.11"
strum.workspace = true
telemetry_events.workspace = true
terminal.workspace = true
terminal_view.workspace = true
theme.workspace = true
tiktoken-rs.workspace = true
toml.workspace = true
ui.workspace = true
util.workspace = true
uuid.workspace = true
workspace.workspace = true
picker.workspace = true
roxmltree = "0.20.0"
[dev-dependencies]
completion = { workspace = true, features = ["test-support"] }
ctor.workspace = true
editor = { workspace = true, features = ["test-support"] }
env_logger.workspace = true
language = { workspace = true, features = ["test-support"] }
log.workspace = true
project = { workspace = true, features = ["test-support"] }
rand.workspace = true
text = { workspace = true, features = ["test-support"] }
unindent.workspace = true

View File

@@ -1,40 +1,40 @@
pub mod assistant_panel;
pub mod assistant_settings;
mod completion_provider;
mod context_store;
mod context;
pub mod context_store;
mod inline_assistant;
mod model_selector;
mod prompt_library;
mod prompts;
mod search;
mod slash_command;
mod streaming_diff;
mod terminal_inline_assistant;
pub use assistant_panel::{AssistantPanel, AssistantPanelEvent};
use assistant_settings::{AnthropicModel, AssistantSettings, CloudModel, OllamaModel, OpenAiModel};
use assistant_settings::AssistantSettings;
use assistant_slash_command::SlashCommandRegistry;
use client::{proto, Client};
use command_palette_hooks::CommandPaletteFilter;
pub(crate) use completion_provider::*;
pub(crate) use context_store::*;
use completion::CompletionProvider;
pub use context::*;
pub use context_store::*;
use fs::Fs;
use gpui::{actions, AppContext, Global, SharedString, UpdateGlobal};
use gpui::{
actions, impl_actions, AppContext, BorrowAppContext, Global, SharedString, UpdateGlobal,
};
use indexed_docs::IndexedDocsRegistry;
pub(crate) use inline_assistant::*;
use language_model::LanguageModelResponseMessage;
pub(crate) use model_selector::*;
use semantic_index::{CloudEmbeddingProvider, SemanticIndex};
use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsStore};
use slash_command::{
active_command, default_command, diagnostics_command, docs_command, fetch_command,
file_command, now_command, project_command, prompt_command, search_command, tabs_command,
term_command,
};
use std::{
fmt::{self, Display},
sync::Arc,
file_command, now_command, project_command, prompt_command, search_command, symbols_command,
tabs_command, term_command,
};
use std::sync::Arc;
pub(crate) use streaming_diff::*;
actions!(
@@ -47,167 +47,31 @@ actions!(
InsertIntoEditor,
ToggleFocus,
ResetKey,
InlineAssist,
InsertActivePrompt,
DeployHistory,
DeployPromptLibrary,
ApplyEdit,
ConfirmCommand,
ToggleModelSelector
ToggleModelSelector,
DebugEditSteps
]
);
#[derive(
Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
struct MessageId(usize);
#[derive(Clone, Copy, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Role {
User,
Assistant,
System,
#[derive(Clone, Default, Deserialize, PartialEq)]
pub struct InlineAssist {
prompt: Option<String>,
}
impl Role {
pub fn cycle(&mut self) {
*self = match self {
Role::User => Role::Assistant,
Role::Assistant => Role::System,
Role::System => Role::User,
}
impl_actions!(assistant, [InlineAssist]);
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct MessageId(clock::Lamport);
impl MessageId {
pub fn as_u64(self) -> u64 {
self.0.as_u64()
}
}
impl Display for Role {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Role::User => write!(f, "user"),
Role::Assistant => write!(f, "assistant"),
Role::System => write!(f, "system"),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum LanguageModel {
Cloud(CloudModel),
OpenAi(OpenAiModel),
Anthropic(AnthropicModel),
Ollama(OllamaModel),
}
impl Default for LanguageModel {
fn default() -> Self {
LanguageModel::Cloud(CloudModel::default())
}
}
impl LanguageModel {
pub fn telemetry_id(&self) -> String {
match self {
LanguageModel::OpenAi(model) => format!("openai/{}", model.id()),
LanguageModel::Anthropic(model) => format!("anthropic/{}", model.id()),
LanguageModel::Cloud(model) => format!("zed.dev/{}", model.id()),
LanguageModel::Ollama(model) => format!("ollama/{}", model.id()),
}
}
pub fn display_name(&self) -> String {
match self {
LanguageModel::OpenAi(model) => model.display_name().into(),
LanguageModel::Anthropic(model) => model.display_name().into(),
LanguageModel::Cloud(model) => model.display_name().into(),
LanguageModel::Ollama(model) => model.display_name().into(),
}
}
pub fn max_token_count(&self) -> usize {
match self {
LanguageModel::OpenAi(model) => model.max_token_count(),
LanguageModel::Anthropic(model) => model.max_token_count(),
LanguageModel::Cloud(model) => model.max_token_count(),
LanguageModel::Ollama(model) => model.max_token_count(),
}
}
pub fn id(&self) -> &str {
match self {
LanguageModel::OpenAi(model) => model.id(),
LanguageModel::Anthropic(model) => model.id(),
LanguageModel::Cloud(model) => model.id(),
LanguageModel::Ollama(model) => model.id(),
}
}
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct LanguageModelRequestMessage {
pub role: Role,
pub content: String,
}
impl LanguageModelRequestMessage {
pub fn to_proto(&self) -> proto::LanguageModelRequestMessage {
proto::LanguageModelRequestMessage {
role: match self.role {
Role::User => proto::LanguageModelRole::LanguageModelUser,
Role::Assistant => proto::LanguageModelRole::LanguageModelAssistant,
Role::System => proto::LanguageModelRole::LanguageModelSystem,
} as i32,
content: self.content.clone(),
tool_calls: Vec::new(),
tool_call_id: None,
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct LanguageModelRequest {
pub model: LanguageModel,
pub messages: Vec<LanguageModelRequestMessage>,
pub stop: Vec<String>,
pub temperature: f32,
}
impl LanguageModelRequest {
pub fn to_proto(&self) -> proto::CompleteWithLanguageModel {
proto::CompleteWithLanguageModel {
model: self.model.id().to_string(),
messages: self.messages.iter().map(|m| m.to_proto()).collect(),
stop: self.stop.clone(),
temperature: self.temperature,
tool_choice: None,
tools: Vec::new(),
}
}
/// Before we send the request to the server, we can perform fixups on it appropriate to the model.
pub fn preprocess(&mut self) {
match &self.model {
LanguageModel::OpenAi(_) => {}
LanguageModel::Anthropic(_) => {}
LanguageModel::Ollama(_) => {}
LanguageModel::Cloud(model) => match model {
CloudModel::Claude3Opus
| CloudModel::Claude3Sonnet
| CloudModel::Claude3Haiku
| CloudModel::Claude3_5Sonnet => {
preprocess_anthropic_request(self);
}
_ => {}
},
}
}
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct LanguageModelResponseMessage {
pub role: Option<Role>,
pub content: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct LanguageModelUsage {
pub prompt_tokens: u32,
@@ -222,19 +86,48 @@ pub struct LanguageModelChoiceDelta {
pub finish_reason: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct MessageMetadata {
role: Role,
status: MessageStatus,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
enum MessageStatus {
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum MessageStatus {
Pending,
Done,
Error(SharedString),
}
impl MessageStatus {
pub fn from_proto(status: proto::ContextMessageStatus) -> MessageStatus {
match status.variant {
Some(proto::context_message_status::Variant::Pending(_)) => MessageStatus::Pending,
Some(proto::context_message_status::Variant::Done(_)) => MessageStatus::Done,
Some(proto::context_message_status::Variant::Error(error)) => {
MessageStatus::Error(error.message.into())
}
None => MessageStatus::Pending,
}
}
pub fn to_proto(&self) -> proto::ContextMessageStatus {
match self {
MessageStatus::Pending => proto::ContextMessageStatus {
variant: Some(proto::context_message_status::Variant::Pending(
proto::context_message_status::Pending {},
)),
},
MessageStatus::Done => proto::ContextMessageStatus {
variant: Some(proto::context_message_status::Variant::Done(
proto::context_message_status::Done {},
)),
},
MessageStatus::Error(message) => proto::ContextMessageStatus {
variant: Some(proto::context_message_status::Variant::Error(
proto::context_message_status::Error {
message: message.to_string(),
},
)),
},
}
}
}
/// The state pertaining to the Assistant.
#[derive(Default)]
struct Assistant {
@@ -287,8 +180,9 @@ pub fn init(fs: Arc<dyn Fs>, client: Arc<Client>, cx: &mut AppContext) {
})
.detach();
context_store::init(&client);
prompt_library::init(cx);
completion_provider::init(client.clone(), cx);
init_completion_provider(Arc::clone(&client), cx);
assistant_slash_command::init(cx);
register_slash_commands(cx);
assistant_panel::init(cx);
@@ -313,10 +207,25 @@ pub fn init(fs: Arc<dyn Fs>, client: Arc<Client>, cx: &mut AppContext) {
.detach();
}
fn init_completion_provider(client: Arc<Client>, cx: &mut AppContext) {
let provider = assistant_settings::create_provider_from_settings(client.clone(), 0, cx);
cx.set_global(CompletionProvider::new(provider, Some(client)));
let mut settings_version = 0;
cx.observe_global::<SettingsStore>(move |cx| {
settings_version += 1;
cx.update_global::<CompletionProvider, _>(|provider, cx| {
assistant_settings::update_completion_provider_settings(provider, settings_version, cx);
})
})
.detach();
}
fn register_slash_commands(cx: &mut AppContext) {
let slash_command_registry = SlashCommandRegistry::global(cx);
slash_command_registry.register_command(file_command::FileSlashCommand, true);
slash_command_registry.register_command(active_command::ActiveSlashCommand, true);
slash_command_registry.register_command(symbols_command::OutlineSlashCommand, true);
slash_command_registry.register_command(tabs_command::TabsSlashCommand, true);
slash_command_registry.register_command(project_command::ProjectSlashCommand, true);
slash_command_registry.register_command(search_command::SearchSlashCommand, true);

File diff suppressed because it is too large Load Diff

View File

@@ -1,154 +1,19 @@
use std::fmt;
use std::{sync::Arc, time::Duration};
use crate::{preprocess_anthropic_request, LanguageModel, LanguageModelRequest};
pub use anthropic::Model as AnthropicModel;
use gpui::Pixels;
pub use ollama::Model as OllamaModel;
pub use open_ai::Model as OpenAiModel;
use schemars::{
schema::{InstanceType, Metadata, Schema, SchemaObject},
JsonSchema,
};
use serde::{
de::{self, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
use anthropic::Model as AnthropicModel;
use client::Client;
use completion::{
AnthropicCompletionProvider, CloudCompletionProvider, CompletionProvider,
LanguageModelCompletionProvider, OllamaCompletionProvider, OpenAiCompletionProvider,
};
use gpui::{AppContext, Pixels};
use language_model::{CloudModel, LanguageModel};
use ollama::Model as OllamaModel;
use open_ai::Model as OpenAiModel;
use parking_lot::RwLock;
use schemars::{schema::Schema, JsonSchema};
use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsSources};
use strum::{EnumIter, IntoEnumIterator};
#[derive(Clone, Debug, Default, PartialEq, EnumIter)]
pub enum CloudModel {
Gpt3Point5Turbo,
Gpt4,
Gpt4Turbo,
#[default]
Gpt4Omni,
Claude3_5Sonnet,
Claude3Opus,
Claude3Sonnet,
Claude3Haiku,
Custom(String),
}
impl Serialize for CloudModel {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.id())
}
}
impl<'de> Deserialize<'de> for CloudModel {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct ZedDotDevModelVisitor;
impl<'de> Visitor<'de> for ZedDotDevModelVisitor {
type Value = CloudModel;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string for a ZedDotDevModel variant or a custom model")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
let model = CloudModel::iter()
.find(|model| model.id() == value)
.unwrap_or_else(|| CloudModel::Custom(value.to_string()));
Ok(model)
}
}
deserializer.deserialize_str(ZedDotDevModelVisitor)
}
}
impl JsonSchema for CloudModel {
fn schema_name() -> String {
"ZedDotDevModel".to_owned()
}
fn json_schema(_generator: &mut schemars::gen::SchemaGenerator) -> Schema {
let variants = CloudModel::iter()
.filter_map(|model| {
let id = model.id();
if id.is_empty() {
None
} else {
Some(id.to_string())
}
})
.collect::<Vec<_>>();
Schema::Object(SchemaObject {
instance_type: Some(InstanceType::String.into()),
enum_values: Some(variants.iter().map(|s| s.clone().into()).collect()),
metadata: Some(Box::new(Metadata {
title: Some("ZedDotDevModel".to_owned()),
default: Some(CloudModel::default().id().into()),
examples: variants.into_iter().map(Into::into).collect(),
..Default::default()
})),
..Default::default()
})
}
}
impl CloudModel {
pub fn id(&self) -> &str {
match self {
Self::Gpt3Point5Turbo => "gpt-3.5-turbo",
Self::Gpt4 => "gpt-4",
Self::Gpt4Turbo => "gpt-4-turbo-preview",
Self::Gpt4Omni => "gpt-4o",
Self::Claude3_5Sonnet => "claude-3-5-sonnet",
Self::Claude3Opus => "claude-3-opus",
Self::Claude3Sonnet => "claude-3-sonnet",
Self::Claude3Haiku => "claude-3-haiku",
Self::Custom(id) => id,
}
}
pub fn display_name(&self) -> &str {
match self {
Self::Gpt3Point5Turbo => "GPT 3.5 Turbo",
Self::Gpt4 => "GPT 4",
Self::Gpt4Turbo => "GPT 4 Turbo",
Self::Gpt4Omni => "GPT 4 Omni",
Self::Claude3_5Sonnet => "Claude 3.5 Sonnet",
Self::Claude3Opus => "Claude 3 Opus",
Self::Claude3Sonnet => "Claude 3 Sonnet",
Self::Claude3Haiku => "Claude 3 Haiku",
Self::Custom(id) => id.as_str(),
}
}
pub fn max_token_count(&self) -> usize {
match self {
Self::Gpt3Point5Turbo => 2048,
Self::Gpt4 => 4096,
Self::Gpt4Turbo | Self::Gpt4Omni => 128000,
Self::Claude3_5Sonnet
| Self::Claude3Opus
| Self::Claude3Sonnet
| Self::Claude3Haiku => 200000,
Self::Custom(_) => 4096, // TODO: Make this configurable
}
}
pub fn preprocess_request(&self, request: &mut LanguageModelRequest) {
match self {
Self::Claude3Opus | Self::Claude3Sonnet | Self::Claude3Haiku => {
preprocess_anthropic_request(request)
}
_ => {}
}
}
}
#[derive(Copy, Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
@@ -608,6 +473,124 @@ fn merge<T>(target: &mut T, value: Option<T>) {
}
}
pub fn update_completion_provider_settings(
provider: &mut CompletionProvider,
version: usize,
cx: &mut AppContext,
) {
let updated = match &AssistantSettings::get_global(cx).provider {
AssistantProvider::ZedDotDev { model } => provider
.update_current_as::<_, CloudCompletionProvider>(|provider| {
provider.update(model.clone(), version);
}),
AssistantProvider::OpenAi {
model,
api_url,
low_speed_timeout_in_seconds,
available_models,
} => provider.update_current_as::<_, OpenAiCompletionProvider>(|provider| {
provider.update(
choose_openai_model(&model, &available_models),
api_url.clone(),
low_speed_timeout_in_seconds.map(Duration::from_secs),
version,
);
}),
AssistantProvider::Anthropic {
model,
api_url,
low_speed_timeout_in_seconds,
} => provider.update_current_as::<_, AnthropicCompletionProvider>(|provider| {
provider.update(
model.clone(),
api_url.clone(),
low_speed_timeout_in_seconds.map(Duration::from_secs),
version,
);
}),
AssistantProvider::Ollama {
model,
api_url,
low_speed_timeout_in_seconds,
} => provider.update_current_as::<_, OllamaCompletionProvider>(|provider| {
provider.update(
model.clone(),
api_url.clone(),
low_speed_timeout_in_seconds.map(Duration::from_secs),
version,
cx,
);
}),
};
// Previously configured provider was changed to another one
if updated.is_none() {
provider.update_provider(|client| create_provider_from_settings(client, version, cx));
}
}
pub(crate) fn create_provider_from_settings(
client: Arc<Client>,
settings_version: usize,
cx: &mut AppContext,
) -> Arc<RwLock<dyn LanguageModelCompletionProvider>> {
match &AssistantSettings::get_global(cx).provider {
AssistantProvider::ZedDotDev { model } => Arc::new(RwLock::new(
CloudCompletionProvider::new(model.clone(), client.clone(), settings_version, cx),
)),
AssistantProvider::OpenAi {
model,
api_url,
low_speed_timeout_in_seconds,
available_models,
} => Arc::new(RwLock::new(OpenAiCompletionProvider::new(
choose_openai_model(&model, &available_models),
api_url.clone(),
client.http_client(),
low_speed_timeout_in_seconds.map(Duration::from_secs),
settings_version,
available_models.clone(),
))),
AssistantProvider::Anthropic {
model,
api_url,
low_speed_timeout_in_seconds,
} => Arc::new(RwLock::new(AnthropicCompletionProvider::new(
model.clone(),
api_url.clone(),
client.http_client(),
low_speed_timeout_in_seconds.map(Duration::from_secs),
settings_version,
))),
AssistantProvider::Ollama {
model,
api_url,
low_speed_timeout_in_seconds,
} => Arc::new(RwLock::new(OllamaCompletionProvider::new(
model.clone(),
api_url.clone(),
client.http_client(),
low_speed_timeout_in_seconds.map(Duration::from_secs),
settings_version,
cx,
))),
}
}
/// Choose which model to use for openai provider.
/// If the model is not available, try to use the first available model, or fallback to the original model.
fn choose_openai_model(
model: &::open_ai::Model,
available_models: &[::open_ai::Model],
) -> ::open_ai::Model {
available_models
.iter()
.find(|&m| m == model)
.or_else(|| available_models.first())
.unwrap_or_else(|| model)
.clone()
}
#[cfg(test)]
mod tests {
use gpui::{AppContext, UpdateGlobal};
@@ -685,7 +668,11 @@ mod tests {
"version": "1",
"provider": {
"name": "zed.dev",
"default_model": "custom"
"default_model": {
"custom": {
"name": "custom-provider"
}
}
}
}
}"#,
@@ -696,7 +683,10 @@ mod tests {
assert_eq!(
AssistantSettings::get_global(cx).provider,
AssistantProvider::ZedDotDev {
model: CloudModel::Custom("custom".into())
model: CloudModel::Custom {
name: "custom-provider".into(),
max_tokens: None
}
}
);
}

View File

@@ -1,373 +0,0 @@
mod anthropic;
mod cloud;
#[cfg(test)]
mod fake;
mod ollama;
mod open_ai;
pub use anthropic::*;
pub use cloud::*;
#[cfg(test)]
pub use fake::*;
pub use ollama::*;
pub use open_ai::*;
use parking_lot::RwLock;
use smol::lock::{Semaphore, SemaphoreGuardArc};
use crate::{
assistant_settings::{AssistantProvider, AssistantSettings},
LanguageModel, LanguageModelRequest,
};
use anyhow::Result;
use client::Client;
use futures::{future::BoxFuture, stream::BoxStream};
use gpui::{AnyView, AppContext, BorrowAppContext, Task, WindowContext};
use settings::{Settings, SettingsStore};
use std::time::Duration;
use std::{any::Any, sync::Arc};
/// Choose which model to use for openai provider.
/// If the model is not available, try to use the first available model, or fallback to the original model.
fn choose_openai_model(
model: &::open_ai::Model,
available_models: &[::open_ai::Model],
) -> ::open_ai::Model {
available_models
.iter()
.find(|&m| m == model)
.or_else(|| available_models.first())
.unwrap_or_else(|| model)
.clone()
}
pub fn init(client: Arc<Client>, cx: &mut AppContext) {
let provider = create_provider_from_settings(client.clone(), 0, cx);
cx.set_global(CompletionProvider::new(provider, Some(client)));
let mut settings_version = 0;
cx.observe_global::<SettingsStore>(move |cx| {
settings_version += 1;
cx.update_global::<CompletionProvider, _>(|provider, cx| {
provider.update_settings(settings_version, cx);
})
})
.detach();
}
pub struct CompletionResponse {
pub inner: BoxFuture<'static, Result<BoxStream<'static, Result<String>>>>,
_lock: SemaphoreGuardArc,
}
pub trait LanguageModelCompletionProvider: Send + Sync {
fn available_models(&self, cx: &AppContext) -> Vec<LanguageModel>;
fn settings_version(&self) -> usize;
fn is_authenticated(&self) -> bool;
fn authenticate(&self, cx: &AppContext) -> Task<Result<()>>;
fn authentication_prompt(&self, cx: &mut WindowContext) -> AnyView;
fn reset_credentials(&self, cx: &AppContext) -> Task<Result<()>>;
fn model(&self) -> LanguageModel;
fn count_tokens(
&self,
request: LanguageModelRequest,
cx: &AppContext,
) -> BoxFuture<'static, Result<usize>>;
fn complete(
&self,
request: LanguageModelRequest,
) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>>;
fn as_any_mut(&mut self) -> &mut dyn Any;
}
const MAX_CONCURRENT_COMPLETION_REQUESTS: usize = 4;
pub struct CompletionProvider {
provider: Arc<RwLock<dyn LanguageModelCompletionProvider>>,
client: Option<Arc<Client>>,
request_limiter: Arc<Semaphore>,
}
impl CompletionProvider {
pub fn new(
provider: Arc<RwLock<dyn LanguageModelCompletionProvider>>,
client: Option<Arc<Client>>,
) -> Self {
Self {
provider,
client,
request_limiter: Arc::new(Semaphore::new(MAX_CONCURRENT_COMPLETION_REQUESTS)),
}
}
pub fn available_models(&self, cx: &AppContext) -> Vec<LanguageModel> {
self.provider.read().available_models(cx)
}
pub fn settings_version(&self) -> usize {
self.provider.read().settings_version()
}
pub fn is_authenticated(&self) -> bool {
self.provider.read().is_authenticated()
}
pub fn authenticate(&self, cx: &AppContext) -> Task<Result<()>> {
self.provider.read().authenticate(cx)
}
pub fn authentication_prompt(&self, cx: &mut WindowContext) -> AnyView {
self.provider.read().authentication_prompt(cx)
}
pub fn reset_credentials(&self, cx: &AppContext) -> Task<Result<()>> {
self.provider.read().reset_credentials(cx)
}
pub fn model(&self) -> LanguageModel {
self.provider.read().model()
}
pub fn count_tokens(
&self,
request: LanguageModelRequest,
cx: &AppContext,
) -> BoxFuture<'static, Result<usize>> {
self.provider.read().count_tokens(request, cx)
}
pub fn complete(
&self,
request: LanguageModelRequest,
cx: &AppContext,
) -> Task<CompletionResponse> {
let rate_limiter = self.request_limiter.clone();
let provider = self.provider.clone();
cx.background_executor().spawn(async move {
let lock = rate_limiter.acquire_arc().await;
let response = provider.read().complete(request);
CompletionResponse {
inner: response,
_lock: lock,
}
})
}
}
impl gpui::Global for CompletionProvider {}
impl CompletionProvider {
pub fn global(cx: &AppContext) -> &Self {
cx.global::<Self>()
}
pub fn update_current_as<R, T: LanguageModelCompletionProvider + 'static>(
&mut self,
update: impl FnOnce(&mut T) -> R,
) -> Option<R> {
let mut provider = self.provider.write();
if let Some(provider) = provider.as_any_mut().downcast_mut::<T>() {
Some(update(provider))
} else {
None
}
}
pub fn update_settings(&mut self, version: usize, cx: &mut AppContext) {
let updated = match &AssistantSettings::get_global(cx).provider {
AssistantProvider::ZedDotDev { model } => self
.update_current_as::<_, CloudCompletionProvider>(|provider| {
provider.update(model.clone(), version);
}),
AssistantProvider::OpenAi {
model,
api_url,
low_speed_timeout_in_seconds,
available_models,
} => self.update_current_as::<_, OpenAiCompletionProvider>(|provider| {
provider.update(
choose_openai_model(&model, &available_models),
api_url.clone(),
low_speed_timeout_in_seconds.map(Duration::from_secs),
version,
);
}),
AssistantProvider::Anthropic {
model,
api_url,
low_speed_timeout_in_seconds,
} => self.update_current_as::<_, AnthropicCompletionProvider>(|provider| {
provider.update(
model.clone(),
api_url.clone(),
low_speed_timeout_in_seconds.map(Duration::from_secs),
version,
);
}),
AssistantProvider::Ollama {
model,
api_url,
low_speed_timeout_in_seconds,
} => self.update_current_as::<_, OllamaCompletionProvider>(|provider| {
provider.update(
model.clone(),
api_url.clone(),
low_speed_timeout_in_seconds.map(Duration::from_secs),
version,
cx,
);
}),
};
// Previously configured provider was changed to another one
if updated.is_none() {
if let Some(client) = self.client.clone() {
self.provider = create_provider_from_settings(client, version, cx);
} else {
log::warn!("completion provider cannot be created because client is not set");
}
}
}
}
fn create_provider_from_settings(
client: Arc<Client>,
settings_version: usize,
cx: &mut AppContext,
) -> Arc<RwLock<dyn LanguageModelCompletionProvider>> {
match &AssistantSettings::get_global(cx).provider {
AssistantProvider::ZedDotDev { model } => Arc::new(RwLock::new(
CloudCompletionProvider::new(model.clone(), client.clone(), settings_version, cx),
)),
AssistantProvider::OpenAi {
model,
api_url,
low_speed_timeout_in_seconds,
available_models,
} => Arc::new(RwLock::new(OpenAiCompletionProvider::new(
choose_openai_model(&model, &available_models),
api_url.clone(),
client.http_client(),
low_speed_timeout_in_seconds.map(Duration::from_secs),
settings_version,
))),
AssistantProvider::Anthropic {
model,
api_url,
low_speed_timeout_in_seconds,
} => Arc::new(RwLock::new(AnthropicCompletionProvider::new(
model.clone(),
api_url.clone(),
client.http_client(),
low_speed_timeout_in_seconds.map(Duration::from_secs),
settings_version,
))),
AssistantProvider::Ollama {
model,
api_url,
low_speed_timeout_in_seconds,
} => Arc::new(RwLock::new(OllamaCompletionProvider::new(
model.clone(),
api_url.clone(),
client.http_client(),
low_speed_timeout_in_seconds.map(Duration::from_secs),
settings_version,
cx,
))),
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use gpui::AppContext;
use parking_lot::RwLock;
use settings::SettingsStore;
use smol::stream::StreamExt;
use crate::{
completion_provider::MAX_CONCURRENT_COMPLETION_REQUESTS, CompletionProvider,
FakeCompletionProvider, LanguageModelRequest,
};
#[gpui::test]
fn test_rate_limiting(cx: &mut AppContext) {
SettingsStore::test(cx);
let fake_provider = FakeCompletionProvider::setup_test(cx);
let provider = CompletionProvider::new(Arc::new(RwLock::new(fake_provider.clone())), None);
// Enqueue some requests
for i in 0..MAX_CONCURRENT_COMPLETION_REQUESTS * 2 {
let response = provider.complete(
LanguageModelRequest {
temperature: i as f32 / 10.0,
..Default::default()
},
cx,
);
cx.background_executor()
.spawn(async move {
let response = response.await;
let mut stream = response.inner.await.unwrap();
while let Some(message) = stream.next().await {
message.unwrap();
}
})
.detach();
}
cx.background_executor().run_until_parked();
assert_eq!(
fake_provider.completion_count(),
MAX_CONCURRENT_COMPLETION_REQUESTS
);
// Get the first completion request that is in flight and mark it as completed.
let completion = fake_provider
.running_completions()
.into_iter()
.next()
.unwrap();
fake_provider.finish_completion(&completion);
// Ensure that the number of in-flight completion requests is reduced.
assert_eq!(
fake_provider.completion_count(),
MAX_CONCURRENT_COMPLETION_REQUESTS - 1
);
cx.background_executor().run_until_parked();
// Ensure that another completion request was allowed to acquire the lock.
assert_eq!(
fake_provider.completion_count(),
MAX_CONCURRENT_COMPLETION_REQUESTS
);
// Mark all completion requests as finished that are in flight.
for request in fake_provider.running_completions() {
fake_provider.finish_completion(&request);
}
assert_eq!(fake_provider.completion_count(), 0);
// Wait until the background tasks acquire the lock again.
cx.background_executor().run_until_parked();
assert_eq!(
fake_provider.completion_count(),
MAX_CONCURRENT_COMPLETION_REQUESTS - 1
);
// Finish all remaining completion requests.
for request in fake_provider.running_completions() {
fake_provider.finish_completion(&request);
}
cx.background_executor().run_until_parked();
assert_eq!(fake_provider.completion_count(), 0);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,97 +1,117 @@
use crate::{assistant_settings::OpenAiModel, MessageId, MessageMetadata};
use anyhow::{anyhow, Result};
use assistant_slash_command::SlashCommandOutputSection;
use collections::HashMap;
use crate::{
Context, ContextEvent, ContextId, ContextOperation, ContextVersion, SavedContext,
SavedContextMetadata,
};
use anyhow::{anyhow, Context as _, Result};
use client::{proto, telemetry::Telemetry, Client, TypedEnvelope};
use clock::ReplicaId;
use fs::Fs;
use futures::StreamExt;
use fuzzy::StringMatchCandidate;
use gpui::{AppContext, Model, ModelContext, Task};
use gpui::{AppContext, AsyncAppContext, Context as _, Model, ModelContext, Task, WeakModel};
use language::LanguageRegistry;
use paths::contexts_dir;
use project::Project;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::{cmp::Reverse, ffi::OsStr, path::PathBuf, sync::Arc, time::Duration};
use ui::Context;
use std::{
cmp::Reverse,
ffi::OsStr,
mem,
path::{Path, PathBuf},
sync::Arc,
time::Duration,
};
use util::{ResultExt, TryFutureExt};
#[derive(Serialize, Deserialize)]
pub struct SavedMessage {
pub id: MessageId,
pub start: usize,
}
#[derive(Serialize, Deserialize)]
pub struct SavedContext {
pub id: Option<String>,
pub zed: String,
pub version: String,
pub text: String,
pub messages: Vec<SavedMessage>,
pub message_metadata: HashMap<MessageId, MessageMetadata>,
pub summary: String,
pub slash_command_output_sections: Vec<SlashCommandOutputSection<usize>>,
}
impl SavedContext {
pub const VERSION: &'static str = "0.3.0";
}
#[derive(Serialize, Deserialize)]
pub struct SavedContextV0_2_0 {
pub id: Option<String>,
pub zed: String,
pub version: String,
pub text: String,
pub messages: Vec<SavedMessage>,
pub message_metadata: HashMap<MessageId, MessageMetadata>,
pub summary: String,
}
#[derive(Serialize, Deserialize)]
struct SavedContextV0_1_0 {
id: Option<String>,
zed: String,
version: String,
text: String,
messages: Vec<SavedMessage>,
message_metadata: HashMap<MessageId, MessageMetadata>,
summary: String,
api_url: Option<String>,
model: OpenAiModel,
pub fn init(client: &Arc<Client>) {
client.add_model_message_handler(ContextStore::handle_advertise_contexts);
client.add_model_request_handler(ContextStore::handle_open_context);
client.add_model_message_handler(ContextStore::handle_update_context);
client.add_model_request_handler(ContextStore::handle_synchronize_contexts);
}
#[derive(Clone)]
pub struct SavedContextMetadata {
pub title: String,
pub path: PathBuf,
pub mtime: chrono::DateTime<chrono::Local>,
pub struct RemoteContextMetadata {
pub id: ContextId,
pub summary: Option<String>,
}
pub struct ContextStore {
contexts: Vec<ContextHandle>,
contexts_metadata: Vec<SavedContextMetadata>,
host_contexts: Vec<RemoteContextMetadata>,
fs: Arc<dyn Fs>,
languages: Arc<LanguageRegistry>,
telemetry: Arc<Telemetry>,
_watch_updates: Task<Option<()>>,
client: Arc<Client>,
project: Model<Project>,
project_is_shared: bool,
client_subscription: Option<client::Subscription>,
_project_subscriptions: Vec<gpui::Subscription>,
}
enum ContextHandle {
Weak(WeakModel<Context>),
Strong(Model<Context>),
}
impl ContextHandle {
fn upgrade(&self) -> Option<Model<Context>> {
match self {
ContextHandle::Weak(weak) => weak.upgrade(),
ContextHandle::Strong(strong) => Some(strong.clone()),
}
}
fn downgrade(&self) -> WeakModel<Context> {
match self {
ContextHandle::Weak(weak) => weak.clone(),
ContextHandle::Strong(strong) => strong.downgrade(),
}
}
}
impl ContextStore {
pub fn new(fs: Arc<dyn Fs>, cx: &mut AppContext) -> Task<Result<Model<Self>>> {
pub fn new(project: Model<Project>, cx: &mut AppContext) -> Task<Result<Model<Self>>> {
let fs = project.read(cx).fs().clone();
let languages = project.read(cx).languages().clone();
let telemetry = project.read(cx).client().telemetry().clone();
cx.spawn(|mut cx| async move {
const CONTEXT_WATCH_DURATION: Duration = Duration::from_millis(100);
let (mut events, _) = fs.watch(contexts_dir(), CONTEXT_WATCH_DURATION).await;
let this = cx.new_model(|cx: &mut ModelContext<Self>| Self {
contexts_metadata: Vec::new(),
fs,
_watch_updates: cx.spawn(|this, mut cx| {
async move {
while events.next().await.is_some() {
this.update(&mut cx, |this, cx| this.reload(cx))?
.await
.log_err();
let this = cx.new_model(|cx: &mut ModelContext<Self>| {
let mut this = Self {
contexts: Vec::new(),
contexts_metadata: Vec::new(),
host_contexts: Vec::new(),
fs,
languages,
telemetry,
_watch_updates: cx.spawn(|this, mut cx| {
async move {
while events.next().await.is_some() {
this.update(&mut cx, |this, cx| this.reload(cx))?
.await
.log_err();
}
anyhow::Ok(())
}
anyhow::Ok(())
}
.log_err()
}),
.log_err()
}),
client_subscription: None,
_project_subscriptions: vec![
cx.observe(&project, Self::handle_project_changed),
cx.subscribe(&project, Self::handle_project_event),
],
project_is_shared: false,
client: project.read(cx).client(),
project: project.clone(),
};
this.handle_project_changed(project, cx);
this.synchronize_contexts(cx);
this
})?;
this.update(&mut cx, |this, cx| this.reload(cx))?
.await
@@ -100,54 +120,433 @@ impl ContextStore {
})
}
pub fn load(&self, path: PathBuf, cx: &AppContext) -> Task<Result<SavedContext>> {
async fn handle_advertise_contexts(
this: Model<Self>,
envelope: TypedEnvelope<proto::AdvertiseContexts>,
mut cx: AsyncAppContext,
) -> Result<()> {
this.update(&mut cx, |this, cx| {
this.host_contexts = envelope
.payload
.contexts
.into_iter()
.map(|context| RemoteContextMetadata {
id: ContextId::from_proto(context.context_id),
summary: context.summary,
})
.collect();
cx.notify();
})
}
async fn handle_open_context(
this: Model<Self>,
envelope: TypedEnvelope<proto::OpenContext>,
mut cx: AsyncAppContext,
) -> Result<proto::OpenContextResponse> {
let context_id = ContextId::from_proto(envelope.payload.context_id);
let operations = this.update(&mut cx, |this, cx| {
if this.project.read(cx).is_remote() {
return Err(anyhow!("only the host contexts can be opened"));
}
let context = this
.loaded_context_for_id(&context_id, cx)
.context("context not found")?;
if context.read(cx).replica_id() != ReplicaId::default() {
return Err(anyhow!("context must be opened via the host"));
}
anyhow::Ok(
context
.read(cx)
.serialize_ops(&ContextVersion::default(), cx),
)
})??;
let operations = operations.await;
Ok(proto::OpenContextResponse {
context: Some(proto::Context { operations }),
})
}
async fn handle_update_context(
this: Model<Self>,
envelope: TypedEnvelope<proto::UpdateContext>,
mut cx: AsyncAppContext,
) -> Result<()> {
this.update(&mut cx, |this, cx| {
let context_id = ContextId::from_proto(envelope.payload.context_id);
if let Some(context) = this.loaded_context_for_id(&context_id, cx) {
let operation_proto = envelope.payload.operation.context("invalid operation")?;
let operation = ContextOperation::from_proto(operation_proto)?;
context.update(cx, |context, cx| context.apply_ops([operation], cx))?;
}
Ok(())
})?
}
async fn handle_synchronize_contexts(
this: Model<Self>,
envelope: TypedEnvelope<proto::SynchronizeContexts>,
mut cx: AsyncAppContext,
) -> Result<proto::SynchronizeContextsResponse> {
this.update(&mut cx, |this, cx| {
if this.project.read(cx).is_remote() {
return Err(anyhow!("only the host can synchronize contexts"));
}
let mut local_versions = Vec::new();
for remote_version_proto in envelope.payload.contexts {
let remote_version = ContextVersion::from_proto(&remote_version_proto);
let context_id = ContextId::from_proto(remote_version_proto.context_id);
if let Some(context) = this.loaded_context_for_id(&context_id, cx) {
let context = context.read(cx);
let operations = context.serialize_ops(&remote_version, cx);
local_versions.push(context.version(cx).to_proto(context_id.clone()));
let client = this.client.clone();
let project_id = envelope.payload.project_id;
cx.background_executor()
.spawn(async move {
let operations = operations.await;
for operation in operations {
client.send(proto::UpdateContext {
project_id,
context_id: context_id.to_proto(),
operation: Some(operation),
})?;
}
anyhow::Ok(())
})
.detach_and_log_err(cx);
}
}
this.advertise_contexts(cx);
anyhow::Ok(proto::SynchronizeContextsResponse {
contexts: local_versions,
})
})?
}
fn handle_project_changed(&mut self, _: Model<Project>, cx: &mut ModelContext<Self>) {
let is_shared = self.project.read(cx).is_shared();
let was_shared = mem::replace(&mut self.project_is_shared, is_shared);
if is_shared == was_shared {
return;
}
if is_shared {
self.contexts.retain_mut(|context| {
if let Some(strong_context) = context.upgrade() {
*context = ContextHandle::Strong(strong_context);
true
} else {
false
}
});
let remote_id = self.project.read(cx).remote_id().unwrap();
self.client_subscription = self
.client
.subscribe_to_entity(remote_id)
.log_err()
.map(|subscription| subscription.set_model(&cx.handle(), &mut cx.to_async()));
self.advertise_contexts(cx);
} else {
self.client_subscription = None;
}
}
fn handle_project_event(
&mut self,
_: Model<Project>,
event: &project::Event,
cx: &mut ModelContext<Self>,
) {
match event {
project::Event::Reshared => {
self.advertise_contexts(cx);
}
project::Event::HostReshared | project::Event::Rejoined => {
self.synchronize_contexts(cx);
}
project::Event::DisconnectedFromHost => {
self.contexts.retain_mut(|context| {
if let Some(strong_context) = context.upgrade() {
*context = ContextHandle::Weak(context.downgrade());
strong_context.update(cx, |context, cx| {
if context.replica_id() != ReplicaId::default() {
context.set_capability(language::Capability::ReadOnly, cx);
}
});
true
} else {
false
}
});
self.host_contexts.clear();
cx.notify();
}
_ => {}
}
}
pub fn create(&mut self, cx: &mut ModelContext<Self>) -> Model<Context> {
let context = cx.new_model(|cx| {
Context::local(self.languages.clone(), Some(self.telemetry.clone()), cx)
});
self.register_context(&context, cx);
context
}
pub fn open_local_context(
&mut self,
path: PathBuf,
cx: &ModelContext<Self>,
) -> Task<Result<Model<Context>>> {
if let Some(existing_context) = self.loaded_context_for_path(&path, cx) {
return Task::ready(Ok(existing_context));
}
let fs = self.fs.clone();
cx.background_executor().spawn(async move {
let saved_context = fs.load(&path).await?;
let saved_context_json = serde_json::from_str::<serde_json::Value>(&saved_context)?;
match saved_context_json
.get("version")
.ok_or_else(|| anyhow!("version not found"))?
{
serde_json::Value::String(version) => match version.as_str() {
SavedContext::VERSION => {
Ok(serde_json::from_value::<SavedContext>(saved_context_json)?)
}
"0.2.0" => {
let saved_context =
serde_json::from_value::<SavedContextV0_2_0>(saved_context_json)?;
Ok(SavedContext {
id: saved_context.id,
zed: saved_context.zed,
version: saved_context.version,
text: saved_context.text,
messages: saved_context.messages,
message_metadata: saved_context.message_metadata,
summary: saved_context.summary,
slash_command_output_sections: Vec::new(),
})
}
"0.1.0" => {
let saved_context =
serde_json::from_value::<SavedContextV0_1_0>(saved_context_json)?;
Ok(SavedContext {
id: saved_context.id,
zed: saved_context.zed,
version: saved_context.version,
text: saved_context.text,
messages: saved_context.messages,
message_metadata: saved_context.message_metadata,
summary: saved_context.summary,
slash_command_output_sections: Vec::new(),
})
}
_ => Err(anyhow!("unrecognized saved context version: {}", version)),
},
_ => Err(anyhow!("version not found on saved context")),
let languages = self.languages.clone();
let telemetry = self.telemetry.clone();
let load = cx.background_executor().spawn({
let path = path.clone();
async move {
let saved_context = fs.load(&path).await?;
SavedContext::from_json(&saved_context)
}
});
cx.spawn(|this, mut cx| async move {
let saved_context = load.await?;
let context = cx.new_model(|cx| {
Context::deserialize(saved_context, path.clone(), languages, Some(telemetry), cx)
})?;
this.update(&mut cx, |this, cx| {
if let Some(existing_context) = this.loaded_context_for_path(&path, cx) {
existing_context
} else {
this.register_context(&context, cx);
context
}
})
})
}
fn loaded_context_for_path(&self, path: &Path, cx: &AppContext) -> Option<Model<Context>> {
self.contexts.iter().find_map(|context| {
let context = context.upgrade()?;
if context.read(cx).path() == Some(path) {
Some(context)
} else {
None
}
})
}
fn loaded_context_for_id(&self, id: &ContextId, cx: &AppContext) -> Option<Model<Context>> {
self.contexts.iter().find_map(|context| {
let context = context.upgrade()?;
if context.read(cx).id() == id {
Some(context)
} else {
None
}
})
}
pub fn open_remote_context(
&mut self,
context_id: ContextId,
cx: &mut ModelContext<Self>,
) -> Task<Result<Model<Context>>> {
let project = self.project.read(cx);
let Some(project_id) = project.remote_id() else {
return Task::ready(Err(anyhow!("project was not remote")));
};
if project.is_local() {
return Task::ready(Err(anyhow!("cannot open remote contexts as the host")));
}
if let Some(context) = self.loaded_context_for_id(&context_id, cx) {
return Task::ready(Ok(context));
}
let replica_id = project.replica_id();
let capability = project.capability();
let language_registry = self.languages.clone();
let telemetry = self.telemetry.clone();
let request = self.client.request(proto::OpenContext {
project_id,
context_id: context_id.to_proto(),
});
cx.spawn(|this, mut cx| async move {
let response = request.await?;
let context_proto = response.context.context("invalid context")?;
let context = cx.new_model(|cx| {
Context::new(
context_id.clone(),
replica_id,
capability,
language_registry,
Some(telemetry),
cx,
)
})?;
let operations = cx
.background_executor()
.spawn(async move {
context_proto
.operations
.into_iter()
.map(|op| ContextOperation::from_proto(op))
.collect::<Result<Vec<_>>>()
})
.await?;
context.update(&mut cx, |context, cx| context.apply_ops(operations, cx))??;
this.update(&mut cx, |this, cx| {
if let Some(existing_context) = this.loaded_context_for_id(&context_id, cx) {
existing_context
} else {
this.register_context(&context, cx);
this.synchronize_contexts(cx);
context
}
})
})
}
fn register_context(&mut self, context: &Model<Context>, cx: &mut ModelContext<Self>) {
let handle = if self.project_is_shared {
ContextHandle::Strong(context.clone())
} else {
ContextHandle::Weak(context.downgrade())
};
self.contexts.push(handle);
self.advertise_contexts(cx);
cx.subscribe(context, Self::handle_context_event).detach();
}
fn handle_context_event(
&mut self,
context: Model<Context>,
event: &ContextEvent,
cx: &mut ModelContext<Self>,
) {
let Some(project_id) = self.project.read(cx).remote_id() else {
return;
};
match event {
ContextEvent::SummaryChanged => {
self.advertise_contexts(cx);
}
ContextEvent::Operation(operation) => {
let context_id = context.read(cx).id().to_proto();
let operation = operation.to_proto();
self.client
.send(proto::UpdateContext {
project_id,
context_id,
operation: Some(operation),
})
.log_err();
}
_ => {}
}
}
fn advertise_contexts(&self, cx: &AppContext) {
let Some(project_id) = self.project.read(cx).remote_id() else {
return;
};
// For now, only the host can advertise their open contexts.
if self.project.read(cx).is_remote() {
return;
}
let contexts = self
.contexts
.iter()
.rev()
.filter_map(|context| {
let context = context.upgrade()?.read(cx);
if context.replica_id() == ReplicaId::default() {
Some(proto::ContextMetadata {
context_id: context.id().to_proto(),
summary: context.summary().map(|summary| summary.text.clone()),
})
} else {
None
}
})
.collect();
self.client
.send(proto::AdvertiseContexts {
project_id,
contexts,
})
.ok();
}
fn synchronize_contexts(&mut self, cx: &mut ModelContext<Self>) {
let Some(project_id) = self.project.read(cx).remote_id() else {
return;
};
let contexts = self
.contexts
.iter()
.filter_map(|context| {
let context = context.upgrade()?.read(cx);
if context.replica_id() != ReplicaId::default() {
Some(context.version(cx).to_proto(context.id().clone()))
} else {
None
}
})
.collect();
let client = self.client.clone();
let request = self.client.request(proto::SynchronizeContexts {
project_id,
contexts,
});
cx.spawn(|this, cx| async move {
let response = request.await?;
let mut context_ids = Vec::new();
let mut operations = Vec::new();
this.read_with(&cx, |this, cx| {
for context_version_proto in response.contexts {
let context_version = ContextVersion::from_proto(&context_version_proto);
let context_id = ContextId::from_proto(context_version_proto.context_id);
if let Some(context) = this.loaded_context_for_id(&context_id, cx) {
context_ids.push(context_id);
operations.push(context.read(cx).serialize_ops(&context_version, cx));
}
}
})?;
let operations = futures::future::join_all(operations).await;
for (context_id, operations) in context_ids.into_iter().zip(operations) {
for operation in operations {
client.send(proto::UpdateContext {
project_id,
context_id: context_id.to_proto(),
operation: Some(operation),
})?;
}
}
anyhow::Ok(())
})
.detach_and_log_err(cx);
}
pub fn search(&self, query: String, cx: &AppContext) -> Task<Vec<SavedContextMetadata>> {
let metadata = self.contexts_metadata.clone();
let executor = cx.background_executor().clone();
@@ -178,6 +577,10 @@ impl ContextStore {
})
}
pub fn host_contexts(&self) -> &[RemoteContextMetadata] {
&self.host_contexts
}
fn reload(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
let fs = self.fs.clone();
cx.spawn(|this, mut cx| async move {

View File

@@ -1,7 +1,6 @@
use crate::{
assistant_settings::AssistantSettings, humanize_token_count, prompts::generate_content_prompt,
AssistantPanel, AssistantPanelEvent, CompletionProvider, Hunk, LanguageModelRequest,
LanguageModelRequestMessage, Role, StreamingDiff,
AssistantPanel, AssistantPanelEvent, CompletionProvider, Hunk, StreamingDiff,
};
use anyhow::{anyhow, Context as _, Result};
use client::telemetry::Telemetry;
@@ -9,27 +8,36 @@ use collections::{hash_map, HashMap, HashSet, VecDeque};
use editor::{
actions::{MoveDown, MoveUp, SelectAll},
display_map::{
BlockContext, BlockDisposition, BlockId, BlockProperties, BlockStyle, RenderBlock,
BlockContext, BlockDisposition, BlockProperties, BlockStyle, CustomBlockId, RenderBlock,
ToDisplayPoint,
},
Anchor, AnchorRangeExt, Editor, EditorElement, EditorEvent, EditorMode, EditorStyle,
ExcerptRange, GutterDimensions, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint,
};
use fs::Fs;
use futures::{channel::mpsc, SinkExt, Stream, StreamExt};
use futures::{
channel::mpsc,
future::LocalBoxFuture,
stream::{self, BoxStream},
SinkExt, Stream, StreamExt,
};
use gpui::{
point, AppContext, EventEmitter, FocusHandle, FocusableView, FontStyle, Global, HighlightStyle,
Model, ModelContext, Subscription, Task, TextStyle, UpdateGlobal, View, ViewContext, WeakView,
WhiteSpace, WindowContext,
point, AppContext, EventEmitter, FocusHandle, FocusableView, Global, HighlightStyle, Model,
ModelContext, Subscription, Task, TextStyle, UpdateGlobal, View, ViewContext, WeakView,
WindowContext,
};
use language::{Buffer, Point, Selection, TransactionId};
use language_model::{LanguageModelRequest, LanguageModelRequestMessage, Role};
use multi_buffer::MultiBufferRow;
use parking_lot::Mutex;
use rope::Rope;
use settings::{update_settings_file, Settings};
use similar::TextDiff;
use smol::future::FutureExt;
use std::{
cmp, mem,
cmp,
future::Future,
mem,
ops::{Range, RangeInclusive},
pin::Pin,
sync::Arc,
@@ -37,7 +45,7 @@ use std::{
time::{Duration, Instant},
};
use theme::ThemeSettings;
use ui::{prelude::*, ContextMenu, PopoverMenu, Tooltip};
use ui::{prelude::*, ContextMenu, IconButtonShape, PopoverMenu, Tooltip};
use util::RangeExt;
use workspace::{notifications::NotificationId, Toast, Workspace};
@@ -79,6 +87,7 @@ impl InlineAssistant {
editor: &View<Editor>,
workspace: Option<WeakView<Workspace>>,
assistant_panel: Option<&View<AssistantPanel>>,
initial_prompt: Option<String>,
cx: &mut WindowContext,
) {
let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
@@ -130,11 +139,11 @@ impl InlineAssistant {
}
let assist_group_id = self.next_assist_group_id.post_inc();
let prompt_buffer = cx.new_model(|cx| Buffer::local("", cx));
let prompt_buffer =
cx.new_model(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx));
let prompt_buffer = cx.new_model(|cx| MultiBuffer::singleton(prompt_buffer, cx));
let mut assists = Vec::new();
let mut assist_blocks = Vec::new();
let mut assist_to_focus = None;
for range in codegen_ranges {
let assist_id = self.next_assist_id.post_inc();
@@ -142,6 +151,7 @@ impl InlineAssistant {
Codegen::new(
editor.read(cx).buffer().clone(),
range.clone(),
None,
self.telemetry.clone(),
cx,
)
@@ -174,42 +184,18 @@ impl InlineAssistant {
}
}
assist_blocks.push(BlockProperties {
style: BlockStyle::Sticky,
position: range.start,
height: prompt_editor.read(cx).height_in_lines,
render: build_assist_editor_renderer(&prompt_editor),
disposition: BlockDisposition::Above,
});
assist_blocks.push(BlockProperties {
style: BlockStyle::Sticky,
position: range.end,
height: 1,
render: Box::new(|cx| {
v_flex()
.h_full()
.w_full()
.border_t_1()
.border_color(cx.theme().status().info_border)
.into_any_element()
}),
disposition: BlockDisposition::Below,
});
assists.push((assist_id, prompt_editor));
}
let [prompt_block_id, end_block_id] =
self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
let assist_block_ids = editor.update(cx, |editor, cx| {
editor.insert_blocks(assist_blocks, None, cx)
});
assists.push((assist_id, prompt_editor, prompt_block_id, end_block_id));
}
let editor_assists = self
.assists_by_editor
.entry(editor.downgrade())
.or_insert_with(|| EditorInlineAssists::new(&editor, cx));
let mut assist_group = InlineAssistGroup::new();
for ((assist_id, prompt_editor), block_ids) in
assists.into_iter().zip(assist_block_ids.chunks_exact(2))
{
for (assist_id, prompt_editor, prompt_block_id, end_block_id) in assists {
self.assists.insert(
assist_id,
InlineAssist::new(
@@ -218,8 +204,8 @@ impl InlineAssistant {
assistant_panel.is_some(),
editor,
&prompt_editor,
block_ids[0],
block_ids[1],
prompt_block_id,
end_block_id,
prompt_editor.read(cx).codegen.clone(),
workspace.clone(),
cx,
@@ -235,6 +221,128 @@ impl InlineAssistant {
}
}
#[allow(clippy::too_many_arguments)]
pub fn suggest_assist(
&mut self,
editor: &View<Editor>,
mut range: Range<Anchor>,
initial_prompt: String,
initial_insertion: Option<String>,
workspace: Option<WeakView<Workspace>>,
assistant_panel: Option<&View<AssistantPanel>>,
cx: &mut WindowContext,
) -> InlineAssistId {
let assist_group_id = self.next_assist_group_id.post_inc();
let prompt_buffer = cx.new_model(|cx| Buffer::local(&initial_prompt, cx));
let prompt_buffer = cx.new_model(|cx| MultiBuffer::singleton(prompt_buffer, cx));
let assist_id = self.next_assist_id.post_inc();
let buffer = editor.read(cx).buffer().clone();
let prepend_transaction_id = initial_insertion.and_then(|initial_insertion| {
buffer.update(cx, |buffer, cx| {
buffer.start_transaction(cx);
buffer.edit([(range.start..range.start, initial_insertion)], None, cx);
buffer.end_transaction(cx)
})
});
range.start = range.start.bias_left(&buffer.read(cx).read(cx));
range.end = range.end.bias_right(&buffer.read(cx).read(cx));
let codegen = cx.new_model(|cx| {
Codegen::new(
editor.read(cx).buffer().clone(),
range.clone(),
prepend_transaction_id,
self.telemetry.clone(),
cx,
)
});
let gutter_dimensions = Arc::new(Mutex::new(GutterDimensions::default()));
let prompt_editor = cx.new_view(|cx| {
PromptEditor::new(
assist_id,
gutter_dimensions.clone(),
self.prompt_history.clone(),
prompt_buffer.clone(),
codegen.clone(),
editor,
assistant_panel,
workspace.clone(),
self.fs.clone(),
cx,
)
});
let [prompt_block_id, end_block_id] =
self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
let editor_assists = self
.assists_by_editor
.entry(editor.downgrade())
.or_insert_with(|| EditorInlineAssists::new(&editor, cx));
let mut assist_group = InlineAssistGroup::new();
self.assists.insert(
assist_id,
InlineAssist::new(
assist_id,
assist_group_id,
assistant_panel.is_some(),
editor,
&prompt_editor,
prompt_block_id,
end_block_id,
prompt_editor.read(cx).codegen.clone(),
workspace.clone(),
cx,
),
);
assist_group.assist_ids.push(assist_id);
editor_assists.assist_ids.push(assist_id);
self.assist_groups.insert(assist_group_id, assist_group);
assist_id
}
fn insert_assist_blocks(
&self,
editor: &View<Editor>,
range: &Range<Anchor>,
prompt_editor: &View<PromptEditor>,
cx: &mut WindowContext,
) -> [CustomBlockId; 2] {
let assist_blocks = vec![
BlockProperties {
style: BlockStyle::Sticky,
position: range.start,
height: prompt_editor.read(cx).height_in_lines,
render: build_assist_editor_renderer(prompt_editor),
disposition: BlockDisposition::Above,
},
BlockProperties {
style: BlockStyle::Sticky,
position: range.end,
height: 1,
render: Box::new(|cx| {
v_flex()
.h_full()
.w_full()
.border_t_1()
.border_color(cx.theme().status().info_border)
.into_any_element()
}),
disposition: BlockDisposition::Below,
},
];
editor.update(cx, |editor, cx| {
let block_ids = editor.insert_blocks(assist_blocks, None, cx);
[block_ids[0], block_ids[1]]
})
}
fn handle_prompt_editor_focus_in(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
let assist = &self.assists[&assist_id];
let Some(decorations) = assist.decorations.as_ref() else {
@@ -379,6 +487,14 @@ impl InlineAssistant {
cx.propagate();
}
fn handle_editor_release(&mut self, editor: WeakView<Editor>, cx: &mut WindowContext) {
if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor) {
for assist_id in editor_assists.assist_ids.clone() {
self.finish_assist(assist_id, true, cx);
}
}
}
fn handle_editor_change(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
return;
@@ -698,7 +814,7 @@ impl InlineAssistant {
assist_group.assist_ids.clone()
}
fn start_assist(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
pub fn start_assist(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
assist
} else {
@@ -727,16 +843,26 @@ impl InlineAssistant {
self.prompt_history.pop_front();
}
assist.codegen.update(cx, |codegen, cx| codegen.undo(cx));
let codegen = assist.codegen.clone();
let request = self.request_for_inline_assist(assist_id, cx);
cx.spawn(|mut cx| async move {
let request = request.await?;
codegen.update(&mut cx, |codegen, cx| codegen.start(request, cx))?;
anyhow::Ok(())
})
.detach_and_log_err(cx);
let telemetry_id = CompletionProvider::global(cx).model().telemetry_id();
let chunks: LocalBoxFuture<Result<BoxStream<Result<String>>>> =
if user_prompt.trim().to_lowercase() == "delete" {
async { Ok(stream::empty().boxed()) }.boxed_local()
} else {
let request = self.request_for_inline_assist(assist_id, cx);
let mut cx = cx.to_async();
async move {
let request = request.await?;
let chunks = cx
.update(|cx| CompletionProvider::global(cx).stream_completion(request, cx))?
.await?;
Ok(chunks.boxed())
}
.boxed_local()
};
codegen.update(cx, |codegen, cx| {
codegen.start(telemetry_id, chunks, cx);
});
}
fn request_for_inline_assist(
@@ -855,7 +981,7 @@ impl InlineAssistant {
})
}
fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
pub fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
assist
} else {
@@ -1074,6 +1200,14 @@ impl EditorInlineAssists {
}
}),
_subscriptions: vec![
cx.observe_release(editor, {
let editor = editor.downgrade();
|_, cx| {
InlineAssistant::update_global(cx, |this, cx| {
this.handle_editor_release(editor, cx);
})
}
}),
cx.observe(editor, move |editor, cx| {
InlineAssistant::update_global(cx, |this, cx| {
this.handle_editor_change(editor, cx)
@@ -1138,7 +1272,7 @@ fn build_assist_editor_renderer(editor: &View<PromptEditor>) -> RenderBlock {
}
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
struct InlineAssistId(usize);
pub struct InlineAssistId(usize);
impl InlineAssistId {
fn post_inc(&mut self) -> InlineAssistId {
@@ -1298,8 +1432,7 @@ impl Render for PromptEditor {
PopoverMenu::new("model-switcher")
.menu(move |cx| {
ContextMenu::build(cx, |mut menu, cx| {
for model in CompletionProvider::global(cx).available_models(cx)
{
for model in CompletionProvider::global(cx).available_models() {
menu = menu.custom_entry(
{
let model = model.clone();
@@ -1328,7 +1461,7 @@ impl Render for PromptEditor {
})
.trigger(
IconButton::new("context", IconName::Settings)
.size(ButtonSize::None)
.shape(IconButtonShape::Square)
.icon_size(IconSize::Small)
.icon_color(Color::Muted)
.tooltip(move |cx| {
@@ -1340,7 +1473,7 @@ impl Render for PromptEditor {
.display_name()
),
None,
"Click to Change Model",
"Change Model",
cx,
)
}),
@@ -1731,12 +1864,8 @@ impl PromptEditor {
font_features: settings.ui_font.features.clone(),
font_size: rems(0.875).into(),
font_weight: settings.ui_font.weight,
font_style: FontStyle::Normal,
line_height: relative(1.3),
background_color: None,
underline: None,
strikethrough: None,
white_space: WhiteSpace::Normal,
..Default::default()
};
EditorElement::new(
&self.editor,
@@ -1768,8 +1897,8 @@ impl InlineAssist {
include_context: bool,
editor: &View<Editor>,
prompt_editor: &View<PromptEditor>,
prompt_block_id: BlockId,
end_block_id: BlockId,
prompt_block_id: CustomBlockId,
end_block_id: CustomBlockId,
codegen: Model<Codegen>,
workspace: Option<WeakView<Workspace>>,
cx: &mut WindowContext,
@@ -1863,10 +1992,10 @@ impl InlineAssist {
}
struct InlineAssistDecorations {
prompt_block_id: BlockId,
prompt_block_id: CustomBlockId,
prompt_editor: View<PromptEditor>,
removed_line_block_ids: HashSet<BlockId>,
end_block_id: BlockId,
removed_line_block_ids: HashSet<CustomBlockId>,
end_block_id: CustomBlockId,
}
#[derive(Debug)]
@@ -1882,7 +2011,8 @@ pub struct Codegen {
range: Range<Anchor>,
edit_position: Anchor,
last_equal_ranges: Vec<Range<Anchor>>,
transaction_id: Option<TransactionId>,
prepend_transaction_id: Option<TransactionId>,
generation_transaction_id: Option<TransactionId>,
status: CodegenStatus,
generation: Task<()>,
diff: Diff,
@@ -1911,6 +2041,7 @@ impl Codegen {
pub fn new(
buffer: Model<MultiBuffer>,
range: Range<Anchor>,
prepend_transaction_id: Option<TransactionId>,
telemetry: Option<Arc<Telemetry>>,
cx: &mut ModelContext<Self>,
) -> Self {
@@ -1943,7 +2074,8 @@ impl Codegen {
range,
snapshot,
last_equal_ranges: Default::default(),
transaction_id: Default::default(),
prepend_transaction_id,
generation_transaction_id: None,
status: CodegenStatus::Idle,
generation: Task::ready(()),
diff: Diff::default(),
@@ -1959,8 +2091,13 @@ impl Codegen {
cx: &mut ModelContext<Self>,
) {
if let multi_buffer::Event::TransactionUndone { transaction_id } = event {
if self.transaction_id == Some(*transaction_id) {
self.transaction_id = None;
if self.generation_transaction_id == Some(*transaction_id) {
self.generation_transaction_id = None;
self.generation = Task::ready(());
cx.emit(CodegenEvent::Undone);
} else if self.prepend_transaction_id == Some(*transaction_id) {
self.prepend_transaction_id = None;
self.generation_transaction_id = None;
self.generation = Task::ready(());
cx.emit(CodegenEvent::Undone);
}
@@ -1971,7 +2108,12 @@ impl Codegen {
&self.last_equal_ranges
}
pub fn start(&mut self, prompt: LanguageModelRequest, cx: &mut ModelContext<Self>) {
pub fn start(
&mut self,
telemetry_id: String,
stream: impl 'static + Future<Output = Result<BoxStream<'static, Result<String>>>>,
cx: &mut ModelContext<Self>,
) {
let range = self.range.clone();
let snapshot = self.snapshot.clone();
let selected_text = snapshot
@@ -1985,15 +2127,17 @@ impl Codegen {
.next()
.unwrap_or_else(|| snapshot.indent_size_for_line(MultiBufferRow(selection_start.row)));
let model_telemetry_id = prompt.model.telemetry_id();
let response = CompletionProvider::global(cx).complete(prompt, cx);
let telemetry = self.telemetry.clone();
self.edit_position = range.start;
self.diff = Diff::default();
self.status = CodegenStatus::Pending;
if let Some(transaction_id) = self.generation_transaction_id.take() {
self.buffer
.update(cx, |buffer, cx| buffer.undo_transaction(transaction_id, cx));
}
self.generation = cx.spawn(|this, mut cx| {
async move {
let response = response.await;
let chunks = stream.await;
let generate = async {
let mut edit_start = range.start.to_offset(&snapshot);
@@ -2003,7 +2147,7 @@ impl Codegen {
let mut response_latency = None;
let request_start = Instant::now();
let diff = async {
let chunks = StripInvalidSpans::new(response.inner.await?);
let chunks = StripInvalidSpans::new(chunks?);
futures::pin_mut!(chunks);
let mut diff = StreamingDiff::new(selected_text.to_string());
@@ -2086,7 +2230,7 @@ impl Codegen {
telemetry.report_assistant_event(
None,
telemetry_events::AssistantKind::Inline,
model_telemetry_id,
telemetry_id,
response_latency,
error_message,
);
@@ -2136,7 +2280,7 @@ impl Codegen {
});
if let Some(transaction) = transaction {
if let Some(first_transaction) = this.transaction_id {
if let Some(first_transaction) = this.generation_transaction_id {
// Group all assistant edits into the first transaction.
this.buffer.update(cx, |buffer, cx| {
buffer.merge_transactions(
@@ -2146,7 +2290,7 @@ impl Codegen {
)
});
} else {
this.transaction_id = Some(transaction);
this.generation_transaction_id = Some(transaction);
this.buffer.update(cx, |buffer, cx| {
buffer.finalize_last_transaction(cx)
});
@@ -2189,7 +2333,12 @@ impl Codegen {
}
pub fn undo(&mut self, cx: &mut ModelContext<Self>) {
if let Some(transaction_id) = self.transaction_id.take() {
if let Some(transaction_id) = self.prepend_transaction_id.take() {
self.buffer
.update(cx, |buffer, cx| buffer.undo_transaction(transaction_id, cx));
}
if let Some(transaction_id) = self.generation_transaction_id.take() {
self.buffer
.update(cx, |buffer, cx| buffer.undo_transaction(transaction_id, cx));
}
@@ -2451,11 +2600,8 @@ fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
#[cfg(test)]
mod tests {
use std::sync::Arc;
use crate::FakeCompletionProvider;
use super::*;
use completion::FakeCompletionProvider;
use futures::stream::{self};
use gpui::{Context, TestAppContext};
use indoc::indoc;
@@ -2466,6 +2612,7 @@ mod tests {
use rand::prelude::*;
use serde::Serialize;
use settings::SettingsStore;
use std::{future, sync::Arc};
#[derive(Serialize)]
pub struct DummyCompletionRequest {
@@ -2475,7 +2622,7 @@ mod tests {
#[gpui::test(iterations = 10)]
async fn test_transform_autoindent(cx: &mut TestAppContext, mut rng: StdRng) {
cx.set_global(cx.update(SettingsStore::test));
let provider = cx.update(|cx| FakeCompletionProvider::setup_test(cx));
cx.update(|cx| FakeCompletionProvider::setup_test(cx));
cx.update(language_settings::init);
let text = indoc! {"
@@ -2493,14 +2640,17 @@ mod tests {
let snapshot = buffer.snapshot(cx);
snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(4, 5))
});
let codegen = cx.new_model(|cx| Codegen::new(buffer.clone(), range, None, cx));
let codegen = cx.new_model(|cx| Codegen::new(buffer.clone(), range, None, None, cx));
let (chunks_tx, chunks_rx) = mpsc::unbounded();
codegen.update(cx, |codegen, cx| {
codegen.start(LanguageModelRequest::default(), cx)
codegen.start(
String::new(),
future::ready(Ok(chunks_rx.map(|chunk| Ok(chunk)).boxed())),
cx,
)
});
cx.background_executor.run_until_parked();
let mut new_text = concat!(
" let mut x = 0;\n",
" while x < 10 {\n",
@@ -2511,11 +2661,11 @@ mod tests {
let max_len = cmp::min(new_text.len(), 10);
let len = rng.gen_range(1..=max_len);
let (chunk, suffix) = new_text.split_at(len);
provider.send_completion(&LanguageModelRequest::default(), chunk.into());
chunks_tx.unbounded_send(chunk.to_string()).unwrap();
new_text = suffix;
cx.background_executor.run_until_parked();
}
provider.finish_completion(&LanguageModelRequest::default());
drop(chunks_tx);
cx.background_executor.run_until_parked();
assert_eq!(
@@ -2536,7 +2686,6 @@ mod tests {
cx: &mut TestAppContext,
mut rng: StdRng,
) {
let provider = cx.update(|cx| FakeCompletionProvider::setup_test(cx));
cx.set_global(cx.update(SettingsStore::test));
cx.update(language_settings::init);
@@ -2552,10 +2701,16 @@ mod tests {
let snapshot = buffer.snapshot(cx);
snapshot.anchor_before(Point::new(1, 6))..snapshot.anchor_after(Point::new(1, 6))
});
let codegen = cx.new_model(|cx| Codegen::new(buffer.clone(), range, None, cx));
let codegen = cx.new_model(|cx| Codegen::new(buffer.clone(), range, None, None, cx));
let request = LanguageModelRequest::default();
codegen.update(cx, |codegen, cx| codegen.start(request, cx));
let (chunks_tx, chunks_rx) = mpsc::unbounded();
codegen.update(cx, |codegen, cx| {
codegen.start(
String::new(),
future::ready(Ok(chunks_rx.map(|chunk| Ok(chunk)).boxed())),
cx,
)
});
cx.background_executor.run_until_parked();
@@ -2569,11 +2724,11 @@ mod tests {
let max_len = cmp::min(new_text.len(), 10);
let len = rng.gen_range(1..=max_len);
let (chunk, suffix) = new_text.split_at(len);
provider.send_completion(&LanguageModelRequest::default(), chunk.into());
chunks_tx.unbounded_send(chunk.to_string()).unwrap();
new_text = suffix;
cx.background_executor.run_until_parked();
}
provider.finish_completion(&LanguageModelRequest::default());
drop(chunks_tx);
cx.background_executor.run_until_parked();
assert_eq!(
@@ -2594,7 +2749,7 @@ mod tests {
cx: &mut TestAppContext,
mut rng: StdRng,
) {
let provider = cx.update(|cx| FakeCompletionProvider::setup_test(cx));
cx.update(|cx| FakeCompletionProvider::setup_test(cx));
cx.set_global(cx.update(SettingsStore::test));
cx.update(language_settings::init);
@@ -2610,10 +2765,16 @@ mod tests {
let snapshot = buffer.snapshot(cx);
snapshot.anchor_before(Point::new(1, 2))..snapshot.anchor_after(Point::new(1, 2))
});
let codegen = cx.new_model(|cx| Codegen::new(buffer.clone(), range, None, cx));
let codegen = cx.new_model(|cx| Codegen::new(buffer.clone(), range, None, None, cx));
let request = LanguageModelRequest::default();
codegen.update(cx, |codegen, cx| codegen.start(request, cx));
let (chunks_tx, chunks_rx) = mpsc::unbounded();
codegen.update(cx, |codegen, cx| {
codegen.start(
String::new(),
future::ready(Ok(chunks_rx.map(|chunk| Ok(chunk)).boxed())),
cx,
)
});
cx.background_executor.run_until_parked();
@@ -2627,11 +2788,11 @@ mod tests {
let max_len = cmp::min(new_text.len(), 10);
let len = rng.gen_range(1..=max_len);
let (chunk, suffix) = new_text.split_at(len);
provider.send_completion(&LanguageModelRequest::default(), chunk.into());
chunks_tx.unbounded_send(chunk.to_string()).unwrap();
new_text = suffix;
cx.background_executor.run_until_parked();
}
provider.finish_completion(&LanguageModelRequest::default());
drop(chunks_tx);
cx.background_executor.run_until_parked();
assert_eq!(

View File

@@ -23,7 +23,7 @@ impl RenderOnce for ModelSelector {
.with_handle(self.handle)
.menu(move |cx| {
ContextMenu::build(cx, |mut menu, cx| {
for model in CompletionProvider::global(cx).available_models(cx) {
for model in CompletionProvider::global(cx).available_models() {
menu = menu.custom_entry(
{
let model = model.clone();

View File

@@ -1,9 +1,9 @@
use crate::{
slash_command::SlashCommandCompletionProvider, AssistantPanel, CompletionProvider,
InlineAssist, InlineAssistant, LanguageModelRequest, LanguageModelRequestMessage, Role,
InlineAssist, InlineAssistant,
};
use anyhow::{anyhow, Result};
use assistant_slash_command::SlashCommandRegistry;
use assets::Assets;
use chrono::{DateTime, Utc};
use collections::{HashMap, HashSet};
use editor::{actions::Tab, CurrentLineHighlight, Editor, EditorElement, EditorEvent, EditorStyle};
@@ -13,12 +13,13 @@ use futures::{
};
use fuzzy::StringMatchCandidate;
use gpui::{
actions, point, size, transparent_black, AppContext, BackgroundExecutor, Bounds, EventEmitter,
Global, HighlightStyle, PromptLevel, ReadGlobal, Subscription, Task, TextStyle,
actions, point, size, transparent_black, AppContext, AssetSource, BackgroundExecutor, Bounds,
EventEmitter, Global, HighlightStyle, PromptLevel, ReadGlobal, Subscription, Task, TextStyle,
TitlebarOptions, UpdateGlobal, View, WindowBounds, WindowHandle, WindowOptions,
};
use heed::{types::SerdeBincode, Database, RoTxn};
use language::{language_settings::SoftWrap, Buffer, LanguageRegistry};
use language_model::{LanguageModelRequest, LanguageModelRequestMessage, Role};
use parking_lot::RwLock;
use picker::{Picker, PickerDelegate};
use rope::Rope;
@@ -269,7 +270,7 @@ impl PickerDelegate for PromptPickerDelegate {
.flex_none()
.py_1()
.px_2()
.mx_2()
.mx_1()
.child(editor.clone())
}
}
@@ -448,7 +449,6 @@ impl PromptLibrary {
self.set_active_prompt(Some(prompt_id), cx);
} else if let Some(prompt_metadata) = self.store.metadata(prompt_id) {
let language_registry = self.language_registry.clone();
let commands = SlashCommandRegistry::global(cx);
let prompt = self.store.load(prompt_id);
self.pending_load = cx.spawn(|this, mut cx| async move {
let prompt = prompt.await;
@@ -477,7 +477,7 @@ impl PromptLibrary {
editor.set_use_modal_editing(false);
editor.set_current_line_highlight(Some(CurrentLineHighlight::None));
editor.set_completion_provider(Box::new(
SlashCommandCompletionProvider::new(commands, None, None),
SlashCommandCompletionProvider::new(None, None),
));
if focus {
editor.focus(cx);
@@ -629,7 +629,7 @@ impl PromptLibrary {
self.picker.update(cx, |picker, cx| picker.focus(cx));
}
pub fn inline_assist(&mut self, _: &InlineAssist, cx: &mut ViewContext<Self>) {
pub fn inline_assist(&mut self, action: &InlineAssist, cx: &mut ViewContext<Self>) {
let Some(active_prompt_id) = self.active_prompt_id else {
cx.propagate();
return;
@@ -637,9 +637,10 @@ impl PromptLibrary {
let prompt_editor = &self.prompt_editors[&active_prompt_id].body_editor;
let provider = CompletionProvider::global(cx);
let initial_prompt = action.prompt.clone();
if provider.is_authenticated() {
InlineAssistant::update_global(cx, |assistant, cx| {
assistant.assist(&prompt_editor, None, None, cx)
assistant.assist(&prompt_editor, None, None, initial_prompt, cx)
})
} else {
for window in cx.windows() {
@@ -768,6 +769,7 @@ impl PromptLibrary {
.capture_action(cx.listener(Self::focus_active_prompt))
.bg(cx.theme().colors().panel_background)
.h_full()
.px_1()
.w_1_3()
.overflow_x_hidden()
.child(
@@ -1297,6 +1299,17 @@ impl PromptStore {
fn first(&self) -> Option<PromptMetadata> {
self.metadata_cache.read().metadata.first().cloned()
}
pub fn operations_prompt(&self) -> String {
String::from_utf8(
Assets
.load("prompts/operations.md")
.unwrap()
.unwrap()
.to_vec(),
)
.unwrap()
}
}
/// Wraps a shared future to a prompt store so it can be assigned as a context global.

View File

@@ -1,171 +0,0 @@
use language::Rope;
use std::ops::Range;
/// Search the given buffer for the given substring, ignoring any differences
/// in line indentation between the query and the buffer.
///
/// Returns a vector of ranges of byte offsets in the buffer corresponding
/// to the entire lines of the buffer.
pub fn fuzzy_search_lines(haystack: &Rope, needle: &str) -> Option<Range<usize>> {
const SIMILARITY_THRESHOLD: f64 = 0.8;
let mut best_match: Option<(Range<usize>, f64)> = None; // (range, score)
let mut haystack_lines = haystack.chunks().lines();
let mut haystack_line_start = 0;
while let Some(mut haystack_line) = haystack_lines.next() {
let next_haystack_line_start = haystack_line_start + haystack_line.len() + 1;
let mut advanced_to_next_haystack_line = false;
let mut matched = true;
let match_start = haystack_line_start;
let mut match_end = next_haystack_line_start;
let mut match_score = 0.0;
let mut needle_lines = needle.lines().peekable();
while let Some(needle_line) = needle_lines.next() {
let similarity = line_similarity(haystack_line, needle_line);
if similarity >= SIMILARITY_THRESHOLD {
match_end = haystack_lines.offset();
match_score += similarity;
if needle_lines.peek().is_some() {
if let Some(next_haystack_line) = haystack_lines.next() {
advanced_to_next_haystack_line = true;
haystack_line = next_haystack_line;
} else {
matched = false;
break;
}
} else {
break;
}
} else {
matched = false;
break;
}
}
if matched
&& best_match
.as_ref()
.map(|(_, best_score)| match_score > *best_score)
.unwrap_or(true)
{
best_match = Some((match_start..match_end, match_score));
}
if advanced_to_next_haystack_line {
haystack_lines.seek(next_haystack_line_start);
}
haystack_line_start = next_haystack_line_start;
}
best_match.map(|(range, _)| range)
}
/// Calculates the similarity between two lines, ignoring leading and trailing whitespace,
/// using the Jaro-Winkler distance.
///
/// Returns a value between 0.0 and 1.0, where 1.0 indicates an exact match.
fn line_similarity(line1: &str, line2: &str) -> f64 {
strsim::jaro_winkler(line1.trim(), line2.trim())
}
#[cfg(test)]
mod test {
use super::*;
use gpui::{AppContext, Context as _};
use language::Buffer;
use unindent::Unindent as _;
use util::test::marked_text_ranges;
#[gpui::test]
fn test_fuzzy_search_lines(cx: &mut AppContext) {
let (text, expected_ranges) = marked_text_ranges(
&r#"
fn main() {
if a() {
assert_eq!(
1 + 2,
does_not_match,
);
}
println!("hi");
assert_eq!(
1 + 2,
3,
); // this last line does not match
« assert_eq!(
1 + 2,
3,
);
»
« assert_eq!(
"something",
"else",
);
»
}
"#
.unindent(),
false,
);
let buffer = cx.new_model(|cx| Buffer::local(&text, cx));
let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
let actual_range = fuzzy_search_lines(
snapshot.as_rope(),
&"
assert_eq!(
1 + 2,
3,
);
"
.unindent(),
)
.unwrap();
assert_eq!(actual_range, expected_ranges[0]);
let actual_range = fuzzy_search_lines(
snapshot.as_rope(),
&"
assert_eq!(
1 + 2,
3,
);
"
.unindent(),
)
.unwrap();
assert_eq!(actual_range, expected_ranges[0]);
let actual_range = fuzzy_search_lines(
snapshot.as_rope(),
&"
asst_eq!(
\"something\",
\"els\"
)
"
.unindent(),
)
.unwrap();
assert_eq!(actual_range, expected_ranges[1]);
let actual_range = fuzzy_search_lines(
snapshot.as_rope(),
&"
assert_eq!(
2 + 1,
3,
);
"
.unindent(),
);
assert_eq!(actual_range, None);
}
}

View File

@@ -27,11 +27,11 @@ pub mod now_command;
pub mod project_command;
pub mod prompt_command;
pub mod search_command;
pub mod symbols_command;
pub mod tabs_command;
pub mod term_command;
pub(crate) struct SlashCommandCompletionProvider {
commands: Arc<SlashCommandRegistry>,
cancel_flag: Mutex<Arc<AtomicBool>>,
editor: Option<WeakView<ContextEditor>>,
workspace: Option<WeakView<Workspace>>,
@@ -46,14 +46,12 @@ pub(crate) struct SlashCommandLine {
impl SlashCommandCompletionProvider {
pub fn new(
commands: Arc<SlashCommandRegistry>,
editor: Option<WeakView<ContextEditor>>,
workspace: Option<WeakView<Workspace>>,
) -> Self {
Self {
cancel_flag: Mutex::new(Arc::new(AtomicBool::new(false))),
editor,
commands,
workspace,
}
}
@@ -65,8 +63,8 @@ impl SlashCommandCompletionProvider {
name_range: Range<Anchor>,
cx: &mut WindowContext,
) -> Task<Result<Vec<project::Completion>>> {
let candidates = self
.commands
let commands = SlashCommandRegistry::global(cx);
let candidates = commands
.command_names()
.into_iter()
.enumerate()
@@ -76,7 +74,6 @@ impl SlashCommandCompletionProvider {
char_bag: def.as_ref().into(),
})
.collect::<Vec<_>>();
let commands = self.commands.clone();
let command_name = command_name.to_string();
let editor = self.editor.clone();
let workspace = self.workspace.clone();
@@ -155,7 +152,8 @@ impl SlashCommandCompletionProvider {
flag.store(true, SeqCst);
*flag = new_cancel_flag.clone();
if let Some(command) = self.commands.command(command_name) {
let commands = SlashCommandRegistry::global(cx);
if let Some(command) = commands.command(command_name) {
let completions = command.complete_argument(
argument,
new_cancel_flag.clone(),

View File

@@ -1,14 +1,16 @@
use std::path::Path;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::Duration;
use anyhow::{anyhow, bail, Result};
use assistant_slash_command::{
ArgumentCompletion, SlashCommand, SlashCommandOutput, SlashCommandOutputSection,
};
use gpui::{AppContext, Model, Task, WeakView};
use gpui::{AppContext, BackgroundExecutor, Model, Task, WeakView};
use indexed_docs::{
IndexedDocsRegistry, IndexedDocsStore, LocalProvider, PackageName, ProviderId, RustdocIndexer,
DocsDotRsProvider, IndexedDocsRegistry, IndexedDocsStore, LocalRustdocProvider, PackageName,
ProviderId,
};
use language::LspAdapterDelegate;
use project::{Project, ProjectPath};
@@ -34,22 +36,22 @@ impl DocsSlashCommand {
))
}
/// Ensures that the rustdoc provider is registered.
/// Ensures that the indexed doc providers for Rust are registered.
///
/// Ideally we would do this sooner, but we need to wait until we're able to
/// access the workspace so we can read the project.
fn ensure_rustdoc_provider_is_registered(
fn ensure_rust_doc_providers_are_registered(
&self,
workspace: Option<WeakView<Workspace>>,
cx: &mut AppContext,
) {
let indexed_docs_registry = IndexedDocsRegistry::global(cx);
if indexed_docs_registry
.get_provider_store(ProviderId::rustdoc())
.get_provider_store(LocalRustdocProvider::id())
.is_none()
{
let index_provider_deps = maybe!({
let workspace = workspace.ok_or_else(|| anyhow!("no workspace"))?;
let workspace = workspace.clone().ok_or_else(|| anyhow!("no workspace"))?;
let workspace = workspace
.upgrade()
.ok_or_else(|| anyhow!("workspace was dropped"))?;
@@ -63,11 +65,80 @@ impl DocsSlashCommand {
});
if let Some((fs, cargo_workspace_root)) = index_provider_deps.log_err() {
indexed_docs_registry.register_provider(Box::new(RustdocIndexer::new(Box::new(
LocalProvider::new(fs, cargo_workspace_root),
))));
indexed_docs_registry.register_provider(Box::new(LocalRustdocProvider::new(
fs,
cargo_workspace_root,
)));
}
}
if indexed_docs_registry
.get_provider_store(DocsDotRsProvider::id())
.is_none()
{
let http_client = maybe!({
let workspace = workspace.ok_or_else(|| anyhow!("no workspace"))?;
let workspace = workspace
.upgrade()
.ok_or_else(|| anyhow!("workspace was dropped"))?;
let project = workspace.read(cx).project().clone();
anyhow::Ok(project.read(cx).client().http_client().clone())
});
if let Some(http_client) = http_client.log_err() {
indexed_docs_registry
.register_provider(Box::new(DocsDotRsProvider::new(http_client)));
}
}
}
/// Runs just-in-time indexing for a given package, in case the slash command
/// is run without any entries existing in the index.
fn run_just_in_time_indexing(
store: Arc<IndexedDocsStore>,
key: String,
package: PackageName,
executor: BackgroundExecutor,
) -> Task<()> {
executor.clone().spawn(async move {
let (prefix, needs_full_index) = if let Some((prefix, _)) = key.split_once('*') {
// If we have a wildcard in the search, we want to wait until
// we've completely finished indexing so we get a full set of
// results for the wildcard.
(prefix.to_string(), true)
} else {
(key, false)
};
// If we already have some entries, we assume that we've indexed the package before
// and don't need to do it again.
let has_any_entries = store
.any_with_prefix(prefix.clone())
.await
.unwrap_or_default();
if has_any_entries {
return ();
};
let index_task = store.clone().index(package.clone());
if needs_full_index {
_ = index_task.await;
} else {
loop {
executor.timer(Duration::from_millis(200)).await;
if store
.any_with_prefix(prefix.clone())
.await
.unwrap_or_default()
|| !store.is_indexing(&package)
{
break;
}
}
}
})
}
}
@@ -95,7 +166,7 @@ impl SlashCommand for DocsSlashCommand {
workspace: Option<WeakView<Workspace>>,
cx: &mut AppContext,
) -> Task<Result<Vec<ArgumentCompletion>>> {
self.ensure_rustdoc_provider_is_registered(workspace, cx);
self.ensure_rust_doc_providers_are_registered(workspace, cx);
let indexed_docs_registry = IndexedDocsRegistry::global(cx);
let args = DocsSlashCommandArgs::parse(&query);
@@ -121,6 +192,14 @@ impl SlashCommand for DocsSlashCommand {
match args {
DocsSlashCommandArgs::NoProvider => {
let providers = indexed_docs_registry.list_providers();
if providers.is_empty() {
return Ok(vec![ArgumentCompletion {
label: "No available docs providers.".to_string(),
new_text: String::new(),
run_command: false,
}]);
}
Ok(providers
.into_iter()
.map(|provider| ArgumentCompletion {
@@ -171,46 +250,72 @@ impl SlashCommand for DocsSlashCommand {
};
let args = DocsSlashCommandArgs::parse(argument);
let text = cx.background_executor().spawn({
let executor = cx.background_executor().clone();
let task = cx.background_executor().spawn({
let store = args
.provider()
.ok_or_else(|| anyhow!("no docs provider specified"))
.and_then(|provider| IndexedDocsStore::try_global(provider, cx));
async move {
match args {
let (provider, key) = match args.clone() {
DocsSlashCommandArgs::NoProvider => bail!("no docs provider specified"),
DocsSlashCommandArgs::SearchPackageDocs {
provider, package, ..
} => {
let store = store?;
let item_docs = store.load(package.clone()).await?;
anyhow::Ok((provider, package, item_docs.to_string()))
}
} => (provider, package),
DocsSlashCommandArgs::SearchItemDocs {
provider,
item_path,
..
} => {
let store = store?;
let item_docs = store.load(item_path.clone()).await?;
} => (provider, item_path),
};
anyhow::Ok((provider, item_path, item_docs.to_string()))
}
let store = store?;
if let Some(package) = args.package() {
Self::run_just_in_time_indexing(store.clone(), key.clone(), package, executor)
.await;
}
let (text, ranges) = if let Some((prefix, _)) = key.split_once('*') {
let docs = store.load_many_by_prefix(prefix.to_string()).await?;
let mut text = String::new();
let mut ranges = Vec::new();
for (key, docs) in docs {
let prev_len = text.len();
text.push_str(&docs.0);
text.push_str("\n");
ranges.push((key, prev_len..text.len()));
text.push_str("\n");
}
(text, ranges)
} else {
let item_docs = store.load(key.clone()).await?;
let text = item_docs.to_string();
let range = 0..text.len();
(text, vec![(key, range)])
};
anyhow::Ok((provider, text, ranges))
}
});
cx.foreground_executor().spawn(async move {
let (provider, path, text) = text.await?;
let range = 0..text.len();
let (provider, text, ranges) = task.await?;
Ok(SlashCommandOutput {
text,
sections: vec![SlashCommandOutputSection {
range,
icon: IconName::FileRust,
label: format!("docs ({provider}): {path}",).into(),
}],
sections: ranges
.into_iter()
.map(|(key, range)| SlashCommandOutputSection {
range,
icon: IconName::FileDoc,
label: format!("docs ({provider}): {key}",).into(),
})
.collect(),
run_commands_in_text: false,
})
})
@@ -221,7 +326,7 @@ fn is_item_path_delimiter(char: char) -> bool {
!char.is_alphanumeric() && char != '-' && char != '_'
}
#[derive(Debug, PartialEq)]
#[derive(Debug, PartialEq, Clone)]
pub(crate) enum DocsSlashCommandArgs {
NoProvider,
SearchPackageDocs {

View File

@@ -27,7 +27,7 @@ pub(crate) struct FetchSlashCommand;
impl FetchSlashCommand {
async fn build_message(http_client: Arc<HttpClientWithUrl>, url: &str) -> Result<String> {
let mut url = url.to_owned();
if !url.starts_with("https://") {
if !url.starts_with("https://") && !url.starts_with("http://") {
url = format!("https://{url}");
}

View File

@@ -23,7 +23,7 @@ impl SlashCommand for NowSlashCommand {
}
fn menu_text(&self) -> String {
"Insert current date and time".into()
"Insert Current Date and Time".into()
}
fn requires_argument(&self) -> bool {

View File

@@ -0,0 +1,89 @@
use super::{SlashCommand, SlashCommandOutput};
use anyhow::{anyhow, Context as _, Result};
use assistant_slash_command::{ArgumentCompletion, SlashCommandOutputSection};
use editor::Editor;
use gpui::{AppContext, Task, WeakView};
use language::LspAdapterDelegate;
use std::sync::Arc;
use std::{path::Path, sync::atomic::AtomicBool};
use ui::{IconName, WindowContext};
use workspace::Workspace;
pub(crate) struct OutlineSlashCommand;
impl SlashCommand for OutlineSlashCommand {
fn name(&self) -> String {
"symbols".into()
}
fn description(&self) -> String {
"insert symbols for active tab".into()
}
fn menu_text(&self) -> String {
"Insert Symbols for Active Tab".into()
}
fn complete_argument(
self: Arc<Self>,
_query: String,
_cancel: Arc<AtomicBool>,
_workspace: Option<WeakView<Workspace>>,
_cx: &mut AppContext,
) -> Task<Result<Vec<ArgumentCompletion>>> {
Task::ready(Err(anyhow!("this command does not require argument")))
}
fn requires_argument(&self) -> bool {
false
}
fn run(
self: Arc<Self>,
_argument: Option<&str>,
workspace: WeakView<Workspace>,
_delegate: Arc<dyn LspAdapterDelegate>,
cx: &mut WindowContext,
) -> Task<Result<SlashCommandOutput>> {
let output = workspace.update(cx, |workspace, cx| {
let Some(active_item) = workspace.active_item(cx) else {
return Task::ready(Err(anyhow!("no active tab")));
};
let Some(buffer) = active_item
.downcast::<Editor>()
.and_then(|editor| editor.read(cx).buffer().read(cx).as_singleton())
else {
return Task::ready(Err(anyhow!("active tab is not an editor")));
};
let snapshot = buffer.read(cx).snapshot();
let path = snapshot.resolve_file_path(cx, true);
cx.background_executor().spawn(async move {
let outline = snapshot
.outline(None)
.context("no symbols for active tab")?;
let path = path.as_deref().unwrap_or(Path::new("untitled"));
let mut outline_text = format!("Symbols for {}:\n", path.display());
for item in &outline.path_candidates {
outline_text.push_str("- ");
outline_text.push_str(&item.string);
outline_text.push('\n');
}
Ok(SlashCommandOutput {
sections: vec![SlashCommandOutputSection {
range: 0..outline_text.len(),
icon: IconName::ListTree,
label: path.to_string_lossy().to_string().into(),
}],
text: outline_text,
run_commands_in_text: false,
})
})
});
output.unwrap_or_else(|error| Task::ready(Err(error)))
}
}

View File

@@ -31,7 +31,7 @@ impl SlashCommand for TermSlashCommand {
}
fn menu_text(&self) -> String {
"Insert terminal output".into()
"Insert Terminal Output".into()
}
fn requires_argument(&self) -> bool {

View File

@@ -1,7 +1,7 @@
use crate::{
assistant_settings::AssistantSettings, humanize_token_count,
prompts::generate_terminal_assistant_prompt, AssistantPanel, AssistantPanelEvent,
CompletionProvider, LanguageModelRequest, LanguageModelRequestMessage, Role,
CompletionProvider,
};
use anyhow::{Context as _, Result};
use client::telemetry::Telemetry;
@@ -13,10 +13,11 @@ use editor::{
use fs::Fs;
use futures::{channel::mpsc, SinkExt, StreamExt};
use gpui::{
AppContext, Context, EventEmitter, FocusHandle, FocusableView, FontStyle, FontWeight, Global,
Model, ModelContext, Subscription, Task, TextStyle, UpdateGlobal, View, WeakView, WhiteSpace,
AppContext, Context, EventEmitter, FocusHandle, FocusableView, Global, Model, ModelContext,
Subscription, Task, TextStyle, UpdateGlobal, View, WeakView,
};
use language::Buffer;
use language_model::{LanguageModelRequest, LanguageModelRequestMessage, Role};
use settings::{update_settings_file, Settings};
use std::{
cmp,
@@ -26,7 +27,7 @@ use std::{
use terminal::Terminal;
use terminal_view::TerminalView;
use theme::ThemeSettings;
use ui::{prelude::*, ContextMenu, PopoverMenu, Tooltip};
use ui::{prelude::*, ContextMenu, IconButtonShape, PopoverMenu, Tooltip};
use util::ResultExt;
use workspace::{notifications::NotificationId, Toast, Workspace};
@@ -73,11 +74,13 @@ impl TerminalInlineAssistant {
terminal_view: &View<TerminalView>,
workspace: Option<WeakView<Workspace>>,
assistant_panel: Option<&View<AssistantPanel>>,
initial_prompt: Option<String>,
cx: &mut WindowContext,
) {
let terminal = terminal_view.read(cx).terminal().clone();
let assist_id = self.next_assist_id.post_inc();
let prompt_buffer = cx.new_model(|cx| Buffer::local("", cx));
let prompt_buffer =
cx.new_model(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx));
let prompt_buffer = cx.new_model(|cx| MultiBuffer::singleton(prompt_buffer, cx));
let codegen = cx.new_model(|_| Codegen::new(terminal, self.telemetry.clone()));
@@ -556,8 +559,7 @@ impl Render for PromptEditor {
PopoverMenu::new("model-switcher")
.menu(move |cx| {
ContextMenu::build(cx, |mut menu, cx| {
for model in CompletionProvider::global(cx).available_models(cx)
{
for model in CompletionProvider::global(cx).available_models() {
menu = menu.custom_entry(
{
let model = model.clone();
@@ -586,7 +588,7 @@ impl Render for PromptEditor {
})
.trigger(
IconButton::new("context", IconName::Settings)
.size(ButtonSize::None)
.shape(IconButtonShape::Square)
.icon_size(IconSize::Small)
.icon_color(Color::Muted)
.tooltip(move |cx| {
@@ -598,7 +600,7 @@ impl Render for PromptEditor {
.display_name()
),
None,
"Click to Change Model",
"Change Model",
cx,
)
}),
@@ -943,13 +945,9 @@ impl PromptEditor {
font_family: settings.ui_font.family.clone(),
font_features: settings.ui_font.features.clone(),
font_size: rems(0.875).into(),
font_weight: FontWeight::NORMAL,
font_style: FontStyle::Normal,
font_weight: settings.ui_font.weight,
line_height: relative(1.3),
background_color: None,
underline: None,
strikethrough: None,
white_space: WhiteSpace::Normal,
..Default::default()
};
EditorElement::new(
&self.editor,
@@ -1026,7 +1024,7 @@ impl Codegen {
let telemetry = self.telemetry.clone();
let model_telemetry_id = prompt.model.telemetry_id();
let response = CompletionProvider::global(cx).complete(prompt, cx);
let response = CompletionProvider::global(cx).stream_completion(prompt, cx);
self.generation = cx.spawn(|this, mut cx| async move {
let response = response.await;
@@ -1037,8 +1035,8 @@ impl Codegen {
let mut response_latency = None;
let request_start = Instant::now();
let task = async {
let mut response = response.inner.await?;
while let Some(chunk) = response.next().await {
let mut chunks = response?;
while let Some(chunk) = chunks.next().await {
if response_latency.is_none() {
response_latency = Some(request_start.elapsed());
}

View File

@@ -67,7 +67,7 @@ pub struct SlashCommandOutput {
pub run_commands_in_text: bool,
}
#[derive(Clone, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SlashCommandOutputSection<T> {
pub range: Range<T>,
pub icon: IconName,

View File

@@ -23,6 +23,7 @@ isahc.workspace = true
log.workspace = true
markdown_preview.workspace = true
menu.workspace = true
paths.workspace = true
release_channel.workspace = true
schemars.workspace = true
serde.workspace = true

View File

@@ -1,7 +1,7 @@
mod update_notification;
use anyhow::{anyhow, Context, Result};
use client::{Client, TelemetrySettings, ZED_APP_PATH};
use client::{Client, TelemetrySettings};
use db::kvp::KEY_VALUE_STORE;
use db::RELEASE_CHANNEL;
use editor::{Editor, MultiBuffer};
@@ -28,7 +28,7 @@ use std::{
consts::{ARCH, OS},
},
ffi::OsString,
path::PathBuf,
path::{Path, PathBuf},
sync::Arc,
time::Duration,
};
@@ -288,7 +288,12 @@ fn view_release_notes_locally(workspace: &mut Workspace, cx: &mut ViewContext<Wo
Some(tab_description),
cx,
);
workspace.add_item_to_active_pane(Box::new(view.clone()), None, cx);
workspace.add_item_to_active_pane(
Box::new(view.clone()),
None,
true,
cx,
);
cx.notify();
})
.log_err();
@@ -354,7 +359,6 @@ impl AutoUpdater {
return;
}
self.status = AutoUpdateStatus::Checking;
cx.notify();
self.pending_poll = Some(cx.spawn(|this, mut cx| async move {
@@ -380,29 +384,65 @@ impl AutoUpdater {
cx.notify();
}
async fn update(this: Model<Self>, mut cx: AsyncAppContext) -> Result<()> {
let (client, current_version) = this.read_with(&cx, |this, _| {
(this.http_client.clone(), this.current_version)
})?;
pub async fn get_latest_remote_server_release(
os: &str,
arch: &str,
mut release_channel: ReleaseChannel,
cx: &mut AsyncAppContext,
) -> Result<PathBuf> {
let this = cx.update(|cx| {
cx.default_global::<GlobalAutoUpdate>()
.0
.clone()
.ok_or_else(|| anyhow!("auto-update not initialized"))
})??;
let asset = match OS {
"linux" => format!("zed-linux-{}.tar.gz", ARCH),
"macos" => "Zed.dmg".into(),
_ => return Err(anyhow!("auto-update not supported for OS {:?}", OS)),
};
if release_channel == ReleaseChannel::Dev {
release_channel = ReleaseChannel::Nightly;
}
let release = Self::get_latest_release(
&this,
"zed-remote-server",
os,
arch,
Some(release_channel),
cx,
)
.await?;
let servers_dir = paths::remote_servers_dir();
let channel_dir = servers_dir.join(release_channel.dev_name());
let platform_dir = channel_dir.join(format!("{}-{}", os, arch));
let version_path = platform_dir.join(format!("{}.gz", release.version));
smol::fs::create_dir_all(&platform_dir).await.ok();
let client = this.read_with(cx, |this, _| this.http_client.clone())?;
if smol::fs::metadata(&version_path).await.is_err() {
log::info!("downloading zed-remote-server {os} {arch}");
download_remote_server_binary(&version_path, release, client, cx).await?;
}
Ok(version_path)
}
async fn get_latest_release(
this: &Model<Self>,
asset: &str,
os: &str,
arch: &str,
release_channel: Option<ReleaseChannel>,
cx: &mut AsyncAppContext,
) -> Result<JsonRelease> {
let client = this.read_with(cx, |this, _| this.http_client.clone())?;
let mut url_string = client.build_url(&format!(
"/api/releases/latest?asset={}&os={}&arch={}",
asset, OS, ARCH
asset, os, arch
));
cx.update(|cx| {
if let Some(param) = ReleaseChannel::try_global(cx)
.and_then(|release_channel| release_channel.release_query_param())
{
url_string += "&";
url_string += param;
}
})?;
if let Some(param) = release_channel.and_then(|c| c.release_query_param()) {
url_string += "&";
url_string += param;
}
let mut response = client.get(&url_string, Default::default(), true).await?;
@@ -413,8 +453,34 @@ impl AutoUpdater {
.await
.context("error reading release")?;
let release: JsonRelease =
serde_json::from_slice(body.as_slice()).context("error deserializing release")?;
if !response.status().is_success() {
Err(anyhow!(
"failed to fetch release: {:?}",
String::from_utf8_lossy(&body),
))?;
}
serde_json::from_slice(body.as_slice()).with_context(|| {
format!(
"error deserializing release {:?}",
String::from_utf8_lossy(&body),
)
})
}
async fn update(this: Model<Self>, mut cx: AsyncAppContext) -> Result<()> {
let (client, current_version, release_channel) = this.update(&mut cx, |this, cx| {
this.status = AutoUpdateStatus::Checking;
cx.notify();
(
this.http_client.clone(),
this.current_version,
ReleaseChannel::try_global(cx),
)
})?;
let release =
Self::get_latest_release(&this, "zed", OS, ARCH, release_channel, &mut cx).await?;
let should_download = match *RELEASE_CHANNEL {
ReleaseChannel::Nightly => cx
@@ -441,19 +507,21 @@ impl AutoUpdater {
let temp_dir = tempfile::Builder::new()
.prefix("zed-auto-update")
.tempdir()?;
let downloaded_asset = download_release(&temp_dir, release, &asset, client, &cx).await?;
let filename = match OS {
"macos" => Ok("Zed.dmg"),
"linux" => Ok("zed.tar.gz"),
_ => Err(anyhow!("not supported: {:?}", OS)),
}?;
let downloaded_asset = temp_dir.path().join(filename);
download_release(&downloaded_asset, release, client, &cx).await?;
this.update(&mut cx, |this, cx| {
this.status = AutoUpdateStatus::Installing;
cx.notify();
})?;
// We store the path of our current binary, before we install, since installation might
// delete it. Once deleted, it's hard to get the path to our binary on Linux.
// So we cache it here, which allows us to then restart later on.
let binary_path = cx.update(|cx| cx.app_path())??;
match OS {
let binary_path = match OS {
"macos" => install_release_macos(&temp_dir, downloaded_asset, &cx).await,
"linux" => install_release_linux(&temp_dir, downloaded_asset, &cx).await,
_ => Err(anyhow!("not supported: {:?}", OS)),
@@ -500,14 +568,38 @@ impl AutoUpdater {
}
}
async fn download_release(
temp_dir: &tempfile::TempDir,
async fn download_remote_server_binary(
target_path: &PathBuf,
release: JsonRelease,
target_filename: &str,
client: Arc<HttpClientWithUrl>,
cx: &AsyncAppContext,
) -> Result<PathBuf> {
let target_path = temp_dir.path().join(target_filename);
) -> Result<()> {
let mut target_file = File::create(&target_path).await?;
let (installation_id, release_channel, telemetry) = cx.update(|cx| {
let installation_id = Client::global(cx).telemetry().installation_id();
let release_channel =
ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
let telemetry = TelemetrySettings::get_global(cx).metrics;
(installation_id, release_channel, telemetry)
})?;
let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
installation_id,
release_channel,
telemetry,
})?);
let mut response = client.get(&release.url, request_body, true).await?;
smol::io::copy(response.body_mut(), &mut target_file).await?;
Ok(())
}
async fn download_release(
target_path: &Path,
release: JsonRelease,
client: Arc<HttpClientWithUrl>,
cx: &AsyncAppContext,
) -> Result<()> {
let mut target_file = File::create(&target_path).await?;
let (installation_id, release_channel, telemetry) = cx.update(|cx| {
@@ -529,16 +621,17 @@ async fn download_release(
smol::io::copy(response.body_mut(), &mut target_file).await?;
log::info!("downloaded update. path:{:?}", target_path);
Ok(target_path)
Ok(())
}
async fn install_release_linux(
temp_dir: &tempfile::TempDir,
downloaded_tar_gz: PathBuf,
cx: &AsyncAppContext,
) -> Result<()> {
) -> Result<PathBuf> {
let channel = cx.update(|cx| ReleaseChannel::global(cx).dev_name())?;
let home_dir = PathBuf::from(env::var("HOME").context("no HOME env var set")?);
let running_app_path = cx.update(|cx| cx.app_path())??;
let extracted = temp_dir.path().join("zed");
fs::create_dir_all(&extracted)
@@ -569,7 +662,16 @@ async fn install_release_linux(
let app_folder_name = format!("zed{}.app", suffix);
let from = extracted.join(&app_folder_name);
let to = home_dir.join(".local");
let mut to = home_dir.join(".local");
let expected_suffix = format!("{}/libexec/zed-editor", app_folder_name);
if let Some(prefix) = running_app_path
.to_str()
.and_then(|str| str.strip_suffix(&expected_suffix))
{
to = PathBuf::from(prefix);
}
let output = Command::new("rsync")
.args(&["-av", "--delete"])
@@ -586,17 +688,15 @@ async fn install_release_linux(
String::from_utf8_lossy(&output.stderr)
);
Ok(())
Ok(to.join(expected_suffix))
}
async fn install_release_macos(
temp_dir: &tempfile::TempDir,
downloaded_dmg: PathBuf,
cx: &AsyncAppContext,
) -> Result<()> {
let running_app_path = ZED_APP_PATH
.clone()
.map_or_else(|| cx.update(|cx| cx.app_path())?, Ok)?;
) -> Result<PathBuf> {
let running_app_path = cx.update(|cx| cx.app_path())??;
let running_app_filename = running_app_path
.file_name()
.ok_or_else(|| anyhow!("invalid running app path"))?;
@@ -644,5 +744,5 @@ async fn install_release_macos(
String::from_utf8_lossy(&output.stderr)
);
Ok(())
Ok(running_app_path)
}

View File

@@ -72,7 +72,7 @@ impl Render for Breadcrumbs {
.into_any()
});
let breadcrumbs = Itertools::intersperse_with(highlighted_segments, || {
Label::new("").color(Color::Muted).into_any_element()
Label::new("").color(Color::Placeholder).into_any_element()
});
let breadcrumbs_stack = h_flex().gap_1().children(breadcrumbs);
@@ -83,7 +83,7 @@ impl Render for Breadcrumbs {
Some(editor) => element.child(
ButtonLike::new("toggle outline view")
.child(breadcrumbs_stack)
.style(ButtonStyle::Subtle)
.style(ButtonStyle::Transparent)
.on_click(move |_, cx| {
if let Some(editor) = editor.upgrade() {
outline::toggle(editor, &editor::actions::ToggleOutline, cx)
@@ -113,29 +113,30 @@ impl ToolbarItemView for Breadcrumbs {
) -> ToolbarItemLocation {
cx.notify();
self.active_item = None;
if let Some(item) = active_pane_item {
let this = cx.view().downgrade();
self.subscription = Some(item.subscribe_to_item_events(
cx,
Box::new(move |event, cx| {
if let ItemEvent::UpdateBreadcrumbs = event {
this.update(cx, |this, cx| {
cx.notify();
if let Some(active_item) = this.active_item.as_ref() {
cx.emit(ToolbarItemEvent::ChangeLocation(
active_item.breadcrumb_location(cx),
))
}
})
.ok();
}
}),
));
self.active_item = Some(item.boxed_clone());
item.breadcrumb_location(cx)
} else {
ToolbarItemLocation::Hidden
}
let Some(item) = active_pane_item else {
return ToolbarItemLocation::Hidden;
};
let this = cx.view().downgrade();
self.subscription = Some(item.subscribe_to_item_events(
cx,
Box::new(move |event, cx| {
if let ItemEvent::UpdateBreadcrumbs = event {
this.update(cx, |this, cx| {
cx.notify();
if let Some(active_item) = this.active_item.as_ref() {
cx.emit(ToolbarItemEvent::ChangeLocation(
active_item.breadcrumb_location(cx),
))
}
})
.ok();
}
}),
));
self.active_item = Some(item.boxed_clone());
item.breadcrumb_location(cx)
}
fn pane_focus_update(&mut self, pane_focused: bool, _: &mut ViewContext<Self>) {

View File

@@ -11,6 +11,7 @@ pub struct IpcHandshake {
pub enum CliRequest {
Open {
paths: Vec<String>,
urls: Vec<String>,
wait: bool,
open_new_workspace: Option<bool>,
dev_server_token: Option<String>,

View File

@@ -5,6 +5,7 @@ use clap::Parser;
use cli::{ipc::IpcOneShotServer, CliRequest, CliResponse, IpcHandshake};
use parking_lot::Mutex;
use std::{
convert::Infallible,
env, fs, io,
path::{Path, PathBuf},
process::ExitStatus,
@@ -37,8 +38,7 @@ struct Args {
///
/// Use `path:line:row` syntax to open a file at a specific location.
/// Non-existing paths and directories will ignore `:line:row` suffix.
#[arg(value_parser = parse_path_with_position)]
paths_with_position: Vec<PathLikeWithPosition<PathBuf>>,
paths_with_position: Vec<String>,
/// Print Zed's version and the app path.
#[arg(short, long)]
version: bool,
@@ -53,12 +53,30 @@ struct Args {
dev_server_token: Option<String>,
}
fn parse_path_with_position(
argument_str: &str,
) -> Result<PathLikeWithPosition<PathBuf>, std::convert::Infallible> {
PathLikeWithPosition::parse_str(argument_str, |_, path_str| {
fn parse_path_with_position(argument_str: &str) -> Result<String, std::io::Error> {
let path_like = PathLikeWithPosition::parse_str::<Infallible>(argument_str, |_, path_str| {
Ok(Path::new(path_str).to_path_buf())
})
.unwrap();
let curdir = env::current_dir()?;
let canonicalized = path_like.map_path_like(|path| match fs::canonicalize(&path) {
Ok(path) => Ok(path),
Err(e) => {
if let Some(mut parent) = path.parent() {
if parent == Path::new("") {
parent = &curdir
}
match fs::canonicalize(parent) {
Ok(parent) => Ok(parent.join(path.file_name().unwrap())),
Err(_) => Err(e),
}
} else {
Err(e)
}
}
})?;
Ok(canonicalized.to_string(|path| path.display().to_string()))
}
fn main() -> Result<()> {
@@ -91,28 +109,6 @@ fn main() -> Result<()> {
return Ok(());
}
let curdir = env::current_dir()?;
let mut paths = vec![];
for path in args.paths_with_position {
let canonicalized = path.map_path_like(|path| match fs::canonicalize(&path) {
Ok(path) => Ok(path),
Err(e) => {
if let Some(mut parent) = path.parent() {
if parent == Path::new("") {
parent = &curdir;
}
match fs::canonicalize(parent) {
Ok(parent) => Ok(parent.join(path.file_name().unwrap())),
Err(_) => Err(e),
}
} else {
Err(e)
}
}
})?;
paths.push(canonicalized.to_string(|path| path.display().to_string()))
}
let (server, server_name) =
IpcOneShotServer::<IpcHandshake>::new().context("Handshake before Zed spawn")?;
let url = format!("zed-cli://{server_name}");
@@ -126,6 +122,20 @@ fn main() -> Result<()> {
};
let exit_status = Arc::new(Mutex::new(None));
let mut paths = vec![];
let mut urls = vec![];
for path in args.paths_with_position.iter() {
if path.starts_with("zed://")
|| path.starts_with("http://")
|| path.starts_with("https://")
|| path.starts_with("file://")
|| path.starts_with("ssh://")
{
urls.push(path.to_string());
} else {
paths.push(parse_path_with_position(path)?)
}
}
let sender: JoinHandle<anyhow::Result<()>> = thread::spawn({
let exit_status = exit_status.clone();
@@ -134,6 +144,7 @@ fn main() -> Result<()> {
let (tx, rx) = (handshake.requests, handshake.responses);
tx.send(CliRequest::Open {
paths,
urls,
wait: args.wait,
open_new_workspace,
dev_server_token: args.dev_server_token,

View File

@@ -13,8 +13,9 @@ use async_tungstenite::tungstenite::{
use clock::SystemClock;
use collections::HashMap;
use futures::{
channel::oneshot, future::LocalBoxFuture, AsyncReadExt, FutureExt, SinkExt, Stream, StreamExt,
TryFutureExt as _, TryStreamExt,
channel::oneshot,
future::{BoxFuture, LocalBoxFuture},
AsyncReadExt, FutureExt, SinkExt, Stream, StreamExt, TryFutureExt as _, TryStreamExt,
};
use gpui::{
actions, AnyModel, AnyWeakModel, AppContext, AsyncAppContext, Global, Model, Task, WeakModel,
@@ -23,6 +24,7 @@ use http::{HttpClient, HttpClientWithUrl};
use lazy_static::lazy_static;
use parking_lot::RwLock;
use postage::watch;
use proto::ProtoClient;
use rand::prelude::*;
use release_channel::{AppVersion, ReleaseChannel};
use rpc::proto::{AnyTypedEnvelope, EntityMessage, EnvelopedMessage, PeerId, RequestMessage};
@@ -217,6 +219,9 @@ pub struct Client {
>,
>,
>,
#[cfg(any(test, feature = "test-support"))]
rpc_url: RwLock<Option<Url>>,
}
#[derive(Error, Debug)]
@@ -527,6 +532,8 @@ impl Client {
authenticate: Default::default(),
#[cfg(any(test, feature = "test-support"))]
establish_connection: Default::default(),
#[cfg(any(test, feature = "test-support"))]
rpc_url: RwLock::default(),
})
}
@@ -584,6 +591,12 @@ impl Client {
self
}
#[cfg(any(test, feature = "test-support"))]
pub fn override_rpc_url(&self, url: Url) -> &Self {
*self.rpc_url.write() = Some(url);
self
}
pub fn global(cx: &AppContext) -> Arc<Self> {
cx.global::<GlobalClient>().0.clone()
}
@@ -1086,38 +1099,50 @@ impl Client {
self.establish_websocket_connection(credentials, cx)
}
async fn get_rpc_url(
fn rpc_url(
&self,
http: Arc<HttpClientWithUrl>,
release_channel: Option<ReleaseChannel>,
) -> Result<Url> {
if let Some(url) = &*ZED_RPC_URL {
return Url::parse(url).context("invalid rpc url");
}
) -> impl Future<Output = Result<Url>> {
#[cfg(any(test, feature = "test-support"))]
let url_override = self.rpc_url.read().clone();
let mut url = http.build_url("/rpc");
if let Some(preview_param) =
release_channel.and_then(|channel| channel.release_query_param())
{
url += "?";
url += preview_param;
}
let response = http.get(&url, Default::default(), false).await?;
let collab_url = if response.status().is_redirection() {
response
.headers()
.get("Location")
.ok_or_else(|| anyhow!("missing location header in /rpc response"))?
.to_str()
.map_err(EstablishConnectionError::other)?
.to_string()
} else {
Err(anyhow!(
"unexpected /rpc response status {}",
response.status()
))?
};
async move {
#[cfg(any(test, feature = "test-support"))]
if let Some(url) = url_override {
return Ok(url);
}
Url::parse(&collab_url).context("invalid rpc url")
if let Some(url) = &*ZED_RPC_URL {
return Url::parse(url).context("invalid rpc url");
}
let mut url = http.build_url("/rpc");
if let Some(preview_param) =
release_channel.and_then(|channel| channel.release_query_param())
{
url += "?";
url += preview_param;
}
let response = http.get(&url, Default::default(), false).await?;
let collab_url = if response.status().is_redirection() {
response
.headers()
.get("Location")
.ok_or_else(|| anyhow!("missing location header in /rpc response"))?
.to_str()
.map_err(EstablishConnectionError::other)?
.to_string()
} else {
Err(anyhow!(
"unexpected /rpc response status {}",
response.status()
))?
};
Url::parse(&collab_url).context("invalid rpc url")
}
}
fn establish_websocket_connection(
@@ -1144,8 +1169,9 @@ impl Client {
);
let http = self.http.clone();
let rpc_url = self.rpc_url(http, release_channel);
cx.background_executor().spawn(async move {
let mut rpc_url = Self::get_rpc_url(http, release_channel).await?;
let mut rpc_url = rpc_url.await?;
let rpc_host = rpc_url
.host_str()
.zip(rpc_url.port_or_known_default())
@@ -1186,6 +1212,7 @@ impl Client {
cx: &AsyncAppContext,
) -> Task<Result<Credentials>> {
let http = self.http.clone();
let this = self.clone();
cx.spawn(|cx| async move {
let background = cx.background_executor().clone();
@@ -1215,7 +1242,8 @@ impl Client {
{
eprintln!("authenticate as admin {login}, {token}");
return Self::authenticate_as_admin(http, login.clone(), token.clone())
return this
.authenticate_as_admin(http, login.clone(), token.clone())
.await;
}
@@ -1303,6 +1331,7 @@ impl Client {
}
async fn authenticate_as_admin(
self: &Arc<Self>,
http: Arc<HttpClientWithUrl>,
login: String,
mut api_token: String,
@@ -1319,7 +1348,7 @@ impl Client {
// Use the collab server's admin API to retrieve the id
// of the impersonated user.
let mut url = Self::get_rpc_url(http.clone(), None).await?;
let mut url = self.rpc_url(http.clone(), None).await?;
url.set_path("/user");
url.set_query(Some(&format!("github_login={login}")));
let request = Request::get(url.as_str())
@@ -1381,6 +1410,11 @@ impl Client {
self.peer.send(self.connection_id()?, message)
}
fn send_dynamic(&self, envelope: proto::Envelope) -> Result<()> {
let connection_id = self.connection_id()?;
self.peer.send_dynamic(connection_id, envelope)
}
pub fn request<T: RequestMessage>(
&self,
request: T,
@@ -1579,6 +1613,20 @@ impl Client {
}
}
impl ProtoClient for Client {
fn request(
&self,
envelope: proto::Envelope,
request_type: &'static str,
) -> BoxFuture<'static, Result<proto::Envelope>> {
self.request_dynamic(envelope, request_type).boxed()
}
fn send(&self, envelope: proto::Envelope) -> Result<()> {
self.send_dynamic(envelope)
}
}
#[derive(Serialize, Deserialize)]
struct DevelopmentCredentials {
user_id: u64,

View File

@@ -1 +0,0 @@

View File

@@ -18,4 +18,5 @@ test-support = ["dep:parking_lot"]
[dependencies]
chrono.workspace = true
parking_lot = { workspace = true, optional = true }
serde.workspace = true
smallvec.workspace = true

View File

@@ -1,5 +1,6 @@
mod system_clock;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use std::{
cmp::{self, Ordering},
@@ -16,7 +17,7 @@ pub type Seq = u32;
/// A [Lamport timestamp](https://en.wikipedia.org/wiki/Lamport_timestamp),
/// used to determine the ordering of events in the editor.
#[derive(Clone, Copy, Default, Eq, Hash, PartialEq)]
#[derive(Clone, Copy, Default, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct Lamport {
pub replica_id: ReplicaId,
pub value: Seq,
@@ -161,6 +162,10 @@ impl Lamport {
}
}
pub fn as_u64(self) -> u64 {
((self.value as u64) << 32) | (self.replica_id as u64)
}
pub fn tick(&mut self) -> Self {
let timestamp = *self;
self.value += 1;

View File

@@ -30,6 +30,7 @@ chrono.workspace = true
clock.workspace = true
clickhouse.workspace = true
collections.workspace = true
completion.workspace = true
dashmap = "5.4"
envy = "0.4.2"
futures.workspace = true
@@ -71,6 +72,7 @@ util.workspace = true
uuid.workspace = true
[dev-dependencies]
assistant = { workspace = true, features = ["test-support"] }
async-trait.workspace = true
audio.workspace = true
call = { workspace = true, features = ["test-support"] }
@@ -78,6 +80,7 @@ channel.workspace = true
client = { workspace = true, features = ["test-support"] }
collab_ui = { workspace = true, features = ["test-support"] }
collections = { workspace = true, features = ["test-support"] }
completion = { workspace = true, features = ["test-support"] }
ctor.workspace = true
editor = { workspace = true, features = ["test-support"] }
env_logger.workspace = true
@@ -98,6 +101,8 @@ pretty_assertions.workspace = true
project = { workspace = true, features = ["test-support"] }
recent_projects = { workspace = true }
release_channel.workspace = true
remote = { workspace = true, features = ["test-support"] }
remote_server.workspace = true
dev_server_projects.workspace = true
rpc = { workspace = true, features = ["test-support"] }
sea-orm = { version = "0.12.x", features = ["sqlx-sqlite"] }

View File

@@ -414,5 +414,5 @@ CREATE TABLE dev_servers (
CREATE TABLE dev_server_projects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
dev_server_id INTEGER NOT NULL REFERENCES dev_servers(id),
path TEXT NOT NULL
paths TEXT NOT NULL
);

View File

@@ -0,0 +1,4 @@
ALTER TABLE dev_server_projects ADD COLUMN paths JSONB NULL;
UPDATE dev_server_projects SET paths = to_json(ARRAY[path]);
ALTER TABLE dev_server_projects ALTER COLUMN paths SET NOT NULL;
ALTER TABLE dev_server_projects ALTER COLUMN path DROP NOT NULL;

View File

@@ -43,11 +43,36 @@ async fn get_extensions(
Extension(app): Extension<Arc<AppState>>,
Query(params): Query<GetExtensionsParams>,
) -> Result<Json<GetExtensionsResponse>> {
let extensions = app
let mut extensions = app
.db
.get_extensions(params.filter.as_deref(), params.max_schema_version, 500)
.await?;
if let Some(filter) = params.filter.as_deref() {
let extension_id = filter.to_lowercase();
let mut exact_match = None;
extensions.retain(|extension| {
if extension.id.as_ref() == &extension_id {
exact_match = Some(extension.clone());
false
} else {
true
}
});
if exact_match.is_none() {
exact_match = app
.db
.get_extensions_by_ids(&[&extension_id], None)
.await?
.first()
.cloned();
}
if let Some(exact_match) = exact_match {
extensions.insert(0, exact_match);
}
};
if let Some(query) = params.filter.as_deref() {
let count = extensions.len();
tracing::info!(query, count, "extension_search")

View File

@@ -5,7 +5,7 @@ use rpc::{
};
use sea_orm::{
ActiveModelTrait, ActiveValue, ColumnTrait, Condition, DatabaseTransaction, EntityTrait,
ModelTrait, QueryFilter,
IntoActiveModel, ModelTrait, QueryFilter,
};
use crate::db::ProjectId;
@@ -56,12 +56,7 @@ impl Database {
.await?;
Ok(servers
.into_iter()
.map(|(dev_server_project, project)| proto::DevServerProject {
id: dev_server_project.id.to_proto(),
project_id: project.map(|p| p.id.to_proto()),
dev_server_id: dev_server_project.dev_server_id.to_proto(),
path: dev_server_project.path,
})
.map(|(dev_server_project, project)| dev_server_project.to_proto(project))
.collect())
}
@@ -134,7 +129,7 @@ impl Database {
let project = dev_server_project::Entity::insert(dev_server_project::ActiveModel {
id: ActiveValue::NotSet,
dev_server_id: ActiveValue::Set(dev_server_id),
path: ActiveValue::Set(path.to_string()),
paths: ActiveValue::Set(dev_server_project::JSONPaths(vec![path.to_string()])),
})
.exec_with_returning(&*tx)
.await?;
@@ -148,6 +143,38 @@ impl Database {
.await
}
pub async fn update_dev_server_project(
&self,
id: DevServerProjectId,
paths: &Vec<String>,
user_id: UserId,
) -> crate::Result<(dev_server_project::Model, proto::DevServerProjectsUpdate)> {
self.transaction(move |tx| async move {
let paths = paths.clone();
let Some((project, Some(dev_server))) = dev_server_project::Entity::find_by_id(id)
.find_also_related(dev_server::Entity)
.one(&*tx)
.await?
else {
return Err(anyhow!("no such dev server project"))?;
};
if dev_server.user_id != user_id {
return Err(anyhow!("not your dev server"))?;
}
let mut project = project.into_active_model();
project.paths = ActiveValue::Set(dev_server_project::JSONPaths(paths));
let project = project.update(&*tx).await?;
let status = self
.dev_server_projects_update_internal(user_id, &tx)
.await?;
Ok((project, status))
})
.await
}
pub async fn delete_dev_server_project(
&self,
dev_server_project_id: DevServerProjectId,
@@ -258,7 +285,6 @@ impl Database {
dev_server_id: DevServerId,
connection: ConnectionId,
) -> crate::Result<Vec<ResharedProject>> {
// todo!() project_transaction? (maybe we can make the lock per-dev-server instead of per-project?)
self.transaction(|tx| async move {
let mut ret = Vec::new();
for reshared_project in reshared_projects {
@@ -322,7 +348,6 @@ impl Database {
user_id: UserId,
connection_id: ConnectionId,
) -> crate::Result<Vec<RejoinedProject>> {
// todo!() project_transaction? (maybe we can make the lock per-dev-server instead of per-project?)
self.transaction(|tx| async move {
let mut ret = Vec::new();
for rejoined_project in rejoined_projects {

View File

@@ -19,6 +19,28 @@ impl Database {
.await
}
pub async fn get_dev_server_for_user(
&self,
dev_server_id: DevServerId,
user_id: UserId,
) -> crate::Result<dev_server::Model> {
self.transaction(|tx| async move {
let server = dev_server::Entity::find_by_id(dev_server_id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow::anyhow!("no dev server with id {}", dev_server_id))?;
if server.user_id != user_id {
return Err(anyhow::anyhow!(
"dev server {} is not owned by user {}",
dev_server_id,
user_id
))?;
}
Ok(server)
})
.await
}
pub async fn get_dev_servers(&self, user_id: UserId) -> crate::Result<Vec<dev_server::Model>> {
self.transaction(|tx| async move {
Ok(dev_server::Entity::find()

View File

@@ -1,7 +1,8 @@
use super::project;
use crate::db::{DevServerId, DevServerProjectId};
use rpc::proto;
use sea_orm::entity::prelude::*;
use sea_orm::{entity::prelude::*, FromJsonQueryResult};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "dev_server_projects")]
@@ -9,9 +10,12 @@ pub struct Model {
#[sea_orm(primary_key)]
pub id: DevServerProjectId,
pub dev_server_id: DevServerId,
pub path: String,
pub paths: JSONPaths,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, FromJsonQueryResult)]
pub struct JSONPaths(pub Vec<String>);
impl ActiveModelBehavior for ActiveModel {}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
@@ -44,7 +48,12 @@ impl Model {
id: self.id.to_proto(),
project_id: project.map(|p| p.id.to_proto()),
dev_server_id: self.dev_server_id.to_proto(),
path: self.path.clone(),
path: self.paths().get(0).cloned().unwrap_or_default(),
paths: self.paths().clone(),
}
}
pub fn paths(&self) -> &Vec<String> {
&self.paths.0
}
}

View File

@@ -562,7 +562,7 @@ fn test_fuzzy_like_string() {
assert_eq!(Database::fuzzy_like_string(" z "), "%z%");
}
#[cfg(target = "macos")]
#[cfg(target_os = "macos")]
#[gpui::test]
async fn test_fuzzy_search_users(cx: &mut gpui::TestAppContext) {
let test_db = tests::TestDb::postgres(cx.executor());

View File

@@ -431,11 +431,13 @@ impl Server {
.add_request_handler(user_handler(join_hosted_project))
.add_request_handler(user_handler(rejoin_dev_server_projects))
.add_request_handler(user_handler(create_dev_server_project))
.add_request_handler(user_handler(update_dev_server_project))
.add_request_handler(user_handler(delete_dev_server_project))
.add_request_handler(user_handler(create_dev_server))
.add_request_handler(user_handler(regenerate_dev_server_token))
.add_request_handler(user_handler(rename_dev_server))
.add_request_handler(user_handler(delete_dev_server))
.add_request_handler(user_handler(list_remote_directory))
.add_request_handler(dev_server_handler(share_dev_server_project))
.add_request_handler(dev_server_handler(shutdown_dev_server))
.add_request_handler(dev_server_handler(reconnect_dev_server))
@@ -595,6 +597,14 @@ impl Server {
.add_message_handler(user_message_handler(acknowledge_channel_message))
.add_message_handler(user_message_handler(acknowledge_buffer_version))
.add_request_handler(user_handler(get_supermaven_api_key))
.add_request_handler(user_handler(
forward_mutating_project_request::<proto::OpenContext>,
))
.add_request_handler(user_handler(
forward_mutating_project_request::<proto::SynchronizeContexts>,
))
.add_message_handler(broadcast_project_message_from_host::<proto::AdvertiseContexts>)
.add_message_handler(update_context)
.add_streaming_request_handler({
let app_state = app_state.clone();
move |request, response, session| {
@@ -2305,6 +2315,69 @@ async fn join_hosted_project(
join_project_internal(response, session, &mut project, &replica_id)
}
async fn list_remote_directory(
request: proto::ListRemoteDirectory,
response: Response<proto::ListRemoteDirectory>,
session: UserSession,
) -> Result<()> {
let dev_server_id = DevServerId(request.dev_server_id as i32);
let dev_server_connection_id = session
.connection_pool()
.await
.dev_server_connection_id_supporting(dev_server_id, ZedVersion::with_list_directory())?;
session
.db()
.await
.get_dev_server_for_user(dev_server_id, session.user_id())
.await?;
response.send(
session
.peer
.forward_request(session.connection_id, dev_server_connection_id, request)
.await?,
)?;
Ok(())
}
async fn update_dev_server_project(
request: proto::UpdateDevServerProject,
response: Response<proto::UpdateDevServerProject>,
session: UserSession,
) -> Result<()> {
let dev_server_project_id = DevServerProjectId(request.dev_server_project_id as i32);
let (dev_server_project, update) = session
.db()
.await
.update_dev_server_project(dev_server_project_id, &request.paths, session.user_id())
.await?;
let projects = session
.db()
.await
.get_projects_for_dev_server(dev_server_project.dev_server_id)
.await?;
let dev_server_connection_id = session
.connection_pool()
.await
.dev_server_connection_id_supporting(
dev_server_project.dev_server_id,
ZedVersion::with_list_directory(),
)?;
session.peer.send(
dev_server_connection_id,
proto::DevServerInstructions { projects },
)?;
send_dev_server_projects_update(session.user_id(), update, &session).await;
response.send(proto::Ack {})
}
async fn create_dev_server_project(
request: proto::CreateDevServerProject,
response: Response<proto::CreateDevServerProject>,
@@ -3056,6 +3129,53 @@ async fn update_buffer(
Ok(())
}
async fn update_context(message: proto::UpdateContext, session: Session) -> Result<()> {
let project_id = ProjectId::from_proto(message.project_id);
let operation = message.operation.as_ref().context("invalid operation")?;
let capability = match operation.variant.as_ref() {
Some(proto::context_operation::Variant::BufferOperation(buffer_op)) => {
if let Some(buffer_op) = buffer_op.operation.as_ref() {
match buffer_op.variant {
None | Some(proto::operation::Variant::UpdateSelections(_)) => {
Capability::ReadOnly
}
_ => Capability::ReadWrite,
}
} else {
Capability::ReadWrite
}
}
Some(_) => Capability::ReadWrite,
None => Capability::ReadOnly,
};
let guard = session
.db()
.await
.connections_for_buffer_update(
project_id,
session.principal_id(),
session.connection_id,
capability,
)
.await?;
let (host, guests) = &*guard;
broadcast(
Some(session.connection_id),
guests.iter().chain([host]).copied(),
|connection_id| {
session
.peer
.forward_send(session.connection_id, connection_id, message.clone())
},
);
Ok(())
}
/// Notify other participants that a project has been updated.
async fn broadcast_project_message_from_host<T: EntityMessage<Entity = ShareProject>>(
request: T,
@@ -4394,7 +4514,7 @@ impl RateLimit for CompleteWithLanguageModelRateLimit {
}
async fn complete_with_language_model(
request: proto::CompleteWithLanguageModel,
mut request: proto::CompleteWithLanguageModel,
response: StreamingResponse<proto::CompleteWithLanguageModel>,
session: Session,
open_ai_api_key: Option<Arc<str>>,
@@ -4410,18 +4530,43 @@ async fn complete_with_language_model(
.check::<CompleteWithLanguageModelRateLimit>(session.user_id())
.await?;
if request.model.starts_with("gpt") {
let api_key =
open_ai_api_key.ok_or_else(|| anyhow!("no OpenAI API key configured on the server"))?;
complete_with_open_ai(request, response, session, api_key).await?;
} else if request.model.starts_with("gemini") {
let api_key = google_ai_api_key
.ok_or_else(|| anyhow!("no Google AI API key configured on the server"))?;
complete_with_google_ai(request, response, session, api_key).await?;
} else if request.model.starts_with("claude") {
let api_key = anthropic_api_key
.ok_or_else(|| anyhow!("no Anthropic AI API key configured on the server"))?;
complete_with_anthropic(request, response, session, api_key).await?;
let mut provider_and_model = request.model.split('/');
let (provider, model) = match (
provider_and_model.next().unwrap(),
provider_and_model.next(),
) {
(provider, Some(model)) => (provider, model),
(model, None) => {
if model.starts_with("gpt") {
("openai", model)
} else if model.starts_with("gemini") {
("google", model)
} else if model.starts_with("claude") {
("anthropic", model)
} else {
("unknown", model)
}
}
};
let provider = provider.to_string();
request.model = model.to_string();
match provider.as_str() {
"openai" => {
let api_key = open_ai_api_key.context("no OpenAI API key configured on the server")?;
complete_with_open_ai(request, response, session, api_key).await?;
}
"anthropic" => {
let api_key =
anthropic_api_key.context("no Anthropic AI API key configured on the server")?;
complete_with_anthropic(request, response, session, api_key).await?;
}
"google" => {
let api_key =
google_ai_api_key.context("no Google AI API key configured on the server")?;
complete_with_google_ai(request, response, session, api_key).await?;
}
provider => return Err(anyhow!("unknown provider {:?}", provider))?,
}
Ok(())

View File

@@ -38,6 +38,10 @@ impl ZedVersion {
pub fn with_save_as() -> ZedVersion {
ZedVersion(SemanticVersion::new(0, 134, 0))
}
pub fn with_list_directory() -> ZedVersion {
ZedVersion(SemanticVersion::new(0, 145, 0))
}
}
pub trait VersionedMessage {
@@ -187,6 +191,18 @@ impl ConnectionPool {
self.connected_dev_servers.get(&dev_server_id).copied()
}
pub fn dev_server_connection_id_supporting(
&self,
dev_server_id: DevServerId,
required: ZedVersion,
) -> Result<ConnectionId> {
match self.connected_dev_servers.get(&dev_server_id) {
Some(cid) if self.connections[cid].zed_version >= required => Ok(*cid),
Some(_) => Err(anyhow!(proto::ErrorCode::RemoteUpgradeRequired)),
None => Err(anyhow!(proto::ErrorCode::DevServerOffline)),
}
}
pub fn channel_user_ids(
&self,
channel_id: ChannelId,

View File

@@ -16,6 +16,7 @@ mod notification_tests;
mod random_channel_buffer_tests;
mod random_project_collaboration_tests;
mod randomized_test_helpers;
mod remote_editing_collaboration_tests;
mod test_server;
use language::{tree_sitter_rust, Language, LanguageConfig, LanguageMatcher};

View File

@@ -66,7 +66,7 @@ async fn test_dev_server(cx: &mut gpui::TestAppContext, cx2: &mut gpui::TestAppC
.update(cx, |store, cx| {
let projects = store.dev_server_projects();
assert_eq!(projects.len(), 1);
assert_eq!(projects[0].path, "/remote");
assert_eq!(projects[0].paths, vec!["/remote"]);
workspace::join_dev_server_project(
projects[0].id,
projects[0].project_id.unwrap(),
@@ -206,7 +206,7 @@ async fn create_dev_server_project(
.update(cx, |store, cx| {
let projects = store.dev_server_projects();
assert_eq!(projects.len(), 1);
assert_eq!(projects[0].path, "/remote");
assert_eq!(projects[0].paths, vec!["/remote"]);
workspace::join_dev_server_project(
projects[0].id,
projects[0].project_id.unwrap(),

View File

@@ -135,7 +135,7 @@ async fn test_basic_following(
assert_eq!(editor.selections.ranges(cx), vec![2..1]);
});
// When client B starts following client A, all visible view states are replicated to client B.
// When client B starts following client A, only the active view state is replicated to client B.
workspace_b.update(cx_b, |workspace, cx| workspace.follow(peer_id_a, cx));
cx_c.executor().run_until_parked();
@@ -156,7 +156,7 @@ async fn test_basic_following(
);
assert_eq!(
editor_b1.update(cx_b, |editor, cx| editor.selections.ranges(cx)),
vec![3..2]
vec![3..3]
);
executor.run_until_parked();
@@ -194,7 +194,7 @@ async fn test_basic_following(
// Client C unfollows client A.
workspace_c.update(cx_c, |workspace, cx| {
workspace.unfollow(&workspace.active_pane().clone(), cx);
workspace.unfollow(peer_id_a, cx).unwrap();
});
// All clients see that clients B is following client A.
@@ -266,7 +266,7 @@ async fn test_basic_following(
// When client A activates a different editor, client B does so as well.
workspace_a.update(cx_a, |workspace, cx| {
workspace.activate_item(&editor_a1, cx)
workspace.activate_item(&editor_a1, true, true, cx)
});
executor.run_until_parked();
workspace_b.update(cx_b, |workspace, cx| {
@@ -311,7 +311,7 @@ async fn test_basic_following(
let editor = cx.new_view(|cx| {
Editor::for_multibuffer(multibuffer_a, Some(project_a.clone()), true, cx)
});
workspace.add_item_to_active_pane(Box::new(editor.clone()), None, cx);
workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
editor
});
executor.run_until_parked();
@@ -398,10 +398,10 @@ async fn test_basic_following(
// After unfollowing, client B stops receiving updates from client A.
workspace_b.update(cx_b, |workspace, cx| {
workspace.unfollow(&workspace.active_pane().clone(), cx)
workspace.unfollow(peer_id_a, cx).unwrap()
});
workspace_a.update(cx_a, |workspace, cx| {
workspace.activate_item(&editor_a2, cx)
workspace.activate_item(&editor_a2, true, true, cx)
});
executor.run_until_parked();
assert_eq!(
@@ -466,7 +466,7 @@ async fn test_basic_following(
// Client B activates a multibuffer that was created by following client A. Client A returns to that multibuffer.
workspace_b.update(cx_b, |workspace, cx| {
workspace.activate_item(&multibuffer_editor_b, cx)
workspace.activate_item(&multibuffer_editor_b, true, true, cx)
});
executor.run_until_parked();
workspace_a.update(cx_a, |workspace, cx| {

View File

@@ -6,6 +6,7 @@ use crate::{
},
};
use anyhow::{anyhow, Result};
use assistant::ContextStore;
use call::{room, ActiveCall, ParticipantLocation, Room};
use client::{User, RECEIVE_TIMEOUT};
use collections::{HashMap, HashSet};
@@ -1527,7 +1528,7 @@ async fn test_project_reconnect(
});
let (worktree_a2, _) = project_a1
.update(cx_a, |p, cx| {
p.find_or_create_local_worktree("/root-1/dir2", true, cx)
p.find_or_create_worktree("/root-1/dir2", true, cx)
})
.await
.unwrap();
@@ -1600,7 +1601,7 @@ async fn test_project_reconnect(
});
let (worktree_a3, _) = project_a1
.update(cx_a, |p, cx| {
p.find_or_create_local_worktree("/root-1/dir3", true, cx)
p.find_or_create_worktree("/root-1/dir3", true, cx)
})
.await
.unwrap();
@@ -1724,7 +1725,7 @@ async fn test_project_reconnect(
// While client B is disconnected, add and remove worktrees from client A's project.
let (worktree_a4, _) = project_a1
.update(cx_a, |p, cx| {
p.find_or_create_local_worktree("/root-1/dir4", true, cx)
p.find_or_create_worktree("/root-1/dir4", true, cx)
})
.await
.unwrap();
@@ -3326,7 +3327,7 @@ async fn test_local_settings(
let store = cx.global::<SettingsStore>();
assert_eq!(
store
.local_settings(worktree_b.read(cx).id().to_usize())
.local_settings(worktree_b.entity_id().as_u64() as _)
.collect::<Vec<_>>(),
&[
(Path::new("").into(), r#"{"tab_size":2}"#.to_string()),
@@ -3345,7 +3346,7 @@ async fn test_local_settings(
let store = cx.global::<SettingsStore>();
assert_eq!(
store
.local_settings(worktree_b.read(cx).id().to_usize())
.local_settings(worktree_b.entity_id().as_u64() as _)
.collect::<Vec<_>>(),
&[
(Path::new("").into(), r#"{}"#.to_string()),
@@ -3374,7 +3375,7 @@ async fn test_local_settings(
let store = cx.global::<SettingsStore>();
assert_eq!(
store
.local_settings(worktree_b.read(cx).id().to_usize())
.local_settings(worktree_b.entity_id().as_u64() as _)
.collect::<Vec<_>>(),
&[
(Path::new("a").into(), r#"{"tab_size":8}"#.to_string()),
@@ -3406,7 +3407,7 @@ async fn test_local_settings(
let store = cx.global::<SettingsStore>();
assert_eq!(
store
.local_settings(worktree_b.read(cx).id().to_usize())
.local_settings(worktree_b.entity_id().as_u64() as _)
.collect::<Vec<_>>(),
&[(Path::new("a").into(), r#"{"hard_tabs":true}"#.to_string()),]
)
@@ -4886,7 +4887,7 @@ async fn test_project_search(
let (project_a, _) = client_a.build_local_project("/root/dir-1", cx_a).await;
let (worktree_2, _) = project_a
.update(cx_a, |p, cx| {
p.find_or_create_local_worktree("/root/dir-2", true, cx)
p.find_or_create_worktree("/root/dir-2", true, cx)
})
.await
.unwrap();
@@ -6449,3 +6450,123 @@ async fn test_preview_tabs(cx: &mut TestAppContext) {
assert!(!pane.can_navigate_forward());
});
}
#[gpui::test(iterations = 10)]
async fn test_context_collaboration_with_reconnect(
executor: BackgroundExecutor,
cx_a: &mut TestAppContext,
cx_b: &mut TestAppContext,
) {
let mut server = TestServer::start(executor.clone()).await;
let client_a = server.create_client(cx_a, "user_a").await;
let client_b = server.create_client(cx_b, "user_b").await;
server
.create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
.await;
let active_call_a = cx_a.read(ActiveCall::global);
client_a.fs().insert_tree("/a", Default::default()).await;
let (project_a, _) = client_a.build_local_project("/a", cx_a).await;
let project_id = active_call_a
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
// Client A sees that a guest has joined.
executor.run_until_parked();
project_a.read_with(cx_a, |project, _| {
assert_eq!(project.collaborators().len(), 1);
});
project_b.read_with(cx_b, |project, _| {
assert_eq!(project.collaborators().len(), 1);
});
let context_store_a = cx_a
.update(|cx| ContextStore::new(project_a.clone(), cx))
.await
.unwrap();
let context_store_b = cx_b
.update(|cx| ContextStore::new(project_b.clone(), cx))
.await
.unwrap();
// Client A creates a new context.
let context_a = context_store_a.update(cx_a, |store, cx| store.create(cx));
executor.run_until_parked();
// Client B retrieves host's contexts and joins one.
let context_b = context_store_b
.update(cx_b, |store, cx| {
let host_contexts = store.host_contexts().to_vec();
assert_eq!(host_contexts.len(), 1);
store.open_remote_context(host_contexts[0].id.clone(), cx)
})
.await
.unwrap();
// Host and guest make changes
context_a.update(cx_a, |context, cx| {
context.buffer().update(cx, |buffer, cx| {
buffer.edit([(0..0, "Host change\n")], None, cx)
})
});
context_b.update(cx_b, |context, cx| {
context.buffer().update(cx, |buffer, cx| {
buffer.edit([(0..0, "Guest change\n")], None, cx)
})
});
executor.run_until_parked();
assert_eq!(
context_a.read_with(cx_a, |context, cx| context.buffer().read(cx).text()),
"Guest change\nHost change\n"
);
assert_eq!(
context_b.read_with(cx_b, |context, cx| context.buffer().read(cx).text()),
"Guest change\nHost change\n"
);
// Disconnect client A and make some changes while disconnected.
server.disconnect_client(client_a.peer_id().unwrap());
server.forbid_connections();
context_a.update(cx_a, |context, cx| {
context.buffer().update(cx, |buffer, cx| {
buffer.edit([(0..0, "Host offline change\n")], None, cx)
})
});
context_b.update(cx_b, |context, cx| {
context.buffer().update(cx, |buffer, cx| {
buffer.edit([(0..0, "Guest offline change\n")], None, cx)
})
});
executor.run_until_parked();
assert_eq!(
context_a.read_with(cx_a, |context, cx| context.buffer().read(cx).text()),
"Host offline change\nGuest change\nHost change\n"
);
assert_eq!(
context_b.read_with(cx_b, |context, cx| context.buffer().read(cx).text()),
"Guest offline change\nGuest change\nHost change\n"
);
// Allow client A to reconnect and verify that contexts converge.
server.allow_connections();
executor.advance_clock(RECEIVE_TIMEOUT);
assert_eq!(
context_a.read_with(cx_a, |context, cx| context.buffer().read(cx).text()),
"Guest offline change\nHost offline change\nGuest change\nHost change\n"
);
assert_eq!(
context_b.read_with(cx_b, |context, cx| context.buffer().read(cx).text()),
"Guest offline change\nHost offline change\nGuest change\nHost change\n"
);
// Client A disconnects without being able to reconnect. Context B becomes readonly.
server.forbid_connections();
server.disconnect_client(client_a.peer_id().unwrap());
executor.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
context_b.read_with(cx_b, |context, cx| {
assert!(context.buffer().read(cx).read_only());
});
}

View File

@@ -581,7 +581,7 @@ impl RandomizedTest for ProjectCollaborationTest {
}
project
.update(cx, |project, cx| {
project.find_or_create_local_worktree(&new_root_path, true, cx)
project.find_or_create_worktree(&new_root_path, true, cx)
})
.await
.unwrap();
@@ -1237,7 +1237,7 @@ impl RandomizedTest for ProjectCollaborationTest {
}
}
for buffer in guest_project.opened_buffers() {
for buffer in guest_project.opened_buffers(cx) {
let buffer = buffer.read(cx);
assert_eq!(
buffer.deferred_ops_len(),
@@ -1287,8 +1287,8 @@ impl RandomizedTest for ProjectCollaborationTest {
for guest_buffer in guest_buffers {
let buffer_id =
guest_buffer.read_with(client_cx, |buffer, _| buffer.remote_id());
let host_buffer = host_project.read_with(host_cx, |project, _| {
project.buffer_for_id(buffer_id).unwrap_or_else(|| {
let host_buffer = host_project.read_with(host_cx, |project, cx| {
project.buffer_for_id(buffer_id, cx).unwrap_or_else(|| {
panic!(
"host does not have buffer for guest:{}, peer:{:?}, id:{}",
client.username,

View File

@@ -0,0 +1,102 @@
use crate::tests::TestServer;
use call::ActiveCall;
use fs::{FakeFs, Fs as _};
use gpui::{Context as _, TestAppContext};
use remote::SshSession;
use remote_server::HeadlessProject;
use serde_json::json;
use std::{path::Path, sync::Arc};
#[gpui::test]
async fn test_sharing_an_ssh_remote_project(
cx_a: &mut TestAppContext,
cx_b: &mut TestAppContext,
server_cx: &mut TestAppContext,
) {
let executor = cx_a.executor();
let mut server = TestServer::start(executor.clone()).await;
let client_a = server.create_client(cx_a, "user_a").await;
let client_b = server.create_client(cx_b, "user_b").await;
server
.create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
.await;
// Set up project on remote FS
let (client_ssh, server_ssh) = SshSession::fake(cx_a, server_cx);
let remote_fs = FakeFs::new(server_cx.executor());
remote_fs
.insert_tree(
"/code",
json!({
"project1": {
"README.md": "# project 1",
"src": {
"lib.rs": "fn one() -> usize { 1 }"
}
},
"project2": {
"README.md": "# project 2",
},
}),
)
.await;
// User A connects to the remote project via SSH.
server_cx.update(HeadlessProject::init);
let _headless_project =
server_cx.new_model(|cx| HeadlessProject::new(server_ssh, remote_fs.clone(), cx));
let (project_a, worktree_id) = client_a
.build_ssh_project("/code/project1", client_ssh, cx_a)
.await;
// User A shares the remote project.
let active_call_a = cx_a.read(ActiveCall::global);
let project_id = active_call_a
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
// User B joins the project.
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let worktree_b = project_b
.update(cx_b, |project, cx| project.worktree_for_id(worktree_id, cx))
.unwrap();
executor.run_until_parked();
worktree_b.update(cx_b, |worktree, _cx| {
assert_eq!(
worktree.paths().map(Arc::as_ref).collect::<Vec<_>>(),
vec![
Path::new("README.md"),
Path::new("src"),
Path::new("src/lib.rs"),
]
);
});
// User B can open buffers in the remote project.
let buffer_b = project_b
.update(cx_b, |project, cx| {
project.open_buffer((worktree_id, "src/lib.rs"), cx)
})
.await
.unwrap();
buffer_b.update(cx_b, |buffer, cx| {
assert_eq!(buffer.text(), "fn one() -> usize { 1 }");
let ix = buffer.text().find('1').unwrap();
buffer.edit([(ix..ix + 1, "100")], None, cx);
});
project_b
.update(cx_b, |project, cx| project.save_buffer(buffer_b, cx))
.await
.unwrap();
assert_eq!(
remote_fs
.load("/code/project1/src/lib.rs".as_ref())
.await
.unwrap(),
"fn one() -> usize { 100 }"
);
}

View File

@@ -25,6 +25,7 @@ use node_runtime::FakeNodeRuntime;
use notifications::NotificationStore;
use parking_lot::Mutex;
use project::{Project, WorktreeId};
use remote::SshSession;
use rpc::{
proto::{self, ChannelRole},
RECEIVE_TIMEOUT,
@@ -294,6 +295,8 @@ impl TestServer {
menu::init();
dev_server_projects::init(client.clone(), cx);
settings::KeymapFile::load_asset(os_keymap, cx).unwrap();
completion::FakeCompletionProvider::setup_test(cx);
assistant::context_store::init(&client);
});
client
@@ -803,9 +806,7 @@ impl TestClient {
) -> (Model<Project>, WorktreeId) {
let project = self.build_empty_local_project(cx);
let (worktree, _) = project
.update(cx, |p, cx| {
p.find_or_create_local_worktree(root_path, true, cx)
})
.update(cx, |p, cx| p.find_or_create_worktree(root_path, true, cx))
.await
.unwrap();
worktree
@@ -814,6 +815,30 @@ impl TestClient {
(project, worktree.read_with(cx, |tree, _| tree.id()))
}
pub async fn build_ssh_project(
&self,
root_path: impl AsRef<Path>,
ssh: Arc<SshSession>,
cx: &mut TestAppContext,
) -> (Model<Project>, WorktreeId) {
let project = cx.update(|cx| {
Project::ssh(
ssh,
self.client().clone(),
self.app_state.node_runtime.clone(),
self.app_state.user_store.clone(),
self.app_state.languages.clone(),
self.app_state.fs.clone(),
cx,
)
});
let (worktree, _) = project
.update(cx, |p, cx| p.find_or_create_worktree(root_path, true, cx))
.await
.unwrap();
(project, worktree.read_with(cx, |tree, _| tree.id()))
}
pub async fn build_test_project(&self, cx: &mut TestAppContext) -> Model<Project> {
self.fs()
.insert_tree(

View File

@@ -32,6 +32,7 @@ test-support = [
anyhow.workspace = true
call.workspace = true
channel.workspace = true
chrono.workspace = true
client.workspace = true
collections.workspace = true
db.workspace = true

View File

@@ -11,21 +11,22 @@ use editor::{
EditorEvent,
};
use gpui::{
actions, AnyElement, AnyView, AppContext, ClipboardItem, Entity as _, EventEmitter,
FocusableView, IntoElement as _, Model, Pixels, Point, Render, Subscription, Task, View,
ViewContext, VisualContext as _, WeakView, WindowContext,
actions, AnyView, AppContext, ClipboardItem, Entity as _, EventEmitter, FocusableView, Model,
Pixels, Point, Render, Subscription, Task, View, ViewContext, VisualContext as _, WeakView,
WindowContext,
};
use project::Project;
use rpc::proto::ChannelVisibility;
use std::{
any::{Any, TypeId},
sync::Arc,
};
use ui::{prelude::*, Label};
use ui::prelude::*;
use util::ResultExt;
use workspace::notifications::NotificationId;
use workspace::item::TabContentParams;
use workspace::{item::Dedup, notifications::NotificationId};
use workspace::{
item::{FollowableItem, Item, ItemEvent, ItemHandle, TabContentParams},
register_followable_item,
item::{FollowableItem, Item, ItemEvent, ItemHandle},
searchable::SearchableItemHandle,
ItemNavHistory, Pane, SaveIntent, Toast, ViewId, Workspace, WorkspaceId,
};
@@ -33,7 +34,7 @@ use workspace::{
actions!(collab, [CopyLink]);
pub fn init(cx: &mut AppContext) {
register_followable_item::<ChannelView>(cx)
workspace::FollowableViewRegistry::register::<ChannelView>(cx)
}
pub struct ChannelView {
@@ -83,6 +84,56 @@ impl ChannelView {
pane: View<Pane>,
workspace: View<Workspace>,
cx: &mut WindowContext,
) -> Task<Result<View<Self>>> {
let channel_view = Self::load(channel_id, workspace, cx);
cx.spawn(|mut cx| async move {
let channel_view = channel_view.await?;
pane.update(&mut cx, |pane, cx| {
let buffer_id = channel_view.read(cx).channel_buffer.read(cx).remote_id(cx);
let existing_view = pane
.items_of_type::<Self>()
.find(|view| view.read(cx).channel_buffer.read(cx).remote_id(cx) == buffer_id);
// If this channel buffer is already open in this pane, just return it.
if let Some(existing_view) = existing_view.clone() {
if existing_view.read(cx).channel_buffer == channel_view.read(cx).channel_buffer
{
if let Some(link_position) = link_position {
existing_view.update(cx, |channel_view, cx| {
channel_view.focus_position_from_link(link_position, true, cx)
});
}
return existing_view;
}
}
// If the pane contained a disconnected view for this channel buffer,
// replace that.
if let Some(existing_item) = existing_view {
if let Some(ix) = pane.index_for_item(&existing_item) {
pane.close_item_by_id(existing_item.entity_id(), SaveIntent::Skip, cx)
.detach();
pane.add_item(Box::new(channel_view.clone()), true, true, Some(ix), cx);
}
}
if let Some(link_position) = link_position {
channel_view.update(cx, |channel_view, cx| {
channel_view.focus_position_from_link(link_position, true, cx)
});
}
channel_view
})
})
}
pub fn load(
channel_id: ChannelId,
workspace: View<Workspace>,
cx: &mut WindowContext,
) -> Task<Result<View<Self>>> {
let weak_workspace = workspace.downgrade();
let workspace = workspace.read(cx);
@@ -107,49 +158,11 @@ impl ChannelView {
})
})?;
pane.update(&mut cx, |pane, cx| {
let buffer_id = channel_buffer.read(cx).remote_id(cx);
let existing_view = pane
.items_of_type::<Self>()
.find(|view| view.read(cx).channel_buffer.read(cx).remote_id(cx) == buffer_id);
// If this channel buffer is already open in this pane, just return it.
if let Some(existing_view) = existing_view.clone() {
if existing_view.read(cx).channel_buffer == channel_buffer {
if let Some(link_position) = link_position {
existing_view.update(cx, |channel_view, cx| {
channel_view.focus_position_from_link(link_position, true, cx)
});
}
return existing_view;
}
}
let view = cx.new_view(|cx| {
let mut this =
Self::new(project, weak_workspace, channel_store, channel_buffer, cx);
this.acknowledge_buffer_version(cx);
this
});
// If the pane contained a disconnected view for this channel buffer,
// replace that.
if let Some(existing_item) = existing_view {
if let Some(ix) = pane.index_for_item(&existing_item) {
pane.close_item_by_id(existing_item.entity_id(), SaveIntent::Skip, cx)
.detach();
pane.add_item(Box::new(view.clone()), true, true, Some(ix), cx);
}
}
if let Some(link_position) = link_position {
view.update(cx, |channel_view, cx| {
channel_view.focus_position_from_link(link_position, true, cx)
});
}
view
cx.new_view(|cx| {
let mut this =
Self::new(project, weak_workspace, channel_store, channel_buffer, cx);
this.acknowledge_buffer_version(cx);
this
})
})
}
@@ -374,24 +387,45 @@ impl Item for ChannelView {
}
}
fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
let label = if let Some(channel) = self.channel(cx) {
match (
fn tab_icon(&self, cx: &WindowContext) -> Option<Icon> {
let channel = self.channel(cx)?;
let icon = match channel.visibility {
ChannelVisibility::Public => IconName::Public,
ChannelVisibility::Members => IconName::Hash,
};
Some(Icon::new(icon))
}
fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> gpui::AnyElement {
let (channel_name, status) = if let Some(channel) = self.channel(cx) {
let status = match (
self.channel_buffer.read(cx).buffer().read(cx).read_only(),
self.channel_buffer.read(cx).is_connected(),
) {
(false, true) => format!("#{}", channel.name),
(true, true) => format!("#{} (read-only)", channel.name),
(_, false) => format!("#{} (disconnected)", channel.name),
}
(false, true) => None,
(true, true) => Some("read-only"),
(_, false) => Some("disconnected"),
};
(channel.name.clone(), status)
} else {
"channel notes (disconnected)".to_string()
("<unknown>".into(), Some("disconnected"))
};
Label::new(label)
.color(if params.selected {
Color::Default
} else {
Color::Muted
h_flex()
.gap_2()
.child(
Label::new(channel_name)
.color(params.text_color())
.italic(params.preview),
)
.when_some(status, |element, status| {
element.child(
Label::new(status)
.size(LabelSize::XSmall)
.color(Color::Muted),
)
})
.into_any_element()
}
@@ -478,7 +512,6 @@ impl FollowableItem for ChannelView {
}
fn from_state_proto(
pane: View<workspace::Pane>,
workspace: View<workspace::Workspace>,
remote_id: workspace::ViewId,
state: &mut Option<proto::view::Variant>,
@@ -491,8 +524,7 @@ impl FollowableItem for ChannelView {
unreachable!()
};
let open =
ChannelView::open_in_pane(ChannelId(state.channel_id), None, pane, workspace, cx);
let open = ChannelView::load(ChannelId(state.channel_id), workspace, cx);
Some(cx.spawn(|mut cx| async move {
let this = open.await?;
@@ -563,6 +595,19 @@ impl FollowableItem for ChannelView {
fn to_follow_event(event: &Self::Event) -> Option<workspace::item::FollowEvent> {
Editor::to_follow_event(event)
}
fn dedup(&self, existing: &Self, cx: &WindowContext) -> Option<Dedup> {
let existing = existing.channel_buffer.read(cx);
if self.channel_buffer.read(cx).channel_id == existing.channel_id {
if existing.is_connected() {
Some(Dedup::KeepExisting)
} else {
Some(Dedup::ReplaceExisting)
}
} else {
None
}
}
}
struct ChannelBufferCollaborationHub(Model<ChannelBuffer>);

View File

@@ -111,6 +111,7 @@ impl ChatPanel {
this.is_scrolled_to_bottom = !event.is_scrolled;
}));
let local_offset = chrono::Local::now().offset().local_minus_utc();
let mut this = Self {
fs,
client,
@@ -120,7 +121,7 @@ impl ChatPanel {
active_chat: Default::default(),
pending_serialization: Task::ready(None),
message_editor: input_editor,
local_timezone: cx.local_timezone(),
local_timezone: UtcOffset::from_whole_seconds(local_offset).unwrap(),
subscriptions: Vec::new(),
is_scrolled_to_bottom: true,
active: false,

View File

@@ -6,7 +6,7 @@ use editor::{AnchorRangeExt, CompletionProvider, Editor, EditorElement, EditorSt
use fuzzy::{StringMatch, StringMatchCandidate};
use gpui::{
AsyncWindowContext, FocusableView, FontStyle, FontWeight, HighlightStyle, IntoElement, Model,
Render, Task, TextStyle, View, ViewContext, WeakView, WhiteSpace,
Render, Task, TextStyle, View, ViewContext, WeakView,
};
use language::{
language_settings::SoftWrap, Anchor, Buffer, BufferSnapshot, CodeLabel, LanguageRegistry,
@@ -537,10 +537,7 @@ impl Render for MessageEditor {
font_weight: settings.ui_font.weight,
font_style: FontStyle::Normal,
line_height: relative(1.3),
background_color: None,
underline: None,
strikethrough: None,
white_space: WhiteSpace::Normal,
..Default::default()
};
div()

View File

@@ -16,7 +16,7 @@ use gpui::{
EventEmitter, FocusHandle, FocusableView, FontStyle, InteractiveElement, IntoElement,
ListOffset, ListState, Model, MouseDownEvent, ParentElement, Pixels, Point, PromptLevel,
Render, SharedString, Styled, Subscription, Task, TextStyle, View, ViewContext, VisualContext,
WeakView, WhiteSpace,
WeakView,
};
use menu::{Cancel, Confirm, SecondaryConfirm, SelectNext, SelectPrev};
use project::{Fs, Project};
@@ -2194,10 +2194,7 @@ impl CollabPanel {
font_weight: settings.ui_font.weight,
font_style: FontStyle::Normal,
line_height: relative(1.3),
background_color: None,
underline: None,
strikethrough: None,
white_space: WhiteSpace::Normal,
..Default::default()
};
EditorElement::new(

View File

@@ -5,7 +5,6 @@ use gpui::{
};
use picker::{Picker, PickerDelegate};
use std::sync::Arc;
use theme::ActiveTheme as _;
use ui::{prelude::*, Avatar, ListItem, ListItemSpacing};
use util::{ResultExt as _, TryFutureExt};
use workspace::ModalView;

View File

@@ -127,11 +127,12 @@ impl NotificationPanel {
},
));
let local_offset = chrono::Local::now().offset().local_minus_utc();
let mut this = Self {
fs,
client,
user_store,
local_timezone: cx.local_timezone(),
local_timezone: UtcOffset::from_whole_seconds(local_offset).unwrap(),
channel_store: ChannelStore::global(cx),
notification_store: NotificationStore::global(cx),
notification_list,

View File

@@ -17,9 +17,10 @@ use gpui::{
use picker::{Picker, PickerDelegate};
use postage::{sink::Sink, stream::Stream};
use settings::Settings;
use ui::{h_flex, prelude::*, v_flex, HighlightedLabel, KeyBinding, ListItem, ListItemSpacing};
use util::ResultExt;
use workspace::{ModalView, Workspace};
use workspace::{ModalView, Workspace, WorkspaceSettings};
use zed_actions::OpenZedUrl;
actions!(command_palette, [Toggle]);
@@ -248,9 +249,13 @@ impl PickerDelegate for CommandPaletteDelegate {
fn update_matches(
&mut self,
query: String,
mut query: String,
cx: &mut ViewContext<Picker<Self>>,
) -> gpui::Task<()> {
let settings = WorkspaceSettings::get_global(cx);
if let Some(alias) = settings.command_aliases.get(&query) {
query = alias.to_string();
}
let (mut tx, mut rx) = postage::dispatch::channel(1);
let task = cx.background_executor().spawn({
let mut commands = self.all_commands.clone();
@@ -477,7 +482,7 @@ mod tests {
});
workspace.update(cx, |workspace, cx| {
workspace.add_item_to_active_pane(Box::new(editor.clone()), None, cx);
workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
editor.update(cx, |editor, cx| editor.focus(cx))
});

View File

@@ -0,0 +1,56 @@
[package]
name = "completion"
version = "0.1.0"
edition = "2021"
publish = false
license = "GPL-3.0-or-later"
[lints]
workspace = true
[lib]
path = "src/completion.rs"
doctest = false
[features]
test-support = [
"editor/test-support",
"language/test-support",
"project/test-support",
"text/test-support",
]
[dependencies]
anthropic = { workspace = true, features = ["schemars"] }
anyhow.workspace = true
client.workspace = true
collections.workspace = true
editor.workspace = true
futures.workspace = true
gpui.workspace = true
http.workspace = true
language_model.workspace = true
log.workspace = true
menu.workspace = true
ollama = { workspace = true, features = ["schemars"] }
open_ai = { workspace = true, features = ["schemars"] }
parking_lot.workspace = true
serde.workspace = true
serde_json.workspace = true
settings.workspace = true
smol.workspace = true
strum.workspace = true
theme.workspace = true
tiktoken-rs.workspace = true
ui.workspace = true
util.workspace = true
[dev-dependencies]
ctor.workspace = true
editor = { workspace = true, features = ["test-support"] }
env_logger.workspace = true
language = { workspace = true, features = ["test-support"] }
project = { workspace = true, features = ["test-support"] }
rand.workspace = true
text = { workspace = true, features = ["test-support"] }
unindent.workspace = true

View File

@@ -0,0 +1 @@
../../LICENSE-GPL

View File

@@ -1,14 +1,12 @@
use crate::{
assistant_settings::AnthropicModel, CompletionProvider, LanguageModel, LanguageModelRequest,
Role,
};
use crate::{count_open_ai_tokens, LanguageModelCompletionProvider, LanguageModelRequestMessage};
use anthropic::{stream_completion, Request, RequestMessage};
use crate::{count_open_ai_tokens, LanguageModelCompletionProvider};
use crate::{CompletionProvider, LanguageModel, LanguageModelRequest};
use anthropic::{stream_completion, Model as AnthropicModel, Request, RequestMessage};
use anyhow::{anyhow, Result};
use editor::{Editor, EditorElement, EditorStyle};
use futures::{future::BoxFuture, stream::BoxStream, FutureExt, StreamExt};
use gpui::{AnyView, AppContext, FontStyle, Task, TextStyle, View, WhiteSpace};
use gpui::{AnyView, AppContext, Task, TextStyle, View};
use http::HttpClient;
use language_model::Role;
use settings::Settings;
use std::time::Duration;
use std::{env, sync::Arc};
@@ -27,7 +25,7 @@ pub struct AnthropicCompletionProvider {
}
impl LanguageModelCompletionProvider for AnthropicCompletionProvider {
fn available_models(&self, _cx: &AppContext) -> Vec<LanguageModel> {
fn available_models(&self) -> Vec<LanguageModel> {
AnthropicModel::iter()
.map(LanguageModel::Anthropic)
.collect()
@@ -94,7 +92,7 @@ impl LanguageModelCompletionProvider for AnthropicCompletionProvider {
count_open_ai_tokens(request, cx.background_executor())
}
fn complete(
fn stream_completion(
&self,
request: LanguageModelRequest,
) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
@@ -176,7 +174,7 @@ impl AnthropicCompletionProvider {
}
fn to_anthropic_request(&self, mut request: LanguageModelRequest) -> Request {
preprocess_anthropic_request(&mut request);
request.preprocess_anthropic();
let model = match request.model {
LanguageModel::Anthropic(model) => model,
@@ -213,49 +211,6 @@ impl AnthropicCompletionProvider {
}
}
pub fn preprocess_anthropic_request(request: &mut LanguageModelRequest) {
let mut new_messages: Vec<LanguageModelRequestMessage> = Vec::new();
let mut system_message = String::new();
for message in request.messages.drain(..) {
if message.content.is_empty() {
continue;
}
match message.role {
Role::User | Role::Assistant => {
if let Some(last_message) = new_messages.last_mut() {
if last_message.role == message.role {
last_message.content.push_str("\n\n");
last_message.content.push_str(&message.content);
continue;
}
}
new_messages.push(message);
}
Role::System => {
if !system_message.is_empty() {
system_message.push_str("\n\n");
}
system_message.push_str(&message.content);
}
}
}
if !system_message.is_empty() {
new_messages.insert(
0,
LanguageModelRequestMessage {
role: Role::System,
content: system_message,
},
);
}
request.messages = new_messages;
}
struct AuthenticationPrompt {
api_key: View<Editor>,
api_url: String,
@@ -302,12 +257,8 @@ impl AuthenticationPrompt {
font_features: settings.ui_font.features.clone(),
font_size: rems(0.875).into(),
font_weight: settings.ui_font.weight,
font_style: FontStyle::Normal,
line_height: relative(1.3),
background_color: None,
underline: None,
strikethrough: None,
white_space: WhiteSpace::Normal,
..Default::default()
};
EditorElement::new(
&self.api_key,

View File

@@ -1,11 +1,12 @@
use crate::{
assistant_settings::CloudModel, count_open_ai_tokens, CompletionProvider, LanguageModel,
LanguageModelCompletionProvider, LanguageModelRequest,
count_open_ai_tokens, CompletionProvider, LanguageModel, LanguageModelCompletionProvider,
LanguageModelRequest,
};
use anyhow::{anyhow, Result};
use client::{proto, Client};
use futures::{future::BoxFuture, stream::BoxStream, FutureExt, StreamExt, TryFutureExt};
use gpui::{AnyView, AppContext, Task};
use language_model::CloudModel;
use std::{future, sync::Arc};
use strum::IntoEnumIterator;
use ui::prelude::*;
@@ -52,16 +53,16 @@ impl CloudCompletionProvider {
}
impl LanguageModelCompletionProvider for CloudCompletionProvider {
fn available_models(&self, _cx: &AppContext) -> Vec<LanguageModel> {
let mut custom_model = if let CloudModel::Custom(custom_model) = self.model.clone() {
Some(custom_model)
fn available_models(&self) -> Vec<LanguageModel> {
let mut custom_model = if matches!(self.model, CloudModel::Custom { .. }) {
Some(self.model.clone())
} else {
None
};
CloudModel::iter()
.filter_map(move |model| {
if let CloudModel::Custom(_) = model {
Some(CloudModel::Custom(custom_model.take()?))
if let CloudModel::Custom { .. } = model {
custom_model.take()
} else {
Some(model)
}
@@ -116,9 +117,9 @@ impl LanguageModelCompletionProvider for CloudCompletionProvider {
// Can't find a tokenizer for Claude 3, so for now just use the same as OpenAI's as an approximation.
count_open_ai_tokens(request, cx.background_executor())
}
LanguageModel::Cloud(CloudModel::Custom(model)) => {
LanguageModel::Cloud(CloudModel::Custom { name, .. }) => {
let request = self.client.request(proto::CountTokensWithLanguageModel {
model,
model: name,
messages: request
.messages
.iter()
@@ -135,7 +136,7 @@ impl LanguageModelCompletionProvider for CloudCompletionProvider {
}
}
fn complete(
fn stream_completion(
&self,
mut request: LanguageModelRequest,
) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {

View File

@@ -0,0 +1,291 @@
mod anthropic;
mod cloud;
#[cfg(any(test, feature = "test-support"))]
mod fake;
mod ollama;
mod open_ai;
pub use anthropic::*;
use anyhow::Result;
use client::Client;
pub use cloud::*;
#[cfg(any(test, feature = "test-support"))]
pub use fake::*;
use futures::{future::BoxFuture, stream::BoxStream, StreamExt};
use gpui::{AnyView, AppContext, Task, WindowContext};
use language_model::{LanguageModel, LanguageModelRequest};
pub use ollama::*;
pub use open_ai::*;
use parking_lot::RwLock;
use smol::lock::{Semaphore, SemaphoreGuardArc};
use std::{any::Any, pin::Pin, sync::Arc, task::Poll};
pub struct CompletionResponse {
inner: BoxStream<'static, Result<String>>,
_lock: SemaphoreGuardArc,
}
impl futures::Stream for CompletionResponse {
type Item = Result<String>;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.inner).poll_next(cx)
}
}
pub trait LanguageModelCompletionProvider: Send + Sync {
fn available_models(&self) -> Vec<LanguageModel>;
fn settings_version(&self) -> usize;
fn is_authenticated(&self) -> bool;
fn authenticate(&self, cx: &AppContext) -> Task<Result<()>>;
fn authentication_prompt(&self, cx: &mut WindowContext) -> AnyView;
fn reset_credentials(&self, cx: &AppContext) -> Task<Result<()>>;
fn model(&self) -> LanguageModel;
fn count_tokens(
&self,
request: LanguageModelRequest,
cx: &AppContext,
) -> BoxFuture<'static, Result<usize>>;
fn stream_completion(
&self,
request: LanguageModelRequest,
) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>>;
fn as_any_mut(&mut self) -> &mut dyn Any;
}
const MAX_CONCURRENT_COMPLETION_REQUESTS: usize = 4;
pub struct CompletionProvider {
provider: Arc<RwLock<dyn LanguageModelCompletionProvider>>,
client: Option<Arc<Client>>,
request_limiter: Arc<Semaphore>,
}
impl CompletionProvider {
pub fn new(
provider: Arc<RwLock<dyn LanguageModelCompletionProvider>>,
client: Option<Arc<Client>>,
) -> Self {
Self {
provider,
client,
request_limiter: Arc::new(Semaphore::new(MAX_CONCURRENT_COMPLETION_REQUESTS)),
}
}
pub fn available_models(&self) -> Vec<LanguageModel> {
self.provider.read().available_models()
}
pub fn settings_version(&self) -> usize {
self.provider.read().settings_version()
}
pub fn is_authenticated(&self) -> bool {
self.provider.read().is_authenticated()
}
pub fn authenticate(&self, cx: &AppContext) -> Task<Result<()>> {
self.provider.read().authenticate(cx)
}
pub fn authentication_prompt(&self, cx: &mut WindowContext) -> AnyView {
self.provider.read().authentication_prompt(cx)
}
pub fn reset_credentials(&self, cx: &AppContext) -> Task<Result<()>> {
self.provider.read().reset_credentials(cx)
}
pub fn model(&self) -> LanguageModel {
self.provider.read().model()
}
pub fn count_tokens(
&self,
request: LanguageModelRequest,
cx: &AppContext,
) -> BoxFuture<'static, Result<usize>> {
self.provider.read().count_tokens(request, cx)
}
pub fn stream_completion(
&self,
request: LanguageModelRequest,
cx: &AppContext,
) -> Task<Result<CompletionResponse>> {
let rate_limiter = self.request_limiter.clone();
let provider = self.provider.clone();
cx.foreground_executor().spawn(async move {
let lock = rate_limiter.acquire_arc().await;
let response = provider.read().stream_completion(request);
let response = response.await?;
Ok(CompletionResponse {
inner: response,
_lock: lock,
})
})
}
pub fn stream_completion_bg(
// TODO consider unifying this with stream_completion, since they share so much code
// (design question: do we want to make a Spawn or perhaps Executor trait to abstract over bg and fg executors?)
&self,
request: LanguageModelRequest,
cx: &AppContext,
) -> Task<Result<CompletionResponse>> {
let rate_limiter = self.request_limiter.clone();
let provider = self.provider.clone();
cx.background_executor().spawn(async move {
let lock = rate_limiter.acquire_arc().await;
let response = provider.read().stream_completion(request);
let response = response.await?;
Ok(CompletionResponse {
inner: response,
_lock: lock,
})
})
}
pub fn complete(&self, request: LanguageModelRequest, cx: &AppContext) -> Task<Result<String>> {
let response = self.stream_completion(request, cx);
cx.foreground_executor().spawn(async move {
let mut chunks = response.await?;
let mut completion = String::new();
while let Some(chunk) = chunks.next().await {
let chunk = chunk?;
completion.push_str(&chunk);
}
Ok(completion)
})
}
pub fn update_provider(
&mut self,
get_provider: impl FnOnce(Arc<Client>) -> Arc<RwLock<dyn LanguageModelCompletionProvider>>,
) {
if let Some(client) = &self.client {
self.provider = get_provider(Arc::clone(client));
} else {
log::warn!("completion provider cannot be updated because its client was not set");
}
}
}
impl gpui::Global for CompletionProvider {}
impl CompletionProvider {
pub fn global(cx: &AppContext) -> &Self {
cx.global::<Self>()
}
pub fn update_current_as<R, T: LanguageModelCompletionProvider + 'static>(
&mut self,
update: impl FnOnce(&mut T) -> R,
) -> Option<R> {
let mut provider = self.provider.write();
if let Some(provider) = provider.as_any_mut().downcast_mut::<T>() {
Some(update(provider))
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use gpui::AppContext;
use parking_lot::RwLock;
use settings::SettingsStore;
use smol::stream::StreamExt;
use crate::{
CompletionProvider, FakeCompletionProvider, LanguageModelRequest,
MAX_CONCURRENT_COMPLETION_REQUESTS,
};
#[gpui::test]
fn test_rate_limiting(cx: &mut AppContext) {
SettingsStore::test(cx);
let fake_provider = FakeCompletionProvider::setup_test(cx);
let provider = CompletionProvider::new(Arc::new(RwLock::new(fake_provider.clone())), None);
// Enqueue some requests
for i in 0..MAX_CONCURRENT_COMPLETION_REQUESTS * 2 {
let response = provider.stream_completion(
LanguageModelRequest {
temperature: i as f32 / 10.0,
..Default::default()
},
cx,
);
cx.background_executor()
.spawn(async move {
let mut stream = response.await.unwrap();
while let Some(message) = stream.next().await {
message.unwrap();
}
})
.detach();
}
cx.background_executor().run_until_parked();
assert_eq!(
fake_provider.completion_count(),
MAX_CONCURRENT_COMPLETION_REQUESTS
);
// Get the first completion request that is in flight and mark it as completed.
let completion = fake_provider
.pending_completions()
.into_iter()
.next()
.unwrap();
fake_provider.finish_completion(&completion);
// Ensure that the number of in-flight completion requests is reduced.
assert_eq!(
fake_provider.completion_count(),
MAX_CONCURRENT_COMPLETION_REQUESTS - 1
);
cx.background_executor().run_until_parked();
// Ensure that another completion request was allowed to acquire the lock.
assert_eq!(
fake_provider.completion_count(),
MAX_CONCURRENT_COMPLETION_REQUESTS
);
// Mark all completion requests as finished that are in flight.
for request in fake_provider.pending_completions() {
fake_provider.finish_completion(&request);
}
assert_eq!(fake_provider.completion_count(), 0);
// Wait until the background tasks acquire the lock again.
cx.background_executor().run_until_parked();
assert_eq!(
fake_provider.completion_count(),
MAX_CONCURRENT_COMPLETION_REQUESTS - 1
);
// Finish all remaining completion requests.
for request in fake_provider.pending_completions() {
fake_provider.finish_completion(&request);
}
cx.background_executor().run_until_parked();
assert_eq!(fake_provider.completion_count(), 0);
}
}

View File

@@ -13,7 +13,6 @@ pub struct FakeCompletionProvider {
}
impl FakeCompletionProvider {
#[cfg(test)]
pub fn setup_test(cx: &mut AppContext) -> Self {
use crate::CompletionProvider;
use parking_lot::RwLock;
@@ -24,7 +23,7 @@ impl FakeCompletionProvider {
this
}
pub fn running_completions(&self) -> Vec<LanguageModelRequest> {
pub fn pending_completions(&self) -> Vec<LanguageModelRequest> {
self.current_completion_txs
.lock()
.keys()
@@ -36,7 +35,7 @@ impl FakeCompletionProvider {
self.current_completion_txs.lock().len()
}
pub fn send_completion(&self, request: &LanguageModelRequest, chunk: String) {
pub fn send_completion_chunk(&self, request: &LanguageModelRequest, chunk: String) {
let json = serde_json::to_string(request).unwrap();
self.current_completion_txs
.lock()
@@ -46,15 +45,24 @@ impl FakeCompletionProvider {
.unwrap();
}
pub fn send_last_completion_chunk(&self, chunk: String) {
self.send_completion_chunk(self.pending_completions().last().unwrap(), chunk);
}
pub fn finish_completion(&self, request: &LanguageModelRequest) {
self.current_completion_txs
.lock()
.remove(&serde_json::to_string(request).unwrap());
.remove(&serde_json::to_string(request).unwrap())
.unwrap();
}
pub fn finish_last_completion(&self) {
self.finish_completion(self.pending_completions().last().unwrap());
}
}
impl LanguageModelCompletionProvider for FakeCompletionProvider {
fn available_models(&self, _cx: &AppContext) -> Vec<LanguageModel> {
fn available_models(&self) -> Vec<LanguageModel> {
vec![LanguageModel::default()]
}
@@ -90,7 +98,7 @@ impl LanguageModelCompletionProvider for FakeCompletionProvider {
futures::future::ready(Ok(0)).boxed()
}
fn complete(
fn stream_completion(
&self,
_request: LanguageModelRequest,
) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {

View File

@@ -1,15 +1,14 @@
use crate::LanguageModelCompletionProvider;
use crate::{
assistant_settings::OllamaModel, CompletionProvider, LanguageModel, LanguageModelRequest, Role,
};
use crate::{CompletionProvider, LanguageModel, LanguageModelRequest};
use anyhow::Result;
use futures::StreamExt as _;
use futures::{future::BoxFuture, stream::BoxStream, FutureExt};
use gpui::{AnyView, AppContext, Task};
use http::HttpClient;
use language_model::Role;
use ollama::Model as OllamaModel;
use ollama::{
get_models, preload_model, stream_chat_completion, ChatMessage, ChatOptions, ChatRequest,
Role as OllamaRole,
};
use std::sync::Arc;
use std::time::Duration;
@@ -28,7 +27,7 @@ pub struct OllamaCompletionProvider {
}
impl LanguageModelCompletionProvider for OllamaCompletionProvider {
fn available_models(&self, _cx: &AppContext) -> Vec<LanguageModel> {
fn available_models(&self) -> Vec<LanguageModel> {
self.available_models
.iter()
.map(|m| LanguageModel::Ollama(m.clone()))
@@ -91,7 +90,7 @@ impl LanguageModelCompletionProvider for OllamaCompletionProvider {
async move { Ok(token_count) }.boxed()
}
fn complete(
fn stream_completion(
&self,
request: LanguageModelRequest,
) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
@@ -262,16 +261,6 @@ impl OllamaCompletionProvider {
}
}
impl From<Role> for ollama::Role {
fn from(val: Role) -> Self {
match val {
Role::User => OllamaRole::User,
Role::Assistant => OllamaRole::Assistant,
Role::System => OllamaRole::System,
}
}
}
struct DownloadOllamaMessage {
retry_connection: Box<dyn Fn(&mut WindowContext) -> Task<Result<()>>>,
}

View File

@@ -1,15 +1,13 @@
use crate::assistant_settings::CloudModel;
use crate::assistant_settings::{AssistantProvider, AssistantSettings};
use crate::CompletionProvider;
use crate::LanguageModelCompletionProvider;
use crate::{
assistant_settings::OpenAiModel, CompletionProvider, LanguageModel, LanguageModelRequest, Role,
};
use anyhow::{anyhow, Result};
use editor::{Editor, EditorElement, EditorStyle};
use futures::{future::BoxFuture, stream::BoxStream, FutureExt, StreamExt};
use gpui::{AnyView, AppContext, FontStyle, Task, TextStyle, View, WhiteSpace};
use gpui::{AnyView, AppContext, Task, TextStyle, View};
use http::HttpClient;
use open_ai::{stream_completion, Request, RequestMessage, Role as OpenAiRole};
use language_model::{CloudModel, LanguageModel, LanguageModelRequest, Role};
use open_ai::Model as OpenAiModel;
use open_ai::{stream_completion, Request, RequestMessage};
use settings::Settings;
use std::time::Duration;
use std::{env, sync::Arc};
@@ -25,6 +23,7 @@ pub struct OpenAiCompletionProvider {
http_client: Arc<dyn HttpClient>,
low_speed_timeout: Option<Duration>,
settings_version: usize,
available_models_from_settings: Vec<OpenAiModel>,
}
impl OpenAiCompletionProvider {
@@ -34,6 +33,7 @@ impl OpenAiCompletionProvider {
http_client: Arc<dyn HttpClient>,
low_speed_timeout: Option<Duration>,
settings_version: usize,
available_models_from_settings: Vec<OpenAiModel>,
) -> Self {
Self {
api_key: None,
@@ -42,6 +42,7 @@ impl OpenAiCompletionProvider {
http_client,
low_speed_timeout,
settings_version,
available_models_from_settings,
}
}
@@ -92,30 +93,26 @@ impl OpenAiCompletionProvider {
}
impl LanguageModelCompletionProvider for OpenAiCompletionProvider {
fn available_models(&self, cx: &AppContext) -> Vec<LanguageModel> {
if let AssistantProvider::OpenAi {
available_models, ..
} = &AssistantSettings::get_global(cx).provider
{
if !available_models.is_empty() {
return available_models
.iter()
.cloned()
.map(LanguageModel::OpenAi)
.collect();
}
}
let available_models = if matches!(self.model, OpenAiModel::Custom { .. }) {
vec![self.model.clone()]
} else {
OpenAiModel::iter()
.filter(|model| !matches!(model, OpenAiModel::Custom { .. }))
fn available_models(&self) -> Vec<LanguageModel> {
if self.available_models_from_settings.is_empty() {
let available_models = if matches!(self.model, OpenAiModel::Custom { .. }) {
vec![self.model.clone()]
} else {
OpenAiModel::iter()
.filter(|model| !matches!(model, OpenAiModel::Custom { .. }))
.collect()
};
available_models
.into_iter()
.map(LanguageModel::OpenAi)
.collect()
};
available_models
.into_iter()
.map(LanguageModel::OpenAi)
.collect()
} else {
self.available_models_from_settings
.iter()
.cloned()
.map(LanguageModel::OpenAi)
.collect()
}
}
fn settings_version(&self) -> usize {
@@ -179,7 +176,7 @@ impl LanguageModelCompletionProvider for OpenAiCompletionProvider {
count_open_ai_tokens(request, cx.background_executor())
}
fn complete(
fn stream_completion(
&self,
request: LanguageModelRequest,
) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
@@ -244,6 +241,7 @@ pub fn count_open_ai_tokens(
| LanguageModel::Cloud(CloudModel::Claude3Opus)
| LanguageModel::Cloud(CloudModel::Claude3Sonnet)
| LanguageModel::Cloud(CloudModel::Claude3Haiku)
| LanguageModel::Cloud(CloudModel::Custom { .. })
| LanguageModel::OpenAi(OpenAiModel::Custom { .. }) => {
// Tiktoken doesn't yet support these models, so we manually use the
// same tokenizer as GPT-4.
@@ -255,16 +253,6 @@ pub fn count_open_ai_tokens(
.boxed()
}
impl From<Role> for open_ai::Role {
fn from(val: Role) -> Self {
match val {
Role::User => OpenAiRole::User,
Role::Assistant => OpenAiRole::Assistant,
Role::System => OpenAiRole::System,
}
}
}
struct AuthenticationPrompt {
api_key: View<Editor>,
api_url: String,
@@ -311,12 +299,8 @@ impl AuthenticationPrompt {
font_features: settings.ui_font.features.clone(),
font_size: rems(0.875).into(),
font_weight: settings.ui_font.weight,
font_style: FontStyle::Normal,
line_height: relative(1.3),
background_color: None,
underline: None,
strikethrough: None,
white_space: WhiteSpace::Normal,
..Default::default()
};
EditorElement::new(
&self.api_key,

View File

@@ -1236,7 +1236,7 @@ mod tests {
unimplemented!()
}
fn to_proto(&self) -> rpc::proto::File {
fn to_proto(&self, _: &AppContext) -> rpc::proto::File {
unimplemented!()
}

View File

@@ -20,7 +20,7 @@ pub struct Store {
pub struct DevServerProject {
pub id: DevServerProjectId,
pub project_id: Option<ProjectId>,
pub path: SharedString,
pub paths: Vec<SharedString>,
pub dev_server_id: DevServerId,
}
@@ -29,7 +29,7 @@ impl From<proto::DevServerProject> for DevServerProject {
Self {
id: DevServerProjectId(project.id),
project_id: project.project_id.map(|id| ProjectId(id)),
path: project.path.into(),
paths: project.paths.into_iter().map(|path| path.into()).collect(),
dev_server_id: DevServerId(project.dev_server_id),
}
}
@@ -85,7 +85,7 @@ impl Store {
.filter(|project| project.dev_server_id == id)
.cloned()
.collect();
projects.sort_by_key(|p| (p.path.clone(), p.id));
projects.sort_by_key(|p| (p.paths.clone(), p.id));
projects
}
@@ -108,7 +108,7 @@ impl Store {
pub fn dev_server_projects(&self) -> Vec<DevServerProject> {
let mut projects: Vec<DevServerProject> =
self.dev_server_projects.values().cloned().collect();
projects.sort_by_key(|p| (p.path.clone(), p.id));
projects.sort_by_key(|p| (p.paths.clone(), p.id));
projects
}

View File

@@ -18,11 +18,13 @@ collections.workspace = true
ctor.workspace = true
editor.workspace = true
env_logger.workspace = true
feature_flags.workspace = true
futures.workspace = true
gpui.workspace = true
language.workspace = true
log.workspace = true
lsp.workspace = true
multi_buffer.workspace = true
project.workspace = true
rand.workspace = true
schemars.workspace = true

View File

@@ -4,16 +4,18 @@ mod toolbar_controls;
#[cfg(test)]
mod diagnostics_tests;
pub(crate) mod grouped_diagnostics;
use anyhow::Result;
use collections::{BTreeSet, HashSet};
use editor::{
diagnostic_block_renderer,
display_map::{BlockDisposition, BlockId, BlockProperties, BlockStyle, RenderBlock},
display_map::{BlockDisposition, BlockProperties, BlockStyle, CustomBlockId, RenderBlock},
highlight_diagnostic_message,
scroll::Autoscroll,
Editor, EditorEvent, ExcerptId, ExcerptRange, MultiBuffer, ToOffset,
};
use feature_flags::FeatureFlagAppExt;
use futures::{
channel::mpsc::{self, UnboundedSender},
StreamExt as _,
@@ -43,7 +45,7 @@ use ui::{h_flex, prelude::*, Icon, IconName, Label};
use util::ResultExt;
use workspace::{
item::{BreadcrumbText, Item, ItemEvent, ItemHandle, TabContentParams},
ItemNavHistory, Pane, ToolbarItemLocation, Workspace,
ItemNavHistory, ToolbarItemLocation, Workspace,
};
actions!(diagnostics, [Deploy, ToggleWarnings]);
@@ -52,6 +54,9 @@ pub fn init(cx: &mut AppContext) {
ProjectDiagnosticsSettings::register(cx);
cx.observe_new_views(ProjectDiagnosticsEditor::register)
.detach();
if !cx.has_flag::<feature_flags::GroupedDiagnostics>() {
grouped_diagnostics::init(cx);
}
}
struct ProjectDiagnosticsEditor {
@@ -80,7 +85,7 @@ struct DiagnosticGroupState {
primary_diagnostic: DiagnosticEntry<language::Anchor>,
primary_excerpt_ix: usize,
excerpts: Vec<ExcerptId>,
blocks: HashSet<BlockId>,
blocks: HashSet<CustomBlockId>,
block_count: usize,
}
@@ -232,13 +237,13 @@ impl ProjectDiagnosticsEditor {
fn deploy(workspace: &mut Workspace, _: &Deploy, cx: &mut ViewContext<Workspace>) {
if let Some(existing) = workspace.item_of_type::<ProjectDiagnosticsEditor>(cx) {
workspace.activate_item(&existing, cx);
workspace.activate_item(&existing, true, true, cx);
} else {
let workspace_handle = cx.view().downgrade();
let diagnostics = cx.new_view(|cx| {
ProjectDiagnosticsEditor::new(workspace.project().clone(), workspace_handle, cx)
});
workspace.add_item_to_active_pane(Box::new(diagnostics), None, cx);
workspace.add_item_to_active_pane(Box::new(diagnostics), None, true, cx);
}
}
@@ -466,7 +471,9 @@ impl ProjectDiagnosticsEditor {
position: (excerpt_id, entry.range.start),
height: diagnostic.message.matches('\n').count() as u8 + 1,
style: BlockStyle::Fixed,
render: diagnostic_block_renderer(diagnostic, true),
render: diagnostic_block_renderer(
diagnostic, None, true, true,
),
disposition: BlockDisposition::Below,
});
}
@@ -642,11 +649,7 @@ impl Item for ProjectDiagnosticsEditor {
fn tab_content(&self, params: TabContentParams, _: &WindowContext) -> AnyElement {
if self.summary.error_count == 0 && self.summary.warning_count == 0 {
Label::new("No problems")
.color(if params.selected {
Color::Default
} else {
Color::Muted
})
.color(params.text_color())
.into_any_element()
} else {
h_flex()
@@ -656,13 +659,10 @@ impl Item for ProjectDiagnosticsEditor {
h_flex()
.gap_1()
.child(Icon::new(IconName::XCircle).color(Color::Error))
.child(Label::new(self.summary.error_count.to_string()).color(
if params.selected {
Color::Default
} else {
Color::Muted
},
)),
.child(
Label::new(self.summary.error_count.to_string())
.color(params.text_color()),
),
)
})
.when(self.summary.warning_count > 0, |then| {
@@ -670,13 +670,10 @@ impl Item for ProjectDiagnosticsEditor {
h_flex()
.gap_1()
.child(Icon::new(IconName::ExclamationTriangle).color(Color::Warning))
.child(Label::new(self.summary.warning_count.to_string()).color(
if params.selected {
Color::Default
} else {
Color::Muted
},
)),
.child(
Label::new(self.summary.warning_count.to_string())
.color(params.text_color()),
),
)
})
.into_any_element()
@@ -779,26 +776,12 @@ impl Item for ProjectDiagnosticsEditor {
self.editor
.update(cx, |editor, cx| editor.added_to_workspace(workspace, cx));
}
fn serialized_item_kind() -> Option<&'static str> {
Some("diagnostics")
}
fn deserialize(
project: Model<Project>,
workspace: WeakView<Workspace>,
_workspace_id: workspace::WorkspaceId,
_item_id: workspace::ItemId,
cx: &mut ViewContext<Pane>,
) -> Task<Result<View<Self>>> {
Task::ready(Ok(cx.new_view(|cx| Self::new(project, workspace, cx))))
}
}
const DIAGNOSTIC_HEADER: &'static str = "diagnostic header";
fn diagnostic_header_renderer(diagnostic: Diagnostic) -> RenderBlock {
let (message, code_ranges) = highlight_diagnostic_message(&diagnostic);
let (message, code_ranges) = highlight_diagnostic_message(&diagnostic, None);
let message: SharedString = message;
Box::new(move |cx| {
let highlight_style: HighlightStyle = cx.theme().colors().text_accent.into();

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