Compare commits

...

290 commits

Author SHA1 Message Date
Tequila
5c967da418
Merge branch 'main' into codex-zed-svg-copy-image 2026-05-31 15:34:23 +08:00
Nathan Sobo
09165c15dc
gpui: Support prompt_for_paths in TestPlatform (#58139)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
Implements the previously-`unimplemented!()`
`TestPlatform::prompt_for_paths` so tests can drive the platform Open
dialog deterministically.

Adds `TestAppContext::simulate_path_prompt_response` and
`did_prompt_for_paths`, mirroring the existing `prompt_for_new_path`
test helpers (`simulate_new_path_selection`). The simulated response
validates that callers don't return multiple paths when
`PathPromptOptions::multiple` is false.

Release Notes:

- N/A
2026-05-30 20:37:39 +00:00
renovate[bot]
e2e7a6769e
Update dependency requests to v2.33.0 [SECURITY] (#58093)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
This PR contains the following updates:

| Package | Change |
[Age](https://docs.renovatebot.com/merge-confidence/) |
[Confidence](https://docs.renovatebot.com/merge-confidence/) |
|---|---|---|---|
| [requests](https://redirect.github.com/psf/requests)
([changelog](https://redirect.github.com/psf/requests/blob/master/HISTORY.md))
| `2.32.3` → `2.33.0` |
![age](https://developer.mend.io/api/mc/badges/age/pypi/requests/2.33.0?slim=true)
|
![confidence](https://developer.mend.io/api/mc/badges/confidence/pypi/requests/2.32.3/2.33.0?slim=true)
|

---

> [!WARNING]
> Some dependencies could not be looked up. Check the [Dependency
Dashboard](../issues/15138) for more information.

---

### Requests vulnerable to .netrc credentials leak via malicious URLs
[CVE-2024-47081](https://nvd.nist.gov/vuln/detail/CVE-2024-47081) /
[GHSA-9hjg-9r4m-mvj7](https://redirect.github.com/advisories/GHSA-9hjg-9r4m-mvj7)

<details>
<summary>More information</summary>

#### Details
##### Impact

Due to a URL parsing issue, Requests releases prior to 2.32.4 may leak
.netrc credentials to third parties for specific maliciously-crafted
URLs.

##### Workarounds
For older versions of Requests, use of the .netrc file can be disabled
with `trust_env=False` on your Requests Session
([docs](https://requests.readthedocs.io/en/latest/api/#requests.Session.trust_env)).

##### References

[https://github.com/psf/requests/pull/6965](https://redirect.github.com/psf/requests/pull/6965)
https://seclists.org/fulldisclosure/2025/Jun/2

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:H/I:N/A:N`

#### References
-
[https://github.com/psf/requests/security/advisories/GHSA-9hjg-9r4m-mvj7](https://redirect.github.com/psf/requests/security/advisories/GHSA-9hjg-9r4m-mvj7)
-
[https://nvd.nist.gov/vuln/detail/CVE-2024-47081](https://nvd.nist.gov/vuln/detail/CVE-2024-47081)
-
[https://github.com/psf/requests/pull/6965](https://redirect.github.com/psf/requests/pull/6965)
-
[96ba401c12)
-
[https://requests.readthedocs.io/en/latest/api/#requests.Session.trust_env](https://requests.readthedocs.io/en/latest/api/#requests.Session.trust_env)
-
[https://seclists.org/fulldisclosure/2025/Jun/2](https://seclists.org/fulldisclosure/2025/Jun/2)
-
[http://seclists.org/fulldisclosure/2025/Jun/2](http://seclists.org/fulldisclosure/2025/Jun/2)
-
[http://www.openwall.com/lists/oss-security/2025/06/03/11](http://www.openwall.com/lists/oss-security/2025/06/03/11)
-
[http://www.openwall.com/lists/oss-security/2025/06/03/9](http://www.openwall.com/lists/oss-security/2025/06/03/9)
-
[http://www.openwall.com/lists/oss-security/2025/06/04/1](http://www.openwall.com/lists/oss-security/2025/06/04/1)
-
[http://www.openwall.com/lists/oss-security/2025/06/04/6](http://www.openwall.com/lists/oss-security/2025/06/04/6)
-
[https://github.com/advisories/GHSA-9hjg-9r4m-mvj7](https://redirect.github.com/advisories/GHSA-9hjg-9r4m-mvj7)

This data is provided by the [GitHub Advisory
Database](https://redirect.github.com/advisories/GHSA-9hjg-9r4m-mvj7)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Requests has Insecure Temp File Reuse in its extract_zipped_paths()
utility function
[CVE-2026-25645](https://nvd.nist.gov/vuln/detail/CVE-2026-25645) /
[GHSA-gc5v-m9x4-r6x2](https://redirect.github.com/advisories/GHSA-gc5v-m9x4-r6x2)

<details>
<summary>More information</summary>

#### Details
##### Impact
The `requests.utils.extract_zipped_paths()` utility function uses a
predictable filename when extracting files from zip archives into the
system temporary directory. If the target file already exists, it is
reused without validation. A local attacker with write access to the
temp directory could pre-create a malicious file that would be loaded in
place of the legitimate one.

##### Affected usages
**Standard usage of the Requests library is not affected by this
vulnerability.** Only applications that call `extract_zipped_paths()`
directly are impacted.

##### Remediation
Upgrade to at least Requests 2.33.0, where the library now extracts
files to a non-deterministic location.

If developers are unable to upgrade, they can set `TMPDIR` in their
environment to a directory with restricted write access.

#### Severity
- CVSS Score: 4.4 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:L/AC:H/PR:L/UI:R/S:U/C:N/I:H/A:N`

#### References
-
[https://github.com/psf/requests/security/advisories/GHSA-gc5v-m9x4-r6x2](https://redirect.github.com/psf/requests/security/advisories/GHSA-gc5v-m9x4-r6x2)
-
[66d21cb07b)
-
[https://github.com/psf/requests/releases/tag/v2.33.0](https://redirect.github.com/psf/requests/releases/tag/v2.33.0)
-
[https://nvd.nist.gov/vuln/detail/CVE-2026-25645](https://nvd.nist.gov/vuln/detail/CVE-2026-25645)
-
[https://github.com/advisories/GHSA-gc5v-m9x4-r6x2](https://redirect.github.com/advisories/GHSA-gc5v-m9x4-r6x2)

This data is provided by the [GitHub Advisory
Database](https://redirect.github.com/advisories/GHSA-gc5v-m9x4-r6x2)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Release Notes

<details>
<summary>psf/requests (requests)</summary>

###
[`v2.33.0`](https://redirect.github.com/psf/requests/blob/HEAD/HISTORY.md#2330-2026-03-25)

[Compare
Source](https://redirect.github.com/psf/requests/compare/v2.32.5...v2.33.0)

**Announcements**

- 📣 Requests is adding inline types. If you have a typed code base that
uses Requests, please take a look at
[#&#8203;7271](https://redirect.github.com/psf/requests/issues/7271).
Give it a try, and report
  any gaps or feedback you may have in the issue. 📣

**Security**

- CVE-2026-25645 `requests.utils.extract_zipped_paths` now extracts
  contents to a non-deterministic location to prevent malicious file
  replacement. This does not affect default usage of Requests, only
  applications calling the utility function directly.

**Improvements**

- Migrated to a PEP 517 build system using setuptools.
([#&#8203;7012](https://redirect.github.com/psf/requests/issues/7012))

**Bugfixes**

- Fixed an issue where an empty netrc entry could cause
  malformed authentication to be applied to Requests on
Python 3.11+.
([#&#8203;7205](https://redirect.github.com/psf/requests/issues/7205))

**Deprecations**

- Dropped support for Python 3.9 following its end of support.
([#&#8203;7196](https://redirect.github.com/psf/requests/issues/7196))

**Documentation**

- Various typo fixes and doc improvements.

###
[`v2.32.5`](https://redirect.github.com/psf/requests/blob/HEAD/HISTORY.md#2325-2025-08-18)

[Compare
Source](https://redirect.github.com/psf/requests/compare/v2.32.4...v2.32.5)

**Bugfixes**

- The SSLContext caching feature originally introduced in 2.32.0 has
created
a new class of issues in Requests that have had negative impact across a
number
of use cases. The Requests team has decided to revert this feature as
long term
maintenance of it is proving to be unsustainable in its current
iteration.

**Deprecations**

- Added support for Python 3.14.
- Dropped support for Python 3.8 following its end of support.

###
[`v2.32.4`](https://redirect.github.com/psf/requests/blob/HEAD/HISTORY.md#2324-2025-06-10)

[Compare
Source](https://redirect.github.com/psf/requests/compare/v2.32.3...v2.32.4)

**Security**

- CVE-2024-47081 Fixed an issue where a maliciously crafted URL and
trusted
environment will retrieve credentials for the wrong hostname/machine
from a
  netrc file.

**Improvements**

- Numerous documentation improvements

**Deprecations**

- Added support for pypy 3.11 for Linux and macOS.
- Dropped support for pypy 3.9 following its end of support.

</details>

---

### Configuration

📅 **Schedule**: (in timezone America/New_York)

- Branch creation
  - ""
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

Release Notes:

- N/A

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4yMDIuMSIsInVwZGF0ZWRJblZlciI6IjQzLjIwMi4xIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-05-29 20:29:38 +00:00
Sathwik Chirivelli
5d3b9e467e
git_ui: Open file diffs from git panel (#56152)
Self-Review Checklist:
- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Addresses https://github.com/zed-industries/zed/discussions/33773.

This changes git panel file activation so double-clicking or
secondary-opening a changed file opens a dedicated full-file diff tab
backed by a `SplittableEditor`.

The per-file diff reuses the project diff staging and restore controls,
respects the configured diff view style, and focuses an existing
per-file diff tab when one is already open instead of creating
duplicates.

Verified with `cargo run`.

Release Notes:

- Improved git panel file diff opening.

---------

Co-authored-by: Christopher Biscardi <chris@christopherbiscardi.com>
2026-05-29 19:43:26 +00:00
Joseph T. Lyons
06826ef10f
Bump urllib3 to v2.7.0 (#58092)
Self-Review Checklist:

- [X] I've reviewed my own diff for quality, security, and reliability
- [ ] Unsafe blocks (if any) have justifying comments
- [ ] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [ ] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-29 17:55:04 +00:00
Anthony Eid
7f4a99aa95
Fix task modal fallback when LSP tasks are empty (#58090)
References
[FR-28](https://linear.app/zed-industries/issue/FR-28/task-modal-does-not-show-runnable-rust-test).

The bug this PR aims to fix is

> I can click the play button beside a rust test function, but it does
not show up in the task modal.

I wasn't able to reproduce it, but I suspect this was caused by the task
system preferring LSP code actions by default. It checked that an LSP
was queried for a task instead of checking if the queried LSP actually
returned any tasks. So the fix was just adding the below if statement as
a check.

```rust
if !new_lsp_tasks.is_empty() {
    lsp_tasks
        .entry(source_kind)
        .or_insert_with(Vec::new)
        .append(&mut new_lsp_tasks);
}
```

I also added a regression test for this

Self-Review Checklist:

- [x] I have reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the UI/UX checklist
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable


Release Notes:

- Fixed task modal failing to show language tasks in some cases
2026-05-29 17:49:11 +00:00
Bennet Bo Fenner
122619624d
x_ai: Add support for specifying reasoning effort (#58078)
See
https://docs.x.ai/developers/model-capabilities/text/reasoning#the-reasoning_effort-parameter

Closes #58056

Release Notes:

- agent: Added support for specifying reasoning effort for Grok 4.3
(xAI)
2026-05-29 16:28:27 +00:00
Smit Barmase
2ea99a81f1
Add new area labels to track mapping (#58083)
| Label | Description |
|---|---|
| `area:preview/csv` | Feedback for Zed's CSV support |
| `area:fs` | Related to the fs crate. |
| `area:scanning` | Worktree scanning related PRs. |
| `area:editor/bookmarks` | Feedback for the editor bookmarks |
| `area:ai/agent thread/skills` | Feedback for Zed's AI Skills feature |
| `area:ai/terminal threads` | Feedback for Zed's Terminal Threads |
| `area:crashes` | PR related to crashes crate. |
| `area:scripts` | Changes in "script" directory |


Release Notes:

- N/A
2026-05-29 16:08:53 +00:00
Nathan Sobo
c30d18b10d
scheduler: Add spawn_dedicated for single-threaded actors with !Send state (#57609)
Adds `scheduler::spawn_dedicated_thread` (and inherent `spawn_dedicated`
methods on `PlatformScheduler` and `TestScheduler`) so single-threaded
actors that own `!Send` state can run on their own OS thread and freely
do blocking I/O without disturbing any other executor.

### Why

A single-threaded actor that needs to do blocking syscalls is currently
stuck: it can't run on the shared foreground executor (blocking would
stall every other foreground session), and it can't move to the
background pool because its state isn't `Send`. `spawn_dedicated` gives
each such actor its own thread and its own `LocalExecutor`, while still
participating in the same testable scheduler infrastructure as
everything else.

### Shape

- `pub fn spawn_dedicated_thread(session_id, scheduler, f) -> Task<_>`
in `scheduler`. Owns the OS thread, the per-session runnable channel,
and the `LocalExecutor` setup.
- Inherent `spawn_dedicated` on `PlatformScheduler` (allocates its own
`SessionId`, delegates to the free function).
- Inherent `spawn_dedicated` on `TestScheduler` (no real thread — runs
as a fresh local session driven by the test scheduler's run loop, so
determinism under `many` is preserved).
- Renames `Scheduler::schedule_foreground` → `schedule_local` and
`scheduler::ForegroundExecutor` → `scheduler::LocalExecutor` to reflect
that these are session-pinned queues rather than "the main thread" (a
dedicated session runs on its own thread). GPUI's wrapper
`gpui::ForegroundExecutor` and the `foreground_executor` field/method
names are unchanged to keep blast radius small.
- `LocalExecutor::new` now takes an explicit dispatch closure, so the
routing decision (default session, dedicated thread, or something else)
lives at the construction site.

### Tests

- `TestScheduler` side: round-trip, `!Send` future, `Send` closure
capturing shared state, inner `executor.spawn`, determinism under `many`
seeds, drop-cancels-future, detached child runs after root completes.
- `PlatformScheduler` side: real separate thread (blocking syscalls
don't stall the test), `!Send` future output, drop-cancels-future,
thread tears down after work completes, detached child outlives root.

cc @as-cii

Release Notes:

- N/A

---------

Co-authored-by: Antonio Scandurra <me@as-cii.com>
Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2026-05-29 15:58:02 +00:00
Bennet Bo Fenner
18051ab399
agent_ui: Remove unused rule APIs (#58080)
Removes unused `@rule` mentions and unused APIs from `prompt_store`

Follow up to #58067

Release Notes:

- N/A
2026-05-29 15:27:28 +00:00
Bennet Bo Fenner
654a864b3a
git_ui: Do not include git commit prompt twice (#58062)
Now that customisation of this prompt was moved to `AGENTS.md`, we don't
want to load the customised prompt, and instead just use the default
prompt, so that we don't include the same instructions twice

Release Notes:

- git: Improve performance when generating git commit message with LLM
2026-05-29 15:27:21 +00:00
Conrad Irwin
5fba9b0cba
Enable gain normalization on collab (#58036)
This updates our WebRTC configuration to enable gain normalization in
the
recording flow, which should help normalize the effective volume of
participants
in calls.

Release Notes:

- Added volume equalizations to participants in collab calls
2026-05-29 15:21:53 +00:00
Smit Barmase
906bff792c
agent_ui: Show permission popover when inline prompt is above the viewport (#58081)
Follow up to https://github.com/zed-industries/zed/pull/57632, uses
changes from https://github.com/zed-industries/zed/pull/58061

Previously the floating permission popover only appeared when the inline
permission prompt was scrolled below the viewport. It now also appears
when the prompt is scrolled above the viewport, with the scroll button
pointing in the right direction.

Release Notes:

- Fixed the agent permission popover not appearing when the inline
prompt was scrolled above the viewport.
2026-05-29 15:11:25 +00:00
Agus Zubiaga
c029cc4354
Bump convert_case to v0.11.0 (#58000)
Bumps the workspace `convert_case` dependency from 0.8 to 0.11 (already
in the tree) so the `zed` binary includes only one copy.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-29 15:00:32 +00:00
Richard Feldman
0bafd1938c
Add handoff feature flag (#58024)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
Adds the handoff feature flag with staff disabled by default, giving the
rest of the auto-compaction stack a rollout gate without changing
behavior for users outside the flag.

Release Notes:

- N/A
2026-05-29 14:10:02 +00:00
Lena
b7b1d1a2c7
Duplicate Bot: Reduce noise (#58074)
Release Notes:

- N/A
2026-05-29 13:28:35 +00:00
Smit Barmase
a1d2ef6514
gpui: Add item_is_above_viewport and item_is_below_viewport APIs to ListState (#58061)
In prep for handling the above-viewport case in
https://github.com/zed-industries/zed/pull/57632, which currently only
handles below case.

This PR adds `ListState::item_is_above_viewport` and
`ListState::item_is_below_viewport` methods, which report whether a
given list item is entirely outside the current viewport. Both return
`None` when the list has not measured enough layout to answer.

Release Notes:

- N/A
2026-05-29 13:24:59 +00:00
Jakub Konka
81f818aa86
nix: Go around a linker issue on Darwin (#58070)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [ ] Unsafe blocks (if any) have justifying comments
- [ ] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [ ] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-29 12:22:37 +00:00
Bennet Bo Fenner
f49be143f3
agent: Do not render diagnostics in diff (#58052)
Release Notes:

- agent: Fixed an issue where diagnostics would show up in agent panel
diffs
2026-05-29 12:18:57 +00:00
Bennet Bo Fenner
3eab273b85
Remove rules library (#58067)
Rules library has been replaced by skills, so we can safely remove it

Release Notes:

- N/A
2026-05-29 11:59:18 +00:00
Mikhail Pertsev
85f8bf7393
editor: Extract header and mouse out of element.rs (#57472)
cc @SomeoneToIgnore

## Summary

Follow-up to [this
comment](https://github.com/zed-industries/zed/discussions/55352#discussioncomment-16961889).
This extracts the buffer header and breadcrumb rendering helpers out of
`element.rs` into a `header.rs` and mouse related things to `mouse.rs`

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-29 11:51:17 +00:00
Jakub Konka
da87558cc2
Revert "Improve ChatGPT subscription response resilience" (#58035)
Reverts zed-industries/zed#57891
2026-05-29 11:23:56 +00:00
Anthony Eid
6bca2136a1
agent: Batch streaming edit operations (#58037)
## Summary

While profiling agent sessions that make a lot of `edit_file`
operations, I noticed the LSP `textDocument/didChange` handler firing
excessively. Looking into this, I found out that the streaming edit
pipeline was applying each `CharOperation` from `StreamingDiff` as its
own `buffer.edit` transaction, and every transaction emits a
`BufferEvent::Edited` event. Each event can trigger several other
expensive events depending on whether the buffer is being rendered in an
editor or is registered with a language.

For example, there are `didChange` LSP events, the editor's on edit work
(matching brackets, bracket colorization, code actions, outline), and
more. A single `edit_file` could trigger hundreds of these at the higher
end in a single synchronous app update, which would block the foreground
thread for a bit and cause Zed to drop frames.

I fixed this by collecting all of a chunk's `CharOperation`s and
applying them in one `buffer.edit` call, so only a single
`BufferEvent::Edited` event gets emitted. This is safe because
operations are non overlapping by design of streaming diff (the edit
cursor only advances).

## Why this wasn't caught earlier

The cost only fully appears when a buffer is both registered with a
language server and rendered in an editor. Without that, most of the per
transaction observers never run, so the existing `edit_file_tool`
benchmark (which ran the tool against a bare buffer) didn't surface it.
I reworked the benchmark to open the edited buffer in an editor view,
register a fake language server with per edit diagnostics, and lay out a
frame, so it exercises the same cascade as the real editor. I also added
a larger fixture.

## Results

Measured with the `release-fast` profile on the reworked benchmark:

| Fixture | Initial file | Before | After | Improvement |
| --- | --- | --- | --- | --- |
| `tiny_function_rewrite` | 1.4 KB | 31.1 ms | 12.1 ms | −61% |
| `small_function_rewrite` | 3.0 KB | 42.4 ms | 19.3 ms | −55% |
| `medium_many_small_changes` | 4.6 KB | 309.2 ms | 151.5 ms | −51% |
| `medium_insertions` | 4.6 KB | 171.8 ms | 126.1 ms | −27% |
| `large_multi_edit` | 44 KB | 9,549 ms | 919 ms | −90% |

Self-Review Checklist:
- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the UI/UX checklist
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:
- Improved agent's edit file tool performance
2026-05-29 09:49:55 +00:00
Agus Zubiaga
ef5da3ccc2
Remove unused --nc flag and nc crate (#55962)
The `nc` crate and `zed --nc <socket>` flag were added in #34577 to let
the Claude Code integration spawn the running zed binary as a
netcat-style bridge between stdio and a Unix socket for its MCP server.

That integration was removed in #37120 in favor of the external
`@agentclientprotocol/claude-agent-acp` npm package, which dropped the
only caller of `--nc`. The flag, its dispatch in `main.rs`, and the `nc`
crate itself were left behind and have been unused since.

Nothing in the Zed codebase spawns `zed --nc` anymore, so remove the
flag and delete the crate. The unrelated `--askpass` netcat bridge (in
the `askpass` crate) is unaffected.

Release Notes:

- N/A
2026-05-29 08:16:05 +00:00
Jakub Konka
a3669a29e6
nix: Fix dev shell on Darwin (#58032)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [ ] Unsafe blocks (if any) have justifying comments
- [ ] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [ ] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-29 08:10:32 +00:00
Shuhei Kadowaki
3d9852ae04
lsp: Fix duplicate workspace/didChangeConfiguration notifications (#56853)
Editing the `lsp` section of `.zed/settings.json` caused two identical
`workspace/didChangeConfiguration` notifications to be sent to each
language server, e.g.:

    // Send:

{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"jetls":{"code_lens":{"references":true},"completion":{"method_signature":{"prepend_inference_result":true}},"full_analysis":{"debounce":2},"inlay_hint":{"block_end":{"min_lines":25}}}}}}

    // Send:

{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"jetls":{"code_lens":{"references":true},"completion":{"method_signature":{"prepend_inference_result":true}},"full_analysis":{"debounce":2},"inlay_hint":{"block_end":{"min_lines":25}}}}}}

`maintain_workspace_config` observed `SettingsStore` directly while
`on_settings_changed` also fed the same loop through
`request_workspace_config_refresh`, so every settings change drove the
refresh loop twice and sent two identical
`workspace/didChangeConfiguration` notifications to each language
server.

Drop the in-loop observer and drive the loop from
`external_refresh_requests` alone. Settings changes still arrive via
`on_settings_changed -> request_workspace_config_refresh`, and toolchain
activation continues to use the same channel.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

- Fixed language servers receiving duplicate
`workspace/didChangeConfiguration` notifications on every settings
change.
2026-05-29 07:31:00 +00:00
Seth Wood
46845bf2f5
edit_prediction: Skip cloud Zeta requests when not signed in (#57615)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #57962

## What

When a user is not signed in to their Zed account, the edit prediction
system was still attempting a cloud API request on every keystroke. The
request would fail deep in the credential check
(`CloudApiClient::build_request`) with a `ClientApiError::NotSignedIn`
error, which propagated back up and was logged at `ERROR` level via
`.log_err()` at line 2389 of `edit_prediction.rs`.

## Why

The sign-in check was happening too late — only discovered after async
tasks were already spawned and the full request pipeline entered. This
fix gates the request at the top of `request_prediction_internal`,
returning `Task::ready(Ok(None))` immediately before any inputs are
built or tasks spawned.

The guard mirrors the existing `is_cloud` provider check already used
elsewhere in the same file, and only applies to the `Zeta` model on the
cloud provider path. Local providers (Ollama, `OpenAiCompatibleApi`) and
other models (Mercury, Fim) are unaffected.

Note: I haven't added a test for this — testing the early-return would
require mocking auth state, which I wasn't sure was worth the complexity
for a one-liner guard. Happy to add one if preferred.

Release Notes:

- Fixed noisy `not signed in` error log on every keystroke when not
signed in to Zed

---------

Co-authored-by: Oleksiy Syvokon <oleksiy@zed.dev>
Co-authored-by: MrSubidubi <finn@zed.dev>
Co-authored-by: David3u <3udavid@gmail.com>
2026-05-29 07:21:30 +00:00
Finn Evers
e4b81180c1
component_preview: Clean up Component trait (#57731)
This primarily
- requires components to have a description as well as a preview
(especially having no preview makes no sense)
- implements some basic previews where missing
- adds a scrollbar to the preview navigation 

with a sadly large diff due to reformatting (less indentation 🎉 ), but
very little changes at its core.

Release Notes:

- N/A
2026-05-29 07:06:57 +00:00
Jakub Konka
aeb5d6d7ff
ci: Reinstate run-nix label in addition to run-bundling (#58034)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [ ] Unsafe blocks (if any) have justifying comments
- [ ] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [ ] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-29 06:01:22 +00:00
Jakub Konka
486e5f7cdd
ci: Remove garnix substitutor (#58033)
Release Notes:

- N/A
2026-05-29 05:56:42 +00:00
Yauhen
d3070bbc0d
dev_container: Respect runServices for Docker Compose (#56293)
This PR fixes Docker Compose dev containers starting every service in
the compose project, even when `devcontainer.json` specifies
`runServices`.

Previously, Zed deserialized `runServices` but did not use it when
invoking Docker Compose. The startup command was:

```sh
docker compose ... up -d
```

With no service operands, Compose starts every enabled service in the
project. This means unrelated services are started even when the
devcontainer config asks to run only the primary service and its
dependencies.

The fix propagates `runServices` into the Docker Compose build/start
path so Zed invokes Compose with the requested services:

```sh
docker compose ... up -d devcontainer
```

Compose will still start services required by `depends_on`, but
unrelated services are left untouched.

**Reproduction**

`.devcontainer/devcontainer.json`:

```json
{
  "name": "Run Services",
  "dockerComposeFile": "../compose.yml",
  "service": "devcontainer",
  "runServices": ["devcontainer"],
  "workspaceFolder": "/workspace"
}
```

`compose.yml`:

```yaml
services:
  devcontainer:
    image: ubuntu:24.04
    command: sleep infinity
    volumes:
      - .:/workspace
    depends_on:
      - database

  database:
    image: postgres:16-alpine
    environment:
      POSTGRES_PASSWORD: postgres

  unrelated:
    image: nginx:alpine
```

**Expected**: Zed starts `devcontainer` and `database`.

**Before this fix**: Zed also starts `unrelated`.

**After this fix**: `unrelated` remains stopped.

Closes: https://github.com/zed-industries/zed/issues/57279

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- Fixed Docker Compose dev containers starting services not listed in
`runServices`.
2026-05-29 05:12:28 +00:00
Richard Feldman
e5f5767d2c
Preserve terminal spinners in thread titles (#57983)
Summary:

- Preserve spinner/logo prefixes from live terminal titles when terminal
threads have custom titles.
- Store raw terminal titles and custom user titles separately,
recomposing display titles on demand.
- Keep spinner prefixes out of the title editor while preserving
sidebar/search display behavior.

Tests:

- cargo test -p agent_ui
test_terminal_custom_title_recomposes_with_live_spinner -- --nocapture
- cargo test -p agent_ui
test_terminal_title_editor_excludes_spinner_prefix -- --nocapture
- cargo test -p sidebar
test_agent_panel_terminals_appear_in_sidebar_and_search -- --nocapture

Closes AI-304

Release Notes:

- Fixed terminal thread titles to preserve animated spinner and logo
prefixes after renaming.
2026-05-29 03:47:05 +00:00
Mikayla Maki
12aacf3cea
Add skill share linking (#58009)
Added because I'd like to get this skill Danilo made without having to
upload a gist

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-28 23:04:44 +00:00
Anthony Eid
b32570d931
terminal: Move PTY spawning to the background thread and retain exit status (#58004)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
This PR does two things 

1. Move PTY child spawning to the background executor. Forking to spawn
the terminal child was taking between 10-70ms on profiles I was looking
at, which caused frames to be dropped because it was on the foreground
thread. This should fix issues such as #57574 where the miniprof from
this comment showed terminal creation blocking the foreground thread as
well.
https://github.com/zed-industries/zed/issues/57574#issuecomment-4546858817

2. Stopped overwriting alacrities exit status with `9` on
`AlacTermEvent::Exit` event handling. Before we get the exit event,
alacritty emits `ChildExit(status)` with the real status, which we used
to overwrite with exit status 9 when handling the AlacTermEvent::Exit.
This was an easy fix so I added it in this PR when I noticed the bug.


Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

- fixed dropped frames caused by agents or users creating new terminals
2026-05-28 22:24:22 +00:00
MartinYe1234
59d8766f35
Show progress when deleting worktrees (#57751)
Adds a progress indicator to the worktree picker so users get visual
feedback while a worktree deletion is in progress, which can take
several seconds.

Closes AI-239

Release Notes:

- Added progress feedback in the worktree picker while deleting a
worktree
2026-05-28 21:52:53 +00:00
morgankrey
27c566c212
Relicense Zed source code under GPL (#57948)
## Summary

This moves the remaining first-party AGPL surface to GPL, a less
restrictive license for these components. Apache-2.0 components are
unchanged.

Changes:
- Updates the `collab` crate from `AGPL-3.0-or-later` to
`GPL-3.0-or-later`
- Removes the root AGPL license file and first-party crate AGPL symlinks
- Updates web, documentation, Flatpak, README, and terms references to
reflect the GPL/Apache licensing split
- Updates the open-source component example list in the terms and
regenerates the RTF copy; no other terms changes are intended
- Adds guardrails so first-party crates cannot declare AGPL licensing or
carry `LICENSE-AGPL` files

Release timing: preview during the week of June 1, 2026; stable during
the week of June 8, 2026.

## Residual AGPL/Affero references

- `LICENSE-GPL`: GPLv3's own compatibility clause; unchanged official
license text.
- `crates/json_schema_store/src/schemas/package.json`: generic npm
package-license schema value, not Zed licensing.
- `script/check-licenses`, `script/new-crate`,
`script/licenses/zed-licenses.toml`: guardrails that reject or warn
against reintroducing AGPL.

## Verification

- `script/check-licenses`
- `script/generate-licenses`
- `script/generate-terms-rtf`
- `script/new-crate license_probe_for_gpl`, then discarded generated
crate
- `script/new-crate license_probe_for_agpl agpl` fails as expected
- `mdbook build docs`
- `./script/clippy`
- `git grep -n -I -E "AGPL|Affero"`
- `git diff --check`

Release Notes:

- The `collab` crate, used to implement Zed's collaboration backend, is
now licensed under the GPL instead of the AGPL. The AGPL license is no
longer used in the zed repository.
2026-05-28 20:19:17 +00:00
JannikRosendahl
2bba4e2220
Make notebook cells follow global font and markdown styling (#57567)
Notebook cells are currently not responding to changes in font-family
(`zed://settings/buffer_font_family`) and font-size
(`zed://settings/buffer_font_size`).

Currently, `MarkdownCell` and `CodeCell` create and set a
`TextStyleRefinement` on their `Editor`, creating copies of font-family
and font-size in the process. As a result, these do not get updated when
the global font-family or font-size change.
By not setting the refinement manually and letting the editor handle
these value instead, these values get updated when the global settings
change.

This behaviour is consistent with how the inline repl already behaves
and in my opinion is according to the users expectations.


After Review: this PR changes the rendered preview of MarkdownCells to
use the themed MarkdownStyle instead of an empty Markdown Style



Before:


https://github.com/user-attachments/assets/e70b9346-8fa1-4d66-aa85-07e987c56ff2

After:


https://github.com/user-attachments/assets/4957e20e-9b5b-4cb9-a9df-3b33538bc686



Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
  - not sure if this needs test or how they should look like...
- [x] Performance impact has been considered and is acceptable

~~Closes #ISSUE~~

Release Notes:

- Fixed notebook cells not responding to appearance settings changes
2026-05-28 20:14:34 +00:00
Lee ByeongJun
ec64ba3e69
time_format: Show compound "N years, M months ago" for blame entries (#57973)
The relative date format introduced in #47687 floors to whole years, so
a commit from 22 months ago is shown as "1 year ago". It would be better
to align with `git blame`'s own behavior so it can display timestamps
like "1 year, 10 months ago".

reference:
c69baaf57b/date.c (L189-L205)

Self-Review Checklist:

- [X] I've reviewed my own diff for quality, security, and reliability
- [ ] Unsafe blocks (if any) have justifying comments
- [ ] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [X] Tests cover the new/changed behavior
- [ ] Performance impact has been considered and is acceptable

Closes #57907

Release Notes:

- Fixed inaccurate humanized date in git blame, e.g. a commit from 22
months ago no longer shows as "1 year ago"
2026-05-28 19:43:30 +00:00
Marshall Bowers
b3d93d4474
anthropic: Fix serialized representation of Effort::XHigh (#57985)
This PR fixes the serialized representation of the `Effort::XHigh`
variant, as it should be `xhigh`, not `x_high`.


https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking#adaptive-thinking-with-the-effort-parameter

Release Notes:

- Fixed using `xhigh` thinking effort with Anthropic models.
2026-05-28 18:20:11 +00:00
Richard Feldman
a6b0ee9f36
Add Claude Opus 4.8 support (#57984)
<img width="627" height="752" alt="Screenshot 2026-05-28 at 1 20 22 PM"
src="https://github.com/user-attachments/assets/0a7825f0-73c5-49e9-b59a-83924a45de98"
/>

Adds Claude Opus 4.8 for BYOK providers, including Anthropic fast-mode
handling and Bedrock/OpenCode model definitions.

Closes AI-336

Release Notes:

- Added Claude Opus 4.8 BYOK support
2026-05-28 17:45:54 +00:00
nullstalgia
3bb2f2a61d
diagnostics: Prefer activating diagnostic under cursor (#52957)
Update the behavior of both `editor: go to diagnostic` and `editor: go
to previous diagnostic` in order to ensure that, if there's a diagnostic
under the user's cursor that isn't active, it is first activated, with a
subsequent call jumping to the next or previous diagnostic,
respectively.

These changes also update how diagnostic activation handles the
situation when the global diagnostic renderer is not registered, as we
used to not update the active diagnostic group in that situation.
However, we now rely on it to determine whether the user's cursor is
already in the active diagnostic, with some tests now failing, so we now
default to an empty set of blocks for the active diagnostic group when
no global renderer is registered.

Release Notes:

- Update both `editor: go to diagnostic` and `editor: go to previous
diagnostic` to prefer activating the diagnostic under the cursor before
jumping to the next or previous diagnostic, respectively

---------

Co-authored-by: dino <dinojoaocosta@gmail.com>
2026-05-28 17:30:36 +00:00
Joseph T. Lyons
24fd1015f0
Sort guild members case insensitively (#57977)
Aligns list sorting with the community champions list.

Self-Review Checklist:

- [X] I've reviewed my own diff for quality, security, and reliability
- [ ] Unsafe blocks (if any) have justifying comments
- [ ] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [ ] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-28 16:55:35 +00:00
morgankrey
ef5606bb61
Improve ChatGPT subscription response resilience (#57891)
## Summary

This started from #57636, after we saw ChatGPT subscription/Codex
requests stall over the past week. OpenCode v1.15.11 shipped related
resilience fixes for the same class of Codex subscription endpoint
issues, so this ports the relevant pieces into Zed's native ChatGPT
subscription provider.

When Zed asks ChatGPT/Codex for a response, sometimes the server
connection can get stuck before it even sends the first response
headers. Before this PR, Zed could wait indefinitely, which looks like
OpenCode/Zed “stalling.”

This PR makes Zed:

- Wait up to 10 seconds for the server to start responding.
- If nothing comes back in that window, treat it as a temporary
network/API failure.
- Let the existing retry logic try again instead of leaving the user
stuck.
- Send a stable session-id header so OpenAI’s Codex backend can
associate requests with the same Zed agent thread.
- Add tests to make sure:
  - stuck-before-response requests time out,
  - normal slow streaming responses are not cut off,
  - ChatGPT subscription requests send the right session header,
  - the agent retries this kind of failure.

intended user-facing result is: fewer “the assistant is just sitting
there forever” failures when using ChatGPT subscription models.

## Verification

- cargo test -p open_ai responses
- cargo test -p language_models openai_subscribed
- cargo test -p agent test_send_retry_on_http_send_error
- cargo check -p open_ai
- cargo check -p language_models
- cargo check -p agent

Release Notes:

- Fixed ChatGPT subscription requests stalling indefinitely before
response headers arrive.
2026-05-28 16:41:26 +00:00
Joseph T. Lyons
5abe4bcbc6
Merge community_champion_auto_labeler into pr_labeler (#57898)
Self-Review Checklist:

- [X] I've reviewed my own diff for quality, security, and reliability
- [n/a] Unsafe blocks (if any) have justifying comments
- [n/a] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [n/a] Tests cover the new/changed behavior
- [n/a] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-28 15:56:02 +00:00
Bennet Bo Fenner
d139a871db
copilot_chat: Fix error when using GPT models (#57958)
We were including reasoning blocks twice. This matches what the Copilot
API does (that is only including the reasoning items in
`output_item.done`).

Before:

```
    {
      "type": "message",
      "role": "user",
      "content": [{ "type": "input_text", "text": "Run ls" }]
    },
    {
      "type": "reasoning",
      "id": "khgBW2vnLWOFgjxAybXdEtL47dY9XaqKW6yvy2JHSaWVeONUkhuQXcDTWwmnbpKKzlzYuaZsO2YUyvieidwC+RbAfD0e2ZjipDSLTdF7DZM6yLUpAwSgV+09d234G93pdg2VRW7dlgcllPCbVeor9V7bZQUOifDp/vU0VIrKVNFjDgigPYojwSZ476o/rTLvTBSlKt1IbkqyLLiix2gokE1lR+DpmG54UiynMFX2WtOVtZP+BriKGfbw3QQF+gz5HQDZuU/Pc7L2CzHTwQVsmTXljeJI9BTZjuiDBVaDZf4ILQiuQ33wVvh3jC5la47lC8jbqlYpmRirsxgBb/vcAFWnUKxcJh/Bgs3tnNk4TKXTeoYhZ+71YGSv2jFnK0JzJ9iZB8w4bkZvHE6136HnSg==",
      "summary": [],
      "encrypted_content": "NgKURnC7g/R/NdnmWu2i70W/hCirYyUWxv7e6Q8CsrTJ1KkUL+e17Frav+KvL1LBzvd0ZklRlmGvLgSUNIW2X+4RG9Ff4m+z660xT00wUqsD5GcAJCTs11k9RPHE0uUJ5gs6EMDNgbgBhj9CcArEbiQEJuzwuRMTINv4lM63aVUcvYfY3R5qQnYm+ixEJr1gQyNmK/WUMvQgZRThjYeMt2/bYtRCPDvKQSXBIrh+tFUMPj9p/ohHSOVRnuwJc7X4JvP0flR0rrqIdZoNXYJ0Jyw2Bm1yz0iy15ckxczFmagqI6r81herd6ZIWA+CrosvLbZujIVUQMYAe0rdESN/kqzgUhqJl6XLShevrWJ+RGxUM5HuICQAuFhMRF6PRBwO+BN4tYi4VEXSBwrR0Z1uhdkPzc1UXPOJFIky25nrhPu0T+k7b3eYWSEAVHvzfsKBC8fKUIFDO8hhSo7LcKrMQx0ADHT4zbbLehF7dP4cR2LgQV2WtPW/AFV160EvR3EySpBSkTgrZ7W3bySYq3PYTbUk7eOYWyauNPD1RBqFIAU51WLlhyagFcfskRjDk7TIEtJnODz4EZvlbwXM1cBt6CwnO9ehy2GWSTSkQbizvNZBr1L8aYI1b3u/nB9ezoM4lOQwPcd1f8g858WlTA1GuIMjDEBoBGNnMolHzn7f64VJZMjinAoyKWFBOLh3U+tQUvPGFpyq9mnDraWwMnkQtsi9NZTbf78kLg5+QRvAepbmCmcdvHuPKZYzFk8BebgQyhiob4ONa2n5q6EmOGKGqkqbAB0dUfjE1+tMsR+rYeF7VLYBjGapYGqJZeYW4wsg6rYrQv1VdleFejmgM7toWDlsd/COEDPAMEZ0mM2doPxfB6JEuxld4T5wJO1uzYA5dVI5ImgnHIXkljjH88/TVSZ0VgOlogsf7qeh8reGSJ4btIReVFZxuHQX7c13Isn+65F0RSx+NCJHh87vuJBE7nGLP0CLNzc7B9pqAQA3G9yVlrBrv3eT1NR0Ha4vah7/1/DNvqzDvBdIzUQB67IpOhQo4gBMUVisXIZHT2U38eusaGry4j7L3SSspBF0cnOsVzdZL34LYgqsl8LxMCgDGOyTyMqKS/PgKofTNtDrwMWKnNApTRdMdrjbDmqY1hNKM6CmQ033XWztToUu5tDW/Mgl5pfUmgdFjVCSHfUpFsNLEdx32LlL1oO/hPofLA8k1SNVBJx55wez73gcWYugkVIV9wPyTEu0tbcOEya1A4CrSDqLf8kbwZ/fhotKjqdKulkGnIhfs0lVathO8ENylCgH0in+jBUZ+b14MMLnBjIK5xV9IXo+rZ4fBsXzwLxYAeUa+Z0VWCZJnjzFhlMUpQZHQxWG83nHTpWcRxE1/JEVBaTi/gJA6VAMaetpEfwoxjdB8Ydh/E2WTlQzqFn1tNdibp46Km1PfwIyeVwwQX2DEkvlN7qDBAQEPdR10/qBEjKXTj1hHZaS+yJt4w5RuCr2/YdUzKz6rDf7oc885NUgTFZtYh+VDVrLl3qYIQyQuAp0h5Hv35cYOnNG2NnxOC+Z79vCK6xoSE5fIYUArzuSyqIrzXR7F4IDgmikH7KplkcLYBP6s9Coc+c2s+WMSUPq1hzZDweWfqnsR22BYzsTTwGAMul3AUurqevcljUmpKsZTOSmuyKt/of2hTzHOrFRiZy5ttFe8T+0CycaediLmx5tdJsPWvJEnIHICaawUxC8O0Mk0shHfKKnR9EYifkBn4ygrm6jPKEE1b7egZ668oPtWIDKxD/HHDCbh1qED7u4PD0i4abZTNwhSpzrB0SOWCNoSYDzEqp37LSlgYubAZJztk8sxmKYWeXwdeZBiuJmNqkclHWQxbPJLXymFlcz1C0LCitwKLLMyUWHWFy47kRXDkH1eYsXgxYANRbKfGHLLxPO+N5cJszqv1DFwOje5PkBxgOAfuYVjO3DtIDqIfdJluNeUPBdphGqm/X3FvUBn3pm6tOQgteaMGwJblN8ewuPY6of+AsubruQ0io0kpDLKCje++9negmo9qMxgVRugEduEs/RlZOJ8E3bAz1DT+nlrCytWXWr9UM8xB8igPlL9cHzeKBv1QFmW/CpHjfjzCqU5fldeDGJ0t2Bu5reLMoNC35hwcD+8K63ePjwb1clMMFFj9fdmGnXUOF+c+twj5xesSLxMB6O4abd+soVb8bHdn49z9w626Br5epVs3Qwf/HNiWDU8CVKgyb9ccj6s8/ETP24zDHUu5EQ517yqm18GPvy/nsyasiH5w0xoZxc1Ba8+KsSYvs+DkPujidl2Wgl3MUJh96R7c8BVTEchPFJoWe1YDDbaEp4aySDApVyTm/YVgG/nACmvPtfUlUgVN7BqR2PxMwZ1FmEYOxxFPEoKDtO9pNx76wsT8H+yKe8VCoguqe9HaXcHm6/pVKfM2Wgkmg5eRtNeFVMjE0Ejys/a4htzma5gPO4xqGc2bH9JxeP94qYkjIe4xp9I55+5vbztXAwsYF00aTQ4K9c6gLugHMbJLLQhoC1AK7ZHPh4XhXIdUBgc00oodMcKR5PaUzFqTZF0XzLCWjhpYiWE4VzmHKjatoPfwQHNsH0mwNWdtFS6UWthUEMvY6azjfZpfyJrry9Pj4RnHvJIaBchGciTo4QSWSh6GmTYspX7QCveF0sVzkC0o0jRtosQ/b6osH1PqOmsDqEw9IWFZCOET0CSyys0Vry2HGa+U1vvQAs8p2ek0va3BKFITeBPkACRhLaZlWHpWjZ5F/AqwUR+Eguo330j3Wk9lQ7F2VV+GAS+ZgDh8Az56ed4kTlA8rHs7NliqKr8nqFUBEWiWDWUlhjEgXtrt9G2/jpFIU/3UF0M1NFQ94F28mTmA=="
    },
    {
      "type": "reasoning",
      "id": "Vj0QJZMbDF6p5SHwQfzk3FCBzFmXvd6ERARDR68BTo93WJpORDWhnaR2CPiPRIMhbvt9fI5VjqR5O5mUXtciw+V74B9petxJMcM1OtsoQqeQr0Go2QjQAYquGV/Q+1n/+x1HjWXRGTzHkwplhZ1KYL9juwFF8PZke8wnl6wQRyUUTjLFxdxNMfl6kTBYAU4RBjnJiz16dSrvzaRLbHc0ZgezT7IqJOIA8paZvwncwY6ftXEcdYTKYUDGChK7aUcVt+RyCGtSl81ayzmoCdv0SGCJBsnX5BuG1GmINkDHEpwTNHteYXmSDxLKgzNIwIBJxR1Z5WMBEZDI4OQWNzLTuKppCOYv0E7UxCclSwkGKEof8yDBVvgdFfwfoFIvFJKJiy/niUDuzKbqW14CtodaLg==",
      "summary": [],
      "encrypted_content": "X9oCaUyulbIo0tcHBAzE0sZ5BIO4OcIAgr/YrjmI24ANFOTxxb16GEwwXGjDQFi402ii2nCbSh0vcaZPmZjbwydelCo0rXC0rkWlKgxPJnIioeVZwKN4GBEW+bgbKkGu1TspCCoJE/Eppkk1qOSkZ1PcuLynj06aDUkTyPMK2ZGQQps3H/TvJ5LHES5bX3Op5pejamPKa4QB7wXIn710j1CIjUyaXgz2aal6OwYHLoZJJyv4TFvmgzP9Wt5eggzpBOFQnJ1tzw+a1/3D41GBogS1UdW0J77bdolkFgoARWAib4uyW9hAiL6+H0qrXH9/FHa9d5WU+XmWG9celRK1zSpV0IXqC1DUOoVeHm4RNRVD/Pwnt2NkFPwpdGOUG4kaDyIxf7rN4Lw571tW8x19DP/lLaqKzWY4BQpzUC3OgL9EX0ky2PhWmYP5b9Zu3U5fhbemvjf7jQ20gzSnWUlyGe5y7ckzBIzhYVxkLGLX1j1CkMnK7Po329Gt1GfPlymOODUOxkxd8e+ZwH66/S19fbgNFdfDFMCGsTtsN1A7YuHYC1KsKnaitpe07t3kWsKkSsaUUyPX1HDW1613QEe56bU45uLQ294p46iFg6xuzPQSfP/ynqExh7xf+dOU+9Iq5kEXh4R3UbTUaVqPlAHdzEYhJflkezVG4cDN3qkUJa1Sh2YtV1Cc2zjEqmfSkhEiOHpthrNHFTC9nHmaV9BR7jMxll7McuoRqjBm/aungGsheXUaTq0+xJUqm/FG5tuQyAga+M+g5/PC9JPcXOXeRpF+43PNnzqNUByA0evd/6qSM2Z8twL7wl5zsGzJuPS9mVVU8zUFUXxH7qJ3aSIu9azwRtNODPn25oIr6yuJlh4yKSYXz48r5/Ak+xYEJTXucm5KJZqffXl72YwjG0M4yk2A0m/mRvVY9G1GpBLWcNw17GBh/JsXv1NLz7FZ3SQLhRGE4yE53/780oMimLWBLcVSG7gyCCnz4+geFOf4mtO1hkQ4bP0n1w7qBZUM9KJUTMHvnXIlL9lR4m6Mgs9hMM/Bx24if7qdHVN/o0bD0cSUiiZsa9jiiibqsumnLte1d3rSjavpc6zkVy/K1H6uXV/YoNS1mn2xdxnLW6W8HD9XU6Luzbg0QjYoIb6BXtb1DTHRq3Op64xIBNmxYMX3OzS5ev+GRFrOBMqj0IJYmnM82gozAMhoHXapW8GNSccxx9/Br6NigwjUV5u/vlTBVqsEB3A7ondmw4S1ZqXuvkBJSg7CoYEKbUK8gf4kNeMD7YpXyFXh0SXVZV+tznKMnjw8aIdXGM6hwQXjym6F9WM4vPah5RrGR7XKyfJQGl4Ouj4PERZyIJcNWHPwBp0rpv+/Vu2el/arBIv5hoal15W2c9rhCg+vA5lrWfPlIRUi4dT/k8RytFSlRlcm0hnwDADaEr4wqwahwwtcSHOPP0eOZYjLEr6PGYdgSxaDnKgtPZHvoTI6zMGIlVMMCVS+46datGm15/3RbjxLXHGCkc0VQGkGfSDjJkgLGHk9LQ/ydzJELZuT392JmDMr1eKKCzVyg4EH4gAFkBKq/B4x7dK7hRJtrbMitdaa0+Llp/McrQADNuG1UKjmz5StXi6ocwDdOr37sQpq1JAYy5ahae85EuZ1WM41n6p5IRQKUG9r786boBYy0zFTIcSjbpNqTteXRWTJOdGQqiW+vxUhmfOTRre3tsszbPNnxhaX2J06EIPSdOXx6T/bBrRkG5b2dwtud/QPbomMXqD17xAsgBQO5+8bKL3Mcks76Y/6yVScSpFVi3tgWsB2+tvY8onE7xsrrhkSSZZhQYJ8wI0D5HJVegs/M7bYTPPMT0r+wAhnC3AMdlbtwrCrDKBwwSUNjc2IoAy7kRfdQWr2+E0Do9xcFKy4cHUXPi/wegiOHCGUimWc9MQNWNrGN5+EpmDyc0kgq4iVvyce/MG61nYXuOxuU4Vr2Q4zRp2xi3ZZAQf6zEMZ5kWGRUJxUO5pZkoQex4JmKdMkyF6xgG25aeqw4ppsiXB0O1puAHhlehCjJcyIDYDoKAToM3u6bfjGj1tWH+t32WTMKZ97JOV8+zi2xHB/qDccxDietNpObIfnEEXn/ZVy6KJ/M9IRLHBy98Ma1LgydXBK68YM/BLUx7NH10JjQStrVSpE4JITADZ7Bw/wi2QSFju7oC6+qtF2pz0FThWXBWHErfYEciAcu2FjNTLH44mjFGF7NC4ETZfo7kBeMq46q4WMzAY6YbkFNvudsYnHO360n/IxTl596944LuVTO2RdqS7DwE5RLVj8hWmlaVTuiDoBhWchHTtcFrk0DCpxRl76Tx8b3LLkotMq3GZfgC0HO1Gz9pJiwseBqg8xS5Kzc6qxKWJbVbqccVz5gGVGSXLiyqI40NO/gQEGNYpTC+0pydbOOgQ1mQEJtpE/6nzBkw7GjDmfmy/1uuU9wQiVt5NLor3dlNH2ClqLnoV5rdZoisDY5Z9vXhp+5qe19S4Qm2WY+h324UzrtGzQgaYdGFRAxS+iki5PSGJEpJnelDCYSzkFoIUGprOzzai0j0jPLG9ueAlKEiMmgz1NV7s5Dx49u2bNGEgfGaKP3o6ey05DrYM19iwfrcGHlzgfj4x1qmx3WzKTwAxL/RFbi788dK3ggn95vWtre1adMpJ8RB9vDnSXmp9gRrosnIgNfMhRhTKZ+3NcvF3sCPJXHe9SLmecUwvXVIE944TihHsLPvpVWRe7RjDFbn3K0TSneJ0Eyf6E5vecRt1S16qHl7zkacxFnl+tL6NOOHC6BvU4anxhX5i0AHOKRxFs4WUf+Nyrl+plURz1lxgoOQBFjrkNHuqSY712AcI8i0KS9SbjlGcRdik6J5gz3fniw=="
    },
    {
      "type": "function_call",
      "call_id": "call_kYosdPp77arTCMT4vxKotORr",
      "name": "update_title",
      "arguments": "{\"title\":\"List project files\"}"
    },
    {
      "type": "function_call_output",
      "call_id": "call_kYosdPp77arTCMT4vxKotORr",
      "output": "Session title updated"
    }
```

After:

```
 {
      "type": "message",
      "role": "user",
      "content": [{ "type": "input_text", "text": "Run ls" }]
    },
    {
      "type": "function_call",
      "call_id": "call_JAUQ6fRiJGBC2WxHjMuG3opI",
      "name": "update_title",
      "arguments": "{\"title\":\"List project files\"}"
    },
    {
      "type": "function_call",
      "call_id": "call_lMZRlqGeJ8sSiITJ4xesgMwt",
      "name": "terminal",
      "arguments": "{\"command\":\"ls\",\"cd\":\"calculator\",\"timeout_ms\":5000,\"allow_network\":false,\"allow_fs_write\":false,\"unsandboxed\":false}"
    },
    {
      "type": "reasoning",
      "summary": [],
      "encrypted_content": "4pRqoArHBOJL2K5USHgwuzGfxOyi4l1sFCcQwTsSxBs4nZJQr/4ELKHuqUK1xCJTO3e9vfPGvZDZtxTiV/ghrF5tNOjl0dxg7G77d2i1DiRm+Wn3dAgr5K1ssOgBMl07252Ukvs7B4zLJ89ovulGe0r/VM6+fg4JeNXYS9lE/whkZnib77lvqLvTsFDHUJkROCMsuUeNEGzavCf5xxG9qhSJQ8ieT2TcNiaTpHAdl4rkCi2JIyOPR6zCQjrptLy3RTJGBzSrChVViHi0v5tnMx0H6vcBR2d3SqYNqvaDfFkCNVOqHeYojSKLNjHoZizx/m9KLM/ZkVdgopsu5DaQpEWXLBzY+JbBkTnNSi+pUVMCCnHaj8UDGqsseCUv3JwsuM0udLFPaWYe+YnjjD340CtmtIG+jjQv80TMSzi9XtTpKS+cuC4OXHSLWMltDJEneoa4JfIKYQObO/xpZ7TwDsxXhR5BVo0KY5UGKcXOAogaLxIS2W5B8mqMfHvjeQtMzfnHjVuLHku/AL6M59SWd4MREFyjXROLLcFyPzwaCR4WrNeMrbIf+8WvzT7HlfD7ImV3McAEwEF/tYrj4pR8zfAMLiUfFCnRQptgoQFwZsm6HxfezPi1Nr4oMjPqlOll6px7lT++b+Tdb1qc6696uZ49MIkUuP4XOfpe6U0p0UqSZHQXQ6WFXm7G5DYHW2JW+sEYc62d1isRbdwoYDt7kVMslmKRCaYdFB0+TpuBOUn/Fpg20PtZe1Zsl6m5feafsLPmS+JypWDpbWj1/XAtCGRKQO0O0soW/QxmOZixvAMJjiym5+6TVeKdJCS1Objyk0faSDAFdlNQVP22B97VaW2aHTP2x1vsSI0Sqvd13iBu8v2oAaeLbfvuGeei9g8V/iEG4rLfK6zDvH8W7OJUoJBEveSSaCzMDzMChTkF5B+naP4PpH9b5rFRepxbWY8eU0Ab3N58aR7G53yXgdwJWBPisqcCj9xp+avO7e/WGro0T30htST0KHH++nVVdHLSb0ZxDec/h866EgMEkh2WrztcwRn5ovb4qwvpbJCSr0cKtyJAV6BT8/z+Pm513Lfe+B64OWAtbBmRasByYtjXSt+GmQ//DJed73UL+OUQm2v9vc9InG0AYWjVC7FRWfVMukTQDapEpo6LULbfbSEI7Z7Qa4eBYUSvoD+OiCHuGrrR+PyliiaGOIIa9/K4/hZQbhABnheVXlxN1igGniZoqtd546oghVGz89pEVO8Dv2zjw3U9+RAQwS2x90Sjqkx7F4Nr+heoXjySlghbSSoxB0ckeQUsn0JIElGH9pQxRgqIQ4swjlVaRtyrXrDK3zX3N6TCFBOlMdmlSZFSo/Gj0oaNM0Aot69DN5MnxkburXnaE7gsLH5xdBfaw8FABZUXxV2hJq/cpB/u9STqdLS6yCySFLwEWCmAn9V3mCClq5nxH3DqhTwo/vhQefQaT9n6+y9NfNV2svIOC+YRMKYbGsmcpxlZ/io/Y453C4Uy83Fl0UHbLieI+y5+Rm7Xs3VK3mcqwMSCniMvK7jiHdiizD9ONQ7KmyAhQyXbPjn/tZXgIHfMEf1RkWaHHxWn6QHSFdAmj+9IYY0owDm64WrmyvVZSuzz795Sicsek+VZZ85fGiemxuNRdkInxbQCC6rG8ZGyWIYTXgGXOrR+t0FvHO/04+RQUOvIJgYm/Bcauprw2oa2ipNQMLg/cdP5wi4pqUHlZiSF0HTixDiRaHS8w/XO0DYqDIKnBikZNmpT57DiiQwIPHK9BNpMi5M/2oQpQVdzCT7GrdPGNWJrl6p7oQCPtOFPQpuGyKvv8sVHMKkqj8l3olK09eimPl67SaLNhaY69+O8b9DXp3nJpWO8jgPfY6cKXPrH+8Sk6nwzc0uTlinZDMLsedJAdmoNObBgq+aqzRrUjuokBat3Ob498Dqajt4VWCpJ2+vO6obcTjML3s2jiU7G8yNrY8SGnMTWuR48GhjcCaub+rtk0zS2f2QVGElucJ1Ev6Fg4INqTjd8PdMLn0KcGF15JZSg3z/SZhxuyI+E6NAeAt/Xnribt4o7gTaqoYm6IMvi7zJ66TSWWp2bjEDJCwabifQRNtMw4UMtCiWNAv3pxG2M+jVFTsJrQ5xVEjoQMwYXWMCoTgtR+3/dK7J0xhkxdx5KweGCdb46pOM5tpSPcyxcr7NOgmpr5ovDKr+vbHK75deKGoQDGogOZehBKLW2ZHGmdAV6RJrtjGE4Ag1MjdO1pk3xAXY9w0tFSIy/YdX85l7pBV0xn719xH0RFG/9T95N9gxBtQAhuAfe9OVobctAZLVOMtQkMyaiPvkI32p6ehe/QD8+b29XhB0iO8HB0bvns2/gQwpIUQeZ3HB8Ef1QJxG3TUbKOP4Ud9XyDwYK4G1ExHXYmHB7bQcl0PrDaW+Au1We+3dmq6TUk/6GndJEVhcMS6rXt42T9cA7pE/8kTVmmea05rZwHyVSDoo8LbxMriAKoZfVi28Kg5rHuGdNOHvPxsa6+BJNY7XW41Q9ck2Pr0wt+aJYgMW9M4jRnQfqUY5QHiaxKYl/1/zASEg76QS1M8YDpjFytyb1S8a1bB5rTO+Ljplf/ubXO4i/tWtnJCecD8iBTnWG6dHBe0DFtDnBtRqFZFmz/stxk1Ti8OxR9klpPVUcuUoLYDwxvblDZnn53/knxbp5cbeIWDAVludm+JqwoycxXvJtbYUPzY2zpU7HcFoPFDHqy3LOvP1QgdWGcWCVplNwbSv2FQiWBfzf08e+o6IjOvk9B19hNbkI1lcAhjN16JlO0j/A2zKWsas3ixGAW216Wx0Z+hdQL6ISzCecQqolLhD/Nqb+MB5kigmH1gtmNQFQn2mrAF4TkoAZr3dS3gsHuq7vnOTGf/GN5g+gLGZvcK0IsG4kUpnja9miPif1bmhXkuHYZxANmr5B3O7vDGl9uirPK/vigLojwz8/bC0lhy4kpayLS1PaG3LBYhsDYKrDVot6R/ogrpfcB620pLN16KkutLIzW/ahDWgIVL/kNvFEIvvmSVuo"
    },
    {
      "type": "function_call_output",
      "call_id": "call_JAUQ6fRiJGBC2WxHjMuG3opI",
      "output": "Session title updated"
    },
    {
      "type": "function_call_output",
      "call_id": "call_lMZRlqGeJ8sSiITJ4xesgMwt",
      "output": "```\nCargo.lock\tCargo.toml\tCLAUDE.md\tsrc\t\ttarget\n```"
    }
```

Closes #57776

Release Notes:

- copilot: Fixed an issue where using GPT models would return an error
in `invalid_request_body`

Co-authored-by: cameron <cameron.studdstreet@gmail.com>
2026-05-28 15:28:26 +00:00
Xiaobo Liu
830414004a
settings: Apply VS Code minimap default when importing settings (#56483)
When importing settings from VS Code, the minimap is now enabled by
default (matching VS Code's behavior) even if the user hasn't explicitly
set minimap-related options in their VS Code settings.json.

Previously, if `editor.minimap.enabled` and `editor.minimap.autohide`
were absent from the VS Code config, Zed would leave minimap at its own
default ("never"). Since VS Code defaults to minimap on, this caused a
mismatch for users expecting their VS Code experience to carry over.

Closes #56297

Release Notes:

- Fixed apply VS Code minimap default when importing settings

Signed-off-by: Xiaobo Liu <cppcoffee@gmail.com>
2026-05-28 15:25:54 +00:00
Anthony Eid
bc64e1f955
copilot: Fix auth db fallback (#57764)
This PR uses https://github.com/zed-industries/zed/pull/57758 as a base
and adds tests, cleans up the comments, and checks changes the database
query used in auth.db to include oauth key.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

- Fixed GitHub Copilot Chat showing an empty model dropdown for users on
newer Copilot SDK builds

---------

Co-authored-by: Alexander Shlemov <eodus@users.noreply.github.com>
Co-authored-by: cameron <cameron.studdstreet@gmail.com>
2026-05-28 15:00:31 +00:00
Bennet Bo Fenner
d74e47ea51
git_ui: Fix creating worktree not possible if default branch unavailable (#57918)
Follow up to #57704

This makes sure that we offer a worktree creation option in case
resolving the default branch fails

Release Notes:

- git: Fixed an issue where worktree creation would not be possible if
resolving default branch fails
2026-05-28 14:15:40 +00:00
Smit Barmase
f0ed342c19
markdown: Add frontmatter metadata block rendering (#57845)
Adds opt-in rendering for Markdown frontmatter metadata blocks in
Markdown Preview and agent markdown.

- Simple `key: value` metadata blocks now render as a two-column table,
while more complex metadata falls back to a code-style block.
- Metadata block content and key/value rows are parsed in the parser
step, and the request layout simply takes over rendering.

<img width="1288" height="436" alt="image"
src="https://github.com/user-attachments/assets/b35b949a-8bc4-47db-82ef-ed835e9ac06f"
/>

Release Notes:

- Added support for rendering Markdown frontmatter metadata blocks in
Markdown Preview and Agent Panel.
2026-05-28 13:47:58 +00:00
KyleBarton
92b0efeee0
Update dev-containers.md (#57901)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes N/A

Release Notes:

- Improved docs for dev containers
2026-05-28 13:36:39 +00:00
Cameron Mcloughlin
4d6a3c7e11
gpui: Application::inaccessible() (#57954)
Provide a way to prevent GPUI from creating AccessKit adapters, and
enable this in Zed.

This will allow us to test AccessKit support in Zed without rolling it
out more broadly, while we gain confidence in the implementation in
GPUI.

I've also added a log statement

## Motivation (i.e. a mini post-mortem about the #56065 panics)

Merging #56065 caused some nasty panics in nightly. This was caused by a
bug in the logic for selecting a focus node for a `TreeUpdate`.
AccessKit panics when an invalid `TreeUpdate` is provided.

My assumption was that, since Zed uses no a11y APIs, and also that
essentially 0 zed users would have AT apps running, that merging this PR
would have no effect on the behaviour of Zed itself. However, two issues
combined to cause the panics:
- It seems like many people (everyone?) on mac gets the activation
callback called by accesskit_macos. A quick search suggests this might
be due to password managers searching for password fields, but not sure
how true that is.
- The bug in question related to *forgetting to check* whether a node
used a11y APIs, so we *were* pushing non-empty `TreeUpdate`s

As a (probably temporary) defensive measure, I added a function to try
to detect the bad cases and fix them. But it would be lovely if this
could live in AccessKit itself, since it would mean we wouldn't have to
do the check twice (once in GPUI, once in AccessKit). This would also
help prevent drift when updating accesskit versions if new invariants
are added.

We also cannot protect against this with `catch_unwind`, since we use
`panic=abort`. So our only option unfortunately is to temporarily
disable AccessKit until we know our implementation is stable.

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-28 13:36:24 +00:00
Ben Kunkle
b8c853a63d
ep: Fix agent edits triggering edit predictions due to diagnostic refresh (#57832)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

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

---------

Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>
2026-05-28 13:27:55 +00:00
Ben Kunkle
8042408df4
ep: Collect data for staff in Zed Industries repos (#57733)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-28 12:59:56 +00:00
KyleBarton
518502e5ef
Respect override command in devcontainer (#57204)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #56357

Release Notes:

- Fixed bug where devcontainers were not respecting override_command
2026-05-28 11:22:41 +00:00
Daniel Martín
6049ceaecf
Auto-scroll hover popup while selecting text (#57518)
Selecting text inside the hover documentation or git popups did not
scroll the popup when the drag passed the visible area, so any text
below the area could not be selected with the mouse.

The popup's container already had a `ScrollHandle` wired to its
scrollbar and wheel scrolling, but the inner `MarkdownElement` was
constructed without one. That left it in the default
`AutoscrollBehavior::Propagate` mode, which routes drag-autoscroll
requests to the editor-wide autoscroll listener, which is a listener
that does not exist inside a floating popover, so the requests were
silently dropped.

Passing the popup's existing `ScrollHandle` into the `MarkdownElement`
switches it to `AutoscrollBehavior::Controlled`, which scrolls the
popup's own container directly during a drag. The markdown preview view
already uses this same pattern.

Release Notes:

- Fixed hover documentation and git popups not scrolling while selecting
text with the mouse

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable
2026-05-28 09:55:14 +00:00
Smit Barmase
6726b15fce
terminal: Forward Shift navigation keys to alternate-screen programs (#57479)
I ran into this while using lazygit: the Shift navigation keys were
being captured by Zed to scroll the terminal buffer instead of being
passed through to the program.

Capturing them makes sense in the normal terminal case, where the user
wants to scroll and Shift has no other meaning. But in alternate-screen
TUIs like lazygit, less, or neovim, terminal scrollback isn't relevant,
so we can forward these keys to the program while it's open.

Release Notes:
- Fixed Shift+Up, Shift+Down, Shift+Home, and Shift+End in terminal TUIs
like lazygit, less, and neovim.

---------

Co-authored-by: John Tur <john-tur@outlook.com>
2026-05-28 09:34:57 +00:00
Ben Brandt
bedfe32fdc
agent_ui: Clarify multi-root agent warning text (#57874)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-28 08:19:11 +00:00
Ben Brandt
58f84cf041
agent_ui: Basic terminal agent telemetry (#57259)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
Some best-effort tracking of an allowed-list of agents (to avoid
grabbing sensitive data) just to get basic data on general usage
patterns.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A

---------

Co-authored-by: morgankrey <morgan@zed.dev>
2026-05-28 04:49:12 +00:00
Pulkit Saraf
60374460f2
helix: Fix a cursor position in helix_select mode` (#57610)
Closes #56493

In Helix select mode, pressing `a` after a selection (e.g. `v a`) placed
the cursor one column too far to the right.

Bound `a` to `vim::HelixAppend` in the `helix_select` keymap so it
matches the behavior in `helix_normal`, and added a regression test for
the `v a` case.

Release Notes:

- Fixed cursor placement after pressing `a` in Helix select mode.

---------

Co-authored-by: Smit Barmase <heysmitbarmase@gmail.com>
2026-05-28 02:36:38 +00:00
Richard Feldman
b141288fb0
Persist terminal tempdirs by thread (#57878)
Summary:
- Store a lazily-created sandboxed terminal temp directory on each agent
thread.
- Persist the tempdir path and remove it when deleting archived threads.
- Update sandbox prompt wording to describe per-thread tempdir reuse.

Tests:
- cargo fmt --package agent --package agent_ui --package zed
- cargo test -p agent db::tests::test_sandboxed_terminal_temp_dir --
--nocapture
- cargo test -p agent
db::tests::test_delete_thread_removes_sandboxed_terminal_temp_dir --
--nocapture
- cargo check -p agent_ui -p zed

Release Notes:

- Improved agent terminal sandboxing to preserve temporary files across
commands in the same thread

---------

Co-authored-by: MartinYe1234 <52641447+MartinYe1234@users.noreply.github.com>
Co-authored-by: Martin Ye <martin@zed.dev>
2026-05-28 00:58:56 +00:00
Cameron Mcloughlin
777e16dd1f
gpui: Fix panic with invalid focus IDs (#57885)
We were missing a check when setting the focused node ID, causing a
panic in accesskit's internal validation logic. Fixes the bug, and adds
some defensive logic to help mitigate potential future issues.

You can reproduce the panic by:
- turning on a screenreader
- launching zed
- opening a menu and pressing tab

This change fixes it.

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-28 00:02:37 +00:00
Richard Feldman
f0341c96a1
Wrap agent terminal commands in macOS Seatbelt sandbox (#57431)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
Stacked on top of #57430.

When the `sandboxing` feature flag is on (macOS only), agent-run
terminal commands are launched under `/usr/bin/sandbox-exec` with a
per-command Seatbelt policy:

- **Reads:** any path on the filesystem.
- **Writes:** each project worktree plus a per-command `$TMPDIR`.
- **Network:** blocked.

The model can request relaxations on individual calls via three new
input flags on the `terminal` tool:

- `allow_network: true`
- `allow_fs_write: true`
- `unsandboxed: true`

Each one triggers a separate always-prompt user approval (bypassing any
`always_allow` rules, since escalation is a stronger trust boundary than
the baseline command approval). The flags are silently ignored when
sandboxing is off, so the model can't surreptitiously change runtime
behavior by setting them in the no-op case.

The per-command tempdir is provisioned regardless of sandbox state so
the model can't infer whether the sandbox is in effect by looking at
`$TMPDIR`.

The Seatbelt config file's lifetime is tied to the `Terminal` entity via
an opaque RAII handle (`SandboxConfigHandle = Box<dyn Any + Send>`), so
cancellation paths drop it automatically.

### Notes for review

- The writable scope passed to the sandbox is the project's worktree
paths plus the per-command tempdir, **not** the resolved `cd` working
directory — `cd` is model-controlled, and using it as the writable scope
would let the model widen its own write permissions outside the project.
- The new tool flags are always present in the JSON schema (with
`#[serde(default)]`), even when the sandbox prompt section isn't
rendered. The system prompt only documents them when the section is
present, so the model shouldn't try to use them when it's not — but the
schema doesn't actively reject them, just ignores them.
- I opted not to add an end-to-end test for the escalation prompt path:
the existing `FakeThreadEnvironment` ignores the new params and toggling
the feature flag in tests is more wiring than felt worth it for a first
cut. The pure-function pieces (`sandbox_approval_title`, schema,
deserialization) are covered, and the sandbox crate itself has
end-to-end tests that actually invoke `sandbox-exec`.

Release Notes:

- N/A

---------

Co-authored-by: MartinYe1234 <52641447+MartinYe1234@users.noreply.github.com>
2026-05-27 21:38:17 +00:00
Richard Feldman
ffbda20db1
Render terminal sandbox section in system prompt behind feature flag (#57430)
Stacked on top of #57429.

Adds a new `sandboxing` feature flag (off for staff by default) and a
single source-of-truth helper `sandboxing_enabled(cx) = cfg!(target_os =
"macos") && cx.has_flag::<SandboxingFeatureFlag>()`. When the helper
returns true, the agent's system prompt gains a new `## Terminal
sandbox` section that:

- Lists each worktree's absolute path as a writable directory.
- Describes the per-command `$TMPDIR` scratch directory.
- States that outbound network access is blocked.
- Documents the three per-command flags (`allow_network`,
`allow_fs_write`, `unsandboxed`) the model can request to relax the
sandbox.
- Tells the model the section is stable for the duration of the
conversation.

When the flag is off, the section is omitted entirely — no mention of
sandboxing at all.

No behavior change to terminal execution yet; that's the next PR in the
stack.

Three new tests cover: section omitted when `sandboxing: false`, section
rendered with all worktrees + flag docs when `sandboxing: true`, and the
zero-worktrees case.

Release Notes:

- N/A

---------

Co-authored-by: MartinYe1234 <52641447+MartinYe1234@users.noreply.github.com>
Co-authored-by: Martin Ye <martin@zed.dev>
2026-05-27 21:11:27 +00:00
Albert Bogusz
c3b9cacc0e
Update git2 to 0.21.0 and add support for SHA-256 object formatted repos (#57587)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [ ] ~Unsafe blocks (if any) have justifying comments~ (N/A)
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior (didn't add new test for
parsing SHA-256 - not sure if would be desired)
- [x] Performance impact has been considered and is acceptable

Closes #24070

Upgrades git2 from 0.20.1 to 0.21.0 with the `unstable-sha256` feature -
adds ability to open and work with git repositories using the SHA-256
object format. `Oid::from_str` now detects 64-char hex strings to parse
SHA-256 OIDs correctly.

Also adapts to breaking API changes in 0.21.0:
`Remote::url()` and `Commit::message()` both now return `Result`.

Release Notes:
- Added support for opening SHA-256 object format git repositories
2026-05-27 20:59:01 +00:00
Richard Feldman
5ec1ce7cd0
Add sandbox crate with macOS Seatbelt integration (#57429)
Adds a new `sandbox` crate that wraps shell invocations under macOS's
`sandbox-exec(1)` with a Seatbelt policy built from per-command
permissions:

- Reads are unrestricted.
- Writes are restricted to a caller-provided list of directories (plus
the standard `/dev/*` write targets).
- Network access and unrestricted filesystem writes must be opted into
per command.

`wrap_invocation(program, args, writable_dirs, permissions)` returns the
new program/args plus a `SeatbeltConfigFile` RAII handle that deletes
the on-disk policy file when dropped — callers hold it for the lifetime
of the spawned command.

No callers yet — this is the first of three stacked PRs. The second
wires the sandbox state into the agent's system prompt behind a feature
flag; the third wires the actual wrapping into the agent terminal tool.

The macOS-only dependencies (`tempfile`, `anyhow`) are gated by
`target.'cfg(target_os = "macos")'` so the crate is empty on other
platforms.

Includes 14 tests covering both the generated Seatbelt policy text and
end-to-end behavior (actually invoking `sandbox-exec` and asserting
reads/writes succeed or fail per policy).

Release Notes:

- N/A
2026-05-27 20:35:32 +00:00
Martín Gaitán
6e58a92713
Fix typo in command palette reference (#57869)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable
2026-05-27 20:03:27 +00:00
Agus Zubiaga
887e3782a8
Remove leftover test a11y label (#57868)
Removes a leftover test label added by #56065 

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-27 20:02:48 +00:00
morgankrey
652f13c7ce
Document Gemini caching behavior (#57864)
## Summary

- Document that Zed-hosted Gemini models do not use Google context
caching
- Clarify that Gemini usage is billed only as input and output tokens,
with no cached-input price
- Link to Google's Vertex AI context caching and zero-data-retention
documentation for background

## Validation

- `script/generate-action-metadata`
- `mdbook build docs`

Release Notes:

- N/A
2026-05-27 20:01:57 +00:00
Richard Feldman
1226e28dd3
Add zed-cherry-pick agent skill (#57833)
Adds a project-scoped agent skill at
`.agents/skills/zed-cherry-pick/SKILL.md` that walks an agent through
cherry-picking a merged PR into Zed's `preview` or `stable` release
branch — including the case where the automated `cherry_pick` GitHub
Actions workflow failed due to a merge conflict.

Captures the conventions enforced by `script/cherry-pick` (branch
naming, PR title/body format) and the gotchas around discovering the
current channel→branch mapping, non-interactive git in agent
environments, and worktree index locks.

Release Notes:

- N/A

---------

Co-authored-by: Martin Ye <martin@zed.dev>
Co-authored-by: Ben Kunkle <ben.kunkle@gmail.com>
2026-05-27 19:46:15 +00:00
Anthony Eid
cbaf8e4d9d
Speed up StreamingDiff::push_new part two (#57849)
Follow-up to #57772.

While comparing the `edit_file_tool_streaming/medium_insertions`
benchmark in Criterion and xctrace, I noticed the DP scoring loop was
spending most of its time on inlined `Matrix::get`/`Matrix::set` access
in `StreamingDiff::push_new`.

This changes the loop to split the previous and current score columns
once per DP column and then index those column slices directly. This
keeps the scoring algorithm the same, but hoists the column offset
calculation out of the inner loop and gives the compiler clearer
aliasing information between the immutable previous column and mutable
current column.

In xctrace, the hottest DP scoring line dropped from 10,407 samples
before to 9,409 samples after on
`edit_file_tool_streaming/medium_insertions`, and total
`StreamingDiff::push_new` leaf samples dropped from 10,800 to 9,822.

This is consistently faster in the end-to-end `edit_file_tool`
benchmark, and gives a small speed-up for the targeted workload without
changing the scoring algorithm.

### Results

Benchmarked with `release-fast` against a clean baseline using
Criterion’s `before_slice` baseline.

#### `streaming_diff_push_new`

| Fixture | Before median | After median | Change |
| --- | ---: | ---: | ---: |
| `tiny_function_rewrite` | `7.6317 ms` | `6.4951 ms` | 10.8% faster |
| `small_function_rewrite` | `45.961 ms` | `44.839 ms` | No significant
change |
| `medium_many_small_changes` | `99.694 ms` | `104.83 ms` | 5.2% slower
|
| `medium_insertions` | `95.909 ms` | `83.093 ms` | 13.5% faster |

#### `edit_file_tool_streaming`

| Fixture | Before median | After median | Change |
| --- | ---: | ---: | ---: |
| `tiny_function_rewrite` | `1.1110 ms` | `1.0617 ms` | 7.1% faster |
| `small_function_rewrite` | `2.4554 ms` | `2.2751 ms` | 7.1% faster |
| `medium_many_small_changes` | `87.272 ms` | `77.065 ms` | 11.5% faster
|
| `medium_insertions` | `92.469 ms` | `87.478 ms` | 5.9% faster |

The lower-level `streaming_diff_push_new` benchmark is mixed, but the
end-to-end `edit_file_tool_streaming` workload improves across all
fixtures.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-27 19:33:04 +00:00
Vlad Ionescu
c19c89a30a
opencode: Model updates (#57792)
Two model updates:
- **Free**: Big Pickle now has a max output tokens of 32k as per
49991c8f8f
- **Go**: added Qwen3.7 Max as per
4f1d5c511a
and
1554a5a82e (diff-a7ee7cf35b40335095a44cfaac16041313c36322cd14544ddad0289ce69131ab).
Tested this successfully by running a simple "_rename this variable for
me. add a function. delete the function_" test

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- OpenCode: updated models (added Qwen3.7 Max, updated Big Pickle token
counts)
2026-05-27 18:55:23 +00:00
Cameron Mcloughlin
1d029c5ff5
gpui: Accesskit support (#56065)
GPUI AccessKit integration

This PR is replacing #51097 , and is much more limited in scope. This PR
*ONLY* adds AccessKit support to GPUI, and doesn't touch Zed. Once this
lands, we can start adding aria attributes to Zed's components.

This PR is the first step to addressing #41138 .

Release Notes:

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

---------

Co-authored-by: John Tur <john-tur@outlook.com>
Co-authored-by: Zed Zippy <234243425+zed-zippy[bot]@users.noreply.github.com>
Co-authored-by: Bennet Bo Fenner <bennetbo@gmx.de>
Co-authored-by: Agus Zubiaga <agus@zed.dev>
2026-05-27 18:17:59 +00:00
Marshall Bowers
bf4e559347
feature_flags: Only respect feature flag overrides for Zed staff (#57860)
This PR is a follow-up to #54206 to make it so we only respect the
feature flag overrides for Zed staff (or when running a development
build).

Previously just the UI portion of the feature flags was disabled for
non-staff, but manipulating the settings file by hand would still allow
setting overrides that would be respected.

The only other setting on the "Developer" page of the settings UI was
the performance profiler. This was previously only available for staff,
as the entire "Developer" page was limited to staff, but it seems
reasonable to allow non-staff to see this.

Release Notes:

- N/A
2026-05-27 18:16:04 +00:00
Danilo Leal
6472f018a6
skill_creator: Use the status toast for confirming creation (#57855)
This PR uses the status toast for the Skill Creator confirming action as
opposed the regular message notification. Aside from it looking a bit
better, it's also auto-dismissed, which is preferred in this case.

Release Notes:

- Improved skill creation toast confirmation by making it
auto-dismissed.

---------

Co-authored-by: Martin Ye <martin@zed.dev>
2026-05-27 18:09:52 +00:00
Oleksiy Syvokon
7ae24463e1
Fix multibuffer chunk splitting at UTF-8 boundaries (#57641)
Don't panic when a diff transform boundary falls inside a multi-byte
UTF-8 character. Round split points up to the next char boundary and
advance past any transform boundaries skipped by that adjustment.

Closes FR-16

Release Notes:

- Fixed a crash when deleting words near inline diff boundaries
containing multi-byte characters
2026-05-27 17:57:15 +00:00
zed-zippy[bot]
710228e3dd
Bump Zed to v1.6.0 (#57858)
Release Notes:

- N/A

Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>
2026-05-27 17:43:55 +00:00
Anthony Eid
6afac23e4a
Speed up StreamingDiff::push_new by 30-36% (#57772)
## Motivation

Miniprofs of Zed dropping frames showed foreground thread stalls of
711.56 ms, 641.01 ms, and 221.99 ms from the `edit_file_tool`. The new
benchmark isolated `StreamingDiff::push_new` as one of the expensive
phases so this PR aims to speed it up so we can avoid dropping more
frames in the future.

## Benchmark methodology

I had an agent create a Criterion suite with four deterministic Rust
edit fixtures: tiny localized rewrite, small localized rewrite, many
small changes, and helper block insertions.

Benchmarked with:

```sh
cargo bench -p streaming_diff --bench streaming_diff --profile release-fast -- --warm-up-time 1 --measurement-time 2
```

The benchmark binary was also recorded under `xctrace` CPU Counters to
inspect CPU samples before and after the change.

## Results

`StreamingDiff::push_new` improved across all fixtures:

| Benchmark | Before | After | Improvement |
|---|---:|---:|---:|
| `tiny_function_rewrite` | ~10.81 ms | ~6.91 ms | ~36% faster |
| `small_function_rewrite` | ~51.02 ms | ~35.39 ms | ~31% faster |
| `medium_many_small_changes` | ~130.71 ms | ~83.83 ms | ~36% faster |
| `medium_insertions` | ~120.52 ms | ~79.90 ms | ~34% faster |

The `xctrace` baseline showed samples in `Hash::hash`,
`RandomState::hash_one`, `HashMap::insert`, and
`RawTable::reserve_rehash`. After replacing the map with two `Vec<u32>`
row buffers, the hash table frames disappeared from the top samples.

The speedup comes from removing hash work from the DP inner loop and
replacing scattered hash table probes with contiguous row buffer access
(better cache hits 🏎️). The trace did not include direct cache miss
counts, but this layout is likely more cache friendly because it
replaces hash table access with a continuous line of memory (the
`Vec`s).

Release Notes:

- N/A
2026-05-27 17:41:11 +00:00
Lukas Wirth
9b4737b0d7
Introduce a skill for #[gpui::test] (#57806)
Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-27 17:06:30 +00:00
Thomas Boom
9a7a5d685d
docs: Update tracking issue link to discussion in README (#57793)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-27 16:56:21 +00:00
Richard Feldman
b49e5f19b9
Avoid duplicate migrated skills (#57853)
## Summary

- Track existing skill file contents and instruction bodies before
migrating Rules to Skills
- Skip writing migrated skills when an equivalent skill already exists
- Cover duplicate detection across differently named skills

## Tests

- cargo test -p prompt_store rules_to_skills_migration

Release Notes:

- Fixed duplicate Skills being created when migrating Rules.
2026-05-27 16:46:54 +00:00
Tom Houlé
32f2593047
client: Refresh cloud models on websocket reconnect (#57528)
Until now, the cloud-hosted model list was only refreshed in response to
events that exercise the LLM token (a `UserUpdated` push, an
organization change, or `PrivateUserInfoUpdated`). If a user wasn't
actively using AI features around the time we shipped new models, the
list could stay stale until they restarted Zed.

This is the second step toward fixing that, after #57078 made the cloud
websocket reconnect on its own. We now treat each successful (re)connect
as a hint that the server state may have changed, so possibly new model
definitions will be available, and trigger a model list refresh.

The trigger is a new `Client::cloud_connection_id()` watch that bumps a
counter each time the websocket handshake completes.
`CloudLanguageModelProvider::State` subscribes to it and, on every tick
after the initial `0`, schedules a debounced refresh (with jitter, so we
don't have all active clients trying to reconnect at the same time after
we deploy in cloud).

Closes CLO-713.

Release Notes:

- The list of Zed hosted models is now refreshed automatically, without
requiring a restart
2026-05-27 16:39:19 +00:00
Cameron Mcloughlin
63f725e8d6
markdown: Merman (#57644)
Big PR that replaces `mermaid-rs` with `merman`.

Adds a new crate `mermaid_render` that exposes a simple API for
rendering a mermaid diagram to an SVG string.

## Why is it so big?

Some of this is explained in the crate-level docs for `mermaid_render`,
but the short version is:
- `mermaid-rs` emits "good enough" SVGs for most use cases. It also
ships with a reasonable default theme
- `merman` emits *very accurate* SVGs, but with borderline unusable CSS
- Most of the new code in this PR are a series of passes to clean up the
output SVG by:
  - Injecting good CSS
  - Fixing issues in the `merman`-generated SVGs
- Tweaking the final result to avoid issues with `usvg` and `resvg`,
which are what will eventually be used to rasterize the SVG
- This code *could* be much smaller, but the following design decisions
made it take a lot more code:
  - Using a real XML parser instead of basic string manipulation
  - Avoiding allocating strings in as many places as possible

Because of this, the design is as follows:
- First, construct a `merman` theme from the user's theme, and render
the mermaid to an SVG string
- Post-process - each step is roughly a `fn(Iterator<Item =
Event<'short>>) -> Iterator<Item = Event<'short>>`, where `Event` is the
type for events produced by `quick-xml` (a pull-based XML parser)
 

## Note for reviewers

It's a big diff, sorry 😅 happy to pair review. 

The new crate is essentially a leaf crate - it does technically depend
on `gpui`, but only for the `Hsla` and `Rgba` types. Extracting a new
`gpui_color` crate felt like overkill for this already-very-big PR.

Each post-process pass is in its own submodule, and has a doc comment
explaining the before/after. Note that bugs in this code are perhaps
less serious than bugs in other parts of the code:
- The code has been thoroughly audited for potentially-panicking code
paths - as far as I know, there are none (excluding some `.expect()`s on
calls to `write!` with `String`, which is [cannot return `Err`][string
write])
- A bug in this code (given that it will not cause a panic) will, at
worst, result in an invalid diagram being rendered, or simply falling
back to showing the code.
- The current `mermaid-rs` renderer *already* does this in quite a lot
of cases, sometimes showing outright misleading information.
---

Some eye candy:
| Before (`mermaid-rs`) | After (`merman`) |
| - | - |
| <img width="1227" height="340" alt="image"
src="https://github.com/user-attachments/assets/58d6904e-64bc-478a-8d67-f75ad4ccbc9e"
/> | <img width="1169" height="482" alt="image"
src="https://github.com/user-attachments/assets/d4bb9cd5-240f-4bf6-ba7f-4862049ed8b0"
/> |
| <img width="842" height="564" alt="image"
src="https://github.com/user-attachments/assets/1668a50d-68f6-4145-8cef-359e4c6a4589"
/> | <img width="869" height="543" alt="image"
src="https://github.com/user-attachments/assets/2ec1a7eb-fc3c-4392-b577-1ad52396b87c"
/> |
| Failed to render | <img width="822" height="1123" alt="image"
src="https://github.com/user-attachments/assets/a97308a1-6b3a-48b6-9778-abf3507c6ad3"
/> |
| <img width="252" height="517" alt="image"
src="https://github.com/user-attachments/assets/dbf86274-004a-4ee4-be89-cc6ff4f6cf35"
/> | <img width="361" height="680" alt="image"
src="https://github.com/user-attachments/assets/8457b6ed-3ca9-4bed-9496-60388ba08206"
/> |
| <img width="550" height="1050" alt="image"
src="https://github.com/user-attachments/assets/c21b8513-fb86-422e-870a-015e0add783a"
/> | <img width="819" height="1148" alt="image"
src="https://github.com/user-attachments/assets/ca646165-302d-41aa-8da5-39e89c96ebb7"
/> |
| <img width="1218" height="225" alt="image"
src="https://github.com/user-attachments/assets/3006a1bf-efe6-46f5-9f9d-289a3fdf9adc"
/> | <img width="1118" height="965" alt="image"
src="https://github.com/user-attachments/assets/90d76098-bf3d-4c69-bc9b-00dd9cbf6990"
/> |
| <img width="800" height="584" alt="image"
src="https://github.com/user-attachments/assets/f688693b-df3d-4514-b105-ccaa3874e40c"
/> | <img width="1153" height="417" alt="image"
src="https://github.com/user-attachments/assets/eeb05f58-7184-4321-a47b-ea3cc53f0d02"
/> |
| <img width="539" height="464" alt="image"
src="https://github.com/user-attachments/assets/0076105d-eef9-4011-9b9a-581918575e49"
/> | <img width="638" height="556" alt="image"
src="https://github.com/user-attachments/assets/72a51966-c296-48d0-b1e2-66835b1a0d5b"
/> |
| <img width="607" height="430" alt="image"
src="https://github.com/user-attachments/assets/d3530814-532b-41ed-a2b6-fd5740d8db58"
/> | <img width="725" height="489" alt="image"
src="https://github.com/user-attachments/assets/c43687d9-f426-4cb8-8a45-23a3c0070c8f"
/> |
| <img width="869" height="577" alt="image"
src="https://github.com/user-attachments/assets/b607f3fd-136c-4f41-a88e-596520e276b9"
/> | <img width="784" height="586" alt="image"
src="https://github.com/user-attachments/assets/22305a64-b4d0-474a-b6f6-8973f2bca933"
/> |
| <img width="1214" height="263" alt="image"
src="https://github.com/user-attachments/assets/183ff0df-a6f3-470c-b271-8099c3e33044"
/> | <img width="1195" height="632" alt="image"
src="https://github.com/user-attachments/assets/868bcb7f-62c6-4d20-ba1e-3f25f8165fff"
/> |
| <img width="573" height="597" alt="image"
src="https://github.com/user-attachments/assets/6414e409-b879-4892-8ef6-89489219b56f"
/> | <img width="578" height="608" alt="image"
src="https://github.com/user-attachments/assets/8ac71b03-f603-4e32-87aa-b993317d4e29"
/> |
| <img width="543" height="472" alt="image"
src="https://github.com/user-attachments/assets/1f19929c-cf07-4287-b9cf-b976eea9faaa"
/> | <img width="760" height="599" alt="image"
src="https://github.com/user-attachments/assets/73926075-db47-4eb1-854e-7aee30522684"
/> |
| <img width="1205" height="219" alt="image"
src="https://github.com/user-attachments/assets/5f3dc936-4b89-44f4-a00a-4dbc47e06504"
/> | <img width="1133" height="349" alt="image"
src="https://github.com/user-attachments/assets/e62901ff-9d75-4fde-a30e-974ff2e783b1"
/> |


Release Notes:

- Improved: Mermaid diagrams now render faster and more accurately

[string write]:
https://doc.rust-lang.org/src/alloc/string.rs.html#3342-3354

---------

Co-authored-by: Danilo Leal <daniloleal09@gmail.com>
Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>
2026-05-27 16:27:18 +00:00
MartinYe1234
aa6062edaf
Stop loading deprecated agent rules (#57844)
Summary:

- Stop loading persisted default Zed Rules into native agent project
context.
- Remove legacy user-rules rendering from agent system prompt templates.
- Keep Skills and project rules file support unchanged.

Tests:

- cargo test -p agent
test_system_prompt_does_not_render_legacy_zed_rules_section --lib
- cargo test -p prompt_store test_empty_skills_sets_has_skills_false
- cargo test -p prompt_store
test_project_context_does_not_filter_by_budget

Closes AI-325
Release Notes:

- Fixed deprecated Rules being automatically included in new agent
requests.
2026-05-27 16:21:30 +00:00
Richard Feldman
bc6a483e5c
Add Actions to open AGENTS.md (#57847)
<img width="620" height="172" alt="Screenshot 2026-05-27 at 12 08 26 PM"
src="https://github.com/user-attachments/assets/226b3d0c-003b-44ac-a16f-10af4f2952b3"
/>


Add command palette actions for opening global and project-specific
AGENTS.md files

Closes AI-324

Release Notes:

- Added commands to open global and project-specific AGENTS.md rules
2026-05-27 16:08:52 +00:00
Oleksiy Syvokon
32d0737318
Add cooldown when file watch limit is reached (#57720)
Stop trying to add new watches for 5 seconds after receiving the "OS
file watch limit reached" error.

This was flooding the logs and many pointless syscalls.

Related to #57422, #57042, FR-18

Release Notes:

- Improved file watcher behavior when the OS file watch limit is
reached.
2026-05-27 15:35:46 +00:00
Fanteria
80a4042ff5
vim: Fix dot repeat after macro replay not capturing insertion text (#57684)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
Closes #47251

Fix dot (`.`) repeat not correctly repeating the last change after
replaying a macro (`@register`)
([#47251](https://github.com/zed-industries/zed/issues/47251))

When replaying a macro that contains text insertions,
`replay_insert_event` calls `handle_input` directly and never emits
`InputHandled`, so the `observe_insertion` subscription never fires.
This left the dot register stale — `.` after `@register` would repeat an
earlier change instead of the last one made by the macro.

Fix by calling `observe_insertion` explicitly in the
`ReplayableAction::Insertion` branch of `Replayer::next`.

Release Notes:

- Fixed dot (`.`) repeat not repeating the last change made by a macro
(`@register`).

---------

Co-authored-by: Smit Barmase <heysmitbarmase@gmail.com>
2026-05-27 14:36:41 +00:00
Danilo Leal
0464de8fdd
skills_creator: Improve header alignment (#57834)
Tiny UI tweak here to improve the label/traffic lights alignment in the
skills creator header.

Release Notes:

- N/A

Co-authored-by: Martin Ye <martin@zed.dev>
Co-authored-by: Bennet Bo Fenner <bennetbo@gmx.de>
2026-05-27 14:34:28 +00:00
Ben Kunkle
a65e677376
ep: Make tree-sitter dependency optional in edit_prediction_metrics (#57829)
Needed for use in cloud

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-27 14:11:23 +00:00
Bennet Bo Fenner
f838eb1248
git_ui: Respect global AGENTS.md when generating commit message (#57827)
Release Notes:

- agent: Fixed an issue where commit message generation would not
respect instructions from global `AGENTS.md`

---------

Co-authored-by: Richard Feldman <oss@rtfeldman.com>
2026-05-27 14:08:15 +00:00
Danilo Leal
ceff1b227b
agent_ui: Improve menu items related to rules (#57828)
Also adds a menu item called "Rules Library" that takes to the
documentation, which will explain the removal of the feature as a whole.

Release Notes:

- N/A

Co-authored-by: Bennet Bo Fenner <bennetbo@gmx.de>
2026-05-27 14:03:28 +00:00
MartinYe1234
d2cbf930f7
Allow path tools to operate on global agent skills (#57760)
Extends the same `~/.agents/skills` special case that
`create_directory`, `edit_file`, and `write_file` already use to the
path tools, so the agent can copy or move skills into and out of the
global skills folder and delete individual skills or skill resources
beneath it.

- `copy_path` now allows source and/or destination to be a descendant of
`~/.agents/skills`, going through `fs::copy_recursive` directly when one
side is outside the project.
- `move_path` now allows source and/or destination to be a descendant of
`~/.agents/skills`, going through `fs.rename` directly when one side is
outside the project. Moving the `~/.agents/skills` root itself is
rejected.
- `delete_path` now allows deleting any file or directory beneath
`~/.agents/skills`, going through `fs.remove_dir` / `fs.remove_file`
directly. Deleting the `~/.agents/skills` root itself is rejected.
- All three tools still always prompt for approval on agent-skill paths,
even when default tool permissions are set to allow.
- Added shared helpers in `tool_permissions.rs` for resolving global
skill descendants and rejecting operations on the skills root where
needed.
- Added tests covering copying and moving skills in both directions,
deleting a global skill directory/file, and rejecting deletion of the
skills root.

Release Notes:

- Agent can now copy or move skills into and out of `~/.agents/skills`
and delete individual skills, with an explicit confirmation prompt for
each operation
2026-05-27 14:02:18 +00:00
Richard Feldman
a55e3e99f5
agent_skills: Read SKILL.md in one shot via fs.load (#57510)
Follow-up to #57466 simplifying `load_skill_frontmatter` rather than
fixing a separate bug.

#57466 fixed the chunked-read loop so it truncates accumulated bytes at
the frontmatter boundary, preventing `str::from_utf8` from failing on a
multi-byte grapheme split across chunks. That fix is correct, but the
chunked read it's working around isn't pulling its weight:
`MAX_SKILL_FILE_SIZE` is 100KB and there's already a metadata pre-check,
so "stop reading early once we've seen the closing `---`" saves at most
~25 pages per file while forcing the use of `open_sync`, a hand-rolled
loop, and a long comment about `smol::unblock` vs the GPUI test
scheduler.

This PR:

- replaces the chunked `open_sync` + read loop with a single
`fs.load(...)` call (the same primitive `read_skill_body` already uses);
- deletes `closing_delimiter_end`, `SKILL_READ_CHUNK_SIZE`, the
`std::io::{self, Read}` import, and the `Parking forbidden` paragraph;
- tightens the metadata pre-check so a metadata error (permissions, I/O,
etc.) bails out instead of silently falling through to a blind read;
- removes the now-obsolete
`test_load_skill_frontmatter_with_emoji_at_chunk_boundary` test — by
construction, a single full read can't split a UTF-8 sequence at any
boundary.

Closes AI-303

Release Notes:

- N/A
2026-05-27 13:52:40 +00:00
Danilo Leal
a9296b9a5a
docs: Update information regarding rules/skills (#57824)
Update some content regarding the skills migration and its impact on the
Git commit prompt.

Release Notes:

- N/A

---------

Co-authored-by: Bennet Bo Fenner <bennetbo@gmx.de>
2026-05-27 13:30:08 +00:00
MartinYe1234
a718a2bde6
skill_creator: Make window resizable and form scrollable (#57754)
The Skill Creator window previously couldn't be resized — its minimum
size was set to the same dimensions as its initial size, so users
couldn't make it smaller or shorter. Its contents also didn't scroll, so
on smaller windows the Skill Content editor would be squeezed below its
usable size.

This change:

- Lowers the window's minimum size to 500×420 so it can be resized in
both directions.
- Wraps the form body in a scrollable container with a vertical
scrollbar.
- Replaces `flex_1 + min_h_0` on the form fields and Skill Content
wrapper with `flex_grow + flex_shrink_0`. Combined with the existing
`min_h(160)` on the body editor, this means:
- When there's extra vertical space, the Skill Content editor grows to
fill it.
- When the window is short, the form keeps its content at natural size
and the outer container scrolls instead of crushing the editor.

Closes AI-315
Release Notes:

- Made the Skill Creator window resizable and its contents scrollable
when the window is smaller than the form.
2026-05-27 13:27:07 +00:00
Tom Houlé
b328711bbe
agent_ui: Put fast mode behind confirmation popover (#57482)
It look like this:

<img width="1698" height="688" alt="grafik"
src="https://github.com/user-attachments/assets/02a37271-63d3-42da-887f-e17b31e8d9ca"
/>

The idea is to avoid people turning on fast mode without understanding
the financial implications. It also clarifiers (in the BYOK case) why
they might not see a difference between fast mode enabled and disabled.

Release Notes:

- N/A

---------

Co-authored-by: Danilo Leal <daniloleal09@gmail.com>
Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>
2026-05-27 13:05:55 +00:00
Kirill Bulatov
fe48ef424c
Fix outline panel hangs during massive project searches (#57814)
Fixes:
*
69d5da20f7
extracts excerpts' data instead of re-iterating them per each search
result entry
*
83fe2e4e88
instead of cancelling and restarting debounced tasks, coalesce new
tasks' submissions during pending debounces
*
d90ecd8820
removes redundant autoscrolls that happen anyway due to match
invalidation event processing — this prevented outline panel from being
scrolled a few seconds after the large project search is over
*
b9e00a3660
tidy up, less allocations


Before:


https://github.com/user-attachments/assets/8bedff61-d57e-4c72-8c8a-7c8127b315f3

After:


https://github.com/user-attachments/assets/bbe87992-3885-46b5-b187-92fc5b539e4a


Release Notes:

- Fixed outline panel hangs during massive project searches
2026-05-27 12:43:06 +00:00
Bennet Bo Fenner
c171bbac44
docs: Remove settings json snippet from agent-panel.md (#57807)
Follow up to #57375. Did not realise that we don't put JSON snippets in
our docs anymore

Release Notes:

- N/A
2026-05-27 11:23:14 +00:00
Lukas Wirth
f839f8e108
scheduler: Fix scheduler retention cycle (#57789)
async_tasks can build a cycle with the scheduler where the runnable
itself keeps a reference to the scheduler and the scheduler keeping
references to the runnable. This effectively can cause scheduler / task
leaks, most notably in test environments, so we break this cycle by
using weak pointers instead.

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-27 10:32:14 +00:00
Lukas Wirth
6555ac3d04
sidebar: Improve performance of rebuild_contents (#57717)
Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-27 10:31:57 +00:00
Lukas Wirth
75c17a6ee9
Bump ctor (#57728)
Otherwise miri might fail in some gpui projects on macos.

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-27 10:31:53 +00:00
Tom Houlé
a1d019bdd8
language_models: Support fast mode on ChatGPT subscription provider (#57436)
Same mechanism as for BYOK: `service_tier == priority`. Most of the work
is already done. When validating this in manual testing, I noticed we
get back `service_tier == auto` in the response, unlike in the regular
OpenAI API scenario with BYOK, but apparently [it doesn't mean priority
tier wasn't
applied](https://github.com/openai/codex/issues/14204#issuecomment-4033184620).
It's not a hard confirmation, but the model does seem to respond faster
when I toggle fast mode on.

Release Notes:

- Added Fast Mode (priority service tier) support to OpenAI models used
through the ChatGPT subscription provider.
2026-05-27 09:22:00 +00:00
Kirill Bulatov
1965d69819
Fall back to default text when no command is available for the resolved lens (#57790)
Follow-up to https://github.com/zed-industries/zed/pull/54100

LSP [code
lens](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#codeLens)
has the only textual data in
[`command`](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#command),
which we use for rendering (`command.title`).

Certain language servers do not send the command by default until
resolved, and this is the only field worth resolving in the code lens
which we have to fetch asynchronously as the user types.

Not including such lens at all caused flickering and
https://github.com/zed-industries/zed/pull/55075 had dealt with this by
reserving the block for all code lens and swapping them with the
resolved data later.

Yet, certain language servers return empty commands even after
resolving, to indicate "nothing referencing this", as it is shown in
VSCode:

<img width="951" height="424" alt="image"
src="https://github.com/user-attachments/assets/19c8db24-c312-4c33-9da3-003da11e27a3"
/>

Before, we have removed blocks for such lens with no command after the
resolve, but this caused flickering as reported in
https://github.com/zed-industries/zed/pull/55075#issuecomment-4549779927

Thus, this PR falls back to the placeholder for such lens, to avoid any
flickering and odd empty blocks.
Also, this PR reworks the tests to have the assertions more readable.

Before:


https://github.com/user-attachments/assets/6af50fc5-92fb-4ce0-b07b-b2867be75c02


After:


https://github.com/user-attachments/assets/4aa91c12-ae3c-4fb8-9bbd-a61d6edb79df



Release Notes:

- Fixed code lens flickering when resolved to no commands
2026-05-27 09:19:04 +00:00
Bennet Bo Fenner
88a54a2683
open_ai: Fix error message not showing up when using ChatGPT subscription (#57750)
The API seems to return nested errors, so made the error deserialise
properly in case we get `{ "error": {...} }` instead of a top-level
error

Closes #57024

For testing, you can prompt something like: `tell me about
https://registry.npmjs.org/vite-plus.`

Before:

<img width="631" height="69" alt="image"
src="https://github.com/user-attachments/assets/5d02e7ec-8176-4bff-87d7-908ac8f0b498"
/>

After:

<img width="697" height="61" alt="image"
src="https://github.com/user-attachments/assets/97fac249-8b76-463c-8483-a150f5db9857"
/>


Release Notes:

- openai: Fixed an issue where error messages would not show up properly
2026-05-27 09:18:39 +00:00
Tom Houlé
5e717a06cd
open_ai: Support fast mode in BYOK via the Responses API service_tier (#57412)
Maps the existing `Speed::Fast` plumbing to OpenAI's `service_tier:
"priority"`, which matches what "fast mode" in Codex does. Relevant docs
[here](https://platform.openai.com/docs/api-reference/chat/create#chat-create-service_tier).

Like for the existing Anthropic fast mode we have a
`Model::supports_priority` method for the variants on
https://openai.com/api-priority-processing. Pro, nano, and legacy gpt-4
are excluded; Custom defaults to false.

This is gated to staff only for now (not in this diff, but the existing
fast mode feature), until we have the mechanism to require confirmation
before you enable fast mode.

Release Notes:

- Added support for Fast Mode (priority service tier) on the OpenAI API
provider.
2026-05-27 09:17:23 +00:00
Luke Deen Taylor
e25458243b
node_runtime: Tolerate non-string values in npm time metadata (#57765)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
> [!NOTE] 
> Authored by Claude, but fixes a real issue I encountered; I have
reviewed the diff

Some npm registries return `npm info --json` with non-string values in
the `time` map. JFrog Artifactory emits `"unpublished": null`, and npm
itself represents `unpublished` as an object for packages that have had
versions unpublished.

Because `NpmInfo.time` was typed `HashMap<String, String>`, serde
aborted the entire deserialization with `invalid type: null, expected a
string`. As a result `select_npm_package_version` never ran, and
language servers installed via npm (for example the tsgo extension,
`tailwindcss-language-server`, and `json-language-server`) failed to
start with an error like:

```
Failed to start language server "tsgo": invalid type: null, expected a string at line 100 column 23
```

Only version keys in `time` are ever read (to honor npm's `before`
cutoff), so this deserializes the map leniently: keep the string-valued
entries and drop the rest. The field type and all downstream logic are
unchanged. Added a regression test covering a `time` map containing
`"unpublished": null`.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the UI/UX checklist
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- Fixed language servers failing to install when the npm registry
returns non-string values (such as `"unpublished": null`) in package
`time` metadata
2026-05-27 04:39:26 +00:00
MartinYe1234
867e51189b
agent_ui: Show global skill paths in edits summary (#57767)
Summary

- Display the full path for global skill files in the agent edits
summary when they do not have a project-relative file name.

Closes AI-320

Validation

- cargo check -p agent_ui --lib

Release Notes:

- Fixed global skill edits appearing without a file path in the agent
changes summary.
2026-05-27 02:24:31 +00:00
Max Brunsfeld
4129fc87d8
Fix the filtering of index.lock + COMMIT_MESSAGE FS events to work in linked worktrees (#57763)
Zed reloads a lot of data about a git repository any time any file
changes inside of the `.git` directory, with the exception of a few
known paths that we know do not warrant a reload, such as `index.lock`
and `COMMIT_MESSAGE`. Previously, we ignored FS events for those files,
but we used a specific path that only worked for the main worktree. This
caused a lot of unnecessary reloads when using linked worktrees. Now we
ignore those files in a general way, by their filename, so that the
optimization applies to linked worktrees as well.

@cole-miller Noticed this bug.

Release Notes:

- Fixed unnecessary reloading of Git state that could occur when editing
in linked worktrees.
2026-05-27 00:04:30 +00:00
Danilo Leal
53ed11b2af
Iterate on skill announcement copywriting (#57532)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
Tweaking a bit the content that will be displayed in the announcement
toast.

Release Notes:

- N/A
2026-05-26 20:49:22 +00:00
MartinYe1234
7103c8c8e6
Allow agent tools to edit global skills (#57678)
Summary

- Allow write_file and edit_file to create or modify files under
~/.agents/skills.
- Keep the global skills exception constrained to that directory and
preserve existing project-path behavior.
- Document global skill file editing support in the built-in
create-skill instructions.

Tests

- cargo fmt -p agent
- cargo test -p agent global_skill_file
- cargo test -p agent
test_create_directory_allows_global_skill_directory

Release Notes:

- Fixed agent file editing for global skills

---------

Co-authored-by: Richard Feldman <oss@rtfeldman.com>
2026-05-26 20:16:43 +00:00
Oleksiy Syvokon
1025b13951
Cap and rotate remote logs (#57672)
This change caps remote log size at 1MB and maintains one rotated file.

Before this change, remote logs were growing indefinitely, leading to
issues like #57042 and #57422


Closes #57422

Release Notes:

- Fixed remote server logs growing unbounded
2026-05-26 19:41:24 +00:00
Oleksiy Syvokon
6df9ae9f8f
Log filesystem watcher lost sync only once per event (#57675)
On Linux, we create a filesystem watcher recursively for every subdir.
When we get "fs watcher lost sync" events, we used to log it for every
child dir, which could results in thousands messages. This becomes
problematic when we get into a state where we get those events
repeatedly (this larger issue is to be addressed separately).

Now we log one message per parent.

Partially addresses #57422, #57042, FR-18

Release Notes:

- N/A
2026-05-26 19:40:49 +00:00
María Craig
6e9f461cf8
Fix agent_profile_switched telemetry event name (#57739)
The `agent_profile_switched` event fired from the profile picker was
using snake_case instead of the title case used by every other agent
telemetry event. This caused it to land in Amplitude as a separate event
from the `Agent Profile Switched` event fired by keyboard cycling,
making it impossible to track profile switches in a single chart.

Renames the event to `Agent Profile Switched` to match. The `source`
property (`"picker"` vs `"cycle"`) still distinguishes the two code
paths.

Release Notes:

- N/A
2026-05-26 18:48:29 +00:00
Shuhei Kadowaki
efacf30294
lsp: Handle dynamic registration of textDocument/documentLink (#57749)
`register_server_capabilities` / `unregister_server_capabilities` had no
arm for `textDocument/documentLink`, so when a server saw our
`documentLink.dynamicRegistration` capability and chose to register the
provider dynamically, the registration silently fell into the `unhandled
capability registration` warning. `document_link_provider` stayed
`None`, `GetDocumentLinks::check_capabilities` returned false, and no
`textDocument/documentLink` request was ever sent.

Follow-up to https://github.com/zed-industries/zed/pull/56011

Release Notes:

- N/A

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 18:11:44 +00:00
MartinYe1234
c551ec93b0
Rename agent threads from the sidebar (#57656)
Summary:

- Added a rename action for agent threads in the sidebar.
- Persisted renamed thread titles and kept open thread views in sync.

Release Notes:

- Improved agent threads by allowing them to be renamed directly from
the sidebar.

---------

Co-authored-by: Danilo Leal <daniloleal09@gmail.com>
Co-authored-by: Bennet Bo Fenner <bennetbo@gmx.de>
2026-05-26 17:55:09 +00:00
Young
533d3d534b
Recognize HIP files as C++ (#57333)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments (I am not adding
new unsafe blocks)
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior (Should I add a test for
this?)
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

- Added Recognizing HIP files as C++
2026-05-26 16:22:19 +00:00
Agus Zubiaga
5618485134
gpui: Make Window::paint_*_shadows pub (#57741)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable


Release Notes:

- N/A
2026-05-26 16:11:21 +00:00
Ben Brandt
4bee412118
agent_ui: Persist external agent selections as defaults (#57511)
Matches behavior from selectors between Zed + external agents.

Also means they will persist across worktree creation 🎉

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-26 15:11:19 +00:00
Lukas Wirth
b20cd411ec
languages: Use rustup rust-analyzer when toolchain override is present (#57696)
rust-analyzer does not really attempt to be backwards compatible, so
when users opt-into the component a toolchain override, we should prefer
that over any other rust-analyzer (especially our own) for better
toolchain compatibility in case people have a more out of date install.
This mirrors the VSCode extension behavior

Release Notes:

- When a worktree contains a Rust toolchain file with a rust analyzer
component specified, Zed will now spawn the given toolchain's
rust-analyzer for toolchain compatability
2026-05-26 14:58:09 +00:00
MartinYe1234
a8966695ee
Fix flicker of pushed-off sticky project header in threads sidebar (#57529)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
The threads sidebar rebuilds its `Vec<ListEntry>` from scratch on events
that touch thread/sidebar state (status changes, title generation, new
live info, sending a message, etc.). It previously called
`ListState::reset` after every rebuild, which rewrote every list item to
`Unmeasured`. On the next render frame, the sticky project header had no
measured bounds for the next project header.

The sticky project header uses `ListState::bounds_for_item` for the next
project header to compute how far it should be pushed off screen. When
those measurements were missing, it temporarily fell back to `top_offset
= 0`, snapped fully into view for one frame, then popped back once the
list was remeasured.

Fix: preserve list measurements for entries whose identity and layout
shape did not change. `EntryShape` captures each entry's identity plus
height-affecting project-header flags. `update_entries` snapshots the
old shapes, rebuilds contents, then splices only the changed shape range
into `ListState`. Unchanged items keep their measured bounds, so the
sticky header remains in its pushed-off position across same-shape
updates.

This also adds a regression test that renders a two-project sidebar,
scrolls into the sticky-header push-off state, performs a same-shape
thread metadata update, and verifies the next header's measured bounds
are preserved.

Closes AI-196

Release Notes:

- Fixed the project section header flickering in the agent threads
sidebar when sending a message while the header was partially scrolled
off screen.
2026-05-26 14:41:26 +00:00
Danilo Leal
eb944cfd7a
gpui: Add support for inset shadow (#57685)
This PR adds support for inset shadows in the box shadow through the
`inset: true` field. It includes support for both the macOS as well WGSL
shaders. For now, there is no immediate application of it in Zed, so
nothing should change in the app.

<img width="600" alt="Screenshot 2026-05-25 at 8  46@2x"
src="https://github.com/user-attachments/assets/db564a6b-8af5-491a-a573-17c060a3647c"
/>

Run the example above with `cargo run --example shadow -p gpui`.

Release Notes:

- N/A

---------

Co-authored-by: Agus Zubiaga <agus@zed.dev>
2026-05-26 14:32:45 +00:00
Lukas Wirth
b5b52ada0c
buffer_diff: Remove git2 dependency from buffer_diff (#56013)
Split out of https://github.com/zed-industries/zed/pull/53453

Release Notes:

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

Co-authored-by: Kieran Freitag <kfreitag@kieran.ca>
2026-05-26 14:28:02 +00:00
Bennet Bo Fenner
b1bfde9e9d
git_ui: Create new worktree on latest origin main (#57704)
When creating a git worktree, we now always fetch latest `origin/main`
and create the worktree based on that. If running `git fetch` fails, we
show an error toast with the option to base the worktree of off local
`origin/main`:

<img width="530" height="45" alt="image"
src="https://github.com/user-attachments/assets/f9ae4c05-8c2c-44f3-9c14-3c291a9d82f6"
/>


Release Notes:

- git: Always create worktrees based on latest `origin/main`
2026-05-26 14:20:50 +00:00
liam
e7bbfd5223
vim: Fix replace in helix select mode (#57553)
Resolves https://github.com/zed-industries/zed/issues/57522

This diff fixes `r` in Helix select mode. The keybinding already pushed
the replace operator in `helix_select`, but when the replacement
character was typed, the operator dispatch only handled `HelixNormal`,
so selected text in `HelixSelect` fell through and cleared the operator
without editing the buffer.

With this change, Helix select mode uses the same `helix_replace` path
as Helix normal mode. Multi-character selections now replace each
selected grapheme with the typed character and return to Helix normal
mode, matching the existing behaviour for Helix normal selections.

Release Notes:
- Fixed `r` not replacing multi-character selections in Helix select
mode.
2026-05-26 14:15:31 +00:00
Bennet Bo Fenner
a60cf568b7
agent: Show error message of edit tool call in UI (#57722)
Ensures that we show the error message of the `edit_file`/`write_file`
tools in the UI

Release Notes:

- agent: Fixed an issue where errors would not show up in the UI if an
edit tool call failed
2026-05-26 14:10:06 +00:00
crazydude123
16ae765da8
vim: Fix g i and g a in Helix mode to match Helix semantics (#57621)
In Helix mode, `g i` and `g a` currently leak through from the catch-all
`VimControl && !menu` section:

- `g i` fires `vim::InsertAtPrevious` (Vim's "go to last insert"), but
Helix's `goto_implementation` expects an LSP jump to the implementation
site.
- `g a` fires `editor::SelectAllMatches`, but Helix's
`goto_last_accessed_file` expects to jump to the alternate buffer.

This adds explicit overrides in the shared `(vim_mode == helix_normal ||
vim_mode == helix_select)` section so both keys behave per Helix's
documented goto-mode bindings: https://docs.helix-editor.com/keymap.html

### Before
| Key | Helix expects (`goto_*`) | Zed actual (leaked from Vim) |
| --- | --- | --- |
| `g i` | `goto_implementation` (LSP) | `vim::InsertAtPrevious` |
| `g a` | `goto_last_accessed_file` | `editor::SelectAllMatches` |

### After
| Key | Action |
| --- | --- |
| `g i` | `editor::GoToImplementation` |
| `g a` | `pane::AlternateFile` |

Refs #4642

Bounty: https://app.opire.dev/issues/01J6HJZCK02FVD4XG900FY36EE

### Release Notes:

- vim: Fixed `g i` and `g a` in Helix mode to invoke
`goto_implementation` and `goto_last_accessed_file` instead of leaking
Vim-mode bindings.

---------

Co-authored-by: Smit Barmase <heysmitbarmase@gmail.com>
2026-05-26 14:06:15 +00:00
liam
158fcac15e
vim: Fix Helix jump on selected lines (#57565)
Resolves https://github.com/zed-industries/zed/issues/57486

This diff fixes `g w` after selecting lines with `x` in Helix mode. `x`
leaves Zed in Helix normal mode with a non-empty selection, but jump
target collection treated non-visual selections as ranges to skip. As a
result, words on the selected line did not receive jump labels.

With this change, Helix normal mode keeps existing selection ranges
eligible for jump targets, matching Helix's behavior where normal mode
can still carry selections. The regression covers `x` followed by `g w`
targeting a word inside the selected line.

Release Notes:

- Fixed `g w` not targeting words on lines selected with `x` in Helix
mode.

---------

Co-authored-by: Smit Barmase <heysmitbarmase@gmail.com>
2026-05-26 14:05:40 +00:00
crazydude123
511d2c43d2
vim: Swap q/Q in Helix mode to match Helix macro semantics (#57622)
Helix inverts Vim's macro keys: **`Q`** starts/stops recording, **`q`**
replays. Currently both leak through to Helix mode from the catch-all
`VimControl && !menu` section using Vim's mapping, so Helix users
hitting `Q` to record a macro instead get playback, and vice versa.

Helix's default keymap explicitly chooses this inversion — the Vim
mapping is even present as a commented-out alternative in
[helix-term/src/keymap/default.rs](https://github.com/helix-editor/helix/blob/master/helix-term/src/keymap/default.rs):

```rust
"Q" => record_macro,
"q" => replay_macro,
// "q" => record_macro,
// "Q" => replay_macro,
```

### Before
| Key | Helix expects | Zed actual (leaked from Vim) |
| --- | --- | --- |
| `q` | `replay_macro` | `vim::ToggleRecord` |
| `Q` | `record_macro` (start/stop) | `vim::ReplayLastRecording` |

### After
| Key | Action |
| --- | --- |
| `q` | `vim::ReplayLastRecording` |
| `shift-q` | `vim::ToggleRecord` |

Refs https://docs.helix-editor.com/keymap.html
Refs #4642

Bounty: https://app.opire.dev/issues/01J6HJZCK02FVD4XG900FY36EE

### Release Notes:

- vim: Swapped `q` and `Q` in Helix mode so they record / replay macros
per Helix defaults instead of leaking Vim bindings.

---------

Co-authored-by: Smit Barmase <heysmitbarmase@gmail.com>
2026-05-26 14:05:31 +00:00
Kunall Banerjee
1a0b54616b
git_ui: Fix commit modal buttons hidden at small ui_font_size (#56366)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [ ] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [ ] Performance impact has been considered and is acceptable

Closes #55939.

Release Notes:

- Fixed commit modal buttons being hidden for `ui_font_size` values
2026-05-26 13:42:51 +00:00
Kunall Banerjee
a0ee9fb431
project_panel: Color worktree-modified files as modified, not warning (#57716)
I use the One Dark theme, so to actually test if my fix worked, I had to
also do:

```jsonc
"experimental.theme_overrides": {
  "warning": "#ff0000",
  "modified": "#00ff00",
},
```

| Before | After |
|--------|--------|
| <img width="676" height="254" alt="image"
src="https://github.com/user-attachments/assets/a2831667-1113-49ac-b6aa-1221c71bf997"
/> | <img width="299" height="137" alt="image"
src="https://github.com/user-attachments/assets/ad6e85aa-ba24-47ad-b69d-6d0c3aa3a407"
/> |

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [ ] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [ ] Performance impact has been considered and is acceptable

Closes #57443.

Release Notes:

- Fixed Project Panel git status indicator showing modified files with a
warning color instead of the modified color
2026-05-26 13:41:44 +00:00
Lukas Wirth
277b22f0d2
go_to_line: Fix go to line in multibuffers (#57700)
Instead of mixing row dimensions accidentally, this will now target the
rows in the current active excerpt, clamping to the nearest excerpt if
out of bounds.


Release Notes:

- Fixed go to line going to arbitrary lines in multibuffers
2026-05-26 13:41:28 +00:00
Cameron Mcloughlin
5139a6bfc1
agent: Fix clipping in fixed-width (#57726)
Fixed width mode wouldn't reliably take the sidebar width into account
when laying out the content of the agent panel. This fixes it
 
Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-26 13:23:01 +00:00
Ben Kunkle
1dac14c53a
Remove CRLF line endings (#57680)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-26 12:59:21 +00:00
Lukas Wirth
63ff99795c
agent: Make messages vec cheap to clone (#57712)
For long threads we will spend more and more time cloning the messages
just to save them to the database, as we need a copy of everything to do
so asynchronously. Messages are really expensive to clone though and we
accumulate a lot of them really fast, so even for smaller threads we
start seeing pauses in the millisecond range. The fix to this is fairly
simple though, we never mutate the messages once pushed to the vec, so
just Arc them.

This PR also slightly changes `UserMessage` to be a bit faster to clone
as well.

Release Notes:

- Fixed a cause of stutters when interacting with the agent
2026-05-26 10:00:34 +00:00
Tom Houlé
49fe1fcad5
anthropic: Pass beta header for speed in BYOK (#57707)
We were sending the `speed` field set to `"standard"` for BYOK Anthropic
but without the corresponding beta header. leading the requests to fail
with "invalid request format to Anthropic's API: speed: Extra inputs are
not permitted".

This makes sure to attach the beta header whenever the `speed` parameter
is used.

Release Notes:

- Fixed "speed: Extra inputs are not permitted" errors for Opus 4.6 and
4.7 in the Anthropic API provider.
2026-05-26 09:00:33 +00:00
David Anekstein
281cfdd7a2
Clarify Lamport ordering comment in remote edit (#52037)
## Context

This PR updates a misleading comment in the remote edit merge path in
the text CRDT.

At `crates/text/src/text.rs`, the code skips fragments when
`fragment.timestamp > timestamp`, but the comment described this as
"lower lamport timestamp." In this codebase, Lamport ordering is
ascending (`value`, then `replica_id`), so `>` means a higher Lamport
timestamp.

This change is comment-only and does not change runtime behavior.

## How to Review

1. Open `crates/text/src/text.rs` and inspect the updated two-line
comment above the `while let Some(fragment) = old_fragments.item()` loop
in `apply_remote_edit`.
2. Confirm the condition directly below is unchanged:
`fragment.timestamp > timestamp`.
3. (Optional) Cross-check Lamport ordering in
`crates/clock/src/clock.rs` (`impl Ord for Lamport`) to confirm the
wording.

## Self-Review Checklist

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior (comment-only change; no
behavior changes)
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A

Co-authored-by: Lukas Wirth <lukas@zed.dev>
2026-05-26 07:48:29 +00:00
KyleBarton
707c00b474
Support local devcontainer features (#55225)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #53486

Note that this builds off of #55117 because both touched similar code
areas; I thought it best to in order to avoid conflicts.

Release Notes:

- Added support for local features in dev containers
2026-05-26 07:13:00 +00:00
Kirill Bulatov
3e77442f2e
Support LSP document links (#56011)
Closes https://github.com/zed-industries/zed/issues/33587


https://github.com/user-attachments/assets/bbaea8a9-402e-485b-800e-2f4486142956

Release Notes:

- Supported LSP document links (enabled by default, use
`"lsp_document_links": false` to turn it off)
2026-05-26 07:09:47 +00:00
Albert Bogusz
a5457029cc
Add icons for Bitbucket, Codeberg, Forgejo, Gitea, and GitLab remotes (#57500)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [ ] ~Unsafe blocks (if any) have justifying comments~ (N/A)
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Improves #44738 by including icons for more non-GitHub remotes instead
of a generic link icon. The SVG icons I added in `assets/icons` are
sourced from [simpleicons.org](https://simpleicons.org) as placeholders.
They most definitely aren't in Zed's style and need design team input.

Previews from History tab in Git panel (clicking on a commit in git
graph also shows matched icons):


![Bitbucket](https://github.com/user-attachments/assets/f6397716-8ac7-42f2-ba6d-7f2564cce19e)


![Codeberg](https://github.com/user-attachments/assets/d4c40d93-2cde-498d-8205-02c7dc495498)


![Forgejo](https://github.com/user-attachments/assets/a11d3ccb-05e3-4af6-9b14-8a89b4390e7e)


![Gitea](https://github.com/user-attachments/assets/7e84701a-a8c4-4298-851b-472765ef05b8)


![GitLab](https://github.com/user-attachments/assets/fb798f67-79f1-4937-add0-c3d636854182)

Release Notes:

- Added icons for Bitbucket, Codeberg, Forgejo, Gitea, and GitLab remote
providers.

---------

Co-authored-by: Danilo Leal <daniloleal09@gmail.com>
2026-05-26 02:10:47 +00:00
MartinYe1234
2984fafdf2
Add skill import from GitHub URL (#57458)
Summary:

- Added a URL mode to Skill Creator for importing GitHub Markdown files.
- Added clipboard prefill and command palette entry for creating a skill
from URL.
- Reused skill frontmatter parsing so imported skills prefill metadata
and content.
- Added Command Palette command to add skills via URL.

Closes AI-301
Release Notes:

- Added Skill Creator support for importing skills from GitHub Markdown
URLs

---------

Co-authored-by: Danilo Leal <daniloleal09@gmail.com>
2026-05-26 02:04:08 +00:00
Smit Barmase
7ef1fa1380
agent_ui: Surface pending tool call permission when scrolled out of view (#57632)
Closes #53266

When a tool call awaiting permission is below the viewport, it’s easy to
miss why the agent has stopped working. This PR adds a floating row at
the bottom of the panel that mirrors the pending permission request.

It reuses the same permission prompt, so you can allow or deny it and
see the raw input without scrolling to the end of the thread. It offers
a "Scroll to" button to jump back to the inline prompt in the thread.
Once the inline prompt is in view, the floating row disappears. If
multiple tool calls need permission, including a subagent’s, they’re
shown one at a time so rows don’t stack on top of each other.

<img width="508" height="181" alt="image"
src="https://github.com/user-attachments/assets/7d5fedd6-bc4d-4674-8ea2-5c8f2ed3aff6"
/>

Release Notes:

- Improved visibility of pending tool call confirmations in the Agent
Panel when its scrolled out of view.

---------

Co-authored-by: Danilo Leal <daniloleal09@gmail.com>
2026-05-26 01:17:14 +00:00
Xiaobo Liu
a6780a5a47
deepseek: Simplify error mapping in DeepSeek stream_completion (#57582)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
Release Notes:

- N/A
2026-05-25 17:01:58 +00:00
Lena
b72e57da65
Duplicate Bot: Handle failure modes better (#57663)
- don't fail to parse json when Claude ignores the instructions and
returns fenced json
- don't fail to search for issues by area labels when Claude ignores the
instructions and returns prose instead of comma-separated list
- don't mark workflow runs as successful when json parsing blew up or
posting the comment failed

Release Notes:

- N/A
2026-05-25 16:49:51 +00:00
Max Brunsfeld
2e20860461
Fix git hang caused by accidental inheritance of stdin FD (#57572)
When restarting Zed, I hit a bug where all Git operations were hung. I
realized that there was a hanging git process running `git cat-file
--batch-check=%(objectname)`. The process was waiting on stdin. This was
surprising, because [the
code](e2bbdb19b6/crates/git/src/repository.rs (L1665-L1709))
that spawns this process explicitly closes the pipe that is attached to
the process's stdin after writing a list of ref names.

Using Claude, I found that this could be caused by that pipe file
descriptor being cloned due to file descriptor inheritance when another
child process is `exec`'d while that stdin pipe is open. The fix is to
enhance our Darwin process spawning layer to set the close-on-exec flag
for the pipe file descriptors, so that they are not inherited by child
processes spawned using code paths that don't set
`POSIX_SPAWN_CLOEXEC_DEFAULT`.

Release Notes:

- Fixed a bug on macOS where Git operations could be blocked depending
on the timing of spawning child processes.
2026-05-25 16:20:30 +00:00
Cole Miller
bcfbf669bd
git: Degrade gracefully when refreshing git state (#57292)
This PR changes the git store's `compute_snapshot`, which runs to update
state that depends on the contents of `.git`, to degrade gracefully when
fetching individual pieces of state fails. For example, when fetching
the list of branches fails, instead of returning early from the function
(leaving the previous git state snapshot in place with stale state), we
continue with an empty list of branches. This prevents failures of
individual git commands from making the entire git UI get stuck
indefinitely.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

- Fixed an issue where failing to fetch branches using the git CLI would
prevent other git-related state from being updated.
2026-05-25 16:15:12 +00:00
MartinYe1234
6a747984d3
Revert "Rename agent threads from the sidebar" (#57654)
Reverts zed-industries/zed#57521
Forgot review approval

Release Notes:
- N/A
2026-05-25 15:45:10 +00:00
Cole Miller
a8cdf1d869
Batch excerpt insertions per file when opening commit view (#57330)
When viewing the diff for a commit where one of the files has a large
number (hundreds or thousands) of diff hunks, we can get a hang on the
main thread, since there's a large amount of work to recompute diff
transforms for thousands of excerpts. This PR makes it so that we batch
the addition of excerpts, with yield points in between batches so the UI
remains responsive.

We should have something similar for the project diff, but that's a bit
trickier; will address it in a separate PR.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- Improved performance when opening the commit view with files that have
many diff hunks.
2026-05-25 14:42:01 +00:00
Finn Evers
216980f671
zed: Add OpenStatusPage action (#57316)
Following up on our recent extension outage, this PR adds an action to
quickly visit our status page (which with the help of @\gaauwe was
recently updated to a more up to date design 🎉 ).

While already invokable through the command palette, we can later use
this to also add buttons where appropriate for a quick lookup of our
current status.

Release Notes:

- Added the `zed::OpenStatusPage` action to be able to easily visit the
Zed status page.
2026-05-25 14:41:33 +00:00
Mikhail Pertsev
786eb24521
git: Recover branch refs when metadata lookup fails (#57285)
cc @cole-miller 

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- Fixed branch enumeration when a broken Git ref prevents commit
metadata from being read.

---------

Co-authored-by: Cole Miller <cole@zed.dev>
2026-05-25 14:29:46 +00:00
Lena
bb460d5f26
Duplicate Bot: Add more context for triagers (V3) (#57647)
In addition to the user-facing suggestions with potential duplicates,
the bot will now also have a separate collapsible block in the same
comment that's meant more for the triagers. This block will list the
duplicates we're less sure about as well as recently closed issues that
seem related to the issue at hand.
This commit updates the bot to V3 for the tracking-effectiveness
purposes and fixes some leftovers from the previous dupe bot change
(activating the bot for issues with no type).
It also improves the reliability of the script a bit, wrapping some
calls to the GitHub API into retries.


Release Notes:

- N/A
2026-05-25 14:29:13 +00:00
MartinYe1234
453b020866
Rename agent threads from the sidebar (#57521)
Summary:
- Added a rename action for agent threads in the sidebar.
- Persisted renamed thread titles and kept open thread views in sync.

Release Notes:

- Improved agent threads by allowing them to be renamed directly from
the sidebar.
2026-05-25 14:25:25 +00:00
Xiaobo Liu
8309bc4098
markdown: Support shift+click to extend text selection (#57586)
When shift is held during a single click, extend the existing selection
from its anchor point to the clicked position instead of starting a new
selection.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- Added markdown support shift+click to extend text selection
2026-05-25 14:09:22 +00:00
Finn Evers
001d94d149
docs: Add more information for releasing extensions (#57261)
Release Notes:

- N/A
2026-05-25 14:06:00 +00:00
Lena
bc41407a5e
Duplicates bot: Stop skipping blank issues (#57643)
We regularly get a certain amount of 'blank' issues on github — those
created bypassing all our templates — and since a fair share of them are
bug reports, it would be helpful for the person triaging if the
duplicates bot has left suggestions on these issues too.

Release Notes:

- N/A
2026-05-25 12:20:10 +00:00
Kirill Bulatov
d3a9fd96a3
Make project panel to auto reveal multi buffer excerpts with latest selection (#57236)
Make non-singleton editors to return project paths by adding a `fn
active_project_path`: this had been added as `fn project_path` and
similar already, so the PR replaced those methods with the generic one
now.

Before:


https://github.com/user-attachments/assets/d0773e18-3910-4c5b-bcb3-a742f9bf9691


After:


https://github.com/user-attachments/assets/e7a3f13e-9649-4564-a7e6-dccf54f8c000


Release Notes:

- Made project panel to auto reveal multi buffer excerpts with latest
selection
2026-05-25 11:53:12 +00:00
Oleksiy Syvokon
13e7c11768
ep: Fix bugs in the split-commit command (#57604)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
Correctness and efficiency fixes to `imitate_human_edits`.

Release Notes:

- N/A
2026-05-24 18:49:05 +00:00
Oleksiy Syvokon
d066a73609
ep: Avoid service files as a split point (#57603)
Make up to ten retries to avoid placing cursor on files that are
typically machine generated (like Cargo.lock)

Release Notes:

- N/A
2026-05-24 18:00:41 +00:00
Oleksiy Syvokon
a74a96e25d
ep: Fix header for target patches (#57598)
Previously, we were always copying the _first_ header of the source
patch, which is wrong for 99% of time.

Release Notes:

- N/A
2026-05-24 17:22:48 +00:00
Oleksiy Syvokon
8bfe32010c
ep: Add jitter to cursor position (#57597)
When generating a training or evaluation example with `ep split-commit`,
the cursor sampling logic becomes:

1. 80% chance of cursor being at the end of the source patch
2. 20% chance of cursor being at the beginning of the target patch
3. 20% chance of adding a jitter offset (same line, ±5 columns for now)

Release Notes:

- N/A
2026-05-24 16:43:53 +00:00
Nikita Tikhomirov
eb2223c080
gpui_wgpu: Bump cosmic-text to v0.19.0 (#56988)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [ ] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Resolves the issues described at
https://github.com/pop-os/cosmic-text/releases/tag/0.19.0
This fix addresses the characters '\u{001C}' | '\u{001D}' | '\u{001E}' |
'\u{0085}' | '\u{2029}', which can cause the Editor gpui-component to
crash, as these characters can cause the 'assert "left == right"'.

Release Notes:
- N/A
2026-05-24 08:33:56 +00:00
Abdullah As-Sadeed
b1180f749c
docs: Fix typo in minimap docs (#57568)
The "all_editor" option for the `minimap.display_in` key is invalid. The
correct option is "all_editors".

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-24 07:27:52 +00:00
Vlad Ionescu
b0911ccc9e
opencode: Model updates (#57556)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
Closes https://github.com/zed-industries/zed/issues/57331

Model updates:
- **Free**: removed MiniMax M2.5 Free as per
10ddc78ce0
- **Zen**: added Gemini 3.5 Flash as per
f5f7d1a167/providers/opencode/models/gemini-3.5-flash.toml
- **Zen**: added Grok Build 0.1 as per
f5f7d1a167/providers/opencode/models/grok-build-0.1.toml

The newly-added Zen models **were not tested** as I don't have a Zen
subscription and I stubbornly refuse to get one.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- OpenCode: updated models (added Gemini 3.5 Flash and Grok Build 0.1,
removed MiniMax M2.5 Free)
2026-05-23 09:39:08 +00:00
liam
450206e49d
grammars: Highlight markdown code spans in tables (#57506)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
Resolves https://github.com/zed-industries/zed/issues/57501

This diff fixes Markdown inline syntax highlighting inside pipe table
cells. The block Markdown parser represents table content as
`pipe_table_cell` nodes rather than `inline` nodes, so Zed’s existing
`markdown-inline` injection ran for paragraph text but skipped code
spans inside tables.

With this change, table cells also inject `markdown-inline`, allowing
existing inline highlighting to handle code spans consistently between
paragraph text and table cells.

| Before | After |
| --- | --- |
| <img width="500" alt="Before screenshot"
src="https://github.com/user-attachments/assets/bdb75c18-9f20-4f3c-bea6-946194098db6"
/> | <img width="500" alt="After screenshot"
src="https://github.com/user-attachments/assets/23ae7bc5-5208-4dc7-ab6f-d07404aeae06"
/> |

Release Notes:

- Fixed Markdown inline code highlighting in table cells.
2026-05-22 22:40:13 +00:00
Cole Miller
de529b5677
scheduler: Add the ability to suppress Running seed output (#57525)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
This is useful when running tests for a large number of iterations
noninteractively

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-22 18:49:48 +00:00
Ben Kunkle
835cd847ef
ep: Fix edit prediction diff popover being occluded by right docs and sidebar (#57519)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

- Fixed an issue where edit prediction previews that appeared in the
diff popover could be occluded by open docks or the sidebar on the right
side of the editor
2026-05-22 18:21:54 +00:00
MartinYe1234
2c26e5e544
Avoid linkifying non-interactive code spans (#57515)
## Summary

- Skip code-span link resolution when markdown prevents mouse
interaction
- Add regression coverage for non-interactive code spans

## Tests

- cargo test -p markdown
test_code_span_link_ignores_code_when_mouse_interaction_is_prevented

Release Notes:

- Fixed extra link styling on file paths in agent tool call labels.
2026-05-22 17:20:57 +00:00
roboticsdude60
d3e27abc87
Fix skill frontmatter loading multi-codepoint UTF-8 graphemes at chunk boundary (#57466)
Self-Review Checklist:

- [X] I've reviewed my own diff for quality, security, and reliability
- [X] Unsafe blocks (if any) have justifying comments
- [X] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [X] Tests cover the new/changed behavior
- [X] Performance impact has been considered and is acceptable

Closes #57463

Release Notes:

- Fixed utf-8 parsing issues when loading skill frontmatter with
multi-codepoint graphemes (such as an emoji) crossing file chunk load
boundaries.
2026-05-22 15:29:06 +00:00
MartinYe1234
cfd0461b5a
Prefix read_file tool output with line numbers (#56779)
Format `read_file` tool output in `cat -n` style: each line is prefixed
with its line number right-aligned in a 6-character field, followed by a
single tab, followed by the line's original content (newlines preserved,
including CRLF). Numbering reflects the actual file lines, so a ranged
read starting at line 42 emits `42` for its first line, not `1`.

For large files, content returned by `get_buffer_content_or_outline` is
**not** prefixed:

- The symbol outline path already conveys structure via its `[L100-150]`
annotations.
- The truncated first-1KB fallback (used when a file exceeds
`AUTO_OUTLINE_SIZE` and has no parseable outline) is wrapped in a
synthetic `# First 1KB of …` header, so its lines don't correspond to
real file line numbers.

Both cases are reported via `BufferContent::is_synthetic` (renamed from
`is_outline`).

Also updates the `edit_file` tool's input doc to describe the prefix
format and tell the model to strip it before constructing `old_text` /
`new_text`, preserving the original indentation that appears after the
tab.

Updates how we render `read_file` tool call outputs in the UI
(screenshots included in comments below).
Also fixes an existing bug where `read_file` tool call outputs would not
re-render their content code block when an older thread was restored
(the tool's `replay` hook was missing).

Closes AI-226

Release Notes:

- Improved how `read_file` tool output renders in the agent panel, with
a line-number gutter, and fixed it not re-rendering on restored threads

---------

Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>
2026-05-22 15:02:17 +00:00
Matei Oprea
949d993146
git_ui: Let branch and repo name use available panel width (#57502)
The git panel footer truncated branch and repo against a predefined
character budget. This PR improves that and lets both float free with
flex-based truncation.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable



Some examples.

<img width="738" height="1794" alt="Screenshot 2026-05-22 at 17 35 09"
src="https://github.com/user-attachments/assets/18a4873c-fbcf-4875-8d1a-82eaa2ce222c"
/>
<img width="1590" height="1562" alt="Screenshot 2026-05-22 at 17 35 15"
src="https://github.com/user-attachments/assets/c4adf7a3-e093-4104-af20-c098eda80c08"
/>
<img width="990" height="1570" alt="Screenshot 2026-05-22 at 17 28 20"
src="https://github.com/user-attachments/assets/eda0dd31-2461-4d4b-b63c-902c6c47231e"
/>
<img width="606" height="1640" alt="Screenshot 2026-05-22 at 17 28 12"
src="https://github.com/user-attachments/assets/4a165d75-93d3-45a4-9d8b-525c39f49493"
/>


Closes #57238

Release Notes:

- Fixed the git panel branch name staying truncated even when the panel
was wide enough to show the full name (#57238)
2026-05-22 14:56:05 +00:00
Ben Brandt
dee596fa96
acp: Enable ACP additional directories (#57497)
If the agent server supports it, we pass along the multiple directories.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #54480

Release Notes:

- acp: External agents that support it now have access to all working
directories in a project.
2026-05-22 13:56:45 +00:00
Ben Brandt
91531fad6d
acp: Add logout support (#57492)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- acp: Add Logout flow for agents that support it.
2026-05-22 12:25:26 +00:00
Danilo Leal
e2a1c4ce0c
agent_ui: Remove count for user rules in context tooltip (#57456)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
The circular progress in the agent panel's message editor would
previously display the number of default user rules auto-embedded into
the thread. However, given default rules are all migrated to a global
AGENTS.md file, that feature doesn't make a lot of sense anymore. So,
this PR fixes it by adding a button that opens up the global file when
it exists.

Release Notes:

- N/A
2026-05-22 01:15:30 +00:00
MartinYe1234
d5cf9a65d2
Fix skill creator remote project scopes (#57453)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
Summary:

- Include remote worktrees as project-scope options in the skill
creator.
- Reuse workspace root path detection for project scope paths.

Validation:

- cargo check -p skill_creator
- cargo test -p skill_creator

Release Notes:

- Fixed project-local skill creation for remote projects.
2026-05-21 23:17:59 +00:00
Danilo Leal
da74e24a79
skills_creator: Add some UI adjustments (#57452)
Tiny changes: improving keyboard nav by fixing the tab order, and
improving styles by making the dropdown take just the width of the label
instead of a fixed width.

Release Notes:

- N/A
2026-05-21 23:00:30 +00:00
Danilo Leal
776b8304b1
sidebar: Remove pending indicator from header when visiting project again (#57454)
Quick follow-up to https://github.com/zed-industries/zed/pull/57322. We
weren't removing the pending notification when re-visiting the project
that contains the pending thread (only while the project is still
collapsed, though).

Release Notes:

- N/A
2026-05-21 23:00:06 +00:00
Danilo Leal
78749a4c2a
agent_skills: Update create-skill description (#57449)
This PR adds a slight update to the built-in `create-skill` skill.

Release Notes:

- N/A
2026-05-21 22:59:15 +00:00
MartinYe1234
6753eb1736
Update skill settings immediately after changes (#57447)
## Summary
- Hide deleted skills immediately in Settings while deletion completes
- Refresh the skill index after creating a skill so Settings updates
without reopening

Closes AI-299
Release Notes:

- Fixed skill management so newly created and deleted skills update in
Settings immediately.
2026-05-21 22:51:57 +00:00
Conrad Irwin
ba350974af
Fix multiline text truncation (#57450)
Improves .text_truncate() in combination with .line_clamp()

<img width="384" height="124" alt="Screenshot 2026-05-21 at 4 28 59 PM"
src="https://github.com/user-attachments/assets/3decc78c-8d5d-4d34-84c5-4274a2d12bea"
/>
<img width="385" height="143" alt="Screenshot 2026-05-21 at 4 26 23 PM"
src="https://github.com/user-attachments/assets/f807b19a-6834-4504-9749-e16b8d68a7aa"
/>

This was previously broken because we assumed lines would break evenly.

Release Notes:

- Improved truncation of multi-line text in the UI
2026-05-21 22:40:35 +00:00
Cole Miller
da66f95237
Make the commit editor's font size independently configurable (#56077)
- Add a separate `git_commit_buffer_font_size` setting, defaulting to
`12px` (the previous default before it was changed to use the buffer
font size)
- Add in-memory buffer font size overrides for zooming the commit modal
and in-panel editor

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- Added a `git_commit_buffer_font_size` setting and made the in-panel
and modal commit message editors zoomable.
2026-05-21 22:16:01 +00:00
MartinYe1234
f78f6da255
Make file paths in backticks clickable in agent panel (#57303)
When the agent mentions a file path inside `backticks` (e.g. ``
`src/main.rs` `` or `` `src/main.rs:42` ``), the rendered code span now
becomes a clickable link in the agent panel. Clicking opens the
referenced file in the workspace, jumping to the right line and column
when present.

## How it works

- **Shared path resolution.** Extracted `OpenTarget` and the
workspace/worktree resolution logic out of
`terminal_view::terminal_path_like_target` into a new
`workspace::path_link` module so both the terminal and the agent panel
can use the same code. Includes a `sanitize_path_text` helper ported
from the terminal's URL/punctuation handling. Pure refactor — terminal
behavior is unchanged.
- **`markdown` crate hook.** Added
`MarkdownElement::on_code_span_link(callback)`. When the callback
returns `Some(url)` for a given code span's contents, the existing
`push_link` machinery wires up cmd-hover, hit testing, and the existing
`on_url_click` callback. When it returns `None`, the code span renders
as before. The hook is opt-in, so `markdown` stays workspace-agnostic.
- **Agent panel wiring.** `render_agent_markdown` constructs an
`AgentCodeSpanResolver` that snapshots the project's visible worktree
entries plus their file extensions. `try_resolve` does a cheap
synchronous heuristic check (path must contain `/`/`\` or end in an
extension present in the workspace, can't be a URL, can't be all digits,
etc.) and then looks the candidate up in the per-worktree
`HashSet<Arc<RelPath>>`. On a hit it returns a `MentionUri::File` or
`MentionUri::Selection` URI, which the existing `thread_view::open_link`
already knows how to open at the right line.

## Edge cases handled

- Code spans inside fenced code blocks stay plain (gated on
`builder.code_block_stack.is_empty()`, matching how regular markdown
links behave).
- Trailing prose punctuation (`` `src/main.rs.` ``) is stripped before
lookup.
- Identifiers like `` `String` ``, `` `await` ``, `` `npm run dev` ``
stay plain — they don't pass the path-like heuristic.
- Cross-platform path separators handled via the per-worktree
`PathStyle`.

## Tests

- `crates/markdown` — unit test asserting code spans become links when
the callback returns `Some`, and stay plain when it doesn't.
- `crates/agent_ui` — unit test for `AgentCodeSpanResolver::try_resolve`
covering hits with and without a `:line` suffix, misses, identifiers,
and trailing punctuation.
- Existing `terminal_view` tests cover the moved resolution code
(unchanged behavior).

## Notes

- There's currently a temporary `log::info!` in
`AgentCodeSpanResolver::try_resolve` that reports per-call worktree-walk
timing and a cumulative total. Kept in for now to verify the feature
isn't being called excessively during streaming renders. Can be removed
before merge.
- Resolution is sync-only against worktree entries; absolute paths
outside the workspace are not resolved (would require an async re-render
path).

Closes AI-277

Release Notes:

- Made file paths in `backticks` clickable in the agent panel; clicking
opens the referenced file at the given line when present.
2026-05-21 22:04:32 +00:00
Danilo Leal
77cbba9b1a
sidebar: Add ability to move projects up and down (#57448)
Closes AI-298

This PR adds the first step towards allowing to reorganize the threads
sidebar. Drag and drop should be supported in the near future, maybe
even replacing this entirely:

<img width="700" alt="Screenshot 2026-05-21 at 6  44@2x"
src="https://github.com/user-attachments/assets/db420466-2323-474b-ba41-17eb4da2cf84"
/>

Release Notes:

- Sidebar: Added the ability to reorder projects by moving them up and
down through the ellipsis menu.
2026-05-21 21:56:35 +00:00
Danilo Leal
1399540715
settings_ui: Display scope in the breadcrumb (#57437)
Whenever there are subpages in the settings UI, a breadcrumb is
displayed. However, we weren't displaying the scope as part of the
breadcrumb, which can be relevant if you're wondering why a certain
information you expected to see here isn't being displayed. It might
just be that it is displayed in the _project_ scope instead of in the
_user_ scope. Therefore, this PR adds the scope in the breadcrumb:

| Before | After |
|--------|--------|
| <img width="1348" height="290" alt="Screenshot 2026-05-21 at 4  38
2@2x"
src="https://github.com/user-attachments/assets/1b64ba98-8e7e-41a7-9b13-19722bdbe093"
/> | <img width="1348" height="290" alt="Screenshot 2026-05-21 at 4 
38@2x"
src="https://github.com/user-attachments/assets/b5deb091-0617-42ac-bb4a-b8ba00ec386c"
/> |

Release Notes:

- Started to display the setting scope (user or project) in the Settings
Editor for better contextualization of settings subpages.
2026-05-21 19:48:51 +00:00
Danilo Leal
f0cbb42fa6
recent_projects: Fix activation defaulting to main worktree (#57321)
Closes AI-280

When navigating between projects opened in the same window through the
recent projects picker, the confirm action would always default to
picking the main worktree in a project. So if you were in a Git worktree
in project A, switched to project B, and then back to project A, when
coming back, you wouldn't be in the Git worktree you were in before. The
fix is done through matching by project group key instead of file system
paths. Since both the main and linked worktrees share the same key, it
will just find the previously active workspace and activate it.

Release Notes:

- Fixed a bug where navigating through open projects in the same window
through the recent projects would always default to the main worktree of
a given project, instead of activating the last active
worktree/workspace.
2026-05-21 19:48:43 +00:00
Danilo Leal
d61ffb8e6b
agent_ui: Add section for skills and rules in ellipsis menu (#57404)
Closes AI-291

This PR adds some new menu items in the agent panel's ellipsis menu to
make it easier to 1) create a new skill, 2) manage all existing skills
through the settings window, 3) open project and global AGENTS.md file,
if it exists.

Minor UI note: I'm adding an ellipsis character to the menu items in
which you need to do something else in a different view to fulfill the
item's label. For example, "Create Skill…" takes the ellipsis because
clicking on the menu item itself doesn't create the skill, but it takes
you to the place where you'll do that.

<img width="600" alt="Screenshot 2026-05-21 at 10  32@2x"
src="https://github.com/user-attachments/assets/1bfdd423-bd75-4c62-97ba-84130035ede8"
/>

Release Notes:

- N/A
2026-05-21 19:37:55 +00:00
Danilo Leal
7ec36d3661
sidebar: Show pending/unread state in project header when collapsed (#57322)
Closes AI-285

Similar to how we display whether there are running threads or a thread
waiting for permission in the collapsed version of the project's header
in the sidebar, I was missing the "unread" state from being shown. I had
to change the approach here as to how we extract this information
because the previous method was relying on observing the state of the
list entries within the sidebar at every `rebuild_contents` run, and
given there aren't any list entires when the project is collapsed, it
wouldn't work.
Release Notes:

- Agent: Added the notification indicator on collapsed project headers
in the sidebar when a thread completes.
2026-05-21 19:35:43 +00:00
Danilo Leal
7afcc87927
agent_ui: Add skills menu item in message editor's context menu (#57407)
Closes AI-295

This PR adds a skills submenu within the "add context" menu in the agent
panel's message editor. This will hopefully be yet another way to find
skills in the app.

<img width="600" alt="Screenshot 2026-05-21 at 11  24@2x"
src="https://github.com/user-attachments/assets/43652081-3929-4ca0-a32b-464077d84dd5"
/>

Release Notes:

- N/A
2026-05-21 19:29:55 +00:00
MartinYe1234
0307c7fb35
agent_ui: Fix crash when opening built-in skill mention in remote projects (#57432)
Clicking a built-in skill mention while connected to a remote project
(SSH or collab) caused Zed to abort with `called create_local_buffer on
a remote project`.

## Root cause

`agent_ui::ui::mention_crease::open_skill_file` was calling
`Project::create_local_buffer` to display the embedded read-only content
of a built-in skill:

```rust
let buffer = project.update(cx, |project, cx| {
    project.create_local_buffer(content, None, false, cx)
});
```

`Project::create_local_buffer` has an explicit panic guard for remote
projects, so any user who clicked a built-in skill mention while in an
SSH or collab project would crash Zed.

## Fix

The buffer is purely a display surface for binary-embedded skill content
— it has no on-disk backing, isn't searchable, and never needs to be
tracked by the project's buffer store. Build it directly with
`language::Buffer::local(content, cx)` instead, matching the pattern
used elsewhere in `agent_ui` (`thread_view.rs`, `message_editor.rs`,
`inline_assistant.rs`, etc.). This works for both local and remote
projects.

## Repro (before fix)

1. Connect Zed to a remote (SSH) project.
2. In the agent panel, click on a built-in skill mention (e.g. one
referencing `create-skill`).
3. Zed aborts with SIGABRT.

After the fix, the mention opens a read-only editor with the embedded
markdown content, identical behavior to local projects.

Release Notes:

- Fixed a crash when clicking a built-in skill mention in the agent
panel while connected to a remote project
2026-05-21 19:29:31 +00:00
MartinYe1234
33eb2d83ed
Skip syntax highlighting for read_file outline responses (#57287)
When `read_file` returns a file outline instead of full contents, the
result is now wrapped in a plain fenced code block rather than tagging
it with the file's path.

Previously, the outline was wrapped in a fenced block tagged with the
file path (e.g. `` ```crates/agent/src/tools/read_file_tool.rs ``).
Because the tag contains a slash, the markdown parser routed it through
`CodeBlockKind::FencedSrc`, resolved the file's language by path, and
ran the language's tree-sitter parser against the outline on every
paint. The outline is structural (e.g. `fn foo [L10-20]`), not actual
source for the file's language, so the parse was both expensive and
produced incorrect highlighting.

Because GPUI rebuilds the visible element tree on every window paint,
anything that triggers a repaint (cursor blink in the focused message
editor, animations, the turn timer, etc.) would re-run the tree-sitter
parse on the entire outline, throttling the frame rate while the tool
call was expanded.

This change adds an `is_outline_response` flag in `ReadFileTool::run`
and, when set, passes an empty tag to `MarkdownCodeBlock` so the
renderer sees `CodeBlockKind::Fenced` (no language). Plain monospace
formatting is preserved; the path tag is still used for the non-outline
(full file) case.

Adds two regression tests: one asserting the outline path uses an
untagged fenced block, and one asserting the full-file path keeps the
path tag (so the next person fixing this doesn't accidentally strip the
tag everywhere).

Also includes a small markdown-rendering follow-up:
`MarkdownElementBuilder::push_text` was recomputing the base text style
(cloning `base_text_style` and walking the style stack) twice per
highlighted token. For a code block with hundreds of highlight tokens,
that's hundreds of redundant `TextStyle` clones per paint. The style
stack does not change while runs are being attributed, so the style is
now computed once outside the loop and reused.

Closes AI-234

Release Notes:

- Improved scrolling smoothness in the agent panel when a `read_file`
tool call with a large file outline is expanded.
2026-05-21 16:16:49 +00:00
Ben Kunkle
560f784776
ep: Increase example capture rate (#57208)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-21 15:23:20 +00:00
Tom Houlé
8d28ca5c01
client: Reconnect cloud websocket after it disconnects (#57078)
The cloud websocket was established once during sign-in and never
re-established. On any server restart or transient network drop the
connection task exited. yawc itself does not reconnect.

This wraps `connect_to_cloud` in a long-lived task that re-establishes
the websocket with exponential backoff and jitter, reusing
`INITIAL_RECONNECTION_DELAY` and `MAX_RECONNECTION_DELAY` so the
behavior matches the Collab reconnect loop in the same module.

Part of CLO-713.

Release Notes:

- N/A
2026-05-21 15:21:19 +00:00
Ben Kunkle
78b5c0e774
Fix bookkeeping error in tracking of language server IDs when dropping single-file worktree (#57298)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-21 13:21:00 +00:00
Ben Brandt
e024200c67
agent_ui: Add keybindable action for terminal threads (#57399)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- Add `agent::NewTerminalThread` for defining custom shortcuts to launch
an Agent Panel terminal thread.
2026-05-21 12:37:12 +00:00
Ben Brandt
800706d7a8
agent: Add experimental update title tool (#57395)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-21 12:25:34 +00:00
Aaron Ang
70733ceb6e
git_graph: Show full commit message in tooltip on hover (#57032)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #56903 

Release Notes:

- Improved commit tooltip in Git Graph.

## Screenshots

Showing full commit message:

<img width="3024" height="1898" alt="CleanShot 2026-05-17 at 21 59
35@2x"
src="https://github.com/user-attachments/assets/503ca832-fc07-4f90-961f-a9c4e25fcba2"
/>

Truncating messages with more than 800 characters:

<img width="1536" height="1096" alt="CleanShot 2026-05-17 at 22 12 07"
src="https://github.com/user-attachments/assets/314be9a9-0aaa-44ff-aa15-de5eb38c863a"
/>


## Alternative

One thing I was considering is whether we should be using a
`HoverPopover` instead so that the preview is wider and we don't have to
truncate the commit message body. I would love to hear your thoughts on
this. For now, I stuck with the `Tooltip` for simplicity reasons.

<img width="3024" height="1896" alt="CleanShot 2026-05-17 at 22 04
39@2x"
src="https://github.com/user-attachments/assets/5b8806f6-3dce-4675-9150-df9257ad6269"
/>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Smit Barmase <heysmitbarmase@gmail.com>
2026-05-21 11:07:12 +00:00
hollmmax
0ec218fa5f
settings_ui: Respect window decorations setting (#57371)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #57370

Release Notes:

- Server-side window decorations now also apply to the settings window.
2026-05-21 10:43:52 +00:00
Bennet Bo Fenner
f15d759bf6
Update single file review docs (#57375)
Release Notes:

- N/A

---------

Co-authored-by: Akrm Al-Hakimi <alk9fh@bosch.com>
2026-05-21 10:43:45 +00:00
Ben Brandt
b13849d04f
google: Add Google thinking level support (#57358)
Also makes sure we are properly catching and processing thinking events.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- google: Support thinking levels for Google models.
2026-05-21 10:00:29 +00:00
Cynthia Rey
97c25c31e4
zed: Make "About" window floating (#57307)
The about window currently is a "Normal" window, which is suboptimal on
tiling window managers.

This changes it to be a floating window, causing less disruptions to
opinionated WM layouts.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- Fixed the "About Zed" dialog being a full window instead of a floating
window.
2026-05-21 09:16:40 +00:00
Finn Evers
c84c22dab5
Deprecate and migrate ACP extensions (#57133)
Self-Review Checklist:

- [X] I've reviewed my own diff for quality, security, and reliability
- [N/A] Unsafe blocks (if any) have justifying comments
- [X] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [X] Performance impact has been considered and is acceptable

Release Notes:

- Removed support for ACP extensions. Installed ACP extensions will be
migrated to use the ACP servers as provided by the ACP registry instead.

---------

Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
Co-authored-by: Marshall Bowers <git@maxdeviant.com>
2026-05-21 08:32:23 +00:00
Tom Houlé
4558d14cf8
google_ai: Support Gemini 3.5 Flash (#57299)
Implements the [official upgrade
instructions](https://ai.google.dev/gemini-api/docs/whats-new-gemini-3.5#migrate-from-3-flash-preview)
for Gemini 3.5 Flash, and adds BYOK support.

The changes about thinking_level and temperature apply to our situation,
but they are only recommendations, and we have to support older models,
so I preferred not trying to force the preferred / remove the
discouraged parameters for now.

`temperature` becomes optional - we don't fill in a default anymore,
since passing it is now discouraged.

This commit also adds support for `thinking_level`, since it is now
preferred to `thinking_budget`.

`FunctionCall` and `FunctionResponse` now support passing an `id` to
properly maintain chain-of-thought preservation and match execution IDs
across turns. When resolving incoming tool uses, the mapper prefers the
execution ID returned by Gemini, falling back to sequential naming in
other scenarios.

Release Notes:

- Added support for Gemini 3.5 Flash in the Google AI model provider.
2026-05-21 07:37:59 +00:00
Oleksiy Syvokon
7f7c21536e
ui: Don't panic on invalid highlight indices in HighlightedLabel (#57291)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
deploy_nightly_docs / deploy_docs (push) Has been skipped
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
HighlightedLabel would crash the application if any provided highlight
index was invalid. In theory, this should never happen. In practice,
this can happen due to race conditions at call sites.

After this change, we only panic in debug builds. In release builds, we
log an error and return a label with no highlights. The error message
includes the call site so that it's easier to fix the root cause.

Related to #57290

Part of FR-11.

Release Notes:

- N/A
2026-05-21 04:01:28 +00:00
Oleksiy Syvokon
ddb847d03a
Fix race condition in OpenPathDelegate (#57290)
Directory entries and string matches can briefly go out of sync during
async updates. When that happens, we used to highlight the wrong
substring (best case), or panic if the offset happens to be mid-Unicode
or out of range.

After this change, we fall back to rendering a row without highlights
when matches are out of sync. The highlight will be shown on the next
frame. This is a rare condition and the easiest fix, so should be
acceptable.

Closes FR-11

Release Notes:

- Fixed rare panic in the open path dialog
2026-05-21 03:59:50 +00:00
Tom Aylott
ee5c7b6d45
Improve link pattern parsing to trim punctuation wrappers (#45457)
Closes # (none)

## Summary

Improved the jump-to-definition reliability for file paths in prose
strings (comments, markdown, etc.) by smarter stripping of surrounding
punctuation.

This allows `cmd/ctrl-click` to work on file paths in contexts like:
- **Markdown backticks**: `` `path/to/file` ``
- **Markdown links**: `[link](path/to/file)`
- **Parentheses**: `(see path/to/file)`
- **Sentence endings**: `Check path/to/file.`
- **Code spans**: `` `cat path/to/file` ``

## Technical Details

- Updated `link_pattern_file_candidates` in `hover_links.rs` to
iteratively trim common leading and trailing punctuation characters.
- Candidate generation now produces multiple variations (trimmed, regex
match, raw) ordered by specificity (most trimmed first).
- Refactored `test_hover_filenames` to be DRY: it now uses a single base
document string and targeted replacements, making it easier to add new
prose test cases without duplication.

Release Notes:

- Improved jump-to-definition reliability for file paths wrapped in
punctuation (backticks, parens, sentence endings).

---------

Co-authored-by: Martin Ye <martin@zed.dev>
Co-authored-by: MartinYe1234 <52641447+MartinYe1234@users.noreply.github.com>
2026-05-20 22:51:14 +00:00
Ben Kunkle
b3ce9a49f7
ep: Don't open unnecessary files during context collection (#57318)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-20 22:42:31 +00:00
Cole Miller
251456cf20
Add some debug logging to understand hangs in the git store's compute_snapshot (#57317)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-20 21:41:33 +00:00
Danilo Leal
0042fb5850
markdown: Add ability to wrap/unwrap codeblock content (#57312)
This PR adds an icon button to Markdown codeblocks allowing to control
whether or not the content should be wrapped. At the moment, this is not
hard-persisted, meaning that 1) wrapping text in one codeblock instance
does not affect others, and 2) the codeblock will be reset every time
its view is recreated (i.e., closing and opening a Markdown Preview tab,
an agent thread, etc.). I intentionally kept it simple just to see how
it feels, but we can certainly consider a setting later on.

| Unwrapping | Wrapping |
|--------|--------|
| <img width="782" height="658" alt="Screenshot 2026-05-20 at 5  09
2@2x"
src="https://github.com/user-attachments/assets/e9151e91-32ba-40d4-9c65-535dec309291"
/> | <img width="736" height="604" alt="Screenshot 2026-05-20 at 5 
09@2x"
src="https://github.com/user-attachments/assets/157db6fd-ec4c-4c96-b44a-119273cbd0f9"
/> |

Release Notes:

- Added the ability to control codeblock content wrapping through the
UI.
2026-05-20 20:51:56 +00:00
María Craig
2b506483b2
docs: Document how to open the Skill Creator (#57314)
Documents the ways to open the Skill Creator in `docs/src/ai/skills.md`:

- From the Agent Panel using the keybinding ({#kb
agent::OpenRulesLibrary})
- From the Agent Panel `...` menu > **Skills**
- From the command palette via {#action agent::OpenSkillCreator}

Release Notes:

- N/A
2026-05-20 20:42:25 +00:00
Richard Feldman
c7b9039e4b
Add runtime diagnostics to git job queue debug dump (#57294)
Adds a `runtime_diagnostics` section to the dev-only "Show Git Job
Queue" output so that when the queue gets stuck, we can tell from the
dump itself whether a git subprocess is wedged (and on supported
platforms, where it's wedged) without needing the user to run
`ps`/`sample`/`lsof` by hand.

The new section contains:

- **`processes`** — every transitive descendant of the Zed process, with
PID, PPID, name, executable, full argv, sysinfo status
(`Run`/`Sleep`/`Stop`/`Zombie`/etc.), and elapsed runtime.
Cross-platform via `sysinfo`. This is the single most useful field: it
instantly answers "is there a stuck `git` child or not?"
- **`linux_proc`** *(Linux only)* — for each descendant,
`/proc/<pid>/wchan` (the kernel function the thread is sleeping in, e.g.
`futex_wait_queue`, `pipe_read`) and `State:` from `/proc/<pid>/status`.
- **`macos_git_children`** *(macOS only)* — for any descendant whose
name contains `git`, a 2-second `sample` user-space stack and `lsof -p`
output. Each is included only if the corresponding system binary exists;
otherwise it's skipped.
- Windows gets just `processes` (no portable way to grab another
process's stack).

### Safety

- Cross-platform: only `sysinfo` (an existing workspace dep) is on the
always-compiled path. All `sample`/`lsof`/`/proc` code is behind
`#[cfg(target_os = ...)]` gates, so Windows builds never see those
symbols.
- Every fallible step is handled individually: on error it logs a
warning and the corresponding key is omitted from the JSON. The queue
dump is built and shown the same way whether `gather()` returned a
populated object, an empty object, or partial data.
- Diagnostics gather runs under `cx.background_spawn(...)` so the macOS
`sample` 2-second wait can't block the foreground.
- `sample`/`lsof` output is truncated to 64 KB per process at a UTF-8
char boundary.

Release Notes:

- N/A
2026-05-20 19:43:07 +00:00
María Craig
814443a466
docs: Fix skill installation instructions (#57289)
Fixes the skill installation instructions in `docs/src/ai/skills.md`.

The previous steps used a `git sparse-checkout` approach that was
inaccurate — the cloned repo would land nested inside the skills folder,
and the sparse-checkout path was wrong for repos that store skills in a
subdirectory. Replaced with a simple instruction to copy the skill's
folder into the appropriate location.

Release Notes:

- N/A
2026-05-20 17:54:47 +00:00
liam
d2953a2b57
Hide agent actions in embedded terminal menus (#56256)
Resolves https://github.com/zed-industries/zed/issues/56138

This diff hides terminal agent actions from context menus shown by
embedded terminal views, such as terminal tool output in agent threads.
Those surfaces render through `TerminalView`, but they are not normal
interactive terminal panes, and actions like Inline Assist and Add to
Agent Thread do not currently resolve the embedded terminal as their
target.

Previously, choosing Inline Assist from terminal tool output could
target the workspace’s active editor instead of the terminal output. The
context menu now limits these agent actions to non-embedded terminal
views, so regular terminal panes keep their existing behavior while
terminal tool output no longer offers actions that cannot resolve to it.

Add to Agent Thread _could_ make sense for embedded terminal selections
in the future, but it would need explicit target-resolution support for
focused embedded terminals. This change keeps that as separate follow-up
work instead of leaving a misleading menu item that does not reliably
act on the selected tool output.

Release Notes:
- Fixed embedded terminal context menus showing agent actions that could
target the wrong item.
2026-05-20 16:03:16 +00:00
María Craig
bb63046a08
docs: Add Skills settings documentation (#57273)
Adds documentation for the Skills settings UI introduced alongside the
Skills feature.

## Changes

- **Updated** `docs/src/ai/skills.md`:
- Updated "Create your own" to lead with `/create-skill` and mention the
Skill Creator UI as a secondary option
- Added "Managing Skills" section documenting the Settings Editor Skills
page (view, open, delete skills)

Release Notes:

- N/A
2026-05-20 15:34:06 +00:00
zed-zippy[bot]
3a81f8e9ab
Bump Zed to v1.5.0 (#57272)
Release Notes:

- N/A

Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>
2026-05-20 14:45:29 +00:00
Kirill Bulatov
80c0f7de0a
Stop building semantic highlights on the main thread (#57264)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
Trace on `main` that showed the hogged main thread: 
[Sample of Zed
Nightly.txt](https://github.com/user-attachments/files/28060310/Sample.of.Zed.Nightly.txt)


Release Notes:

- N/A
2026-05-20 14:12:42 +00:00
María Craig
dd528e3efb
docs: Add Skills documentation (#57095)
Adds documentation for the new Skills feature, which replaces Rules
starting in Zed v1.4.0.

## Changes

- **New page**: `docs/src/ai/skills.md` — covers what skills are,
finding and installing skills from skills.sh, using skills via slash
commands and model invocation, creating a skill (folder structure,
SKILL.md format, frontmatter fields, bundled resources), where skills
live (global vs project-local), security model, and limitations
- **Updated**: `docs/src/ai/rules.md` — added deprecation notice
pointing to Skills
- **Updated**: `docs/src/SUMMARY.md` — added Skills entry above Rules in
the AI section
- **Updated**: `docs/src/ai/agent-panel.md` — replaced reference to
"rules files" with "skills" in the Adding Context section

Release Notes:

- Added documentation for the Skills feature

---------

Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>
Co-authored-by: Danilo Leal <daniloleal09@gmail.com>
2026-05-20 14:10:59 +00:00
Danilo Leal
a4c6a8392d
settings_ui: Fix skills link (#57265)
This PR ensures clicking to copy the skills link in the settings UI
works properly.

Release Notes:

- N/A
2026-05-20 14:00:43 +00:00
Ben Brandt
43b7ca9cc2
terminal: Fix pty info change detection race (#57257)
I think I introduced this at some point in the terminal agent situation.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-20 13:13:00 +00:00
Ben Brandt
1103bd8055
agent_ui: Improve agent terminal notification visibility logic (#57248)
Aligns Terminal notifications much closer to Thread notifications

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-20 12:47:18 +00:00
Oleksiy Syvokon
d33a3186aa
Respect max line limit for invisible character replacements (#57137)
This change makes sure that `LineWithInvisibles::from_chunks` applies
the max line length limit to invisible character replacements as it does
to normal text chunks.

Without this change, pathological lines containing many invisible
characters could produce unbounded number of line fragments.

Closes FR-6.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable


Release Notes:

- Fixed a rare panic that could occur when lines in the editor contained
many invisible characters.
2026-05-20 12:41:02 +00:00
Marshall Bowers
bc363322af
Upgrade tree-sitter to v0.26.9 (#57183)
This PR upgrades `tree-sitter` to v0.26.9.

We're interested in
https://github.com/tree-sitter/tree-sitter/pull/5605, which should fix a
panic when loading certain grammars.

Closes FR-1.

Release Notes:

- Fixed a panic when loading certain Tree-sitter grammars containing
supertypes.
2026-05-20 10:46:54 +00:00
Cameron Mcloughlin
e82c04b356
agent: Pull diagnostics (#56663)
Currently, the `diagnostics` tool queries the current state of the
workspace. However, if the LSP is slow to update diagnostics, this can
lead to stale diagnostics being given to the agent.

This PR changes the `diagnostics` tool to attempt to pull fresh
diagnostics. If it fails, it informs the agent and falls back to the old
behaviour (not all LSPs support pull-based diagnostics).

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-20 08:57:46 +00:00
Bennet Bo Fenner
80d41375e5
agent: Save files when model uses rename tool (#57228)
Release Notes:

- N/A
2026-05-20 08:36:32 +00:00
Tom Houlé
5656f3eb3f
client: Use cloud as source of truth for the selected organization (#57140)
Now that the cloud platform exposes a system-settings endpoint for the
user's selected organization, switch `UserStore` over to it and drop the
local database persistence. The server already returns the current
selected organization for `get_authenticated_user()`.

set_current_organization becomes a optimistic, with the in-memory
selection updated immediately. hen a background task POSTs to the system
settings endpoint.

Stale current_organization_id rows from older installs are left dangling
— harmless and not worth a migration. This is the second step in moving
organization selection to cloud; the first added the
update_system_settings client method.

Part of CLO-716

Release Notes:

- N/A

---------

Co-authored-by: Marshall Bowers <git@maxdeviant.com>
2026-05-20 07:00:02 +00:00
Tom Houlé
0f6ebdd269
cli: Respect --new when opening URLs from the CLI (#54408)
`zed --new ssh://host/path/to/file` only created a new window on the
first call. Subsequent invocations silently reused the existing SSH
workspace for the same host, which then tried to open the new path
against the existing worktree and surfaced a
`DevServerProjectPathDoesNotExist` popup when the path didn't belong to
any open worktree.

The CLI correctly translated `--new` to `OpenBehavior::AlwaysNew`, but
the URL branch of `handle_cli_connection` dropped the `open_behavior`.
`handle_open_request` then called `open_remote_project` (and
`open_paths_with_positions` for `file://`) with
`OpenOptions::default()`, which is `WorkspaceMatching::MatchExact`, so
any existing SSH window for the same host won the match. The issue
applies to `file://` URLs and `-a` / `-e` / `--reuse` for URL-shaped
arguments in general; `--new` was just the most visible symptom.

The fix is making sure the translation of `OpenRequest` is uniform
across plain paths and URL-shaped arguments.

Closes #52679.

Release Notes:

- Fixed `zed --new ssh://host/path` reusing an existing SSH window
instead of opening a new one. This also applied to other URL-shaped path
arguments.
2026-05-20 06:58:10 +00:00
Liber
068d64edd6
vim: Fix n/N and */# selecting text after cmd+f search (#54027)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
The cmd_f_search flag introduced in #51073 was never cleared when
switching to vim-style search commands, causing collapse_matches to
remain false and match ranges to appear as visual selections.

Reset cmd_f_search when n/N or */# are used, restore Normal mode if
Visual was entered due to the non-collapsed selection, and fix an early
return in visual select_match that leaked collapse_matches.

Fixes #53896

Self-Review Checklist:

- [ ] I've reviewed my own diff for quality, security, and reliability
- [ ] Unsafe blocks (if any) have justifying comments
- [ ] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [ ] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

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

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2026-05-20 03:39:36 +00:00
MartinYe1234
e2c38b5358
Replace Rules UI with Skills creation UI (#56924)
Replaces the legacy Rules creation UI with a focused "New Skill"
creation window when the `SkillsFeatureFlag` is on.

The new `skills_library` crate provides a single-skill form with:
- Name, Description, and Body fields (placeholders double as labels)
- Live validation matching the SKILL.md spec (name: 1–64 lowercase +
digits + hyphens, no leading/trailing hyphen; description: non-empty,
≤1024 chars)
- A scope dropdown listing every local worktree in the originating
workspace plus "Global"
- An Optional Parameters card with the `disable-model-invocation`
checkbox
- Save writes `<scope>/.agents/skills/<name>/SKILL.md` via
`serde_yaml_ng` (YAML-safe escaping), refuses to overwrite existing
skills, shows a success toast in the originating workspace, then closes
the window

The "Rules" entry in the agent panel triple-dot menu is renamed to
"Skills" when the flag is on. The existing `cmd-alt-l` keyboard shortcut
still works: `AgentPanel::deploy_rules_library` reroutes to
`deploy_skills_library` when the flag is on, so any persisted keymaps
and the menu's automatic shortcut lookup keep functioning without
changes to the default keymap files.

The old `rules_library` crate is intentionally left in place for this PR
— once the flag rolls out and the few remaining `OpenRulesLibrary {
prompt_to_select }` call sites (in thread_view link handlers and
@-mention crease) are migrated to an "open existing skill" flow, a
follow-up can delete the crate entirely.

15 unit tests cover the validation rules, frontmatter formatting
(including YAML-special-character round-tripping), and disk write
behavior (creates directory, refuses overwrite).

Closes AI-247

Release Notes:

- Added a new Skills creation UI that replaces the old Rules library
when the Skills feature flag is enabled.

---------

Co-authored-by: Danilo Leal <daniloleal09@gmail.com>
2026-05-20 02:40:57 +00:00
David
661f185f9f
Add file icon for Ballerina (.bal) files (#56799)
## Summary

- Adds a `ballerina` icon key to the default icon theme, mapping the
`.bal` file suffix to a new SVG under
`assets/icons/file_icons/ballerina.svg`.
- Icon is the monochrome Ballerina mark from the official WSO2 VS Code
extension, rescaled to Zed's 16×16 viewBox.

## Icon source / license

The SVG is adapted from `ballerina-inverse.svg` in
[wso2/vscode-extensions](https://github.com/wso2/vscode-extensions),
which is Apache-2.0 licensed. The original 400×400 geometry is preserved
via the existing `translate`/`scale` transform; only the viewBox and
fill were normalized to match the convention used by the other icons in
`assets/icons/file_icons/`.

## Test plan

- [x] `cargo build --release --bin zed`
- [x] Opened a folder containing `.bal` files and confirmed the icon
renders in the project panel and tabs.
- [x] Alphabetical ordering preserved in both
`FILE_SUFFIXES_BY_ICON_KEY` and `FILE_ICONS`.

Release Notes:

- N/A

---------

Co-authored-by: Danilo Leal <daniloleal09@gmail.com>
Co-authored-by: Danilo Leal <67129314+danilo-leal@users.noreply.github.com>
2026-05-20 02:33:07 +00:00
Agus Zubiaga
7c10059340
ui: Add thousands separators to diff stats (#56754)
<img width="282" height="90" alt="CleanShot 2026-05-14 at 11 28 40@2x"
src="https://github.com/user-attachments/assets/34516022-0e26-4380-9e80-568256483309"></img>

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- Improved diff stats by formatting large line counts with thousand
separators.
2026-05-20 02:22:25 +00:00
Danilo Leal
1ddf7407e9
Use the announcement toast for skills support (#56873)
Closes AI-244

This PR changes the approach for announcing skills support. It uses the
announcement toast, the same thing used for parallel agents, which
observes a specific version number to be displayed. I ended up
simplifying things a bit by thinking we could rely on documentation for
more detailed information (with more extensive paths and whatnot).

Release Notes:

- N/A

---------

Co-authored-by: Richard Feldman <richard@zed.dev>
Co-authored-by: MartinYe1234 <52641447+MartinYe1234@users.noreply.github.com>
Co-authored-by: Martin Ye <martinye022@gmail.com>
2026-05-20 01:26:06 +00:00
Richard Feldman
2e70059cd9
Remove Skills feature flag (#57162)
Removes the `skills` feature flag now that Skills are ready to ship to
all users. Cleans up all `cx.has_flag::<SkillsFeatureFlag>()` gates
across the agent, agent_ui, prompt_store, and title_bar crates, drops
the now-unused `feature_flags` dependency from `prompt_store` and
`title_bar`, and removes the dead `update_flags(true, vec!["skills"])`
calls from the agent's skills tests.

Closes AI-269

Release Notes:

- Enabled Skills for all users.

---------

Co-authored-by: MartinYe1234 <52641447+MartinYe1234@users.noreply.github.com>
Co-authored-by: Martin Ye <martinye022@gmail.com>
2026-05-20 00:28:09 +00:00
Mikayla Maki
952119de41
Fix window crash (#57203)
Closes ZED-86Q

Fixes this (rare) crash by making entity creation via a window context
infallible.

The shape of the result is a bit clunky due to the type signatures
involved. The real solution is to remove AsyncWindowContext entirely and
move it's fallible APIs into WindowHandle, but until then this will give
you a simple starting point.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-20 00:05:34 +00:00
Helmer Nordström
d42edc15f9
grammars: Add runnables.scm for C++ (#57161)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
Added a runnables.scm for cpp grammar so that tasks can be made with the
play button. It is already implemented for C.
2026-05-19 22:03:01 +00:00
Tom Zaspel
1d207b02e0
docs: Update Tree-sitter reference in OpenTofu and Terraform languages (#57168)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)

Release Notes:

- N/A
2026-05-19 21:57:50 +00:00
Jakub Konka
7b6be29669
linux: Bundle libstdc++.so for release (#57132)
Self-Review Checklist:

- [ ] I've reviewed my own diff for quality, security, and reliability
- [ ] Unsafe blocks (if any) have justifying comments
- [ ] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [ ] Performance impact has been considered and is acceptable

Closes https://github.com/zed-industries/zed/issues/57073

Release Notes:

- Fixed running Zed on Ubuntu 20.04 installed via the installer by
bundling the required `libstdc++.so`.
2026-05-19 21:43:35 +00:00
Joseph T. Lyons
a11af20495
Disable auto watch when leaving a call (#57196)
Auto watch's lifespan should be tied to that of the call and it should
not be assumed the user wants to have this on indefinitely (until app
restart), as it's more of a niche feature. This PR disables it when the
user leaves a call.

Self-Review Checklist:

- [X] I've reviewed my own diff for quality, security, and reliability
- [X] Unsafe blocks (if any) have justifying comments
- [X] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [X] Tests cover the new/changed behavior
- [X] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-19 21:31:34 +00:00
Danilo Leal
be0fc7fdf5
Add settings UI page for skills (#57101)
Closes AI-267

This PR adds a skills subpage in the settings UI, where we display
global skills in the user tab and project skills in the corresponding
project tab. The approach taken here was the simplest one out of the
possible avenues we could've taken to implement this (which would
possibly require bigger refactors), given this is potentially the very
first page in the settings UI where we're displaying stuff that does not
correspond to data available in the `settings.json`.

Important to note that a major limitation of the global approach is that
it's dependent on the native agent having loaded the skill index,
meaning there's an edge case where, if you open the settings UI _before_
having opened the agent panel, you won't immediately see the available
skills. Something to discuss but that it felt like a viable option for a
first ship.

Release Notes:

- Agent: Added a skills section to the settings UI.
2026-05-19 21:12:44 +00:00
Ben Brandt
0535f47291
sidebar: Don't block worktree archival on empty drafts (#57145)
If we have empty drafts, they don't show up in the UI, so you can't get
rid of them. But they currently blocked worktree archival. Which is
particularly troublesome with terminal agents in a few cases.

This should hopefully solve the issue for terminals, but I think I need
to do a follow-up to investigate what happens when the last draft is
closed.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-19 21:08:39 +00:00
Ben Brandt
a39f1d163d
docs: Add more agent configuration examples (#57188)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-19 21:08:14 +00:00
Ben Kunkle
ad042e5c9d
fs: Don't opt into polling for virtiofs based file systems (#57184)
Technically we don't know if a `virtiofs` file system supports `inotify`
or not, but it seems like it's mostly used inside virtual machines
provided by:
- OrbStack (`inotify` works)
- Docker Desktop (`inotify` works)
- Lima (`inotify` works with flag)
- Colima (`inotify` works with flag)
- QEMU + virtiofs setup (`inotify` doesn't work without extra setup)

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #57103 

Closes FR-9

Release Notes:

- Fixed an issue where file system watching would default to the polling
backend inside of `OrbStack` VMs on MacOS
2026-05-19 20:14:50 +00:00
María Craig
40d3c79f2f
Update workspace mentions in the sidebar (#54833)
Replaces "workspace" labels in the sidebar with more accurate
terminology:

- "Focus Last Workspace" → "Focus Last Project"
- "Focus Workspace" → "Focus Project"
- "Close Workspace" tooltip → "Close Worktree"

Release Notes:

- N/A
2026-05-19 20:05:13 +00:00
María Craig
69effe73d9
docs: Document Terminal Threads feature (#56679)
Adds documentation for the Terminal Threads feature — the ability to
open interactive terminals in the Agent Panel alongside threads.

## Changes

- **`agent-panel.md`**: Adds a new `## Terminals` section covering how
to open terminals, terminal titles, bell notifications, and closing.
Also adds a Terminal bullet to the `+` menu description in "Creating New
Threads".
- **`parallel-agents.md`**: Updates the page title, description, and
opening paragraph to include terminals alongside threads. Adds a note in
the Threads Sidebar section that terminals appear there too.

Release Notes:

- N/A

---------

Co-authored-by: Zed Zippy <234243425+zed-zippy[bot]@users.noreply.github.com>
Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2026-05-19 19:21:41 +00:00
Richard Feldman
8dff89c8d1
Fix Gemini schema conversion dropping anyOf and nullability (#57160)
Follow-up to #49292:

- **Bug fix in `push_any_of_constraint`**: when both an `anyOf` and a
non-empty `allOf` were already present at the same level, the existing
`anyOf` was silently dropped. Now it's always preserved.
- **Canonical OpenAPI nullability**: collapse `{nullable: true}`-only
entries out of `anyOf` onto the parent so `anyOf: [{type: "string"},
{type: "null"}]` becomes `{type: "string", nullable: true}` (the form
Gemini actually expects) instead of `anyOf: [{type: "string"},
{nullable: true}]`.
- **Compile-time path consistency**: route `ToJsonSchemaSubsetTransform`
through the same `convert_null_in_types_to_nullable` helper so
Rust-defined tools using `Option<T>` also keep nullability on Gemini,
instead of silently truncating to the non-null type.
- Drop an unnecessary clone in `push_any_of_constraint` and simplify
`convert_types_to_any_of_defs`.
- Add a small `obj()` test helper and a regression test for the `anyOf +
allOf + multi-type` case.

Release Notes:

- Fixed `Option<T>` tool parameters being sent to Gemini without their
nullability, and fixed tool schemas with `anyOf` + `allOf` losing
constraints during the OpenAPI 3.0 conversion

Co-authored-by: Daniel Strobusch <1438302+dastrobu@users.noreply.github.com>
2026-05-19 19:04:48 +00:00
Ben Kunkle
a0aa3e842f
fs: Poll until watched path is created instead of watching parent (#57152)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Part of FR-9.

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-19 17:55:54 +00:00
Cole Miller
57a64fc824
Add some more logging to diagnose lost FS events and stale git state (#57173)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A

---------

Co-authored-by: Ben Kunkle <ben@zed.dev>
2026-05-19 17:53:00 +00:00
Tom Houlé
0d832bc6d5
Implement MCP OAuth client preregistration (#52900)
In the interactive MCP OAuth flow, the MCP client registers itself with
the authorization in one of three ways:

- Client ID Metadata Document aka CIMD (recommended default). This is
already implemented: https://zed.dev/oauth/client-metadata.json.
- Dynamic Client Registration (DCR). This is the traditional method.
Also already implemented in Zed.
- Pre-registration: the client is registered out of band, typically in
the IdP or SaaS provider's UI. You get a client id and maybe a client
secret, that have to be provided by the MCP client when it wants to
exchange an access token. This is what this pull request is about.

This PR has two main parts:

- Allow users to configure a client id and optional client secret for an
MCP server in their configuration, under a new `oauth` key, and take it
into account
- Make the MCP server state and the configuration modal aware of the
intermediate states (client secret missing) and error cases stemming
from client pre-registration.

The client secret can be stored either in the system keychain or in
plain text in the MCP server configuration. The UI tries to steer user
towards the more secure option: the keychain.

<img width="715" height="201" alt="Screenshot 2026-04-10 at 16 48 06"
src="https://github.com/user-attachments/assets/5e64103e-6746-4ef0-8bd9-533d492b6912"
/>

<img width="884" height="544" alt="Screenshot 2026-04-10 at 16 47 07"
src="https://github.com/user-attachments/assets/0e35bb3c-cbc4-4e8c-a713-66323597b2e2"
/>


<img width="785" height="558" alt="Screenshot 2026-04-10 at 16 47 23"
src="https://github.com/user-attachments/assets/03339187-1508-461a-87ae-a7c2647df9a5"
/>



Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes
https://github.com/issues/assigned?issue=zed-industries%7Czed%7C52198

**Note for the reviewer: I know how busy the AI team is at the moment so
please treat this as low priority, we don't have signal that this is a
highly desired feature. It's a rather large PR, so I'm happy to pair
review / walk through it.**

Release Notes:

- Added support for OAuth client pre-registration (client id, client
secret) to the built-in MCP client.
2026-05-19 17:45:07 +00:00
alkinun
c0596fade7
markdown: Fix escaping non-ASCII chars (#55782)
Fixes #55704

The `escape` function in `crates/markdown/src/markdown.rs` was calling
`c as u8` on the `char`s before passing to `MarkdownEscaper::next()`.
This strips non ASCII Unicode codepoints down to just their low 8 bits
which might be in the ASCII punctuation range and thus cause an extra
backslash to be added in front of these non ASCII chars.
 
Release Notes:

- Fixed a bug where non-ASCII chars in diagnostic messages were
incorrectly rendered with spurious `\` characters
2026-05-19 17:20:24 +00:00
Oleksiy Syvokon
a949cabb32
Fix crash in manipulate_text on multibuffers (#57165)
In `Editor::manipulate_text`, we computed selection boundaries for the
updated text assuming the requested edit would be applied exactly. This
is not always true. As a result, we could produce an invalid selection
range and panic.

This change replaces manual selection boundary computation with anchors.
It also skips edits when `new_text == old_text`.

Closes FR-10.

Release Notes:

- N/A
2026-05-19 17:04:29 +00:00
Daniel Strobusch
ae47ec9ac0
language_models: Fix Gemini tool parameter nullability and multi-type schema (#49292)
Transform JSON schemas for Google AI tools to use `nullable: true`
instead of `type: ["type", "null"]`, which is not supported by the
Gemini API.

Additionally, convert multi-type arrays (e.g., `type: ["string",
"number"]`)
to `anyOf` constraints, as Gemini expects a single string for the `type`
field.

This handles recursive transformation of properties, items, definitions,
and logical operators, safely merging conflicting `anyOf` and `allOf`
constraints.

Closes https://github.com/zed-industries/zed/issues/44875
Closes https://github.com/zed-industries/zed/issues/32429

Release Notes:

- Fixed a bug where using Gemini with certain tools (especially via MCP)
resulted in "Invalid JSON payload received" errors due to incompatible
JSON schema formats.

## Testing

Added unit tests in `crates/language_model/src/tool_schema.rs` covering
nullability, multi-types, and `oneOf` conversions.

### Manual Testing with MCP Test Server
The [MCP Test Server](https://github.com/dastrobu/mcp-test-server) was
used to verify these edge cases with Gemini 3 Flash.

#### Setup
1. Install the test server: `cargo install --git
https://github.com/dastrobu/mcp-test-server`
2. Add to Zed `settings.json`:
   ```json
   "context_servers": [
     {
       "command": "mcp-test-server"
     }
   ]
   ```


Use the following pattern in a chat window:

```
call the add_tool function to create a new tool: weather with input schema: 

  {
    "type": "object",
    "properties": {
      "city": { "type": ["string", "null"] }
    }
  }
```
Afterwards:
...

```
call it
```

Without fix: 

<img width="671" height="448" alt="image"
src="https://github.com/user-attachments/assets/e8b6e7bd-d431-4a7e-8c9a-fff73d82127d"
/>

With fix:

<img width="729" height="334" alt="image"
src="https://github.com/user-attachments/assets/eb758765-4c34-4915-a8cf-dd4bfb993619"
/>

#### Cases verified manually:



**1. Nullability in properties**
- **Input:**
  ```json
  {
    "type": "object",
    "properties": {
      "city": { "type": ["string", "null"] }
    }
  }
  ```
- **Converted:**
  ```json
  {
    "type": "object",
    "properties": {
      "city": { "type": "string", "nullable": true }
    }
  }
  ```

**2. Multi-type properties**
- **Input:**
  ```json
  {
    "type": "object",
    "properties": {
      "city": { "type": ["string", "number"] }
    }
  }
  ```
- **Converted:**
  ```json
  {
    "type": "object",
    "properties": {
      "city": {
        "anyOf": [
          { "type": "string" },
          { "type": "number" }
        ]
      }
    }
  }
  ```

**3. Explicit `anyOf` with nullability**
- **Input:**
  ```json
  {
    "type": "object",
    "properties": {
      "city": {
        "anyOf": [
          { "type": "string" },
          { "type": "null" }
        ]
      }
    }
  }
  ```
- **Converted:**
  ```json
  {
    "type": "object",
    "properties": {
      "city": {
        "anyOf": [
          { "type": "string" },
          { "nullable": true }
        ]
      }
    }
  }
  ```

**4. Conflicting `anyOf` sources (Multi-type + existing `anyOf`)**
- **Input:**
  ```json
  {
    "type": "object",
    "properties": {
      "city": {
        "type": ["string", "number"],
        "anyOf": [
          { "minLength": 5 }
        ]
      }
    }
  }
  ```
- **Converted:**
  ```json
  {
    "type": "object",
    "properties": {
      "city": {
        "allOf": [
          { "anyOf": [{ "minLength": 5 }] },
          { "anyOf": [{ "type": "string" }, { "type": "number" }] }
        ]
      }
    }
  }
  ```

Co-authored-by: Richard Feldman <richard@zed.dev>
2026-05-19 15:56:34 +00:00
Ben Brandt
ad437c93c2
sidebar: Fix stale sidebar thread header state (#57017)
There was a case where if you archived or closed all threads, you
wouldn't see the empty state again.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-19 14:43:38 +00:00
Danilo Leal
c5f6fca756
Don't show trust modal for linked worktrees if main is trusted (#57153)
Follow up to https://github.com/zed-industries/zed/pull/57056 — This PR
ensures we're refreshing the security modal so that it consumes the
trust given to the main worktree when creating a new linked (Git)
worktree.

Release Notes:

- N/A
2026-05-19 14:32:46 +00:00
Ben Brandt
589dc95c87
agent_ui: Restore last active agent panel entry (#57150)
Makes sure we can reload the last terminal, and also keeps track more
globally what your last agent type was so we can carry that over to new
workspaces

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-19 14:07:09 +00:00
Danilo Leal
3a821765e5
icons: Update some icon SVGs (#57151)
Just some house-keeping here, aligning and fixing size on some SVGs.

Release Notes:

- N/A
2026-05-19 13:28:45 +00:00
Bennet Bo Fenner
da43bdb648
agent: Support image output from MCP tools (#57134)
Release Notes:

- agent: Support image output from MCP tools
2026-05-19 12:51:42 +00:00
Bennet Bo Fenner
c352cad169
agent: Replay image output (#57143)
Release Notes:

- agent: Fix image output from tools not being reloaded when restoring
thread
2026-05-19 12:29:35 +00:00
Conrad Irwin
46b08f9d7d
gpui: Trim trailing whitespace and punctuation before ellipsis (#57106)
When truncating text at the end with an ellipsis, the truncation point
can land right after a space or punctuation character, producing results
like `"some text …"` or `"some text-…"`.

This trims trailing whitespace and ASCII punctuation from the truncated
prefix before appending the ellipsis affix, so you get clean results
like `"some text…"` instead.

Release Notes:

- Improved text truncation to avoid trailing spaces or punctuation
before the ellipsis.
2026-05-19 11:46:05 +00:00
Ben Brandt
4557ad7ad1
eval_cli: Initialize themes in eval headless mode (#57139)
Also fix patch generation

Release Notes:

- N/A
2026-05-19 11:29:00 +00:00
Kunall Banerjee
85f410004c
agent_ui: Trigger @-mention menu after opening brackets (#55504)
Typing `@` immediately after `(`, `[`, or `{` did not open the Agent
Panel’s @-mention completion menu, so `(@file)`, `[@file]`, and
`{@file}` were unusable. This has been bothering me for quite some time
now. Overall, I believe this is a QoL improvement, albeit a small one.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [ ] Unsafe blocks (if any) have justifying comments
- [ ] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [ ] Performance impact has been considered and is acceptable

Release Notes:

- Fixed the Agent Panel’s @-mention menu not appearing when `@`
immediately follows `(`, `[`, or `{`.

---------

Co-authored-by: Bennet Bo Fenner <bennetbo@gmx.de>
2026-05-19 10:05:49 +00:00
Ben Brandt
938490639a
agent_ui: Activate workspace from terminal notifications (#57096)
We weren't activating and focusing the right thing before.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-19 09:55:02 +00:00
Bennet Bo Fenner
8708a6fa74
agent: Do not decode images during render (#56866)
Turns out we were creating an ImageDecoder on every frame (added in
#46167) when a tool returned an image as output, because we were trying
to get its dimensions. That is now cached on `ContentBlock::Image`.

Release Notes:

- N/A
2026-05-19 09:51:42 +00:00
zed-zippy[bot]
b8dce970fa
extension_ci: Bump extension CLI version to 2a00db0 (#57098)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
This PR bumps the extension CLI version used in the extension workflows
to `2a00db06ce6d01089bfafd207b6348078e980df9`.

Release Notes:

- N/A

Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>
2026-05-19 07:01:38 +00:00
Marshall Bowers
14befe2151
agent: Fix a panic when splitting streamed-in edits inside of a multibyte character (#57100)
This PR fixes a panic that could occur in the `edit_file` tool where
streaming in text could split in the middle of a multibyte character.

Closes FR-3 and [ZED-7ZX](https://zed-dev.sentry.io/issues/7480598098).

Release Notes:

- Fixed a panic that could occur when streaming in text with the
`edit_file` tool.
2026-05-19 06:44:48 +00:00
Danilo Leal
8ca194d833
Add built-in create-skill skill (#57064)
Closes AI-266

This PR adds a built-in skill called `create-skill`, which allows the
Zed agent to have access to a skill that teaches it how to properly
create skills for Zed. You can manually invoke it as well as just
letting the model auto-invoke it in case your prompt suggests creating a
new skill.

Release Notes:

- Agent: Added a built-in skill called `create-skill` to make the Zed
agent informed about how to do that.

---------

Co-authored-by: Richard Feldman <richard@zed.dev>
2026-05-19 00:16:04 +00:00
Higor Prado
980a294292
gpui: Prefer Mailbox present mode on Wayland to avoid FIFO stalls (#57077)
The WgpuRenderer defaults to VK_PRESENT_MODE_FIFO_KHR (vsync), which
blocks vkQueuePresentKHR until the compositor releases a buffer via
wl_surface.frame. On some Wayland compositor+driver combinations
(notably NVIDIA proprietary + Hyprland, but also observed on KDE/GNOME +
AMD RADV), these frame callbacks can be delayed or lost, stalling the
entire calloop event loop for tens of seconds.

VK_PRESENT_MODE_MAILBOX_KHR does not block on vblank: it replaces the
pending frame in a single-entry queue. This avoids the stall entirely.
The renderer already falls back to Fifo automatically if Mailbox is
unsupported by the driver.

The WgpuSurfaceConfig has had a preferred_present_mode field since
#50815 (added for Android lifecycle transitions with the same
rationale). This commit sets it to Mailbox in the Wayland window
creation path only. X11 is not affected.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Note on tests: This change is in the Wayland platform's window creation
path (WaylandWindowState::new). The surface configuration is delegated
to WgpuRenderer which already has test coverage for
preferred_present_mode fallback logic. A full integration test would
require a running Wayland compositor in CI. Verified manually and tested
against the renderer's unwrap_or(Fifo) safety net by inspecting
surface_caps.present_modes on both NVIDIA proprietary and Mesa RADV
drivers.

Closes: #50229
Closes: #55345
Closes: #39097
Closes: #50734

Refs: #38497, #52009, #52403, #50574, #49961, #47750, #46203, #50195,
#50283, #42164, #39156, #39234, #35948, #32618

Release Notes:

- Fixed UI freezes on Linux (Wayland) when on certain GPU/driver
combinations

---------

Co-authored-by: Neel <neel@zed.dev>
2026-05-18 23:57:51 +00:00
Gepcel
9abb73ee32
xtask: Fix setup-webrtc config overwrite refusal and Windows path format (#57058)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] No unsafe blocks
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #57057

Release Notes:

- N/A

---------

Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>
2026-05-18 22:32:04 +00:00
Ben Brandt
2a00db06ce
node_runtime: Respect npm release-age filters for managed npm installs (#56957)
Zed-managed npm installers were resolving a concrete latest version with
`npm info` and then installing `package@version`. That is brittle when
users
configure npm release-age filtering via `before` or `min-release-age`:
npm's
installer applies those rules during resolution, but our pinned install
target
could disagree with it, and therefore fail to install.

This changes managed npm installs to install `package@latest` and let
npm apply
its own resolver and user config. The local latest-version lookup
remains as a
best-effort cache freshness check, not as the exact install target.

Exact extension API installs remain unchanged because extensions
explicitly
request a package and version. If we want to revisit that we can.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #53611

Release Notes:

- Fixed npm-backed tool installs to better respect npm release-age
filters.
2026-05-18 21:10:06 +00:00
Ben Brandt
10fc0fb527
Update wgpu to 29.0.3 (#57086)
Updates our fork to the latest v29 branch. Still waiting on a backport
to get upstreamed so we can go back to the main crate.

Release Notes:

- N/A
2026-05-18 19:07:09 +00:00
Ben Brandt
c3951af24f
acp: Support additional session directories (#57051)
Still behind a feature flag for now for testing with various agents.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-18 18:27:54 +00:00
Neel
7a37888f7b
editor: Add action to toggle all diff hunks (#56421)
Release Notes:

- Added action to toggle all diff hunks
2026-05-18 18:02:51 +00:00
Vlad Ionescu
7dcd422a73
opencode: Model updates (#57076)
**TL;DR**: clearer docs + models cleanup.

----

**Docs**: 
- as per the discussion in
https://github.com/zed-industries/zed/issues/56869, added a note to the
docs highlighting that temporary models should be configured using
Custom Models. Adding a whole example felt redundant considering the
full example is literally 2 rows below.


**Model updates**:
- **Ring 2.6 1T Free**: removed
- **GLM 5 and GLM 5.1**: different settings based on subscription —
[131k](8e710e19ea/providers/opencode/models/glm-5.1.toml (L22))
[output](8e710e19ea/providers/opencode/models/glm-5.toml (L22))
on OpenCode but
[32k](8e710e19ea/providers/opencode-go/models/glm-5.1.toml (L22))
[output](8e710e19ea/providers/opencode-go/models/glm-5.toml (L22))
on OpenCode Go
- **MiniMax M2.5**: different settings based on subscription — [131k
output on
OpenCode](8e710e19ea/providers/opencode/models/minimax-m2.5.toml (L22))
and [65k on OpenCode
Go](8e710e19ea/providers/opencode-go/models/minimax-m2.5.toml (L19))
- **Nemotron 3 Super Free**: enabled interleaved reasoning as per
[docs](8e710e19ea/providers/opencode/models/nemotron-3-super-free.toml (L13)).
Ran some quick tests and confirmed everything seems to work fine
(_"rename this variable. add a simple function. remove the function.
tell me a joke"_)
- **GPT 5.3 Codex Spark**: removed image support as per
[docs](https://github.com/anomalyco/models.dev/blob/dev/providers/opencode/models/gpt-5.3-codex-spark.toml#L23-L25)

The [docs say GLM 5 in OpenCode Zen has a deprecation date of May
14](https://opencode.ai/docs/zen/#deprecated-models) but that seems to
still be active and is [not marked as deprecated on
models.dev](8e710e19ea/providers/opencode/models/glm-5.toml)
so I didn't remove it yet 🤷

----

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes https://github.com/zed-industries/zed/issues/56869

Release Notes:
- OpenCode: updated models (removed Ring 2.6 1T Free, enabled
interleaved reasoning for Nemotron 3 Super Free, deleted incorrect image
support for GPT 5.3 Codex Spark, and updated token counts for MiniMax
M2.5, GLM 5, and GLM 5.1)
- OpenCode Free: clearer docs for temporary free models
2026-05-18 17:15:04 +00:00
Danilo Leal
b9ba43c9c1
agent_ui: Add mention disambiguation (#56926)
Closes AI-261

This PR adds mention disambiguation in the agent panel, which works both
for regular @-mentions as well as for skills. Effectively, when you
mention files with the same name, the mention crease displays the next
path parent name, following a similar approach to common tabs in the
editor. For skills, the skill source is displayed (either global or from
some project).

<img width="500" alt="Screenshot 2026-05-15 at 6  32@2x"
src="https://github.com/user-attachments/assets/72c99480-cf32-42ac-9304-3f65167a1d94"
/>

Release Notes:

- Agent: Improved file and skill mention disambiguation in the agent
panel.

---------

Co-authored-by: Richard Feldman <richard@zed.dev>
2026-05-18 16:36:37 +00:00
Danilo Leal
ec9ba5f069
Make restricted mode more obvious (#57056)
Closes TRA-150

This PR makes the restricted mode more obvious by:

- Immediately opening the restricted mode modal upon opening an
untrusted project
- Disabling dismissing the modal on escape or click away to force
choosing one of the two options (and avoid accidentally staying in
restricted mode by simply dismissing it)
- Showing the LSP button but with communication about language servers
being disabled for untrusted projects
- Showing a banner in the project settings with the same communication

The motivation for this change was that we tried to be minimal with how
we communicate a project is untrusted, but it was so minimal that people
were confused as to why language servers and other settings weren't
working. It was easy to miss the title bar button, for some reason. The
changes in this PR makes it so acting on this decision (trust or not a
project) is mandatory in order to even start to interact with the
project. I appreciate changes here are more aggressive, but I think it's
better to make you think about this decision vs. letting you be confused
as to why you don't see LS completions or formatting.

Release Notes:

- Made restricted mode more obvious, demanding immediate action when
opening an untrusted project.
2026-05-18 16:18:59 +00:00
Hadley99
ea01b926ea
languages: Exclude angle brackets from rainbow bracket colorization for Javascript (#57063)
## Summary

Extends #51311 to JSX in JavaScript files, which uses the same
javascript grammar for both .js and .jsx.

## Changes

- Added (#set! rainbow.exclude) to the three angle bracket patterns in
crates/grammars/src/javascript/brackets.scm, matching the TSX fix in
#51311.

## Before / After

Before: angle brackets in JSX tags receive rainbow colors alongside
`{}`, `()`, `[]`, making every tag visually noisy.

After: only `{}`, `()`, and `[]` receive rainbow colors — angle brackets
are excluded, matching the HTML extension behavior.

Release Notes:

- Fixed angled brackets being included in rainbow bracket highlights for
JavaScript.
2026-05-18 15:54:51 +00:00
Ben Kunkle
342580531c
script: Trigger docs release (#56953)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-05-18 15:35:35 +00:00
Neel
d3d5fb0d15
zed: Improve zed:// URL handling (#57047)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
Release Notes:

- Improved `zed://` and `zed://agent` URL handling
2026-05-18 15:09:21 +00:00
Neel
988f083fc5
docs: Update threshold billing section (#57060)
Release Notes:

- N/A
2026-05-18 14:59:50 +00:00
Tom Houlé
62c01be72e
cloud_api_client: Add update_system_settings (#56843)
Wire up the client side of the new `PATCH /client/system_settings`
endpoint added in zed-industries/cloud#2444, so we can persist the
currently selected organization on a per-system basis. This PR only adds
the request types and the client method; hooking it up to the actual
organization switcher in the editor will come next.

The endpoint requires the `x-zed-system-id` header (the server returns
400 without it), so the method does not take an Option like the other
client calls.

Release Notes:

- N/A
2026-05-18 14:49:40 +00:00
Koya Masuda
8ce894b909
git_ui: Count commit title length by characters instead of bytes (#57025)
# What

- Replace `title.len()` with `title.chars().count()` in the commit title
length check, so the limit is measured in Unicode characters instead of
UTF-8 bytes.
- Applied in two places that share the same logic:
  - `crates/git_ui/src/git_panel.rs` — Git panel's inline warning
  - `crates/git_ui/src/commit_modal.rs` — commit modal's inline warning

# Why

The commit title length check used str::len(), which returns UTF-8 byte
length rather than character count. As a result, titles containing
multi-byte characters (Japanese, Chinese, emoji, etc.) triggered the
warning far below the configured commit_title_max_length — around 24
characters instead of the default 72.


Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
  - Before


https://github.com/user-attachments/assets/a895530c-2f73-470c-97fa-29d9467c14e1

  - After


https://github.com/user-attachments/assets/ffbe1ba2-0ccc-4b02-87f5-836da7841dd9


- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

- Fixed commit title length check miscounting multi-byte characters as
multiple characters.
2026-05-18 13:13:41 +00:00
Finn Evers
533e975df0
extension_cli: Disallow slash command extensions (#56864)
This will make CI error when we receive updates or new slash command
extensions.

Release Notes:

- N/A

---------

Co-authored-by: Marshall Bowers <git@maxdeviant.com>
2026-05-18 12:59:22 +00:00
Tom Houlé
79f998a5f3
context_server: Mirror authorization server grant_types_supported (#53501)
In MCP OAuth, mirror the authorization server's grant_types_supported in
the DCR registration body instead of hardcoding just authorization_code.
Logfire's auth server requires both authorization_code and refresh_token
in grant_types, and we already uses refresh tokens, so the only issue
was not advertising the capability during registration. The DCR body now
intersects our supported grant types with what the server advertises, or
sends all of ours when the server metadata omits grant_types_supported.

Without this change, the Pydantic Logfire MCP auth server refuses our
client registration.

Release Notes:

- MCP: Improve selection of the `grant_types` we send during OAuth
dynamic client registration.
2026-05-18 12:49:09 +00:00
Tom Houlé
770e20c839
context_server: Handle bad WWW-Authenticate resource_metadata URLs (#53502)
In MCP OAuth, when the resource_metadata URL from the WWW-Authenticate
header from the MCP server is on the same origin, but points to a broken
endpoint (for example Pydantic Logfire doubles the path component,
producing /mcp/mcp), fall back to the RFC 9728 well-known URIs instead
of failing outright. The header URL is still tried first, as per the MCP
spec.

Release Notes:

- MCP OAuth: Handle bad URLs in WWW-Authenticate by falling back to the
well known authorization server metadata URLs.
2026-05-18 12:48:55 +00:00
Bennet Bo Fenner
68340172a1
agent: Remove unused LanguageModelImage APIs (#57050)
Pulled out from #56866. Will help with MCP image support

Release Notes:

- N/A
2026-05-18 12:22:22 +00:00
Ben Brandt
e1f13a84b7
sidebar: Persist terminal threads in sidebar metadata (#56966)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- Persist Terminal Threads across reloads

---------

Co-authored-by: Bennet Bo Fenner <bennetbo@gmx.de>
2026-05-18 11:18:05 +00:00
Bennet Bo Fenner
1dc07b40b9
copilot: Fix issue when switching between OpenAI and Anthropic models (#56655)
We were storing reasoning output inside `RedactedThinking` which causes
issues when switching mid-turn from an OpenAI to an Anthropic model.
This implementation fixes this by storing it inside `reasoning_details`,
which matches our responses implementation in `open_ai.rs`

See
https://github.com/microsoft/vscode-copilot-chat/blob/main/src/platform/endpoint/node/responsesApi.ts

For whatever reason the copilot chat extension sets `summary: []`, this
is what our implementation does too

Closes #56385

Release Notes:

- Fixed an issue where the agent would error when using Copilot as a
provider and switching between OpenAI and Anthropic models
2026-05-18 09:57:08 +00:00
Ben Brandt
5aeb8a7e0f
eval_cli: Wait for model discovery (#57038)
Given the model list is dynamic now, we need a wait

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-18 08:41:02 +00:00
Xiaobo Liu
bfe914beec
editor: Remove redundant allocation when merging highlight ranges (#57034)
Reduce one Vec clone + collect allocation per frame

Release Notes:

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

---------

Signed-off-by: Xiaobo Liu <cppcoffee@gmail.com>
2026-05-18 07:45:02 +00:00
Ben Brandt
f2df3f9e18
acp: Add logout support for ACP agents (#56959)
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Has been skipped
Behind feature flag until we move RFD forward, but already working great
on codex

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A

---------

Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>
2026-05-17 20:50:16 +00:00
Xiaobo Liu
2bd7f35157
project: Remove stale registry agent archive caches (#55290)
Registry archive agents install each version into a versioned cache
directory, but older extracted archives were left behind after updates
and
could accumulate disk usage.

After resolving the current archive cache directory, remove other
versioned
cache directories for the same registry agent while preserving the
current
version.

Release Notes:

- Fix certain ACP registry agents not cleaning up old versions

---------

Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2026-05-17 20:35:45 +00:00
marius851000
53c910982c
open_ai: Fix parsing response if token use info is unspecified (#55919)
I tried to use google cloud to test gemma4 and compare with the result
of ollama. it had response such as

```json
{"choices":[{"delta":{"content":"Hello","reasoning_content":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null,"matched_stop":null}],"created":1778081610,"id":"KV_7adz7Ov20xN8Py-angQ8","model":"google/gemma-4-26b-a4b-it-maas","object":"chat.completion.chunk","usage":{"extra_properties":{"google":{"traffic_type":"ON_DEMAND"}}}}
```

(notice that, while "usage" is present, it does not have any of the
usual value)

Eventually, I had some more issue when parsing the response (unrelated
to this), so I decided to try the google ai endpoint, with its own set
of issue.

Those simple change should only loosen the accepted format, so no new
compatibility error are expected (but I haven’t tried with other
provider)

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [ ] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
(no change)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable


Release Notes:

- Improved open-ai compatibility when token usage info is absent
2026-05-17 19:50:14 +00:00
Rio Fujita
4d13f01c89
project: Context server updates on worktree changes (#51244)
Before you mark this PR as ready for review, make sure that you have:
- [x] Added a solid test coverage and/or screenshots from doing manual
testing
- [x] Done a self-review taking into account security and performance
aspects
- [x] Aligned any UI changes with the UI checklist

Release Notes:

- Fixed context server availability updates when a new worktree is added
to or removed from a project.

---------

Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2026-05-17 19:38:37 +00:00
Ben Brandt
43585afc29
agent_ui: Paste dropped paths into agent terminals (#56686)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-17 17:15:09 +00:00
Ben Brandt
23231879cd
acp: Add ACP session deletion support (#57004)
Still behind a flag until RFD progresses. But also fixes one area where
we would have called delete even if we didn't have support.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-17 17:03:17 +00:00
Ben Brandt
ce38fd67a8
agent_ui: Show title edit for terminals in agent panel (#57005)
Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-05-17 17:01:36 +00:00
622 changed files with 60191 additions and 21779 deletions

View file

@ -0,0 +1,160 @@
---
name: gpui-test
description: >-
Use when writing, debugging, or reproducing GPUI tests in Zed, including
gpui::test arguments, TestAppContext parameters, scheduler seeds,
ITERATIONS/SEED reproduction, parking failures, and pending task traces.
---
# GPUI Test Debugging
Use this skill when the user asks about `#[gpui::test]`, GPUI test seeds or iterations, deterministic scheduler failures, parking/pending task failures, or how to reproduce a flaky GPUI test.
## What `#[gpui::test]` does
`#[gpui::test]` expands to a normal Rust `#[test]`, so it runs under standard Rust test runners such as `cargo test` and `cargo nextest`.
It wraps the body in GPUI's deterministic test dispatcher/scheduler and can run the same test multiple times with different seeds. The seed controls scheduler task interleavings and any `StdRng` argument injected into the test.
The macro supports both synchronous and asynchronous tests.
### Supported function arguments
The macro recognizes arguments by type name:
| Test kind | Supported arguments |
| --- | --- |
| Sync and async | `&TestAppContext`, `&mut TestAppContext`, `StdRng` |
| Async only | `BackgroundExecutor` |
| Sync only | `&App`, `&mut App` |
`StdRng` is seeded from the current GPUI test seed, and `BackgroundExecutor` is backed by the same deterministic test dispatcher.
### Attribute arguments
Use these forms on `#[gpui::test(arguments)]`:
- No arguments: runs once with seed `0`, unless `SEED` is set.
- `seed = N`: adds a single explicit seed.
- `seeds(...)`: adds multiple explicit seeds.
- `iterations = N`: runs sequential seeds starting at `0` by default.
- `retries = N`: retries a failing run up to `N` times before surfacing the failure.
- `on_failure = "path::to::function"`: calls the function after final failure, before resuming the panic.
- `iterations` can be combined with explicit `seed` / `seeds`; explicit seeds are appended to the `0..iterations` range.
- If the `SEED` environment variable is set, it takes precedence over explicit seeds.
- With `SEED=N` and `ITERATIONS=M` or `iterations = M`, the harness runs seeds `N..N+M`.
## Environment variables
### GPUI test macro / scheduler execution
- `SEED=<u64>` — chooses the scheduler seed. Use this to reproduce a failure printed as `failing seed: N`. It also seeds injected `StdRng` arguments. For `#[gpui::property_test]`, it controls the scheduler seed and GPUI applies it to the proptest config for deterministic case generation.
- `ITERATIONS=<usize>` — overrides the `iterations = ...` value at runtime. Use to sweep many seeds without editing the test.
- `PENDING_TRACES=1` or `PENDING_TRACES=true` — captures and prints pending task traces when the test scheduler panics with `Parking forbidden`. Use this when `run_until_parked()` or teardown reports pending work.
- `GPUI_RUN_UNTIL_PARKED_LOG=1` — logs when `allow_parking()` is enabled. Use to find tests that explicitly permit parking/pending work.
- `DEBUG_SCHEDULER=1` — prints scheduler clock/timer debugging from `scheduler::TestScheduler`.
### Lower-level scheduler tests
- `SCHEDULER_NONINTERACTIVE=1` — suppresses interactive seed progress output in `scheduler::TestScheduler::many`. This does not affect the `#[gpui::test]` harness path.
### General Rust test debugging vars often useful with GPUI tests
- `RUST_BACKTRACE=1` or `RUST_BACKTRACE=full` — show panic backtraces.
- `RUST_LOG=<filter>` — enable logs when the test initializes logging.
- `ZED_HEADLESS=1` — forces GPUI platform guessing toward headless mode; useful for tests that otherwise interact with platform/window setup.
Prefer env vars over editing the test when narrowing a reproduction.
## Reproducing a specific GPUI test
1. Identify the crate/package and test name.
2. Run the narrowest test filter first, skip to 3. if a failing seed is known.
```sh
cargo -q test -p <crate-name> <test_name> -- --nocapture
```
3. If the failure mentions a seed, rerun exactly that seed.
```sh
SEED=<seed> cargo -q test -p <crate-name> <test_name> -- --nocapture
```
4. If the failure is flaky and no seed is known, sweep seeds.
```sh
ITERATIONS=100 cargo -q test -p <crate-name> <test_name> -- --nocapture
```
When the harness prints `failing seed: <seed>`, switch to `SEED=<seed>` for all future debugging.
5. If the failure is `Parking forbidden`, rerun with pending traces.
```sh
PENDING_TRACES=1 cargo -q test -p <crate-name> <test_name> -- --nocapture
```
If a failing seed was printed or is already known, include it too:
```sh
SEED=<seed> PENDING_TRACES=1 cargo -q test -p <crate-name> <test_name> -- --nocapture
```
Inspect the pending traces for a task that was spawned but not awaited, detached, completed, or intentionally allowed to park.
6. If timing or timer advancement is involved, prefer GPUI scheduler timers in tests:
```rust
cx.background_executor().timer(duration).await;
```
Avoid `smol::Timer::after(...)` in GPUI tests that rely on `run_until_parked()`, because GPUI's scheduler may not track it.
7. Minimize the reproduction.
- Keep the failing `SEED` fixed.
- Reduce `ITERATIONS` to `1` or remove it once a seed is known.
- Remove unrelated setup only after confirming the same seed still fails.
- Preserve scheduler-sensitive awaits/yields; removing them can mask the bug.
- If randomness is test-controlled via `StdRng`, log or assert the generated scenario after fixing the scheduler seed.
8. Validate the fix.
- Run the fixed seed.
- Run a modest seed sweep, e.g. `ITERATIONS=20`, if the failure was scheduler-sensitive.
- Run the relevant crate's test filter or broader suite if the touched code has shared behavior.
## Common diagnosis patterns
### Seed-dependent assertion failure
Likely caused by a scheduler interleaving or by `StdRng`-driven test data. Fix `SEED`, reproduce, and inspect which task or generated scenario differs.
### `Parking forbidden`
Usually means a foreground/background task is still pending when the scheduler expected the test to make progress or finish. Look for:
- A task that should be awaited but was dropped.
- A task that should be detached with error logging.
- A timer or receiver that is waiting forever.
- A missing `cx.run_until_parked()` after triggering async work in a test.
- A missing `cx.advance_clock(...)` to wait for debounced work in a test.
- Use of non-GPUI timers or executors that the test scheduler cannot drive.
Rerun with `PENDING_TRACES=1` before changing code.
### Non-determinism / wrong thread
The scheduler can report activity from an unexpected thread. Look for work escaping GPUI's foreground/background executors, direct thread spawns, or external async runtimes not controlled by the test dispatcher.
### Tests pass alone but fail in sweeps
Use the failing seed from sweep output. Avoid assuming test order unless the runner is explicitly serial. Check globals, leaked entities/tasks, and state not reset by test initialization.
## Writing GPUI tests
- Prefer `#[gpui::test]` for tests that need `TestAppContext`, deterministic executors, fake time, or scheduler interleaving coverage.
- Add `iterations = N` when the test is intentionally checking interleavings.
- Use `StdRng` as a test argument when randomized test data should follow the same seed as the scheduler.
- Use `cx.background_executor().timer(duration).await` for delays/timeouts in GPUI tests.
- Do not add or increase `retries` while fixing a test unless the user explicitly asks or the test already documents why probabilistic tolerance is intentional. Retries can mask the failure instead of fixing it.

View file

@ -0,0 +1,175 @@
---
name: zed-cherry-pick
description: Cherry-pick one or more merged PRs and/or commits into Zed's `preview` or `stable` release branch. Use this whenever the user mentions cherry-picking to preview/stable, a failed cherry-pick run, or wants to manually port fix(es) into a release branch.
---
# Zed Cherry-Pick
Zed ships from two long-lived release branches that live on `origin`:
- `preview` channel → branch like `v1.4.x`
- `stable` channel → branch like `v1.3.x`
The version numbers change with each release. **Never hardcode them — always discover the current mapping** (see [Finding the target branch](#finding-the-target-branch)).
A merged PR on `main` gets ported to a release branch by `script/cherry-pick`, normally driven by the `cherry_pick` GitHub Actions workflow. When that workflow fails (almost always a merge conflict), use this skill to finish the job locally and open the cherry-pick PR by hand.
## When to use
Use this when the user asks to cherry-pick one or more commits and/or Pull Requests (by number or URL) to `preview` or `stable`.
Optionally, the user may specify whether to resolve merge conflicts; if unspecified, attempt the cherry-pick, and then if there are merge conflicts in practice, stop and inform the user that there are merge conflicts and offer to resolve them. (Users may prefer to resolve the merge conflicts themselves before continuing.)
## The script you're emulating
The canonical procedure lives in `script/cherry-pick` and the `cherry_pick` GitHub Actions workflow. Read the script first if anything looks off — your local steps must produce the same branch name, PR title, and PR body it would.
Signature: `script/cherry-pick <branch-name> <commit-sha> <channel>`
- `<branch-name>` is the release branch (e.g. `v1.4.x`), **not** the channel name.
- `<channel>` is `preview` or `stable`, used only for display text in the PR title/body.
It creates a local branch named `cherry-pick-<branch-name>-<short-sha>` (the short SHA is the first 8 chars of the commit), force-pushes it to `origin`, and opens a PR.
## Finding the target branch
The channel→branch mapping changes every release. Find the current one by inspecting the most recent `cherry_pick` workflow runs:
```
gh run list --workflow=cherry_pick.yml --limit 30 --json displayTitle,databaseId
# pick a recent run for the channel you want, then:
gh run view <id> --log 2>&1 | grep -E "BRANCH:|CHANNEL:"
```
A successful run prints both `BRANCH:` and `CHANNEL:` env vars; that's your mapping.
## Procedure
### 1. Gather context
You need three things: the **merge commit SHA**, the **target branch**, and the **channel name**.
If the user requested multiple PRs and/or commits, gather the metadata for all of them first and cherry-pick them in the order they landed on `main`, oldest to newest. For PRs, order by `mergedAt`; for raw commits, use their order on `main` when available, otherwise commit date. This tends to reduce avoidable conflicts because later changes may depend on earlier ones, but it does not guarantee a conflict-free cherry-pick when the release branch has diverged.
```
gh pr view <PR_NUMBER> --json title,number,mergeCommit,mergedAt,url
```
If the user said the workflow failed, fetch its log to see exactly which command failed and which file conflicted:
```
gh run list --workflow=cherry_pick.yml --limit 10 --json databaseId,displayTitle,status,conclusion
gh run view <failed_run_id> --log-failed
```
The failed-run log also confirms the `BRANCH` and `COMMIT` the workflow used — handy if there's any ambiguity.
### 2. Reproduce the script's setup locally
The repository may be a worktree (check `.git` — if it's a file, you're in a worktree pointing at a shared gitdir). That's fine; just operate normally.
```
git --no-pager fetch origin <branch-name> <commit-sha>
git checkout --force origin/<branch-name> -B cherry-pick-<branch-name>-<short-sha>
git cherry-pick <commit-sha>
```
The branch name **must** match `cherry-pick-<branch-name>-<short-sha>` exactly (script convention; reviewers and tooling expect it).
### 3. Check for missing prerequisite cherry-picks
If the cherry-pick conflicts, do not immediately resolve the conflicts manually.
First determine whether the conflict is likely caused by other PRs or commits that are already on `main` but missing from the release branch. If so, point out those candidate prerequisite PRs/commits to the user, including PR links, and offer to either resolve the conflicts manually or let the user run the GitHub cherry-pick workflow for those commits first.
If the user wants to run the workflow for the missing prerequisites, stop here. This often keeps cherry-picks clean and eligible for automatic approval.
Only resolve conflicts manually if:
- no likely missing prerequisites are found, or
- the user chooses manual conflict resolution instead of cherry-picking the prerequisites first.
### 4. Resolve the conflicts manually
Do this only after checking for missing prerequisite cherry-picks.
- Inspect every conflicted file with `grep -n '<<<<<<<\\|>>>>>>>\\|=======' <path>` to find the markers.
- Conflicts are usually `diff3` style with three sections: HEAD (release branch), `||||||| parent of <sha>` (merge base on `main`), and the incoming change.
- Read the **original commit** (`git --no-pager show <commit-sha> -- <path>`) to understand the author's intent, then pick the resolution that produces the equivalent end state on the release branch.
- Don't grab unrelated changes from `main` that happen to surround the conflict — keep the cherry-pick minimal.
### 5. Validate
Always build and (if reasonable) test the affected crate(s) before continuing the cherry-pick.
```
cargo check -p <affected_crate>
cargo test -p <affected_crate>
```
If validation fails, fix the resolution — do **not** continue with a broken build. If you can't reach a clean state, abort with `git cherry-pick --abort` and report back to the user.
### 6. Finish the cherry-pick
`git cherry-pick --continue` opens an editor by default. Prevent that:
```
git add <resolved_files>
GIT_EDITOR=true git cherry-pick --continue
```
This preserves the original commit message verbatim, which is what the script does.
### 7. Push and open the PR
```
git push origin -f cherry-pick-<branch-name>-<short-sha>
```
Then create the PR with the **exact** title and body format `script/cherry-pick` uses, so it's indistinguishable from an automated one.
**Title:**
```
<original commit subject> (cherry-pick to <channel>)
```
The original commit subject already ends in ` (#<original_pr_number>)`; keep it.
**Body** (when the original commit title ends in `(#<N>)`, which is the normal case):
```
Cherry-pick of #<original_pr_number> to <channel>
----
<original commit body, verbatim>
```
Create it with `gh pr create`, writing the body to a temp file to keep formatting intact:
```
git --no-pager log -1 --pretty=format:"%b" > /tmp/cp-body-tail.md
printf 'Cherry-pick of #%s to %s\n\n----\n' <PR_NUMBER> <channel> | cat - /tmp/cp-body-tail.md > /tmp/cp-body.md
gh pr create --base <branch-name> --head cherry-pick-<branch-name>-<short-sha> \\
--title "<commit subject> (cherry-pick to <channel>)" \\
--body-file /tmp/cp-body.md
```
Do **not** add a `Release Notes:` section — the original commit body already has one (or already says `N/A`), and you don't want it duplicated.
## Final report to the user
Tell the user:
- The new PR URL.
- A one-line summary of the conflict and how you resolved it.
- What validation you ran (commands + result).
- That their local branch is now `cherry-pick-<branch-name>-<short-sha>`, in case they want you to switch back.
## Gotchas
- **`--no-pager` and `GIT_EDITOR=true`**: required for non-interactive git in this environment. Forgetting `GIT_EDITOR=true` on `cherry-pick --continue` hangs the terminal.
- **Worktree index lock**: if a previous git command was interrupted, you may see `index.lock` errors. The lock lives at `<gitdir>/index.lock` where `<gitdir>` is what `cat .git` points to (for a worktree). Remove it only if you're sure no git process is running.
- **Don't expand the cherry-pick's scope**: when resolving conflicts, never pull in unrelated changes from `main` just because they sit next to the conflict region. The PR should be the smallest diff that reproduces the original commit's intent on the release branch.
- **Channel branches are not called `preview`/`stable`**: don't try to `git fetch origin preview`. Look up the actual `vX.Y.x` branch name first.
## When Finished
After everything is finished, the last thing to do is to provide a link to the opened pull request(s) for the cherry-pick(s).

View file

@ -55,7 +55,6 @@
/crates/open_ai/ @zed-industries/ai-team
/crates/open_router/ @zed-industries/ai-team
/crates/prompt_store/ @zed-industries/ai-team
/crates/rules_library/ @zed-industries/ai-team
# SUGGESTED: Review needed - based on Richard Feldman (2 commits)
/crates/shell_command_parser/ @zed-industries/ai-team
/crates/vercel/ @zed-industries/ai-team
@ -181,7 +180,6 @@
/crates/fs_benchmarks/ @zed-industries/infrastructure-team
/crates/http_client/ @zed-industries/infrastructure-team
/crates/http_client_tls/ @zed-industries/infrastructure-team
/crates/nc/ @zed-industries/infrastructure-team
/crates/net/ @zed-industries/infrastructure-team
/crates/paths/ @zed-industries/infrastructure-team
/crates/release_channel/ @zed-industries/infrastructure-team

View file

@ -1,113 +0,0 @@
name: Community Champion Auto Labeler
on:
issues:
types: [opened]
pull_request_target:
types: [opened]
jobs:
label_community_champion:
if: github.repository_owner == 'zed-industries'
runs-on: namespace-profile-2x4-ubuntu-2404
steps:
- name: Check if author is a community champion and apply label
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
env:
COMMUNITY_CHAMPIONS: |
0x2CA
5brian
5herlocked
abdelq
afgomez
AidanV
akbxr
AlvaroParker
amtoaer
artemevsevev
bajrangCoder
bcomnes
Be-ing
blopker
bnjjj
bobbymannino
CharlesChen0823
chbk
davewa
davidbarsky
ddoemonn
djsauble
errmayank
fantacell
fdncred
findrakecil
FloppyDisco
gko
huacnlee
imumesh18
injust
jacobtread
jansol
jeffreyguenther
jenslys
jongretar
lemorage
lingyaochu
lnay
marcocondrache
marius851000
mikebronner
ognevny
PKief
playdohface
RemcoSmitsDev
rgbkrk
romaninsh
rxptr
Simek
someone13574
sourcefrog
suxiaoshao
Takk8IS
tartarughina
thedadams
tidely
timvermeulen
valentinegb
versecafe
vitallium
WhySoBad
ya7010
Zertsov
with:
script: |
const communityChampions = process.env.COMMUNITY_CHAMPIONS
.split('\n')
.map(handle => handle.trim().toLowerCase())
.filter(handle => handle.length > 0);
let author;
if (context.eventName === 'issues') {
author = context.payload.issue.user.login;
} else if (context.eventName === 'pull_request_target') {
author = context.payload.pull_request.user.login;
}
if (!author || !communityChampions.includes(author.toLowerCase())) {
return;
}
const issueNumber = context.payload.issue?.number || context.payload.pull_request?.number;
try {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: ['community champion']
});
console.log(`Applied 'community champion' label to #${issueNumber} by ${author}`);
} catch (error) {
console.error(`Failed to apply label: ${error.message}`);
}

View file

@ -5,7 +5,7 @@ env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: '1'
CARGO_INCREMENTAL: '0'
ZED_EXTENSION_CLI_SHA: 1fa7f1a3ec28ea1eae6db2e937d7a538fb10c0c7
ZED_EXTENSION_CLI_SHA: 2a00db06ce6d01089bfafd207b6348078e980df9
on:
workflow_call:
inputs:

View file

@ -5,7 +5,7 @@ env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: '1'
CARGO_INCREMENTAL: '0'
ZED_EXTENSION_CLI_SHA: 1fa7f1a3ec28ea1eae6db2e937d7a538fb10c0c7
ZED_EXTENSION_CLI_SHA: 2a00db06ce6d01089bfafd207b6348078e980df9
RUSTUP_TOOLCHAIN: stable
CARGO_BUILD_TARGET: wasm32-wasip2
on:

97
.github/workflows/nix_build.yml vendored Normal file
View file

@ -0,0 +1,97 @@
# Generated from xtask::workflows::nix_build
# Rebuild with `cargo xtask workflows`.
name: nix_build
env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: '1'
on:
pull_request:
types:
- labeled
- synchronize
jobs:
build_nix_linux_x86_64:
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') && ((github.event.action == 'labeled' && (github.event.label.name == 'run-nix' || github.event.label.name == 'run-bundling')) || (github.event.action == 'synchronize' && (contains(github.event.pull_request.labels.*.name, 'run-nix') || contains(github.event.pull_request.labels.*.name, 'run-bundling'))))
runs-on: namespace-profile-32x64-ubuntu-2004
env:
ZED_CLIENT_CHECKSUM_SEED: ${{ secrets.ZED_CLIENT_CHECKSUM_SEED }}
ZED_MINIDUMP_ENDPOINT: ${{ secrets.ZED_SENTRY_MINIDUMP_ENDPOINT }}
ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON: ${{ secrets.ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON }}
GIT_LFS_SKIP_SMUDGE: '1'
steps:
- name: steps::checkout_repo
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
with:
clean: false
- name: steps::cache_nix_dependencies_namespace
uses: namespacelabs/nscloud-cache-action@a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9
with:
cache: nix
- name: nix_build::build_nix::install_nix
uses: cachix/install-nix-action@02a151ada4993995686f9ed4f1be7cfbb229e56f
with:
github_access_token: ${{ secrets.GITHUB_TOKEN }}
- name: nix_build::build_nix::cachix_action
uses: cachix/cachix-action@0fc020193b5a1fa3ac4575aa3a7d3aa6a35435ad
with:
name: zed
authToken: ${{ secrets.CACHIX_AUTH_TOKEN }}
cachixArgs: -v
pushFilter: -zed-editor-[0-9.]*
- name: nix_build::build_nix::build
run: nix build .#default -L --accept-flake-config
timeout-minutes: 60
continue-on-error: true
build_nix_mac_aarch64:
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') && ((github.event.action == 'labeled' && (github.event.label.name == 'run-nix' || github.event.label.name == 'run-bundling')) || (github.event.action == 'synchronize' && (contains(github.event.pull_request.labels.*.name, 'run-nix') || contains(github.event.pull_request.labels.*.name, 'run-bundling'))))
runs-on: namespace-profile-mac-large
env:
ZED_CLIENT_CHECKSUM_SEED: ${{ secrets.ZED_CLIENT_CHECKSUM_SEED }}
ZED_MINIDUMP_ENDPOINT: ${{ secrets.ZED_SENTRY_MINIDUMP_ENDPOINT }}
ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON: ${{ secrets.ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON }}
GIT_LFS_SKIP_SMUDGE: '1'
steps:
- name: steps::checkout_repo
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
with:
clean: false
- name: steps::cache_nix_store_macos
uses: namespacelabs/nscloud-cache-action@a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9
with:
path: ~/nix-cache
- name: nix_build::build_nix::install_nix
uses: cachix/install-nix-action@02a151ada4993995686f9ed4f1be7cfbb229e56f
with:
github_access_token: ${{ secrets.GITHUB_TOKEN }}
- name: nix_build::build_nix::configure_local_nix_cache
run: |
mkdir -p ~/nix-cache
echo "extra-substituters = file://$HOME/nix-cache?priority=10" | sudo tee -a /etc/nix/nix.conf
echo "require-sigs = false" | sudo tee -a /etc/nix/nix.conf
sudo launchctl kickstart -k system/org.nixos.nix-daemon
- name: nix_build::build_nix::cachix_action
uses: cachix/cachix-action@0fc020193b5a1fa3ac4575aa3a7d3aa6a35435ad
with:
name: zed
authToken: ${{ secrets.CACHIX_AUTH_TOKEN }}
cachixArgs: -v
pushFilter: -zed-editor-[0-9.]*
- name: nix_build::build_nix::build
run: nix build .#default -L --accept-flake-config
- name: nix_build::build_nix::export_to_local_nix_cache
if: always()
run: |
if [ -L result ]; then
echo "Copying build closure to local binary cache..."
nix copy --to "file://$HOME/nix-cache" ./result || echo "Warning: nix copy to local cache failed"
else
echo "No build result found, skipping cache export."
fi
timeout-minutes: 60
continue-on-error: true
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: true
defaults:
run:
shell: bash -euxo pipefail {0}

247
.github/workflows/pr_issue_labeler.yml vendored Normal file
View file

@ -0,0 +1,247 @@
# Labels pull requests by author:
# - 'community champion' for community champions
# - 'bot' for bot accounts
# - 'staff' for staff team members
# - 'guild' for guild members
# - 'first contribution' for first-time external contributors
# Labels issues by author:
# - 'community champion' for community champions
name: PR Issue Labeler
on:
issues:
types: [opened]
pull_request_target:
types: [opened]
permissions:
contents: read
jobs:
check-authorship-and-label:
if: github.repository == 'zed-industries/zed'
runs-on: namespace-profile-2x4-ubuntu-2404
timeout-minutes: 5
steps:
- id: get-app-token
uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859 # v3.0.0
with:
app-id: ${{ secrets.ZED_COMMUNITY_BOT_APP_ID }}
private-key: ${{ secrets.ZED_COMMUNITY_BOT_PRIVATE_KEY }}
owner: zed-industries
- id: apply-authorship-label
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
with:
github-token: ${{ steps.get-app-token.outputs.token }}
script: |
const BOT_LABEL = 'bot';
const STAFF_LABEL = 'staff';
const STAFF_TEAM_SLUG = 'staff';
const FIRST_CONTRIBUTION_LABEL = 'first contribution';
const GUILD_LABEL = 'guild';
const GUILD_MEMBERS = [
'11happy',
'AidanV',
'alanpjohn',
'AmaanBilwar',
'arjunkomath',
'austincummings',
'ayushk-1801',
'criticic',
'dongdong867',
'emamulandalib',
'eureka928',
'feitreim',
'iam-liam',
'iksuddle',
'ishaksebsib',
'lingyaochu',
'loadingalias',
'marcocondrache',
'mchisolm0',
'MostlyKIGuess',
'nairadithya',
'nihalxkumar',
'notJoon',
'OmChillure',
'Palanikannan1437',
'polyesterswing',
'prayanshchh',
'razeghi71',
'sarmadgulzar',
'seanstrom',
'Shivansh-25',
'SkandaBhat',
'th0jensen',
'tommyming',
'transitoryangel',
'TwistingTwists',
'virajbhartiya',
'YEDASAVG',
'Ziqi-Yang',
];
const COMMUNITY_CHAMPION_LABEL = 'community champion';
const COMMUNITY_CHAMPIONS = [
'0x2CA',
'5brian',
'5herlocked',
'abdelq',
'afgomez',
'AidanV',
'akbxr',
'AlvaroParker',
'amtoaer',
'artemevsevev',
'bajrangCoder',
'bcomnes',
'Be-ing',
'blopker',
'bnjjj',
'bobbymannino',
'CharlesChen0823',
'chbk',
'davewa',
'davidbarsky',
'ddoemonn',
'djsauble',
'errmayank',
'fantacell',
'fdncred',
'findrakecil',
'FloppyDisco',
'gko',
'huacnlee',
'imumesh18',
'injust',
'jacobtread',
'jansol',
'jeffreyguenther',
'jenslys',
'jongretar',
'lemorage',
'lingyaochu',
'lnay',
'marcocondrache',
'marius851000',
'mikebronner',
'ognevny',
'PKief',
'playdohface',
'RemcoSmitsDev',
'rgbkrk',
'romaninsh',
'rxptr',
'Simek',
'someone13574',
'sourcefrog',
'suxiaoshao',
'Takk8IS',
'tartarughina',
'thedadams',
'tidely',
'timvermeulen',
'valentinegb',
'versecafe',
'vitallium',
'WhySoBad',
'ya7010',
'Zertsov',
];
const pr = context.payload.pull_request;
const issue = context.payload.issue;
const target = pr || issue;
const author = target.user.login;
const listIncludesAuthor = (members, author) => {
const authorLower = author.toLowerCase();
return members.some((member) => member.toLowerCase() === authorLower);
};
const isStaffMember = async (author) => {
try {
const response = await github.rest.teams.getMembershipForUserInOrg({
org: 'zed-industries',
team_slug: STAFF_TEAM_SLUG,
username: author
});
return response.data.state === 'active';
} catch (error) {
if (error.status !== 404) {
throw error;
}
return false;
}
};
const getIssueLabels = () => {
if (listIncludesAuthor(COMMUNITY_CHAMPIONS, author)) {
return [COMMUNITY_CHAMPION_LABEL];
}
return [];
};
const getPullRequestLabels = async () => {
if (target.user.type === 'Bot') {
return [BOT_LABEL];
}
if (await isStaffMember(author)) {
return [STAFF_LABEL];
}
// External contributors
const labelsToAdd = [];
if (listIncludesAuthor(COMMUNITY_CHAMPIONS, author)) {
labelsToAdd.push(COMMUNITY_CHAMPION_LABEL);
}
if (listIncludesAuthor(GUILD_MEMBERS, author)) {
labelsToAdd.push(GUILD_LABEL);
}
// We use inverted logic here due to a suspected GitHub bug where first-time contributors
// get 'NONE' instead of 'FIRST_TIME_CONTRIBUTOR' or 'FIRST_TIMER'.
// https://github.com/orgs/community/discussions/78038
// This will break if GitHub ever adds new associations.
const association = pr.author_association;
const knownAssociations = ['CONTRIBUTOR', 'COLLABORATOR', 'MEMBER', 'OWNER', 'MANNEQUIN'];
if (knownAssociations.includes(association)) {
console.log(`PR #${pr.number} by ${author}: not a first-time contributor (association: '${association}')`);
} else {
labelsToAdd.push(FIRST_CONTRIBUTION_LABEL);
}
return labelsToAdd;
};
const labelsToAdd = pr ? await getPullRequestLabels() : getIssueLabels();
if (labelsToAdd.length === 0) {
return;
}
try {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: target.number,
labels: labelsToAdd
});
const targetType = pr ? 'PR' : 'issue';
const labels = labelsToAdd.map((label) => `'${label}'`).join(', ');
console.log(`${targetType} #${target.number} by ${author}: labeled ${labels}`);
} catch (error) {
if (pr) {
throw error;
}
console.error(`Failed to label issue #${target.number}: ${error.message}`);
}

View file

@ -1,150 +0,0 @@
# Labels pull requests by author: 'bot' for bot accounts, 'staff' for
# staff team members, 'guild' for guild members, 'first contribution' for
# first-time external contributors.
name: PR Labeler
on:
pull_request_target:
types: [opened]
permissions:
contents: read
jobs:
check-authorship-and-label:
if: github.repository == 'zed-industries/zed'
runs-on: namespace-profile-2x4-ubuntu-2404
timeout-minutes: 5
steps:
- id: get-app-token
uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859 # v3.0.0
with:
app-id: ${{ secrets.ZED_COMMUNITY_BOT_APP_ID }}
private-key: ${{ secrets.ZED_COMMUNITY_BOT_PRIVATE_KEY }}
owner: zed-industries
- id: apply-authorship-label
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
with:
github-token: ${{ steps.get-app-token.outputs.token }}
script: |
const BOT_LABEL = 'bot';
const STAFF_LABEL = 'staff';
const GUILD_LABEL = 'guild';
const FIRST_CONTRIBUTION_LABEL = 'first contribution';
const STAFF_TEAM_SLUG = 'staff';
const GUILD_MEMBERS = [
'11happy',
'AidanV',
'AmaanBilwar',
'MostlyKIGuess',
'OmChillure',
'Palanikannan1437',
'Shivansh-25',
'SkandaBhat',
'TwistingTwists',
'YEDASAVG',
'Ziqi-Yang',
'alanpjohn',
'arjunkomath',
'austincummings',
'ayushk-1801',
'criticic',
'dongdong867',
'emamulandalib',
'eureka928',
'feitreim',
'iam-liam',
'iksuddle',
'ishaksebsib',
'lingyaochu',
'loadingalias',
'marcocondrache',
'mchisolm0',
'nairadithya',
'nihalxkumar',
'notJoon',
'polyesterswing',
'prayanshchh',
'razeghi71',
'sarmadgulzar',
'seanstrom',
'th0jensen',
'tommyming',
'transitoryangel',
'virajbhartiya',
];
const pr = context.payload.pull_request;
const author = pr.user.login;
if (pr.user.type === 'Bot') {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
labels: [BOT_LABEL]
});
console.log(`PR #${pr.number} by ${author}: labeled '${BOT_LABEL}' (user type: '${pr.user.type}')`);
return;
}
let isStaff = false;
try {
const response = await github.rest.teams.getMembershipForUserInOrg({
org: 'zed-industries',
team_slug: STAFF_TEAM_SLUG,
username: author
});
isStaff = response.data.state === 'active';
} catch (error) {
if (error.status !== 404) {
throw error;
}
}
if (isStaff) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
labels: [STAFF_LABEL]
});
console.log(`PR #${pr.number} by ${author}: labeled '${STAFF_LABEL}' (staff team member)`);
return;
}
const authorLower = author.toLowerCase();
const isGuildMember = GUILD_MEMBERS.some(
(member) => member.toLowerCase() === authorLower
);
if (isGuildMember) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
labels: [GUILD_LABEL]
});
console.log(`PR #${pr.number} by ${author}: labeled '${GUILD_LABEL}' (guild member)`);
// No early return: guild members can also get 'first contribution'
}
// We use inverted logic here due to a suspected GitHub bug where first-time contributors
// get 'NONE' instead of 'FIRST_TIME_CONTRIBUTOR' or 'FIRST_TIMER'.
// https://github.com/orgs/community/discussions/78038
// This will break if GitHub ever adds new associations.
const association = pr.author_association;
const knownAssociations = ['CONTRIBUTOR', 'COLLABORATOR', 'MEMBER', 'OWNER', 'MANNEQUIN'];
if (knownAssociations.includes(association)) {
console.log(`PR #${pr.number} by ${author}: not a first-time contributor (association: '${association}')`);
return;
}
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
labels: [FIRST_CONTRIBUTION_LABEL]
});
console.log(`PR #${pr.number} by ${author}: labeled '${FIRST_CONTRIBUTION_LABEL}' (association: '${association}')`);

View file

@ -264,85 +264,6 @@ jobs:
path: target/zed-remote-server-windows-x86_64.zip
if-no-files-found: error
timeout-minutes: 60
build_nix_linux_x86_64:
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') && ((github.event.action == 'labeled' && github.event.label.name == 'run-bundling') || (github.event.action == 'synchronize' && contains(github.event.pull_request.labels.*.name, 'run-bundling')))
runs-on: namespace-profile-32x64-ubuntu-2004
env:
ZED_CLIENT_CHECKSUM_SEED: ${{ secrets.ZED_CLIENT_CHECKSUM_SEED }}
ZED_MINIDUMP_ENDPOINT: ${{ secrets.ZED_SENTRY_MINIDUMP_ENDPOINT }}
ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON: ${{ secrets.ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON }}
GIT_LFS_SKIP_SMUDGE: '1'
steps:
- name: steps::checkout_repo
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
with:
clean: false
- name: steps::cache_nix_dependencies_namespace
uses: namespacelabs/nscloud-cache-action@a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9
with:
cache: nix
- name: nix_build::build_nix::install_nix
uses: cachix/install-nix-action@02a151ada4993995686f9ed4f1be7cfbb229e56f
with:
github_access_token: ${{ secrets.GITHUB_TOKEN }}
- name: nix_build::build_nix::cachix_action
uses: cachix/cachix-action@0fc020193b5a1fa3ac4575aa3a7d3aa6a35435ad
with:
name: zed
authToken: ${{ secrets.CACHIX_AUTH_TOKEN }}
cachixArgs: -v
pushFilter: -zed-editor-[0-9.]*
- name: nix_build::build_nix::build
run: nix build .#default -L --accept-flake-config
timeout-minutes: 60
continue-on-error: true
build_nix_mac_aarch64:
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') && ((github.event.action == 'labeled' && github.event.label.name == 'run-bundling') || (github.event.action == 'synchronize' && contains(github.event.pull_request.labels.*.name, 'run-bundling')))
runs-on: namespace-profile-mac-large
env:
ZED_CLIENT_CHECKSUM_SEED: ${{ secrets.ZED_CLIENT_CHECKSUM_SEED }}
ZED_MINIDUMP_ENDPOINT: ${{ secrets.ZED_SENTRY_MINIDUMP_ENDPOINT }}
ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON: ${{ secrets.ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON }}
GIT_LFS_SKIP_SMUDGE: '1'
steps:
- name: steps::checkout_repo
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
with:
clean: false
- name: steps::cache_nix_store_macos
uses: namespacelabs/nscloud-cache-action@a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9
with:
path: ~/nix-cache
- name: nix_build::build_nix::install_nix
uses: cachix/install-nix-action@02a151ada4993995686f9ed4f1be7cfbb229e56f
with:
github_access_token: ${{ secrets.GITHUB_TOKEN }}
- name: nix_build::build_nix::configure_local_nix_cache
run: |
mkdir -p ~/nix-cache
echo "extra-substituters = file://$HOME/nix-cache?priority=10" | sudo tee -a /etc/nix/nix.conf
echo "require-sigs = false" | sudo tee -a /etc/nix/nix.conf
sudo launchctl kickstart -k system/org.nixos.nix-daemon
- name: nix_build::build_nix::cachix_action
uses: cachix/cachix-action@0fc020193b5a1fa3ac4575aa3a7d3aa6a35435ad
with:
name: zed
authToken: ${{ secrets.CACHIX_AUTH_TOKEN }}
cachixArgs: -v
pushFilter: -zed-editor-[0-9.]*
- name: nix_build::build_nix::build
run: nix build .#default -L --accept-flake-config
- name: nix_build::build_nix::export_to_local_nix_cache
if: always()
run: |
if [ -L result ]; then
echo "Copying build closure to local binary cache..."
nix copy --to "file://$HOME/nix-cache" ./result || echo "Warning: nix copy to local cache failed"
else
echo "No build result found, skipping cache export."
fi
timeout-minutes: 60
continue-on-error: true
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: true

View file

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

3
.gitignore vendored
View file

@ -55,3 +55,6 @@ crates/docs_preprocessor/actions.json
# Local documentation audit files
/december-2025-releases.md
/docs/december-2025-documentation-gaps.md
# NixOS integration test state
.nixos-test-history

1484
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -130,13 +130,13 @@ members = [
"crates/lsp",
"crates/markdown",
"crates/markdown_preview",
"crates/mermaid_render",
"crates/media",
"crates/menu",
"crates/migrator",
"crates/miniprofiler_ui",
"crates/mistral",
"crates/multi_buffer",
"crates/nc",
"crates/net",
"crates/node_runtime",
"crates/notifications",
@ -171,7 +171,8 @@ members = [
"crates/reqwest_client",
"crates/rope",
"crates/rpc",
"crates/rules_library",
"crates/sandbox",
"crates/skill_creator",
"crates/scheduler",
"crates/schema_generator",
"crates/search",
@ -388,15 +389,14 @@ lmstudio = { path = "crates/lmstudio" }
lsp = { path = "crates/lsp" }
markdown = { path = "crates/markdown" }
markdown_preview = { path = "crates/markdown_preview" }
mermaid_render = { path = "crates/mermaid_render" }
svg_preview = { path = "crates/svg_preview" }
media = { path = "crates/media" }
menu = { path = "crates/menu" }
mermaid-rs-renderer = { git = "https://github.com/zed-industries/mermaid-rs-renderer", rev = "782b89a7da3f0e91e51f98d00a93acba679be6fb", default-features = false }
migrator = { path = "crates/migrator" }
mistral = { path = "crates/mistral" }
multi_buffer = { path = "crates/multi_buffer" }
miniprofiler_ui = { path = "crates/miniprofiler_ui" }
nc = { path = "crates/nc" }
net = { path = "crates/net" }
node_runtime = { path = "crates/node_runtime" }
notifications = { path = "crates/notifications" }
@ -431,8 +431,9 @@ reqwest_client = { path = "crates/reqwest_client" }
rodio = { git = "https://github.com/RustAudio/rodio", rev = "e50e726ddd0292f6ef9de0dda6b90af4ed1fb66a", features = ["wav", "playback", "wav_output", "recording"] }
rope = { path = "crates/rope" }
rpc = { path = "crates/rpc" }
rules_library = { path = "crates/rules_library" }
skill_creator = { path = "crates/skill_creator" }
scheduler = { path = "crates/scheduler" }
sandbox = { path = "crates/sandbox" }
search = { path = "crates/search" }
session = { path = "crates/session" }
sidebar = { path = "crates/sidebar" }
@ -500,9 +501,13 @@ ztracing_macro = { path = "crates/ztracing_macro" }
# External crates
#
agent-client-protocol = { version = "=0.11.1", features = ["unstable"] }
accesskit = "0.24.0"
accesskit_macos = "0.26.0"
accesskit_unix = "0.21.0"
accesskit_windows = "0.32.1"
agent-client-protocol = { version = "=0.12.1", features = ["unstable"] }
aho-corasick = "1.1"
alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "9d9640d4" }
alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "fcf32feacb367b75ec84dd40f041e4fd411d3cc1" }
any_vec = "0.14"
anyhow = "1.0.86"
ashpd = { version = "0.13", default-features = false, features = [
@ -554,14 +559,14 @@ clap = { version = "4.4", features = ["derive", "wrap_help"] }
cocoa = "=0.26.0"
cocoa-foundation = "=0.2.0"
const_format = "0.2"
convert_case = "0.8.0"
convert_case = "0.11.0"
core-foundation = "=0.10.0"
core-foundation-sys = "0.8.6"
core-video = { version = "0.5.2", features = ["metal"] }
cpal = "0.17"
crash-handler = "0.7"
criterion = { version = "0.5", features = ["html_reports"] }
ctor = "0.4.0"
ctor = "1.0.6"
dap-types = { git = "https://github.com/zed-industries/dap-types", rev = "1b461b310481d01e02b2603c16d7144b926339f8" }
dashmap = "6.0"
derive_more = { version = "2.1.1", features = [
@ -590,7 +595,7 @@ futures = "0.3.32"
futures-concurrency = "7.7.1"
futures-lite = "1.13"
gh-workflow = { git = "https://github.com/zed-industries/gh-workflow", rev = "37f3c0575d379c218a9c455ee67585184e40d43f" }
git2 = { version = "0.20.1", default-features = false, features = ["vendored-libgit2"] }
git2 = { version = "0.21.0", default-features = false, features = ["vendored-libgit2", "unstable-sha256"] }
globset = "0.4"
heapless = "0.9.2"
handlebars = "4.3"
@ -620,6 +625,7 @@ linkify = "0.10.0"
libwebrtc = "0.3.26"
livekit = { version = "0.7.32", features = ["tokio", "rustls-tls-native-roots"] }
log = { version = "0.4.16", features = ["kv_unstable_serde", "serde"] }
lru = "0.16"
lsp-types = { git = "https://github.com/zed-industries/lsp-types", rev = "f4dfa89a21ca35cd929b70354b1583fabae325f8" }
mach2 = "0.5"
markup5ever_rcdom = "0.3.0"
@ -721,6 +727,7 @@ serde_json_lenient = { version = "0.2", features = [
"preserve_order",
"raw_value",
] }
serde_yaml = "0.9.34"
serde_path_to_error = "0.1.17"
serde_urlencoded = "0.7"
sha2 = "0.10"
@ -762,7 +769,7 @@ toml_edit = { version = "0.22", default-features = false, features = [
"serde",
] }
tower-http = "0.4.4"
tree-sitter = { version = "0.26.8", features = ["wasm"] }
tree-sitter = { version = "0.26.9", features = ["wasm"] }
tree-sitter-bash = "0.25.1"
tree-sitter-c = "0.24.1"
tree-sitter-cpp = { git = "https://github.com/tree-sitter/tree-sitter-cpp", rev = "5cb9b693cfd7bfacab1d9ff4acac1a4150700609" }
@ -812,7 +819,7 @@ which = "6.0.0"
wasm-bindgen = "0.2.120"
web-time = "1.1.0"
webrtc-sys = "0.3.23"
wgpu = { git = "https://github.com/zed-industries/wgpu.git", branch = "v29" }
wgpu = { git = "https://github.com/zed-industries/wgpu.git", rev = "357a0c56e0070480ad9daea5d2eaa83150b79e88" }
windows-core = "0.61"
yaml-rust2 = "0.8"
yawc = "0.2.5"
@ -884,9 +891,9 @@ notify = { git = "https://github.com/zed-industries/notify.git", rev = "ce58c24c
notify-types = { git = "https://github.com/zed-industries/notify.git", rev = "ce58c24cad542c28e04ced02e20325a4ec28a31d" }
windows-capture = { git = "https://github.com/zed-industries/windows-capture.git", rev = "f0d6c1b6691db75461b732f6d5ff56eed002eeb9" }
calloop = { git = "https://github.com/zed-industries/calloop" }
livekit = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "147fbca3d4b592d96d33f5e6a84b59fc0b5d9bf1" }
libwebrtc = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "147fbca3d4b592d96d33f5e6a84b59fc0b5d9bf1" }
webrtc-sys = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "147fbca3d4b592d96d33f5e6a84b59fc0b5d9bf1" }
livekit = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "c3a55bbc207008f1ca3474b6037fdd3c443cad0f" }
libwebrtc = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "c3a55bbc207008f1ca3474b6037fdd3c443cad0f" }
webrtc-sys = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "c3a55bbc207008f1ca3474b6037fdd3c443cad0f" }
[profile.dev]
split-debuginfo = "unpacked"

View file

@ -1,788 +0,0 @@
Copyright 2022 - 2025 Zed Industries, Inc.
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View file

@ -13,7 +13,7 @@ On macOS, Linux, and Windows you can [download Zed directly](https://zed.dev/dow
Other platforms are not yet available:
- Web ([tracking issue](https://github.com/zed-industries/zed/issues/5396))
- Web ([tracking discussion](https://github.com/zed-industries/zed/discussions/26195))
### Developing Zed
@ -29,6 +29,8 @@ Also... we're hiring! Check out our [jobs](https://zed.dev/jobs) page for open r
### Licensing
Zed source code is licensed primarily under GPL-3.0-or-later, with Apache-2.0 components where marked.
License information for third party dependencies must be correctly provided for CI to pass.
We use [`cargo-about`](https://github.com/EmbarkStudios/cargo-about) to automatically comply with open source licenses. If CI is failing, check the following:

View file

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

Before

Width:  |  Height:  |  Size: 868 B

After

Width:  |  Height:  |  Size: 851 B

View file

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

Before

Width:  |  Height:  |  Size: 3.6 KiB

After

Width:  |  Height:  |  Size: 3.6 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 8.3 KiB

After

Width:  |  Height:  |  Size: 8.4 KiB

View file

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

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

View file

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

Before

Width:  |  Height:  |  Size: 379 B

After

Width:  |  Height:  |  Size: 371 B

View file

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

Before

Width:  |  Height:  |  Size: 870 B

After

Width:  |  Height:  |  Size: 861 B

View file

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

After

Width:  |  Height:  |  Size: 778 B

View file

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

Before

Width:  |  Height:  |  Size: 237 B

After

Width:  |  Height:  |  Size: 239 B

View file

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

After

Width:  |  Height:  |  Size: 1.2 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 6.3 KiB

After

Width:  |  Height:  |  Size: 6.3 KiB

View file

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

Before

Width:  |  Height:  |  Size: 769 B

After

Width:  |  Height:  |  Size: 746 B

View file

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

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

View file

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

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

View file

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

Before

Width:  |  Height:  |  Size: 1 KiB

After

Width:  |  Height:  |  Size: 1 KiB

View file

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

Before

Width:  |  Height:  |  Size: 876 B

After

Width:  |  Height:  |  Size: 872 B

View file

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

After

Width:  |  Height:  |  Size: 1.8 KiB

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

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

After

Width:  |  Height:  |  Size: 1.6 KiB

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

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

After

Width:  |  Height:  |  Size: 3.8 KiB

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

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

After

Width:  |  Height:  |  Size: 1 KiB

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

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

After

Width:  |  Height:  |  Size: 711 B

View file

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

After

Width:  |  Height:  |  Size: 566 B

View file

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

After

Width:  |  Height:  |  Size: 871 B

View file

@ -380,15 +380,7 @@
"shift-backspace": "agent::ArchiveSelectedThread",
},
},
{
"context": "RulesLibrary",
"bindings": {
"new": "rules_library::NewRule",
"ctrl-n": "rules_library::NewRule",
"ctrl-shift-s": "rules_library::ToggleDefaultRule",
"ctrl-w": "workspace::CloseWindow",
},
},
{
"context": "BufferSearchBar",
"bindings": {
@ -729,6 +721,7 @@
"use_key_equivalents": true,
"bindings": {
"space": "menu::Confirm",
"shift-r": "agent::RenameSelectedThread",
},
},
{
@ -1558,4 +1551,22 @@
"shift-tab": "git_graph::FocusPreviousTabStop",
},
},
{
"context": "SkillCreator",
"bindings": {
"ctrl-w": "workspace::CloseWindow",
"ctrl-enter": "skill_creator::SaveSkill",
"tab": "skill_creator::FocusNextField",
"shift-tab": "skill_creator::FocusPreviousField",
},
},
{
"context": "SkillCreator > Editor",
"bindings": {
"ctrl-w": "workspace::CloseWindow",
"ctrl-enter": "skill_creator::SaveSkill",
"tab": "skill_creator::FocusNextField",
"shift-tab": "skill_creator::FocusPreviousField",
},
},
]

View file

@ -427,15 +427,6 @@
"backspace": "agent::ArchiveSelectedThread",
},
},
{
"context": "RulesLibrary",
"use_key_equivalents": true,
"bindings": {
"cmd-n": "rules_library::NewRule",
"cmd-shift-s": "rules_library::ToggleDefaultRule",
"cmd-w": "workspace::CloseWindow",
},
},
{
"context": "BufferSearchBar",
"use_key_equivalents": true,
@ -785,6 +776,7 @@
"use_key_equivalents": true,
"bindings": {
"space": "menu::Confirm",
"shift-r": "agent::RenameSelectedThread",
},
},
{
@ -1651,4 +1643,24 @@
"shift-tab": "git_graph::FocusPreviousTabStop",
},
},
{
"context": "SkillCreator",
"use_key_equivalents": true,
"bindings": {
"cmd-w": "workspace::CloseWindow",
"cmd-enter": "skill_creator::SaveSkill",
"tab": "skill_creator::FocusNextField",
"shift-tab": "skill_creator::FocusPreviousField",
},
},
{
"context": "SkillCreator > Editor",
"use_key_equivalents": true,
"bindings": {
"cmd-w": "workspace::CloseWindow",
"cmd-enter": "skill_creator::SaveSkill",
"tab": "skill_creator::FocusNextField",
"shift-tab": "skill_creator::FocusPreviousField",
},
},
]

View file

@ -383,15 +383,6 @@
"shift-backspace": "agent::ArchiveSelectedThread",
},
},
{
"context": "RulesLibrary",
"use_key_equivalents": true,
"bindings": {
"ctrl-n": "rules_library::NewRule",
"ctrl-shift-s": "rules_library::ToggleDefaultRule",
"ctrl-w": "workspace::CloseWindow",
},
},
{
"context": "BufferSearchBar",
"use_key_equivalents": true,
@ -732,6 +723,7 @@
"use_key_equivalents": true,
"bindings": {
"space": "menu::Confirm",
"shift-r": "agent::RenameSelectedThread",
},
},
{
@ -1577,4 +1569,24 @@
"shift-tab": "git_graph::FocusPreviousTabStop",
},
},
{
"context": "SkillCreator",
"use_key_equivalents": true,
"bindings": {
"ctrl-w": "workspace::CloseWindow",
"ctrl-enter": "skill_creator::SaveSkill",
"tab": "skill_creator::FocusNextField",
"shift-tab": "skill_creator::FocusPreviousField",
},
},
{
"context": "SkillCreator > Editor",
"use_key_equivalents": true,
"bindings": {
"ctrl-w": "workspace::CloseWindow",
"ctrl-enter": "skill_creator::SaveSkill",
"tab": "skill_creator::FocusNextField",
"shift-tab": "skill_creator::FocusPreviousField",
},
},
]

View file

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

View file

@ -71,6 +71,8 @@
"agent_ui_font_size": null,
// The default font size for user messages in the agent panel.
"agent_buffer_font_size": 12,
// The default font size for the commit editor in the git panel and commit modal.
"git_commit_buffer_font_size": 12,
// How much to fade out unused code.
"unnecessary_code_fade": 0.3,
// Active pane styling settings.
@ -1133,6 +1135,7 @@
"spawn_agent": true,
"terminal": true,
"update_plan": true,
"update_title": true,
"search_web": true,
},
},
@ -1153,6 +1156,7 @@
"skill": true,
"spawn_agent": true,
"update_plan": true,
"update_title": true,
"search_web": true,
},
},
@ -1496,6 +1500,10 @@
// 4. Draw a background behind the color text..
// "lsp_document_colors": "background",
"lsp_document_colors": "inlay",
// Whether to query and display LSP `textDocument/documentLink` links in the editor.
//
// Default: true
"lsp_document_links": true,
// Diagnostics configuration.
"diagnostics": {
// Whether to show the project diagnostics button in the status bar.

View file

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

View file

@ -16,7 +16,9 @@ use gpui::{
};
use itertools::Itertools;
use language::language_settings::FormatOnSave;
use language::{Anchor, Buffer, BufferSnapshot, LanguageRegistry, Point, ToPoint, text_diff};
use language::{
Anchor, Buffer, BufferEditSource, BufferSnapshot, LanguageRegistry, Point, ToPoint, text_diff,
};
use markdown::{Markdown, MarkdownOptions};
pub use mention::*;
use project::lsp_store::{FormatTrigger, LspFormatTarget};
@ -648,9 +650,16 @@ impl Display for ToolCallStatus {
#[derive(Debug, PartialEq, Clone)]
pub enum ContentBlock {
Empty,
Markdown { markdown: Entity<Markdown> },
ResourceLink { resource_link: acp::ResourceLink },
Image { image: Arc<gpui::Image> },
Markdown {
markdown: Entity<Markdown>,
},
ResourceLink {
resource_link: acp::ResourceLink,
},
Image {
image: Arc<gpui::Image>,
dimensions: Option<gpui::Size<u32>>,
},
}
impl ContentBlock {
@ -692,8 +701,8 @@ impl ContentBlock {
};
}
(ContentBlock::Empty, acp::ContentBlock::Image(image_content)) => {
if let Some(image) = Self::decode_image(image_content) {
*self = ContentBlock::Image { image };
if let Some((image, dimensions)) = Self::decode_image(image_content) {
*self = ContentBlock::Image { image, dimensions };
} else {
let new_content = Self::image_md(image_content);
*self = Self::create_markdown_block(new_content, language_registry, cx);
@ -721,14 +730,36 @@ impl ContentBlock {
}
}
fn decode_image(image_content: &acp::ImageContent) -> Option<Arc<gpui::Image>> {
fn decode_image(
image_content: &acp::ImageContent,
) -> Option<(Arc<gpui::Image>, Option<gpui::Size<u32>>)> {
use base64::Engine as _;
let bytes = base64::engine::general_purpose::STANDARD
.decode(image_content.data.as_bytes())
.ok()?;
let format = gpui::ImageFormat::from_mime_type(&image_content.mime_type)?;
Some(Arc::new(gpui::Image::from_bytes(format, bytes)))
let dimensions = Self::image_dimensions(&bytes, format);
Some((Arc::new(gpui::Image::from_bytes(format, bytes)), dimensions))
}
fn image_dimensions(bytes: &[u8], format: gpui::ImageFormat) -> Option<gpui::Size<u32>> {
let format = match format {
gpui::ImageFormat::Png => image::ImageFormat::Png,
gpui::ImageFormat::Jpeg => image::ImageFormat::Jpeg,
gpui::ImageFormat::Webp => image::ImageFormat::WebP,
gpui::ImageFormat::Gif => image::ImageFormat::Gif,
gpui::ImageFormat::Svg => return None,
gpui::ImageFormat::Bmp => image::ImageFormat::Bmp,
gpui::ImageFormat::Tiff => image::ImageFormat::Tiff,
gpui::ImageFormat::Ico => image::ImageFormat::Ico,
gpui::ImageFormat::Pnm => image::ImageFormat::Pnm,
};
image::ImageReader::with_format(std::io::Cursor::new(bytes), format)
.into_dimensions()
.ok()
.map(|(width, height)| gpui::Size { width, height })
}
fn create_markdown_block(
@ -744,6 +775,7 @@ impl ContentBlock {
None,
MarkdownOptions {
render_mermaid_diagrams: true,
render_metadata_blocks: true,
..Default::default()
},
cx,
@ -808,9 +840,9 @@ impl ContentBlock {
}
}
pub fn image(&self) -> Option<&Arc<gpui::Image>> {
pub fn image(&self) -> Option<(&Arc<gpui::Image>, Option<gpui::Size<u32>>)> {
match self {
ContentBlock::Image { image } => Some(image),
ContentBlock::Image { image, dimensions } => Some((image, *dimensions)),
_ => None,
}
}
@ -895,7 +927,7 @@ impl ToolCallContent {
}
}
pub fn image(&self) -> Option<&Arc<gpui::Image>> {
pub fn image(&self) -> Option<(&Arc<gpui::Image>, Option<gpui::Size<u32>>)> {
match self {
Self::ContentBlock(content) => content.image(),
_ => None,
@ -2883,7 +2915,9 @@ impl AcpThread {
});
let format_on_save = buffer.update(cx, |buffer, cx| {
buffer.start_transaction();
buffer.edit(edits, None, cx);
buffer.end_transaction_with_source(BufferEditSource::Agent, cx);
let settings =
language::language_settings::LanguageSettings::for_buffer(buffer, cx);
@ -2926,6 +2960,7 @@ impl AcpThread {
extra_env: Vec<acp::EnvVariable>,
cwd: Option<PathBuf>,
output_byte_limit: Option<u64>,
sandbox_wrap: Option<SandboxWrap>,
cx: &mut Context<Self>,
) -> Task<Result<Entity<Terminal>>> {
let env = match &cwd {
@ -2966,6 +3001,8 @@ impl AcpThread {
ShellBuilder::new(&Shell::Program(shell), is_windows)
.redirect_stdin_to_dev_null()
.build(Some(command.clone()), &args);
let (task_command, task_args, sandbox_config) =
apply_sandbox_wrap(task_command, task_args, sandbox_wrap)?;
let terminal = project
.update(cx, |project, cx| {
project.create_terminal_task(
@ -2989,6 +3026,7 @@ impl AcpThread {
output_byte_limit.map(|l| l as usize),
terminal,
language_registry,
sandbox_config,
cx,
)
}))
@ -3068,6 +3106,9 @@ impl AcpThread {
output_byte_limit.map(|l| l as usize),
terminal,
language_registry,
// External terminal providers manage their own sandboxing
// (if any). We don't wrap their commands.
None,
cx,
)
});

View file

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

View file

@ -1,7 +1,6 @@
use agent_client_protocol::schema as acp;
use anyhow::{Context as _, Result, bail};
use file_icons::FileIcons;
use prompt_store::{PromptId, UserPromptId};
use serde::{Deserialize, Serialize};
use std::{
borrow::Cow,
@ -37,10 +36,6 @@ pub enum MentionUri {
id: acp::SessionId,
name: String,
},
Rule {
id: PromptId,
name: String,
},
Diagnostics {
#[serde(default = "default_include_errors")]
include_errors: bool,
@ -51,6 +46,8 @@ pub enum MentionUri {
#[serde(default, skip_serializing_if = "Option::is_none")]
abs_path: Option<PathBuf>,
line_range: RangeInclusive<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
column: Option<u32>,
},
Fetch {
url: Url,
@ -105,6 +102,17 @@ impl MentionUri {
Ok(start_line..=end_line)
}
let parse_column =
|input: Option<String>| -> Option<u32> { input?.parse::<u32>().ok()?.checked_sub(1) };
let validate_query_params = |url: &Url, allowed: &[&str]| -> Result<()> {
for (key, _) in url.query_pairs() {
if !allowed.contains(&key.as_ref()) {
bail!("invalid query parameter")
}
}
Ok(())
};
let parse_absolute_path = |input: &str| -> Result<Self> {
let (path_input, fragment) = input
.split_once('#')
@ -114,6 +122,7 @@ impl MentionUri {
return Ok(MentionUri::Selection {
abs_path: Some(path_input.into()),
line_range: fragment,
column: None,
});
}
@ -123,10 +132,12 @@ impl MentionUri {
let line = row
.checked_sub(1)
.context("Line numbers should be 1-based")?;
// TODO: Preserve column info too.
Ok(MentionUri::Selection {
abs_path: Some(abs_path),
line_range: line..=line,
column: path_with_position
.column
.map(|column| column.saturating_sub(1)),
})
} else {
Ok(MentionUri::File { abs_path })
@ -156,8 +167,10 @@ impl MentionUri {
let path = normalized.as_ref();
if let Some(fragment) = url.fragment() {
validate_query_params(&url, &["symbol", "column"])?;
let line_range = parse_line_range(fragment).log_err().unwrap_or(1..=1);
if let Some(name) = single_query_param(&url, "symbol")? {
let column = parse_column(query_param(&url, "column"));
if let Some(name) = query_param(&url, "symbol") {
Ok(Self::Symbol {
name,
abs_path: path.into(),
@ -167,6 +180,7 @@ impl MentionUri {
Ok(Self::Selection {
abs_path: Some(path.into()),
line_range,
column,
})
}
} else if input.ends_with("/") {
@ -186,13 +200,6 @@ impl MentionUri {
id: acp::SessionId::new(thread_id),
name,
})
} else if let Some(rule_id) = path.strip_prefix("/agent/rule/") {
let name = single_query_param(&url, "name")?.context("Missing rule name")?;
let rule_id = UserPromptId(rule_id.parse()?);
Ok(Self::Rule {
id: rule_id.into(),
name,
})
} else if path == "/agent/diagnostics" {
let mut include_errors = default_include_errors();
let mut include_warnings = false;
@ -216,9 +223,11 @@ impl MentionUri {
.fragment()
.context("Missing fragment for untitled buffer selection")?;
let line_range = parse_line_range(fragment)?;
validate_query_params(&url, &["column"])?;
Ok(Self::Selection {
abs_path: None,
line_range,
column: parse_column(query_param(&url, "column")),
})
} else if let Some(name) = path.strip_prefix("/agent/symbol/") {
let fragment = url
@ -245,13 +254,15 @@ impl MentionUri {
abs_path: path.into(),
})
} else if path.starts_with("/agent/selection") {
validate_query_params(&url, &["path", "column"])?;
let fragment = url.fragment().context("Missing fragment for selection")?;
let line_range = parse_line_range(fragment)?;
let path =
single_query_param(&url, "path")?.context("Missing path for selection")?;
let column = parse_column(query_param(&url, "column"));
let path = query_param(&url, "path").context("Missing path for selection")?;
Ok(Self::Selection {
abs_path: Some(path.into()),
line_range,
column,
})
} else if path.starts_with("/agent/terminal-selection") {
let line_count = single_query_param(&url, "lines")?
@ -319,7 +330,6 @@ impl MentionUri {
MentionUri::PastedImage { name } => name.clone(),
MentionUri::Symbol { name, .. } => name.clone(),
MentionUri::Thread { name, .. } => name.clone(),
MentionUri::Rule { name, .. } => name.clone(),
MentionUri::Diagnostics { .. } => "Diagnostics".to_string(),
MentionUri::TerminalSelection { line_count } => {
if *line_count == 1 {
@ -342,13 +352,33 @@ impl MentionUri {
..
} => selection_name(path.as_deref(), line_range),
MentionUri::Fetch { url } => url.to_string(),
MentionUri::Skill { name, .. } => name.clone(),
}
}
/// Returns a label for this mention at the given disambiguation `detail`
/// level. `detail == 0` is the base name returned by [`Self::name`]; higher
/// levels include progressively more context (e.g. additional parent path
/// components for files, or the source for skills) until a fixed point is
/// reached. Intended to be driven by [`util::disambiguate::compute_disambiguation_details`].
pub fn disambiguated_name(&self, detail: usize) -> String {
if detail == 0 {
return self.name();
}
match self {
MentionUri::Skill { name, source, .. } => {
if source.is_empty() {
// Must match `SkillSource::display_label()` in agent_skills.
format!("{} (global)", name)
} else {
format!("{} ({})", name, source)
}
}
MentionUri::File { abs_path, .. } | MentionUri::Directory { abs_path, .. } => {
project::path_suffix(abs_path, detail)
}
_ => self.name(),
}
}
@ -400,7 +430,6 @@ impl MentionUri {
.unwrap_or_else(|| IconName::Folder.path().into()),
MentionUri::Symbol { .. } => IconName::Code.path().into(),
MentionUri::Thread { .. } => IconName::Thread.path().into(),
MentionUri::Rule { .. } => IconName::Reader.path().into(),
MentionUri::Diagnostics { .. } => IconName::Warning.path().into(),
MentionUri::TerminalSelection { .. } => IconName::Terminal.path().into(),
MentionUri::Selection { .. } => IconName::Reader.path().into(),
@ -440,6 +469,7 @@ impl MentionUri {
abs_path,
name,
line_range,
..
} => {
let mut url = Url::parse("file:///").unwrap();
url.set_path(&abs_path.to_string_lossy());
@ -454,6 +484,7 @@ impl MentionUri {
MentionUri::Selection {
abs_path,
line_range,
column,
} => {
let mut url = if let Some(path) = abs_path {
let mut url = Url::parse("file:///").unwrap();
@ -464,6 +495,10 @@ impl MentionUri {
url.set_path("/agent/untitled-buffer");
url
};
if let Some(column) = column {
url.query_pairs_mut()
.append_pair("column", &(column + 1).to_string());
}
url.set_fragment(Some(&format!(
"L{}:{}",
line_range.start() + 1,
@ -477,12 +512,6 @@ impl MentionUri {
url.query_pairs_mut().append_pair("name", name);
url
}
MentionUri::Rule { name, id } => {
let mut url = Url::parse("zed:///").unwrap();
url.set_path(&format!("/agent/rule/{id}"));
url.query_pairs_mut().append_pair("name", name);
url
}
MentionUri::Diagnostics {
include_errors,
include_warnings,
@ -544,6 +573,11 @@ fn default_include_errors() -> bool {
true
}
fn query_param(url: &Url, name: &'static str) -> Option<String> {
url.query_pairs()
.find_map(|(key, value)| (key == name).then(|| value.to_string()))
}
fn single_query_param(url: &Url, name: &'static str) -> Result<Option<String>> {
let pairs = url.query_pairs().collect::<Vec<_>>();
match pairs.as_slice() {
@ -678,6 +712,7 @@ mod tests {
abs_path: path,
name,
line_range,
..
} => {
assert_eq!(path, Path::new(path!("/path/to/file.rs")));
assert_eq!(name, "MySymbol");
@ -697,6 +732,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
assert_eq!(line_range.start(), &4);
@ -728,6 +764,7 @@ mod tests {
MentionUri::Selection {
abs_path: None,
line_range,
..
} => {
assert_eq!(line_range.start(), &0);
assert_eq!(line_range.end(), &9);
@ -754,20 +791,6 @@ mod tests {
assert_eq!(parsed.to_uri().to_string(), thread_uri);
}
#[test]
fn test_parse_rule_uri() {
let rule_uri = "zed:///agent/rule/d8694ff2-90d5-4b6f-be33-33c1763acd52?name=Some+rule";
let parsed = MentionUri::parse(rule_uri, PathStyle::local()).unwrap();
match &parsed {
MentionUri::Rule { id, name } => {
assert_eq!(id.to_string(), "d8694ff2-90d5-4b6f-be33-33c1763acd52");
assert_eq!(name, "Some rule");
}
_ => panic!("Expected Rule variant"),
}
assert_eq!(parsed.to_uri().to_string(), rule_uri);
}
#[test]
fn test_parse_skill_uri_round_trip() {
let skill_uri = MentionUri::Skill {
@ -875,6 +898,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
assert_eq!(line_range.start(), &41);
@ -884,6 +908,29 @@ mod tests {
}
}
#[test]
fn test_parse_absolute_file_path_with_row_and_column() {
let file_path = "/path/to/file.rs:42:5";
let parsed = MentionUri::parse(file_path, PathStyle::Posix).unwrap();
match &parsed {
MentionUri::Selection {
abs_path: path,
line_range,
column,
} => {
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
assert_eq!(line_range.start(), &41);
assert_eq!(line_range.end(), &41);
assert_eq!(column, &Some(4));
let parsed_again = MentionUri::parse(parsed.to_uri().as_ref(), PathStyle::Posix)
.expect("selection URI with column should parse");
assert_eq!(parsed_again, parsed.clone());
}
_ => panic!("Expected Selection variant"),
}
}
#[test]
fn test_parse_absolute_file_path_with_fragment_line() {
let file_path = "/path/to/file.rs#L42";
@ -892,6 +939,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
assert_eq!(line_range.start(), &41);
@ -921,6 +969,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(
path.as_ref().unwrap(),
@ -941,6 +990,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(
path.as_ref().unwrap(),
@ -973,6 +1023,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
assert_eq!(line_range.start(), &41);
@ -990,6 +1041,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(
path.as_ref().unwrap(),
@ -1011,6 +1063,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
assert_eq!(line_range.start(), &1871);
@ -1028,6 +1081,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
assert_eq!(line_range.start(), &9);
@ -1043,6 +1097,7 @@ mod tests {
MentionUri::Selection {
abs_path: path,
line_range,
..
} => {
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
assert_eq!(line_range.start(), &9);
@ -1070,4 +1125,68 @@ mod tests {
let parsed_single = MentionUri::parse(single_line_uri, PathStyle::local()).unwrap();
assert_eq!(parsed_single.name(), "Terminal (1 line)");
}
#[test]
fn test_disambiguated_name() {
// Two files with the same name — should disambiguate with parent dir
let file_a = MentionUri::File {
abs_path: PathBuf::from(path!("/project/src/README.md")),
};
let file_b = MentionUri::File {
abs_path: PathBuf::from(path!("/project/docs/README.md")),
};
assert_eq!(file_a.name(), "README.md");
assert_eq!(file_b.name(), "README.md");
assert_eq!(file_a.disambiguated_name(0), "README.md");
assert_eq!(file_a.disambiguated_name(1), "src/README.md");
assert_eq!(file_b.disambiguated_name(1), "docs/README.md");
// Files that still collide at one parent should grow further.
let deep_a = MentionUri::File {
abs_path: PathBuf::from(path!("/a/src/foo.rs")),
};
let deep_b = MentionUri::File {
abs_path: PathBuf::from(path!("/b/src/foo.rs")),
};
assert_eq!(deep_a.disambiguated_name(1), "src/foo.rs");
assert_eq!(deep_b.disambiguated_name(1), "src/foo.rs");
assert_eq!(deep_a.disambiguated_name(2), "a/src/foo.rs");
assert_eq!(deep_b.disambiguated_name(2), "b/src/foo.rs");
// Two skills with the same name — should disambiguate with source
let global_skill = MentionUri::Skill {
name: "create-skill".into(),
source: "".into(),
skill_file_path: PathBuf::from("/global/create-skill/SKILL.md"),
};
let project_skill = MentionUri::Skill {
name: "create-skill".into(),
source: "my-project".into(),
skill_file_path: PathBuf::from("/project/create-skill/SKILL.md"),
};
assert_eq!(global_skill.name(), "create-skill");
assert_eq!(global_skill.disambiguated_name(0), "create-skill");
assert_eq!(global_skill.disambiguated_name(1), "create-skill (global)");
assert_eq!(
project_skill.disambiguated_name(1),
"create-skill (my-project)"
);
// A type without special disambiguation (Thread) — detail has no effect
// (the value is a fixed point so the disambiguation loop terminates).
let thread = MentionUri::Thread {
id: acp::SessionId::new("123"),
name: "My Thread".into(),
};
assert_eq!(thread.disambiguated_name(0), "My Thread");
assert_eq!(thread.disambiguated_name(1), "My Thread");
assert_eq!(thread.disambiguated_name(5), "My Thread");
// Edge case: file at filesystem root has no parent to show
let root_file = MentionUri::File {
abs_path: PathBuf::from(path!("/README.md")),
};
assert_eq!(root_file.disambiguated_name(1), "README.md");
assert_eq!(root_file.disambiguated_name(5), "README.md");
}
}

View file

@ -17,6 +17,82 @@ use std::{
use task::Shell;
use util::get_default_system_shell_preferring_bash;
/// Request to run a terminal command inside an OS-level sandbox.
///
/// Passed to [`super::AcpThread::create_terminal`]. The actual sandboxing
/// mechanism is platform-specific (today: macOS Seatbelt; nothing on other
/// platforms — the wrap is silently a no-op there), so callers describe the
/// *intent* with plain data here rather than constructing platform-specific
/// types directly.
///
/// All-zero defaults are the fully-sandboxed run. Setting `allow_network` /
/// `allow_fs_write` requests a relaxation; the caller is responsible for
/// having obtained user approval before reaching this point.
#[derive(Clone, Debug, Default)]
pub struct SandboxWrap {
/// Directory subtrees the sandbox should allow writes to. Pass the
/// project's worktree paths (and any per-command scratch directory)
/// here — *not* the command's working directory, which is model-
/// controlled and would let the model widen its own writable scope.
pub writable_paths: Vec<PathBuf>,
/// Allow outbound network access for this command.
pub allow_network: bool,
/// Allow unrestricted filesystem writes (ignores `writable_paths`).
pub allow_fs_write: bool,
}
/// Opaque RAII handle the sandbox implementation hands back to keep its
/// per-command resources (e.g. an on-disk Seatbelt config file) alive for
/// the duration of the spawned command. `Terminal` holds it in a field
/// whose only job is to drop with the entity.
pub type SandboxConfigHandle = Box<dyn std::any::Any + Send>;
/// Apply a [`SandboxWrap`] to a `(program, args)` pair, substituting the
/// platform's sandbox-launcher invocation in place of the original. The
/// returned `SandboxConfigHandle` (when `Some`) must be kept alive for the
/// duration of the spawned command — dropping it deletes any on-disk
/// config the launcher reads at startup.
///
/// On non-macOS hosts this is a no-op: the inputs pass through unchanged
/// and the returned handle is `None`. (We don't yet have a sandbox
/// integration for other platforms.)
pub(crate) fn apply_sandbox_wrap(
program: String,
args: Vec<String>,
sandbox_wrap: Option<SandboxWrap>,
) -> anyhow::Result<(String, Vec<String>, Option<SandboxConfigHandle>)> {
let Some(sandbox_wrap) = sandbox_wrap else {
return Ok((program, args, None));
};
#[cfg(target_os = "macos")]
{
let writable: Vec<&std::path::Path> = sandbox_wrap
.writable_paths
.iter()
.map(|p| p.as_path())
.collect();
let permissions = sandbox::macos_seatbelt::SandboxPermissions {
allow_network: sandbox_wrap.allow_network,
allow_fs_write: sandbox_wrap.allow_fs_write,
};
let (new_program, new_args, config_file) =
sandbox::macos_seatbelt::wrap_invocation(&program, &args, &writable, permissions)?;
Ok((
new_program,
new_args,
Some(Box::new(config_file) as SandboxConfigHandle),
))
}
#[cfg(not(target_os = "macos"))]
{
// No sandbox integration available; ignore the wrap request and
// let the command run with the agent's ambient permissions.
let _ = sandbox_wrap;
Ok((program, args, None))
}
}
pub struct Terminal {
id: acp::TerminalId,
command: Entity<Markdown>,
@ -30,6 +106,10 @@ pub struct Terminal {
/// (e.g., clicking the Stop button). This is set before kill() is called
/// so that code awaiting wait_for_exit() can check it deterministically.
user_stopped: Arc<AtomicBool>,
/// RAII handle kept alive for the duration of the sandboxed command.
/// `None` when the command isn't sandboxed (the common case for
/// terminals not created by the agent).
_sandbox_config: Option<SandboxConfigHandle>,
}
pub struct TerminalOutput {
@ -48,11 +128,13 @@ impl Terminal {
output_byte_limit: Option<usize>,
terminal: Entity<terminal::Terminal>,
language_registry: Arc<LanguageRegistry>,
sandbox_config: Option<SandboxConfigHandle>,
cx: &mut Context<Self>,
) -> Self {
let command_task = terminal.read(cx).wait_for_completed_task(cx);
Self {
id,
_sandbox_config: sandbox_config,
command: cx.new(|cx| {
Markdown::new(
format!("```\n{}\n```", command_label).into(),

View file

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

View file

@ -936,7 +936,11 @@ impl ActionLog {
let mut undo_buffers = Vec::new();
let mut futures = Vec::new();
for buffer in self.changed_buffers(cx).into_keys() {
for buffer in self
.changed_buffers(cx)
.map(|(buffer, _)| buffer)
.collect::<Vec<_>>()
{
let buffer_ranges = vec![Anchor::min_max_range_for_buffer(
buffer.read(cx).remote_id(),
)];
@ -1023,17 +1027,19 @@ impl ActionLog {
}
/// Returns the set of buffers that contain edits that haven't been reviewed by the user.
pub fn changed_buffers(&self, cx: &App) -> BTreeMap<Entity<Buffer>, Entity<BufferDiff>> {
pub fn changed_buffers(
&self,
cx: &App,
) -> impl Iterator<Item = (Entity<Buffer>, Entity<BufferDiff>)> {
self.tracked_buffers
.iter()
.filter(|(_, tracked)| tracked.has_edits(cx))
.map(|(buffer, tracked)| (buffer.clone(), tracked.diff.clone()))
.collect()
}
/// Returns the total number of lines added and removed across all unreviewed buffers.
pub fn diff_stats(&self, cx: &App) -> DiffStats {
DiffStats::all_files(&self.changed_buffers(cx), cx)
DiffStats::all_files(self.changed_buffers(cx), cx)
}
/// Iterate over buffers changed since last read or edited by the model
@ -1079,7 +1085,7 @@ impl DiffStats {
}
pub fn all_files(
changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
changed_buffers: impl IntoIterator<Item = (Entity<Buffer>, Entity<BufferDiff>)>,
cx: &App,
) -> Self {
let mut total = DiffStats::default();
@ -1334,7 +1340,7 @@ mod tests {
use std::env;
use util::{RandomCharIter, path};
#[ctor::ctor]
#[ctor::ctor(unsafe)]
fn init_logger() {
zlog::init_test();
}
@ -3254,21 +3260,21 @@ mod tests {
child_log_1
.read(cx)
.changed_buffers(cx)
.into_keys()
.map(|(buffer, _)| buffer)
.collect()
});
let child_2_changed: Vec<_> = cx.read(|cx| {
child_log_2
.read(cx)
.changed_buffers(cx)
.into_keys()
.map(|(buffer, _)| buffer)
.collect()
});
let parent_changed: Vec<_> = cx.read(|cx| {
parent_log
.read(cx)
.changed_buffers(cx)
.into_keys()
.map(|(buffer, _)| buffer)
.collect()
});
@ -3494,7 +3500,6 @@ mod tests {
action_log
.read(cx)
.changed_buffers(cx)
.into_iter()
.map(|(buffer, diff)| {
let snapshot = buffer.read(cx).snapshot();
(

View file

@ -65,6 +65,7 @@ streaming_diff.workspace = true
strsim.workspace = true
task.workspace = true
telemetry.workspace = true
tempfile.workspace = true
text.workspace = true
thiserror.workspace = true
ui.workspace = true
@ -77,11 +78,13 @@ zed_env_vars.workspace = true
zstd.workspace = true
[dev-dependencies]
assets.workspace = true
async-io.workspace = true
agent_servers = { workspace = true, "features" = ["test-support"] }
client = { workspace = true, "features" = ["test-support"] }
clock = { workspace = true, "features" = ["test-support"] }
context_server = { workspace = true, "features" = ["test-support"] }
criterion.workspace = true
ctor.workspace = true
db = { workspace = true, "features" = ["test-support"] }
editor = { workspace = true, "features" = ["test-support"] }
@ -99,10 +102,15 @@ project = { workspace = true, "features" = ["test-support"] }
rand.workspace = true
reqwest_client.workspace = true
settings = { workspace = true, "features" = ["test-support"] }
tempfile.workspace = true
theme = { workspace = true, "features" = ["test-support"] }
theme_settings.workspace = true
unindent = { workspace = true }
zlog.workspace = true
[[bench]]
name = "edit_file_tool"
harness = false
required-features = ["test-support"]

View file

@ -0,0 +1,743 @@
use std::{
any::Any,
future::Future,
path::Path,
sync::Arc,
task::{Context, Poll},
};
use action_log::ActionLog;
use agent::{
AgentTool, ContextServerRegistry, EditFileTool, EditFileToolInput, EditFileToolOutput,
Templates, Thread, ToolCallEventStream, ToolInput,
};
use agent_settings::{AgentSettings, ToolRules};
use criterion::{
BatchSize, BenchmarkId, Criterion, Throughput, black_box, criterion_group, criterion_main,
};
use editor::{Editor, EditorStyle};
use futures::{StreamExt as _, pin_mut, task::noop_waker};
use gpui::{
AnyWindowHandle, AppContext as _, BackgroundExecutor, Entity, Focusable as _, TestAppContext,
UpdateGlobal as _,
};
use language::{FakeLspAdapter, rust_lang};
use language_model::fake_provider::FakeLanguageModel;
use project::{FakeFs, Project};
use prompt_store::ProjectContext;
use rand::{Rng as _, SeedableRng as _, rngs::StdRng};
use serde_json::{Value, json};
use settings::{Settings as _, SettingsStore};
use ui::IntoElement as _;
const SEED: u64 = 0x5EED_5EED;
const OLD_TEXT_CHUNK_SIZE: usize = 512;
const NEW_TEXT_CHUNK_SIZE: usize = 512;
const FILE_PROJECT_PATH: &str = "root/src/workspace_snapshot.rs";
const FILE_ABS_PATH: &str = "/root/src/workspace_snapshot.rs";
#[derive(Clone)]
struct EditOp {
old_text: String,
new_text: String,
}
#[derive(Clone)]
struct EditFixture {
name: &'static str,
old_file_text: String,
expected_file_text: String,
edits: Vec<EditOp>,
}
struct BenchmarkHarness {
cx: Option<TestAppContext>,
edit_tool: Option<Arc<EditFileTool>>,
thread: Option<Entity<Thread>>,
partial_payloads: Vec<Value>,
final_payload: Value,
expected_file_text: String,
editor: Option<Entity<Editor>>,
window: Option<AnyWindowHandle>,
// Keeps the LSP buffer-registration handle and the fake language server alive
// for the lifetime of the benchmark so `didChange`/diagnostics keep flowing
// while edits are applied.
keep_alive: Vec<Box<dyn Any>>,
}
impl Drop for BenchmarkHarness {
fn drop(&mut self) {
// Release our handles to the entities first.
self.edit_tool.take();
self.thread.take();
self.editor.take();
self.keep_alive.clear();
if let Some(mut cx) = self.cx.take() {
// Close the editor window so the editor entity and the buffer handles
// it holds are released, then pump the executor so cancelled editor /
// action-log background tasks drop their captured handles before the
// leak detector runs on `TestAppContext` drop.
if let Some(window) = self.window.take() {
cx.update_window(window, |_, window, _| window.remove_window())
.ok();
}
cx.update(|_| {});
cx.executor().run_until_parked();
cx.quit();
}
}
}
fn edit_file_tool_streaming(c: &mut Criterion) {
let fixtures = fixtures();
let mut group = c.benchmark_group("edit_file_tool_streaming");
group.sample_size(10);
for fixture in fixtures {
let new_bytes: usize = fixture.edits.iter().map(|edit| edit.new_text.len()).sum();
group.throughput(Throughput::Bytes(new_bytes as u64));
group.bench_with_input(
BenchmarkId::new(fixture.name, fixture.old_file_text.len()),
&fixture,
|bench, fixture| {
bench.iter_batched(
|| setup_harness(fixture.clone()),
|mut harness| {
let output = run_streamed_edit(&mut harness);
let EditFileToolOutput::Success { new_text, .. } = &output else {
panic!("expected edit_file tool to succeed");
};
assert_eq!(new_text, &harness.expected_file_text);
// Return the harness as part of the output so its teardown (which has
// to pump the executor to release `Entity<Buffer>` handles captured by
// background tasks) runs in criterion's drop phase after the timer has
// stopped, rather than inside the timed region.
(black_box(output), harness)
},
BatchSize::SmallInput,
);
},
);
}
group.finish();
}
fn setup_harness(fixture: EditFixture) -> BenchmarkHarness {
let mut cx = init_context();
let executor = cx.executor();
let parts = block_on_executor(
&executor,
setup_editor_and_tool(&mut cx, fixture.old_file_text.clone()),
);
// Let the LSP handshake, initial parse, and first layout settle before timing.
cx.executor().run_until_parked();
let partial_payloads = streamed_partial_payloads(&fixture.edits);
let final_payload = json!({
"path": FILE_PROJECT_PATH,
"edits": fixture
.edits
.iter()
.map(|edit| json!({ "old_text": edit.old_text, "new_text": edit.new_text }))
.collect::<Vec<_>>(),
});
BenchmarkHarness {
cx: Some(cx),
edit_tool: Some(parts.edit_tool),
thread: Some(parts.thread),
partial_payloads,
final_payload,
expected_file_text: fixture.expected_file_text,
editor: Some(parts.editor),
window: Some(parts.window),
keep_alive: parts.keep_alive,
}
}
struct HarnessParts {
edit_tool: Arc<EditFileTool>,
thread: Entity<Thread>,
editor: Entity<Editor>,
window: AnyWindowHandle,
keep_alive: Vec<Box<dyn Any>>,
}
/// Builds a project + edit tool, opens the target buffer in an editor view inside
/// a window, and attaches a fake Rust language server. This mirrors the real app:
/// the edited file is open in a pane with a language server, so each buffer edit
/// drives the editor's observer cascade (matching brackets, code actions, outline,
/// bracket colorization), a tree-sitter reparse, and an LSP `didChange` +
/// diagnostics round-trip — the costs that dominate a real agent edit.
async fn setup_editor_and_tool(cx: &mut TestAppContext, file_text: String) -> HarnessParts {
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
"/root",
json!({
"src": {
"workspace_snapshot.rs": file_text,
},
}),
)
.await;
let project = Project::test(fs, [Path::new("/root")], cx).await;
let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
language_registry.add(rust_lang());
let mut fake_servers = language_registry.register_fake_lsp(
"Rust",
FakeLspAdapter {
capabilities: lsp::ServerCapabilities {
text_document_sync: Some(lsp::TextDocumentSyncCapability::Kind(
lsp::TextDocumentSyncKind::INCREMENTAL,
)),
..Default::default()
},
..Default::default()
},
);
let context_server_registry =
cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
let model = Arc::new(FakeLanguageModel::default());
let thread = cx.new(|cx| {
Thread::new(
project.clone(),
cx.new(|_cx| ProjectContext::default()),
context_server_registry,
Templates::new(),
Some(model),
cx,
)
});
let action_log: Entity<ActionLog> =
thread.read_with(cx, |thread, _cx| thread.action_log().clone());
let edit_tool = Arc::new(EditFileTool::new(
project.clone(),
thread.downgrade(),
action_log,
language_registry,
));
// Open the same buffer the tool will edit and register it with the language
// servers so edits produce `didChange` notifications.
let buffer = project
.update(cx, |project, cx| {
project.open_local_buffer(FILE_ABS_PATH, cx)
})
.await
.expect("failed to open buffer");
let lsp_handle = project.update(cx, |project, cx| {
project.register_buffer_with_language_servers(&buffer, cx)
});
let fake_server = fake_servers
.next()
.await
.expect("fake language server should start");
// Publish diagnostics on every edit, mirroring a real server reacting to
// `didChange`, so the editor's diagnostics path runs per edit.
let server = fake_server.clone();
fake_server.handle_notification::<lsp::notification::DidChangeTextDocument, _>(
move |params, _cx| {
server.notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
uri: params.text_document.uri.clone(),
version: Some(params.text_document.version),
diagnostics: vec![lsp::Diagnostic {
range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 1)),
severity: Some(lsp::DiagnosticSeverity::WARNING),
message: "bench diagnostic".to_string(),
..Default::default()
}],
});
},
);
// Attach an editor view in a window and lay it out once so the viewport-gated
// observers (bracket colorization, selection highlights) have a visible range.
let window = cx.add_window(|window, cx| {
let mut editor = Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
editor.set_style(EditorStyle::default(), window, cx);
window.focus(&editor.focus_handle(cx), cx);
editor
});
let editor = window.root(cx).expect("window should have an editor root");
let window: AnyWindowHandle = window.into();
// Lay out and paint a real frame so the editor establishes a viewport (this
// is what makes the viewport-gated observers like bracket colorization run).
{
let mut visual_cx = gpui::VisualTestContext::from_window(window, &*cx);
visual_cx.draw(
gpui::point(gpui::px(0.0), gpui::px(0.0)),
gpui::size(gpui::px(1024.0), gpui::px(768.0)),
|_, _| editor.clone().into_any_element(),
);
}
let keep_alive: Vec<Box<dyn Any>> = vec![
Box::new(lsp_handle),
Box::new(fake_server),
Box::new(fake_servers),
Box::new(buffer),
];
HarnessParts {
edit_tool,
thread,
editor,
window,
keep_alive,
}
}
fn init_context() -> TestAppContext {
let cx = TestAppContext::single();
cx.update(|cx| {
let settings_store = SettingsStore::test(cx);
cx.set_global(settings_store);
assets::Assets.load_test_fonts(cx);
theme_settings::init(theme::LoadThemes::JustBase, cx);
editor::init(cx);
SettingsStore::update_global(cx, |store: &mut SettingsStore, cx| {
store.update_user_settings(cx, |settings| {
settings
.project
.all_languages
.defaults
.ensure_final_newline_on_save = Some(false);
settings.project.all_languages.defaults.colorize_brackets = Some(true);
});
});
let mut agent_settings = AgentSettings::get_global(cx).clone();
agent_settings.tool_permissions.tools.insert(
EditFileTool::NAME.into(),
ToolRules {
default: Some(settings::ToolPermissionMode::Allow),
always_allow: vec![],
always_deny: vec![],
always_confirm: vec![],
invalid_patterns: vec![],
},
);
AgentSettings::override_global(agent_settings, cx);
});
cx
}
fn run_streamed_edit(harness: &mut BenchmarkHarness) -> EditFileToolOutput {
let (mut sender, input): (_, ToolInput<EditFileToolInput>) = ToolInput::test();
for payload in &harness.partial_payloads {
sender.send_partial(payload.clone());
}
sender.send_full(harness.final_payload.clone());
let (event_stream, _event_rx) = ToolCallEventStream::test();
let cx = harness
.cx
.as_ref()
.expect("benchmark harness should have a cx");
let task = cx.update(|cx| {
harness
.edit_tool
.as_ref()
.expect("benchmark harness should have an edit tool")
.clone()
.run(input, event_stream, cx)
});
let executor = harness
.cx
.as_ref()
.expect("benchmark harness should have a cx")
.executor();
block_on_executor(&executor, task).unwrap()
}
fn block_on_executor<R>(executor: &BackgroundExecutor, future: impl Future<Output = R>) -> R {
pin_mut!(future);
let waker = noop_waker();
let mut task_context = Context::from_waker(&waker);
for _ in 0..10_000 {
if let Poll::Ready(output) = future.as_mut().poll(&mut task_context) {
return output;
}
executor.run_until_parked();
}
panic!("future did not complete while running edit_file_tool benchmark");
}
/// Builds the streamed partial payloads for a (possibly multi-edit) session,
/// mirroring how the agent reveals one edit at a time: earlier edits stay
/// complete in the array while the current edit streams its `old_text` then its
/// `new_text` in chunks.
fn streamed_partial_payloads(edits: &[EditOp]) -> Vec<Value> {
let path = FILE_PROJECT_PATH;
let mut payloads = vec![json!({ "path": path }), json!({ "path": path })];
for index in 0..edits.len() {
let completed: Vec<Value> = edits[..index]
.iter()
.map(|edit| json!({ "old_text": edit.old_text, "new_text": edit.new_text }))
.collect();
let edit = &edits[index];
for old_end in chunk_ends(&edit.old_text, OLD_TEXT_CHUNK_SIZE) {
let mut arr = completed.clone();
arr.push(json!({ "old_text": &edit.old_text[..old_end] }));
payloads.push(json!({ "path": path, "edits": arr }));
}
let mut arr = completed.clone();
arr.push(json!({ "old_text": edit.old_text, "new_text": "" }));
payloads.push(json!({ "path": path, "edits": arr }));
for new_end in chunk_ends(&edit.new_text, NEW_TEXT_CHUNK_SIZE) {
let mut arr = completed.clone();
arr.push(json!({ "old_text": edit.old_text, "new_text": &edit.new_text[..new_end] }));
payloads.push(json!({ "path": path, "edits": arr }));
}
}
payloads
}
fn chunk_ends(text: &str, chunk_size: usize) -> impl Iterator<Item = usize> + '_ {
let mut end = 0;
std::iter::from_fn(move || {
if end == text.len() {
return None;
}
end = (end + chunk_size).min(text.len());
while !text.is_char_boundary(end) {
end -= 1;
}
Some(end)
})
}
fn fixtures() -> Vec<EditFixture> {
vec![
make_fixture(
"tiny_function_rewrite",
2,
EditPattern::LocalizedRewrite {
start_line: 12,
line_count: 6,
},
SEED,
),
make_fixture(
"small_function_rewrite",
5,
EditPattern::LocalizedRewrite {
start_line: 22,
line_count: 12,
},
SEED + 1,
),
make_fixture(
"medium_many_small_changes",
8,
EditPattern::ManySmallChanges { every_nth_line: 7 },
SEED + 2,
),
make_fixture(
"medium_insertions",
8,
EditPattern::InsertHelperBlocks { every_nth_line: 9 },
SEED + 3,
),
make_large_multi_edit_fixture("large_multi_edit", 80, 16, SEED + 4),
]
}
enum EditPattern {
LocalizedRewrite {
start_line: usize,
line_count: usize,
},
ManySmallChanges {
every_nth_line: usize,
},
InsertHelperBlocks {
every_nth_line: usize,
},
}
fn make_fixture(
name: &'static str,
function_count: usize,
pattern: EditPattern,
seed: u64,
) -> EditFixture {
let mut rng = StdRng::seed_from_u64(seed);
let old_lines = random_rust_module(&mut rng, function_count);
let edit_range = edit_range(&old_lines, &pattern);
let old_text = old_lines[edit_range.clone()].join("\n");
let mut new_lines = old_lines.clone();
match pattern {
EditPattern::LocalizedRewrite { .. } => {
rewrite_local_block(&mut new_lines[edit_range.clone()], &mut rng)
}
EditPattern::ManySmallChanges { every_nth_line } => {
rewrite_many_small_lines(&mut new_lines[edit_range.clone()], every_nth_line, &mut rng)
}
EditPattern::InsertHelperBlocks { every_nth_line } => {
insert_helper_blocks(&mut new_lines, edit_range.clone(), every_nth_line, &mut rng)
}
}
let new_text_end = edit_range.end + new_lines.len().saturating_sub(old_lines.len());
let old_file_text = old_lines.join("\n");
let expected_file_text = new_lines.join("\n");
let new_text = new_lines[edit_range.start..new_text_end].join("\n");
EditFixture {
name,
old_file_text,
expected_file_text,
edits: vec![EditOp { old_text, new_text }],
}
}
fn make_large_multi_edit_fixture(
name: &'static str,
function_count: usize,
edit_count: usize,
seed: u64,
) -> EditFixture {
const HEADER_LINES: usize = 10;
const FUNCTION_LINES: usize = 12;
const FUNCTION_BODY_LINES: usize = 11;
let mut rng = StdRng::seed_from_u64(seed);
let old_lines = random_rust_module(&mut rng, function_count);
let old_file_text = old_lines.join("\n");
let step = (function_count / edit_count).max(1);
let mut picks: Vec<usize> = (0..edit_count)
.map(|k| (k * step).min(function_count - 1))
.collect();
picks.dedup();
let replacements: Vec<(usize, Vec<String>)> = picks
.iter()
.map(|&function_index| {
(
function_index,
large_function_lines(&mut rng, function_index),
)
})
.collect();
let edits = replacements
.iter()
.map(|(function_index, new_function)| {
let start = HEADER_LINES + function_index * FUNCTION_LINES;
let end = start + FUNCTION_BODY_LINES;
EditOp {
old_text: old_lines[start..end].join("\n"),
new_text: new_function.join("\n"),
}
})
.collect();
let mut new_lines = old_lines;
for (function_index, new_function) in replacements.iter().rev() {
let start = HEADER_LINES + function_index * FUNCTION_LINES;
let end = start + FUNCTION_BODY_LINES;
new_lines.splice(start..end, new_function.iter().cloned());
}
let expected_file_text = new_lines.join("\n");
EditFixture {
name,
old_file_text,
expected_file_text,
edits,
}
}
fn large_function_lines(rng: &mut StdRng, index: usize) -> Vec<String> {
let function_name = identifier(rng, index + 40_000);
let argument_name = identifier(rng, index + 41_000);
let mut lines = vec![
format!(
" pub fn {function_name}(&mut self, {argument_name}: usize) -> Result<usize> {{"
),
format!(" let mut accumulator = {argument_name};"),
];
let body_lines = rng.random_range(30..42);
for body_index in 0..body_lines {
let local_name = identifier(rng, index + 50_000 + body_index);
let multiplier = rng.random_range(2..19);
let offset = rng.random_range(1..256);
match body_index % 4 {
0 => lines.push(format!(
" let {local_name} = accumulator.saturating_mul({multiplier}).saturating_add({offset});"
)),
1 => lines.push(format!(
" accumulator = {local_name}.saturating_sub(self.version % {offset}.max(1));"
)),
2 => lines.push(format!(
" if {local_name} % {multiplier} == 0 {{ accumulator = accumulator.saturating_add({local_name}); }}"
)),
_ => lines.push(format!(
" self.buffers.insert(\"{local_name}\".to_string(), accumulator);"
)),
}
}
lines.push(" self.version = self.version.saturating_add(accumulator);".to_string());
lines.push(" Ok(accumulator)".to_string());
lines.push(" }".to_string());
lines
}
fn edit_range(lines: &[String], pattern: &EditPattern) -> std::ops::Range<usize> {
let mut range = match pattern {
EditPattern::LocalizedRewrite {
start_line,
line_count,
} => *start_line..(*start_line + *line_count).min(lines.len()),
EditPattern::ManySmallChanges { .. } | EditPattern::InsertHelperBlocks { .. } => {
10..lines.len().saturating_sub(5)
}
};
while range.end > range.start && lines[range.end - 1].is_empty() {
range.end -= 1;
}
range
}
fn random_rust_module(rng: &mut StdRng, function_count: usize) -> Vec<String> {
let mut lines = vec![
"use anyhow::{Context as _, Result};".to_string(),
"use collections::HashMap;".to_string(),
"".to_string(),
"#[derive(Clone, Debug)]".to_string(),
"pub struct WorkspaceSnapshot {".to_string(),
" buffers: HashMap<String, usize>,".to_string(),
" version: usize,".to_string(),
"}".to_string(),
"".to_string(),
"impl WorkspaceSnapshot {".to_string(),
];
for function_index in 0..function_count {
let function_name = identifier(rng, function_index);
let argument_name = identifier(rng, function_index + 1_000);
let local_name = identifier(rng, function_index + 2_000);
let branch_name = identifier(rng, function_index + 3_000);
let multiplier = rng.random_range(2..17);
let offset = rng.random_range(1..128);
lines.extend([
format!(
" pub fn {function_name}(&mut self, {argument_name}: usize) -> Result<usize> {{"
),
format!(" let mut {local_name} = {argument_name}.saturating_mul({multiplier});"),
format!(" if {local_name} % 2 == 0 {{"),
format!(
" {local_name} = {local_name}.saturating_add(self.version + {offset});"
),
" } else {".to_string(),
format!(" {local_name} = {local_name}.saturating_sub({offset});"),
" }".to_string(),
format!(" let {branch_name} = self.buffers.len().saturating_add({local_name});"),
format!(" self.version = self.version.saturating_add({branch_name});"),
format!(" Ok({branch_name})"),
" }".to_string(),
"".to_string(),
]);
}
lines.push("}".to_string());
lines.push("".to_string());
lines.push("pub fn normalize_path(path: &str) -> String {".to_string());
lines.push(" path.replace('\\\\', \"/\")".to_string());
lines.push("}".to_string());
lines
}
fn rewrite_local_block(lines: &mut [String], rng: &mut StdRng) {
for (line_index, line) in lines.iter_mut().enumerate() {
let suffix = identifier(rng, line_index + 10_000);
if line.contains("saturating_add") {
*line = format!(
" let {suffix} = self.version.checked_add({line_index}).context(\"version overflow\")?;"
);
} else if line.contains("saturating_sub") {
*line = format!(
" {suffix}.saturating_sub({});",
rng.random_range(8..256)
);
} else if line.trim().is_empty() {
*line =
format!(" tracing::trace!(target: \"agent_bench\", value = {line_index});");
} else {
*line = format!("{line} // updated {suffix}");
}
}
}
fn rewrite_many_small_lines(lines: &mut [String], every_nth_line: usize, rng: &mut StdRng) {
for (line_index, line) in lines.iter_mut().enumerate() {
if line_index.is_multiple_of(every_nth_line) || line.trim().is_empty() {
continue;
}
let suffix = identifier(rng, line_index + 20_000);
*line = format!("{line} // audited {suffix}");
}
}
fn insert_helper_blocks(
lines: &mut Vec<String>,
range: std::ops::Range<usize>,
every_nth_line: usize,
rng: &mut StdRng,
) {
let mut line_index = range.start;
while line_index < range.end.min(lines.len()) {
if line_index.is_multiple_of(every_nth_line) && !lines[line_index].trim().is_empty() {
let suffix = identifier(rng, line_index + 30_000);
lines.splice(
line_index..line_index,
[
format!(" let {suffix}_before = self.version;"),
format!(" tracing::debug!(version = {suffix}_before);"),
],
);
line_index += 2;
}
line_index += 1;
}
}
fn identifier(rng: &mut StdRng, salt: usize) -> String {
const PARTS: &[&str] = &[
"alpha", "beta", "gamma", "delta", "epsilon", "zeta", "theta", "lambda", "sigma", "omega",
];
format!(
"{}_{}_{}",
PARTS[rng.random_range(0..PARTS.len())],
salt,
rng.random_range(0..10_000)
)
}
criterion_group!(benches, edit_file_tool_streaming);
criterion_main!(benches);

File diff suppressed because it is too large Load diff

View file

@ -16,7 +16,7 @@ use sqlez::{
connection::Connection,
statement::Statement,
};
use std::sync::Arc;
use std::{io::ErrorKind, path::PathBuf, sync::Arc};
use ui::{App, SharedString};
use util::path_list::PathList;
use zed_env_vars::ZED_STATELESS;
@ -53,7 +53,7 @@ impl From<&DbThreadMetadata> for acp_thread::AgentSessionInfo {
#[derive(Debug, Serialize, Deserialize)]
pub struct DbThread {
pub title: SharedString,
pub messages: Vec<DbMessage>,
pub messages: Vec<Arc<DbMessage>>,
pub updated_at: DateTime<Utc>,
#[serde(default)]
pub detailed_summary: Option<SharedString>,
@ -81,6 +81,8 @@ pub struct DbThread {
pub draft_prompt: Option<Vec<acp::ContentBlock>>,
#[serde(default)]
pub ui_scroll_position: Option<SerializedScrollPosition>,
#[serde(default)]
pub sandboxed_terminal_temp_dir: Option<PathBuf>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
@ -92,7 +94,7 @@ pub struct SerializedScrollPosition {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SharedThread {
pub title: SharedString,
pub messages: Vec<DbMessage>,
pub messages: Vec<Arc<DbMessage>>,
pub updated_at: DateTime<Utc>,
#[serde(default)]
pub model: Option<DbLanguageModel>,
@ -130,6 +132,7 @@ impl SharedThread {
thinking_effort: None,
draft_prompt: None,
ui_scroll_position: None,
sandboxed_terminal_temp_dir: None,
}
}
@ -206,7 +209,7 @@ impl DbThread {
crate::Message::User(UserMessage {
// MessageId from old format can't be meaningfully converted, so generate a new one
id,
content,
content: Arc::from(content),
})
}
language_model::Role::Assistant => {
@ -285,7 +288,7 @@ impl DbThread {
}
};
messages.push(message);
messages.push(Arc::new(message));
}
Ok(Self {
@ -309,6 +312,7 @@ impl DbThread {
thinking_effort: None,
draft_prompt: None,
ui_scroll_position: None,
sandboxed_terminal_temp_dir: None,
})
}
}
@ -569,15 +573,7 @@ impl ThreadsDatabase {
let rows = select(id.0)?;
if let Some((data_type, data)) = rows.into_iter().next() {
let json_data = match data_type {
DataType::Zstd => {
let decompressed = zstd::decode_all(&data[..])?;
String::from_utf8(decompressed)?
}
DataType::Json => String::from_utf8(data)?,
};
let thread = DbThread::from_json(json_data.as_bytes())?;
Ok(Some(thread))
Ok(Some(Self::deserialize_thread(data_type, data)?))
} else {
Ok(None)
}
@ -596,17 +592,71 @@ impl ThreadsDatabase {
.spawn(async move { Self::save_thread_sync(&connection, id, thread, &folder_paths) })
}
fn deserialize_thread(data_type: DataType, data: Vec<u8>) -> Result<DbThread> {
let json_data = match data_type {
DataType::Zstd => {
let decompressed = zstd::decode_all(&data[..])?;
String::from_utf8(decompressed)?
}
DataType::Json => String::from_utf8(data)?,
};
DbThread::from_json(json_data.as_bytes())
}
fn sandboxed_terminal_temp_dir(data_type: DataType, data: Vec<u8>) -> Option<PathBuf> {
match Self::deserialize_thread(data_type, data) {
Ok(thread) => thread.sandboxed_terminal_temp_dir,
Err(error) => {
log::warn!("failed to deserialize thread before deleting it: {error:#}");
None
}
}
}
fn remove_sandboxed_terminal_temp_dir(temp_dir: PathBuf) {
match std::fs::remove_dir_all(&temp_dir) {
Ok(()) => {}
Err(error) if error.kind() == ErrorKind::NotFound => {}
Err(error) => {
log::warn!(
"failed to remove sandboxed terminal temp directory {}: {error}",
temp_dir.display()
);
}
}
}
pub fn delete_thread(&self, id: acp::SessionId) -> Task<Result<()>> {
let connection = self.connection.clone();
self.executor.spawn(async move {
let connection = connection.lock();
let sandboxed_terminal_temp_dir = {
let connection = connection.lock();
let mut delete = connection.exec_bound::<Arc<str>>(indoc! {"
DELETE FROM threads WHERE id = ?
"})?;
let mut select =
connection.select_bound::<Arc<str>, (DataType, Vec<u8>)>(indoc! {"
SELECT data_type, data FROM threads WHERE id = ? LIMIT 1
"})?;
delete(id.0)?;
let sandboxed_terminal_temp_dir = select(id.0.clone())?
.into_iter()
.next()
.and_then(|(data_type, data)| {
Self::sandboxed_terminal_temp_dir(data_type, data)
});
let mut delete = connection.exec_bound::<Arc<str>>(indoc! {"
DELETE FROM threads WHERE id = ?
"})?;
delete(id.0)?;
sandboxed_terminal_temp_dir
};
if let Some(temp_dir) = sandboxed_terminal_temp_dir {
Self::remove_sandboxed_terminal_temp_dir(temp_dir);
}
Ok(())
})
@ -616,13 +666,32 @@ impl ThreadsDatabase {
let connection = self.connection.clone();
self.executor.spawn(async move {
let connection = connection.lock();
let sandboxed_terminal_temp_dirs = {
let connection = connection.lock();
let mut delete = connection.exec_bound::<()>(indoc! {"
DELETE FROM threads
"})?;
let mut select = connection.select_bound::<(), (DataType, Vec<u8>)>(indoc! {"
SELECT data_type, data FROM threads
"})?;
delete(())?;
let sandboxed_terminal_temp_dirs = select(())?
.into_iter()
.filter_map(|(data_type, data)| {
Self::sandboxed_terminal_temp_dir(data_type, data)
})
.collect::<Vec<_>>();
let mut delete = connection.exec_bound::<()>(indoc! {"
DELETE FROM threads
"})?;
delete(())?;
sandboxed_terminal_temp_dirs
};
for temp_dir in sandboxed_terminal_temp_dirs {
Self::remove_sandboxed_terminal_temp_dir(temp_dir);
}
Ok(())
})
@ -694,6 +763,7 @@ mod tests {
thinking_effort: None,
draft_prompt: None,
ui_scroll_position: None,
sandboxed_terminal_temp_dir: None,
}
}
@ -797,6 +867,78 @@ mod tests {
);
}
#[test]
fn test_sandboxed_terminal_temp_dir_defaults_to_none() {
let json = r#"{
"title": "Old Thread",
"messages": [],
"updated_at": "2024-01-01T00:00:00Z"
}"#;
let db_thread: DbThread = serde_json::from_str(json).expect("Failed to deserialize");
assert!(
db_thread.sandboxed_terminal_temp_dir.is_none(),
"Legacy threads without sandboxed_terminal_temp_dir should default to None"
);
}
#[gpui::test]
async fn test_sandboxed_terminal_temp_dir_roundtrips_through_save_load(
cx: &mut TestAppContext,
) {
let database = ThreadsDatabase::new(cx.executor()).unwrap();
let thread_id = session_id("sandbox-temp-dir-thread");
let temp_dir = tempfile::Builder::new()
.prefix("zed-agent-terminal-test-")
.tempdir()
.unwrap()
.keep();
let mut thread = make_thread(
"Sandbox Temp Dir Thread",
Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(),
);
thread.sandboxed_terminal_temp_dir = Some(temp_dir.clone());
database
.save_thread(thread_id.clone(), thread, PathList::default())
.await
.unwrap();
let loaded = database
.load_thread(thread_id)
.await
.unwrap()
.expect("thread should exist");
assert_eq!(loaded.sandboxed_terminal_temp_dir, Some(temp_dir.clone()));
std::fs::remove_dir_all(temp_dir).unwrap();
}
#[gpui::test]
async fn test_delete_thread_removes_sandboxed_terminal_temp_dir(cx: &mut TestAppContext) {
let database = ThreadsDatabase::new(cx.executor()).unwrap();
let thread_id = session_id("sandbox-temp-dir-delete-thread");
let temp_dir = tempfile::Builder::new()
.prefix("zed-agent-terminal-test-")
.tempdir()
.unwrap()
.keep();
std::fs::write(temp_dir.join("sentinel"), b"content").unwrap();
let mut thread = make_thread(
"Sandbox Temp Dir Delete Thread",
Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(),
);
thread.sandboxed_terminal_temp_dir = Some(temp_dir.clone());
database
.save_thread(thread_id.clone(), thread, PathList::default())
.await
.unwrap();
database.delete_thread(thread_id).await.unwrap();
assert!(!temp_dir.exists());
}
#[gpui::test]
async fn test_subagent_context_roundtrips_through_save_load(cx: &mut TestAppContext) {
let database = ThreadsDatabase::new(cx.executor()).unwrap();

View file

@ -9,9 +9,7 @@ use fs::Fs;
use gpui::{App, Entity, Task};
use language_model::{LanguageModelId, LanguageModelProviderId, LanguageModelRegistry};
use project::{AgentId, Project};
use prompt_store::PromptStore;
use settings::{LanguageModelSelection, Settings as _, update_settings_file};
use util::ResultExt as _;
use crate::{NativeAgent, NativeAgentConnection, ThreadStore, templates::Templates};
@ -45,15 +43,12 @@ impl AgentServer for NativeAgentServer {
log::debug!("NativeAgentServer::connect");
let fs = self.fs.clone();
let thread_store = self.thread_store.clone();
let prompt_store = PromptStore::global(cx);
cx.spawn(async move |cx| {
log::debug!("Creating templates for native agent");
let templates = Templates::new();
let prompt_store = prompt_store.await.log_err();
log::debug!("Creating native agent entity");
let agent =
cx.update(|cx| NativeAgent::new(thread_store, templates, prompt_store, fs, cx));
let agent = cx.update(|cx| NativeAgent::new(thread_store, templates, fs, cx));
// Create the connection wrapper
let connection = NativeAgentConnection(agent);

View file

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

View file

@ -0,0 +1,25 @@
//! Agent-side glue for the [`sandbox`] crate.
//!
//! Centralizes the "should agent-run terminal commands be sandboxed for this
//! process?" check so the system prompt, the terminal tool, and any other
//! caller see the same answer (and so the `target_os` gate lives in one
//! place instead of scattered across the agent crate).
//!
//! The current policy is: enabled iff we're on macOS *and* the user has the
//! `sandboxing` feature flag turned on. There's deliberately no settings or
//! env-var override yet — the flag is the only switch.
//!
//! On non-macOS hosts we don't have a sandbox integration today, so this
//! returns `false` regardless of the flag.
//!
//! Naming note: this module is about agent terminal sandboxing specifically.
//! Other agent operations (e.g. file edits) are gated separately.
use feature_flags::{FeatureFlagAppExt as _, SandboxingFeatureFlag};
use gpui::App;
/// Whether agent-run terminal commands should be wrapped in an OS-level
/// sandbox for this process. See module docs for the policy.
pub(crate) fn sandboxing_enabled(cx: &App) -> bool {
cfg!(target_os = "macos") && cx.has_flag::<SandboxingFeatureFlag>()
}

View file

@ -43,6 +43,12 @@ pub struct SystemPromptTemplate<'a> {
/// Contents of the user-global `~/.config/zed/AGENTS.md` file (or the
/// platform equivalent), if present and non-empty.
pub user_agents_md: Option<SharedString>,
/// Whether agent-run terminal commands are wrapped in an OS-level
/// sandbox for this conversation. When `true`, the rendered prompt
/// describes the sandbox's read/write/network rules and the
/// per-command flags the model can request to relax them. When
/// `false`, the prompt omits the sandbox section entirely.
pub sandboxing: bool,
}
impl Template for SystemPromptTemplate<'_> {
@ -83,10 +89,11 @@ mod tests {
let project = prompt_store::ProjectContext::default();
let template = SystemPromptTemplate {
project: &project,
available_tools: vec!["echo".into(), "update_plan".into()],
available_tools: vec!["echo".into(), "update_plan".into(), "update_title".into()],
model_name: Some("test-model".to_string()),
date: "2026-01-01".to_string(),
user_agents_md: None,
sandboxing: false,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
@ -94,6 +101,7 @@ mod tests {
assert!(rendered.contains("Today's Date: 2026-01-01"));
assert!(rendered.contains("## Fixing Diagnostics"));
assert!(rendered.contains("## Planning"));
assert!(rendered.contains("## Session Title"));
assert!(rendered.contains("test-model"));
}
@ -111,13 +119,14 @@ mod tests {
project_entry_id: 1,
}),
}];
let project = ProjectContext::new(worktrees, Vec::new());
let project = ProjectContext::new(worktrees);
let template = SystemPromptTemplate {
project: &project,
available_tools: vec!["echo".into()],
model_name: Some("test-model".to_string()),
date: "2026-01-01".to_string(),
user_agents_md: Some("always be concise".into()),
sandboxing: false,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
@ -135,6 +144,78 @@ mod tests {
);
}
#[test]
fn test_system_prompt_omits_sandbox_section_when_sandboxing_disabled() {
let project = prompt_store::ProjectContext::default();
let template = SystemPromptTemplate {
project: &project,
available_tools: vec!["echo".into()],
model_name: Some("test-model".to_string()),
date: "2026-01-01".to_string(),
user_agents_md: None,
sandboxing: false,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
assert!(!rendered.contains("## Terminal sandbox"));
assert!(!rendered.contains("allow_network"));
}
#[test]
fn test_system_prompt_renders_sandbox_section_with_worktrees_when_enabled() {
use prompt_store::{ProjectContext, WorktreeContext};
let worktrees = vec![
WorktreeContext {
root_name: "alpha".to_string(),
abs_path: std::path::Path::new("/tmp/alpha").into(),
rules_file: None,
},
WorktreeContext {
root_name: "beta".to_string(),
abs_path: std::path::Path::new("/tmp/beta").into(),
rules_file: None,
},
];
let project = ProjectContext::new(worktrees);
let template = SystemPromptTemplate {
project: &project,
available_tools: vec!["echo".into()],
model_name: Some("test-model".to_string()),
date: "2026-01-01".to_string(),
user_agents_md: None,
sandboxing: true,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
assert!(rendered.contains("## Terminal sandbox"));
assert!(rendered.contains("`/tmp/alpha`"));
assert!(rendered.contains("`/tmp/beta`"));
assert!(rendered.contains("allow_network: true"));
assert!(rendered.contains("allow_fs_write: true"));
assert!(rendered.contains("unsandboxed: true"));
assert!(rendered.contains("remain in effect for the entire duration"));
}
#[test]
fn test_system_prompt_sandbox_section_handles_zero_worktrees() {
let project = prompt_store::ProjectContext::default();
let template = SystemPromptTemplate {
project: &project,
available_tools: vec!["echo".into()],
model_name: Some("test-model".to_string()),
date: "2026-01-01".to_string(),
user_agents_md: None,
sandboxing: true,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
assert!(rendered.contains("## Terminal sandbox"));
assert!(rendered.contains("No project directories are currently writable"));
}
#[test]
fn test_system_prompt_omits_user_agents_md_section_when_absent() {
let project = prompt_store::ProjectContext::default();
@ -144,9 +225,28 @@ mod tests {
model_name: Some("test-model".to_string()),
date: "2026-01-01".to_string(),
user_agents_md: None,
sandboxing: false,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
assert!(!rendered.contains("### Personal `AGENTS.md`"));
}
#[test]
fn test_system_prompt_does_not_render_legacy_zed_rules_section() {
let project = prompt_store::ProjectContext::default();
let template = SystemPromptTemplate {
project: &project,
available_tools: vec!["echo".into()],
model_name: Some("test-model".to_string()),
date: "2026-01-01".to_string(),
user_agents_md: None,
sandboxing: false,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
assert!(!rendered.contains("The user has specified the following rules"));
assert!(!rendered.contains("Rules title:"));
}
}

View file

@ -52,6 +52,17 @@ Use a plan when:
- The user asked you to do more than one thing in a single prompt.
- You discover additional steps while working and intend to complete them before yielding to the user.
{{/if}}
{{#if (contains available_tools 'update_title') }}
## Session Title
- Use the `update_title` tool to set the title shown to the user for the current session.
- You MUST set a title at least once, even for small tasks. Do it early in the conversation, after the first user message, before you start working. There is no title to begin with, so you are responsible for setting one.
- Update the title again whenever the goal changes materially.
- Titles are very important to communicate to the user what you are working on. A session should always have a title.
- Keep titles concise and specific. Prefer a short noun phrase over a full sentence, and do not wrap the title in quotes.
- Do not mention that you changed the title unless it is directly relevant to the user.
{{/if}}
## Searching and Reading
@ -162,12 +173,11 @@ The current project contains the following root directories:
You are powered by the model named {{model_name}}.
{{/if}}
{{#if (or has_rules has_user_rules)}}
{{#if has_rules}}
## User's Custom Instructions
The following additional instructions are provided by the user and should be followed to the best of your ability{{#if (gt (len available_tools) 0)}} without interfering with the tool use guidelines{{/if}}.
{{#if has_rules}}
There are project rules that apply to these root directories:
{{#each worktrees}}
{{#if rules_file}}
@ -178,17 +188,3 @@ There are project rules that apply to these root directories:
{{/if}}
{{/each}}
{{/if}}
{{#if has_user_rules}}
The user has specified the following rules that should be applied:
{{#each user_rules}}
{{#if title}}
Rules title: {{title}}
{{/if}}
``````
{{contents}}
``````
{{/each}}
{{/if}}
{{/if}}

View file

@ -23,15 +23,13 @@ graph TD
A[Start] --> B[End]
```
The renderer supports the following diagram types: flowchart, sequence, class, state, ER, gantt, pie, gitgraph, mindmap, timeline, quadrant chart, xy chart, and journey. Other diagram types will only show as code.
Mermaid diagrams are automatically themed to match the user's editor theme. Do not include `%%{init}%%` directives or define your own `classDef` styles.
Do *NOT* include inline HTML elements in mermaid diagrams, as they cannot be rendered. It is better to simply skip formatting (e.g. bold/italic/etc.).
When you need accent colors for emphasis (e.g. color-coding layers, categories, or states), use the pre-defined classes `accent0` through `accent7` with the `:::` syntax:
A:::accent0 --> B:::accent1 --> C:::accent2
These classes automatically match the user's theme. Do not hardcode hex color values unless an exact color match is specifically required. Note that the rendered view may be narrow, so try to prioritize generating taller diagrams over wider ones.
Mermaid diagrams are automatically color-coded using the user's theme accent palette. Do not hardcode hex color values unless an exact color match is specifically required. Note that the rendered view may be narrow, so try to prioritize generating taller diagrams over wider ones.
{{#if (gt (len available_tools) 0)}}
## Tool Use
@ -74,6 +72,17 @@ Use a plan when:
- The user asked you to do more than one thing in a single prompt.
- You discover additional steps while working and intend to complete them before yielding to the user.
{{/if}}
{{#if (contains available_tools 'update_title') }}
## Session Title
- Use the `update_title` tool to set the title shown to the user for the current session.
- You MUST set a title at least once, even for small tasks. Do it early in the conversation, after the first user message, before you start working. There is no title to begin with, so you are responsible for setting one.
- Update the title again whenever the goal changes materially.
- Titles are very important to communicate to the user what you are working on. A session should always have a title.
- Keep titles concise and specific. Prefer a short noun phrase over a full sentence, and do not wrap the title in quotes.
- Do not mention that you changed the title unless it is directly relevant to the user.
{{/if}}
## Searching and Reading
@ -178,6 +187,24 @@ The current project contains the following root directories:
- `{{abs_path}}`
{{/each}}
{{#if sandboxing}}
## Terminal sandbox
The `terminal` tool runs commands inside a sandbox with these permissions:
- Reads: any path on the filesystem is readable.
- Writes: a per-thread temporary directory exposed via `$TMPDIR`, `$TMP`, and `$TEMP` is writable and persists across `terminal` calls in this conversation{{#if worktrees}}, along with these project directories:
{{#each worktrees}}
- `{{abs_path}}`
{{/each}}
Writes anywhere else on the filesystem are blocked.{{else}}. No project directories are currently writable.{{/if}}
- Network: outbound network access is blocked.
You can request elevated permissions on individual `terminal` calls by setting `allow_network: true`, `allow_fs_write: true`, or `unsandboxed: true`. The user will be prompted to approve before the command runs.
These sandbox settings are guaranteed to remain in effect for the entire duration of this conversation. If they ever change, you will be told.
{{/if}}
{{#if model_name}}
## Model Information
@ -212,7 +239,7 @@ To use a Skill:
4. If the Skill references additional files, use `read_file` to access them. Paths inside a Skill resolve relative to that Skill's directory (the parent of its `SKILL.md`).
{{/if}}
{{#if (or user_agents_md has_rules has_user_rules)}}
{{#if (or user_agents_md has_rules)}}
## User's Custom Instructions
The following additional instructions are provided by the user and should be followed to the best of your ability{{#if (gt (len available_tools) 0)}} without interfering with the tool use guidelines{{/if}}.
@ -243,16 +270,4 @@ There are project rules that apply to these root directories:
{{/each}}
{{/if}}
{{#if has_user_rules}}
The user has specified the following rules that should be applied:
{{#each user_rules}}
{{#if title}}
Rules title: {{title}}
{{/if}}
``````
{{contents}}
``````
{{/each}}
{{/if}}
{{/if}}

View file

@ -26,10 +26,10 @@ use gpui::{
use indoc::indoc;
use language_model::{
CompletionIntent, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
LanguageModelId, LanguageModelProviderId, LanguageModelProviderName, LanguageModelRegistry,
LanguageModelRequest, LanguageModelRequestMessage, LanguageModelToolResult,
LanguageModelToolSchemaFormat, LanguageModelToolUse, MessageContent, Role, StopReason,
TokenUsage,
LanguageModelId, LanguageModelImageExt, LanguageModelProviderId, LanguageModelProviderName,
LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
LanguageModelToolResult, LanguageModelToolSchemaFormat, LanguageModelToolUse, MessageContent,
Role, StopReason, TokenUsage,
fake_provider::{FakeLanguageModel, FakeLanguageModelProvider},
};
use pretty_assertions::assert_eq;
@ -200,8 +200,10 @@ impl crate::ThreadEnvironment for FakeThreadEnvironment {
fn create_terminal(
&self,
_command: String,
_extra_env: Vec<acp::EnvVariable>,
_cwd: Option<std::path::PathBuf>,
_output_byte_limit: Option<u64>,
_sandbox_wrap: Option<acp_thread::SandboxWrap>,
_cx: &mut AsyncApp,
) -> Task<Result<Rc<dyn crate::TerminalHandle>>> {
self.terminal_creations.fetch_add(1, Ordering::SeqCst);
@ -242,8 +244,10 @@ impl crate::ThreadEnvironment for MultiTerminalEnvironment {
fn create_terminal(
&self,
_command: String,
_extra_env: Vec<acp::EnvVariable>,
_cwd: Option<std::path::PathBuf>,
_output_byte_limit: Option<u64>,
_sandbox_wrap: Option<acp_thread::SandboxWrap>,
cx: &mut AsyncApp,
) -> Task<Result<Rc<dyn crate::TerminalHandle>>> {
let handle = Rc::new(cx.update(|cx| FakeTerminalHandle::new_never_exits(cx)));
@ -320,6 +324,7 @@ async fn test_terminal_tool_timeout_kills_handle(cx: &mut TestAppContext) {
command: "sleep 1000".to_string(),
cd: ".".to_string(),
timeout_ms: Some(5),
..Default::default()
}),
event_stream,
cx,
@ -387,6 +392,7 @@ async fn test_terminal_tool_without_timeout_does_not_kill_handle(cx: &mut TestAp
command: "sleep 1000".to_string(),
cd: ".".to_string(),
timeout_ms: None,
..Default::default()
}),
event_stream,
cx,
@ -1656,6 +1662,7 @@ async fn test_mcp_tool_multi_content_response(cx: &mut TestAppContext) {
let (tool_call_params, tool_call_response) = mcp_tool_calls.next().await.unwrap();
assert_eq!(tool_call_params.name, "screenshot");
let image_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
tool_call_response
.send(context_server::types::CallToolResponse {
content: vec![
@ -1663,7 +1670,7 @@ async fn test_mcp_tool_multi_content_response(cx: &mut TestAppContext) {
text: "Some text".into(),
},
context_server::types::ToolResponseContent::Image {
data: "aGVsbG8=".into(),
data: image_data.into(),
mime_type: "image/png".into(),
},
context_server::types::ToolResponseContent::Text {
@ -1691,13 +1698,25 @@ async fn test_mcp_tool_multi_content_response(cx: &mut TestAppContext) {
})
.expect("expected a tool result");
assert_eq!(tool_result.tool_use_id, "tool_1".into());
assert_eq!(tool_result.content.len(), 2);
assert_eq!(tool_result.content.len(), 3);
assert_eq!(
tool_result.content[0],
language_model::LanguageModelToolResultContent::Text(Arc::from("Some text"))
);
let expected_image =
language_model::LanguageModelImage::from_base64_image(image_data, "image/png")
.expect("image conversion should not error")
.expect("image conversion should succeed");
assert_eq!(
tool_result.content[0],
language_model::LanguageModelToolResultContent::Text(Arc::from("Some text"))
);
assert_eq!(
tool_result.content[1],
language_model::LanguageModelToolResultContent::Image(expected_image)
);
assert_eq!(
tool_result.content[2],
language_model::LanguageModelToolResultContent::Text(Arc::from("Some more text"))
);
fake_model.end_last_completion_stream();
@ -3507,8 +3526,8 @@ async fn test_agent_connection(cx: &mut TestAppContext) {
let thread_store = cx.new(|cx| ThreadStore::new(cx));
// Create agent and connection
let agent = cx
.update(|cx| NativeAgent::new(thread_store, templates.clone(), None, fake_fs.clone(), cx));
let agent =
cx.update(|cx| NativeAgent::new(thread_store, templates.clone(), fake_fs.clone(), cx));
let connection = NativeAgentConnection(agent.clone());
// Create a thread using new_thread
@ -3794,6 +3813,155 @@ async fn test_update_plan_tool_updates_thread_events(cx: &mut TestAppContext) {
);
}
#[gpui::test]
async fn test_update_title_tool_sets_thread_title(cx: &mut TestAppContext) {
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
let fake_model = model.as_fake();
let summary_model = Arc::new(FakeLanguageModel::default());
cx.update(|cx| {
cx.update_flags(true, vec!["update-title-tool".to_string()]);
});
thread.update(cx, |thread, cx| {
thread.add_tool(UpdateTitleTool::new(cx.weak_entity()));
thread.set_summarization_model(Some(summary_model.clone()), cx);
});
let mut events = thread
.update(cx, |thread, cx| {
thread.send(UserMessageId::new(), ["Explore title tooling"], cx)
})
.unwrap();
cx.run_until_parked();
let input = json!({
"title": "Session title tool"
});
fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
LanguageModelToolUse {
id: "title_1".into(),
name: UpdateTitleTool::NAME.into(),
raw_input: input.to_string(),
input,
is_input_complete: true,
thought_signature: None,
},
));
fake_model.end_last_completion_stream();
cx.run_until_parked();
let tool_call = expect_tool_call(&mut events).await;
assert_eq!(
tool_call,
acp::ToolCall::new("title_1", "Update title: Session title tool")
.kind(acp::ToolKind::Think)
.raw_input(json!({
"title": "Session title tool"
}))
.meta(acp::Meta::from_iter([(
"tool_name".into(),
"update_title".into()
)]))
);
let update = expect_tool_call_update_fields(&mut events).await;
assert_eq!(
update,
acp::ToolCallUpdate::new(
"title_1",
acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress)
)
);
let update = expect_tool_call_update_fields(&mut events).await;
assert_eq!(
update,
acp::ToolCallUpdate::new(
"title_1",
acp::ToolCallUpdateFields::new()
.status(acp::ToolCallStatus::Completed)
.raw_output("Session title updated")
)
);
thread.read_with(cx, |thread, _| {
assert_eq!(thread.title(), Some("Session title tool".into()));
});
assert_eq!(summary_model.pending_completions(), Vec::new());
}
#[gpui::test]
async fn test_update_title_availability_suppresses_summary_title_generation(
cx: &mut TestAppContext,
) {
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
let fake_model = model.as_fake();
let summary_model = Arc::new(FakeLanguageModel::default());
cx.update(|cx| {
cx.update_flags(true, vec!["update-title-tool".to_string()]);
});
thread.update(cx, |thread, cx| {
thread.add_tool(UpdateTitleTool::new(cx.weak_entity()));
thread.set_summarization_model(Some(summary_model.clone()), cx);
});
let send = thread
.update(cx, |thread, cx| {
thread.send(UserMessageId::new(), ["Explore title tooling"], cx)
})
.unwrap();
cx.run_until_parked();
fake_model.send_last_completion_stream_text_chunk("Done");
fake_model.end_last_completion_stream();
send.collect::<Vec<_>>().await;
cx.run_until_parked();
thread.read_with(cx, |thread, _| {
assert_eq!(thread.title(), None);
});
assert_eq!(summary_model.pending_completions(), Vec::new());
}
#[gpui::test]
async fn test_update_title_flag_without_available_tool_falls_back_to_summary_title_generation(
cx: &mut TestAppContext,
) {
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
let fake_model = model.as_fake();
let summary_model = Arc::new(FakeLanguageModel::default());
cx.update(|cx| {
cx.update_flags(true, vec!["update-title-tool".to_string()]);
});
thread.update(cx, |thread, cx| {
thread.set_summarization_model(Some(summary_model.clone()), cx);
});
let send = thread
.update(cx, |thread, cx| {
thread.send(UserMessageId::new(), ["Explore title tooling"], cx)
})
.unwrap();
cx.run_until_parked();
fake_model.send_last_completion_stream_text_chunk("Done");
fake_model.end_last_completion_stream();
cx.run_until_parked();
assert_eq!(summary_model.pending_completions().len(), 1);
summary_model.send_last_completion_stream_text_chunk("Fallback title");
summary_model.end_last_completion_stream();
send.collect::<Vec<_>>().await;
cx.run_until_parked();
thread.read_with(cx, |thread, _| {
assert_eq!(thread.title(), Some("Fallback title".into()));
});
}
#[gpui::test]
async fn test_send_no_retry_on_success(cx: &mut TestAppContext) {
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
@ -3971,8 +4139,8 @@ async fn test_send_retry_finishes_tool_calls_on_error(cx: &mut TestAppContext) {
events.collect::<Vec<_>>().await;
thread.read_with(cx, |thread, _cx| {
assert_eq!(
thread.last_received_or_pending_message(),
Some(Message::Agent(AgentMessage {
thread.last_received_or_pending_message().as_deref(),
Some(&Message::Agent(AgentMessage {
content: vec![AgentMessageContent::Text("Done".into())],
tool_results: IndexMap::default(),
reasoning_details: None,
@ -4307,6 +4475,7 @@ async fn setup(cx: &mut TestAppContext, model: TestModel) -> ThreadTest {
StreamingFailingEchoTool::NAME: true,
TerminalTool::NAME: true,
UpdatePlanTool::NAME: true,
UpdateTitleTool::NAME: true,
}
}
}
@ -4389,7 +4558,7 @@ async fn setup(cx: &mut TestAppContext, model: TestModel) -> ThreadTest {
}
#[cfg(test)]
#[ctor::ctor]
#[ctor::ctor(unsafe)]
fn init_logger() {
if std::env::var("RUST_LOG").is_ok() {
env_logger::init();
@ -4729,6 +4898,7 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) {
command: "rm -rf /".to_string(),
cd: ".".to_string(),
timeout_ms: None,
..Default::default()
}),
event_stream,
cx,
@ -4781,6 +4951,7 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) {
command: "echo hello".to_string(),
cd: ".".to_string(),
timeout_ms: None,
..Default::default()
}),
event_stream,
cx,
@ -4839,6 +5010,7 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) {
command: "sudo rm file".to_string(),
cd: ".".to_string(),
timeout_ms: None,
..Default::default()
}),
event_stream,
cx,
@ -4886,6 +5058,7 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) {
command: "echo hello".to_string(),
cd: ".".to_string(),
timeout_ms: None,
..Default::default()
}),
event_stream,
cx,
@ -4928,9 +5101,8 @@ async fn test_subagent_tool_call_end_to_end(cx: &mut TestAppContext) {
.await;
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
let thread_store = cx.new(|cx| ThreadStore::new(cx));
let agent = cx.update(|cx| {
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
});
let agent =
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
let connection = Rc::new(NativeAgentConnection(agent.clone()));
let acp_thread = cx
@ -5063,9 +5235,8 @@ async fn test_subagent_tool_output_does_not_include_thinking(cx: &mut TestAppCon
.await;
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
let thread_store = cx.new(|cx| ThreadStore::new(cx));
let agent = cx.update(|cx| {
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
});
let agent =
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
let connection = Rc::new(NativeAgentConnection(agent.clone()));
let acp_thread = cx
@ -5211,9 +5382,8 @@ async fn test_subagent_tool_call_cancellation_during_task_prompt(cx: &mut TestAp
.await;
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
let thread_store = cx.new(|cx| ThreadStore::new(cx));
let agent = cx.update(|cx| {
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
});
let agent =
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
let connection = Rc::new(NativeAgentConnection(agent.clone()));
let acp_thread = cx
@ -5341,9 +5511,8 @@ async fn test_subagent_tool_resume_session(cx: &mut TestAppContext) {
.await;
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
let thread_store = cx.new(|cx| ThreadStore::new(cx));
let agent = cx.update(|cx| {
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
});
let agent =
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
let connection = Rc::new(NativeAgentConnection(agent.clone()));
let acp_thread = cx
@ -5874,9 +6043,8 @@ async fn test_subagent_context_window_warning(cx: &mut TestAppContext) {
.await;
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
let thread_store = cx.new(|cx| ThreadStore::new(cx));
let agent = cx.update(|cx| {
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
});
let agent =
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
let connection = Rc::new(NativeAgentConnection(agent.clone()));
let acp_thread = cx
@ -6000,9 +6168,8 @@ async fn test_subagent_no_context_window_warning_when_already_at_warning(cx: &mu
.await;
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
let thread_store = cx.new(|cx| ThreadStore::new(cx));
let agent = cx.update(|cx| {
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
});
let agent =
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
let connection = Rc::new(NativeAgentConnection(agent.clone()));
let acp_thread = cx
@ -6174,9 +6341,8 @@ async fn test_subagent_error_propagation(cx: &mut TestAppContext) {
.await;
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
let thread_store = cx.new(|cx| ThreadStore::new(cx));
let agent = cx.update(|cx| {
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
});
let agent =
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
let connection = Rc::new(NativeAgentConnection(agent.clone()));
let acp_thread = cx

View file

@ -4,12 +4,14 @@ use crate::{
FindPathTool, FindReferencesTool, GetCodeActionsTool, GoToDefinitionTool, GrepTool,
ListDirectoryTool, MovePathTool, ProjectSnapshot, ReadFileTool, RenameTool, SpawnAgentTool,
SystemPromptTemplate, Template, Templates, TerminalTool, ToolPermissionDecision,
UpdatePlanTool, UserAgentsMd, WebSearchTool, WriteFileTool, decide_permission_from_settings,
UpdatePlanTool, UpdateTitleTool, WebSearchTool, WriteFileTool, decide_permission_from_settings,
};
use acp_thread::{MentionUri, UserMessageId};
use action_log::ActionLog;
use agent_settings::UserAgentsMd;
use feature_flags::{
FeatureFlagAppExt as _, LspToolFeatureFlag, RenameToolFeatureFlag, UpdatePlanToolFeatureFlag,
UpdateTitleToolFeatureFlag,
};
use agent_client_protocol::schema as acp;
@ -49,16 +51,16 @@ use serde::{Deserialize, Serialize};
use settings::{
LanguageModelSelection, Settings, SettingsStore, ToolPermissionMode, update_settings_file,
};
use std::fmt::Write;
use std::{
collections::BTreeMap,
marker::PhantomData,
ops::RangeInclusive,
path::Path,
path::{Path, PathBuf},
rc::Rc,
sync::Arc,
time::{Duration, Instant},
};
use std::{fmt::Write, path::PathBuf};
use util::{ResultExt, debug_panic, markdown::MarkdownCodeBlock, paths::PathStyle};
use uuid::Uuid;
@ -121,7 +123,7 @@ enum RetryStrategy {
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Message {
User(UserMessage),
Agent(AgentMessage),
@ -174,13 +176,16 @@ impl Message {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserMessage {
pub id: UserMessageId,
pub content: Vec<UserMessageContent>,
pub content: Arc<[UserMessageContent]>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum UserMessageContent {
Text(String),
Mention { uri: MentionUri, content: String },
Mention {
uri: MentionUri,
content: SharedString,
},
Image(LanguageModelImage),
}
@ -188,7 +193,7 @@ impl UserMessage {
pub fn to_markdown(&self) -> String {
let mut markdown = String::new();
for content in &self.content {
for content in &*self.content {
match content {
UserMessageContent::Text(text) => {
markdown.push_str(text);
@ -248,7 +253,7 @@ impl UserMessage {
let mut merge_conflict_context = MERGE_CONFLICT_TAG.to_string();
let mut skills_context = OPEN_SKILLS_TAG.to_string();
for chunk in &self.content {
for chunk in &*self.content {
let chunk = match chunk {
UserMessageContent::Text(text) => {
language_model::MessageContent::Text(text.clone())
@ -264,7 +269,7 @@ impl UserMessage {
"\n{}",
MarkdownCodeBlock {
tag: &codeblock_tag(abs_path, None),
text: &content.to_string(),
text: content,
}
)
.ok();
@ -311,17 +316,6 @@ impl UserMessage {
MentionUri::Thread { .. } => {
write!(&mut thread_context, "\n{}\n", content).ok();
}
MentionUri::Rule { .. } => {
write!(
&mut rules_context,
"\n{}",
MarkdownCodeBlock {
tag: "",
text: content
}
)
.ok();
}
MentionUri::Fetch { url } => {
write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();
}
@ -364,11 +358,7 @@ impl UserMessage {
.ok();
}
MentionUri::Skill { name, source, .. } => {
let label = if source.is_empty() {
format!("{} (global)", name)
} else {
format!("{} ({})", name, source)
};
let label = format!("{} ({})", name, source);
write!(&mut skills_context, "\nSkill: {}\n{}\n", label, content).ok();
}
}
@ -629,9 +619,9 @@ impl AgentMessage {
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentMessage {
pub content: Vec<AgentMessageContent>,
pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
pub reasoning_details: Option<serde_json::Value>,
pub(crate) content: Vec<AgentMessageContent>,
pub(crate) tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
pub(crate) reasoning_details: Option<Arc<serde_json::Value>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@ -667,8 +657,10 @@ pub trait ThreadEnvironment {
fn create_terminal(
&self,
command: String,
extra_env: Vec<acp::EnvVariable>,
cwd: Option<PathBuf>,
output_byte_limit: Option<u64>,
sandbox_wrap: Option<acp_thread::SandboxWrap>,
cx: &mut AsyncApp,
) -> Task<Result<Rc<dyn TerminalHandle>>>;
@ -965,7 +957,7 @@ pub struct Thread {
title_generation_failed: bool,
pending_summary_generation: Option<Shared<Task<Option<SharedString>>>>,
summary: Option<SharedString>,
messages: Vec<Message>,
messages: Vec<Arc<Message>>,
user_store: Entity<UserStore>,
/// Holds the task that handles agent interaction until the end of the turn.
/// Survives across multiple requests as the model performs tool calls and
@ -1004,6 +996,7 @@ pub struct Thread {
/// Weak references to running subagent threads for cancellation propagation
running_subagents: Vec<WeakEntity<Thread>>,
inherits_parent_model_settings: bool,
sandboxed_terminal_temp_dir: Option<PathBuf>,
}
impl Thread {
@ -1130,6 +1123,7 @@ impl Thread {
ui_scroll_position: None,
running_subagents: Vec::new(),
inherits_parent_model_settings: true,
sandboxed_terminal_temp_dir: None,
}
}
@ -1173,6 +1167,30 @@ impl Thread {
&self.id
}
pub(crate) fn sandboxed_terminal_temp_dir(
&mut self,
cx: &mut Context<Self>,
) -> Result<PathBuf> {
if let Some(temp_dir) = &self.sandboxed_terminal_temp_dir {
std::fs::create_dir_all(temp_dir).with_context(|| {
format!(
"failed to recreate sandboxed terminal temp directory {}",
temp_dir.display()
)
})?;
return Ok(temp_dir.clone());
}
let temp_dir = tempfile::Builder::new()
.prefix("zed-agent-terminal-")
.tempdir()
.context("failed to create sandboxed terminal temp directory")?;
let temp_dir = temp_dir.keep();
self.sandboxed_terminal_temp_dir = Some(temp_dir.clone());
cx.notify();
Ok(temp_dir)
}
/// Returns true if this thread was imported from a shared thread.
pub fn is_imported(&self) -> bool {
self.imported
@ -1185,7 +1203,7 @@ impl Thread {
let (tx, rx) = mpsc::unbounded();
let stream = ThreadEventStream(tx);
for message in &self.messages {
match message {
match &**message {
Message::User(user_message) => stream.send_user_message(user_message),
Message::Agent(assistant_message) => {
for content in &assistant_message.content {
@ -1219,10 +1237,10 @@ impl Thread {
stream: &ThreadEventStream,
cx: &mut Context<Self>,
) {
// Extract saved output and status first, so they're available even if tool is not found
let output = tool_result
.as_ref()
.and_then(|result| result.output.clone());
let replay_content = tool_result.and_then(Self::tool_result_content_for_replay);
let status = tool_result
.as_ref()
.map_or(acp::ToolCallStatus::Failed, |result| {
@ -1251,21 +1269,25 @@ impl Thread {
// but still display the saved result if available.
// We need to send both ToolCall and ToolCallUpdate events because the UI
// only converts raw_output to displayable content in update_fields, not from_acp.
let title = Self::title_for_replayed_tool_use(tool_use);
stream
.0
.unbounded_send(Ok(ThreadEvent::ToolCall(
acp::ToolCall::new(tool_use.id.to_string(), tool_use.name.to_string())
acp::ToolCall::new(tool_use.id.to_string(), title.clone())
.status(status)
.raw_input(tool_use.input.clone()),
)))
.ok();
stream.update_tool_call_fields(
&tool_use.id,
acp::ToolCallUpdateFields::new()
.status(status)
.raw_output(output),
None,
);
let mut fields = acp::ToolCallUpdateFields::new()
.status(status)
.raw_output(output);
if tool_use.name.as_ref() == UpdateTitleTool::NAME {
fields = fields.title(title);
}
if let Some(content) = replay_content {
fields = fields.content(content);
}
stream.update_tool_call_fields(&tool_use.id, fields, None);
return;
};
@ -1279,6 +1301,14 @@ impl Thread {
tool_use.input.clone(),
);
if let Some(content) = replay_content {
stream.update_tool_call_fields(
&tool_use.id,
acp::ToolCallUpdateFields::new().content(content),
None,
);
}
if let Some(output) = output.clone() {
// For replay, we use a dummy cancellation receiver since the tool already completed
let (_cancellation_tx, cancellation_rx) = watch::channel(false);
@ -1301,6 +1331,55 @@ impl Thread {
);
}
fn title_for_replayed_tool_use(tool_use: &LanguageModelToolUse) -> String {
if tool_use.name.as_ref() == UpdateTitleTool::NAME {
let input = serde_json::from_value(tool_use.input.clone())
.map_err(|_| serde_json::Value::String(tool_use.raw_input.clone()));
UpdateTitleTool::title_for_input(input).to_string()
} else {
tool_use.name.to_string()
}
}
fn tool_result_content_for_replay(
tool_result: &LanguageModelToolResult,
) -> Option<Vec<acp::ToolCallContent>> {
let has_image = tool_result
.content
.iter()
.any(|part| matches!(part, LanguageModelToolResultContent::Image(_)));
if !has_image && tool_result.output.is_some() {
return None;
}
let content = tool_result
.content
.iter()
.filter_map(|part| match part {
LanguageModelToolResultContent::Text(text) => {
if text.is_empty() {
None
} else {
Some(acp::ToolCallContent::Content(acp::Content::new(
acp::ContentBlock::Text(acp::TextContent::new(text.to_string())),
)))
}
}
LanguageModelToolResultContent::Image(image) => Some(
acp::ToolCallContent::Content(acp::Content::new(acp::ContentBlock::Image(
acp::ImageContent::new(image.source.clone(), "image/png"),
))),
),
})
.collect::<Vec<_>>();
if content.is_empty() {
None
} else {
Some(content)
}
}
pub fn from_db(
id: acp::SessionId,
db_thread: DbThread,
@ -1387,6 +1466,7 @@ impl Thread {
}),
running_subagents: Vec::new(),
inherits_parent_model_settings: true,
sandboxed_terminal_temp_dir: db_thread.sandboxed_terminal_temp_dir,
}
}
@ -1417,6 +1497,7 @@ impl Thread {
offset_in_item: lo.offset_in_item.as_f32(),
}
}),
sandboxed_terminal_temp_dir: self.sandboxed_terminal_temp_dir.clone(),
};
cx.background_spawn(async move {
@ -1580,13 +1661,13 @@ impl Thread {
}
pub fn last_message(&self) -> Option<&Message> {
self.messages.last()
self.messages.last().map(std::ops::Deref::deref)
}
#[cfg(any(test, feature = "test-support"))]
pub fn last_received_or_pending_message(&self) -> Option<Message> {
pub fn last_received_or_pending_message(&self) -> Option<Arc<Message>> {
if let Some(message) = self.pending_message.clone() {
Some(Message::Agent(message))
Some(Arc::new(Message::Agent(message)))
} else {
self.messages.last().cloned()
}
@ -1627,6 +1708,9 @@ impl Thread {
if cx.has_flag::<UpdatePlanToolFeatureFlag>() {
self.add_tool(UpdatePlanTool);
}
if cx.has_flag::<UpdateTitleToolFeatureFlag>() {
self.add_tool(UpdateTitleTool::new(cx.weak_entity()));
}
self.add_tool(ReadFileTool::new(
self.project.clone(),
self.action_log.clone(),
@ -1740,13 +1824,13 @@ impl Thread {
// and we don't want that content to be added after we truncate
self.pending_message.take();
let Some(position) = self.messages.iter().position(
|msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
|msg| matches!(&**msg, Message::User(UserMessage { id, .. }) if id == &message_id),
) else {
return Err(anyhow!("Message not found"));
};
for message in self.messages.drain(position..) {
match message {
match &*message {
Message::User(message) => {
self.request_token_usage.remove(&message.id);
}
@ -1788,7 +1872,7 @@ impl Thread {
let mut previous_user_message_id: Option<&UserMessageId> = None;
for message in &self.messages {
if let Message::User(user_msg) = message {
if let Message::User(user_msg) = &**message {
if &user_msg.id == target_id {
let prev_id = previous_user_message_id?;
let usage = self.request_token_usage.get(prev_id)?;
@ -1833,7 +1917,7 @@ impl Thread {
&mut self,
cx: &mut Context<Self>,
) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
self.messages.push(Message::Resume);
self.messages.push(Arc::new(Message::Resume));
cx.notify();
log::debug!("Total messages in thread: {}", self.messages.len());
@ -1852,11 +1936,11 @@ impl Thread {
where
T: Into<UserMessageContent>,
{
let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
let content = content.into_iter().map(Into::into).collect::<Arc<_>>();
log::debug!("Thread::send content: {:?}", content);
self.messages
.push(Message::User(UserMessage { id, content }));
.push(Arc::new(Message::User(UserMessage { id, content })));
cx.notify();
self.send_existing(cx)
@ -1887,9 +1971,9 @@ impl Thread {
let content = blocks
.into_iter()
.map(|block| UserMessageContent::from_content_block(block, path_style))
.collect::<Vec<_>>();
.collect::<Arc<_>>();
self.messages
.push(Message::User(UserMessage { id, content }));
.push(Arc::new(Message::User(UserMessage { id, content })));
cx.notify();
}
@ -1907,10 +1991,10 @@ impl Thread {
_ => "[unknown]".to_string(),
};
self.messages.push(Message::Agent(AgentMessage {
self.messages.push(Arc::new(Message::Agent(AgentMessage {
content: vec![AgentMessageContent::Text(text)],
..Default::default()
}));
})));
cx.notify();
}
@ -2140,7 +2224,7 @@ impl Thread {
this.update(cx, |this, cx| {
this.flush_pending_message(cx);
if this.title.is_none() && this.pending_title_generation.is_none() {
if this.title.is_none() {
this.generate_title(cx);
}
})?;
@ -2168,10 +2252,10 @@ impl Thread {
}
}
this.update(cx, |this, _cx| {
if let Some(Message::Agent(message)) = this.messages.last() {
if let Some(Message::Agent(message)) = this.last_message() {
if message.tool_results.is_empty() {
intent = CompletionIntent::UserPrompt;
this.messages.push(Message::Resume);
this.messages.push(Arc::new(Message::Resume));
}
}
})?;
@ -2294,12 +2378,12 @@ impl Thread {
let last_message = self.pending_message();
// Store the last non-empty reasoning_details (overwrites earlier ones)
// This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
if let serde_json::Value::Array(ref arr) = details {
if let serde_json::Value::Array(arr) = &details {
if !arr.is_empty() {
last_message.reasoning_details = Some(details);
last_message.reasoning_details = Some(Arc::new(details));
}
} else {
last_message.reasoning_details = Some(details);
last_message.reasoning_details = Some(Arc::new(details));
}
}
ToolUse(tool_use) => {
@ -2669,6 +2753,20 @@ impl Thread {
self.title_generation_failed
}
pub fn can_generate_title(&self, cx: &App) -> bool {
self.pending_title_generation.is_none()
&& self.summarization_model.is_some()
&& !self.update_title_tool_available(cx)
}
fn update_title_tool_available(&self, cx: &App) -> bool {
if let Some(running_turn) = self.running_turn.as_ref() {
running_turn.tools.contains_key(UpdateTitleTool::NAME)
} else {
self.enabled_tools(cx).contains_key(UpdateTitleTool::NAME)
}
}
pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
if let Some(summary) = self.summary.as_ref() {
return Task::ready(Some(summary.clone())).shared();
@ -2730,6 +2828,10 @@ impl Thread {
}
pub fn generate_title(&mut self, cx: &mut Context<Self>) {
if !self.can_generate_title(cx) {
return;
}
self.title_generation_failed = false;
let Some(model) = self.summarization_model.clone() else {
return;
@ -2815,7 +2917,7 @@ impl Thread {
self.messages
.iter()
.rev()
.find_map(|message| match message {
.find_map(|message| match &**message {
Message::User(user_message) => Some(user_message),
Message::Agent(_) => None,
Message::Resume => None,
@ -2856,7 +2958,7 @@ impl Thread {
}
}
self.messages.push(Message::Agent(message));
self.messages.push(Arc::new(Message::Agent(message)));
self.updated_at = Utc::now();
self.clear_summary();
cx.notify()
@ -3088,6 +3190,7 @@ impl Thread {
model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
date: Local::now().format("%Y-%m-%d").to_string(),
user_agents_md,
sandboxing: crate::sandboxing::sandboxing_enabled(cx),
}
.render(&self.templates)
.context("failed to build system prompt")
@ -3119,7 +3222,7 @@ impl Thread {
if ix > 0 {
markdown.push('\n');
}
match message {
match &**message {
Message::User(_) => markdown.push_str("## User\n\n"),
Message::Agent(_) => markdown.push_str("## Assistant\n\n"),
Message::Resume => {}
@ -4331,7 +4434,7 @@ impl UserMessageContent {
match MentionUri::parse(&resource_link.uri, path_style) {
Ok(uri) => Self::Mention {
uri,
content: String::new(),
content: SharedString::default(),
},
Err(err) => {
log::error!("Failed to parse mention link: {}", err);
@ -4344,7 +4447,7 @@ impl UserMessageContent {
match MentionUri::parse(&resource.uri, path_style) {
Ok(uri) => Self::Mention {
uri,
content: resource.text,
content: resource.text.into(),
},
Err(err) => {
log::error!("Failed to parse mention link: {}", err);
@ -4394,7 +4497,6 @@ impl From<UserMessageContent> for acp::ContentBlock {
fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
LanguageModelImage {
source: image_content.data.into(),
size: None,
}
}
@ -4459,6 +4561,259 @@ mod tests {
})
}
struct ReplayImageTool;
impl AgentTool for ReplayImageTool {
type Input = ();
type Output = String;
const NAME: &'static str = "registered_image_tool";
fn kind() -> acp::ToolKind {
acp::ToolKind::Other
}
fn initial_title(
&self,
_input: Result<Self::Input, serde_json::Value>,
_cx: &mut App,
) -> SharedString {
"Registered Image Tool".into()
}
fn run(
self: Arc<Self>,
_input: ToolInput<Self::Input>,
_event_stream: ToolCallEventStream,
_cx: &mut App,
) -> Task<Result<Self::Output, Self::Output>> {
Task::ready(Ok(String::new()))
}
}
#[gpui::test]
async fn test_replay_tool_call_replays_image_content(cx: &mut TestAppContext) {
let (thread, _event_stream) = setup_thread_for_test(cx).await;
let registered_tool_use_id = LanguageModelToolUseId::from("registered_tool_id");
let missing_tool_use_id = LanguageModelToolUseId::from("missing_tool_id");
let image_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
let image = LanguageModelImage {
source: image_data.into(),
};
let mut replay_events = cx.update(|cx| {
thread.update(cx, |thread, cx| {
thread.add_tool(ReplayImageTool);
let registered_tool_use = LanguageModelToolUse {
id: registered_tool_use_id.clone(),
name: ReplayImageTool::NAME.into(),
raw_input: "null".to_string(),
input: json!(null),
is_input_complete: true,
thought_signature: None,
};
let missing_tool_use = LanguageModelToolUse {
id: missing_tool_use_id.clone(),
name: "missing_image_tool".into(),
raw_input: "{}".to_string(),
input: json!({}),
is_input_complete: true,
thought_signature: None,
};
let mut tool_results = IndexMap::default();
tool_results.insert(
registered_tool_use_id.clone(),
LanguageModelToolResult {
tool_use_id: registered_tool_use_id.clone(),
tool_name: ReplayImageTool::NAME.into(),
is_error: false,
content: vec![
LanguageModelToolResultContent::Text("before".into()),
LanguageModelToolResultContent::Image(image.clone()),
LanguageModelToolResultContent::Text("after".into()),
],
output: Some(json!("raw output")),
},
);
tool_results.insert(
missing_tool_use_id.clone(),
LanguageModelToolResult {
tool_use_id: missing_tool_use_id.clone(),
tool_name: "missing_image_tool".into(),
is_error: false,
content: vec![LanguageModelToolResultContent::Image(image.clone())],
output: Some(json!("raw output")),
},
);
thread.messages.push(Arc::new(Message::Agent(AgentMessage {
content: vec![
AgentMessageContent::ToolUse(registered_tool_use),
AgentMessageContent::ToolUse(missing_tool_use),
],
tool_results,
reasoning_details: None,
})));
thread.replay(cx)
})
});
let mut tool_use_ids_with_image_content = HashSet::default();
while let Some(event) = replay_events.next().await {
let event = event.unwrap();
if let ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update)) =
event
&& let Some(content) = &update.fields.content
&& content.iter().any(|content| {
matches!(
content,
acp::ToolCallContent::Content(acp::Content {
content: acp::ContentBlock::Image(_),
..
})
)
})
{
tool_use_ids_with_image_content.insert(update.tool_call_id.to_string());
}
}
assert!(tool_use_ids_with_image_content.contains(&registered_tool_use_id.to_string()));
assert!(tool_use_ids_with_image_content.contains(&missing_tool_use_id.to_string()));
}
#[gpui::test]
async fn test_update_title_tool_replay_does_not_reenter_thread(cx: &mut TestAppContext) {
let (thread, _event_stream) = setup_thread_for_test(cx).await;
let tool_use_id = LanguageModelToolUseId::from("title_tool_id");
let mut replay_events = cx.update(|cx| {
thread.update(cx, |thread, cx| {
thread.add_tool(UpdateTitleTool::new(cx.weak_entity()));
push_completed_update_title_tool_call(thread, tool_use_id.clone());
thread.replay(cx)
})
});
let mut saw_tool_call_title = false;
let mut saw_replayed_title_update = false;
let mut saw_completed_update = false;
while let Some(event) = replay_events.next().await {
let event = event.unwrap();
match event {
ThreadEvent::ToolCall(tool_call)
if tool_call.tool_call_id.to_string() == tool_use_id.to_string()
&& tool_call.title == "Update title: Replayed title" =>
{
saw_tool_call_title = true;
}
ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update))
if update.tool_call_id.to_string() == tool_use_id.to_string() =>
{
if update.fields.title == Some("Update title: Replayed title".to_string()) {
saw_replayed_title_update = true;
}
if update.fields.status == Some(acp::ToolCallStatus::Completed) {
saw_completed_update = true;
}
}
_ => {}
}
}
assert!(saw_tool_call_title);
assert!(saw_replayed_title_update);
assert!(saw_completed_update);
thread.read_with(cx, |thread, _cx| {
assert_eq!(thread.title(), None);
});
}
#[gpui::test]
async fn test_update_title_tool_replay_title_when_tool_not_registered(cx: &mut TestAppContext) {
let (thread, _event_stream) = setup_thread_for_test(cx).await;
let tool_use_id = LanguageModelToolUseId::from("title_tool_id");
let mut replay_events = cx.update(|cx| {
thread.update(cx, |thread, cx| {
push_completed_update_title_tool_call(thread, tool_use_id.clone());
thread.replay(cx)
})
});
let mut saw_tool_call_title = false;
let mut saw_replayed_title_update = false;
let mut saw_completed_update = false;
while let Some(event) = replay_events.next().await {
let event = event.unwrap();
match event {
ThreadEvent::ToolCall(tool_call)
if tool_call.tool_call_id.to_string() == tool_use_id.to_string()
&& tool_call.title == "Update title: Replayed title" =>
{
saw_tool_call_title = true;
}
ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update))
if update.tool_call_id.to_string() == tool_use_id.to_string() =>
{
if update.fields.title == Some("Update title: Replayed title".to_string()) {
saw_replayed_title_update = true;
}
if update.fields.status == Some(acp::ToolCallStatus::Completed) {
saw_completed_update = true;
}
}
_ => {}
}
}
assert!(saw_tool_call_title);
assert!(saw_replayed_title_update);
assert!(saw_completed_update);
thread.read_with(cx, |thread, _cx| {
assert_eq!(thread.title(), None);
});
}
fn push_completed_update_title_tool_call(
thread: &mut Thread,
tool_use_id: LanguageModelToolUseId,
) {
let tool_use = LanguageModelToolUse {
id: tool_use_id.clone(),
name: UpdateTitleTool::NAME.into(),
raw_input: json!({ "title": "Replayed title" }).to_string(),
input: json!({ "title": "Replayed title" }),
is_input_complete: true,
thought_signature: None,
};
let mut tool_results = IndexMap::default();
tool_results.insert(
tool_use_id.clone(),
LanguageModelToolResult {
tool_use_id,
tool_name: UpdateTitleTool::NAME.into(),
is_error: false,
content: vec![LanguageModelToolResultContent::Text(
"Session title updated".into(),
)],
output: Some(json!("Session title updated")),
},
);
thread.messages.push(Arc::new(Message::Agent(AgentMessage {
content: vec![AgentMessageContent::ToolUse(tool_use)],
tool_results,
reasoning_details: None,
})));
}
#[gpui::test]
async fn test_set_model_propagates_to_subagents(cx: &mut TestAppContext) {
let (parent, _event_stream) = setup_thread_for_test(cx).await;

View file

@ -167,6 +167,7 @@ mod tests {
thinking_effort: None,
draft_prompt: None,
ui_scroll_position: None,
sandboxed_terminal_temp_dir: None,
}
}

View file

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

View file

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

View file

@ -1,5 +1,6 @@
use super::tool_permissions::{
authorize_symlink_escapes, canonicalize_worktree_roots, collect_symlink_escapes,
resolve_creatable_global_skill_descendant_path, resolve_global_skill_descendant_path,
sensitive_settings_kind,
};
use crate::{
@ -23,6 +24,7 @@ use util::markdown::MarkdownInlineCode;
///
/// This tool should be used when it's desirable to create a copy of a file or directory without modifying the original.
/// It's much more efficient than doing this by separately reading and then writing the file or directory's contents, so this tool should be preferred over that approach whenever copying is the goal.
/// The only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct CopyPathToolInput {
/// The source path of the file or directory to copy.
@ -100,6 +102,15 @@ impl AgentTool for CopyPathTool {
let fs = project.read_with(cx, |project, _cx| project.fs().clone());
let canonical_roots = canonicalize_worktree_roots(&project, &fs, cx).await;
let global_source_path =
resolve_global_skill_descendant_path(Path::new(&input.source_path), fs.as_ref())
.await;
let global_destination_path = resolve_creatable_global_skill_descendant_path(
Path::new(&input.destination_path),
fs.as_ref(),
)
.await;
let symlink_escapes: Vec<(&str, std::path::PathBuf)> =
project.read_with(cx, |project, cx| {
collect_symlink_escapes(
@ -160,6 +171,63 @@ impl AgentTool for CopyPathTool {
authorize.await.map_err(|e| e.to_string())?;
}
if global_source_path.is_some() || global_destination_path.is_some() {
let source_path = if let Some(global_source_path) = global_source_path {
global_source_path
} else {
project.read_with(cx, |project, cx| {
let project_path = project.find_project_path(&input.source_path, cx).ok_or_else(|| {
format!("Source path {} was not found in the project.", input.source_path)
})?;
project.entry_for_path(&project_path, cx).ok_or_else(|| {
format!("Source path {} was not found in the project.", input.source_path)
})?;
project.absolute_path(&project_path, cx).ok_or_else(|| {
format!("Source path {} could not be resolved.", input.source_path)
})
})?
};
let destination_path = if let Some(global_destination_path) = global_destination_path
{
global_destination_path
} else {
project.read_with(cx, |project, cx| {
let project_path = project.find_project_path(&input.destination_path, cx).ok_or_else(|| {
format!(
"Destination path {} was outside the project.",
input.destination_path
)
})?;
project.absolute_path(&project_path, cx).ok_or_else(|| {
format!(
"Destination path {} could not be resolved.",
input.destination_path
)
})
})?
};
futures::select! {
result = fs::copy_recursive(
fs.as_ref(),
&source_path,
&destination_path,
fs::CopyOptions::default(),
).fuse() => {
result.map_err(|e| format!("Copying {} to {}: {e}", input.source_path, input.destination_path))?;
}
_ = event_stream.cancelled_by_user().fuse() => {
return Err("Copy cancelled by user".to_string());
}
}
return Ok(format!(
"Copied {} to {}",
input.source_path, input.destination_path
));
}
let copy_task = project.update(cx, |project, cx| {
match project
.find_project_path(&input.source_path, cx)
@ -222,6 +290,124 @@ mod tests {
});
}
#[gpui::test]
async fn test_copy_path_global_skill_directory_to_project(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(path!("/root/project"), json!({})).await;
let skill_dir = agent_skills::global_skills_dir().join("my-skill");
fs.insert_tree(&skill_dir, json!({ "SKILL.md": "content" }))
.await;
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
cx.executor().run_until_parked();
let tool = Arc::new(CopyPathTool::new(project));
let input_path = PathBuf::from("~")
.join(".agents")
.join("skills")
.join("my-skill")
.to_string_lossy()
.into_owned();
let (event_stream, mut event_rx) = ToolCallEventStream::test();
let task = cx.update(|cx| {
tool.run(
ToolInput::resolved(CopyPathToolInput {
source_path: input_path,
destination_path: path!("/root/project/my-skill").to_string(),
}),
event_stream,
cx,
)
});
let auth = event_rx.expect_authorization().await;
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
);
auth.response
.send(acp_thread::SelectedPermissionOutcome::new(
acp::PermissionOptionId::new("allow"),
acp::PermissionOptionKind::AllowOnce,
))
.expect("authorization response should send");
let result = task.await;
assert!(result.is_ok(), "should copy after approval: {result:?}");
assert!(fs.is_dir(&skill_dir).await);
assert_eq!(
fs.load(path!("/root/project/my-skill/SKILL.md").as_ref())
.await
.unwrap(),
"content"
);
}
#[gpui::test]
async fn test_copy_path_project_directory_to_global_skill_directory(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/root/project"),
json!({ "exported-skill": { "SKILL.md": "content" } }),
)
.await;
let skills_dir = agent_skills::global_skills_dir();
fs.create_dir(&skills_dir).await.unwrap();
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
cx.executor().run_until_parked();
let tool = Arc::new(CopyPathTool::new(project));
let destination_path = PathBuf::from("~")
.join(".agents")
.join("skills")
.join("exported-skill")
.to_string_lossy()
.into_owned();
let (event_stream, mut event_rx) = ToolCallEventStream::test();
let task = cx.update(|cx| {
tool.run(
ToolInput::resolved(CopyPathToolInput {
source_path: path!("/root/project/exported-skill").to_string(),
destination_path,
}),
event_stream,
cx,
)
});
let auth = event_rx.expect_authorization().await;
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
);
auth.response
.send(acp_thread::SelectedPermissionOutcome::new(
acp::PermissionOptionId::new("allow"),
acp::PermissionOptionKind::AllowOnce,
))
.expect("authorization response should send");
let result = task.await;
assert!(result.is_ok(), "should copy after approval: {result:?}");
assert!(
fs.is_dir(path!("/root/project/exported-skill").as_ref())
.await
);
assert_eq!(
fs.load(skills_dir.join("exported-skill").join("SKILL.md").as_ref())
.await
.unwrap(),
"content"
);
}
#[gpui::test]
async fn test_copy_path_symlink_escape_source_requests_authorization(cx: &mut TestAppContext) {
init_test(cx);

View file

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

View file

@ -1,6 +1,6 @@
use super::tool_permissions::{
authorize_symlink_access, canonicalize_worktree_roots, detect_symlink_escape,
sensitive_settings_kind,
resolve_global_skill_descendant_path, resolves_to_global_skills_dir, sensitive_settings_kind,
};
use crate::{
AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision,
@ -20,6 +20,8 @@ use std::sync::Arc;
use util::markdown::MarkdownInlineCode;
/// Deletes the file or directory (and the directory's contents, recursively) at the specified path in the project, and returns confirmation of the deletion.
///
/// The only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct DeletePathToolInput {
/// The path of the file or directory to delete.
@ -95,6 +97,16 @@ impl AgentTool for DeletePathTool {
let fs = project.read_with(cx, |project, _cx| project.fs().clone());
let canonical_roots = canonicalize_worktree_roots(&project, &fs, cx).await;
if resolves_to_global_skills_dir(Path::new(&path), fs.as_ref()).await {
return Err(
"Cannot delete the global agent skills directory itself. Delete a skill directory or file beneath it instead."
.to_string(),
);
}
let global_skill_path =
resolve_global_skill_descendant_path(Path::new(&path), fs.as_ref()).await;
let symlink_escape_target = project.read_with(cx, |project, cx| {
detect_symlink_escape(project, &path, &canonical_roots, cx)
.map(|(_, target)| target)
@ -147,6 +159,38 @@ impl AgentTool for DeletePathTool {
authorize.await.map_err(|e| e.to_string())?;
}
if let Some(global_skill_path) = global_skill_path {
let metadata = fs
.metadata(&global_skill_path)
.await
.map_err(|e| format!("Deleting {path}: {e}"))?
.ok_or_else(|| format!("Deleting {path}: path not found"))?;
futures::select! {
result = async {
if metadata.is_dir {
fs.remove_dir(
&global_skill_path,
fs::RemoveOptions {
recursive: true,
..fs::RemoveOptions::default()
},
)
.await
} else {
fs.remove_file(&global_skill_path, fs::RemoveOptions::default()).await
}
}.fuse() => {
result.map_err(|e| format!("Deleting {path}: {e}"))?;
}
_ = event_stream.cancelled_by_user().fuse() => {
return Err("Delete cancelled by user".to_string());
}
}
return Ok(format!("Deleted {path}"));
}
let (project_path, worktree_snapshot) = project.read_with(cx, |project, cx| {
let project_path = project.find_project_path(&path, cx).ok_or_else(|| {
format!("Couldn't delete {path} because that path isn't in this project.")
@ -248,6 +292,145 @@ mod tests {
});
}
#[gpui::test]
async fn test_delete_path_global_skill_directory(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(path!("/root/project"), json!({})).await;
let skills_dir = agent_skills::global_skills_dir();
let skill_dir = skills_dir.join("my-skill");
fs.insert_tree(&skill_dir, json!({ "SKILL.md": "content" }))
.await;
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
cx.executor().run_until_parked();
let action_log = cx.new(|_| ActionLog::new(project.clone()));
let tool = Arc::new(DeletePathTool::new(project, action_log));
let input_path = PathBuf::from("~")
.join(".agents")
.join("skills")
.join("my-skill")
.to_string_lossy()
.into_owned();
let (event_stream, mut event_rx) = ToolCallEventStream::test();
let task = cx.update(|cx| {
tool.run(
ToolInput::resolved(DeletePathToolInput { path: input_path }),
event_stream,
cx,
)
});
let auth = event_rx.expect_authorization().await;
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
);
auth.response
.send(acp_thread::SelectedPermissionOutcome::new(
acp::PermissionOptionId::new("allow"),
acp::PermissionOptionKind::AllowOnce,
))
.expect("authorization response should send");
let result = task.await;
assert!(result.is_ok(), "should delete after approval: {result:?}");
assert!(fs.is_dir(&skills_dir).await);
assert!(!fs.is_dir(&skill_dir).await);
}
#[gpui::test]
async fn test_delete_path_global_skill_file(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(path!("/root/project"), json!({})).await;
let skill_file = agent_skills::global_skills_dir()
.join("my-skill")
.join("references")
.join("notes.md");
fs.create_dir(skill_file.parent().unwrap()).await.unwrap();
fs.insert_file(&skill_file, b"notes".to_vec()).await;
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
cx.executor().run_until_parked();
let action_log = cx.new(|_| ActionLog::new(project.clone()));
let tool = Arc::new(DeletePathTool::new(project, action_log));
let input_path = PathBuf::from("~")
.join(".agents")
.join("skills")
.join("my-skill")
.join("references")
.join("notes.md")
.to_string_lossy()
.into_owned();
let (event_stream, mut event_rx) = ToolCallEventStream::test();
let task = cx.update(|cx| {
tool.run(
ToolInput::resolved(DeletePathToolInput { path: input_path }),
event_stream,
cx,
)
});
let auth = event_rx.expect_authorization().await;
auth.response
.send(acp_thread::SelectedPermissionOutcome::new(
acp::PermissionOptionId::new("allow"),
acp::PermissionOptionKind::AllowOnce,
))
.expect("authorization response should send");
let result = task.await;
assert!(result.is_ok(), "should delete after approval: {result:?}");
assert!(!fs.is_file(&skill_file).await);
}
#[gpui::test]
async fn test_delete_path_rejects_global_skills_root(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(path!("/root/project"), json!({})).await;
let skills_dir = agent_skills::global_skills_dir();
fs.create_dir(&skills_dir).await.unwrap();
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
cx.executor().run_until_parked();
let action_log = cx.new(|_| ActionLog::new(project.clone()));
let tool = Arc::new(DeletePathTool::new(project, action_log));
let input_path = PathBuf::from("~")
.join(".agents")
.join("skills")
.to_string_lossy()
.into_owned();
let (event_stream, mut event_rx) = ToolCallEventStream::test();
let result = cx
.update(|cx| {
tool.run(
ToolInput::resolved(DeletePathToolInput { path: input_path }),
event_stream,
cx,
)
})
.await;
assert!(result.is_err(), "should reject deleting skills root");
assert!(fs.is_dir(&skills_dir).await);
assert!(
!matches!(
event_rx.try_recv(),
Ok(Ok(crate::ThreadEvent::ToolCallAuthorization(_)))
),
"Deleting the skills root should fail before requesting authorization",
);
}
#[gpui::test]
async fn test_delete_path_symlink_escape_requests_authorization(cx: &mut TestAppContext) {
init_test(cx);

View file

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

View file

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

View file

@ -2,6 +2,7 @@ mod reindent;
mod streaming_fuzzy_matcher;
mod streaming_parser;
use super::tool_permissions::resolve_creatable_global_skill_path;
use crate::{Thread, ToolCallEventStream};
use acp_thread::Diff;
use action_log::ActionLog;
@ -11,7 +12,7 @@ use collections::HashSet;
use futures::{FutureExt, channel::oneshot};
use gpui::{App, AppContext, AsyncApp, Entity, Task, WeakEntity};
use language::language_settings::{self, FormatOnSave};
use language::{Buffer, BufferEvent, LanguageRegistry};
use language::{Buffer, BufferEditSource, BufferEvent, LanguageRegistry};
use language_model::LanguageModelToolResultContent;
use project::lsp_store::{FormatTrigger, LspFormatTarget};
use project::{AgentLocation, Project, ProjectPath};
@ -277,6 +278,7 @@ pub(crate) enum EditSessionResult {
pub(crate) async fn run_session(
result: EditSessionResult,
event_stream: &ToolCallEventStream,
cx: &mut AsyncApp,
) -> Result<EditSessionOutput, EditSessionOutput> {
match result {
@ -302,6 +304,11 @@ pub(crate) async fn run_session(
.ensure_buffer_saved(&session.buffer, cx)
.await;
let (_new_text, diff) = session.compute_new_text_and_diff(cx).await;
if diff.is_empty() {
event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
acp::ToolCallContent::Content(acp::Content::new(error.clone())),
]));
}
Err(EditSessionOutput::Error {
error,
input_path: Some(session.input_path),
@ -311,11 +318,16 @@ pub(crate) async fn run_session(
EditSessionResult::Failed {
error,
session: None,
} => Err(EditSessionOutput::Error {
error,
input_path: None,
diff: String::new(),
}),
} => {
event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
acp::ToolCallContent::Content(acp::Content::new(error.clone())),
]));
Err(EditSessionOutput::Error {
error,
input_path: None,
diff: String::new(),
})
}
}
}
@ -352,6 +364,16 @@ pub(crate) struct EditSession {
_finalize_diff_guard: Deferred<Box<dyn FnOnce()>>,
}
/// The destination of an edit session, identified by its absolute path on
/// disk. `project_path` is `Some` for files that live inside one of the
/// project's worktrees (i.e. that the standard project-path machinery can
/// resolve), and `None` for global skill files reached through the
/// `~/.agents/skills` allowlist.
struct EditSessionTarget {
abs_path: PathBuf,
project_path: Option<ProjectPath>,
}
enum Pipeline {
Write(WritePipeline),
Edit(EditPipeline),
@ -598,21 +620,14 @@ impl EditPipeline {
log::debug!("new_text_chunk: done=true, final_text='{}'", final_text);
if !final_text.is_empty() {
let char_ops = streaming_diff.push_new(&final_text);
apply_char_operations(
&char_ops,
buffer,
&original_snapshot,
&mut edit_cursor,
&context.action_log,
cx,
);
}
let remaining_ops = streaming_diff.finish();
let mut char_ops = if final_text.is_empty() {
Vec::new()
} else {
streaming_diff.push_new(&final_text)
};
char_ops.extend(streaming_diff.finish());
apply_char_operations(
&remaining_ops,
&char_ops,
buffer,
&original_snapshot,
&mut edit_cursor,
@ -639,16 +654,34 @@ impl EditSession {
event_stream: &ToolCallEventStream,
cx: &mut AsyncApp,
) -> Result<Self, String> {
let project_path = cx.update(|cx| resolve_path(mode, &path, &context.project, cx))?;
let target = if let Some(abs_path) =
resolve_global_skill_path_for_edit_session(mode, &path, &context, cx).await?
{
EditSessionTarget {
abs_path,
project_path: None,
}
} else {
let project_path = cx.update(|cx| resolve_path(mode, &path, &context.project, cx))?;
let Some(abs_path) =
cx.update(|cx| context.project.read(cx).absolute_path(&project_path, cx))
else {
return Err(format!(
"Worktree at '{}' does not exist",
path.to_string_lossy()
));
let Some(abs_path) =
cx.update(|cx| context.project.read(cx).absolute_path(&project_path, cx))
else {
return Err(format!(
"Worktree at '{}' does not exist",
path.to_string_lossy()
));
};
EditSessionTarget {
abs_path,
project_path: Some(project_path),
}
};
let EditSessionTarget {
abs_path,
project_path,
} = target;
event_stream.update_fields(
ToolCallUpdateFields::new().locations(vec![ToolCallLocation::new(abs_path.clone())]),
@ -658,11 +691,20 @@ impl EditSession {
.await
.map_err(|e| e.to_string())?;
let buffer = context
.project
.update(cx, |project, cx| project.open_buffer(project_path, cx))
.await
.map_err(|e| e.to_string())?;
let buffer = match project_path {
Some(project_path) => context
.project
.update(cx, |project, cx| project.open_buffer(project_path, cx))
.await
.map_err(|e| e.to_string())?,
None => context
.project
.update(cx, |project, cx| {
project.open_local_buffer(abs_path.clone(), cx)
})
.await
.map_err(|e| e.to_string())?,
};
let file_changed_since_last_read =
ensure_buffer_saved(&buffer, &abs_path, mode, &context, event_stream, cx).await?;
@ -853,16 +895,17 @@ fn apply_char_operations(
action_log: &Entity<ActionLog>,
cx: &mut AsyncApp,
) {
let mut edits: Vec<_> = Vec::new();
for op in ops {
match op {
CharOperation::Insert { text } => {
let anchor = snapshot.anchor_after(*edit_cursor);
agent_edit_buffer(&buffer, [(anchor..anchor, text.as_str())], action_log, cx);
edits.push((anchor..anchor, text.as_str().into()));
}
CharOperation::Delete { bytes } => {
let delete_end = *edit_cursor + bytes;
let anchor_range = snapshot.anchor_range_inside(*edit_cursor..delete_end);
agent_edit_buffer(&buffer, [(anchor_range, "")], action_log, cx);
edits.push((anchor_range, Arc::<str>::from("")));
*edit_cursor = delete_end;
}
CharOperation::Keep { bytes } => {
@ -870,6 +913,9 @@ fn apply_char_operations(
}
}
}
if !edits.is_empty() {
agent_edit_buffer(buffer, edits, action_log, cx);
}
}
fn extract_match(
@ -926,7 +972,9 @@ fn agent_edit_buffer<I, S, T>(
{
cx.update(|cx| {
buffer.update(cx, |buffer, cx| {
buffer.start_transaction();
buffer.edit(edits, None, cx);
buffer.end_transaction_with_source(BufferEditSource::Agent, cx);
});
action_log.update(cx, |log, cx| log.buffer_edited(buffer.clone(), cx));
});
@ -1055,6 +1103,72 @@ async fn resolve_dirty_buffer(
Ok(())
}
/// Mirrors [`resolve_path`]'s pre-auth validation for the global-skill
/// branch: returns `Ok(Some(abs_path))` if the path lives under
/// `~/.agents/skills` and is in a valid state for the requested mode,
/// `Ok(None)` if the path isn't a global skill at all (so the caller should
/// fall through to project-path resolution), or `Err(message)` if the path
/// is a global skill but can't be used (missing in Edit mode, parent
/// missing in Write mode, etc.).
///
/// Errors returned from here surface to the model as tool-result errors
/// without prompting the user — same contract as [`resolve_path`]. The
/// idea is that "file doesn't exist" or "parent isn't a directory" are
/// model mistakes, not decisions the user should be asked to approve.
async fn resolve_global_skill_path_for_edit_session(
mode: EditSessionMode,
path: &PathBuf,
context: &EditSessionContext,
cx: &mut AsyncApp,
) -> Result<Option<PathBuf>, String> {
let fs = context
.project
.read_with(cx, |project, _cx| project.fs().clone());
let Some(abs_path) = resolve_creatable_global_skill_path(path, fs.as_ref()).await else {
return Ok(None);
};
match mode {
EditSessionMode::Edit => {
let metadata = fs
.metadata(&abs_path)
.await
.map_err(|e| format!("Can't edit file: {e}"))?
.ok_or_else(|| "Can't edit file: path not found".to_string())?;
if metadata.is_dir {
return Err("Can't edit file: path is a directory".to_string());
}
}
EditSessionMode::Write => {
if let Some(metadata) = fs
.metadata(&abs_path)
.await
.map_err(|e| format!("Can't write to file: {e}"))?
{
if metadata.is_dir {
return Err("Can't write to file: path is a directory".to_string());
}
} else {
let parent_path = abs_path
.parent()
.ok_or_else(|| "Can't create file: incorrect path".to_string())?;
let parent_metadata = fs
.metadata(parent_path)
.await
.map_err(|e| format!("Can't create file: {e}"))?
.ok_or_else(|| {
"Can't create file: parent directory doesn't exist".to_string()
})?;
if !parent_metadata.is_dir {
return Err("Can't create file: parent is not a directory".to_string());
}
}
}
}
Ok(Some(abs_path))
}
fn resolve_path(
mode: EditSessionMode,
path: &PathBuf,

View file

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

View file

@ -361,7 +361,7 @@ impl EditToolTest {
abs_path: Path::new("/path/to/root").into(),
rules_file: None,
}];
let project_context = ProjectContext::new(worktrees, Vec::default());
let project_context = ProjectContext::new(worktrees);
let tool_names = tools
.iter()
.map(|tool| tool.name.clone().into())
@ -372,6 +372,7 @@ impl EditToolTest {
model_name: None,
date: chrono::Local::now().format("%Y-%m-%d").to_string(),
user_agents_md: None,
sandboxing: false,
};
let templates = Templates::new();
template.render(&templates)?

View file

@ -220,7 +220,7 @@ impl TerminalToolTest {
abs_path: Path::new("/path/to/root").into(),
rules_file: None,
}];
let project_context = ProjectContext::new(worktrees, Vec::default());
let project_context = ProjectContext::new(worktrees);
let tool_names = tools
.iter()
.map(|tool| tool.name.clone().into())
@ -231,6 +231,7 @@ impl TerminalToolTest {
model_name: None,
date: chrono::Local::now().format("%Y-%m-%d").to_string(),
user_agents_md: None,
sandboxing: false,
};
template.render(&Templates::new())?
};

View file

@ -191,7 +191,7 @@ impl WriteToolTest {
abs_path: Path::new("/path/to/root").into(),
rules_file: None,
}];
let project_context = ProjectContext::new(worktrees, Vec::default());
let project_context = ProjectContext::new(worktrees);
let tool_names = tools
.iter()
.map(|tool| tool.name.clone().into())
@ -202,6 +202,7 @@ impl WriteToolTest {
model_name: None,
date: chrono::Local::now().format("%Y-%m-%d").to_string(),
user_agents_md: None,
sandboxing: false,
};
let templates = Templates::new();
template.render(&templates)?

View file

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

View file

@ -1,6 +1,7 @@
use super::tool_permissions::{
authorize_symlink_escapes, canonicalize_worktree_roots, collect_symlink_escapes,
sensitive_settings_kind,
resolve_creatable_global_skill_descendant_path, resolve_global_skill_descendant_path,
resolves_to_global_skills_dir, sensitive_settings_kind,
};
use crate::{
AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision,
@ -22,6 +23,7 @@ use util::markdown::MarkdownInlineCode;
/// If the source and destination directories are the same, but the filename is different, this performs a rename. Otherwise, it performs a move.
///
/// This tool should be used when it's desirable to move or rename a file or directory without changing its contents at all.
/// The only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct MovePathToolInput {
/// The source path of the file or directory to move/rename.
@ -116,6 +118,28 @@ impl AgentTool for MovePathTool {
let fs = project.read_with(cx, |project, _cx| project.fs().clone());
let canonical_roots = canonicalize_worktree_roots(&project, &fs, cx).await;
if resolves_to_global_skills_dir(Path::new(&input.source_path), fs.as_ref()).await
|| resolves_to_global_skills_dir(
Path::new(&input.destination_path),
fs.as_ref(),
)
.await
{
return Err(
"Cannot move the global agent skills directory itself. Move a skill directory or file beneath it instead."
.to_string(),
);
}
let global_source_path =
resolve_global_skill_descendant_path(Path::new(&input.source_path), fs.as_ref())
.await;
let global_destination_path = resolve_creatable_global_skill_descendant_path(
Path::new(&input.destination_path),
fs.as_ref(),
)
.await;
let symlink_escapes: Vec<(&str, std::path::PathBuf)> =
project.read_with(cx, |project, cx| {
collect_symlink_escapes(
@ -176,6 +200,65 @@ impl AgentTool for MovePathTool {
authorize.await.map_err(|e| e.to_string())?;
}
if global_source_path.is_some() || global_destination_path.is_some() {
let source_path = if let Some(global_source_path) = global_source_path {
global_source_path
} else {
project.read_with(cx, |project, cx| {
let project_path = project.find_project_path(&input.source_path, cx).ok_or_else(|| {
format!("Source path {} was not found in the project.", input.source_path)
})?;
project.entry_for_path(&project_path, cx).ok_or_else(|| {
format!("Source path {} was not found in the project.", input.source_path)
})?;
project.absolute_path(&project_path, cx).ok_or_else(|| {
format!("Source path {} could not be resolved.", input.source_path)
})
})?
};
let destination_path = if let Some(global_destination_path) = global_destination_path
{
global_destination_path
} else {
project.read_with(cx, |project, cx| {
let project_path = project.find_project_path(&input.destination_path, cx).ok_or_else(|| {
format!(
"Destination path {} was outside the project.",
input.destination_path
)
})?;
project.absolute_path(&project_path, cx).ok_or_else(|| {
format!(
"Destination path {} could not be resolved.",
input.destination_path
)
})
})?
};
futures::select! {
result = fs.rename(
&source_path,
&destination_path,
fs::RenameOptions {
create_parents: true,
..fs::RenameOptions::default()
},
).fuse() => {
result.map_err(|e| format!("Moving {} to {}: {e}", input.source_path, input.destination_path))?;
}
_ = event_stream.cancelled_by_user().fuse() => {
return Err("Move cancelled by user".to_string());
}
}
return Ok(format!(
"Moved {} to {}",
input.source_path, input.destination_path
));
}
let rename_task = project.update(cx, |project, cx| {
match project
.find_project_path(&input.source_path, cx)
@ -232,6 +315,125 @@ mod tests {
});
}
#[gpui::test]
async fn test_move_path_global_skill_directory_to_project(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(path!("/root/project"), json!({})).await;
let skill_dir = agent_skills::global_skills_dir().join("my-skill");
fs.insert_tree(&skill_dir, json!({ "SKILL.md": "content" }))
.await;
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
cx.executor().run_until_parked();
let tool = Arc::new(MovePathTool::new(project));
let input_path = PathBuf::from("~")
.join(".agents")
.join("skills")
.join("my-skill")
.to_string_lossy()
.into_owned();
let destination_path = path!("/root/project/my-skill").to_string();
let (event_stream, mut event_rx) = ToolCallEventStream::test();
let task = cx.update(|cx| {
tool.run(
ToolInput::resolved(MovePathToolInput {
source_path: input_path,
destination_path,
}),
event_stream,
cx,
)
});
let auth = event_rx.expect_authorization().await;
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
);
auth.response
.send(acp_thread::SelectedPermissionOutcome::new(
acp::PermissionOptionId::new("allow"),
acp::PermissionOptionKind::AllowOnce,
))
.expect("authorization response should send");
let result = task.await;
assert!(result.is_ok(), "should move after approval: {result:?}");
assert!(!fs.is_dir(&skill_dir).await);
assert_eq!(
fs.load(path!("/root/project/my-skill/SKILL.md").as_ref())
.await
.unwrap(),
"content"
);
}
#[gpui::test]
async fn test_move_path_project_directory_to_global_skill_directory(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/root/project"),
json!({ "exported-skill": { "SKILL.md": "content" } }),
)
.await;
let skills_dir = agent_skills::global_skills_dir();
fs.create_dir(&skills_dir).await.unwrap();
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
cx.executor().run_until_parked();
let tool = Arc::new(MovePathTool::new(project));
let destination_path = PathBuf::from("~")
.join(".agents")
.join("skills")
.join("exported-skill")
.to_string_lossy()
.into_owned();
let (event_stream, mut event_rx) = ToolCallEventStream::test();
let task = cx.update(|cx| {
tool.run(
ToolInput::resolved(MovePathToolInput {
source_path: path!("/root/project/exported-skill").to_string(),
destination_path,
}),
event_stream,
cx,
)
});
let auth = event_rx.expect_authorization().await;
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
);
auth.response
.send(acp_thread::SelectedPermissionOutcome::new(
acp::PermissionOptionId::new("allow"),
acp::PermissionOptionKind::AllowOnce,
))
.expect("authorization response should send");
let result = task.await;
assert!(result.is_ok(), "should move after approval: {result:?}");
assert!(
!fs.is_dir(path!("/root/project/exported-skill").as_ref())
.await
);
assert_eq!(
fs.load(skills_dir.join("exported-skill").join("SKILL.md").as_ref())
.await
.unwrap(),
"content"
);
}
#[gpui::test]
async fn test_move_path_symlink_escape_source_requests_authorization(cx: &mut TestAppContext) {
init_test(cx);

View file

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

View file

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

View file

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

View file

@ -14,6 +14,7 @@ use std::{
time::Duration,
};
use crate::sandboxing::sandboxing_enabled;
use crate::{AgentTool, ThreadEnvironment, ToolCallEventStream, ToolInput};
const COMMAND_OUTPUT_LIMIT: u64 = 16 * 1024;
@ -39,7 +40,7 @@ const COMMAND_OUTPUT_LIMIT: u64 = 16 * 1024;
/// - Always insert `--no-pager` immediately after `git` for any read-only git command, including `git log`, `git diff`, `git show`, `git blame`, and `git stash show`. Example: `git --no-pager log -n 5` (NOT `git log -n 5`).
/// - Always prepend `GIT_EDITOR=true ` to any git command that may invoke an editor, including `git rebase`, `git commit`, `git merge`, and `git tag`. Example: `GIT_EDITOR=true git rebase origin/main` (NOT `git rebase origin/main`).
/// - For other commands that may open a pager or editor, set `PAGER=cat` and/or `EDITOR=true` similarly.
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct TerminalToolInput {
/// The one-liner command to execute. Do not include shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`; resolve those values first or ask the user.
///
@ -49,6 +50,35 @@ pub struct TerminalToolInput {
pub cd: String,
/// Optional maximum runtime (in milliseconds). If exceeded, the running terminal task is killed.
pub timeout_ms: Option<u64>,
/// Request network access for this command.
///
/// Only meaningful when the system prompt's "Terminal sandbox" section
/// is present — ignored otherwise. By default sandboxed commands
/// cannot make outbound network connections; set this to `true` only
/// when the command needs network access. The user will be prompted
/// to approve before the command runs.
#[serde(default)]
pub allow_network: Option<bool>,
/// Request unrestricted filesystem-write access for this command.
///
/// Only meaningful when the system prompt's "Terminal sandbox" section
/// is present — ignored otherwise. By default sandboxed commands can
/// only write to the project worktree directories and a per-command
/// temporary directory; set this to `true` only when the command
/// needs to write elsewhere. The user will be prompted to approve
/// before the command runs.
#[serde(default)]
pub allow_fs_write: Option<bool>,
/// Request to run this command outside the sandbox entirely.
///
/// Only meaningful when the system prompt's "Terminal sandbox" section
/// is present — ignored otherwise. Prefer `allow_network: true` or
/// `allow_fs_write: true` when one of those is enough. Set this to
/// `true` ONLY when the command needs behavior that the sandbox can't
/// grant on a per-permission basis. The user will be prompted to
/// approve before the command runs without sandbox restrictions.
#[serde(default)]
pub unsandboxed: Option<bool>,
}
pub struct TerminalTool {
@ -96,24 +126,100 @@ impl AgentTool for TerminalTool {
cx.spawn(async move |cx| {
let input = input.recv().await.map_err(|e| e.to_string())?;
let (working_dir, authorize) = cx.update(|cx| {
let (working_dir, authorize, sandboxing) = cx.update(|cx| {
let working_dir =
working_dir(&input, &self.project, cx).map_err(|err| err.to_string())?;
let context =
crate::ToolPermissionContext::new(Self::NAME, vec![input.command.clone()]);
let authorize =
event_stream.authorize(self.initial_title(Ok(input.clone()), cx), context, cx);
Result::<_, String>::Ok((working_dir, authorize))
let sandboxing = sandboxing_enabled(cx);
Result::<_, String>::Ok((working_dir, authorize, sandboxing))
})?;
authorize.await.map_err(|e| e.to_string())?;
// Sandbox flags only do anything when sandboxing is on. When
// off, we treat them as `None` so the model can't surreptitiously
// change runtime behavior by setting flags described as a no-op
// in the system prompt.
let want_network = sandboxing && input.allow_network == Some(true);
let want_fs_write = sandboxing && input.allow_fs_write == Some(true);
let want_unsandboxed = sandboxing && input.unsandboxed == Some(true);
// `unsandboxed: true` bypasses the wrap entirely; per-permission
// requests are only meaningful when the command is still being
// sandboxed.
let escalate = !want_unsandboxed && (want_network || want_fs_write);
if want_unsandboxed || escalate {
let title = sandbox_approval_title(want_network, want_fs_write, want_unsandboxed);
let approve = cx.update(|cx| {
let context = crate::ToolPermissionContext::new(
Self::NAME,
vec![input.command.clone()],
);
// Sandbox escalations always prompt, even if the user
// has `always_allow` rules for this command — the
// escalation is a stronger trust boundary than the
// baseline command approval.
event_stream.authorize_always_prompt(title, context, cx)
});
if let Err(error) = approve.await {
return Ok(if want_unsandboxed {
format!(
"Command cancelled: user denied permission to run outside the sandbox ({error})."
)
} else {
format!(
"Command cancelled: user denied the requested sandbox permissions ({error})."
)
});
}
}
// The per-thread scratch directory (and the `$TMPDIR`/`TMP`/
// `TEMP` environment variables pointing at it) is provisioned by
// the thread environment in `create_terminal`, which also adds it
// to the sandbox's writable scope. We must not set `$TMPDIR` here:
// the environment overrides it with the per-thread directory, so a
// per-command directory set here would never be the `$TMPDIR` the
// command actually sees and would be left out of the writable
// scope, breaking writes into `$TMPDIR`.
let extra_env = Vec::new();
// Build the writable scope from the project's worktrees. The
// per-thread temp directory is appended by the thread environment
// (which owns it and points `$TMPDIR` at it). Crucially we do
// *not* include the resolved `cd` working directory — that's
// model-controlled, and using it as the writable scope would
// let the model widen its own write permissions outside the
// project.
let sandbox_wrap = if sandboxing && !want_unsandboxed {
let writable_paths: Vec<PathBuf> = cx.update(|cx| {
self.project
.read(cx)
.worktrees(cx)
.map(|w| w.read(cx).abs_path().to_path_buf())
.collect::<Vec<_>>()
});
Some(acp_thread::SandboxWrap {
writable_paths,
allow_network: want_network,
allow_fs_write: want_fs_write,
})
} else {
None
};
let terminal = self
.environment
.create_terminal(
input.command.clone(),
extra_env,
working_dir,
Some(COMMAND_OUTPUT_LIMIT),
sandbox_wrap,
cx,
)
.await
@ -182,6 +288,29 @@ impl AgentTool for TerminalTool {
}
}
/// User-facing title for the sandbox-escalation approval prompt.
///
/// `want_unsandboxed` wins over the per-permission flags because
/// `unsandboxed: true` bypasses the per-permission machinery entirely.
fn sandbox_approval_title(
want_network: bool,
want_fs_write: bool,
want_unsandboxed: bool,
) -> &'static str {
if want_unsandboxed {
"Allow this command to run outside the sandbox?"
} else {
match (want_network, want_fs_write) {
(true, true) => "Allow network access and arbitrary filesystem writes?",
(true, false) => "Allow network access?",
(false, true) => "Allow arbitrary filesystem writes?",
// Caller only invokes this when at least one flag is set, so
// this fallback is unreachable in practice.
(false, false) => "Allow this command to run?",
}
}
}
fn process_content(
output: acp::TerminalOutputResponse,
command: &str,
@ -310,6 +439,7 @@ mod tests {
.to_string(),
cd: ".".to_string(),
timeout_ms: None,
..Default::default()
};
let title = format_initial_title(Ok(input));
@ -369,6 +499,7 @@ mod tests {
command: cmd.to_string(),
cd: ".".to_string(),
timeout_ms: None,
..Default::default()
};
let title = format_initial_title(Ok(input));
@ -406,6 +537,7 @@ mod tests {
command: "echo 'hello world'".to_string(),
cd: ".".to_string(),
timeout_ms: None,
..Default::default()
};
let title = format_initial_title(Ok(input));
@ -435,6 +567,7 @@ mod tests {
command: long_command,
cd: ".".to_string(),
timeout_ms: None,
..Default::default()
};
let title = format_initial_title(Ok(input));
@ -641,6 +774,7 @@ mod tests {
command: "echo $HOME".to_string(),
cd: "root".to_string(),
timeout_ms: None,
..Default::default()
}),
event_stream,
cx,
@ -708,6 +842,7 @@ mod tests {
command: "echo $HOME".to_string(),
cd: "root".to_string(),
timeout_ms: None,
..Default::default()
}),
event_stream,
cx,
@ -769,6 +904,7 @@ mod tests {
command: "echo $(rm -rf /)".to_string(),
cd: "root".to_string(),
timeout_ms: None,
..Default::default()
}),
event_stream,
cx,
@ -838,6 +974,7 @@ mod tests {
command: "PAGER=blah git log --oneline".to_string(),
cd: "root".to_string(),
timeout_ms: None,
..Default::default()
}),
event_stream,
cx,
@ -911,6 +1048,7 @@ mod tests {
command: "PAGER=blah git log".to_string(),
cd: "root".to_string(),
timeout_ms: None,
..Default::default()
}),
event_stream,
cx,
@ -1018,6 +1156,7 @@ mod tests {
command: command.to_string(),
cd: "root".to_string(),
timeout_ms: None,
..Default::default()
}),
event_stream,
cx,
@ -1185,6 +1324,7 @@ mod tests {
command: "echo $(whoami)".to_string(),
cd: "root".to_string(),
timeout_ms: None,
..Default::default()
}),
event_stream,
cx,
@ -1257,6 +1397,7 @@ mod tests {
command: "PAGER=other git log".to_string(),
cd: "root".to_string(),
timeout_ms: None,
..Default::default()
}),
event_stream,
cx,
@ -1323,6 +1464,7 @@ mod tests {
command: "A=1 B=2 git log".to_string(),
cd: "root".to_string(),
timeout_ms: None,
..Default::default()
}),
event_stream,
cx,
@ -1400,6 +1542,7 @@ mod tests {
command: "PAGER=\"less -R\" git log".to_string(),
cd: "root".to_string(),
timeout_ms: None,
..Default::default()
}),
event_stream,
cx,
@ -1428,4 +1571,72 @@ mod tests {
"unexpected terminal result: {result}"
);
}
#[test]
fn test_sandbox_approval_title_unsandboxed_wins() {
// `unsandboxed: true` skips the sandbox entirely, so the title should
// reflect that even when other flags are also set — they're moot.
assert_eq!(
sandbox_approval_title(true, true, true),
"Allow this command to run outside the sandbox?"
);
assert_eq!(
sandbox_approval_title(false, false, true),
"Allow this command to run outside the sandbox?"
);
}
#[test]
fn test_sandbox_approval_title_per_permission_flags() {
assert_eq!(
sandbox_approval_title(true, true, false),
"Allow network access and arbitrary filesystem writes?"
);
assert_eq!(
sandbox_approval_title(true, false, false),
"Allow network access?"
);
assert_eq!(
sandbox_approval_title(false, true, false),
"Allow arbitrary filesystem writes?"
);
}
#[test]
fn test_input_schema_includes_sandbox_flags() {
// The model only sees these fields when the sandboxing prompt
// section is rendered, but they're always present in the schema so
// input validation doesn't reject them when sent. Guard against
// accidentally renaming or removing them.
let schema = serde_json::to_string(&schemars::schema_for!(TerminalToolInput))
.expect("input schema should serialize");
assert!(
schema.contains("allow_network"),
"schema should advertise allow_network: {schema}"
);
assert!(
schema.contains("allow_fs_write"),
"schema should advertise allow_fs_write: {schema}"
);
assert!(
schema.contains("unsandboxed"),
"schema should advertise unsandboxed: {schema}"
);
}
#[test]
fn test_sandbox_flags_default_to_none_when_absent() {
// The model is expected to omit the sandbox fields entirely on most
// calls. Make sure deserialization doesn't reject the minimal
// payload and that the fields default to `None` (which the tool
// interprets as "no escalation requested").
let input: TerminalToolInput = serde_json::from_value(serde_json::json!({
"command": "echo hi",
"cd": ".",
}))
.expect("minimal input should deserialize");
assert_eq!(input.allow_network, None);
assert_eq!(input.allow_fs_write, None);
assert_eq!(input.unsandboxed, None);
}
}

View file

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

View file

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

View file

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

File diff suppressed because it is too large Load diff

View file

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

View file

@ -21,6 +21,7 @@ futures.workspace = true
gpui.workspace = true
language_model.workspace = true
log.workspace = true
paths.workspace = true
project.workspace = true
regex.workspace = true
schemars.workspace = true
@ -31,7 +32,6 @@ util.workspace = true
[dev-dependencies]
fs.workspace = true
gpui = { workspace = true, features = ["test-support"] }
paths.workspace = true
serde_json_lenient.workspace = true
serde_json.workspace = true

View file

@ -1,4 +1,5 @@
mod agent_profile;
mod user_agents_md;
use std::path::{Component, Path};
use std::sync::{Arc, LazyLock};
@ -20,6 +21,7 @@ use settings::{
};
pub use crate::agent_profile::*;
pub use crate::user_agents_md::{UserAgentsMd, UserAgentsMdState, init as init_user_agents_md};
pub const SUMMARIZE_THREAD_PROMPT: &str = include_str!("prompts/summarize_thread_prompt.txt");
pub const SUMMARIZE_THREAD_DETAILED_PROMPT: &str =

View file

@ -13,6 +13,7 @@ path = "agent_skills.rs"
[dependencies]
anyhow.workspace = true
base64.workspace = true
const_format.workspace = true
fs.workspace = true
futures.workspace = true
@ -20,6 +21,7 @@ gpui.workspace = true
paths.workspace = true
serde.workspace = true
serde_yaml_ng.workspace = true
url.workspace = true
util.workspace = true
[dev-dependencies]

View file

@ -1,11 +1,12 @@
use anyhow::{Context as _, Result};
use const_format::concatcp;
use const_format::{concatcp, formatcp};
use fs::Fs;
use futures::StreamExt;
use gpui::{Global, SharedString};
use serde::{Deserialize, Serialize};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use url::Url;
use util::paths::component_matches_ignore_ascii_case;
/// First segment of the skills directory path: `.agents`.
@ -64,11 +65,19 @@ pub struct Skill {
/// `skill` tool refuses to load it. The user can still invoke it as a
/// slash command.
pub disable_model_invocation: bool,
/// For built-in skills whose content is compiled into the binary,
/// this holds the full SKILL.md body so the skill tool can serve it
/// without a filesystem read.
pub embedded_body: Option<&'static str>,
}
/// Indicates where a skill was loaded from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SkillSource {
/// Compiled into the Zed binary. These are always available and have
/// the lowest override priority (global and project-local skills can
/// shadow them).
BuiltIn,
/// From ~/.agents/skills/
Global,
/// From {project}/.agents/skills/
@ -79,6 +88,23 @@ pub enum SkillSource {
}
impl SkillSource {
/// Precedence for resolving same-named skills. Higher values shadow
/// lower ones: `ProjectLocal` > `Global` > `BuiltIn`. Two sources
/// returning equal precedence (e.g. two project-local skills from
/// different worktrees) leave the winner up to the caller, which by
/// convention keeps the first one in iteration order.
///
/// Adding a new `SkillSource` variant should be a one-line change
/// here — every consumer routes through this method so the hierarchy
/// stays in sync.
pub fn precedence(&self) -> u8 {
match self {
Self::BuiltIn => 0,
Self::Global => 1,
Self::ProjectLocal { .. } => 2,
}
}
/// Scope prefix used in the `/<prefix>:<name>` slash-command
/// syntax that the autocomplete popup inserts. Global skills use
/// an empty prefix (so the inserted text is `/:<name>`), and
@ -91,9 +117,21 @@ impl SkillSource {
/// invoked as `/:<name>`, and the worktree's skill is invoked as
/// `/global:<name>`. The two grammars never collide on the
/// inserted text.
/// Human-readable label for this source, used in the UI to
/// distinguish skills from different origins.
pub fn display_label(&self) -> &str {
match self {
Self::BuiltIn => "built-in",
Self::Global => "global",
Self::ProjectLocal {
worktree_root_name, ..
} => worktree_root_name.as_ref(),
}
}
pub fn scope_prefix(&self) -> &str {
match self {
Self::Global => "",
Self::BuiltIn | Self::Global => "",
Self::ProjectLocal {
worktree_root_name, ..
} => worktree_root_name.as_ref(),
@ -112,7 +150,7 @@ impl SkillSource {
/// strictness only affects users typing by memory.
pub fn matches_scope(&self, scope: &str) -> bool {
match self {
Self::Global => scope.is_empty(),
Self::BuiltIn | Self::Global => scope.is_empty(),
Self::ProjectLocal {
worktree_root_name, ..
} => !scope.is_empty() && worktree_root_name.as_ref() == scope,
@ -120,6 +158,23 @@ impl SkillSource {
}
}
/// App-wide index of loaded skills, published by NativeAgent and read
/// by any UI that needs to display the skill list (e.g. Settings UI).
#[derive(Default)]
pub struct SkillIndex {
pub global_skills: Vec<Skill>,
pub project_skills: Vec<ProjectSkillGroup>,
}
#[derive(Clone)]
pub struct ProjectSkillGroup {
pub worktree_id: SkillScopeId,
pub worktree_root_name: SharedString,
pub skills: Vec<Skill>,
}
impl Global for SkillIndex {}
/// Just the frontmatter, used for parsing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillMetadata {
@ -187,17 +242,7 @@ pub fn parse_skill_frontmatter(
content: &str,
source: SkillSource,
) -> Result<Skill> {
if content.len() > MAX_SKILL_FILE_SIZE {
anyhow::bail!(
"SKILL.md file exceeds maximum size of {}KB",
MAX_SKILL_FILE_SIZE / 1024
);
}
let (metadata, _body) = extract_frontmatter(content)?;
validate_name(&metadata.name)?;
validate_description(&metadata.description)?;
let (metadata, _body) = parse_skill_file_content(content)?;
let directory_path = skill_file_path
.parent()
@ -211,9 +256,33 @@ pub fn parse_skill_frontmatter(
directory_path,
skill_file_path: skill_file_path.to_path_buf(),
disable_model_invocation: metadata.disable_model_invocation,
embedded_body: None,
})
}
/// Extract the YAML frontmatter and body from a SKILL.md file without
/// validating the metadata fields.
pub fn extract_skill_frontmatter(content: &str) -> Result<(SkillMetadata, &str)> {
if content.len() > MAX_SKILL_FILE_SIZE {
anyhow::bail!(
"SKILL.md file exceeds maximum size of {}KB",
MAX_SKILL_FILE_SIZE / 1024
);
}
extract_frontmatter(content)
}
/// Parse and validate the YAML frontmatter and body from a SKILL.md file.
pub fn parse_skill_file_content(content: &str) -> Result<(SkillMetadata, &str)> {
let (metadata, body) = extract_skill_frontmatter(content)?;
validate_name(&metadata.name).map_err(anyhow::Error::msg)?;
validate_description(&metadata.description).map_err(anyhow::Error::msg)?;
Ok((metadata, body))
}
fn extract_frontmatter(content: &str) -> Result<(SkillMetadata, &str)> {
let content = content.trim_start();
@ -290,6 +359,14 @@ fn extract_frontmatter(content: &str) -> Result<(SkillMetadata, &str)> {
/// by [`validate_name`].
pub const MAX_SKILL_NAME_LEN: usize = 64;
/// Maximum length (in bytes) for a valid skill description. Mirrors the
/// upper bound enforced by [`validate_description`].
///
/// Byte-based rather than char-based because that's what `.len()` returns
/// and what every caller currently measures; the UI also surfaces this
/// limit as a byte count so the editor's counter matches the validator.
pub const MAX_SKILL_DESCRIPTION_LEN: usize = 1024;
/// Convert an arbitrary human-readable string into a valid skill name, or
/// return `None` if no valid name can be produced (e.g. the input contains
/// no ASCII alphanumeric characters at all).
@ -354,34 +431,54 @@ pub fn slugify_skill_name(input: &str) -> Option<String> {
if slug.is_empty() { None } else { Some(slug) }
}
fn validate_name(name: &str) -> Result<()> {
/// Validate a skill name against the rules enforced by both the loader
/// and the create-skill UI.
///
/// Rules:
/// * non-empty
/// * at most [`MAX_SKILL_NAME_LEN`] bytes
/// * ASCII lowercase letters, digits, and hyphens only
/// * must not start or end with a hyphen — [`slugify_skill_name`]
/// already guarantees this for its output, so requiring it in the
/// validator keeps hand-written `SKILL.md` files consistent with
/// slugifier output
///
/// Error messages are returned as `&'static str` (interpolated at
/// compile time via `formatcp!`) so that UI surfaces can store them in
/// `Option<&'static str>` fields without allocating, and loader callers
/// can convert them to `anyhow::Error` via `anyhow::Error::msg`.
pub fn validate_name(name: &str) -> Result<(), &'static str> {
if name.is_empty() {
anyhow::bail!("Skill name cannot be empty");
return Err("Skill name cannot be empty");
}
if name.len() > MAX_SKILL_NAME_LEN {
anyhow::bail!("Skill name must be at most {MAX_SKILL_NAME_LEN} characters");
return Err(formatcp!(
"Skill name must be at most {MAX_SKILL_NAME_LEN} characters"
));
}
if name.starts_with('-') || name.ends_with('-') {
return Err("Skill name must not start or end with a hyphen");
}
if !name
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
{
anyhow::bail!("Skill name must contain only lowercase letters, numbers, and hyphens");
return Err("Skill name must contain only lowercase letters, numbers, and hyphens");
}
Ok(())
}
fn validate_description(description: &str) -> Result<()> {
if description.is_empty() {
anyhow::bail!("Skill description cannot be empty");
/// Validate a skill description against the rules enforced by both the
/// loader and the create-skill UI.
pub fn validate_description(description: &str) -> Result<(), &'static str> {
if description.trim().is_empty() {
return Err("Skill description cannot be empty");
}
if description.len() > 1024 {
anyhow::bail!("Skill description must be at most 1024 characters");
if description.len() > MAX_SKILL_DESCRIPTION_LEN {
return Err(formatcp!(
"Skill description must be at most {MAX_SKILL_DESCRIPTION_LEN} bytes"
));
}
Ok(())
}
@ -460,53 +557,15 @@ async fn find_skill_files(fs: &Arc<dyn Fs>, directory: &Path) -> Vec<PathBuf> {
.await
}
/// Returns the byte index ONE PAST the end of the closing frontmatter
/// delimiter line in `bytes`, or `None` if no closing delimiter has been
/// seen yet. Used by the chunked reader to know when it has enough
/// bytes to stop pulling from disk.
/// Read `skill_file_path` from disk and parse its frontmatter. The
/// SKILL.md body is parsed away by `parse_skill_frontmatter` and not
/// surfaced here; it's re-read on demand via `read_skill_body` when a
/// skill is actually being loaded for the model.
///
/// Scans for the first `\n---` line followed by `\n`, `\r\n`, or EOF
/// (excluding the opening line itself, which sits at byte 0 and is
/// naturally skipped because we only consider lines following a `\n`).
/// This may overshoot in pathological cases (e.g. `---` inside a quoted
/// YAML string), but `parse_skill_frontmatter`'s candidate-and-validate
/// logic still produces a correct result or a YAML parse error.
fn closing_delimiter_end(bytes: &[u8]) -> Option<usize> {
for (i, &b) in bytes.iter().enumerate() {
if b != b'\n' {
continue;
}
let line_start = i + 1;
if line_start + 3 > bytes.len() {
continue;
}
if &bytes[line_start..line_start + 3] != b"---" {
continue;
}
let after_dashes = line_start + 3;
if after_dashes == bytes.len() {
return Some(after_dashes);
}
if bytes[after_dashes] == b'\n' {
return Some(after_dashes + 1);
}
if after_dashes + 1 < bytes.len()
&& bytes[after_dashes] == b'\r'
&& bytes[after_dashes + 1] == b'\n'
{
return Some(after_dashes + 2);
}
// Line is `---trailing` or `----`; keep scanning.
}
None
}
/// Read just enough of `skill_file_path` from disk to parse its
/// frontmatter. The SKILL.md body is NOT loaded — that's deferred to
/// `read_skill_body`, called only when a skill is actually being
/// materialized for the model. Reading in 4KB chunks keeps the peak
/// memory cost of loading N skills proportional to total frontmatter
/// size, not total file size.
/// We load the whole file in one go rather than streaming up to the
/// closing `---`. `MAX_SKILL_FILE_SIZE` is 100KB and the metadata check
/// below caps the worst case at that, so the peak transient cost is
/// trivially small (≤ `MAX_SKILL_FILE_SIZE` × `SKILL_IO_CONCURRENCY`).
pub async fn load_skill_frontmatter(
fs: Arc<dyn Fs>,
skill_file_path: PathBuf,
@ -514,10 +573,15 @@ pub async fn load_skill_frontmatter(
) -> Result<Skill, SkillLoadError> {
// Short-circuit on oversized files before reading any of their
// contents, so a stray multi-GB file named `SKILL.md` can't OOM the
// app. We only act on a positive signal that the file is too large;
// if metadata fails or is unavailable, we fall through to the read
// loop, which is itself capped at `MAX_SKILL_FILE_SIZE`.
if let Ok(Some(metadata)) = fs.metadata(&skill_file_path).await
// app. If metadata is unavailable, refuse to read.
let metadata = fs
.metadata(&skill_file_path)
.await
.map_err(|e| SkillLoadError {
path: skill_file_path.clone(),
message: format!("Failed to read SKILL.md metadata: {}", e),
})?;
if let Some(metadata) = metadata
&& metadata.len > MAX_SKILL_FILE_SIZE as u64
{
return Err(SkillLoadError {
@ -529,51 +593,15 @@ pub async fn load_skill_frontmatter(
});
}
let mut reader = fs
.open_sync(&skill_file_path)
let content = fs
.load(&skill_file_path)
.await
.map_err(|e| SkillLoadError {
path: skill_file_path.clone(),
message: format!("Failed to open file: {}", e),
message: format!("Failed to read file: {}", e),
})?;
// The chunked read is intentionally synchronous: `Fs::open_sync`
// returns a synchronous `Read` (RealFs uses `std::fs::File`), and
// production callers already wrap `load_skills_from_directory` in
// `cx.background_spawn`, so any blocking happens on the background
// executor — not on the foreground thread. Routing through
// `smol::unblock` instead would schedule the work on smol's blocking
// pool, whose wakeups don't drive GPUI's test scheduler and therefore
// panic with "Parking forbidden" under `TestAppContext`.
let read_result: Result<Vec<u8>, io::Error> = (|| {
let mut accumulated: Vec<u8> = Vec::new();
let mut chunk = [0u8; 4096];
loop {
let n = reader.read(&mut chunk)?;
if n == 0 {
break;
}
accumulated.extend_from_slice(&chunk[..n]);
if closing_delimiter_end(&accumulated).is_some() {
break;
}
if accumulated.len() > MAX_SKILL_FILE_SIZE {
break;
}
}
Ok(accumulated)
})();
let accumulated = read_result.map_err(|e| SkillLoadError {
path: skill_file_path.clone(),
message: format!("Failed to read file: {}", e),
})?;
let content = std::str::from_utf8(&accumulated).map_err(|e| SkillLoadError {
path: skill_file_path.clone(),
message: format!("SKILL.md is not valid UTF-8: {}", e),
})?;
parse_skill_frontmatter(&skill_file_path, content, source).map_err(|e| SkillLoadError {
parse_skill_frontmatter(&skill_file_path, &content, source).map_err(|e| SkillLoadError {
path: skill_file_path.clone(),
message: e.to_string(),
})
@ -600,6 +628,53 @@ pub async fn read_skill_body(
Ok(body.trim().to_string())
}
/// Content of the built-in `create-skill` SKILL.md, embedded at compile time.
const CREATE_SKILL_CONTENT: &str = include_str!("builtin/create-skill/SKILL.md");
/// Returns the set of skills that are compiled into the Zed binary.
pub fn builtin_skills() -> Vec<Skill> {
let mut skills = Vec::new();
if let Ok(skill) = parse_builtin_skill("create-skill", CREATE_SKILL_CONTENT) {
skills.push(skill);
}
skills
}
/// Parse a built-in skill from its embedded SKILL.md content. The skill
/// gets a synthetic `<built-in>` path since it doesn't live on disk.
fn parse_builtin_skill(name: &str, content: &'static str) -> Result<Skill> {
let (metadata, body) = extract_frontmatter(content)?;
validate_name(&metadata.name).map_err(anyhow::Error::msg)?;
validate_description(&metadata.description).map_err(anyhow::Error::msg)?;
let synthetic_dir = PathBuf::from(format!("<built-in>/{}", name));
let synthetic_path = synthetic_dir.join(SKILL_FILE_NAME);
Ok(Skill {
name: metadata.name,
description: metadata.description,
source: SkillSource::BuiltIn,
directory_path: synthetic_dir,
skill_file_path: synthetic_path,
disable_model_invocation: metadata.disable_model_invocation,
embedded_body: Some(body.trim()),
})
}
/// All built-in skills as `(name, raw_content)` pairs. Used by
/// `builtin_skill_content` to serve the full SKILL.md without disk I/O.
const BUILTIN_SKILL_ENTRIES: &[(&str, &str)] = &[("create-skill", CREATE_SKILL_CONTENT)];
/// Look up the full embedded content of a built-in skill by its
/// synthetic file path. Returns `None` if the path doesn't match any
/// built-in skill.
pub fn builtin_skill_content(skill_file_path: &Path) -> Option<&'static str> {
BUILTIN_SKILL_ENTRIES.iter().find_map(|(name, content)| {
let expected = PathBuf::from(format!("<built-in>/{}", name)).join(SKILL_FILE_NAME);
(expected == skill_file_path).then_some(*content)
})
}
/// Returns the global skills directory: `~/.agents/skills`.
///
/// Other agents (e.g. Claude Code) already write skill files into this
@ -657,12 +732,92 @@ pub fn is_agents_skills_path(path: &Path) -> bool {
false
}
/// The `zed://` scheme used by share links.
const SKILL_SHARE_LINK_SCHEME: &str = "zed";
/// The host (the part after `zed://`) that identifies a skill share link.
const SKILL_SHARE_LINK_HOST: &str = "skill";
/// The query parameter that carries the embedded `SKILL.md` payload.
const SKILL_SHARE_LINK_DATA_PARAM: &str = "data";
/// The `zed://` deep-link prefix for a shared skill. Opening a link with this
/// prefix prompts the recipient to review and install the embedded skill.
pub const SKILL_SHARE_LINK_PREFIX: &str =
concatcp!(SKILL_SHARE_LINK_SCHEME, "://", SKILL_SHARE_LINK_HOST);
/// Build a shareable `zed://skill?data=…` link that fully embeds the given
/// `SKILL.md` file contents.
///
/// The contents are base64url-encoded (no padding) so the link is
/// self-contained and URL-safe: the recipient doesn't need the skill to be
/// hosted anywhere. Recover the contents with [`decode_skill_share_link`].
pub fn encode_skill_share_link(skill_file_content: &str) -> String {
use base64::Engine as _;
let data =
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(skill_file_content.as_bytes());
let mut url = Url::parse(SKILL_SHARE_LINK_PREFIX).expect("skill share link prefix is valid");
url.query_pairs_mut()
.append_pair(SKILL_SHARE_LINK_DATA_PARAM, &data);
url.into()
}
/// Recover the `SKILL.md` contents embedded in a `zed://skill?data=…` link
/// produced by [`encode_skill_share_link`].
pub fn decode_skill_share_link(link: &str) -> Result<String> {
use base64::Engine as _;
let url = Url::parse(link).context("skill share link is not a valid URL")?;
anyhow::ensure!(
url.scheme() == SKILL_SHARE_LINK_SCHEME && url.host_str() == Some(SKILL_SHARE_LINK_HOST),
"not a skill share link"
);
let data = url
.query_pairs()
.find_map(|(key, value)| (key == SKILL_SHARE_LINK_DATA_PARAM).then_some(value))
.context("skill share link is missing the `data` parameter")?;
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(data.as_bytes())
.context("skill share link `data` is not valid base64")?;
anyhow::ensure!(
bytes.len() <= MAX_SKILL_FILE_SIZE,
"shared skill exceeds the maximum size of {MAX_SKILL_FILE_SIZE} bytes"
);
let content = String::from_utf8(bytes).context("skill share link `data` is not valid UTF-8")?;
Ok(content)
}
#[cfg(test)]
mod tests {
use super::*;
use fs::FakeFs;
use gpui::TestAppContext;
#[test]
fn test_skill_source_precedence_is_total_and_ordered() {
// Pin the hierarchy: project-local > global > built-in. Every
// override and conflict-resolution site routes through this,
// so the rest of the codebase relies on it being correct.
let built_in = SkillSource::BuiltIn.precedence();
let global = SkillSource::Global.precedence();
let project = SkillSource::ProjectLocal {
worktree_id: SkillScopeId(1),
worktree_root_name: "my-project".into(),
}
.precedence();
assert!(built_in < global, "global must shadow built-in");
assert!(global < project, "project-local must shadow global");
// Two project-local skills from different worktrees tie. The
// "first wins" convention is enforced by the callers, but the
// precedence itself must be equal so neither silently shadows
// the other.
let other_project = SkillSource::ProjectLocal {
worktree_id: SkillScopeId(2),
worktree_root_name: "other-project".into(),
}
.precedence();
assert_eq!(project, other_project);
}
#[test]
fn test_parse_valid_skill() {
let content = r#"---
@ -690,6 +845,26 @@ Do the thing.
assert!(!skill.disable_model_invocation);
}
#[test]
fn test_parse_skill_file_content_returns_body() {
let content = r#"---
name: my-skill
description: A test skill for testing purposes
---
# My Skill
Do the thing.
"#;
let (metadata, body) = parse_skill_file_content(content)
.expect("valid skill content should parse successfully");
assert_eq!(metadata.name, "my-skill");
assert_eq!(metadata.description, "A test skill for testing purposes");
assert_eq!(body.trim(), "# My Skill\n\nDo the thing.");
}
#[test]
fn test_parse_disable_model_invocation_true() {
let content = r#"---
@ -873,12 +1048,8 @@ Content.
SkillSource::Global,
);
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("at most 64 characters")
);
let expected = format!("at most {MAX_SKILL_NAME_LEN} characters");
assert!(result.unwrap_err().to_string().contains(&expected));
}
#[test]
@ -1154,12 +1325,8 @@ Content.
SkillSource::Global,
);
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("at most 1024 characters")
);
let expected = format!("at most {MAX_SKILL_DESCRIPTION_LEN} bytes");
assert!(result.unwrap_err().to_string().contains(&expected));
}
#[test]
@ -1532,6 +1699,7 @@ description: A skill with no body content
directory_path: PathBuf::from("/skills/test-skill"),
skill_file_path: PathBuf::from("/skills/test-skill/SKILL.md"),
disable_model_invocation: false,
embedded_body: None,
};
let summary = SkillSummary::from(&skill);
@ -1759,4 +1927,110 @@ description: A skill with no body content
"project/.AGENTS/SKILLS/foo"
)));
}
#[test]
fn validate_name_accepts_valid_names() {
assert!(validate_name("draft-pr").is_ok());
assert!(validate_name("a").is_ok());
assert!(validate_name("skill1").is_ok());
assert!(validate_name(&"a".repeat(MAX_SKILL_NAME_LEN)).is_ok());
}
#[test]
fn validate_name_rejects_empty() {
assert!(validate_name("").is_err());
}
#[test]
fn validate_name_rejects_uppercase() {
assert!(validate_name("Draft-PR").is_err());
}
#[test]
fn validate_name_rejects_leading_and_trailing_hyphens() {
assert!(validate_name("-draft").is_err());
assert!(validate_name("draft-").is_err());
}
#[test]
fn validate_name_rejects_invalid_chars() {
assert!(validate_name("draft_pr").is_err());
assert!(validate_name("draft pr").is_err());
assert!(validate_name("draft.pr").is_err());
}
#[test]
fn validate_name_rejects_too_long() {
assert!(validate_name(&"a".repeat(MAX_SKILL_NAME_LEN + 1)).is_err());
}
#[test]
fn validate_description_accepts_valid() {
assert!(validate_description("A useful skill").is_ok());
}
#[test]
fn validate_description_rejects_empty_and_whitespace_only() {
assert!(validate_description("").is_err());
assert!(validate_description(" ").is_err());
assert!(validate_description("\t\n ").is_err());
}
#[test]
fn validate_description_rejects_too_long() {
assert!(validate_description(&"a".repeat(MAX_SKILL_DESCRIPTION_LEN + 1)).is_err());
}
#[test]
fn validate_description_length_is_measured_in_bytes() {
// "é" is 2 bytes in UTF-8. A string of MAX/2 + 1 "é" characters has
// only ~MAX/2 + 1 chars but exceeds MAX bytes, so it must be
// rejected by a byte-based validator (and accepted by a char-based
// one). This regression-tests the byte semantics that the loader
// and UI both rely on.
let chars = MAX_SKILL_DESCRIPTION_LEN / 2 + 1;
let description = "é".repeat(chars);
assert!(description.chars().count() <= MAX_SKILL_DESCRIPTION_LEN);
assert!(description.len() > MAX_SKILL_DESCRIPTION_LEN);
assert!(validate_description(&description).is_err());
}
#[test]
fn slugify_output_always_passes_validate_name() {
for input in [
"foo",
"Foo Bar",
"rock & roll",
"---weird---",
"a".repeat(200).as_str(),
] {
if let Some(slug) = slugify_skill_name(input) {
assert!(
validate_name(&slug).is_ok(),
"slug {slug:?} from {input:?} failed validate_name"
);
}
}
}
#[test]
fn skill_share_link_round_trips() {
let content =
"---\nname: my-skill\ndescription: Does a thing.\n---\n\n## Steps\n\nDo the thing.\n";
let link = encode_skill_share_link(content);
let data = link
.strip_prefix("zed://skill?data=")
.expect("link should start with the skill share prefix");
// base64url (no-pad) output must not require percent-encoding.
assert!(!data.contains('+') && !data.contains('/') && !data.contains('='));
assert_eq!(decode_skill_share_link(&link).unwrap(), content);
}
#[test]
fn decode_skill_share_link_rejects_non_skill_links() {
assert!(decode_skill_share_link("zed://settings/agent.skills").is_err());
assert!(decode_skill_share_link("zed://skill").is_err());
assert!(decode_skill_share_link("zed://skill?other=1").is_err());
assert!(decode_skill_share_link("zed://skill?data=!!!notbase64").is_err());
}
}

View file

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

View file

@ -30,10 +30,10 @@ acp_thread.workspace = true
action_log.workspace = true
agent-client-protocol.workspace = true
agent.workspace = true
agent_skills.workspace = true
async-channel.workspace = true
agent_servers.workspace = true
agent_settings.workspace = true
agent_skills.workspace = true
ai_onboarding.workspace = true
anyhow.workspace = true
heapless.workspace = true
@ -69,6 +69,7 @@ language.workspace = true
language_model.workspace = true
language_models.workspace = true
log.workspace = true
lru.workspace = true
lsp.workspace = true
markdown.workspace = true
menu.workspace = true
@ -88,7 +89,7 @@ release_channel.workspace = true
remote.workspace = true
remote_connection.workspace = true
rope.workspace = true
rules_library.workspace = true
skill_creator.workspace = true
schemars.workspace = true
serde.workspace = true
serde_json.workspace = true
@ -145,3 +146,4 @@ tempfile.workspace = true
vim.workspace = true
tree-sitter-md.workspace = true
unindent.workspace = true
terminal = { workspace = true, features = ["test-support"] }

View file

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

View file

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

View file

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

File diff suppressed because it is too large Load diff

View file

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

View file

@ -26,6 +26,7 @@ mod model_selector_popover;
mod profile_selector;
mod terminal_codegen;
mod terminal_inline_assistant;
pub mod terminal_thread_metadata_store;
#[cfg(any(test, feature = "test-support"))]
pub mod test_support;
mod thread_import;
@ -42,10 +43,12 @@ use ::ui::IconName;
use agent_client_protocol::schema as acp;
use agent_settings::{AgentProfileId, AgentSettings};
use command_palette_hooks::CommandPaletteFilter;
use feature_flags::{FeatureFlagAppExt as _, SkillsFeatureFlag};
use editor::{Editor, SelectionEffects, scroll::Autoscroll};
use feature_flags::FeatureFlagAppExt as _;
use fs::Fs;
use gpui::{
Action, App, Context, Entity, ImageSource, Resource, SharedString, SharedUri, Window, actions,
Action, App, Context, Entity, ImageSource, Resource, SharedString, SharedUri, TaskExt, Window,
actions,
};
use language::{
LanguageRegistry,
@ -55,7 +58,8 @@ use language_model::{
ConfiguredModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
};
use project::{AgentId, DisableAiSettings};
use prompt_store::{PromptBuilder, rules_to_skills_migration};
use prompt_store::{self, PromptBuilder, rules_to_skills_migration};
use rope::Point;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use settings::{LanguageModelSelection, Settings as _, SettingsStore, SidebarSide};
@ -111,6 +115,42 @@ pub(crate) fn resolve_agent_image(
None
}
pub(crate) fn open_abs_path_at_point(
workspace: &mut Workspace,
abs_path: PathBuf,
point: Point,
window: &mut Window,
cx: &mut Context<Workspace>,
) -> bool {
let project = workspace.project();
let Some(path) = project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
else {
return false;
};
let item = workspace.open_path(path, None, true, window, cx);
window
.spawn(cx, async move |cx| {
let Some(editor) = item.await?.downcast::<Editor>() else {
return Ok(());
};
let range = point..point;
editor
.update_in(cx, |editor, window, cx| {
editor.change_selections(
SelectionEffects::scroll(Autoscroll::center()),
window,
cx,
|selections| selections.select_ranges([range]),
);
})
.ok();
anyhow::Ok(())
})
.detach_and_log_err(cx);
true
}
pub const DEFAULT_THREAD_TITLE: &str = "New Agent Thread";
const PARALLEL_AGENT_LAYOUT_BACKFILL_KEY: &str = "parallel_agent_layout_backfilled";
@ -159,6 +199,8 @@ actions!(
ArchiveSelectedThread,
/// Removes the currently selected thread.
RemoveSelectedThread,
/// Renames the currently selected thread.
RenameSelectedThread,
/// Starts a chat conversation with follow-up enabled.
ChatWithFollow,
/// Cycles to the next inline assist suggestion.
@ -203,6 +245,8 @@ actions!(
ResetTrialUpsell,
/// Resets the trial end upsell notification.
ResetTrialEndUpsell,
/// Re-enables the fast mode warning for every provider and model.
ResetFastModeWarnings,
/// Opens the "Add Context" menu in the message editor.
OpenAddContextMenu,
/// Interrupts the current generation and sends the message immediately.
@ -243,6 +287,8 @@ actions!(
ScrollOutputToNextMessage,
/// Import agent threads from other Zed release channels (e.g. Preview, Nightly).
ImportThreadsFromOtherChannels,
/// Starts a new terminal thread.
NewTerminalThread,
]
);
@ -504,7 +550,8 @@ pub fn init(
cx: &mut App,
) {
agent::ThreadStore::init_global(cx);
rules_library::init(cx);
prompt_store::init(cx);
skill_creator::init(cx);
if !is_eval {
// Initializing the language model from the user settings messes with the eval, so we only initialize them when
// we're not running inside of the eval.
@ -513,6 +560,7 @@ pub fn init(
agent_panel::init(cx);
context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
thread_metadata_store::init(cx);
terminal_thread_metadata_store::init(cx);
inline_assistant::init(fs.clone(), prompt_builder.clone(), cx);
terminal_inline_assistant::init(fs.clone(), prompt_builder, cx);
@ -552,32 +600,6 @@ pub fn init(
);
})
.detach();
cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
workspace.register_action(
|workspace: &mut Workspace,
_: &zed_actions::agent::OpenRulesToSkillsMigrationInfo,
window: &mut Window,
cx: &mut Context<Workspace>| {
// The banner is the only intended entry point and is
// gated on the skills flag, but dispatch from the
// command palette or a keybind is still possible — only
// open the explainer if the flag is enabled so it never
// surfaces outside its intended audience.
//
// Race note: `has_flag` returns false before server
// flags are received, so a dispatch during that brief
// window is a no-op even for users who genuinely have
// the flag. The banner itself has the same race — it
// stays hidden until flags arrive — so a user who can
// see the banner has, by definition, already passed it.
if cx.has_flag::<SkillsFeatureFlag>() {
crate::ui::RulesToSkillsModal::toggle(workspace, window, cx);
}
},
);
})
.detach();
cx.observe_new(ManageProfilesModal::register).detach();
cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
workspace.register_action(
@ -606,10 +628,16 @@ pub fn init(
})
.detach();
// Once the `skills` feature flag has resolved, kick off the one-time
// migration of non-Default Rules to global Skills. Idempotent and
// self-gated on the flag, so it's safe to call on every flag-ready
// notification (and a no-op for users without the flag).
// Kick off the one-time migration of non-Default Rules to global
// Skills, deferred until server feature flags arrive.
//
// The migration itself is idempotent and no longer gated on a flag,
// but the deferral via `on_flags_ready` still matters: the migration
// writes to the on-disk `GlobalKeyValueStore`, which dispatches work
// on the `sqlezWorker` background thread. In `gpui::test` contexts,
// server flags are never received, so this callback never fires —
// which keeps that sqlite worker activity from racing with the
// `TestScheduler` and tripping its non-determinism panic.
{
let fs = fs.clone();
cx.on_flags_ready(move |_, cx| {
@ -651,12 +679,6 @@ fn update_command_palette_filter(cx: &mut App) {
.edit_predictions
.provider;
// The Skills feature flag is loaded asynchronously, so this value may
// be `false` before flags resolve. `update_command_palette_filter`
// gets re-run from `cx.on_flags_ready` (see `init`), which means the
// filter is reapplied with the correct value once flags arrive.
let skills_enabled = cx.has_flag::<SkillsFeatureFlag>();
CommandPaletteFilter::update_global(cx, |filter, _| {
use editor::actions::{
AcceptEditPrediction, AcceptNextLineEditPrediction, AcceptNextWordEditPrediction,
@ -666,7 +688,6 @@ fn update_command_palette_filter(cx: &mut App) {
TypeId::of::<AcceptEditPrediction>(),
TypeId::of::<AcceptNextWordEditPrediction>(),
TypeId::of::<AcceptNextLineEditPrediction>(),
TypeId::of::<AcceptEditPrediction>(),
TypeId::of::<ShowEditPrediction>(),
TypeId::of::<NextEditPrediction>(),
TypeId::of::<PreviousEditPrediction>(),
@ -674,6 +695,10 @@ fn update_command_palette_filter(cx: &mut App) {
];
let open_rules_library_action = [TypeId::of::<zed_actions::assistant::OpenRulesLibrary>()];
let skill_creator_actions = [
TypeId::of::<zed_actions::assistant::OpenSkillCreator>(),
TypeId::of::<zed_actions::assistant::CreateSkillFromUrl>(),
];
if disable_ai {
filter.hide_namespace("agent");
@ -724,15 +749,17 @@ fn update_command_palette_filter(cx: &mut App) {
filter.show_namespace("multi_workspace");
}
// Hide `assistant: open rules library` when Skills are enabled —
// Rules are surfaced through the Skills UI in that case. Applied
// after the disable-ai / agent-enabled branches so it overrides
// the `show_namespace("assistant")` call above without affecting
// the rest of that namespace's actions.
if !disable_ai && skills_enabled {
// Hide `assistant: open rules library` — Rules are surfaced
// through the Skills UI now. Applied after the disable-ai /
// agent-enabled branches so it overrides the
// `show_namespace("assistant")` call above without affecting the
// rest of that namespace's actions.
if !disable_ai {
filter.hide_action_types(&open_rules_library_action);
filter.show_action_types(skill_creator_actions.iter());
} else {
filter.show_action_types(open_rules_library_action.iter());
filter.hide_action_types(&skill_creator_actions);
}
});
}
@ -870,6 +897,26 @@ mod tests {
!filter.is_hidden(&NewThread),
"NewThread should be visible by default"
);
assert!(
!filter.is_hidden(&NewTerminalThread),
"NewTerminalThread should be visible by default"
);
assert!(
!filter.is_hidden(&zed_actions::assistant::OpenSkillCreator),
"OpenSkillCreator should be visible by default"
);
assert!(
!filter.is_hidden(&zed_actions::assistant::CreateSkillFromUrl),
"CreateSkillFromUrl should be visible by default"
);
assert!(
!filter.is_hidden(&zed_actions::assistant::OpenGlobalAgentsMdRules),
"OpenGlobalAgentsMdRules should be visible by default"
);
assert!(
!filter.is_hidden(&zed_actions::assistant::OpenProjectAgentsMdRules),
"OpenProjectAgentsMdRules should be visible by default"
);
});
// Disable agent
@ -889,6 +936,18 @@ mod tests {
filter.is_hidden(&NewThread),
"NewThread should be hidden when agent is disabled"
);
assert!(
filter.is_hidden(&NewTerminalThread),
"NewTerminalThread should be hidden when agent is disabled"
);
assert!(
filter.is_hidden(&zed_actions::assistant::OpenGlobalAgentsMdRules),
"OpenGlobalAgentsMdRules should be hidden when agent is disabled"
);
assert!(
filter.is_hidden(&zed_actions::assistant::OpenProjectAgentsMdRules),
"OpenProjectAgentsMdRules should be hidden when agent is disabled"
);
});
// Test EditPredictionProvider

View file

@ -12,7 +12,9 @@ use futures::{
stream::BoxStream,
};
use gpui::{App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Subscription, Task};
use language::{Buffer, IndentKind, LanguageName, Point, TransactionId, line_diff};
use language::{
Buffer, BufferEditSource, IndentKind, LanguageName, Point, TransactionId, line_diff,
};
use language_model::{
CompletionIntent, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
@ -978,7 +980,7 @@ impl CodegenAlternative {
buffer.finalize_last_transaction(cx);
buffer.start_transaction(cx);
buffer.edit(edits, None, cx);
buffer.end_transaction(cx)
buffer.end_transaction_with_source(BufferEditSource::Agent, cx)
});
if let Some(transaction) = transaction {

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