Compare commits
210 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
09165c15dc | ||
|
|
e2e7a6769e | ||
|
|
5d3b9e467e | ||
|
|
06826ef10f | ||
|
|
7f4a99aa95 | ||
|
|
122619624d | ||
|
|
2ea99a81f1 | ||
|
|
c30d18b10d | ||
|
|
18051ab399 | ||
|
|
654a864b3a | ||
|
|
5fba9b0cba | ||
|
|
906bff792c | ||
|
|
c029cc4354 | ||
|
|
0bafd1938c | ||
|
|
b7b1d1a2c7 | ||
|
|
a1d2ef6514 | ||
|
|
81f818aa86 | ||
|
|
f49be143f3 | ||
|
|
3eab273b85 | ||
|
|
85f8bf7393 | ||
|
|
da87558cc2 | ||
|
|
6bca2136a1 | ||
|
|
ef5da3ccc2 | ||
|
|
a3669a29e6 | ||
|
|
3d9852ae04 | ||
|
|
46845bf2f5 | ||
|
|
e4b81180c1 | ||
|
|
aeb5d6d7ff | ||
|
|
486e5f7cdd | ||
|
|
d3070bbc0d | ||
|
|
e5f5767d2c | ||
|
|
12aacf3cea | ||
|
|
b32570d931 | ||
|
|
59d8766f35 | ||
|
|
27c566c212 | ||
|
|
2bba4e2220 | ||
|
|
ec64ba3e69 | ||
|
|
b3d93d4474 | ||
|
|
a6b0ee9f36 | ||
|
|
3bb2f2a61d | ||
|
|
24fd1015f0 | ||
|
|
ef5606bb61 | ||
|
|
5abe4bcbc6 | ||
|
|
d139a871db | ||
|
|
830414004a | ||
|
|
bc64e1f955 | ||
|
|
d74e47ea51 | ||
|
|
f0ed342c19 | ||
|
|
92b0efeee0 | ||
|
|
4d6a3c7e11 | ||
|
|
b8c853a63d | ||
|
|
8042408df4 | ||
|
|
518502e5ef | ||
|
|
6049ceaecf | ||
|
|
6726b15fce | ||
|
|
bedfe32fdc | ||
|
|
58f84cf041 | ||
|
|
60374460f2 | ||
|
|
b141288fb0 | ||
|
|
777e16dd1f | ||
|
|
f0341c96a1 | ||
|
|
ffbda20db1 | ||
|
|
c3b9cacc0e | ||
|
|
5ec1ce7cd0 | ||
|
|
6e58a92713 | ||
|
|
887e3782a8 | ||
|
|
652f13c7ce | ||
|
|
1226e28dd3 | ||
|
|
cbaf8e4d9d | ||
|
|
c19c89a30a | ||
|
|
1d029c5ff5 | ||
|
|
bf4e559347 | ||
|
|
6472f018a6 | ||
|
|
7ae24463e1 | ||
|
|
710228e3dd | ||
|
|
6afac23e4a | ||
|
|
9b4737b0d7 | ||
|
|
9a7a5d685d | ||
|
|
b49e5f19b9 | ||
|
|
32f2593047 | ||
|
|
63f725e8d6 | ||
|
|
aa6062edaf | ||
|
|
bc6a483e5c | ||
|
|
32d0737318 | ||
|
|
80a4042ff5 | ||
|
|
0464de8fdd | ||
|
|
a65e677376 | ||
|
|
f838eb1248 | ||
|
|
ceff1b227b | ||
|
|
d2cbf930f7 | ||
|
|
a55e3e99f5 | ||
|
|
a9296b9a5a | ||
|
|
a718a2bde6 | ||
|
|
b328711bbe | ||
|
|
fe48ef424c | ||
|
|
c171bbac44 | ||
|
|
f839f8e108 | ||
|
|
6555ac3d04 | ||
|
|
75c17a6ee9 | ||
|
|
a1d019bdd8 | ||
|
|
1965d69819 | ||
|
|
88a54a2683 | ||
|
|
5e717a06cd | ||
|
|
e25458243b | ||
|
|
867e51189b | ||
|
|
4129fc87d8 | ||
|
|
53ed11b2af | ||
|
|
7103c8c8e6 | ||
|
|
1025b13951 | ||
|
|
6df9ae9f8f | ||
|
|
6e9f461cf8 | ||
|
|
efacf30294 | ||
|
|
c551ec93b0 | ||
|
|
533d3d534b | ||
|
|
5618485134 | ||
|
|
4bee412118 | ||
|
|
b20cd411ec | ||
|
|
a8966695ee | ||
|
|
eb944cfd7a | ||
|
|
b5b52ada0c | ||
|
|
b1bfde9e9d | ||
|
|
e7bbfd5223 | ||
|
|
a60cf568b7 | ||
|
|
16ae765da8 | ||
|
|
158fcac15e | ||
|
|
511d2c43d2 | ||
|
|
1a0b54616b | ||
|
|
a0ee9fb431 | ||
|
|
277b22f0d2 | ||
|
|
5139a6bfc1 | ||
|
|
1dac14c53a | ||
|
|
63ff99795c | ||
|
|
49fe1fcad5 | ||
|
|
281cfdd7a2 | ||
|
|
707c00b474 | ||
|
|
3e77442f2e | ||
|
|
a5457029cc | ||
|
|
2984fafdf2 | ||
|
|
7ef1fa1380 | ||
|
|
a6780a5a47 | ||
|
|
b72e57da65 | ||
|
|
2e20860461 | ||
|
|
bcfbf669bd | ||
|
|
6a747984d3 | ||
|
|
a8cdf1d869 | ||
|
|
216980f671 | ||
|
|
786eb24521 | ||
|
|
bb460d5f26 | ||
|
|
453b020866 | ||
|
|
8309bc4098 | ||
|
|
001d94d149 | ||
|
|
bc41407a5e | ||
|
|
d3a9fd96a3 | ||
|
|
13e7c11768 | ||
|
|
d066a73609 | ||
|
|
a74a96e25d | ||
|
|
8bfe32010c | ||
|
|
eb2223c080 | ||
|
|
b1180f749c | ||
|
|
b0911ccc9e | ||
|
|
450206e49d | ||
|
|
de529b5677 | ||
|
|
835cd847ef | ||
|
|
2c26e5e544 | ||
|
|
d3e27abc87 | ||
|
|
cfd0461b5a | ||
|
|
949d993146 | ||
|
|
dee596fa96 | ||
|
|
91531fad6d | ||
|
|
e2a1c4ce0c | ||
|
|
d5cf9a65d2 | ||
|
|
da74e24a79 | ||
|
|
776b8304b1 | ||
|
|
78749a4c2a | ||
|
|
6753eb1736 | ||
|
|
ba350974af | ||
|
|
da66f95237 | ||
|
|
f78f6da255 | ||
|
|
77cbba9b1a | ||
|
|
1399540715 | ||
|
|
f0cbb42fa6 | ||
|
|
d61ffb8e6b | ||
|
|
7ec36d3661 | ||
|
|
7afcc87927 | ||
|
|
0307c7fb35 | ||
|
|
33eb2d83ed | ||
|
|
560f784776 | ||
|
|
8d28ca5c01 | ||
|
|
78b5c0e774 | ||
|
|
e024200c67 | ||
|
|
800706d7a8 | ||
|
|
70733ceb6e | ||
|
|
0ec218fa5f | ||
|
|
f15d759bf6 | ||
|
|
b13849d04f | ||
|
|
97c25c31e4 | ||
|
|
c84c22dab5 | ||
|
|
4558d14cf8 | ||
|
|
7f7c21536e | ||
|
|
ddb847d03a | ||
|
|
ee5c7b6d45 | ||
|
|
b3ce9a49f7 | ||
|
|
251456cf20 | ||
|
|
0042fb5850 | ||
|
|
2b506483b2 | ||
|
|
c7b9039e4b | ||
|
|
814443a466 | ||
|
|
d2953a2b57 | ||
|
|
bb63046a08 | ||
|
|
3a81f8e9ab |
160
.agents/skills/gpui-test/SKILL.md
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
---
|
||||
name: gpui-test
|
||||
description: >-
|
||||
Use when writing, debugging, or reproducing GPUI tests in Zed, including
|
||||
gpui::test arguments, TestAppContext parameters, scheduler seeds,
|
||||
ITERATIONS/SEED reproduction, parking failures, and pending task traces.
|
||||
---
|
||||
|
||||
# GPUI Test Debugging
|
||||
|
||||
Use this skill when the user asks about `#[gpui::test]`, GPUI test seeds or iterations, deterministic scheduler failures, parking/pending task failures, or how to reproduce a flaky GPUI test.
|
||||
|
||||
## What `#[gpui::test]` does
|
||||
|
||||
`#[gpui::test]` expands to a normal Rust `#[test]`, so it runs under standard Rust test runners such as `cargo test` and `cargo nextest`.
|
||||
|
||||
It wraps the body in GPUI's deterministic test dispatcher/scheduler and can run the same test multiple times with different seeds. The seed controls scheduler task interleavings and any `StdRng` argument injected into the test.
|
||||
|
||||
The macro supports both synchronous and asynchronous tests.
|
||||
|
||||
### Supported function arguments
|
||||
|
||||
The macro recognizes arguments by type name:
|
||||
|
||||
| Test kind | Supported arguments |
|
||||
| --- | --- |
|
||||
| Sync and async | `&TestAppContext`, `&mut TestAppContext`, `StdRng` |
|
||||
| Async only | `BackgroundExecutor` |
|
||||
| Sync only | `&App`, `&mut App` |
|
||||
|
||||
`StdRng` is seeded from the current GPUI test seed, and `BackgroundExecutor` is backed by the same deterministic test dispatcher.
|
||||
|
||||
### Attribute arguments
|
||||
|
||||
Use these forms on `#[gpui::test(arguments)]`:
|
||||
|
||||
- No arguments: runs once with seed `0`, unless `SEED` is set.
|
||||
- `seed = N`: adds a single explicit seed.
|
||||
- `seeds(...)`: adds multiple explicit seeds.
|
||||
- `iterations = N`: runs sequential seeds starting at `0` by default.
|
||||
- `retries = N`: retries a failing run up to `N` times before surfacing the failure.
|
||||
- `on_failure = "path::to::function"`: calls the function after final failure, before resuming the panic.
|
||||
- `iterations` can be combined with explicit `seed` / `seeds`; explicit seeds are appended to the `0..iterations` range.
|
||||
- If the `SEED` environment variable is set, it takes precedence over explicit seeds.
|
||||
- With `SEED=N` and `ITERATIONS=M` or `iterations = M`, the harness runs seeds `N..N+M`.
|
||||
|
||||
## Environment variables
|
||||
|
||||
### GPUI test macro / scheduler execution
|
||||
|
||||
- `SEED=<u64>` — chooses the scheduler seed. Use this to reproduce a failure printed as `failing seed: N`. It also seeds injected `StdRng` arguments. For `#[gpui::property_test]`, it controls the scheduler seed and GPUI applies it to the proptest config for deterministic case generation.
|
||||
- `ITERATIONS=<usize>` — overrides the `iterations = ...` value at runtime. Use to sweep many seeds without editing the test.
|
||||
- `PENDING_TRACES=1` or `PENDING_TRACES=true` — captures and prints pending task traces when the test scheduler panics with `Parking forbidden`. Use this when `run_until_parked()` or teardown reports pending work.
|
||||
- `GPUI_RUN_UNTIL_PARKED_LOG=1` — logs when `allow_parking()` is enabled. Use to find tests that explicitly permit parking/pending work.
|
||||
- `DEBUG_SCHEDULER=1` — prints scheduler clock/timer debugging from `scheduler::TestScheduler`.
|
||||
|
||||
### Lower-level scheduler tests
|
||||
|
||||
- `SCHEDULER_NONINTERACTIVE=1` — suppresses interactive seed progress output in `scheduler::TestScheduler::many`. This does not affect the `#[gpui::test]` harness path.
|
||||
|
||||
### General Rust test debugging vars often useful with GPUI tests
|
||||
|
||||
- `RUST_BACKTRACE=1` or `RUST_BACKTRACE=full` — show panic backtraces.
|
||||
- `RUST_LOG=<filter>` — enable logs when the test initializes logging.
|
||||
- `ZED_HEADLESS=1` — forces GPUI platform guessing toward headless mode; useful for tests that otherwise interact with platform/window setup.
|
||||
|
||||
Prefer env vars over editing the test when narrowing a reproduction.
|
||||
|
||||
## Reproducing a specific GPUI test
|
||||
|
||||
1. Identify the crate/package and test name.
|
||||
|
||||
2. Run the narrowest test filter first, skip to 3. if a failing seed is known.
|
||||
|
||||
```sh
|
||||
cargo -q test -p <crate-name> <test_name> -- --nocapture
|
||||
```
|
||||
|
||||
3. If the failure mentions a seed, rerun exactly that seed.
|
||||
|
||||
```sh
|
||||
SEED=<seed> cargo -q test -p <crate-name> <test_name> -- --nocapture
|
||||
```
|
||||
|
||||
4. If the failure is flaky and no seed is known, sweep seeds.
|
||||
|
||||
```sh
|
||||
ITERATIONS=100 cargo -q test -p <crate-name> <test_name> -- --nocapture
|
||||
```
|
||||
|
||||
When the harness prints `failing seed: <seed>`, switch to `SEED=<seed>` for all future debugging.
|
||||
|
||||
5. If the failure is `Parking forbidden`, rerun with pending traces.
|
||||
|
||||
```sh
|
||||
PENDING_TRACES=1 cargo -q test -p <crate-name> <test_name> -- --nocapture
|
||||
```
|
||||
|
||||
If a failing seed was printed or is already known, include it too:
|
||||
|
||||
```sh
|
||||
SEED=<seed> PENDING_TRACES=1 cargo -q test -p <crate-name> <test_name> -- --nocapture
|
||||
```
|
||||
|
||||
Inspect the pending traces for a task that was spawned but not awaited, detached, completed, or intentionally allowed to park.
|
||||
|
||||
6. If timing or timer advancement is involved, prefer GPUI scheduler timers in tests:
|
||||
|
||||
```rust
|
||||
cx.background_executor().timer(duration).await;
|
||||
```
|
||||
|
||||
Avoid `smol::Timer::after(...)` in GPUI tests that rely on `run_until_parked()`, because GPUI's scheduler may not track it.
|
||||
|
||||
7. Minimize the reproduction.
|
||||
- Keep the failing `SEED` fixed.
|
||||
- Reduce `ITERATIONS` to `1` or remove it once a seed is known.
|
||||
- Remove unrelated setup only after confirming the same seed still fails.
|
||||
- Preserve scheduler-sensitive awaits/yields; removing them can mask the bug.
|
||||
- If randomness is test-controlled via `StdRng`, log or assert the generated scenario after fixing the scheduler seed.
|
||||
|
||||
8. Validate the fix.
|
||||
- Run the fixed seed.
|
||||
- Run a modest seed sweep, e.g. `ITERATIONS=20`, if the failure was scheduler-sensitive.
|
||||
- Run the relevant crate's test filter or broader suite if the touched code has shared behavior.
|
||||
|
||||
## Common diagnosis patterns
|
||||
|
||||
### Seed-dependent assertion failure
|
||||
|
||||
Likely caused by a scheduler interleaving or by `StdRng`-driven test data. Fix `SEED`, reproduce, and inspect which task or generated scenario differs.
|
||||
|
||||
### `Parking forbidden`
|
||||
|
||||
Usually means a foreground/background task is still pending when the scheduler expected the test to make progress or finish. Look for:
|
||||
|
||||
- A task that should be awaited but was dropped.
|
||||
- A task that should be detached with error logging.
|
||||
- A timer or receiver that is waiting forever.
|
||||
- A missing `cx.run_until_parked()` after triggering async work in a test.
|
||||
- A missing `cx.advance_clock(...)` to wait for debounced work in a test.
|
||||
- Use of non-GPUI timers or executors that the test scheduler cannot drive.
|
||||
|
||||
Rerun with `PENDING_TRACES=1` before changing code.
|
||||
|
||||
### Non-determinism / wrong thread
|
||||
|
||||
The scheduler can report activity from an unexpected thread. Look for work escaping GPUI's foreground/background executors, direct thread spawns, or external async runtimes not controlled by the test dispatcher.
|
||||
|
||||
### Tests pass alone but fail in sweeps
|
||||
|
||||
Use the failing seed from sweep output. Avoid assuming test order unless the runner is explicitly serial. Check globals, leaked entities/tasks, and state not reset by test initialization.
|
||||
|
||||
## Writing GPUI tests
|
||||
|
||||
- Prefer `#[gpui::test]` for tests that need `TestAppContext`, deterministic executors, fake time, or scheduler interleaving coverage.
|
||||
- Add `iterations = N` when the test is intentionally checking interleavings.
|
||||
- Use `StdRng` as a test argument when randomized test data should follow the same seed as the scheduler.
|
||||
- Use `cx.background_executor().timer(duration).await` for delays/timeouts in GPUI tests.
|
||||
- Do not add or increase `retries` while fixing a test unless the user explicitly asks or the test already documents why probabilistic tolerance is intentional. Retries can mask the failure instead of fixing it.
|
||||
175
.agents/skills/zed-cherry-pick/SKILL.md
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
---
|
||||
name: zed-cherry-pick
|
||||
description: Cherry-pick one or more merged PRs and/or commits into Zed's `preview` or `stable` release branch. Use this whenever the user mentions cherry-picking to preview/stable, a failed cherry-pick run, or wants to manually port fix(es) into a release branch.
|
||||
---
|
||||
|
||||
# Zed Cherry-Pick
|
||||
|
||||
Zed ships from two long-lived release branches that live on `origin`:
|
||||
|
||||
- `preview` channel → branch like `v1.4.x`
|
||||
- `stable` channel → branch like `v1.3.x`
|
||||
|
||||
The version numbers change with each release. **Never hardcode them — always discover the current mapping** (see [Finding the target branch](#finding-the-target-branch)).
|
||||
|
||||
A merged PR on `main` gets ported to a release branch by `script/cherry-pick`, normally driven by the `cherry_pick` GitHub Actions workflow. When that workflow fails (almost always a merge conflict), use this skill to finish the job locally and open the cherry-pick PR by hand.
|
||||
|
||||
## When to use
|
||||
|
||||
Use this when the user asks to cherry-pick one or more commits and/or Pull Requests (by number or URL) to `preview` or `stable`.
|
||||
Optionally, the user may specify whether to resolve merge conflicts; if unspecified, attempt the cherry-pick, and then if there are merge conflicts in practice, stop and inform the user that there are merge conflicts and offer to resolve them. (Users may prefer to resolve the merge conflicts themselves before continuing.)
|
||||
|
||||
## The script you're emulating
|
||||
|
||||
The canonical procedure lives in `script/cherry-pick` and the `cherry_pick` GitHub Actions workflow. Read the script first if anything looks off — your local steps must produce the same branch name, PR title, and PR body it would.
|
||||
|
||||
Signature: `script/cherry-pick <branch-name> <commit-sha> <channel>`
|
||||
|
||||
- `<branch-name>` is the release branch (e.g. `v1.4.x`), **not** the channel name.
|
||||
- `<channel>` is `preview` or `stable`, used only for display text in the PR title/body.
|
||||
|
||||
It creates a local branch named `cherry-pick-<branch-name>-<short-sha>` (the short SHA is the first 8 chars of the commit), force-pushes it to `origin`, and opens a PR.
|
||||
|
||||
## Finding the target branch
|
||||
|
||||
The channel→branch mapping changes every release. Find the current one by inspecting the most recent `cherry_pick` workflow runs:
|
||||
|
||||
```
|
||||
gh run list --workflow=cherry_pick.yml --limit 30 --json displayTitle,databaseId
|
||||
# pick a recent run for the channel you want, then:
|
||||
gh run view <id> --log 2>&1 | grep -E "BRANCH:|CHANNEL:"
|
||||
```
|
||||
|
||||
A successful run prints both `BRANCH:` and `CHANNEL:` env vars; that's your mapping.
|
||||
|
||||
## Procedure
|
||||
|
||||
### 1. Gather context
|
||||
|
||||
You need three things: the **merge commit SHA**, the **target branch**, and the **channel name**.
|
||||
|
||||
If the user requested multiple PRs and/or commits, gather the metadata for all of them first and cherry-pick them in the order they landed on `main`, oldest to newest. For PRs, order by `mergedAt`; for raw commits, use their order on `main` when available, otherwise commit date. This tends to reduce avoidable conflicts because later changes may depend on earlier ones, but it does not guarantee a conflict-free cherry-pick when the release branch has diverged.
|
||||
|
||||
```
|
||||
gh pr view <PR_NUMBER> --json title,number,mergeCommit,mergedAt,url
|
||||
```
|
||||
|
||||
If the user said the workflow failed, fetch its log to see exactly which command failed and which file conflicted:
|
||||
|
||||
```
|
||||
gh run list --workflow=cherry_pick.yml --limit 10 --json databaseId,displayTitle,status,conclusion
|
||||
gh run view <failed_run_id> --log-failed
|
||||
```
|
||||
|
||||
The failed-run log also confirms the `BRANCH` and `COMMIT` the workflow used — handy if there's any ambiguity.
|
||||
|
||||
### 2. Reproduce the script's setup locally
|
||||
|
||||
The repository may be a worktree (check `.git` — if it's a file, you're in a worktree pointing at a shared gitdir). That's fine; just operate normally.
|
||||
|
||||
```
|
||||
git --no-pager fetch origin <branch-name> <commit-sha>
|
||||
git checkout --force origin/<branch-name> -B cherry-pick-<branch-name>-<short-sha>
|
||||
git cherry-pick <commit-sha>
|
||||
```
|
||||
|
||||
The branch name **must** match `cherry-pick-<branch-name>-<short-sha>` exactly (script convention; reviewers and tooling expect it).
|
||||
|
||||
### 3. Check for missing prerequisite cherry-picks
|
||||
|
||||
If the cherry-pick conflicts, do not immediately resolve the conflicts manually.
|
||||
|
||||
First determine whether the conflict is likely caused by other PRs or commits that are already on `main` but missing from the release branch. If so, point out those candidate prerequisite PRs/commits to the user, including PR links, and offer to either resolve the conflicts manually or let the user run the GitHub cherry-pick workflow for those commits first.
|
||||
|
||||
If the user wants to run the workflow for the missing prerequisites, stop here. This often keeps cherry-picks clean and eligible for automatic approval.
|
||||
|
||||
Only resolve conflicts manually if:
|
||||
- no likely missing prerequisites are found, or
|
||||
- the user chooses manual conflict resolution instead of cherry-picking the prerequisites first.
|
||||
|
||||
### 4. Resolve the conflicts manually
|
||||
|
||||
Do this only after checking for missing prerequisite cherry-picks.
|
||||
|
||||
- Inspect every conflicted file with `grep -n '<<<<<<<\\|>>>>>>>\\|=======' <path>` to find the markers.
|
||||
- Conflicts are usually `diff3` style with three sections: HEAD (release branch), `||||||| parent of <sha>` (merge base on `main`), and the incoming change.
|
||||
- Read the **original commit** (`git --no-pager show <commit-sha> -- <path>`) to understand the author's intent, then pick the resolution that produces the equivalent end state on the release branch.
|
||||
- Don't grab unrelated changes from `main` that happen to surround the conflict — keep the cherry-pick minimal.
|
||||
|
||||
### 5. Validate
|
||||
|
||||
Always build and (if reasonable) test the affected crate(s) before continuing the cherry-pick.
|
||||
|
||||
```
|
||||
cargo check -p <affected_crate>
|
||||
cargo test -p <affected_crate>
|
||||
```
|
||||
|
||||
If validation fails, fix the resolution — do **not** continue with a broken build. If you can't reach a clean state, abort with `git cherry-pick --abort` and report back to the user.
|
||||
|
||||
### 6. Finish the cherry-pick
|
||||
|
||||
`git cherry-pick --continue` opens an editor by default. Prevent that:
|
||||
|
||||
```
|
||||
git add <resolved_files>
|
||||
GIT_EDITOR=true git cherry-pick --continue
|
||||
```
|
||||
|
||||
This preserves the original commit message verbatim, which is what the script does.
|
||||
|
||||
### 7. Push and open the PR
|
||||
|
||||
```
|
||||
git push origin -f cherry-pick-<branch-name>-<short-sha>
|
||||
```
|
||||
|
||||
Then create the PR with the **exact** title and body format `script/cherry-pick` uses, so it's indistinguishable from an automated one.
|
||||
|
||||
**Title:**
|
||||
|
||||
```
|
||||
<original commit subject> (cherry-pick to <channel>)
|
||||
```
|
||||
|
||||
The original commit subject already ends in ` (#<original_pr_number>)`; keep it.
|
||||
|
||||
**Body** (when the original commit title ends in `(#<N>)`, which is the normal case):
|
||||
|
||||
```
|
||||
Cherry-pick of #<original_pr_number> to <channel>
|
||||
|
||||
----
|
||||
<original commit body, verbatim>
|
||||
```
|
||||
|
||||
Create it with `gh pr create`, writing the body to a temp file to keep formatting intact:
|
||||
|
||||
```
|
||||
git --no-pager log -1 --pretty=format:"%b" > /tmp/cp-body-tail.md
|
||||
printf 'Cherry-pick of #%s to %s\n\n----\n' <PR_NUMBER> <channel> | cat - /tmp/cp-body-tail.md > /tmp/cp-body.md
|
||||
gh pr create --base <branch-name> --head cherry-pick-<branch-name>-<short-sha> \\
|
||||
--title "<commit subject> (cherry-pick to <channel>)" \\
|
||||
--body-file /tmp/cp-body.md
|
||||
```
|
||||
|
||||
Do **not** add a `Release Notes:` section — the original commit body already has one (or already says `N/A`), and you don't want it duplicated.
|
||||
|
||||
## Final report to the user
|
||||
|
||||
Tell the user:
|
||||
- The new PR URL.
|
||||
- A one-line summary of the conflict and how you resolved it.
|
||||
- What validation you ran (commands + result).
|
||||
- That their local branch is now `cherry-pick-<branch-name>-<short-sha>`, in case they want you to switch back.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **`--no-pager` and `GIT_EDITOR=true`**: required for non-interactive git in this environment. Forgetting `GIT_EDITOR=true` on `cherry-pick --continue` hangs the terminal.
|
||||
- **Worktree index lock**: if a previous git command was interrupted, you may see `index.lock` errors. The lock lives at `<gitdir>/index.lock` where `<gitdir>` is what `cat .git` points to (for a worktree). Remove it only if you're sure no git process is running.
|
||||
- **Don't expand the cherry-pick's scope**: when resolving conflicts, never pull in unrelated changes from `main` just because they sit next to the conflict region. The PR should be the smallest diff that reproduces the original commit's intent on the release branch.
|
||||
- **Channel branches are not called `preview`/`stable`**: don't try to `git fetch origin preview`. Look up the actual `vX.Y.x` branch name first.
|
||||
|
||||
## When Finished
|
||||
|
||||
After everything is finished, the last thing to do is to provide a link to the opened pull request(s) for the cherry-pick(s).
|
||||
2
.github/CODEOWNERS.hold
vendored
|
|
@ -55,7 +55,6 @@
|
|||
/crates/open_ai/ @zed-industries/ai-team
|
||||
/crates/open_router/ @zed-industries/ai-team
|
||||
/crates/prompt_store/ @zed-industries/ai-team
|
||||
/crates/rules_library/ @zed-industries/ai-team
|
||||
# SUGGESTED: Review needed - based on Richard Feldman (2 commits)
|
||||
/crates/shell_command_parser/ @zed-industries/ai-team
|
||||
/crates/vercel/ @zed-industries/ai-team
|
||||
|
|
@ -181,7 +180,6 @@
|
|||
/crates/fs_benchmarks/ @zed-industries/infrastructure-team
|
||||
/crates/http_client/ @zed-industries/infrastructure-team
|
||||
/crates/http_client_tls/ @zed-industries/infrastructure-team
|
||||
/crates/nc/ @zed-industries/infrastructure-team
|
||||
/crates/net/ @zed-industries/infrastructure-team
|
||||
/crates/paths/ @zed-industries/infrastructure-team
|
||||
/crates/release_channel/ @zed-industries/infrastructure-team
|
||||
|
|
|
|||
|
|
@ -1,113 +0,0 @@
|
|||
name: Community Champion Auto Labeler
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened]
|
||||
pull_request_target:
|
||||
types: [opened]
|
||||
|
||||
jobs:
|
||||
label_community_champion:
|
||||
if: github.repository_owner == 'zed-industries'
|
||||
runs-on: namespace-profile-2x4-ubuntu-2404
|
||||
steps:
|
||||
- name: Check if author is a community champion and apply label
|
||||
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
|
||||
env:
|
||||
COMMUNITY_CHAMPIONS: |
|
||||
0x2CA
|
||||
5brian
|
||||
5herlocked
|
||||
abdelq
|
||||
afgomez
|
||||
AidanV
|
||||
akbxr
|
||||
AlvaroParker
|
||||
amtoaer
|
||||
artemevsevev
|
||||
bajrangCoder
|
||||
bcomnes
|
||||
Be-ing
|
||||
blopker
|
||||
bnjjj
|
||||
bobbymannino
|
||||
CharlesChen0823
|
||||
chbk
|
||||
davewa
|
||||
davidbarsky
|
||||
ddoemonn
|
||||
djsauble
|
||||
errmayank
|
||||
fantacell
|
||||
fdncred
|
||||
findrakecil
|
||||
FloppyDisco
|
||||
gko
|
||||
huacnlee
|
||||
imumesh18
|
||||
injust
|
||||
jacobtread
|
||||
jansol
|
||||
jeffreyguenther
|
||||
jenslys
|
||||
jongretar
|
||||
lemorage
|
||||
lingyaochu
|
||||
lnay
|
||||
marcocondrache
|
||||
marius851000
|
||||
mikebronner
|
||||
ognevny
|
||||
PKief
|
||||
playdohface
|
||||
RemcoSmitsDev
|
||||
rgbkrk
|
||||
romaninsh
|
||||
rxptr
|
||||
Simek
|
||||
someone13574
|
||||
sourcefrog
|
||||
suxiaoshao
|
||||
Takk8IS
|
||||
tartarughina
|
||||
thedadams
|
||||
tidely
|
||||
timvermeulen
|
||||
valentinegb
|
||||
versecafe
|
||||
vitallium
|
||||
WhySoBad
|
||||
ya7010
|
||||
Zertsov
|
||||
with:
|
||||
script: |
|
||||
const communityChampions = process.env.COMMUNITY_CHAMPIONS
|
||||
.split('\n')
|
||||
.map(handle => handle.trim().toLowerCase())
|
||||
.filter(handle => handle.length > 0);
|
||||
|
||||
let author;
|
||||
if (context.eventName === 'issues') {
|
||||
author = context.payload.issue.user.login;
|
||||
} else if (context.eventName === 'pull_request_target') {
|
||||
author = context.payload.pull_request.user.login;
|
||||
}
|
||||
|
||||
if (!author || !communityChampions.includes(author.toLowerCase())) {
|
||||
return;
|
||||
}
|
||||
|
||||
const issueNumber = context.payload.issue?.number || context.payload.pull_request?.number;
|
||||
|
||||
try {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
labels: ['community champion']
|
||||
});
|
||||
|
||||
console.log(`Applied 'community champion' label to #${issueNumber} by ${author}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to apply label: ${error.message}`);
|
||||
}
|
||||
97
.github/workflows/nix_build.yml
vendored
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
# Generated from xtask::workflows::nix_build
|
||||
# Rebuild with `cargo xtask workflows`.
|
||||
name: nix_build
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: '1'
|
||||
on:
|
||||
pull_request:
|
||||
types:
|
||||
- labeled
|
||||
- synchronize
|
||||
jobs:
|
||||
build_nix_linux_x86_64:
|
||||
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') && ((github.event.action == 'labeled' && (github.event.label.name == 'run-nix' || github.event.label.name == 'run-bundling')) || (github.event.action == 'synchronize' && (contains(github.event.pull_request.labels.*.name, 'run-nix') || contains(github.event.pull_request.labels.*.name, 'run-bundling'))))
|
||||
runs-on: namespace-profile-32x64-ubuntu-2004
|
||||
env:
|
||||
ZED_CLIENT_CHECKSUM_SEED: ${{ secrets.ZED_CLIENT_CHECKSUM_SEED }}
|
||||
ZED_MINIDUMP_ENDPOINT: ${{ secrets.ZED_SENTRY_MINIDUMP_ENDPOINT }}
|
||||
ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON: ${{ secrets.ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON }}
|
||||
GIT_LFS_SKIP_SMUDGE: '1'
|
||||
steps:
|
||||
- name: steps::checkout_repo
|
||||
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
|
||||
with:
|
||||
clean: false
|
||||
- name: steps::cache_nix_dependencies_namespace
|
||||
uses: namespacelabs/nscloud-cache-action@a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9
|
||||
with:
|
||||
cache: nix
|
||||
- name: nix_build::build_nix::install_nix
|
||||
uses: cachix/install-nix-action@02a151ada4993995686f9ed4f1be7cfbb229e56f
|
||||
with:
|
||||
github_access_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: nix_build::build_nix::cachix_action
|
||||
uses: cachix/cachix-action@0fc020193b5a1fa3ac4575aa3a7d3aa6a35435ad
|
||||
with:
|
||||
name: zed
|
||||
authToken: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||
cachixArgs: -v
|
||||
pushFilter: -zed-editor-[0-9.]*
|
||||
- name: nix_build::build_nix::build
|
||||
run: nix build .#default -L --accept-flake-config
|
||||
timeout-minutes: 60
|
||||
continue-on-error: true
|
||||
build_nix_mac_aarch64:
|
||||
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') && ((github.event.action == 'labeled' && (github.event.label.name == 'run-nix' || github.event.label.name == 'run-bundling')) || (github.event.action == 'synchronize' && (contains(github.event.pull_request.labels.*.name, 'run-nix') || contains(github.event.pull_request.labels.*.name, 'run-bundling'))))
|
||||
runs-on: namespace-profile-mac-large
|
||||
env:
|
||||
ZED_CLIENT_CHECKSUM_SEED: ${{ secrets.ZED_CLIENT_CHECKSUM_SEED }}
|
||||
ZED_MINIDUMP_ENDPOINT: ${{ secrets.ZED_SENTRY_MINIDUMP_ENDPOINT }}
|
||||
ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON: ${{ secrets.ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON }}
|
||||
GIT_LFS_SKIP_SMUDGE: '1'
|
||||
steps:
|
||||
- name: steps::checkout_repo
|
||||
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
|
||||
with:
|
||||
clean: false
|
||||
- name: steps::cache_nix_store_macos
|
||||
uses: namespacelabs/nscloud-cache-action@a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9
|
||||
with:
|
||||
path: ~/nix-cache
|
||||
- name: nix_build::build_nix::install_nix
|
||||
uses: cachix/install-nix-action@02a151ada4993995686f9ed4f1be7cfbb229e56f
|
||||
with:
|
||||
github_access_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: nix_build::build_nix::configure_local_nix_cache
|
||||
run: |
|
||||
mkdir -p ~/nix-cache
|
||||
echo "extra-substituters = file://$HOME/nix-cache?priority=10" | sudo tee -a /etc/nix/nix.conf
|
||||
echo "require-sigs = false" | sudo tee -a /etc/nix/nix.conf
|
||||
sudo launchctl kickstart -k system/org.nixos.nix-daemon
|
||||
- name: nix_build::build_nix::cachix_action
|
||||
uses: cachix/cachix-action@0fc020193b5a1fa3ac4575aa3a7d3aa6a35435ad
|
||||
with:
|
||||
name: zed
|
||||
authToken: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||
cachixArgs: -v
|
||||
pushFilter: -zed-editor-[0-9.]*
|
||||
- name: nix_build::build_nix::build
|
||||
run: nix build .#default -L --accept-flake-config
|
||||
- name: nix_build::build_nix::export_to_local_nix_cache
|
||||
if: always()
|
||||
run: |
|
||||
if [ -L result ]; then
|
||||
echo "Copying build closure to local binary cache..."
|
||||
nix copy --to "file://$HOME/nix-cache" ./result || echo "Warning: nix copy to local cache failed"
|
||||
else
|
||||
echo "No build result found, skipping cache export."
|
||||
fi
|
||||
timeout-minutes: 60
|
||||
continue-on-error: true
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
|
||||
cancel-in-progress: true
|
||||
defaults:
|
||||
run:
|
||||
shell: bash -euxo pipefail {0}
|
||||
247
.github/workflows/pr_issue_labeler.yml
vendored
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
# Labels pull requests by author:
|
||||
# - 'community champion' for community champions
|
||||
# - 'bot' for bot accounts
|
||||
# - 'staff' for staff team members
|
||||
# - 'guild' for guild members
|
||||
# - 'first contribution' for first-time external contributors
|
||||
# Labels issues by author:
|
||||
# - 'community champion' for community champions
|
||||
|
||||
name: PR Issue Labeler
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened]
|
||||
pull_request_target:
|
||||
types: [opened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
check-authorship-and-label:
|
||||
if: github.repository == 'zed-industries/zed'
|
||||
runs-on: namespace-profile-2x4-ubuntu-2404
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- id: get-app-token
|
||||
uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859 # v3.0.0
|
||||
with:
|
||||
app-id: ${{ secrets.ZED_COMMUNITY_BOT_APP_ID }}
|
||||
private-key: ${{ secrets.ZED_COMMUNITY_BOT_PRIVATE_KEY }}
|
||||
owner: zed-industries
|
||||
|
||||
- id: apply-authorship-label
|
||||
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||
with:
|
||||
github-token: ${{ steps.get-app-token.outputs.token }}
|
||||
script: |
|
||||
const BOT_LABEL = 'bot';
|
||||
const STAFF_LABEL = 'staff';
|
||||
const STAFF_TEAM_SLUG = 'staff';
|
||||
const FIRST_CONTRIBUTION_LABEL = 'first contribution';
|
||||
const GUILD_LABEL = 'guild';
|
||||
const GUILD_MEMBERS = [
|
||||
'11happy',
|
||||
'AidanV',
|
||||
'alanpjohn',
|
||||
'AmaanBilwar',
|
||||
'arjunkomath',
|
||||
'austincummings',
|
||||
'ayushk-1801',
|
||||
'criticic',
|
||||
'dongdong867',
|
||||
'emamulandalib',
|
||||
'eureka928',
|
||||
'feitreim',
|
||||
'iam-liam',
|
||||
'iksuddle',
|
||||
'ishaksebsib',
|
||||
'lingyaochu',
|
||||
'loadingalias',
|
||||
'marcocondrache',
|
||||
'mchisolm0',
|
||||
'MostlyKIGuess',
|
||||
'nairadithya',
|
||||
'nihalxkumar',
|
||||
'notJoon',
|
||||
'OmChillure',
|
||||
'Palanikannan1437',
|
||||
'polyesterswing',
|
||||
'prayanshchh',
|
||||
'razeghi71',
|
||||
'sarmadgulzar',
|
||||
'seanstrom',
|
||||
'Shivansh-25',
|
||||
'SkandaBhat',
|
||||
'th0jensen',
|
||||
'tommyming',
|
||||
'transitoryangel',
|
||||
'TwistingTwists',
|
||||
'virajbhartiya',
|
||||
'YEDASAVG',
|
||||
'Ziqi-Yang',
|
||||
];
|
||||
const COMMUNITY_CHAMPION_LABEL = 'community champion';
|
||||
const COMMUNITY_CHAMPIONS = [
|
||||
'0x2CA',
|
||||
'5brian',
|
||||
'5herlocked',
|
||||
'abdelq',
|
||||
'afgomez',
|
||||
'AidanV',
|
||||
'akbxr',
|
||||
'AlvaroParker',
|
||||
'amtoaer',
|
||||
'artemevsevev',
|
||||
'bajrangCoder',
|
||||
'bcomnes',
|
||||
'Be-ing',
|
||||
'blopker',
|
||||
'bnjjj',
|
||||
'bobbymannino',
|
||||
'CharlesChen0823',
|
||||
'chbk',
|
||||
'davewa',
|
||||
'davidbarsky',
|
||||
'ddoemonn',
|
||||
'djsauble',
|
||||
'errmayank',
|
||||
'fantacell',
|
||||
'fdncred',
|
||||
'findrakecil',
|
||||
'FloppyDisco',
|
||||
'gko',
|
||||
'huacnlee',
|
||||
'imumesh18',
|
||||
'injust',
|
||||
'jacobtread',
|
||||
'jansol',
|
||||
'jeffreyguenther',
|
||||
'jenslys',
|
||||
'jongretar',
|
||||
'lemorage',
|
||||
'lingyaochu',
|
||||
'lnay',
|
||||
'marcocondrache',
|
||||
'marius851000',
|
||||
'mikebronner',
|
||||
'ognevny',
|
||||
'PKief',
|
||||
'playdohface',
|
||||
'RemcoSmitsDev',
|
||||
'rgbkrk',
|
||||
'romaninsh',
|
||||
'rxptr',
|
||||
'Simek',
|
||||
'someone13574',
|
||||
'sourcefrog',
|
||||
'suxiaoshao',
|
||||
'Takk8IS',
|
||||
'tartarughina',
|
||||
'thedadams',
|
||||
'tidely',
|
||||
'timvermeulen',
|
||||
'valentinegb',
|
||||
'versecafe',
|
||||
'vitallium',
|
||||
'WhySoBad',
|
||||
'ya7010',
|
||||
'Zertsov',
|
||||
];
|
||||
|
||||
const pr = context.payload.pull_request;
|
||||
const issue = context.payload.issue;
|
||||
const target = pr || issue;
|
||||
const author = target.user.login;
|
||||
|
||||
const listIncludesAuthor = (members, author) => {
|
||||
const authorLower = author.toLowerCase();
|
||||
return members.some((member) => member.toLowerCase() === authorLower);
|
||||
};
|
||||
|
||||
const isStaffMember = async (author) => {
|
||||
try {
|
||||
const response = await github.rest.teams.getMembershipForUserInOrg({
|
||||
org: 'zed-industries',
|
||||
team_slug: STAFF_TEAM_SLUG,
|
||||
username: author
|
||||
});
|
||||
return response.data.state === 'active';
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const getIssueLabels = () => {
|
||||
if (listIncludesAuthor(COMMUNITY_CHAMPIONS, author)) {
|
||||
return [COMMUNITY_CHAMPION_LABEL];
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
const getPullRequestLabels = async () => {
|
||||
if (target.user.type === 'Bot') {
|
||||
return [BOT_LABEL];
|
||||
}
|
||||
|
||||
if (await isStaffMember(author)) {
|
||||
return [STAFF_LABEL];
|
||||
}
|
||||
|
||||
// External contributors
|
||||
|
||||
const labelsToAdd = [];
|
||||
|
||||
if (listIncludesAuthor(COMMUNITY_CHAMPIONS, author)) {
|
||||
labelsToAdd.push(COMMUNITY_CHAMPION_LABEL);
|
||||
}
|
||||
|
||||
if (listIncludesAuthor(GUILD_MEMBERS, author)) {
|
||||
labelsToAdd.push(GUILD_LABEL);
|
||||
}
|
||||
|
||||
// We use inverted logic here due to a suspected GitHub bug where first-time contributors
|
||||
// get 'NONE' instead of 'FIRST_TIME_CONTRIBUTOR' or 'FIRST_TIMER'.
|
||||
// https://github.com/orgs/community/discussions/78038
|
||||
// This will break if GitHub ever adds new associations.
|
||||
const association = pr.author_association;
|
||||
const knownAssociations = ['CONTRIBUTOR', 'COLLABORATOR', 'MEMBER', 'OWNER', 'MANNEQUIN'];
|
||||
|
||||
if (knownAssociations.includes(association)) {
|
||||
console.log(`PR #${pr.number} by ${author}: not a first-time contributor (association: '${association}')`);
|
||||
} else {
|
||||
labelsToAdd.push(FIRST_CONTRIBUTION_LABEL);
|
||||
}
|
||||
|
||||
return labelsToAdd;
|
||||
};
|
||||
|
||||
const labelsToAdd = pr ? await getPullRequestLabels() : getIssueLabels();
|
||||
|
||||
if (labelsToAdd.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: target.number,
|
||||
labels: labelsToAdd
|
||||
});
|
||||
|
||||
const targetType = pr ? 'PR' : 'issue';
|
||||
const labels = labelsToAdd.map((label) => `'${label}'`).join(', ');
|
||||
console.log(`${targetType} #${target.number} by ${author}: labeled ${labels}`);
|
||||
} catch (error) {
|
||||
if (pr) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
console.error(`Failed to label issue #${target.number}: ${error.message}`);
|
||||
}
|
||||
150
.github/workflows/pr_labeler.yml
vendored
|
|
@ -1,150 +0,0 @@
|
|||
# Labels pull requests by author: 'bot' for bot accounts, 'staff' for
|
||||
# staff team members, 'guild' for guild members, 'first contribution' for
|
||||
# first-time external contributors.
|
||||
name: PR Labeler
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
check-authorship-and-label:
|
||||
if: github.repository == 'zed-industries/zed'
|
||||
runs-on: namespace-profile-2x4-ubuntu-2404
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- id: get-app-token
|
||||
uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859 # v3.0.0
|
||||
with:
|
||||
app-id: ${{ secrets.ZED_COMMUNITY_BOT_APP_ID }}
|
||||
private-key: ${{ secrets.ZED_COMMUNITY_BOT_PRIVATE_KEY }}
|
||||
owner: zed-industries
|
||||
|
||||
- id: apply-authorship-label
|
||||
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||
with:
|
||||
github-token: ${{ steps.get-app-token.outputs.token }}
|
||||
script: |
|
||||
const BOT_LABEL = 'bot';
|
||||
const STAFF_LABEL = 'staff';
|
||||
const GUILD_LABEL = 'guild';
|
||||
const FIRST_CONTRIBUTION_LABEL = 'first contribution';
|
||||
const STAFF_TEAM_SLUG = 'staff';
|
||||
const GUILD_MEMBERS = [
|
||||
'11happy',
|
||||
'AidanV',
|
||||
'AmaanBilwar',
|
||||
'MostlyKIGuess',
|
||||
'OmChillure',
|
||||
'Palanikannan1437',
|
||||
'Shivansh-25',
|
||||
'SkandaBhat',
|
||||
'TwistingTwists',
|
||||
'YEDASAVG',
|
||||
'Ziqi-Yang',
|
||||
'alanpjohn',
|
||||
'arjunkomath',
|
||||
'austincummings',
|
||||
'ayushk-1801',
|
||||
'criticic',
|
||||
'dongdong867',
|
||||
'emamulandalib',
|
||||
'eureka928',
|
||||
'feitreim',
|
||||
'iam-liam',
|
||||
'iksuddle',
|
||||
'ishaksebsib',
|
||||
'lingyaochu',
|
||||
'loadingalias',
|
||||
'marcocondrache',
|
||||
'mchisolm0',
|
||||
'nairadithya',
|
||||
'nihalxkumar',
|
||||
'notJoon',
|
||||
'polyesterswing',
|
||||
'prayanshchh',
|
||||
'razeghi71',
|
||||
'sarmadgulzar',
|
||||
'seanstrom',
|
||||
'th0jensen',
|
||||
'tommyming',
|
||||
'transitoryangel',
|
||||
'virajbhartiya',
|
||||
];
|
||||
|
||||
const pr = context.payload.pull_request;
|
||||
const author = pr.user.login;
|
||||
|
||||
if (pr.user.type === 'Bot') {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: pr.number,
|
||||
labels: [BOT_LABEL]
|
||||
});
|
||||
console.log(`PR #${pr.number} by ${author}: labeled '${BOT_LABEL}' (user type: '${pr.user.type}')`);
|
||||
return;
|
||||
}
|
||||
|
||||
let isStaff = false;
|
||||
try {
|
||||
const response = await github.rest.teams.getMembershipForUserInOrg({
|
||||
org: 'zed-industries',
|
||||
team_slug: STAFF_TEAM_SLUG,
|
||||
username: author
|
||||
});
|
||||
isStaff = response.data.state === 'active';
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (isStaff) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: pr.number,
|
||||
labels: [STAFF_LABEL]
|
||||
});
|
||||
console.log(`PR #${pr.number} by ${author}: labeled '${STAFF_LABEL}' (staff team member)`);
|
||||
return;
|
||||
}
|
||||
|
||||
const authorLower = author.toLowerCase();
|
||||
const isGuildMember = GUILD_MEMBERS.some(
|
||||
(member) => member.toLowerCase() === authorLower
|
||||
);
|
||||
if (isGuildMember) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: pr.number,
|
||||
labels: [GUILD_LABEL]
|
||||
});
|
||||
console.log(`PR #${pr.number} by ${author}: labeled '${GUILD_LABEL}' (guild member)`);
|
||||
// No early return: guild members can also get 'first contribution'
|
||||
}
|
||||
|
||||
// We use inverted logic here due to a suspected GitHub bug where first-time contributors
|
||||
// get 'NONE' instead of 'FIRST_TIME_CONTRIBUTOR' or 'FIRST_TIMER'.
|
||||
// https://github.com/orgs/community/discussions/78038
|
||||
// This will break if GitHub ever adds new associations.
|
||||
const association = pr.author_association;
|
||||
const knownAssociations = ['CONTRIBUTOR', 'COLLABORATOR', 'MEMBER', 'OWNER', 'MANNEQUIN'];
|
||||
|
||||
if (knownAssociations.includes(association)) {
|
||||
console.log(`PR #${pr.number} by ${author}: not a first-time contributor (association: '${association}')`);
|
||||
return;
|
||||
}
|
||||
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: pr.number,
|
||||
labels: [FIRST_CONTRIBUTION_LABEL]
|
||||
});
|
||||
console.log(`PR #${pr.number} by ${author}: labeled '${FIRST_CONTRIBUTION_LABEL}' (association: '${association}')`);
|
||||
79
.github/workflows/run_bundling.yml
vendored
|
|
@ -264,85 +264,6 @@ jobs:
|
|||
path: target/zed-remote-server-windows-x86_64.zip
|
||||
if-no-files-found: error
|
||||
timeout-minutes: 60
|
||||
build_nix_linux_x86_64:
|
||||
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') && ((github.event.action == 'labeled' && github.event.label.name == 'run-bundling') || (github.event.action == 'synchronize' && contains(github.event.pull_request.labels.*.name, 'run-bundling')))
|
||||
runs-on: namespace-profile-32x64-ubuntu-2004
|
||||
env:
|
||||
ZED_CLIENT_CHECKSUM_SEED: ${{ secrets.ZED_CLIENT_CHECKSUM_SEED }}
|
||||
ZED_MINIDUMP_ENDPOINT: ${{ secrets.ZED_SENTRY_MINIDUMP_ENDPOINT }}
|
||||
ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON: ${{ secrets.ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON }}
|
||||
GIT_LFS_SKIP_SMUDGE: '1'
|
||||
steps:
|
||||
- name: steps::checkout_repo
|
||||
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
|
||||
with:
|
||||
clean: false
|
||||
- name: steps::cache_nix_dependencies_namespace
|
||||
uses: namespacelabs/nscloud-cache-action@a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9
|
||||
with:
|
||||
cache: nix
|
||||
- name: nix_build::build_nix::install_nix
|
||||
uses: cachix/install-nix-action@02a151ada4993995686f9ed4f1be7cfbb229e56f
|
||||
with:
|
||||
github_access_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: nix_build::build_nix::cachix_action
|
||||
uses: cachix/cachix-action@0fc020193b5a1fa3ac4575aa3a7d3aa6a35435ad
|
||||
with:
|
||||
name: zed
|
||||
authToken: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||
cachixArgs: -v
|
||||
pushFilter: -zed-editor-[0-9.]*
|
||||
- name: nix_build::build_nix::build
|
||||
run: nix build .#default -L --accept-flake-config
|
||||
timeout-minutes: 60
|
||||
continue-on-error: true
|
||||
build_nix_mac_aarch64:
|
||||
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') && ((github.event.action == 'labeled' && github.event.label.name == 'run-bundling') || (github.event.action == 'synchronize' && contains(github.event.pull_request.labels.*.name, 'run-bundling')))
|
||||
runs-on: namespace-profile-mac-large
|
||||
env:
|
||||
ZED_CLIENT_CHECKSUM_SEED: ${{ secrets.ZED_CLIENT_CHECKSUM_SEED }}
|
||||
ZED_MINIDUMP_ENDPOINT: ${{ secrets.ZED_SENTRY_MINIDUMP_ENDPOINT }}
|
||||
ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON: ${{ secrets.ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON }}
|
||||
GIT_LFS_SKIP_SMUDGE: '1'
|
||||
steps:
|
||||
- name: steps::checkout_repo
|
||||
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
|
||||
with:
|
||||
clean: false
|
||||
- name: steps::cache_nix_store_macos
|
||||
uses: namespacelabs/nscloud-cache-action@a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9
|
||||
with:
|
||||
path: ~/nix-cache
|
||||
- name: nix_build::build_nix::install_nix
|
||||
uses: cachix/install-nix-action@02a151ada4993995686f9ed4f1be7cfbb229e56f
|
||||
with:
|
||||
github_access_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: nix_build::build_nix::configure_local_nix_cache
|
||||
run: |
|
||||
mkdir -p ~/nix-cache
|
||||
echo "extra-substituters = file://$HOME/nix-cache?priority=10" | sudo tee -a /etc/nix/nix.conf
|
||||
echo "require-sigs = false" | sudo tee -a /etc/nix/nix.conf
|
||||
sudo launchctl kickstart -k system/org.nixos.nix-daemon
|
||||
- name: nix_build::build_nix::cachix_action
|
||||
uses: cachix/cachix-action@0fc020193b5a1fa3ac4575aa3a7d3aa6a35435ad
|
||||
with:
|
||||
name: zed
|
||||
authToken: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||
cachixArgs: -v
|
||||
pushFilter: -zed-editor-[0-9.]*
|
||||
- name: nix_build::build_nix::build
|
||||
run: nix build .#default -L --accept-flake-config
|
||||
- name: nix_build::build_nix::export_to_local_nix_cache
|
||||
if: always()
|
||||
run: |
|
||||
if [ -L result ]; then
|
||||
echo "Copying build closure to local binary cache..."
|
||||
nix copy --to "file://$HOME/nix-cache" ./result || echo "Warning: nix copy to local cache failed"
|
||||
else
|
||||
echo "No build result found, skipping cache export."
|
||||
fi
|
||||
timeout-minutes: 60
|
||||
continue-on-error: true
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
|
|
|||
|
|
@ -16,8 +16,9 @@ jobs:
|
|||
github.event_name == 'issues' &&
|
||||
github.repository == 'zed-industries/zed' &&
|
||||
github.event.issue.pull_request == null &&
|
||||
github.event.issue.type != null &&
|
||||
(github.event.issue.type.name == 'Bug' || github.event.issue.type.name == 'Crash')
|
||||
(github.event.issue.type == null ||
|
||||
github.event.issue.type.name == 'Bug' ||
|
||||
github.event.issue.type.name == 'Crash')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
|
|
|
|||
3
.gitignore
vendored
|
|
@ -55,3 +55,6 @@ crates/docs_preprocessor/actions.json
|
|||
# Local documentation audit files
|
||||
/december-2025-releases.md
|
||||
/docs/december-2025-documentation-gaps.md
|
||||
|
||||
# NixOS integration test state
|
||||
.nixos-test-history
|
||||
|
|
|
|||
1358
Cargo.lock
generated
29
Cargo.toml
|
|
@ -130,13 +130,13 @@ members = [
|
|||
"crates/lsp",
|
||||
"crates/markdown",
|
||||
"crates/markdown_preview",
|
||||
"crates/mermaid_render",
|
||||
"crates/media",
|
||||
"crates/menu",
|
||||
"crates/migrator",
|
||||
"crates/miniprofiler_ui",
|
||||
"crates/mistral",
|
||||
"crates/multi_buffer",
|
||||
"crates/nc",
|
||||
"crates/net",
|
||||
"crates/node_runtime",
|
||||
"crates/notifications",
|
||||
|
|
@ -171,7 +171,7 @@ members = [
|
|||
"crates/reqwest_client",
|
||||
"crates/rope",
|
||||
"crates/rpc",
|
||||
"crates/rules_library",
|
||||
"crates/sandbox",
|
||||
"crates/skill_creator",
|
||||
"crates/scheduler",
|
||||
"crates/schema_generator",
|
||||
|
|
@ -389,15 +389,14 @@ lmstudio = { path = "crates/lmstudio" }
|
|||
lsp = { path = "crates/lsp" }
|
||||
markdown = { path = "crates/markdown" }
|
||||
markdown_preview = { path = "crates/markdown_preview" }
|
||||
mermaid_render = { path = "crates/mermaid_render" }
|
||||
svg_preview = { path = "crates/svg_preview" }
|
||||
media = { path = "crates/media" }
|
||||
menu = { path = "crates/menu" }
|
||||
mermaid-rs-renderer = { git = "https://github.com/zed-industries/mermaid-rs-renderer", rev = "782b89a7da3f0e91e51f98d00a93acba679be6fb", default-features = false }
|
||||
migrator = { path = "crates/migrator" }
|
||||
mistral = { path = "crates/mistral" }
|
||||
multi_buffer = { path = "crates/multi_buffer" }
|
||||
miniprofiler_ui = { path = "crates/miniprofiler_ui" }
|
||||
nc = { path = "crates/nc" }
|
||||
net = { path = "crates/net" }
|
||||
node_runtime = { path = "crates/node_runtime" }
|
||||
notifications = { path = "crates/notifications" }
|
||||
|
|
@ -432,9 +431,9 @@ reqwest_client = { path = "crates/reqwest_client" }
|
|||
rodio = { git = "https://github.com/RustAudio/rodio", rev = "e50e726ddd0292f6ef9de0dda6b90af4ed1fb66a", features = ["wav", "playback", "wav_output", "recording"] }
|
||||
rope = { path = "crates/rope" }
|
||||
rpc = { path = "crates/rpc" }
|
||||
rules_library = { path = "crates/rules_library" }
|
||||
skill_creator = { path = "crates/skill_creator" }
|
||||
scheduler = { path = "crates/scheduler" }
|
||||
sandbox = { path = "crates/sandbox" }
|
||||
search = { path = "crates/search" }
|
||||
session = { path = "crates/session" }
|
||||
sidebar = { path = "crates/sidebar" }
|
||||
|
|
@ -502,9 +501,13 @@ ztracing_macro = { path = "crates/ztracing_macro" }
|
|||
# External crates
|
||||
#
|
||||
|
||||
accesskit = "0.24.0"
|
||||
accesskit_macos = "0.26.0"
|
||||
accesskit_unix = "0.21.0"
|
||||
accesskit_windows = "0.32.1"
|
||||
agent-client-protocol = { version = "=0.12.1", features = ["unstable"] }
|
||||
aho-corasick = "1.1"
|
||||
alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "9d9640d4" }
|
||||
alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "fcf32feacb367b75ec84dd40f041e4fd411d3cc1" }
|
||||
any_vec = "0.14"
|
||||
anyhow = "1.0.86"
|
||||
ashpd = { version = "0.13", default-features = false, features = [
|
||||
|
|
@ -556,14 +559,14 @@ clap = { version = "4.4", features = ["derive", "wrap_help"] }
|
|||
cocoa = "=0.26.0"
|
||||
cocoa-foundation = "=0.2.0"
|
||||
const_format = "0.2"
|
||||
convert_case = "0.8.0"
|
||||
convert_case = "0.11.0"
|
||||
core-foundation = "=0.10.0"
|
||||
core-foundation-sys = "0.8.6"
|
||||
core-video = { version = "0.5.2", features = ["metal"] }
|
||||
cpal = "0.17"
|
||||
crash-handler = "0.7"
|
||||
criterion = { version = "0.5", features = ["html_reports"] }
|
||||
ctor = "0.4.0"
|
||||
ctor = "1.0.6"
|
||||
dap-types = { git = "https://github.com/zed-industries/dap-types", rev = "1b461b310481d01e02b2603c16d7144b926339f8" }
|
||||
dashmap = "6.0"
|
||||
derive_more = { version = "2.1.1", features = [
|
||||
|
|
@ -592,7 +595,7 @@ futures = "0.3.32"
|
|||
futures-concurrency = "7.7.1"
|
||||
futures-lite = "1.13"
|
||||
gh-workflow = { git = "https://github.com/zed-industries/gh-workflow", rev = "37f3c0575d379c218a9c455ee67585184e40d43f" }
|
||||
git2 = { version = "0.20.1", default-features = false, features = ["vendored-libgit2"] }
|
||||
git2 = { version = "0.21.0", default-features = false, features = ["vendored-libgit2", "unstable-sha256"] }
|
||||
globset = "0.4"
|
||||
heapless = "0.9.2"
|
||||
handlebars = "4.3"
|
||||
|
|
@ -622,6 +625,7 @@ linkify = "0.10.0"
|
|||
libwebrtc = "0.3.26"
|
||||
livekit = { version = "0.7.32", features = ["tokio", "rustls-tls-native-roots"] }
|
||||
log = { version = "0.4.16", features = ["kv_unstable_serde", "serde"] }
|
||||
lru = "0.16"
|
||||
lsp-types = { git = "https://github.com/zed-industries/lsp-types", rev = "f4dfa89a21ca35cd929b70354b1583fabae325f8" }
|
||||
mach2 = "0.5"
|
||||
markup5ever_rcdom = "0.3.0"
|
||||
|
|
@ -723,6 +727,7 @@ serde_json_lenient = { version = "0.2", features = [
|
|||
"preserve_order",
|
||||
"raw_value",
|
||||
] }
|
||||
serde_yaml = "0.9.34"
|
||||
serde_path_to_error = "0.1.17"
|
||||
serde_urlencoded = "0.7"
|
||||
sha2 = "0.10"
|
||||
|
|
@ -886,9 +891,9 @@ notify = { git = "https://github.com/zed-industries/notify.git", rev = "ce58c24c
|
|||
notify-types = { git = "https://github.com/zed-industries/notify.git", rev = "ce58c24cad542c28e04ced02e20325a4ec28a31d" }
|
||||
windows-capture = { git = "https://github.com/zed-industries/windows-capture.git", rev = "f0d6c1b6691db75461b732f6d5ff56eed002eeb9" }
|
||||
calloop = { git = "https://github.com/zed-industries/calloop" }
|
||||
livekit = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "147fbca3d4b592d96d33f5e6a84b59fc0b5d9bf1" }
|
||||
libwebrtc = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "147fbca3d4b592d96d33f5e6a84b59fc0b5d9bf1" }
|
||||
webrtc-sys = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "147fbca3d4b592d96d33f5e6a84b59fc0b5d9bf1" }
|
||||
livekit = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "c3a55bbc207008f1ca3474b6037fdd3c443cad0f" }
|
||||
libwebrtc = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "c3a55bbc207008f1ca3474b6037fdd3c443cad0f" }
|
||||
webrtc-sys = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "c3a55bbc207008f1ca3474b6037fdd3c443cad0f" }
|
||||
|
||||
[profile.dev]
|
||||
split-debuginfo = "unpacked"
|
||||
|
|
|
|||
788
LICENSE-AGPL
|
|
@ -1,788 +0,0 @@
|
|||
Copyright 2022 - 2025 Zed Industries, Inc.
|
||||
|
||||
|
||||
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
||||
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
Preamble
|
||||
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
|
||||
0. Definitions.
|
||||
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
|
||||
1. Source Code.
|
||||
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
|
||||
8. Termination.
|
||||
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
|
||||
11. Patents.
|
||||
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
|
@ -13,7 +13,7 @@ On macOS, Linux, and Windows you can [download Zed directly](https://zed.dev/dow
|
|||
|
||||
Other platforms are not yet available:
|
||||
|
||||
- Web ([tracking issue](https://github.com/zed-industries/zed/issues/5396))
|
||||
- Web ([tracking discussion](https://github.com/zed-industries/zed/discussions/26195))
|
||||
|
||||
### Developing Zed
|
||||
|
||||
|
|
@ -29,6 +29,8 @@ Also... we're hiring! Check out our [jobs](https://zed.dev/jobs) page for open r
|
|||
|
||||
### Licensing
|
||||
|
||||
Zed source code is licensed primarily under GPL-3.0-or-later, with Apache-2.0 components where marked.
|
||||
|
||||
License information for third party dependencies must be correctly provided for CI to pass.
|
||||
|
||||
We use [`cargo-about`](https://github.com/EmbarkStudios/cargo-about) to automatically comply with open source licenses. If CI is failing, check the following:
|
||||
|
|
|
|||
3
assets/icons/bitbucket.svg
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M2.38893 2.60654C2.33283 2.6058 2.27725 2.61737 2.2261 2.64042C2.17496 2.66347 2.12948 2.69745 2.09288 2.73996C2.05627 2.78247 2.02943 2.83249 2.01423 2.8865C1.99904 2.9405 1.99586 2.99718 2.00492 3.05254L3.63644 12.9576C3.67844 13.2076 3.89394 13.3916 4.14744 13.3941H11.975C12.0672 13.3951 12.1567 13.3631 12.2273 13.3039C12.2979 13.2446 12.345 13.1621 12.36 13.0711L13.995 3.05604C14.004 3.00072 14.0008 2.94409 13.9856 2.89015C13.9703 2.83621 13.9435 2.78626 13.9069 2.7438C13.8703 2.70134 13.8248 2.66741 13.7737 2.64439C13.7226 2.62137 13.6671 2.60982 13.611 2.61054L2.38893 2.60654ZM9.26 9.76511H6.76097L6.08496 6.23308H9.8655L9.26 9.76511Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 778 B |
|
|
@ -1,3 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M8 11C9.65685 11 11 9.65685 11 8C11 6.34315 9.65685 5 8 5C6.34315 5 5 6.34315 5 8C5 9.65685 6.34315 11 8 11Z" fill="black"/>
|
||||
<path d="M8 12C10.2091 12 12 10.2091 12 8C12 5.79087 10.2091 4 8 4C5.79087 4 4 5.79087 4 8C4 10.2091 5.79087 12 8 12Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 237 B After Width: | Height: | Size: 239 B |
3
assets/icons/codeberg.svg
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M7.99947 2.00001C7.15863 1.99826 6.32573 2.16261 5.54858 2.48364C4.77144 2.80466 4.06536 3.27604 3.4709 3.87071C2.87644 4.46537 2.40529 5.1716 2.08452 5.94885C1.76376 6.7261 1.59968 7.55906 1.60172 8.39989C1.60172 9.6017 1.94029 10.7806 2.57906 11.7995L7.91309 4.90217C7.95148 4.85311 8.04692 4.85311 8.08531 4.90217L10.313 7.78246H8.71767L8.75233 7.90989H10.4122L10.8824 8.51666H8.92348L8.9784 8.71608H11.0365L11.4508 9.25087H9.12716L9.19914 9.5084H11.6481L12.0187 9.98507H9.33244L9.42042 10.2991H12.2602L12.5849 10.7177H9.53665L9.63369 11.0642H12.8531L13.1527 11.4519H9.74193L9.83951 11.7984H13.4209C14.0594 10.7799 14.3982 9.60205 14.3983 8.39989C14.4001 7.55903 14.2359 6.72608 13.9149 5.94885C13.594 5.17163 13.1228 4.46543 12.5283 3.8708C11.9337 3.27616 11.2276 2.8048 10.4504 2.48376C9.67326 2.16272 8.84033 1.99833 7.99947 2.00001ZM9.94774 12.1861L10.0448 12.5327H12.8846C12.9768 12.4239 13.0728 12.3018 13.1581 12.1861H9.94774ZM10.153 12.9203L10.249 13.2669H12.1488C12.273 13.1613 12.4073 13.0386 12.5284 12.9203H10.153ZM10.3572 13.6545L10.4543 14H11.0957C11.2855 13.8912 11.4609 13.7803 11.6513 13.6545H10.3572Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
3
assets/icons/forgejo.svg
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M10.4889 1.74811C11.3234 1.74811 12 2.42467 12 3.25924C12 4.09382 11.3234 4.77032 10.4889 4.77032C9.92344 4.77032 9.43053 4.45981 9.17144 3.99993H8.4741C7.25904 3.99993 6.27176 4.97512 6.25212 6.18549L6.25176 7.28869C6.87559 6.81941 7.63228 6.56028 8.41283 6.54862L8.4741 6.5481L9.17144 6.5482C9.43053 6.08832 9.92344 5.77776 10.4889 5.77776C11.3234 5.77776 12 6.45432 12 7.28889C12 8.12347 11.3234 8.79998 10.4889 8.79998C9.92344 8.79998 9.43053 8.48947 9.17144 8.02959H8.4741C7.25904 8.02959 6.27176 9.00478 6.25212 10.2151L6.25176 11.4233C6.71164 11.6824 7.0222 12.1753 7.0222 12.7407C7.0222 13.5754 6.34564 14.2519 5.51107 14.2519C4.67654 14.2519 3.99998 13.5753 3.99998 12.7407C3.99998 12.1753 4.3105 11.6824 4.77043 11.4233L4.77032 6.22222C4.77032 4.19713 6.39555 2.55168 8.41283 2.51902L8.4741 2.5185H9.17144C9.43053 2.05872 9.92349 1.74811 10.4889 1.74811ZM5.51107 12.1185C5.16742 12.1185 4.88885 12.3971 4.88885 12.7407C4.88885 13.0844 5.16742 13.363 5.51107 13.363C5.85471 13.363 6.13334 13.0844 6.13334 12.7407C6.13334 12.3971 5.85471 12.1185 5.51107 12.1185ZM10.4889 6.66668C10.1453 6.66668 9.86665 6.94525 9.86665 7.28889C9.86665 7.63254 10.1453 7.91111 10.4889 7.91111C10.8326 7.91111 11.1111 7.63254 11.1111 7.28889C11.1111 6.94525 10.8326 6.66668 10.4889 6.66668ZM10.4889 2.63702C10.1453 2.63702 9.86665 2.9156 9.86665 3.25924C9.86665 3.60289 10.1453 3.88146 10.4889 3.88146C10.8326 3.88146 11.1111 3.60289 11.1111 3.25924C11.1111 2.9156 10.8326 2.63702 10.4889 2.63702Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
3
assets/icons/gitea.svg
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M3.45524 3.60059C3.31116 3.60059 3.14899 3.61226 2.96524 3.65192C2.77099 3.69276 2.21858 3.81701 1.76707 4.25101C0.764907 5.14467 1.02041 6.56509 1.05191 6.77917C1.08982 7.03934 1.20532 7.76326 1.75774 8.39384C2.77799 9.64276 4.97366 9.61418 4.97366 9.61418C4.97366 9.61418 5.24316 10.2576 5.65499 10.8503C6.21208 11.587 6.78433 12.1616 7.34083 12.231C8.74433 12.231 11.5478 12.2287 11.5478 12.2287C11.5478 12.2287 11.815 12.231 12.1778 11.9988C12.4899 11.8098 12.7687 11.4779 12.7687 11.4779C12.7687 11.4779 13.0557 11.1705 13.4571 10.4688C13.5796 10.2529 13.6817 10.0435 13.7709 9.84576C13.7709 9.84576 15 7.23768 15 4.69901C14.9755 3.93017 14.7859 3.79484 14.7416 3.74992C14.6506 3.65892 14.5281 3.66067 14.5281 3.66067C14.5281 3.66067 11.9177 3.80767 10.5661 3.83917C10.2697 3.84559 9.97575 3.85259 9.68408 3.85492V6.46476L9.31425 6.28917C9.31425 5.47834 9.31191 3.85667 9.31191 3.85667C8.66616 3.86601 7.32566 3.80767 7.32566 3.80767C7.32566 3.80767 4.17624 3.65017 3.83324 3.61867C3.72416 3.61226 3.59933 3.60059 3.45524 3.60059ZM3.66174 4.66926H3.72649C3.72649 4.66926 3.88458 5.99284 4.07649 6.76751C4.23691 7.41792 4.62833 8.49884 4.62833 8.49884C4.62833 8.49884 4.04733 8.42943 3.67108 8.29584C3.09358 8.10684 2.84916 7.87934 2.84916 7.87934C2.84916 7.87934 2.42333 7.58126 2.20983 6.99268C1.84232 6.00801 2.17891 5.40717 2.17891 5.40717C2.17891 5.40717 2.36558 4.90609 3.03641 4.73926C3.26683 4.67742 3.53983 4.66926 3.66174 4.66926ZM8.52091 6.15909C8.67258 6.16084 8.81783 6.23317 8.81783 6.23317L9.32416 6.47934L9.01558 7.10642C8.94244 7.10526 8.87038 7.12417 8.80724 7.16109C8.74409 7.19801 8.69227 7.25153 8.65741 7.31584C8.62013 7.3853 8.60423 7.46422 8.61171 7.5427C8.61918 7.62117 8.64969 7.69567 8.69941 7.75684L8.15166 8.87918C8.0625 8.88053 7.97631 8.91146 7.90663 8.9671C7.83695 9.02274 7.78772 9.09994 7.76666 9.18659C7.74656 9.27272 7.75551 9.36308 7.79213 9.44358C7.82874 9.52409 7.89096 9.59022 7.96908 9.63168C8.05388 9.67515 8.15141 9.68693 8.24412 9.6649C8.33684 9.64287 8.41864 9.58848 8.47483 9.51151C8.52969 9.43471 8.55573 9.34103 8.54837 9.24693C8.541 9.15284 8.50072 9.06435 8.43458 8.99701L8.96891 7.90384C9.01532 7.90827 9.06215 7.90432 9.10716 7.89218C9.16538 7.87825 9.21952 7.85088 9.26525 7.81226C9.46902 7.89896 9.66699 7.99873 9.85791 8.11093C9.92725 8.14983 9.98487 8.20664 10.0247 8.27543C10.0673 8.39793 9.98216 8.60734 9.98216 8.60734C9.93141 8.77651 9.57266 9.51151 9.57266 9.51151C9.48573 9.50923 9.40039 9.53508 9.32933 9.58521C9.25828 9.63535 9.20532 9.70709 9.17833 9.78976C9.15763 9.85611 9.15471 9.92673 9.16985 9.99456C9.18498 10.0624 9.21765 10.1251 9.26459 10.1763C9.31153 10.2276 9.3711 10.2656 9.43734 10.2867C9.50359 10.3077 9.57419 10.311 9.6421 10.2962C9.71001 10.2814 9.77285 10.2491 9.82435 10.2024C9.87585 10.1557 9.9142 10.0963 9.93557 10.0302C9.95694 9.96406 9.96058 9.89347 9.94614 9.82548C9.93169 9.7575 9.89966 9.69449 9.85325 9.64276C9.89583 9.56051 9.9355 9.47826 9.97808 9.39134C10.0889 9.15976 10.2785 8.71468 10.2785 8.71468C10.2989 8.67618 10.4057 8.48484 10.3386 8.23984C10.2832 7.98609 10.0586 7.86768 10.0586 7.86768C9.78616 7.69209 9.40758 7.52934 9.40758 7.52934C9.40758 7.52934 9.40758 7.43834 9.38308 7.37184C9.36435 7.31951 9.33495 7.27164 9.29675 7.23126L9.59775 6.61176L11.2836 7.42901C11.2836 7.42901 11.5636 7.55618 11.6237 7.79009C11.6662 7.95459 11.6126 8.10159 11.5834 8.17334C11.4434 8.51576 10.3584 10.6916 10.3584 10.6916C10.3584 10.6916 10.2231 11.0148 9.92208 11.0346C9.8447 11.0402 9.76694 11.0313 9.69283 11.0083L9.575 10.9617L7.06083 9.73668C7.06083 9.73668 6.81758 9.60951 6.77499 9.38901C6.72658 9.20818 6.83566 8.98593 6.83566 8.98593L8.04491 6.49392C8.04491 6.49392 8.15166 6.27809 8.31675 6.20401C8.38086 6.17478 8.45045 6.15947 8.52091 6.15909Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.8 KiB |
3
assets/icons/gitlab.svg
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M14.0228 6.75008L14.0053 6.70533L12.3092 2.27915C12.2747 2.19237 12.2136 2.11876 12.1347 2.06887C12.0557 2.01987 11.9636 1.99627 11.8708 2.00128C11.7779 2.00628 11.6889 2.03964 11.6156 2.09686C11.5432 2.15571 11.4906 2.23546 11.4651 2.32525L10.32 5.82877H5.68303L4.53784 2.32525C4.513 2.23496 4.46031 2.1548 4.38727 2.09618C4.31401 2.03898 4.22496 2.00564 4.13214 2.00065C4.03932 1.99567 3.94721 2.01928 3.86824 2.0683C3.78948 2.11837 3.72842 2.1919 3.69368 2.27852L1.99452 6.70273L1.97764 6.74748C1.73349 7.38539 1.70335 8.08539 1.89177 8.74192C2.08018 9.39845 2.47694 9.97594 3.02221 10.3873L3.02808 10.3918L3.04365 10.4029L5.62716 12.3376L6.90542 13.305L7.68395 13.8928C7.77502 13.9619 7.88623 13.9994 8.00058 13.9994C8.11493 13.9994 8.22613 13.9619 8.31721 13.8928L9.09574 13.305L10.3739 12.3376L12.973 10.3912L12.9795 10.386C13.5236 9.97456 13.9194 9.39768 14.1075 8.74203C14.2957 8.08638 14.2659 7.38738 14.0228 6.75008Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1 KiB |
6
assets/icons/text_unwrap.svg
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M11.748 5.74794L14 7.99998L11.748 10.252" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M14 7.99997L3 7.99997" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M8 3L8 6" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M8 10L8 13" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 566 B |
5
assets/icons/text_wrap.svg
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M5.19924 8.90081L2.9472 6.64876L5.19924 4.39673" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M2.9472 6.64877H7.67649C8.00178 6.64877 8.32391 6.71285 8.6245 6.83734C8.92501 6.96184 9.19813 7.14431 9.42817 7.37434C9.6582 7.60437 9.84067 7.87746 9.96512 8.17802C10.0897 8.47856 10.1537 8.8007 10.1537 9.12601C10.1537 9.45131 10.0897 9.77345 9.96512 10.074C9.84067 10.3745 9.6582 10.6477 9.42817 10.8777C9.19813 11.1077 8.92501 11.2902 8.6245 11.4147C8.32391 11.5392 8.00178 11.6033 7.67649 11.6033H6.10005" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M13.0528 3.33331V12.6666" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 871 B |
|
|
@ -380,15 +380,7 @@
|
|||
"shift-backspace": "agent::ArchiveSelectedThread",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "RulesLibrary",
|
||||
"bindings": {
|
||||
"new": "rules_library::NewRule",
|
||||
"ctrl-n": "rules_library::NewRule",
|
||||
"ctrl-shift-s": "rules_library::ToggleDefaultRule",
|
||||
"ctrl-w": "workspace::CloseWindow",
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
"context": "BufferSearchBar",
|
||||
"bindings": {
|
||||
|
|
@ -729,6 +721,7 @@
|
|||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"space": "menu::Confirm",
|
||||
"shift-r": "agent::RenameSelectedThread",
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -1562,6 +1555,7 @@
|
|||
"context": "SkillCreator",
|
||||
"bindings": {
|
||||
"ctrl-w": "workspace::CloseWindow",
|
||||
"ctrl-enter": "skill_creator::SaveSkill",
|
||||
"tab": "skill_creator::FocusNextField",
|
||||
"shift-tab": "skill_creator::FocusPreviousField",
|
||||
},
|
||||
|
|
@ -1570,6 +1564,7 @@
|
|||
"context": "SkillCreator > Editor",
|
||||
"bindings": {
|
||||
"ctrl-w": "workspace::CloseWindow",
|
||||
"ctrl-enter": "skill_creator::SaveSkill",
|
||||
"tab": "skill_creator::FocusNextField",
|
||||
"shift-tab": "skill_creator::FocusPreviousField",
|
||||
},
|
||||
|
|
|
|||
|
|
@ -427,15 +427,6 @@
|
|||
"backspace": "agent::ArchiveSelectedThread",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "RulesLibrary",
|
||||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"cmd-n": "rules_library::NewRule",
|
||||
"cmd-shift-s": "rules_library::ToggleDefaultRule",
|
||||
"cmd-w": "workspace::CloseWindow",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "BufferSearchBar",
|
||||
"use_key_equivalents": true,
|
||||
|
|
@ -785,6 +776,7 @@
|
|||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"space": "menu::Confirm",
|
||||
"shift-r": "agent::RenameSelectedThread",
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -1656,6 +1648,7 @@
|
|||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"cmd-w": "workspace::CloseWindow",
|
||||
"cmd-enter": "skill_creator::SaveSkill",
|
||||
"tab": "skill_creator::FocusNextField",
|
||||
"shift-tab": "skill_creator::FocusPreviousField",
|
||||
},
|
||||
|
|
@ -1665,6 +1658,7 @@
|
|||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"cmd-w": "workspace::CloseWindow",
|
||||
"cmd-enter": "skill_creator::SaveSkill",
|
||||
"tab": "skill_creator::FocusNextField",
|
||||
"shift-tab": "skill_creator::FocusPreviousField",
|
||||
},
|
||||
|
|
|
|||
|
|
@ -383,15 +383,6 @@
|
|||
"shift-backspace": "agent::ArchiveSelectedThread",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "RulesLibrary",
|
||||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"ctrl-n": "rules_library::NewRule",
|
||||
"ctrl-shift-s": "rules_library::ToggleDefaultRule",
|
||||
"ctrl-w": "workspace::CloseWindow",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "BufferSearchBar",
|
||||
"use_key_equivalents": true,
|
||||
|
|
@ -732,6 +723,7 @@
|
|||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"space": "menu::Confirm",
|
||||
"shift-r": "agent::RenameSelectedThread",
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -1582,6 +1574,7 @@
|
|||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"ctrl-w": "workspace::CloseWindow",
|
||||
"ctrl-enter": "skill_creator::SaveSkill",
|
||||
"tab": "skill_creator::FocusNextField",
|
||||
"shift-tab": "skill_creator::FocusPreviousField",
|
||||
},
|
||||
|
|
@ -1591,6 +1584,7 @@
|
|||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"ctrl-w": "workspace::CloseWindow",
|
||||
"ctrl-enter": "skill_creator::SaveSkill",
|
||||
"tab": "skill_creator::FocusNextField",
|
||||
"shift-tab": "skill_creator::FocusPreviousField",
|
||||
},
|
||||
|
|
|
|||
|
|
@ -338,7 +338,7 @@
|
|||
"ctrl-x": "vim::Decrement",
|
||||
"shift-j": "vim::JoinLines",
|
||||
"i": "vim::InsertBefore",
|
||||
"a": "vim::InsertAfter",
|
||||
"a": "vim::HelixAppend",
|
||||
"o": "vim::InsertLineBelow",
|
||||
"shift-o": "vim::InsertLineAbove",
|
||||
"p": "vim::Paste",
|
||||
|
|
@ -494,6 +494,10 @@
|
|||
"n": "vim::HelixSelectNext",
|
||||
"shift-n": "vim::HelixSelectPrevious",
|
||||
|
||||
// Macros — Helix swaps Vim's q/Q: Q records, q replays
|
||||
"q": "vim::ReplayLastRecording",
|
||||
"shift-q": "vim::ToggleRecord",
|
||||
|
||||
// Goto mode
|
||||
"g e": "vim::EndOfDocument",
|
||||
"g h": "vim::StartOfLine",
|
||||
|
|
@ -503,6 +507,8 @@
|
|||
"g c": "vim::WindowMiddle",
|
||||
"g b": "vim::WindowBottom",
|
||||
"g r": "editor::FindAllReferences",
|
||||
"g i": "editor::GoToImplementation",
|
||||
"g a": "pane::AlternateFile",
|
||||
"g n": "pane::ActivateNextItem",
|
||||
"shift-l": "pane::ActivateNextItem", // not a helix default
|
||||
"g p": "pane::ActivatePreviousItem",
|
||||
|
|
|
|||
|
|
@ -71,6 +71,8 @@
|
|||
"agent_ui_font_size": null,
|
||||
// The default font size for user messages in the agent panel.
|
||||
"agent_buffer_font_size": 12,
|
||||
// The default font size for the commit editor in the git panel and commit modal.
|
||||
"git_commit_buffer_font_size": 12,
|
||||
// How much to fade out unused code.
|
||||
"unnecessary_code_fade": 0.3,
|
||||
// Active pane styling settings.
|
||||
|
|
@ -1133,6 +1135,7 @@
|
|||
"spawn_agent": true,
|
||||
"terminal": true,
|
||||
"update_plan": true,
|
||||
"update_title": true,
|
||||
"search_web": true,
|
||||
},
|
||||
},
|
||||
|
|
@ -1153,6 +1156,7 @@
|
|||
"skill": true,
|
||||
"spawn_agent": true,
|
||||
"update_plan": true,
|
||||
"update_title": true,
|
||||
"search_web": true,
|
||||
},
|
||||
},
|
||||
|
|
@ -1496,6 +1500,10 @@
|
|||
// 4. Draw a background behind the color text..
|
||||
// "lsp_document_colors": "background",
|
||||
"lsp_document_colors": "inlay",
|
||||
// Whether to query and display LSP `textDocument/documentLink` links in the editor.
|
||||
//
|
||||
// Default: true
|
||||
"lsp_document_links": true,
|
||||
// Diagnostics configuration.
|
||||
"diagnostics": {
|
||||
// Whether to show the project diagnostics button in the status bar.
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ parking_lot = { workspace = true, optional = true }
|
|||
image.workspace = true
|
||||
portable-pty.workspace = true
|
||||
project.workspace = true
|
||||
prompt_store.workspace = true
|
||||
sandbox.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
settings.workspace = true
|
||||
|
|
|
|||
|
|
@ -16,7 +16,9 @@ use gpui::{
|
|||
};
|
||||
use itertools::Itertools;
|
||||
use language::language_settings::FormatOnSave;
|
||||
use language::{Anchor, Buffer, BufferSnapshot, LanguageRegistry, Point, ToPoint, text_diff};
|
||||
use language::{
|
||||
Anchor, Buffer, BufferEditSource, BufferSnapshot, LanguageRegistry, Point, ToPoint, text_diff,
|
||||
};
|
||||
use markdown::{Markdown, MarkdownOptions};
|
||||
pub use mention::*;
|
||||
use project::lsp_store::{FormatTrigger, LspFormatTarget};
|
||||
|
|
@ -773,6 +775,7 @@ impl ContentBlock {
|
|||
None,
|
||||
MarkdownOptions {
|
||||
render_mermaid_diagrams: true,
|
||||
render_metadata_blocks: true,
|
||||
..Default::default()
|
||||
},
|
||||
cx,
|
||||
|
|
@ -2912,7 +2915,9 @@ impl AcpThread {
|
|||
});
|
||||
|
||||
let format_on_save = buffer.update(cx, |buffer, cx| {
|
||||
buffer.start_transaction();
|
||||
buffer.edit(edits, None, cx);
|
||||
buffer.end_transaction_with_source(BufferEditSource::Agent, cx);
|
||||
|
||||
let settings =
|
||||
language::language_settings::LanguageSettings::for_buffer(buffer, cx);
|
||||
|
|
@ -2955,6 +2960,7 @@ impl AcpThread {
|
|||
extra_env: Vec<acp::EnvVariable>,
|
||||
cwd: Option<PathBuf>,
|
||||
output_byte_limit: Option<u64>,
|
||||
sandbox_wrap: Option<SandboxWrap>,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Task<Result<Entity<Terminal>>> {
|
||||
let env = match &cwd {
|
||||
|
|
@ -2995,6 +3001,8 @@ impl AcpThread {
|
|||
ShellBuilder::new(&Shell::Program(shell), is_windows)
|
||||
.redirect_stdin_to_dev_null()
|
||||
.build(Some(command.clone()), &args);
|
||||
let (task_command, task_args, sandbox_config) =
|
||||
apply_sandbox_wrap(task_command, task_args, sandbox_wrap)?;
|
||||
let terminal = project
|
||||
.update(cx, |project, cx| {
|
||||
project.create_terminal_task(
|
||||
|
|
@ -3018,6 +3026,7 @@ impl AcpThread {
|
|||
output_byte_limit.map(|l| l as usize),
|
||||
terminal,
|
||||
language_registry,
|
||||
sandbox_config,
|
||||
cx,
|
||||
)
|
||||
}))
|
||||
|
|
@ -3097,6 +3106,9 @@ impl AcpThread {
|
|||
output_byte_limit.map(|l| l as usize),
|
||||
terminal,
|
||||
language_registry,
|
||||
// External terminal providers manage their own sandboxing
|
||||
// (if any). We don't wrap their commands.
|
||||
None,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
|
|
|||
|
|
@ -7,14 +7,14 @@ use gpui::{Entity, SharedString, Task};
|
|||
use language_model::LanguageModelProviderId;
|
||||
use project::{AgentId, Project};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{any::Any, error::Error, fmt, path::PathBuf, rc::Rc, sync::Arc};
|
||||
use std::{any::Any, error::Error, fmt, path::PathBuf, rc::Rc};
|
||||
use task::{HideStrategy, SpawnInTerminal, TaskId};
|
||||
use ui::{App, IconName};
|
||||
use util::path_list::PathList;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
|
||||
pub struct UserMessageId(Arc<str>);
|
||||
pub struct UserMessageId(SharedString);
|
||||
|
||||
impl UserMessageId {
|
||||
pub fn new() -> Self {
|
||||
|
|
@ -116,7 +116,7 @@ pub trait AgentConnection {
|
|||
}
|
||||
|
||||
/// Whether this agent supports additional session directories.
|
||||
fn supports_session_additional_directories(&self, _cx: &App) -> bool {
|
||||
fn supports_session_additional_directories(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
|
|
@ -132,7 +132,7 @@ pub trait AgentConnection {
|
|||
|
||||
fn authenticate(&self, method: acp::AuthMethodId, cx: &mut App) -> Task<Result<()>>;
|
||||
|
||||
fn supports_logout(&self, _cx: &App) -> bool {
|
||||
fn supports_logout(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
|
|
@ -878,7 +878,7 @@ mod test_support {
|
|||
self.supports_load_session
|
||||
}
|
||||
|
||||
fn supports_session_additional_directories(&self, _cx: &App) -> bool {
|
||||
fn supports_session_additional_directories(&self) -> bool {
|
||||
self.supports_session_additional_directories
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
use agent_client_protocol::schema as acp;
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use file_icons::FileIcons;
|
||||
use prompt_store::{PromptId, UserPromptId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
|
|
@ -37,10 +36,6 @@ pub enum MentionUri {
|
|||
id: acp::SessionId,
|
||||
name: String,
|
||||
},
|
||||
Rule {
|
||||
id: PromptId,
|
||||
name: String,
|
||||
},
|
||||
Diagnostics {
|
||||
#[serde(default = "default_include_errors")]
|
||||
include_errors: bool,
|
||||
|
|
@ -51,6 +46,8 @@ pub enum MentionUri {
|
|||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
abs_path: Option<PathBuf>,
|
||||
line_range: RangeInclusive<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
column: Option<u32>,
|
||||
},
|
||||
Fetch {
|
||||
url: Url,
|
||||
|
|
@ -105,6 +102,17 @@ impl MentionUri {
|
|||
Ok(start_line..=end_line)
|
||||
}
|
||||
|
||||
let parse_column =
|
||||
|input: Option<String>| -> Option<u32> { input?.parse::<u32>().ok()?.checked_sub(1) };
|
||||
let validate_query_params = |url: &Url, allowed: &[&str]| -> Result<()> {
|
||||
for (key, _) in url.query_pairs() {
|
||||
if !allowed.contains(&key.as_ref()) {
|
||||
bail!("invalid query parameter")
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
|
||||
let parse_absolute_path = |input: &str| -> Result<Self> {
|
||||
let (path_input, fragment) = input
|
||||
.split_once('#')
|
||||
|
|
@ -114,6 +122,7 @@ impl MentionUri {
|
|||
return Ok(MentionUri::Selection {
|
||||
abs_path: Some(path_input.into()),
|
||||
line_range: fragment,
|
||||
column: None,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -123,10 +132,12 @@ impl MentionUri {
|
|||
let line = row
|
||||
.checked_sub(1)
|
||||
.context("Line numbers should be 1-based")?;
|
||||
// TODO: Preserve column info too.
|
||||
Ok(MentionUri::Selection {
|
||||
abs_path: Some(abs_path),
|
||||
line_range: line..=line,
|
||||
column: path_with_position
|
||||
.column
|
||||
.map(|column| column.saturating_sub(1)),
|
||||
})
|
||||
} else {
|
||||
Ok(MentionUri::File { abs_path })
|
||||
|
|
@ -156,8 +167,10 @@ impl MentionUri {
|
|||
let path = normalized.as_ref();
|
||||
|
||||
if let Some(fragment) = url.fragment() {
|
||||
validate_query_params(&url, &["symbol", "column"])?;
|
||||
let line_range = parse_line_range(fragment).log_err().unwrap_or(1..=1);
|
||||
if let Some(name) = single_query_param(&url, "symbol")? {
|
||||
let column = parse_column(query_param(&url, "column"));
|
||||
if let Some(name) = query_param(&url, "symbol") {
|
||||
Ok(Self::Symbol {
|
||||
name,
|
||||
abs_path: path.into(),
|
||||
|
|
@ -167,6 +180,7 @@ impl MentionUri {
|
|||
Ok(Self::Selection {
|
||||
abs_path: Some(path.into()),
|
||||
line_range,
|
||||
column,
|
||||
})
|
||||
}
|
||||
} else if input.ends_with("/") {
|
||||
|
|
@ -186,13 +200,6 @@ impl MentionUri {
|
|||
id: acp::SessionId::new(thread_id),
|
||||
name,
|
||||
})
|
||||
} else if let Some(rule_id) = path.strip_prefix("/agent/rule/") {
|
||||
let name = single_query_param(&url, "name")?.context("Missing rule name")?;
|
||||
let rule_id = UserPromptId(rule_id.parse()?);
|
||||
Ok(Self::Rule {
|
||||
id: rule_id.into(),
|
||||
name,
|
||||
})
|
||||
} else if path == "/agent/diagnostics" {
|
||||
let mut include_errors = default_include_errors();
|
||||
let mut include_warnings = false;
|
||||
|
|
@ -216,9 +223,11 @@ impl MentionUri {
|
|||
.fragment()
|
||||
.context("Missing fragment for untitled buffer selection")?;
|
||||
let line_range = parse_line_range(fragment)?;
|
||||
validate_query_params(&url, &["column"])?;
|
||||
Ok(Self::Selection {
|
||||
abs_path: None,
|
||||
line_range,
|
||||
column: parse_column(query_param(&url, "column")),
|
||||
})
|
||||
} else if let Some(name) = path.strip_prefix("/agent/symbol/") {
|
||||
let fragment = url
|
||||
|
|
@ -245,13 +254,15 @@ impl MentionUri {
|
|||
abs_path: path.into(),
|
||||
})
|
||||
} else if path.starts_with("/agent/selection") {
|
||||
validate_query_params(&url, &["path", "column"])?;
|
||||
let fragment = url.fragment().context("Missing fragment for selection")?;
|
||||
let line_range = parse_line_range(fragment)?;
|
||||
let path =
|
||||
single_query_param(&url, "path")?.context("Missing path for selection")?;
|
||||
let column = parse_column(query_param(&url, "column"));
|
||||
let path = query_param(&url, "path").context("Missing path for selection")?;
|
||||
Ok(Self::Selection {
|
||||
abs_path: Some(path.into()),
|
||||
line_range,
|
||||
column,
|
||||
})
|
||||
} else if path.starts_with("/agent/terminal-selection") {
|
||||
let line_count = single_query_param(&url, "lines")?
|
||||
|
|
@ -319,7 +330,6 @@ impl MentionUri {
|
|||
MentionUri::PastedImage { name } => name.clone(),
|
||||
MentionUri::Symbol { name, .. } => name.clone(),
|
||||
MentionUri::Thread { name, .. } => name.clone(),
|
||||
MentionUri::Rule { name, .. } => name.clone(),
|
||||
MentionUri::Diagnostics { .. } => "Diagnostics".to_string(),
|
||||
MentionUri::TerminalSelection { line_count } => {
|
||||
if *line_count == 1 {
|
||||
|
|
@ -420,7 +430,6 @@ impl MentionUri {
|
|||
.unwrap_or_else(|| IconName::Folder.path().into()),
|
||||
MentionUri::Symbol { .. } => IconName::Code.path().into(),
|
||||
MentionUri::Thread { .. } => IconName::Thread.path().into(),
|
||||
MentionUri::Rule { .. } => IconName::Reader.path().into(),
|
||||
MentionUri::Diagnostics { .. } => IconName::Warning.path().into(),
|
||||
MentionUri::TerminalSelection { .. } => IconName::Terminal.path().into(),
|
||||
MentionUri::Selection { .. } => IconName::Reader.path().into(),
|
||||
|
|
@ -460,6 +469,7 @@ impl MentionUri {
|
|||
abs_path,
|
||||
name,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
let mut url = Url::parse("file:///").unwrap();
|
||||
url.set_path(&abs_path.to_string_lossy());
|
||||
|
|
@ -474,6 +484,7 @@ impl MentionUri {
|
|||
MentionUri::Selection {
|
||||
abs_path,
|
||||
line_range,
|
||||
column,
|
||||
} => {
|
||||
let mut url = if let Some(path) = abs_path {
|
||||
let mut url = Url::parse("file:///").unwrap();
|
||||
|
|
@ -484,6 +495,10 @@ impl MentionUri {
|
|||
url.set_path("/agent/untitled-buffer");
|
||||
url
|
||||
};
|
||||
if let Some(column) = column {
|
||||
url.query_pairs_mut()
|
||||
.append_pair("column", &(column + 1).to_string());
|
||||
}
|
||||
url.set_fragment(Some(&format!(
|
||||
"L{}:{}",
|
||||
line_range.start() + 1,
|
||||
|
|
@ -497,12 +512,6 @@ impl MentionUri {
|
|||
url.query_pairs_mut().append_pair("name", name);
|
||||
url
|
||||
}
|
||||
MentionUri::Rule { name, id } => {
|
||||
let mut url = Url::parse("zed:///").unwrap();
|
||||
url.set_path(&format!("/agent/rule/{id}"));
|
||||
url.query_pairs_mut().append_pair("name", name);
|
||||
url
|
||||
}
|
||||
MentionUri::Diagnostics {
|
||||
include_errors,
|
||||
include_warnings,
|
||||
|
|
@ -564,6 +573,11 @@ fn default_include_errors() -> bool {
|
|||
true
|
||||
}
|
||||
|
||||
fn query_param(url: &Url, name: &'static str) -> Option<String> {
|
||||
url.query_pairs()
|
||||
.find_map(|(key, value)| (key == name).then(|| value.to_string()))
|
||||
}
|
||||
|
||||
fn single_query_param(url: &Url, name: &'static str) -> Result<Option<String>> {
|
||||
let pairs = url.query_pairs().collect::<Vec<_>>();
|
||||
match pairs.as_slice() {
|
||||
|
|
@ -698,6 +712,7 @@ mod tests {
|
|||
abs_path: path,
|
||||
name,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path, Path::new(path!("/path/to/file.rs")));
|
||||
assert_eq!(name, "MySymbol");
|
||||
|
|
@ -717,6 +732,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
|
||||
assert_eq!(line_range.start(), &4);
|
||||
|
|
@ -748,6 +764,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: None,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(line_range.start(), &0);
|
||||
assert_eq!(line_range.end(), &9);
|
||||
|
|
@ -774,20 +791,6 @@ mod tests {
|
|||
assert_eq!(parsed.to_uri().to_string(), thread_uri);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_rule_uri() {
|
||||
let rule_uri = "zed:///agent/rule/d8694ff2-90d5-4b6f-be33-33c1763acd52?name=Some+rule";
|
||||
let parsed = MentionUri::parse(rule_uri, PathStyle::local()).unwrap();
|
||||
match &parsed {
|
||||
MentionUri::Rule { id, name } => {
|
||||
assert_eq!(id.to_string(), "d8694ff2-90d5-4b6f-be33-33c1763acd52");
|
||||
assert_eq!(name, "Some rule");
|
||||
}
|
||||
_ => panic!("Expected Rule variant"),
|
||||
}
|
||||
assert_eq!(parsed.to_uri().to_string(), rule_uri);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_skill_uri_round_trip() {
|
||||
let skill_uri = MentionUri::Skill {
|
||||
|
|
@ -895,6 +898,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
|
||||
assert_eq!(line_range.start(), &41);
|
||||
|
|
@ -904,6 +908,29 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_absolute_file_path_with_row_and_column() {
|
||||
let file_path = "/path/to/file.rs:42:5";
|
||||
let parsed = MentionUri::parse(file_path, PathStyle::Posix).unwrap();
|
||||
match &parsed {
|
||||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
column,
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
|
||||
assert_eq!(line_range.start(), &41);
|
||||
assert_eq!(line_range.end(), &41);
|
||||
assert_eq!(column, &Some(4));
|
||||
|
||||
let parsed_again = MentionUri::parse(parsed.to_uri().as_ref(), PathStyle::Posix)
|
||||
.expect("selection URI with column should parse");
|
||||
assert_eq!(parsed_again, parsed.clone());
|
||||
}
|
||||
_ => panic!("Expected Selection variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_absolute_file_path_with_fragment_line() {
|
||||
let file_path = "/path/to/file.rs#L42";
|
||||
|
|
@ -912,6 +939,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
|
||||
assert_eq!(line_range.start(), &41);
|
||||
|
|
@ -941,6 +969,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(
|
||||
path.as_ref().unwrap(),
|
||||
|
|
@ -961,6 +990,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(
|
||||
path.as_ref().unwrap(),
|
||||
|
|
@ -993,6 +1023,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
|
||||
assert_eq!(line_range.start(), &41);
|
||||
|
|
@ -1010,6 +1041,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(
|
||||
path.as_ref().unwrap(),
|
||||
|
|
@ -1031,6 +1063,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
|
||||
assert_eq!(line_range.start(), &1871);
|
||||
|
|
@ -1048,6 +1081,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
|
||||
assert_eq!(line_range.start(), &9);
|
||||
|
|
@ -1063,6 +1097,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
|
||||
assert_eq!(line_range.start(), &9);
|
||||
|
|
|
|||
|
|
@ -17,6 +17,82 @@ use std::{
|
|||
use task::Shell;
|
||||
use util::get_default_system_shell_preferring_bash;
|
||||
|
||||
/// Request to run a terminal command inside an OS-level sandbox.
|
||||
///
|
||||
/// Passed to [`super::AcpThread::create_terminal`]. The actual sandboxing
|
||||
/// mechanism is platform-specific (today: macOS Seatbelt; nothing on other
|
||||
/// platforms — the wrap is silently a no-op there), so callers describe the
|
||||
/// *intent* with plain data here rather than constructing platform-specific
|
||||
/// types directly.
|
||||
///
|
||||
/// All-zero defaults are the fully-sandboxed run. Setting `allow_network` /
|
||||
/// `allow_fs_write` requests a relaxation; the caller is responsible for
|
||||
/// having obtained user approval before reaching this point.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SandboxWrap {
|
||||
/// Directory subtrees the sandbox should allow writes to. Pass the
|
||||
/// project's worktree paths (and any per-command scratch directory)
|
||||
/// here — *not* the command's working directory, which is model-
|
||||
/// controlled and would let the model widen its own writable scope.
|
||||
pub writable_paths: Vec<PathBuf>,
|
||||
/// Allow outbound network access for this command.
|
||||
pub allow_network: bool,
|
||||
/// Allow unrestricted filesystem writes (ignores `writable_paths`).
|
||||
pub allow_fs_write: bool,
|
||||
}
|
||||
|
||||
/// Opaque RAII handle the sandbox implementation hands back to keep its
|
||||
/// per-command resources (e.g. an on-disk Seatbelt config file) alive for
|
||||
/// the duration of the spawned command. `Terminal` holds it in a field
|
||||
/// whose only job is to drop with the entity.
|
||||
pub type SandboxConfigHandle = Box<dyn std::any::Any + Send>;
|
||||
|
||||
/// Apply a [`SandboxWrap`] to a `(program, args)` pair, substituting the
|
||||
/// platform's sandbox-launcher invocation in place of the original. The
|
||||
/// returned `SandboxConfigHandle` (when `Some`) must be kept alive for the
|
||||
/// duration of the spawned command — dropping it deletes any on-disk
|
||||
/// config the launcher reads at startup.
|
||||
///
|
||||
/// On non-macOS hosts this is a no-op: the inputs pass through unchanged
|
||||
/// and the returned handle is `None`. (We don't yet have a sandbox
|
||||
/// integration for other platforms.)
|
||||
pub(crate) fn apply_sandbox_wrap(
|
||||
program: String,
|
||||
args: Vec<String>,
|
||||
sandbox_wrap: Option<SandboxWrap>,
|
||||
) -> anyhow::Result<(String, Vec<String>, Option<SandboxConfigHandle>)> {
|
||||
let Some(sandbox_wrap) = sandbox_wrap else {
|
||||
return Ok((program, args, None));
|
||||
};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let writable: Vec<&std::path::Path> = sandbox_wrap
|
||||
.writable_paths
|
||||
.iter()
|
||||
.map(|p| p.as_path())
|
||||
.collect();
|
||||
let permissions = sandbox::macos_seatbelt::SandboxPermissions {
|
||||
allow_network: sandbox_wrap.allow_network,
|
||||
allow_fs_write: sandbox_wrap.allow_fs_write,
|
||||
};
|
||||
let (new_program, new_args, config_file) =
|
||||
sandbox::macos_seatbelt::wrap_invocation(&program, &args, &writable, permissions)?;
|
||||
Ok((
|
||||
new_program,
|
||||
new_args,
|
||||
Some(Box::new(config_file) as SandboxConfigHandle),
|
||||
))
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
// No sandbox integration available; ignore the wrap request and
|
||||
// let the command run with the agent's ambient permissions.
|
||||
let _ = sandbox_wrap;
|
||||
Ok((program, args, None))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Terminal {
|
||||
id: acp::TerminalId,
|
||||
command: Entity<Markdown>,
|
||||
|
|
@ -30,6 +106,10 @@ pub struct Terminal {
|
|||
/// (e.g., clicking the Stop button). This is set before kill() is called
|
||||
/// so that code awaiting wait_for_exit() can check it deterministically.
|
||||
user_stopped: Arc<AtomicBool>,
|
||||
/// RAII handle kept alive for the duration of the sandboxed command.
|
||||
/// `None` when the command isn't sandboxed (the common case for
|
||||
/// terminals not created by the agent).
|
||||
_sandbox_config: Option<SandboxConfigHandle>,
|
||||
}
|
||||
|
||||
pub struct TerminalOutput {
|
||||
|
|
@ -48,11 +128,13 @@ impl Terminal {
|
|||
output_byte_limit: Option<usize>,
|
||||
terminal: Entity<terminal::Terminal>,
|
||||
language_registry: Arc<LanguageRegistry>,
|
||||
sandbox_config: Option<SandboxConfigHandle>,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let command_task = terminal.read(cx).wait_for_completed_task(cx);
|
||||
Self {
|
||||
id,
|
||||
_sandbox_config: sandbox_config,
|
||||
command: cx.new(|cx| {
|
||||
Markdown::new(
|
||||
format!("```\n{}\n```", command_label).into(),
|
||||
|
|
|
|||
|
|
@ -508,6 +508,7 @@ impl AcpTools {
|
|||
} else {
|
||||
CopyButtonVisibility::Hidden
|
||||
},
|
||||
wrap_button_visibility: markdown::WrapButtonVisibility::Hidden,
|
||||
border: false,
|
||||
},
|
||||
),
|
||||
|
|
|
|||
|
|
@ -936,7 +936,11 @@ impl ActionLog {
|
|||
let mut undo_buffers = Vec::new();
|
||||
let mut futures = Vec::new();
|
||||
|
||||
for buffer in self.changed_buffers(cx).into_keys() {
|
||||
for buffer in self
|
||||
.changed_buffers(cx)
|
||||
.map(|(buffer, _)| buffer)
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
let buffer_ranges = vec![Anchor::min_max_range_for_buffer(
|
||||
buffer.read(cx).remote_id(),
|
||||
)];
|
||||
|
|
@ -1023,17 +1027,19 @@ impl ActionLog {
|
|||
}
|
||||
|
||||
/// Returns the set of buffers that contain edits that haven't been reviewed by the user.
|
||||
pub fn changed_buffers(&self, cx: &App) -> BTreeMap<Entity<Buffer>, Entity<BufferDiff>> {
|
||||
pub fn changed_buffers(
|
||||
&self,
|
||||
cx: &App,
|
||||
) -> impl Iterator<Item = (Entity<Buffer>, Entity<BufferDiff>)> {
|
||||
self.tracked_buffers
|
||||
.iter()
|
||||
.filter(|(_, tracked)| tracked.has_edits(cx))
|
||||
.map(|(buffer, tracked)| (buffer.clone(), tracked.diff.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Returns the total number of lines added and removed across all unreviewed buffers.
|
||||
pub fn diff_stats(&self, cx: &App) -> DiffStats {
|
||||
DiffStats::all_files(&self.changed_buffers(cx), cx)
|
||||
DiffStats::all_files(self.changed_buffers(cx), cx)
|
||||
}
|
||||
|
||||
/// Iterate over buffers changed since last read or edited by the model
|
||||
|
|
@ -1079,7 +1085,7 @@ impl DiffStats {
|
|||
}
|
||||
|
||||
pub fn all_files(
|
||||
changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
|
||||
changed_buffers: impl IntoIterator<Item = (Entity<Buffer>, Entity<BufferDiff>)>,
|
||||
cx: &App,
|
||||
) -> Self {
|
||||
let mut total = DiffStats::default();
|
||||
|
|
@ -1334,7 +1340,7 @@ mod tests {
|
|||
use std::env;
|
||||
use util::{RandomCharIter, path};
|
||||
|
||||
#[ctor::ctor]
|
||||
#[ctor::ctor(unsafe)]
|
||||
fn init_logger() {
|
||||
zlog::init_test();
|
||||
}
|
||||
|
|
@ -3254,21 +3260,21 @@ mod tests {
|
|||
child_log_1
|
||||
.read(cx)
|
||||
.changed_buffers(cx)
|
||||
.into_keys()
|
||||
.map(|(buffer, _)| buffer)
|
||||
.collect()
|
||||
});
|
||||
let child_2_changed: Vec<_> = cx.read(|cx| {
|
||||
child_log_2
|
||||
.read(cx)
|
||||
.changed_buffers(cx)
|
||||
.into_keys()
|
||||
.map(|(buffer, _)| buffer)
|
||||
.collect()
|
||||
});
|
||||
let parent_changed: Vec<_> = cx.read(|cx| {
|
||||
parent_log
|
||||
.read(cx)
|
||||
.changed_buffers(cx)
|
||||
.into_keys()
|
||||
.map(|(buffer, _)| buffer)
|
||||
.collect()
|
||||
});
|
||||
|
||||
|
|
@ -3494,7 +3500,6 @@ mod tests {
|
|||
action_log
|
||||
.read(cx)
|
||||
.changed_buffers(cx)
|
||||
.into_iter()
|
||||
.map(|(buffer, diff)| {
|
||||
let snapshot = buffer.read(cx).snapshot();
|
||||
(
|
||||
|
|
|
|||
|
|
@ -65,6 +65,7 @@ streaming_diff.workspace = true
|
|||
strsim.workspace = true
|
||||
task.workspace = true
|
||||
telemetry.workspace = true
|
||||
tempfile.workspace = true
|
||||
text.workspace = true
|
||||
thiserror.workspace = true
|
||||
ui.workspace = true
|
||||
|
|
@ -77,11 +78,13 @@ zed_env_vars.workspace = true
|
|||
zstd.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
assets.workspace = true
|
||||
async-io.workspace = true
|
||||
agent_servers = { workspace = true, "features" = ["test-support"] }
|
||||
client = { workspace = true, "features" = ["test-support"] }
|
||||
clock = { workspace = true, "features" = ["test-support"] }
|
||||
context_server = { workspace = true, "features" = ["test-support"] }
|
||||
criterion.workspace = true
|
||||
ctor.workspace = true
|
||||
db = { workspace = true, "features" = ["test-support"] }
|
||||
editor = { workspace = true, "features" = ["test-support"] }
|
||||
|
|
@ -99,10 +102,15 @@ project = { workspace = true, "features" = ["test-support"] }
|
|||
rand.workspace = true
|
||||
reqwest_client.workspace = true
|
||||
settings = { workspace = true, "features" = ["test-support"] }
|
||||
tempfile.workspace = true
|
||||
|
||||
theme = { workspace = true, "features" = ["test-support"] }
|
||||
theme_settings.workspace = true
|
||||
|
||||
unindent = { workspace = true }
|
||||
|
||||
zlog.workspace = true
|
||||
|
||||
[[bench]]
|
||||
name = "edit_file_tool"
|
||||
harness = false
|
||||
required-features = ["test-support"]
|
||||
|
|
|
|||
743
crates/agent/benches/edit_file_tool.rs
Normal file
|
|
@ -0,0 +1,743 @@
|
|||
use std::{
|
||||
any::Any,
|
||||
future::Future,
|
||||
path::Path,
|
||||
sync::Arc,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use action_log::ActionLog;
|
||||
use agent::{
|
||||
AgentTool, ContextServerRegistry, EditFileTool, EditFileToolInput, EditFileToolOutput,
|
||||
Templates, Thread, ToolCallEventStream, ToolInput,
|
||||
};
|
||||
use agent_settings::{AgentSettings, ToolRules};
|
||||
use criterion::{
|
||||
BatchSize, BenchmarkId, Criterion, Throughput, black_box, criterion_group, criterion_main,
|
||||
};
|
||||
use editor::{Editor, EditorStyle};
|
||||
use futures::{StreamExt as _, pin_mut, task::noop_waker};
|
||||
use gpui::{
|
||||
AnyWindowHandle, AppContext as _, BackgroundExecutor, Entity, Focusable as _, TestAppContext,
|
||||
UpdateGlobal as _,
|
||||
};
|
||||
use language::{FakeLspAdapter, rust_lang};
|
||||
use language_model::fake_provider::FakeLanguageModel;
|
||||
use project::{FakeFs, Project};
|
||||
use prompt_store::ProjectContext;
|
||||
use rand::{Rng as _, SeedableRng as _, rngs::StdRng};
|
||||
use serde_json::{Value, json};
|
||||
use settings::{Settings as _, SettingsStore};
|
||||
use ui::IntoElement as _;
|
||||
|
||||
const SEED: u64 = 0x5EED_5EED;
|
||||
const OLD_TEXT_CHUNK_SIZE: usize = 512;
|
||||
const NEW_TEXT_CHUNK_SIZE: usize = 512;
|
||||
|
||||
const FILE_PROJECT_PATH: &str = "root/src/workspace_snapshot.rs";
|
||||
const FILE_ABS_PATH: &str = "/root/src/workspace_snapshot.rs";
|
||||
|
||||
#[derive(Clone)]
|
||||
struct EditOp {
|
||||
old_text: String,
|
||||
new_text: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct EditFixture {
|
||||
name: &'static str,
|
||||
old_file_text: String,
|
||||
expected_file_text: String,
|
||||
edits: Vec<EditOp>,
|
||||
}
|
||||
|
||||
struct BenchmarkHarness {
|
||||
cx: Option<TestAppContext>,
|
||||
edit_tool: Option<Arc<EditFileTool>>,
|
||||
thread: Option<Entity<Thread>>,
|
||||
partial_payloads: Vec<Value>,
|
||||
final_payload: Value,
|
||||
expected_file_text: String,
|
||||
editor: Option<Entity<Editor>>,
|
||||
window: Option<AnyWindowHandle>,
|
||||
// Keeps the LSP buffer-registration handle and the fake language server alive
|
||||
// for the lifetime of the benchmark so `didChange`/diagnostics keep flowing
|
||||
// while edits are applied.
|
||||
keep_alive: Vec<Box<dyn Any>>,
|
||||
}
|
||||
|
||||
impl Drop for BenchmarkHarness {
|
||||
fn drop(&mut self) {
|
||||
// Release our handles to the entities first.
|
||||
self.edit_tool.take();
|
||||
self.thread.take();
|
||||
self.editor.take();
|
||||
self.keep_alive.clear();
|
||||
|
||||
if let Some(mut cx) = self.cx.take() {
|
||||
// Close the editor window so the editor entity and the buffer handles
|
||||
// it holds are released, then pump the executor so cancelled editor /
|
||||
// action-log background tasks drop their captured handles before the
|
||||
// leak detector runs on `TestAppContext` drop.
|
||||
if let Some(window) = self.window.take() {
|
||||
cx.update_window(window, |_, window, _| window.remove_window())
|
||||
.ok();
|
||||
}
|
||||
cx.update(|_| {});
|
||||
cx.executor().run_until_parked();
|
||||
cx.quit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn edit_file_tool_streaming(c: &mut Criterion) {
|
||||
let fixtures = fixtures();
|
||||
let mut group = c.benchmark_group("edit_file_tool_streaming");
|
||||
group.sample_size(10);
|
||||
|
||||
for fixture in fixtures {
|
||||
let new_bytes: usize = fixture.edits.iter().map(|edit| edit.new_text.len()).sum();
|
||||
group.throughput(Throughput::Bytes(new_bytes as u64));
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new(fixture.name, fixture.old_file_text.len()),
|
||||
&fixture,
|
||||
|bench, fixture| {
|
||||
bench.iter_batched(
|
||||
|| setup_harness(fixture.clone()),
|
||||
|mut harness| {
|
||||
let output = run_streamed_edit(&mut harness);
|
||||
let EditFileToolOutput::Success { new_text, .. } = &output else {
|
||||
panic!("expected edit_file tool to succeed");
|
||||
};
|
||||
assert_eq!(new_text, &harness.expected_file_text);
|
||||
// Return the harness as part of the output so its teardown (which has
|
||||
// to pump the executor to release `Entity<Buffer>` handles captured by
|
||||
// background tasks) runs in criterion's drop phase after the timer has
|
||||
// stopped, rather than inside the timed region.
|
||||
(black_box(output), harness)
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
fn setup_harness(fixture: EditFixture) -> BenchmarkHarness {
|
||||
let mut cx = init_context();
|
||||
let executor = cx.executor();
|
||||
let parts = block_on_executor(
|
||||
&executor,
|
||||
setup_editor_and_tool(&mut cx, fixture.old_file_text.clone()),
|
||||
);
|
||||
// Let the LSP handshake, initial parse, and first layout settle before timing.
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let partial_payloads = streamed_partial_payloads(&fixture.edits);
|
||||
let final_payload = json!({
|
||||
"path": FILE_PROJECT_PATH,
|
||||
"edits": fixture
|
||||
.edits
|
||||
.iter()
|
||||
.map(|edit| json!({ "old_text": edit.old_text, "new_text": edit.new_text }))
|
||||
.collect::<Vec<_>>(),
|
||||
});
|
||||
|
||||
BenchmarkHarness {
|
||||
cx: Some(cx),
|
||||
edit_tool: Some(parts.edit_tool),
|
||||
thread: Some(parts.thread),
|
||||
partial_payloads,
|
||||
final_payload,
|
||||
expected_file_text: fixture.expected_file_text,
|
||||
editor: Some(parts.editor),
|
||||
window: Some(parts.window),
|
||||
keep_alive: parts.keep_alive,
|
||||
}
|
||||
}
|
||||
|
||||
struct HarnessParts {
|
||||
edit_tool: Arc<EditFileTool>,
|
||||
thread: Entity<Thread>,
|
||||
editor: Entity<Editor>,
|
||||
window: AnyWindowHandle,
|
||||
keep_alive: Vec<Box<dyn Any>>,
|
||||
}
|
||||
|
||||
/// Builds a project + edit tool, opens the target buffer in an editor view inside
|
||||
/// a window, and attaches a fake Rust language server. This mirrors the real app:
|
||||
/// the edited file is open in a pane with a language server, so each buffer edit
|
||||
/// drives the editor's observer cascade (matching brackets, code actions, outline,
|
||||
/// bracket colorization), a tree-sitter reparse, and an LSP `didChange` +
|
||||
/// diagnostics round-trip — the costs that dominate a real agent edit.
|
||||
async fn setup_editor_and_tool(cx: &mut TestAppContext, file_text: String) -> HarnessParts {
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(
|
||||
"/root",
|
||||
json!({
|
||||
"src": {
|
||||
"workspace_snapshot.rs": file_text,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
let project = Project::test(fs, [Path::new("/root")], cx).await;
|
||||
let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
|
||||
language_registry.add(rust_lang());
|
||||
let mut fake_servers = language_registry.register_fake_lsp(
|
||||
"Rust",
|
||||
FakeLspAdapter {
|
||||
capabilities: lsp::ServerCapabilities {
|
||||
text_document_sync: Some(lsp::TextDocumentSyncCapability::Kind(
|
||||
lsp::TextDocumentSyncKind::INCREMENTAL,
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
let context_server_registry =
|
||||
cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
|
||||
let model = Arc::new(FakeLanguageModel::default());
|
||||
let thread = cx.new(|cx| {
|
||||
Thread::new(
|
||||
project.clone(),
|
||||
cx.new(|_cx| ProjectContext::default()),
|
||||
context_server_registry,
|
||||
Templates::new(),
|
||||
Some(model),
|
||||
cx,
|
||||
)
|
||||
});
|
||||
let action_log: Entity<ActionLog> =
|
||||
thread.read_with(cx, |thread, _cx| thread.action_log().clone());
|
||||
let edit_tool = Arc::new(EditFileTool::new(
|
||||
project.clone(),
|
||||
thread.downgrade(),
|
||||
action_log,
|
||||
language_registry,
|
||||
));
|
||||
|
||||
// Open the same buffer the tool will edit and register it with the language
|
||||
// servers so edits produce `didChange` notifications.
|
||||
let buffer = project
|
||||
.update(cx, |project, cx| {
|
||||
project.open_local_buffer(FILE_ABS_PATH, cx)
|
||||
})
|
||||
.await
|
||||
.expect("failed to open buffer");
|
||||
let lsp_handle = project.update(cx, |project, cx| {
|
||||
project.register_buffer_with_language_servers(&buffer, cx)
|
||||
});
|
||||
|
||||
let fake_server = fake_servers
|
||||
.next()
|
||||
.await
|
||||
.expect("fake language server should start");
|
||||
// Publish diagnostics on every edit, mirroring a real server reacting to
|
||||
// `didChange`, so the editor's diagnostics path runs per edit.
|
||||
let server = fake_server.clone();
|
||||
fake_server.handle_notification::<lsp::notification::DidChangeTextDocument, _>(
|
||||
move |params, _cx| {
|
||||
server.notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
|
||||
uri: params.text_document.uri.clone(),
|
||||
version: Some(params.text_document.version),
|
||||
diagnostics: vec![lsp::Diagnostic {
|
||||
range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 1)),
|
||||
severity: Some(lsp::DiagnosticSeverity::WARNING),
|
||||
message: "bench diagnostic".to_string(),
|
||||
..Default::default()
|
||||
}],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Attach an editor view in a window and lay it out once so the viewport-gated
|
||||
// observers (bracket colorization, selection highlights) have a visible range.
|
||||
let window = cx.add_window(|window, cx| {
|
||||
let mut editor = Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
|
||||
editor.set_style(EditorStyle::default(), window, cx);
|
||||
window.focus(&editor.focus_handle(cx), cx);
|
||||
editor
|
||||
});
|
||||
let editor = window.root(cx).expect("window should have an editor root");
|
||||
let window: AnyWindowHandle = window.into();
|
||||
// Lay out and paint a real frame so the editor establishes a viewport (this
|
||||
// is what makes the viewport-gated observers like bracket colorization run).
|
||||
{
|
||||
let mut visual_cx = gpui::VisualTestContext::from_window(window, &*cx);
|
||||
visual_cx.draw(
|
||||
gpui::point(gpui::px(0.0), gpui::px(0.0)),
|
||||
gpui::size(gpui::px(1024.0), gpui::px(768.0)),
|
||||
|_, _| editor.clone().into_any_element(),
|
||||
);
|
||||
}
|
||||
|
||||
let keep_alive: Vec<Box<dyn Any>> = vec![
|
||||
Box::new(lsp_handle),
|
||||
Box::new(fake_server),
|
||||
Box::new(fake_servers),
|
||||
Box::new(buffer),
|
||||
];
|
||||
|
||||
HarnessParts {
|
||||
edit_tool,
|
||||
thread,
|
||||
editor,
|
||||
window,
|
||||
keep_alive,
|
||||
}
|
||||
}
|
||||
|
||||
fn init_context() -> TestAppContext {
|
||||
let cx = TestAppContext::single();
|
||||
cx.update(|cx| {
|
||||
let settings_store = SettingsStore::test(cx);
|
||||
cx.set_global(settings_store);
|
||||
assets::Assets.load_test_fonts(cx);
|
||||
theme_settings::init(theme::LoadThemes::JustBase, cx);
|
||||
editor::init(cx);
|
||||
SettingsStore::update_global(cx, |store: &mut SettingsStore, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings
|
||||
.project
|
||||
.all_languages
|
||||
.defaults
|
||||
.ensure_final_newline_on_save = Some(false);
|
||||
settings.project.all_languages.defaults.colorize_brackets = Some(true);
|
||||
});
|
||||
});
|
||||
|
||||
let mut agent_settings = AgentSettings::get_global(cx).clone();
|
||||
agent_settings.tool_permissions.tools.insert(
|
||||
EditFileTool::NAME.into(),
|
||||
ToolRules {
|
||||
default: Some(settings::ToolPermissionMode::Allow),
|
||||
always_allow: vec![],
|
||||
always_deny: vec![],
|
||||
always_confirm: vec![],
|
||||
invalid_patterns: vec![],
|
||||
},
|
||||
);
|
||||
AgentSettings::override_global(agent_settings, cx);
|
||||
});
|
||||
cx
|
||||
}
|
||||
|
||||
fn run_streamed_edit(harness: &mut BenchmarkHarness) -> EditFileToolOutput {
|
||||
let (mut sender, input): (_, ToolInput<EditFileToolInput>) = ToolInput::test();
|
||||
for payload in &harness.partial_payloads {
|
||||
sender.send_partial(payload.clone());
|
||||
}
|
||||
sender.send_full(harness.final_payload.clone());
|
||||
|
||||
let (event_stream, _event_rx) = ToolCallEventStream::test();
|
||||
let cx = harness
|
||||
.cx
|
||||
.as_ref()
|
||||
.expect("benchmark harness should have a cx");
|
||||
let task = cx.update(|cx| {
|
||||
harness
|
||||
.edit_tool
|
||||
.as_ref()
|
||||
.expect("benchmark harness should have an edit tool")
|
||||
.clone()
|
||||
.run(input, event_stream, cx)
|
||||
});
|
||||
|
||||
let executor = harness
|
||||
.cx
|
||||
.as_ref()
|
||||
.expect("benchmark harness should have a cx")
|
||||
.executor();
|
||||
block_on_executor(&executor, task).unwrap()
|
||||
}
|
||||
|
||||
fn block_on_executor<R>(executor: &BackgroundExecutor, future: impl Future<Output = R>) -> R {
|
||||
pin_mut!(future);
|
||||
let waker = noop_waker();
|
||||
let mut task_context = Context::from_waker(&waker);
|
||||
|
||||
for _ in 0..10_000 {
|
||||
if let Poll::Ready(output) = future.as_mut().poll(&mut task_context) {
|
||||
return output;
|
||||
}
|
||||
executor.run_until_parked();
|
||||
}
|
||||
|
||||
panic!("future did not complete while running edit_file_tool benchmark");
|
||||
}
|
||||
|
||||
/// Builds the streamed partial payloads for a (possibly multi-edit) session,
|
||||
/// mirroring how the agent reveals one edit at a time: earlier edits stay
|
||||
/// complete in the array while the current edit streams its `old_text` then its
|
||||
/// `new_text` in chunks.
|
||||
fn streamed_partial_payloads(edits: &[EditOp]) -> Vec<Value> {
|
||||
let path = FILE_PROJECT_PATH;
|
||||
let mut payloads = vec![json!({ "path": path }), json!({ "path": path })];
|
||||
|
||||
for index in 0..edits.len() {
|
||||
let completed: Vec<Value> = edits[..index]
|
||||
.iter()
|
||||
.map(|edit| json!({ "old_text": edit.old_text, "new_text": edit.new_text }))
|
||||
.collect();
|
||||
let edit = &edits[index];
|
||||
|
||||
for old_end in chunk_ends(&edit.old_text, OLD_TEXT_CHUNK_SIZE) {
|
||||
let mut arr = completed.clone();
|
||||
arr.push(json!({ "old_text": &edit.old_text[..old_end] }));
|
||||
payloads.push(json!({ "path": path, "edits": arr }));
|
||||
}
|
||||
|
||||
let mut arr = completed.clone();
|
||||
arr.push(json!({ "old_text": edit.old_text, "new_text": "" }));
|
||||
payloads.push(json!({ "path": path, "edits": arr }));
|
||||
|
||||
for new_end in chunk_ends(&edit.new_text, NEW_TEXT_CHUNK_SIZE) {
|
||||
let mut arr = completed.clone();
|
||||
arr.push(json!({ "old_text": edit.old_text, "new_text": &edit.new_text[..new_end] }));
|
||||
payloads.push(json!({ "path": path, "edits": arr }));
|
||||
}
|
||||
}
|
||||
|
||||
payloads
|
||||
}
|
||||
|
||||
fn chunk_ends(text: &str, chunk_size: usize) -> impl Iterator<Item = usize> + '_ {
|
||||
let mut end = 0;
|
||||
std::iter::from_fn(move || {
|
||||
if end == text.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
end = (end + chunk_size).min(text.len());
|
||||
while !text.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
Some(end)
|
||||
})
|
||||
}
|
||||
|
||||
fn fixtures() -> Vec<EditFixture> {
|
||||
vec![
|
||||
make_fixture(
|
||||
"tiny_function_rewrite",
|
||||
2,
|
||||
EditPattern::LocalizedRewrite {
|
||||
start_line: 12,
|
||||
line_count: 6,
|
||||
},
|
||||
SEED,
|
||||
),
|
||||
make_fixture(
|
||||
"small_function_rewrite",
|
||||
5,
|
||||
EditPattern::LocalizedRewrite {
|
||||
start_line: 22,
|
||||
line_count: 12,
|
||||
},
|
||||
SEED + 1,
|
||||
),
|
||||
make_fixture(
|
||||
"medium_many_small_changes",
|
||||
8,
|
||||
EditPattern::ManySmallChanges { every_nth_line: 7 },
|
||||
SEED + 2,
|
||||
),
|
||||
make_fixture(
|
||||
"medium_insertions",
|
||||
8,
|
||||
EditPattern::InsertHelperBlocks { every_nth_line: 9 },
|
||||
SEED + 3,
|
||||
),
|
||||
make_large_multi_edit_fixture("large_multi_edit", 80, 16, SEED + 4),
|
||||
]
|
||||
}
|
||||
|
||||
enum EditPattern {
|
||||
LocalizedRewrite {
|
||||
start_line: usize,
|
||||
line_count: usize,
|
||||
},
|
||||
ManySmallChanges {
|
||||
every_nth_line: usize,
|
||||
},
|
||||
InsertHelperBlocks {
|
||||
every_nth_line: usize,
|
||||
},
|
||||
}
|
||||
|
||||
fn make_fixture(
|
||||
name: &'static str,
|
||||
function_count: usize,
|
||||
pattern: EditPattern,
|
||||
seed: u64,
|
||||
) -> EditFixture {
|
||||
let mut rng = StdRng::seed_from_u64(seed);
|
||||
let old_lines = random_rust_module(&mut rng, function_count);
|
||||
let edit_range = edit_range(&old_lines, &pattern);
|
||||
let old_text = old_lines[edit_range.clone()].join("\n");
|
||||
let mut new_lines = old_lines.clone();
|
||||
|
||||
match pattern {
|
||||
EditPattern::LocalizedRewrite { .. } => {
|
||||
rewrite_local_block(&mut new_lines[edit_range.clone()], &mut rng)
|
||||
}
|
||||
EditPattern::ManySmallChanges { every_nth_line } => {
|
||||
rewrite_many_small_lines(&mut new_lines[edit_range.clone()], every_nth_line, &mut rng)
|
||||
}
|
||||
EditPattern::InsertHelperBlocks { every_nth_line } => {
|
||||
insert_helper_blocks(&mut new_lines, edit_range.clone(), every_nth_line, &mut rng)
|
||||
}
|
||||
}
|
||||
|
||||
let new_text_end = edit_range.end + new_lines.len().saturating_sub(old_lines.len());
|
||||
let old_file_text = old_lines.join("\n");
|
||||
let expected_file_text = new_lines.join("\n");
|
||||
let new_text = new_lines[edit_range.start..new_text_end].join("\n");
|
||||
|
||||
EditFixture {
|
||||
name,
|
||||
old_file_text,
|
||||
expected_file_text,
|
||||
edits: vec![EditOp { old_text, new_text }],
|
||||
}
|
||||
}
|
||||
|
||||
fn make_large_multi_edit_fixture(
|
||||
name: &'static str,
|
||||
function_count: usize,
|
||||
edit_count: usize,
|
||||
seed: u64,
|
||||
) -> EditFixture {
|
||||
const HEADER_LINES: usize = 10;
|
||||
const FUNCTION_LINES: usize = 12;
|
||||
const FUNCTION_BODY_LINES: usize = 11;
|
||||
|
||||
let mut rng = StdRng::seed_from_u64(seed);
|
||||
let old_lines = random_rust_module(&mut rng, function_count);
|
||||
let old_file_text = old_lines.join("\n");
|
||||
|
||||
let step = (function_count / edit_count).max(1);
|
||||
let mut picks: Vec<usize> = (0..edit_count)
|
||||
.map(|k| (k * step).min(function_count - 1))
|
||||
.collect();
|
||||
picks.dedup();
|
||||
|
||||
let replacements: Vec<(usize, Vec<String>)> = picks
|
||||
.iter()
|
||||
.map(|&function_index| {
|
||||
(
|
||||
function_index,
|
||||
large_function_lines(&mut rng, function_index),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let edits = replacements
|
||||
.iter()
|
||||
.map(|(function_index, new_function)| {
|
||||
let start = HEADER_LINES + function_index * FUNCTION_LINES;
|
||||
let end = start + FUNCTION_BODY_LINES;
|
||||
EditOp {
|
||||
old_text: old_lines[start..end].join("\n"),
|
||||
new_text: new_function.join("\n"),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut new_lines = old_lines;
|
||||
for (function_index, new_function) in replacements.iter().rev() {
|
||||
let start = HEADER_LINES + function_index * FUNCTION_LINES;
|
||||
let end = start + FUNCTION_BODY_LINES;
|
||||
new_lines.splice(start..end, new_function.iter().cloned());
|
||||
}
|
||||
let expected_file_text = new_lines.join("\n");
|
||||
|
||||
EditFixture {
|
||||
name,
|
||||
old_file_text,
|
||||
expected_file_text,
|
||||
edits,
|
||||
}
|
||||
}
|
||||
|
||||
fn large_function_lines(rng: &mut StdRng, index: usize) -> Vec<String> {
|
||||
let function_name = identifier(rng, index + 40_000);
|
||||
let argument_name = identifier(rng, index + 41_000);
|
||||
|
||||
let mut lines = vec![
|
||||
format!(
|
||||
" pub fn {function_name}(&mut self, {argument_name}: usize) -> Result<usize> {{"
|
||||
),
|
||||
format!(" let mut accumulator = {argument_name};"),
|
||||
];
|
||||
|
||||
let body_lines = rng.random_range(30..42);
|
||||
for body_index in 0..body_lines {
|
||||
let local_name = identifier(rng, index + 50_000 + body_index);
|
||||
let multiplier = rng.random_range(2..19);
|
||||
let offset = rng.random_range(1..256);
|
||||
match body_index % 4 {
|
||||
0 => lines.push(format!(
|
||||
" let {local_name} = accumulator.saturating_mul({multiplier}).saturating_add({offset});"
|
||||
)),
|
||||
1 => lines.push(format!(
|
||||
" accumulator = {local_name}.saturating_sub(self.version % {offset}.max(1));"
|
||||
)),
|
||||
2 => lines.push(format!(
|
||||
" if {local_name} % {multiplier} == 0 {{ accumulator = accumulator.saturating_add({local_name}); }}"
|
||||
)),
|
||||
_ => lines.push(format!(
|
||||
" self.buffers.insert(\"{local_name}\".to_string(), accumulator);"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(" self.version = self.version.saturating_add(accumulator);".to_string());
|
||||
lines.push(" Ok(accumulator)".to_string());
|
||||
lines.push(" }".to_string());
|
||||
lines
|
||||
}
|
||||
|
||||
fn edit_range(lines: &[String], pattern: &EditPattern) -> std::ops::Range<usize> {
|
||||
let mut range = match pattern {
|
||||
EditPattern::LocalizedRewrite {
|
||||
start_line,
|
||||
line_count,
|
||||
} => *start_line..(*start_line + *line_count).min(lines.len()),
|
||||
EditPattern::ManySmallChanges { .. } | EditPattern::InsertHelperBlocks { .. } => {
|
||||
10..lines.len().saturating_sub(5)
|
||||
}
|
||||
};
|
||||
|
||||
while range.end > range.start && lines[range.end - 1].is_empty() {
|
||||
range.end -= 1;
|
||||
}
|
||||
|
||||
range
|
||||
}
|
||||
|
||||
fn random_rust_module(rng: &mut StdRng, function_count: usize) -> Vec<String> {
|
||||
let mut lines = vec![
|
||||
"use anyhow::{Context as _, Result};".to_string(),
|
||||
"use collections::HashMap;".to_string(),
|
||||
"".to_string(),
|
||||
"#[derive(Clone, Debug)]".to_string(),
|
||||
"pub struct WorkspaceSnapshot {".to_string(),
|
||||
" buffers: HashMap<String, usize>,".to_string(),
|
||||
" version: usize,".to_string(),
|
||||
"}".to_string(),
|
||||
"".to_string(),
|
||||
"impl WorkspaceSnapshot {".to_string(),
|
||||
];
|
||||
|
||||
for function_index in 0..function_count {
|
||||
let function_name = identifier(rng, function_index);
|
||||
let argument_name = identifier(rng, function_index + 1_000);
|
||||
let local_name = identifier(rng, function_index + 2_000);
|
||||
let branch_name = identifier(rng, function_index + 3_000);
|
||||
let multiplier = rng.random_range(2..17);
|
||||
let offset = rng.random_range(1..128);
|
||||
|
||||
lines.extend([
|
||||
format!(
|
||||
" pub fn {function_name}(&mut self, {argument_name}: usize) -> Result<usize> {{"
|
||||
),
|
||||
format!(" let mut {local_name} = {argument_name}.saturating_mul({multiplier});"),
|
||||
format!(" if {local_name} % 2 == 0 {{"),
|
||||
format!(
|
||||
" {local_name} = {local_name}.saturating_add(self.version + {offset});"
|
||||
),
|
||||
" } else {".to_string(),
|
||||
format!(" {local_name} = {local_name}.saturating_sub({offset});"),
|
||||
" }".to_string(),
|
||||
format!(" let {branch_name} = self.buffers.len().saturating_add({local_name});"),
|
||||
format!(" self.version = self.version.saturating_add({branch_name});"),
|
||||
format!(" Ok({branch_name})"),
|
||||
" }".to_string(),
|
||||
"".to_string(),
|
||||
]);
|
||||
}
|
||||
|
||||
lines.push("}".to_string());
|
||||
lines.push("".to_string());
|
||||
lines.push("pub fn normalize_path(path: &str) -> String {".to_string());
|
||||
lines.push(" path.replace('\\\\', \"/\")".to_string());
|
||||
lines.push("}".to_string());
|
||||
lines
|
||||
}
|
||||
|
||||
fn rewrite_local_block(lines: &mut [String], rng: &mut StdRng) {
|
||||
for (line_index, line) in lines.iter_mut().enumerate() {
|
||||
let suffix = identifier(rng, line_index + 10_000);
|
||||
if line.contains("saturating_add") {
|
||||
*line = format!(
|
||||
" let {suffix} = self.version.checked_add({line_index}).context(\"version overflow\")?;"
|
||||
);
|
||||
} else if line.contains("saturating_sub") {
|
||||
*line = format!(
|
||||
" {suffix}.saturating_sub({});",
|
||||
rng.random_range(8..256)
|
||||
);
|
||||
} else if line.trim().is_empty() {
|
||||
*line =
|
||||
format!(" tracing::trace!(target: \"agent_bench\", value = {line_index});");
|
||||
} else {
|
||||
*line = format!("{line} // updated {suffix}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn rewrite_many_small_lines(lines: &mut [String], every_nth_line: usize, rng: &mut StdRng) {
|
||||
for (line_index, line) in lines.iter_mut().enumerate() {
|
||||
if line_index.is_multiple_of(every_nth_line) || line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let suffix = identifier(rng, line_index + 20_000);
|
||||
*line = format!("{line} // audited {suffix}");
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_helper_blocks(
|
||||
lines: &mut Vec<String>,
|
||||
range: std::ops::Range<usize>,
|
||||
every_nth_line: usize,
|
||||
rng: &mut StdRng,
|
||||
) {
|
||||
let mut line_index = range.start;
|
||||
while line_index < range.end.min(lines.len()) {
|
||||
if line_index.is_multiple_of(every_nth_line) && !lines[line_index].trim().is_empty() {
|
||||
let suffix = identifier(rng, line_index + 30_000);
|
||||
lines.splice(
|
||||
line_index..line_index,
|
||||
[
|
||||
format!(" let {suffix}_before = self.version;"),
|
||||
format!(" tracing::debug!(version = {suffix}_before);"),
|
||||
],
|
||||
);
|
||||
line_index += 2;
|
||||
}
|
||||
line_index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn identifier(rng: &mut StdRng, salt: usize) -> String {
|
||||
const PARTS: &[&str] = &[
|
||||
"alpha", "beta", "gamma", "delta", "epsilon", "zeta", "theta", "lambda", "sigma", "omega",
|
||||
];
|
||||
format!(
|
||||
"{}_{}_{}",
|
||||
PARTS[rng.random_range(0..PARTS.len())],
|
||||
salt,
|
||||
rng.random_range(0..10_000)
|
||||
)
|
||||
}
|
||||
|
||||
criterion_group!(benches, edit_file_tool_streaming);
|
||||
criterion_main!(benches);
|
||||
|
|
@ -3,6 +3,7 @@ mod legacy_thread;
|
|||
mod native_agent_server;
|
||||
pub mod outline;
|
||||
mod pattern_extraction;
|
||||
mod sandboxing;
|
||||
mod templates;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
|
@ -10,7 +11,6 @@ mod thread;
|
|||
mod thread_store;
|
||||
mod tool_permissions;
|
||||
mod tools;
|
||||
mod user_agents_md;
|
||||
|
||||
use context_server::ContextServerId;
|
||||
pub use db::*;
|
||||
|
|
@ -23,7 +23,6 @@ pub use thread::*;
|
|||
pub use thread_store::*;
|
||||
pub use tool_permissions::*;
|
||||
pub use tools::*;
|
||||
pub use user_agents_md::{UserAgentsMd, UserAgentsMdState, init as init_user_agents_md};
|
||||
|
||||
use acp_thread::{
|
||||
AcpThread, AgentModelSelector, AgentSessionInfo, AgentSessionList, AgentSessionListRequest,
|
||||
|
|
@ -51,10 +50,7 @@ use language_model::{IconOrSvg, LanguageModel, LanguageModelProvider, LanguageMo
|
|||
use project::{
|
||||
AgentId, Project, ProjectItem, ProjectPath, Worktree, trusted_worktrees::TrustedWorktrees,
|
||||
};
|
||||
use prompt_store::{
|
||||
ProjectContext, PromptStore, RULES_FILE_NAMES, RulesFileContext, UserRulesContext,
|
||||
WorktreeContext,
|
||||
};
|
||||
use prompt_store::{ProjectContext, RULES_FILE_NAMES, RulesFileContext, WorktreeContext};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use settings::{LanguageModelSelection, Settings as _, update_settings_file};
|
||||
use std::any::Any;
|
||||
|
|
@ -308,7 +304,6 @@ pub struct NativeAgent {
|
|||
templates: Arc<Templates>,
|
||||
/// Cached model information
|
||||
models: LanguageModels,
|
||||
prompt_store: Option<Entity<PromptStore>>,
|
||||
fs: Arc<dyn Fs>,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
/// Tracks the lifecycle of global skills directory observation. We
|
||||
|
|
@ -355,20 +350,16 @@ impl NativeAgent {
|
|||
pub fn new(
|
||||
thread_store: Entity<ThreadStore>,
|
||||
templates: Arc<Templates>,
|
||||
prompt_store: Option<Entity<PromptStore>>,
|
||||
fs: Arc<dyn Fs>,
|
||||
cx: &mut App,
|
||||
) -> Entity<NativeAgent> {
|
||||
log::debug!("Creating new NativeAgent");
|
||||
|
||||
cx.new(|cx| {
|
||||
let mut subscriptions = vec![cx.subscribe(
|
||||
let subscriptions = vec![cx.subscribe(
|
||||
&LanguageModelRegistry::global(cx),
|
||||
Self::handle_models_updated_event,
|
||||
)];
|
||||
if let Some(prompt_store) = prompt_store.as_ref() {
|
||||
subscriptions.push(cx.subscribe(prompt_store, Self::handle_prompts_updated_event))
|
||||
}
|
||||
|
||||
if !cx.has_global::<SkillIndex>() {
|
||||
cx.set_global(SkillIndex::default());
|
||||
|
|
@ -381,7 +372,6 @@ impl NativeAgent {
|
|||
projects: HashMap::default(),
|
||||
templates,
|
||||
models: LanguageModels::new(cx),
|
||||
prompt_store,
|
||||
fs,
|
||||
_subscriptions: subscriptions,
|
||||
skills_state: SkillsState::default(),
|
||||
|
|
@ -640,7 +630,7 @@ impl NativeAgent {
|
|||
return project_id;
|
||||
}
|
||||
|
||||
let project_context = cx.new(|_| ProjectContext::new(vec![], vec![]));
|
||||
let project_context = cx.new(|_| ProjectContext::new(vec![]));
|
||||
self.register_project_with_initial_context(project.clone(), project_context, cx);
|
||||
if let Some(state) = self.projects.get_mut(&project_id) {
|
||||
state.project_context_needs_refresh.send(()).ok();
|
||||
|
|
@ -733,7 +723,6 @@ impl NativeAgent {
|
|||
.context("project state not found")?;
|
||||
anyhow::Ok(Self::build_project_context(
|
||||
&state.project,
|
||||
this.prompt_store.as_ref(),
|
||||
this.fs.clone(),
|
||||
cx,
|
||||
))
|
||||
|
|
@ -805,7 +794,6 @@ impl NativeAgent {
|
|||
|
||||
fn build_project_context(
|
||||
project: &Entity<Project>,
|
||||
prompt_store: Option<&Entity<PromptStore>>,
|
||||
fs: Arc<dyn Fs>,
|
||||
cx: &mut App,
|
||||
) -> Task<(ProjectContext, Vec<Skill>, Vec<SkillLoadError>)> {
|
||||
|
|
@ -887,22 +875,8 @@ impl NativeAgent {
|
|||
.collect();
|
||||
cx.background_spawn(async move { future::join_all(project_skills_futures).await })
|
||||
};
|
||||
let default_user_rules_task = if let Some(prompt_store) = prompt_store.as_ref() {
|
||||
prompt_store.read_with(cx, |prompt_store, cx| {
|
||||
let prompts = prompt_store.default_prompt_metadata();
|
||||
let load_tasks = prompts.into_iter().map(|prompt_metadata| {
|
||||
let contents = prompt_store.load(prompt_metadata.id, cx);
|
||||
async move { (contents.await, prompt_metadata) }
|
||||
});
|
||||
cx.background_spawn(future::join_all(load_tasks))
|
||||
})
|
||||
} else {
|
||||
Task::ready(vec![])
|
||||
};
|
||||
|
||||
cx.spawn(async move |_cx| {
|
||||
let (worktrees, default_user_rules) =
|
||||
future::join(future::join_all(worktree_tasks), default_user_rules_task).await;
|
||||
let worktrees = future::join_all(worktree_tasks).await;
|
||||
|
||||
let worktrees = worktrees
|
||||
.into_iter()
|
||||
|
|
@ -915,27 +889,6 @@ impl NativeAgent {
|
|||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let default_user_rules = default_user_rules
|
||||
.into_iter()
|
||||
.flat_map(|(contents, prompt_metadata)| match contents {
|
||||
Ok(contents) => Some(UserRulesContext {
|
||||
uuid: prompt_metadata.id.as_user()?,
|
||||
title: prompt_metadata.title.map(|title| title.to_string()),
|
||||
contents,
|
||||
}),
|
||||
Err(_err) => {
|
||||
// TODO: show error message
|
||||
// this.update(cx, |_, cx| {
|
||||
// cx.emit(RulesLoadingError {
|
||||
// message: format!("{err:?}").into(),
|
||||
// });
|
||||
// })
|
||||
// .ok();
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Load and combine skills. `combine_skills` deliberately
|
||||
// does NOT deduplicate — the autocomplete popup needs to
|
||||
// see every entry so users can disambiguate same-named
|
||||
|
|
@ -959,8 +912,7 @@ impl NativeAgent {
|
|||
let (catalog_skills, budget_errors) = select_catalog_skills(&overridden);
|
||||
skill_errors.extend(budget_errors);
|
||||
|
||||
let project_context =
|
||||
ProjectContext::new(worktrees, default_user_rules).with_skills(catalog_skills);
|
||||
let project_context = ProjectContext::new(worktrees).with_skills(catalog_skills);
|
||||
(project_context, skills, skill_errors)
|
||||
})
|
||||
}
|
||||
|
|
@ -1121,17 +1073,6 @@ impl NativeAgent {
|
|||
}
|
||||
}
|
||||
|
||||
fn handle_prompts_updated_event(
|
||||
&mut self,
|
||||
_prompt_store: Entity<PromptStore>,
|
||||
_event: &prompt_store::PromptsUpdatedEvent,
|
||||
_cx: &mut Context<Self>,
|
||||
) {
|
||||
for state in self.projects.values_mut() {
|
||||
state.project_context_needs_refresh.send(()).ok();
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_models_updated_event(
|
||||
&mut self,
|
||||
_registry: Entity<LanguageModelRegistry>,
|
||||
|
|
@ -1766,6 +1707,16 @@ impl NativeAgentConnection {
|
|||
.update(cx, |agent, cx| agent.ensure_skills_scan_started(cx));
|
||||
}
|
||||
|
||||
pub fn refresh_skills_for_project(&self, project: Entity<Project>, cx: &mut App) {
|
||||
self.0.update(cx, |agent, cx| {
|
||||
let project_id = agent.get_or_create_project_state(&project, cx);
|
||||
agent.ensure_skills_scan_started(cx);
|
||||
if let Some(state) = agent.projects.get_mut(&project_id) {
|
||||
state.project_context_needs_refresh.send(()).ok();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn available_skills(
|
||||
&self,
|
||||
session_id: &acp::SessionId,
|
||||
|
|
@ -1834,10 +1785,10 @@ impl NativeAgentConnection {
|
|||
match event {
|
||||
ThreadEvent::UserMessage(message) => {
|
||||
acp_thread.update(cx, |thread, cx| {
|
||||
for content in message.content {
|
||||
for content in &*message.content {
|
||||
thread.push_user_content_block(
|
||||
Some(message.id.clone()),
|
||||
content.into(),
|
||||
content.clone().into(),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
|
|
@ -2659,12 +2610,54 @@ impl ThreadEnvironment for NativeThreadEnvironment {
|
|||
fn create_terminal(
|
||||
&self,
|
||||
command: String,
|
||||
extra_env: Vec<acp::EnvVariable>,
|
||||
cwd: Option<PathBuf>,
|
||||
output_byte_limit: Option<u64>,
|
||||
sandbox_wrap: Option<acp_thread::SandboxWrap>,
|
||||
cx: &mut AsyncApp,
|
||||
) -> Task<Result<Rc<dyn TerminalHandle>>> {
|
||||
// Use a per-thread temp directory for all terminal commands, even when
|
||||
// sandboxing is disabled, so the model can't infer sandbox state from
|
||||
// `$TMPDIR` changing between conversations.
|
||||
let mut extra_env = extra_env;
|
||||
let mut sandbox_wrap = sandbox_wrap;
|
||||
match self
|
||||
.thread
|
||||
.update(cx, |thread, cx| thread.sandboxed_terminal_temp_dir(cx))
|
||||
{
|
||||
Ok(Ok(temp_dir)) => {
|
||||
// Canonicalize so the path matches what the sandbox resolves
|
||||
// symlinks to (e.g. `/var` -> `/private/var` on macOS).
|
||||
// `$TMPDIR` and the writable-scope entry below must agree, and
|
||||
// they must agree with the path the kernel actually checks.
|
||||
let temp_dir = temp_dir.canonicalize().unwrap_or(temp_dir);
|
||||
let temp_dir_string = temp_dir.to_string_lossy().into_owned();
|
||||
extra_env.extend([
|
||||
acp::EnvVariable::new("TMPDIR", &temp_dir_string),
|
||||
acp::EnvVariable::new("TMP", &temp_dir_string),
|
||||
acp::EnvVariable::new("TEMP", &temp_dir_string),
|
||||
]);
|
||||
// The command's `$TMPDIR` must live inside the sandbox's
|
||||
// writable scope. The per-thread temp directory is owned here
|
||||
// (not in the terminal tool that assembles the rest of the
|
||||
// writable set), so add it whenever the command is sandboxed.
|
||||
if let Some(sandbox_wrap) = &mut sandbox_wrap {
|
||||
sandbox_wrap.writable_paths.push(temp_dir);
|
||||
}
|
||||
}
|
||||
Ok(Err(error)) => return Task::ready(Err(error)),
|
||||
Err(error) => return Task::ready(Err(error)),
|
||||
};
|
||||
let task = self.acp_thread.update(cx, |thread, cx| {
|
||||
thread.create_terminal(command, vec![], vec![], cwd, output_byte_limit, cx)
|
||||
thread.create_terminal(
|
||||
command,
|
||||
vec![],
|
||||
extra_env,
|
||||
cwd,
|
||||
output_byte_limit,
|
||||
sandbox_wrap,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let acp_thread = self.acp_thread.clone();
|
||||
|
|
@ -3491,7 +3484,7 @@ mod internal_tests {
|
|||
let project = Project::test(fs.clone(), [], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), fs.clone(), cx));
|
||||
|
||||
// Creating a session registers the project and triggers context building.
|
||||
let connection = NativeAgentConnection(agent.clone());
|
||||
|
|
@ -3582,7 +3575,7 @@ mod internal_tests {
|
|||
let project = Project::test(fs.clone(), [], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), fs.clone(), cx));
|
||||
|
||||
// Simulate the user-interaction trigger that the agent panel
|
||||
// fires (input focus, slash autocomplete, or submit). In tests
|
||||
|
|
@ -3645,7 +3638,7 @@ mod internal_tests {
|
|||
let project = Project::test(fs.clone(), [], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), fs.clone(), cx));
|
||||
|
||||
// First scan trigger: nothing on disk yet, state stays idle.
|
||||
cx.update(|cx| {
|
||||
|
|
@ -3722,7 +3715,7 @@ mod internal_tests {
|
|||
let project = Project::test(fs.clone(), [], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), fs.clone(), cx));
|
||||
|
||||
// First scan trigger: nothing on disk yet.
|
||||
cx.update(|cx| {
|
||||
|
|
@ -3868,7 +3861,7 @@ mod internal_tests {
|
|||
let project = Project::test(fs.clone(), [], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), fs.clone(), cx));
|
||||
|
||||
// Open a parent session through the connection, the same way
|
||||
// production does. This triggers project-context refresh which
|
||||
|
|
@ -3981,7 +3974,7 @@ mod internal_tests {
|
|||
let project = Project::test(fs.clone(), [], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), fs.clone(), cx));
|
||||
|
||||
let connection = NativeAgentConnection(agent.clone());
|
||||
let acp_thread = cx
|
||||
|
|
@ -4086,7 +4079,7 @@ mod internal_tests {
|
|||
Project::test_with_worktree_trust(fs.clone(), [Path::new("/project")], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), fs.clone(), cx));
|
||||
|
||||
let connection = NativeAgentConnection(agent.clone());
|
||||
let acp_thread = cx
|
||||
|
|
@ -4167,10 +4160,9 @@ mod internal_tests {
|
|||
fs.insert_tree("/", json!({ "a": {} })).await;
|
||||
let project = Project::test(fs.clone(), [], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let connection =
|
||||
NativeAgentConnection(cx.update(|cx| {
|
||||
NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx)
|
||||
}));
|
||||
let connection = NativeAgentConnection(
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), fs.clone(), cx)),
|
||||
);
|
||||
|
||||
// Create a thread/session
|
||||
let acp_thread = cx
|
||||
|
|
@ -4244,7 +4236,7 @@ mod internal_tests {
|
|||
|
||||
// Create the agent and connection
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), fs.clone(), cx));
|
||||
let connection = NativeAgentConnection(agent.clone());
|
||||
|
||||
// Create a thread/session
|
||||
|
|
@ -4341,7 +4333,7 @@ mod internal_tests {
|
|||
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), fs.clone(), cx));
|
||||
let connection = NativeAgentConnection(agent.clone());
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -4432,7 +4424,7 @@ mod internal_tests {
|
|||
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), None, fs.clone(), cx));
|
||||
cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -4483,9 +4475,8 @@ mod internal_tests {
|
|||
fs.insert_tree("/", json!({ "a": {} })).await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent = cx
|
||||
.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
// Register a thinking model.
|
||||
|
|
@ -4586,9 +4577,8 @@ mod internal_tests {
|
|||
fs.insert_tree("/", json!({ "a": {} })).await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent = cx
|
||||
.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
// Register a model where id() != name(), like real Anthropic models
|
||||
|
|
@ -4702,9 +4692,8 @@ mod internal_tests {
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent = cx
|
||||
.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -4884,9 +4873,8 @@ mod internal_tests {
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent = cx
|
||||
.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -4965,9 +4953,8 @@ mod internal_tests {
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent = cx
|
||||
.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -5049,9 +5036,8 @@ mod internal_tests {
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent = cx
|
||||
.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -5194,9 +5180,8 @@ mod internal_tests {
|
|||
fs.insert_tree("/", json!({ "a": {} })).await;
|
||||
let project = Project::test(fs.clone(), [], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent = cx
|
||||
.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ use sqlez::{
|
|||
connection::Connection,
|
||||
statement::Statement,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use std::{io::ErrorKind, path::PathBuf, sync::Arc};
|
||||
use ui::{App, SharedString};
|
||||
use util::path_list::PathList;
|
||||
use zed_env_vars::ZED_STATELESS;
|
||||
|
|
@ -53,7 +53,7 @@ impl From<&DbThreadMetadata> for acp_thread::AgentSessionInfo {
|
|||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct DbThread {
|
||||
pub title: SharedString,
|
||||
pub messages: Vec<DbMessage>,
|
||||
pub messages: Vec<Arc<DbMessage>>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
#[serde(default)]
|
||||
pub detailed_summary: Option<SharedString>,
|
||||
|
|
@ -81,6 +81,8 @@ pub struct DbThread {
|
|||
pub draft_prompt: Option<Vec<acp::ContentBlock>>,
|
||||
#[serde(default)]
|
||||
pub ui_scroll_position: Option<SerializedScrollPosition>,
|
||||
#[serde(default)]
|
||||
pub sandboxed_terminal_temp_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
|
|
@ -92,7 +94,7 @@ pub struct SerializedScrollPosition {
|
|||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SharedThread {
|
||||
pub title: SharedString,
|
||||
pub messages: Vec<DbMessage>,
|
||||
pub messages: Vec<Arc<DbMessage>>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
#[serde(default)]
|
||||
pub model: Option<DbLanguageModel>,
|
||||
|
|
@ -130,6 +132,7 @@ impl SharedThread {
|
|||
thinking_effort: None,
|
||||
draft_prompt: None,
|
||||
ui_scroll_position: None,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -206,7 +209,7 @@ impl DbThread {
|
|||
crate::Message::User(UserMessage {
|
||||
// MessageId from old format can't be meaningfully converted, so generate a new one
|
||||
id,
|
||||
content,
|
||||
content: Arc::from(content),
|
||||
})
|
||||
}
|
||||
language_model::Role::Assistant => {
|
||||
|
|
@ -285,7 +288,7 @@ impl DbThread {
|
|||
}
|
||||
};
|
||||
|
||||
messages.push(message);
|
||||
messages.push(Arc::new(message));
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
|
|
@ -309,6 +312,7 @@ impl DbThread {
|
|||
thinking_effort: None,
|
||||
draft_prompt: None,
|
||||
ui_scroll_position: None,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -569,15 +573,7 @@ impl ThreadsDatabase {
|
|||
|
||||
let rows = select(id.0)?;
|
||||
if let Some((data_type, data)) = rows.into_iter().next() {
|
||||
let json_data = match data_type {
|
||||
DataType::Zstd => {
|
||||
let decompressed = zstd::decode_all(&data[..])?;
|
||||
String::from_utf8(decompressed)?
|
||||
}
|
||||
DataType::Json => String::from_utf8(data)?,
|
||||
};
|
||||
let thread = DbThread::from_json(json_data.as_bytes())?;
|
||||
Ok(Some(thread))
|
||||
Ok(Some(Self::deserialize_thread(data_type, data)?))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
|
|
@ -596,17 +592,71 @@ impl ThreadsDatabase {
|
|||
.spawn(async move { Self::save_thread_sync(&connection, id, thread, &folder_paths) })
|
||||
}
|
||||
|
||||
fn deserialize_thread(data_type: DataType, data: Vec<u8>) -> Result<DbThread> {
|
||||
let json_data = match data_type {
|
||||
DataType::Zstd => {
|
||||
let decompressed = zstd::decode_all(&data[..])?;
|
||||
String::from_utf8(decompressed)?
|
||||
}
|
||||
DataType::Json => String::from_utf8(data)?,
|
||||
};
|
||||
DbThread::from_json(json_data.as_bytes())
|
||||
}
|
||||
|
||||
fn sandboxed_terminal_temp_dir(data_type: DataType, data: Vec<u8>) -> Option<PathBuf> {
|
||||
match Self::deserialize_thread(data_type, data) {
|
||||
Ok(thread) => thread.sandboxed_terminal_temp_dir,
|
||||
Err(error) => {
|
||||
log::warn!("failed to deserialize thread before deleting it: {error:#}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_sandboxed_terminal_temp_dir(temp_dir: PathBuf) {
|
||||
match std::fs::remove_dir_all(&temp_dir) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => {}
|
||||
Err(error) => {
|
||||
log::warn!(
|
||||
"failed to remove sandboxed terminal temp directory {}: {error}",
|
||||
temp_dir.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn delete_thread(&self, id: acp::SessionId) -> Task<Result<()>> {
|
||||
let connection = self.connection.clone();
|
||||
|
||||
self.executor.spawn(async move {
|
||||
let connection = connection.lock();
|
||||
let sandboxed_terminal_temp_dir = {
|
||||
let connection = connection.lock();
|
||||
|
||||
let mut delete = connection.exec_bound::<Arc<str>>(indoc! {"
|
||||
DELETE FROM threads WHERE id = ?
|
||||
"})?;
|
||||
let mut select =
|
||||
connection.select_bound::<Arc<str>, (DataType, Vec<u8>)>(indoc! {"
|
||||
SELECT data_type, data FROM threads WHERE id = ? LIMIT 1
|
||||
"})?;
|
||||
|
||||
delete(id.0)?;
|
||||
let sandboxed_terminal_temp_dir = select(id.0.clone())?
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|(data_type, data)| {
|
||||
Self::sandboxed_terminal_temp_dir(data_type, data)
|
||||
});
|
||||
|
||||
let mut delete = connection.exec_bound::<Arc<str>>(indoc! {"
|
||||
DELETE FROM threads WHERE id = ?
|
||||
"})?;
|
||||
|
||||
delete(id.0)?;
|
||||
|
||||
sandboxed_terminal_temp_dir
|
||||
};
|
||||
|
||||
if let Some(temp_dir) = sandboxed_terminal_temp_dir {
|
||||
Self::remove_sandboxed_terminal_temp_dir(temp_dir);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
|
|
@ -616,13 +666,32 @@ impl ThreadsDatabase {
|
|||
let connection = self.connection.clone();
|
||||
|
||||
self.executor.spawn(async move {
|
||||
let connection = connection.lock();
|
||||
let sandboxed_terminal_temp_dirs = {
|
||||
let connection = connection.lock();
|
||||
|
||||
let mut delete = connection.exec_bound::<()>(indoc! {"
|
||||
DELETE FROM threads
|
||||
"})?;
|
||||
let mut select = connection.select_bound::<(), (DataType, Vec<u8>)>(indoc! {"
|
||||
SELECT data_type, data FROM threads
|
||||
"})?;
|
||||
|
||||
delete(())?;
|
||||
let sandboxed_terminal_temp_dirs = select(())?
|
||||
.into_iter()
|
||||
.filter_map(|(data_type, data)| {
|
||||
Self::sandboxed_terminal_temp_dir(data_type, data)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let mut delete = connection.exec_bound::<()>(indoc! {"
|
||||
DELETE FROM threads
|
||||
"})?;
|
||||
|
||||
delete(())?;
|
||||
|
||||
sandboxed_terminal_temp_dirs
|
||||
};
|
||||
|
||||
for temp_dir in sandboxed_terminal_temp_dirs {
|
||||
Self::remove_sandboxed_terminal_temp_dir(temp_dir);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
|
|
@ -694,6 +763,7 @@ mod tests {
|
|||
thinking_effort: None,
|
||||
draft_prompt: None,
|
||||
ui_scroll_position: None,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -797,6 +867,78 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sandboxed_terminal_temp_dir_defaults_to_none() {
|
||||
let json = r#"{
|
||||
"title": "Old Thread",
|
||||
"messages": [],
|
||||
"updated_at": "2024-01-01T00:00:00Z"
|
||||
}"#;
|
||||
|
||||
let db_thread: DbThread = serde_json::from_str(json).expect("Failed to deserialize");
|
||||
|
||||
assert!(
|
||||
db_thread.sandboxed_terminal_temp_dir.is_none(),
|
||||
"Legacy threads without sandboxed_terminal_temp_dir should default to None"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_sandboxed_terminal_temp_dir_roundtrips_through_save_load(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let database = ThreadsDatabase::new(cx.executor()).unwrap();
|
||||
let thread_id = session_id("sandbox-temp-dir-thread");
|
||||
let temp_dir = tempfile::Builder::new()
|
||||
.prefix("zed-agent-terminal-test-")
|
||||
.tempdir()
|
||||
.unwrap()
|
||||
.keep();
|
||||
let mut thread = make_thread(
|
||||
"Sandbox Temp Dir Thread",
|
||||
Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(),
|
||||
);
|
||||
thread.sandboxed_terminal_temp_dir = Some(temp_dir.clone());
|
||||
|
||||
database
|
||||
.save_thread(thread_id.clone(), thread, PathList::default())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let loaded = database
|
||||
.load_thread(thread_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("thread should exist");
|
||||
assert_eq!(loaded.sandboxed_terminal_temp_dir, Some(temp_dir.clone()));
|
||||
std::fs::remove_dir_all(temp_dir).unwrap();
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_delete_thread_removes_sandboxed_terminal_temp_dir(cx: &mut TestAppContext) {
|
||||
let database = ThreadsDatabase::new(cx.executor()).unwrap();
|
||||
let thread_id = session_id("sandbox-temp-dir-delete-thread");
|
||||
let temp_dir = tempfile::Builder::new()
|
||||
.prefix("zed-agent-terminal-test-")
|
||||
.tempdir()
|
||||
.unwrap()
|
||||
.keep();
|
||||
std::fs::write(temp_dir.join("sentinel"), b"content").unwrap();
|
||||
let mut thread = make_thread(
|
||||
"Sandbox Temp Dir Delete Thread",
|
||||
Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(),
|
||||
);
|
||||
thread.sandboxed_terminal_temp_dir = Some(temp_dir.clone());
|
||||
|
||||
database
|
||||
.save_thread(thread_id.clone(), thread, PathList::default())
|
||||
.await
|
||||
.unwrap();
|
||||
database.delete_thread(thread_id).await.unwrap();
|
||||
|
||||
assert!(!temp_dir.exists());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_subagent_context_roundtrips_through_save_load(cx: &mut TestAppContext) {
|
||||
let database = ThreadsDatabase::new(cx.executor()).unwrap();
|
||||
|
|
|
|||
|
|
@ -9,9 +9,7 @@ use fs::Fs;
|
|||
use gpui::{App, Entity, Task};
|
||||
use language_model::{LanguageModelId, LanguageModelProviderId, LanguageModelRegistry};
|
||||
use project::{AgentId, Project};
|
||||
use prompt_store::PromptStore;
|
||||
use settings::{LanguageModelSelection, Settings as _, update_settings_file};
|
||||
use util::ResultExt as _;
|
||||
|
||||
use crate::{NativeAgent, NativeAgentConnection, ThreadStore, templates::Templates};
|
||||
|
||||
|
|
@ -45,15 +43,12 @@ impl AgentServer for NativeAgentServer {
|
|||
log::debug!("NativeAgentServer::connect");
|
||||
let fs = self.fs.clone();
|
||||
let thread_store = self.thread_store.clone();
|
||||
let prompt_store = PromptStore::global(cx);
|
||||
cx.spawn(async move |cx| {
|
||||
log::debug!("Creating templates for native agent");
|
||||
let templates = Templates::new();
|
||||
let prompt_store = prompt_store.await.log_err();
|
||||
|
||||
log::debug!("Creating native agent entity");
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store, templates, prompt_store, fs, cx));
|
||||
let agent = cx.update(|cx| NativeAgent::new(thread_store, templates, fs, cx));
|
||||
|
||||
// Create the connection wrapper
|
||||
let connection = NativeAgentConnection(agent);
|
||||
|
|
|
|||
|
|
@ -11,10 +11,15 @@ pub const AUTO_OUTLINE_SIZE: usize = 16384;
|
|||
|
||||
/// Result of getting buffer content, which can be either full content or an outline.
|
||||
pub struct BufferContent {
|
||||
/// The actual content (either full text or outline)
|
||||
/// The actual content (either full text, a symbol outline, or a
|
||||
/// truncated fallback — see `is_synthetic`).
|
||||
pub text: String,
|
||||
/// Whether this is an outline (true) or full content (false)
|
||||
pub is_outline: bool,
|
||||
/// `true` when `text` is not the file's full content — either a symbol
|
||||
/// outline or the truncated first-1KB fallback used when no outline is
|
||||
/// available. Callers that prefix line numbers to file content must
|
||||
/// skip prefixing in this case, because line numbers in `text` would
|
||||
/// not correspond to the file's real line numbers.
|
||||
pub is_synthetic: bool,
|
||||
}
|
||||
|
||||
/// Returns either the full content of a buffer or its outline, depending on size.
|
||||
|
|
@ -44,7 +49,10 @@ pub async fn get_buffer_content_or_outline(
|
|||
.collect::<Vec<_>>()
|
||||
});
|
||||
|
||||
// If no outline exists, fall back to first 1KB so the agent has some context
|
||||
// If no outline exists, fall back to first 1KB so the agent has some context.
|
||||
// This is reported as `is_synthetic: true` because the returned text is not
|
||||
// the file's full content — it has a synthetic header and is truncated — so
|
||||
// callers must not attach real-file line numbers to it.
|
||||
if outline_items.is_empty() {
|
||||
let text = buffer.read_with(cx, |buffer, _| {
|
||||
let snapshot = buffer.snapshot();
|
||||
|
|
@ -59,7 +67,7 @@ pub async fn get_buffer_content_or_outline(
|
|||
|
||||
return Ok(BufferContent {
|
||||
text,
|
||||
is_outline: false,
|
||||
is_synthetic: true,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -72,14 +80,14 @@ pub async fn get_buffer_content_or_outline(
|
|||
};
|
||||
Ok(BufferContent {
|
||||
text,
|
||||
is_outline: true,
|
||||
is_synthetic: true,
|
||||
})
|
||||
} else {
|
||||
// File is small enough, return full content
|
||||
let text = buffer.read_with(cx, |buffer, _| buffer.text());
|
||||
Ok(BufferContent {
|
||||
text,
|
||||
is_outline: false,
|
||||
is_synthetic: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -196,10 +204,13 @@ mod tests {
|
|||
"Result did not contain content subset"
|
||||
);
|
||||
|
||||
// Should be marked as not an outline (it's truncated content)
|
||||
// Should be marked synthetic: the returned text is not the file's full
|
||||
// content (it's a truncated first-1KB fallback with a synthetic header), so
|
||||
// callers must treat it the same as the symbol-outline case and not attach
|
||||
// real-file line numbers to it.
|
||||
assert!(
|
||||
!result.is_outline,
|
||||
"Large file without outline should not be marked as outline"
|
||||
result.is_synthetic,
|
||||
"Truncated fallback should be reported as synthetic so callers skip line numbering"
|
||||
);
|
||||
|
||||
// Should be reasonably sized (much smaller than original)
|
||||
|
|
|
|||
25
crates/agent/src/sandboxing.rs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
//! Agent-side glue for the [`sandbox`] crate.
|
||||
//!
|
||||
//! Centralizes the "should agent-run terminal commands be sandboxed for this
|
||||
//! process?" check so the system prompt, the terminal tool, and any other
|
||||
//! caller see the same answer (and so the `target_os` gate lives in one
|
||||
//! place instead of scattered across the agent crate).
|
||||
//!
|
||||
//! The current policy is: enabled iff we're on macOS *and* the user has the
|
||||
//! `sandboxing` feature flag turned on. There's deliberately no settings or
|
||||
//! env-var override yet — the flag is the only switch.
|
||||
//!
|
||||
//! On non-macOS hosts we don't have a sandbox integration today, so this
|
||||
//! returns `false` regardless of the flag.
|
||||
//!
|
||||
//! Naming note: this module is about agent terminal sandboxing specifically.
|
||||
//! Other agent operations (e.g. file edits) are gated separately.
|
||||
|
||||
use feature_flags::{FeatureFlagAppExt as _, SandboxingFeatureFlag};
|
||||
use gpui::App;
|
||||
|
||||
/// Whether agent-run terminal commands should be wrapped in an OS-level
|
||||
/// sandbox for this process. See module docs for the policy.
|
||||
pub(crate) fn sandboxing_enabled(cx: &App) -> bool {
|
||||
cfg!(target_os = "macos") && cx.has_flag::<SandboxingFeatureFlag>()
|
||||
}
|
||||
|
|
@ -43,6 +43,12 @@ pub struct SystemPromptTemplate<'a> {
|
|||
/// Contents of the user-global `~/.config/zed/AGENTS.md` file (or the
|
||||
/// platform equivalent), if present and non-empty.
|
||||
pub user_agents_md: Option<SharedString>,
|
||||
/// Whether agent-run terminal commands are wrapped in an OS-level
|
||||
/// sandbox for this conversation. When `true`, the rendered prompt
|
||||
/// describes the sandbox's read/write/network rules and the
|
||||
/// per-command flags the model can request to relax them. When
|
||||
/// `false`, the prompt omits the sandbox section entirely.
|
||||
pub sandboxing: bool,
|
||||
}
|
||||
|
||||
impl Template for SystemPromptTemplate<'_> {
|
||||
|
|
@ -83,10 +89,11 @@ mod tests {
|
|||
let project = prompt_store::ProjectContext::default();
|
||||
let template = SystemPromptTemplate {
|
||||
project: &project,
|
||||
available_tools: vec!["echo".into(), "update_plan".into()],
|
||||
available_tools: vec!["echo".into(), "update_plan".into(), "update_title".into()],
|
||||
model_name: Some("test-model".to_string()),
|
||||
date: "2026-01-01".to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: false,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
|
|
@ -94,6 +101,7 @@ mod tests {
|
|||
assert!(rendered.contains("Today's Date: 2026-01-01"));
|
||||
assert!(rendered.contains("## Fixing Diagnostics"));
|
||||
assert!(rendered.contains("## Planning"));
|
||||
assert!(rendered.contains("## Session Title"));
|
||||
assert!(rendered.contains("test-model"));
|
||||
}
|
||||
|
||||
|
|
@ -111,13 +119,14 @@ mod tests {
|
|||
project_entry_id: 1,
|
||||
}),
|
||||
}];
|
||||
let project = ProjectContext::new(worktrees, Vec::new());
|
||||
let project = ProjectContext::new(worktrees);
|
||||
let template = SystemPromptTemplate {
|
||||
project: &project,
|
||||
available_tools: vec!["echo".into()],
|
||||
model_name: Some("test-model".to_string()),
|
||||
date: "2026-01-01".to_string(),
|
||||
user_agents_md: Some("always be concise".into()),
|
||||
sandboxing: false,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
|
|
@ -135,6 +144,78 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_system_prompt_omits_sandbox_section_when_sandboxing_disabled() {
|
||||
let project = prompt_store::ProjectContext::default();
|
||||
let template = SystemPromptTemplate {
|
||||
project: &project,
|
||||
available_tools: vec!["echo".into()],
|
||||
model_name: Some("test-model".to_string()),
|
||||
date: "2026-01-01".to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: false,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
assert!(!rendered.contains("## Terminal sandbox"));
|
||||
assert!(!rendered.contains("allow_network"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_system_prompt_renders_sandbox_section_with_worktrees_when_enabled() {
|
||||
use prompt_store::{ProjectContext, WorktreeContext};
|
||||
|
||||
let worktrees = vec![
|
||||
WorktreeContext {
|
||||
root_name: "alpha".to_string(),
|
||||
abs_path: std::path::Path::new("/tmp/alpha").into(),
|
||||
rules_file: None,
|
||||
},
|
||||
WorktreeContext {
|
||||
root_name: "beta".to_string(),
|
||||
abs_path: std::path::Path::new("/tmp/beta").into(),
|
||||
rules_file: None,
|
||||
},
|
||||
];
|
||||
let project = ProjectContext::new(worktrees);
|
||||
let template = SystemPromptTemplate {
|
||||
project: &project,
|
||||
available_tools: vec!["echo".into()],
|
||||
model_name: Some("test-model".to_string()),
|
||||
date: "2026-01-01".to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: true,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
|
||||
assert!(rendered.contains("## Terminal sandbox"));
|
||||
assert!(rendered.contains("`/tmp/alpha`"));
|
||||
assert!(rendered.contains("`/tmp/beta`"));
|
||||
assert!(rendered.contains("allow_network: true"));
|
||||
assert!(rendered.contains("allow_fs_write: true"));
|
||||
assert!(rendered.contains("unsandboxed: true"));
|
||||
assert!(rendered.contains("remain in effect for the entire duration"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_system_prompt_sandbox_section_handles_zero_worktrees() {
|
||||
let project = prompt_store::ProjectContext::default();
|
||||
let template = SystemPromptTemplate {
|
||||
project: &project,
|
||||
available_tools: vec!["echo".into()],
|
||||
model_name: Some("test-model".to_string()),
|
||||
date: "2026-01-01".to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: true,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
|
||||
assert!(rendered.contains("## Terminal sandbox"));
|
||||
assert!(rendered.contains("No project directories are currently writable"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_system_prompt_omits_user_agents_md_section_when_absent() {
|
||||
let project = prompt_store::ProjectContext::default();
|
||||
|
|
@ -144,9 +225,28 @@ mod tests {
|
|||
model_name: Some("test-model".to_string()),
|
||||
date: "2026-01-01".to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: false,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
assert!(!rendered.contains("### Personal `AGENTS.md`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_system_prompt_does_not_render_legacy_zed_rules_section() {
|
||||
let project = prompt_store::ProjectContext::default();
|
||||
let template = SystemPromptTemplate {
|
||||
project: &project,
|
||||
available_tools: vec!["echo".into()],
|
||||
model_name: Some("test-model".to_string()),
|
||||
date: "2026-01-01".to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: false,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
|
||||
assert!(!rendered.contains("The user has specified the following rules"));
|
||||
assert!(!rendered.contains("Rules title:"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -52,6 +52,17 @@ Use a plan when:
|
|||
- The user asked you to do more than one thing in a single prompt.
|
||||
- You discover additional steps while working and intend to complete them before yielding to the user.
|
||||
|
||||
{{/if}}
|
||||
{{#if (contains available_tools 'update_title') }}
|
||||
## Session Title
|
||||
|
||||
- Use the `update_title` tool to set the title shown to the user for the current session.
|
||||
- You MUST set a title at least once, even for small tasks. Do it early in the conversation, after the first user message, before you start working. There is no title to begin with, so you are responsible for setting one.
|
||||
- Update the title again whenever the goal changes materially.
|
||||
- Titles are very important to communicate to the user what you are working on. A session should always have a title.
|
||||
- Keep titles concise and specific. Prefer a short noun phrase over a full sentence, and do not wrap the title in quotes.
|
||||
- Do not mention that you changed the title unless it is directly relevant to the user.
|
||||
|
||||
{{/if}}
|
||||
## Searching and Reading
|
||||
|
||||
|
|
@ -162,12 +173,11 @@ The current project contains the following root directories:
|
|||
You are powered by the model named {{model_name}}.
|
||||
|
||||
{{/if}}
|
||||
{{#if (or has_rules has_user_rules)}}
|
||||
{{#if has_rules}}
|
||||
## User's Custom Instructions
|
||||
|
||||
The following additional instructions are provided by the user and should be followed to the best of your ability{{#if (gt (len available_tools) 0)}} without interfering with the tool use guidelines{{/if}}.
|
||||
|
||||
{{#if has_rules}}
|
||||
There are project rules that apply to these root directories:
|
||||
{{#each worktrees}}
|
||||
{{#if rules_file}}
|
||||
|
|
@ -178,17 +188,3 @@ There are project rules that apply to these root directories:
|
|||
{{/if}}
|
||||
{{/each}}
|
||||
{{/if}}
|
||||
|
||||
{{#if has_user_rules}}
|
||||
The user has specified the following rules that should be applied:
|
||||
{{#each user_rules}}
|
||||
|
||||
{{#if title}}
|
||||
Rules title: {{title}}
|
||||
{{/if}}
|
||||
``````
|
||||
{{contents}}
|
||||
``````
|
||||
{{/each}}
|
||||
{{/if}}
|
||||
{{/if}}
|
||||
|
|
|
|||
|
|
@ -23,15 +23,13 @@ graph TD
|
|||
A[Start] --> B[End]
|
||||
```
|
||||
|
||||
The renderer supports the following diagram types: flowchart, sequence, class, state, ER, gantt, pie, gitgraph, mindmap, timeline, quadrant chart, xy chart, and journey. Other diagram types will only show as code.
|
||||
|
||||
Mermaid diagrams are automatically themed to match the user's editor theme. Do not include `%%{init}%%` directives or define your own `classDef` styles.
|
||||
|
||||
Do *NOT* include inline HTML elements in mermaid diagrams, as they cannot be rendered. It is better to simply skip formatting (e.g. bold/italic/etc.).
|
||||
|
||||
When you need accent colors for emphasis (e.g. color-coding layers, categories, or states), use the pre-defined classes `accent0` through `accent7` with the `:::` syntax:
|
||||
|
||||
A:::accent0 --> B:::accent1 --> C:::accent2
|
||||
|
||||
These classes automatically match the user's theme. Do not hardcode hex color values unless an exact color match is specifically required. Note that the rendered view may be narrow, so try to prioritize generating taller diagrams over wider ones.
|
||||
Mermaid diagrams are automatically color-coded using the user's theme accent palette. Do not hardcode hex color values unless an exact color match is specifically required. Note that the rendered view may be narrow, so try to prioritize generating taller diagrams over wider ones.
|
||||
|
||||
{{#if (gt (len available_tools) 0)}}
|
||||
## Tool Use
|
||||
|
|
@ -74,6 +72,17 @@ Use a plan when:
|
|||
- The user asked you to do more than one thing in a single prompt.
|
||||
- You discover additional steps while working and intend to complete them before yielding to the user.
|
||||
|
||||
{{/if}}
|
||||
{{#if (contains available_tools 'update_title') }}
|
||||
## Session Title
|
||||
|
||||
- Use the `update_title` tool to set the title shown to the user for the current session.
|
||||
- You MUST set a title at least once, even for small tasks. Do it early in the conversation, after the first user message, before you start working. There is no title to begin with, so you are responsible for setting one.
|
||||
- Update the title again whenever the goal changes materially.
|
||||
- Titles are very important to communicate to the user what you are working on. A session should always have a title.
|
||||
- Keep titles concise and specific. Prefer a short noun phrase over a full sentence, and do not wrap the title in quotes.
|
||||
- Do not mention that you changed the title unless it is directly relevant to the user.
|
||||
|
||||
{{/if}}
|
||||
## Searching and Reading
|
||||
|
||||
|
|
@ -178,6 +187,24 @@ The current project contains the following root directories:
|
|||
- `{{abs_path}}`
|
||||
{{/each}}
|
||||
|
||||
{{#if sandboxing}}
|
||||
## Terminal sandbox
|
||||
|
||||
The `terminal` tool runs commands inside a sandbox with these permissions:
|
||||
|
||||
- Reads: any path on the filesystem is readable.
|
||||
- Writes: a per-thread temporary directory exposed via `$TMPDIR`, `$TMP`, and `$TEMP` is writable and persists across `terminal` calls in this conversation{{#if worktrees}}, along with these project directories:
|
||||
{{#each worktrees}}
|
||||
- `{{abs_path}}`
|
||||
{{/each}}
|
||||
Writes anywhere else on the filesystem are blocked.{{else}}. No project directories are currently writable.{{/if}}
|
||||
- Network: outbound network access is blocked.
|
||||
|
||||
You can request elevated permissions on individual `terminal` calls by setting `allow_network: true`, `allow_fs_write: true`, or `unsandboxed: true`. The user will be prompted to approve before the command runs.
|
||||
|
||||
These sandbox settings are guaranteed to remain in effect for the entire duration of this conversation. If they ever change, you will be told.
|
||||
|
||||
{{/if}}
|
||||
{{#if model_name}}
|
||||
## Model Information
|
||||
|
||||
|
|
@ -212,7 +239,7 @@ To use a Skill:
|
|||
4. If the Skill references additional files, use `read_file` to access them. Paths inside a Skill resolve relative to that Skill's directory (the parent of its `SKILL.md`).
|
||||
|
||||
{{/if}}
|
||||
{{#if (or user_agents_md has_rules has_user_rules)}}
|
||||
{{#if (or user_agents_md has_rules)}}
|
||||
## User's Custom Instructions
|
||||
|
||||
The following additional instructions are provided by the user and should be followed to the best of your ability{{#if (gt (len available_tools) 0)}} without interfering with the tool use guidelines{{/if}}.
|
||||
|
|
@ -243,16 +270,4 @@ There are project rules that apply to these root directories:
|
|||
{{/each}}
|
||||
{{/if}}
|
||||
|
||||
{{#if has_user_rules}}
|
||||
The user has specified the following rules that should be applied:
|
||||
{{#each user_rules}}
|
||||
|
||||
{{#if title}}
|
||||
Rules title: {{title}}
|
||||
{{/if}}
|
||||
``````
|
||||
{{contents}}
|
||||
``````
|
||||
{{/each}}
|
||||
{{/if}}
|
||||
{{/if}}
|
||||
|
|
|
|||
|
|
@ -200,8 +200,10 @@ impl crate::ThreadEnvironment for FakeThreadEnvironment {
|
|||
fn create_terminal(
|
||||
&self,
|
||||
_command: String,
|
||||
_extra_env: Vec<acp::EnvVariable>,
|
||||
_cwd: Option<std::path::PathBuf>,
|
||||
_output_byte_limit: Option<u64>,
|
||||
_sandbox_wrap: Option<acp_thread::SandboxWrap>,
|
||||
_cx: &mut AsyncApp,
|
||||
) -> Task<Result<Rc<dyn crate::TerminalHandle>>> {
|
||||
self.terminal_creations.fetch_add(1, Ordering::SeqCst);
|
||||
|
|
@ -242,8 +244,10 @@ impl crate::ThreadEnvironment for MultiTerminalEnvironment {
|
|||
fn create_terminal(
|
||||
&self,
|
||||
_command: String,
|
||||
_extra_env: Vec<acp::EnvVariable>,
|
||||
_cwd: Option<std::path::PathBuf>,
|
||||
_output_byte_limit: Option<u64>,
|
||||
_sandbox_wrap: Option<acp_thread::SandboxWrap>,
|
||||
cx: &mut AsyncApp,
|
||||
) -> Task<Result<Rc<dyn crate::TerminalHandle>>> {
|
||||
let handle = Rc::new(cx.update(|cx| FakeTerminalHandle::new_never_exits(cx)));
|
||||
|
|
@ -320,6 +324,7 @@ async fn test_terminal_tool_timeout_kills_handle(cx: &mut TestAppContext) {
|
|||
command: "sleep 1000".to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: Some(5),
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -387,6 +392,7 @@ async fn test_terminal_tool_without_timeout_does_not_kill_handle(cx: &mut TestAp
|
|||
command: "sleep 1000".to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -3520,8 +3526,8 @@ async fn test_agent_connection(cx: &mut TestAppContext) {
|
|||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
|
||||
// Create agent and connection
|
||||
let agent = cx
|
||||
.update(|cx| NativeAgent::new(thread_store, templates.clone(), None, fake_fs.clone(), cx));
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store, templates.clone(), fake_fs.clone(), cx));
|
||||
let connection = NativeAgentConnection(agent.clone());
|
||||
|
||||
// Create a thread using new_thread
|
||||
|
|
@ -3807,6 +3813,155 @@ async fn test_update_plan_tool_updates_thread_events(cx: &mut TestAppContext) {
|
|||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_update_title_tool_sets_thread_title(cx: &mut TestAppContext) {
|
||||
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
|
||||
let fake_model = model.as_fake();
|
||||
let summary_model = Arc::new(FakeLanguageModel::default());
|
||||
|
||||
cx.update(|cx| {
|
||||
cx.update_flags(true, vec!["update-title-tool".to_string()]);
|
||||
});
|
||||
thread.update(cx, |thread, cx| {
|
||||
thread.add_tool(UpdateTitleTool::new(cx.weak_entity()));
|
||||
thread.set_summarization_model(Some(summary_model.clone()), cx);
|
||||
});
|
||||
|
||||
let mut events = thread
|
||||
.update(cx, |thread, cx| {
|
||||
thread.send(UserMessageId::new(), ["Explore title tooling"], cx)
|
||||
})
|
||||
.unwrap();
|
||||
cx.run_until_parked();
|
||||
|
||||
let input = json!({
|
||||
"title": "Session title tool"
|
||||
});
|
||||
fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
|
||||
LanguageModelToolUse {
|
||||
id: "title_1".into(),
|
||||
name: UpdateTitleTool::NAME.into(),
|
||||
raw_input: input.to_string(),
|
||||
input,
|
||||
is_input_complete: true,
|
||||
thought_signature: None,
|
||||
},
|
||||
));
|
||||
fake_model.end_last_completion_stream();
|
||||
cx.run_until_parked();
|
||||
|
||||
let tool_call = expect_tool_call(&mut events).await;
|
||||
assert_eq!(
|
||||
tool_call,
|
||||
acp::ToolCall::new("title_1", "Update title: Session title tool")
|
||||
.kind(acp::ToolKind::Think)
|
||||
.raw_input(json!({
|
||||
"title": "Session title tool"
|
||||
}))
|
||||
.meta(acp::Meta::from_iter([(
|
||||
"tool_name".into(),
|
||||
"update_title".into()
|
||||
)]))
|
||||
);
|
||||
|
||||
let update = expect_tool_call_update_fields(&mut events).await;
|
||||
assert_eq!(
|
||||
update,
|
||||
acp::ToolCallUpdate::new(
|
||||
"title_1",
|
||||
acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress)
|
||||
)
|
||||
);
|
||||
|
||||
let update = expect_tool_call_update_fields(&mut events).await;
|
||||
assert_eq!(
|
||||
update,
|
||||
acp::ToolCallUpdate::new(
|
||||
"title_1",
|
||||
acp::ToolCallUpdateFields::new()
|
||||
.status(acp::ToolCallStatus::Completed)
|
||||
.raw_output("Session title updated")
|
||||
)
|
||||
);
|
||||
|
||||
thread.read_with(cx, |thread, _| {
|
||||
assert_eq!(thread.title(), Some("Session title tool".into()));
|
||||
});
|
||||
assert_eq!(summary_model.pending_completions(), Vec::new());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_update_title_availability_suppresses_summary_title_generation(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
|
||||
let fake_model = model.as_fake();
|
||||
let summary_model = Arc::new(FakeLanguageModel::default());
|
||||
|
||||
cx.update(|cx| {
|
||||
cx.update_flags(true, vec!["update-title-tool".to_string()]);
|
||||
});
|
||||
thread.update(cx, |thread, cx| {
|
||||
thread.add_tool(UpdateTitleTool::new(cx.weak_entity()));
|
||||
thread.set_summarization_model(Some(summary_model.clone()), cx);
|
||||
});
|
||||
|
||||
let send = thread
|
||||
.update(cx, |thread, cx| {
|
||||
thread.send(UserMessageId::new(), ["Explore title tooling"], cx)
|
||||
})
|
||||
.unwrap();
|
||||
cx.run_until_parked();
|
||||
|
||||
fake_model.send_last_completion_stream_text_chunk("Done");
|
||||
fake_model.end_last_completion_stream();
|
||||
send.collect::<Vec<_>>().await;
|
||||
cx.run_until_parked();
|
||||
|
||||
thread.read_with(cx, |thread, _| {
|
||||
assert_eq!(thread.title(), None);
|
||||
});
|
||||
assert_eq!(summary_model.pending_completions(), Vec::new());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_update_title_flag_without_available_tool_falls_back_to_summary_title_generation(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
|
||||
let fake_model = model.as_fake();
|
||||
let summary_model = Arc::new(FakeLanguageModel::default());
|
||||
|
||||
cx.update(|cx| {
|
||||
cx.update_flags(true, vec!["update-title-tool".to_string()]);
|
||||
});
|
||||
thread.update(cx, |thread, cx| {
|
||||
thread.set_summarization_model(Some(summary_model.clone()), cx);
|
||||
});
|
||||
|
||||
let send = thread
|
||||
.update(cx, |thread, cx| {
|
||||
thread.send(UserMessageId::new(), ["Explore title tooling"], cx)
|
||||
})
|
||||
.unwrap();
|
||||
cx.run_until_parked();
|
||||
|
||||
fake_model.send_last_completion_stream_text_chunk("Done");
|
||||
fake_model.end_last_completion_stream();
|
||||
cx.run_until_parked();
|
||||
|
||||
assert_eq!(summary_model.pending_completions().len(), 1);
|
||||
|
||||
summary_model.send_last_completion_stream_text_chunk("Fallback title");
|
||||
summary_model.end_last_completion_stream();
|
||||
send.collect::<Vec<_>>().await;
|
||||
cx.run_until_parked();
|
||||
|
||||
thread.read_with(cx, |thread, _| {
|
||||
assert_eq!(thread.title(), Some("Fallback title".into()));
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_send_no_retry_on_success(cx: &mut TestAppContext) {
|
||||
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
|
||||
|
|
@ -3984,8 +4139,8 @@ async fn test_send_retry_finishes_tool_calls_on_error(cx: &mut TestAppContext) {
|
|||
events.collect::<Vec<_>>().await;
|
||||
thread.read_with(cx, |thread, _cx| {
|
||||
assert_eq!(
|
||||
thread.last_received_or_pending_message(),
|
||||
Some(Message::Agent(AgentMessage {
|
||||
thread.last_received_or_pending_message().as_deref(),
|
||||
Some(&Message::Agent(AgentMessage {
|
||||
content: vec![AgentMessageContent::Text("Done".into())],
|
||||
tool_results: IndexMap::default(),
|
||||
reasoning_details: None,
|
||||
|
|
@ -4320,6 +4475,7 @@ async fn setup(cx: &mut TestAppContext, model: TestModel) -> ThreadTest {
|
|||
StreamingFailingEchoTool::NAME: true,
|
||||
TerminalTool::NAME: true,
|
||||
UpdatePlanTool::NAME: true,
|
||||
UpdateTitleTool::NAME: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -4402,7 +4558,7 @@ async fn setup(cx: &mut TestAppContext, model: TestModel) -> ThreadTest {
|
|||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[ctor::ctor]
|
||||
#[ctor::ctor(unsafe)]
|
||||
fn init_logger() {
|
||||
if std::env::var("RUST_LOG").is_ok() {
|
||||
env_logger::init();
|
||||
|
|
@ -4742,6 +4898,7 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) {
|
|||
command: "rm -rf /".to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -4794,6 +4951,7 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) {
|
|||
command: "echo hello".to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -4852,6 +5010,7 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) {
|
|||
command: "sudo rm file".to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -4899,6 +5058,7 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) {
|
|||
command: "echo hello".to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -4941,9 +5101,8 @@ async fn test_subagent_tool_call_end_to_end(cx: &mut TestAppContext) {
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -5076,9 +5235,8 @@ async fn test_subagent_tool_output_does_not_include_thinking(cx: &mut TestAppCon
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -5224,9 +5382,8 @@ async fn test_subagent_tool_call_cancellation_during_task_prompt(cx: &mut TestAp
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -5354,9 +5511,8 @@ async fn test_subagent_tool_resume_session(cx: &mut TestAppContext) {
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -5887,9 +6043,8 @@ async fn test_subagent_context_window_warning(cx: &mut TestAppContext) {
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -6013,9 +6168,8 @@ async fn test_subagent_no_context_window_warning_when_already_at_warning(cx: &mu
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -6187,9 +6341,8 @@ async fn test_subagent_error_propagation(cx: &mut TestAppContext) {
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
|
|||
|
|
@ -4,12 +4,14 @@ use crate::{
|
|||
FindPathTool, FindReferencesTool, GetCodeActionsTool, GoToDefinitionTool, GrepTool,
|
||||
ListDirectoryTool, MovePathTool, ProjectSnapshot, ReadFileTool, RenameTool, SpawnAgentTool,
|
||||
SystemPromptTemplate, Template, Templates, TerminalTool, ToolPermissionDecision,
|
||||
UpdatePlanTool, UserAgentsMd, WebSearchTool, WriteFileTool, decide_permission_from_settings,
|
||||
UpdatePlanTool, UpdateTitleTool, WebSearchTool, WriteFileTool, decide_permission_from_settings,
|
||||
};
|
||||
use acp_thread::{MentionUri, UserMessageId};
|
||||
use action_log::ActionLog;
|
||||
use agent_settings::UserAgentsMd;
|
||||
use feature_flags::{
|
||||
FeatureFlagAppExt as _, LspToolFeatureFlag, RenameToolFeatureFlag, UpdatePlanToolFeatureFlag,
|
||||
UpdateTitleToolFeatureFlag,
|
||||
};
|
||||
|
||||
use agent_client_protocol::schema as acp;
|
||||
|
|
@ -49,16 +51,16 @@ use serde::{Deserialize, Serialize};
|
|||
use settings::{
|
||||
LanguageModelSelection, Settings, SettingsStore, ToolPermissionMode, update_settings_file,
|
||||
};
|
||||
use std::fmt::Write;
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
marker::PhantomData,
|
||||
ops::RangeInclusive,
|
||||
path::Path,
|
||||
path::{Path, PathBuf},
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use std::{fmt::Write, path::PathBuf};
|
||||
use util::{ResultExt, debug_panic, markdown::MarkdownCodeBlock, paths::PathStyle};
|
||||
use uuid::Uuid;
|
||||
|
||||
|
|
@ -121,7 +123,7 @@ enum RetryStrategy {
|
|||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Message {
|
||||
User(UserMessage),
|
||||
Agent(AgentMessage),
|
||||
|
|
@ -174,13 +176,16 @@ impl Message {
|
|||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct UserMessage {
|
||||
pub id: UserMessageId,
|
||||
pub content: Vec<UserMessageContent>,
|
||||
pub content: Arc<[UserMessageContent]>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum UserMessageContent {
|
||||
Text(String),
|
||||
Mention { uri: MentionUri, content: String },
|
||||
Mention {
|
||||
uri: MentionUri,
|
||||
content: SharedString,
|
||||
},
|
||||
Image(LanguageModelImage),
|
||||
}
|
||||
|
||||
|
|
@ -188,7 +193,7 @@ impl UserMessage {
|
|||
pub fn to_markdown(&self) -> String {
|
||||
let mut markdown = String::new();
|
||||
|
||||
for content in &self.content {
|
||||
for content in &*self.content {
|
||||
match content {
|
||||
UserMessageContent::Text(text) => {
|
||||
markdown.push_str(text);
|
||||
|
|
@ -248,7 +253,7 @@ impl UserMessage {
|
|||
let mut merge_conflict_context = MERGE_CONFLICT_TAG.to_string();
|
||||
let mut skills_context = OPEN_SKILLS_TAG.to_string();
|
||||
|
||||
for chunk in &self.content {
|
||||
for chunk in &*self.content {
|
||||
let chunk = match chunk {
|
||||
UserMessageContent::Text(text) => {
|
||||
language_model::MessageContent::Text(text.clone())
|
||||
|
|
@ -264,7 +269,7 @@ impl UserMessage {
|
|||
"\n{}",
|
||||
MarkdownCodeBlock {
|
||||
tag: &codeblock_tag(abs_path, None),
|
||||
text: &content.to_string(),
|
||||
text: content,
|
||||
}
|
||||
)
|
||||
.ok();
|
||||
|
|
@ -311,17 +316,6 @@ impl UserMessage {
|
|||
MentionUri::Thread { .. } => {
|
||||
write!(&mut thread_context, "\n{}\n", content).ok();
|
||||
}
|
||||
MentionUri::Rule { .. } => {
|
||||
write!(
|
||||
&mut rules_context,
|
||||
"\n{}",
|
||||
MarkdownCodeBlock {
|
||||
tag: "",
|
||||
text: content
|
||||
}
|
||||
)
|
||||
.ok();
|
||||
}
|
||||
MentionUri::Fetch { url } => {
|
||||
write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();
|
||||
}
|
||||
|
|
@ -625,9 +619,9 @@ impl AgentMessage {
|
|||
|
||||
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AgentMessage {
|
||||
pub content: Vec<AgentMessageContent>,
|
||||
pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
|
||||
pub reasoning_details: Option<serde_json::Value>,
|
||||
pub(crate) content: Vec<AgentMessageContent>,
|
||||
pub(crate) tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
|
||||
pub(crate) reasoning_details: Option<Arc<serde_json::Value>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
@ -663,8 +657,10 @@ pub trait ThreadEnvironment {
|
|||
fn create_terminal(
|
||||
&self,
|
||||
command: String,
|
||||
extra_env: Vec<acp::EnvVariable>,
|
||||
cwd: Option<PathBuf>,
|
||||
output_byte_limit: Option<u64>,
|
||||
sandbox_wrap: Option<acp_thread::SandboxWrap>,
|
||||
cx: &mut AsyncApp,
|
||||
) -> Task<Result<Rc<dyn TerminalHandle>>>;
|
||||
|
||||
|
|
@ -961,7 +957,7 @@ pub struct Thread {
|
|||
title_generation_failed: bool,
|
||||
pending_summary_generation: Option<Shared<Task<Option<SharedString>>>>,
|
||||
summary: Option<SharedString>,
|
||||
messages: Vec<Message>,
|
||||
messages: Vec<Arc<Message>>,
|
||||
user_store: Entity<UserStore>,
|
||||
/// Holds the task that handles agent interaction until the end of the turn.
|
||||
/// Survives across multiple requests as the model performs tool calls and
|
||||
|
|
@ -1000,6 +996,7 @@ pub struct Thread {
|
|||
/// Weak references to running subagent threads for cancellation propagation
|
||||
running_subagents: Vec<WeakEntity<Thread>>,
|
||||
inherits_parent_model_settings: bool,
|
||||
sandboxed_terminal_temp_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Thread {
|
||||
|
|
@ -1126,6 +1123,7 @@ impl Thread {
|
|||
ui_scroll_position: None,
|
||||
running_subagents: Vec::new(),
|
||||
inherits_parent_model_settings: true,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1169,6 +1167,30 @@ impl Thread {
|
|||
&self.id
|
||||
}
|
||||
|
||||
pub(crate) fn sandboxed_terminal_temp_dir(
|
||||
&mut self,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Result<PathBuf> {
|
||||
if let Some(temp_dir) = &self.sandboxed_terminal_temp_dir {
|
||||
std::fs::create_dir_all(temp_dir).with_context(|| {
|
||||
format!(
|
||||
"failed to recreate sandboxed terminal temp directory {}",
|
||||
temp_dir.display()
|
||||
)
|
||||
})?;
|
||||
return Ok(temp_dir.clone());
|
||||
}
|
||||
|
||||
let temp_dir = tempfile::Builder::new()
|
||||
.prefix("zed-agent-terminal-")
|
||||
.tempdir()
|
||||
.context("failed to create sandboxed terminal temp directory")?;
|
||||
let temp_dir = temp_dir.keep();
|
||||
self.sandboxed_terminal_temp_dir = Some(temp_dir.clone());
|
||||
cx.notify();
|
||||
Ok(temp_dir)
|
||||
}
|
||||
|
||||
/// Returns true if this thread was imported from a shared thread.
|
||||
pub fn is_imported(&self) -> bool {
|
||||
self.imported
|
||||
|
|
@ -1181,7 +1203,7 @@ impl Thread {
|
|||
let (tx, rx) = mpsc::unbounded();
|
||||
let stream = ThreadEventStream(tx);
|
||||
for message in &self.messages {
|
||||
match message {
|
||||
match &**message {
|
||||
Message::User(user_message) => stream.send_user_message(user_message),
|
||||
Message::Agent(assistant_message) => {
|
||||
for content in &assistant_message.content {
|
||||
|
|
@ -1247,10 +1269,11 @@ impl Thread {
|
|||
// but still display the saved result if available.
|
||||
// We need to send both ToolCall and ToolCallUpdate events because the UI
|
||||
// only converts raw_output to displayable content in update_fields, not from_acp.
|
||||
let title = Self::title_for_replayed_tool_use(tool_use);
|
||||
stream
|
||||
.0
|
||||
.unbounded_send(Ok(ThreadEvent::ToolCall(
|
||||
acp::ToolCall::new(tool_use.id.to_string(), tool_use.name.to_string())
|
||||
acp::ToolCall::new(tool_use.id.to_string(), title.clone())
|
||||
.status(status)
|
||||
.raw_input(tool_use.input.clone()),
|
||||
)))
|
||||
|
|
@ -1258,6 +1281,9 @@ impl Thread {
|
|||
let mut fields = acp::ToolCallUpdateFields::new()
|
||||
.status(status)
|
||||
.raw_output(output);
|
||||
if tool_use.name.as_ref() == UpdateTitleTool::NAME {
|
||||
fields = fields.title(title);
|
||||
}
|
||||
if let Some(content) = replay_content {
|
||||
fields = fields.content(content);
|
||||
}
|
||||
|
|
@ -1305,6 +1331,16 @@ impl Thread {
|
|||
);
|
||||
}
|
||||
|
||||
fn title_for_replayed_tool_use(tool_use: &LanguageModelToolUse) -> String {
|
||||
if tool_use.name.as_ref() == UpdateTitleTool::NAME {
|
||||
let input = serde_json::from_value(tool_use.input.clone())
|
||||
.map_err(|_| serde_json::Value::String(tool_use.raw_input.clone()));
|
||||
UpdateTitleTool::title_for_input(input).to_string()
|
||||
} else {
|
||||
tool_use.name.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn tool_result_content_for_replay(
|
||||
tool_result: &LanguageModelToolResult,
|
||||
) -> Option<Vec<acp::ToolCallContent>> {
|
||||
|
|
@ -1430,6 +1466,7 @@ impl Thread {
|
|||
}),
|
||||
running_subagents: Vec::new(),
|
||||
inherits_parent_model_settings: true,
|
||||
sandboxed_terminal_temp_dir: db_thread.sandboxed_terminal_temp_dir,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1460,6 +1497,7 @@ impl Thread {
|
|||
offset_in_item: lo.offset_in_item.as_f32(),
|
||||
}
|
||||
}),
|
||||
sandboxed_terminal_temp_dir: self.sandboxed_terminal_temp_dir.clone(),
|
||||
};
|
||||
|
||||
cx.background_spawn(async move {
|
||||
|
|
@ -1623,13 +1661,13 @@ impl Thread {
|
|||
}
|
||||
|
||||
pub fn last_message(&self) -> Option<&Message> {
|
||||
self.messages.last()
|
||||
self.messages.last().map(std::ops::Deref::deref)
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn last_received_or_pending_message(&self) -> Option<Message> {
|
||||
pub fn last_received_or_pending_message(&self) -> Option<Arc<Message>> {
|
||||
if let Some(message) = self.pending_message.clone() {
|
||||
Some(Message::Agent(message))
|
||||
Some(Arc::new(Message::Agent(message)))
|
||||
} else {
|
||||
self.messages.last().cloned()
|
||||
}
|
||||
|
|
@ -1670,6 +1708,9 @@ impl Thread {
|
|||
if cx.has_flag::<UpdatePlanToolFeatureFlag>() {
|
||||
self.add_tool(UpdatePlanTool);
|
||||
}
|
||||
if cx.has_flag::<UpdateTitleToolFeatureFlag>() {
|
||||
self.add_tool(UpdateTitleTool::new(cx.weak_entity()));
|
||||
}
|
||||
self.add_tool(ReadFileTool::new(
|
||||
self.project.clone(),
|
||||
self.action_log.clone(),
|
||||
|
|
@ -1783,13 +1824,13 @@ impl Thread {
|
|||
// and we don't want that content to be added after we truncate
|
||||
self.pending_message.take();
|
||||
let Some(position) = self.messages.iter().position(
|
||||
|msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
|
||||
|msg| matches!(&**msg, Message::User(UserMessage { id, .. }) if id == &message_id),
|
||||
) else {
|
||||
return Err(anyhow!("Message not found"));
|
||||
};
|
||||
|
||||
for message in self.messages.drain(position..) {
|
||||
match message {
|
||||
match &*message {
|
||||
Message::User(message) => {
|
||||
self.request_token_usage.remove(&message.id);
|
||||
}
|
||||
|
|
@ -1831,7 +1872,7 @@ impl Thread {
|
|||
let mut previous_user_message_id: Option<&UserMessageId> = None;
|
||||
|
||||
for message in &self.messages {
|
||||
if let Message::User(user_msg) = message {
|
||||
if let Message::User(user_msg) = &**message {
|
||||
if &user_msg.id == target_id {
|
||||
let prev_id = previous_user_message_id?;
|
||||
let usage = self.request_token_usage.get(prev_id)?;
|
||||
|
|
@ -1876,7 +1917,7 @@ impl Thread {
|
|||
&mut self,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
|
||||
self.messages.push(Message::Resume);
|
||||
self.messages.push(Arc::new(Message::Resume));
|
||||
cx.notify();
|
||||
|
||||
log::debug!("Total messages in thread: {}", self.messages.len());
|
||||
|
|
@ -1895,11 +1936,11 @@ impl Thread {
|
|||
where
|
||||
T: Into<UserMessageContent>,
|
||||
{
|
||||
let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
|
||||
let content = content.into_iter().map(Into::into).collect::<Arc<_>>();
|
||||
log::debug!("Thread::send content: {:?}", content);
|
||||
|
||||
self.messages
|
||||
.push(Message::User(UserMessage { id, content }));
|
||||
.push(Arc::new(Message::User(UserMessage { id, content })));
|
||||
cx.notify();
|
||||
|
||||
self.send_existing(cx)
|
||||
|
|
@ -1930,9 +1971,9 @@ impl Thread {
|
|||
let content = blocks
|
||||
.into_iter()
|
||||
.map(|block| UserMessageContent::from_content_block(block, path_style))
|
||||
.collect::<Vec<_>>();
|
||||
.collect::<Arc<_>>();
|
||||
self.messages
|
||||
.push(Message::User(UserMessage { id, content }));
|
||||
.push(Arc::new(Message::User(UserMessage { id, content })));
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
|
|
@ -1950,10 +1991,10 @@ impl Thread {
|
|||
_ => "[unknown]".to_string(),
|
||||
};
|
||||
|
||||
self.messages.push(Message::Agent(AgentMessage {
|
||||
self.messages.push(Arc::new(Message::Agent(AgentMessage {
|
||||
content: vec![AgentMessageContent::Text(text)],
|
||||
..Default::default()
|
||||
}));
|
||||
})));
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
|
|
@ -2183,7 +2224,7 @@ impl Thread {
|
|||
|
||||
this.update(cx, |this, cx| {
|
||||
this.flush_pending_message(cx);
|
||||
if this.title.is_none() && this.pending_title_generation.is_none() {
|
||||
if this.title.is_none() {
|
||||
this.generate_title(cx);
|
||||
}
|
||||
})?;
|
||||
|
|
@ -2211,10 +2252,10 @@ impl Thread {
|
|||
}
|
||||
}
|
||||
this.update(cx, |this, _cx| {
|
||||
if let Some(Message::Agent(message)) = this.messages.last() {
|
||||
if let Some(Message::Agent(message)) = this.last_message() {
|
||||
if message.tool_results.is_empty() {
|
||||
intent = CompletionIntent::UserPrompt;
|
||||
this.messages.push(Message::Resume);
|
||||
this.messages.push(Arc::new(Message::Resume));
|
||||
}
|
||||
}
|
||||
})?;
|
||||
|
|
@ -2337,12 +2378,12 @@ impl Thread {
|
|||
let last_message = self.pending_message();
|
||||
// Store the last non-empty reasoning_details (overwrites earlier ones)
|
||||
// This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
|
||||
if let serde_json::Value::Array(ref arr) = details {
|
||||
if let serde_json::Value::Array(arr) = &details {
|
||||
if !arr.is_empty() {
|
||||
last_message.reasoning_details = Some(details);
|
||||
last_message.reasoning_details = Some(Arc::new(details));
|
||||
}
|
||||
} else {
|
||||
last_message.reasoning_details = Some(details);
|
||||
last_message.reasoning_details = Some(Arc::new(details));
|
||||
}
|
||||
}
|
||||
ToolUse(tool_use) => {
|
||||
|
|
@ -2712,6 +2753,20 @@ impl Thread {
|
|||
self.title_generation_failed
|
||||
}
|
||||
|
||||
pub fn can_generate_title(&self, cx: &App) -> bool {
|
||||
self.pending_title_generation.is_none()
|
||||
&& self.summarization_model.is_some()
|
||||
&& !self.update_title_tool_available(cx)
|
||||
}
|
||||
|
||||
fn update_title_tool_available(&self, cx: &App) -> bool {
|
||||
if let Some(running_turn) = self.running_turn.as_ref() {
|
||||
running_turn.tools.contains_key(UpdateTitleTool::NAME)
|
||||
} else {
|
||||
self.enabled_tools(cx).contains_key(UpdateTitleTool::NAME)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
|
||||
if let Some(summary) = self.summary.as_ref() {
|
||||
return Task::ready(Some(summary.clone())).shared();
|
||||
|
|
@ -2773,6 +2828,10 @@ impl Thread {
|
|||
}
|
||||
|
||||
pub fn generate_title(&mut self, cx: &mut Context<Self>) {
|
||||
if !self.can_generate_title(cx) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.title_generation_failed = false;
|
||||
let Some(model) = self.summarization_model.clone() else {
|
||||
return;
|
||||
|
|
@ -2858,7 +2917,7 @@ impl Thread {
|
|||
self.messages
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|message| match message {
|
||||
.find_map(|message| match &**message {
|
||||
Message::User(user_message) => Some(user_message),
|
||||
Message::Agent(_) => None,
|
||||
Message::Resume => None,
|
||||
|
|
@ -2899,7 +2958,7 @@ impl Thread {
|
|||
}
|
||||
}
|
||||
|
||||
self.messages.push(Message::Agent(message));
|
||||
self.messages.push(Arc::new(Message::Agent(message)));
|
||||
self.updated_at = Utc::now();
|
||||
self.clear_summary();
|
||||
cx.notify()
|
||||
|
|
@ -3131,6 +3190,7 @@ impl Thread {
|
|||
model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
|
||||
date: Local::now().format("%Y-%m-%d").to_string(),
|
||||
user_agents_md,
|
||||
sandboxing: crate::sandboxing::sandboxing_enabled(cx),
|
||||
}
|
||||
.render(&self.templates)
|
||||
.context("failed to build system prompt")
|
||||
|
|
@ -3162,7 +3222,7 @@ impl Thread {
|
|||
if ix > 0 {
|
||||
markdown.push('\n');
|
||||
}
|
||||
match message {
|
||||
match &**message {
|
||||
Message::User(_) => markdown.push_str("## User\n\n"),
|
||||
Message::Agent(_) => markdown.push_str("## Assistant\n\n"),
|
||||
Message::Resume => {}
|
||||
|
|
@ -4374,7 +4434,7 @@ impl UserMessageContent {
|
|||
match MentionUri::parse(&resource_link.uri, path_style) {
|
||||
Ok(uri) => Self::Mention {
|
||||
uri,
|
||||
content: String::new(),
|
||||
content: SharedString::default(),
|
||||
},
|
||||
Err(err) => {
|
||||
log::error!("Failed to parse mention link: {}", err);
|
||||
|
|
@ -4387,7 +4447,7 @@ impl UserMessageContent {
|
|||
match MentionUri::parse(&resource.uri, path_style) {
|
||||
Ok(uri) => Self::Mention {
|
||||
uri,
|
||||
content: resource.text,
|
||||
content: resource.text.into(),
|
||||
},
|
||||
Err(err) => {
|
||||
log::error!("Failed to parse mention link: {}", err);
|
||||
|
|
@ -4589,14 +4649,14 @@ mod tests {
|
|||
},
|
||||
);
|
||||
|
||||
thread.messages.push(Message::Agent(AgentMessage {
|
||||
thread.messages.push(Arc::new(Message::Agent(AgentMessage {
|
||||
content: vec![
|
||||
AgentMessageContent::ToolUse(registered_tool_use),
|
||||
AgentMessageContent::ToolUse(missing_tool_use),
|
||||
],
|
||||
tool_results,
|
||||
reasoning_details: None,
|
||||
}));
|
||||
})));
|
||||
|
||||
thread.replay(cx)
|
||||
})
|
||||
|
|
@ -4626,6 +4686,134 @@ mod tests {
|
|||
assert!(tool_use_ids_with_image_content.contains(&missing_tool_use_id.to_string()));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_update_title_tool_replay_does_not_reenter_thread(cx: &mut TestAppContext) {
|
||||
let (thread, _event_stream) = setup_thread_for_test(cx).await;
|
||||
|
||||
let tool_use_id = LanguageModelToolUseId::from("title_tool_id");
|
||||
let mut replay_events = cx.update(|cx| {
|
||||
thread.update(cx, |thread, cx| {
|
||||
thread.add_tool(UpdateTitleTool::new(cx.weak_entity()));
|
||||
push_completed_update_title_tool_call(thread, tool_use_id.clone());
|
||||
|
||||
thread.replay(cx)
|
||||
})
|
||||
});
|
||||
|
||||
let mut saw_tool_call_title = false;
|
||||
let mut saw_replayed_title_update = false;
|
||||
let mut saw_completed_update = false;
|
||||
while let Some(event) = replay_events.next().await {
|
||||
let event = event.unwrap();
|
||||
match event {
|
||||
ThreadEvent::ToolCall(tool_call)
|
||||
if tool_call.tool_call_id.to_string() == tool_use_id.to_string()
|
||||
&& tool_call.title == "Update title: Replayed title" =>
|
||||
{
|
||||
saw_tool_call_title = true;
|
||||
}
|
||||
ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update))
|
||||
if update.tool_call_id.to_string() == tool_use_id.to_string() =>
|
||||
{
|
||||
if update.fields.title == Some("Update title: Replayed title".to_string()) {
|
||||
saw_replayed_title_update = true;
|
||||
}
|
||||
if update.fields.status == Some(acp::ToolCallStatus::Completed) {
|
||||
saw_completed_update = true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(saw_tool_call_title);
|
||||
assert!(saw_replayed_title_update);
|
||||
assert!(saw_completed_update);
|
||||
thread.read_with(cx, |thread, _cx| {
|
||||
assert_eq!(thread.title(), None);
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_update_title_tool_replay_title_when_tool_not_registered(cx: &mut TestAppContext) {
|
||||
let (thread, _event_stream) = setup_thread_for_test(cx).await;
|
||||
|
||||
let tool_use_id = LanguageModelToolUseId::from("title_tool_id");
|
||||
let mut replay_events = cx.update(|cx| {
|
||||
thread.update(cx, |thread, cx| {
|
||||
push_completed_update_title_tool_call(thread, tool_use_id.clone());
|
||||
thread.replay(cx)
|
||||
})
|
||||
});
|
||||
|
||||
let mut saw_tool_call_title = false;
|
||||
let mut saw_replayed_title_update = false;
|
||||
let mut saw_completed_update = false;
|
||||
while let Some(event) = replay_events.next().await {
|
||||
let event = event.unwrap();
|
||||
match event {
|
||||
ThreadEvent::ToolCall(tool_call)
|
||||
if tool_call.tool_call_id.to_string() == tool_use_id.to_string()
|
||||
&& tool_call.title == "Update title: Replayed title" =>
|
||||
{
|
||||
saw_tool_call_title = true;
|
||||
}
|
||||
ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update))
|
||||
if update.tool_call_id.to_string() == tool_use_id.to_string() =>
|
||||
{
|
||||
if update.fields.title == Some("Update title: Replayed title".to_string()) {
|
||||
saw_replayed_title_update = true;
|
||||
}
|
||||
if update.fields.status == Some(acp::ToolCallStatus::Completed) {
|
||||
saw_completed_update = true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(saw_tool_call_title);
|
||||
assert!(saw_replayed_title_update);
|
||||
assert!(saw_completed_update);
|
||||
thread.read_with(cx, |thread, _cx| {
|
||||
assert_eq!(thread.title(), None);
|
||||
});
|
||||
}
|
||||
|
||||
fn push_completed_update_title_tool_call(
|
||||
thread: &mut Thread,
|
||||
tool_use_id: LanguageModelToolUseId,
|
||||
) {
|
||||
let tool_use = LanguageModelToolUse {
|
||||
id: tool_use_id.clone(),
|
||||
name: UpdateTitleTool::NAME.into(),
|
||||
raw_input: json!({ "title": "Replayed title" }).to_string(),
|
||||
input: json!({ "title": "Replayed title" }),
|
||||
is_input_complete: true,
|
||||
thought_signature: None,
|
||||
};
|
||||
|
||||
let mut tool_results = IndexMap::default();
|
||||
tool_results.insert(
|
||||
tool_use_id.clone(),
|
||||
LanguageModelToolResult {
|
||||
tool_use_id,
|
||||
tool_name: UpdateTitleTool::NAME.into(),
|
||||
is_error: false,
|
||||
content: vec![LanguageModelToolResultContent::Text(
|
||||
"Session title updated".into(),
|
||||
)],
|
||||
output: Some(json!("Session title updated")),
|
||||
},
|
||||
);
|
||||
|
||||
thread.messages.push(Arc::new(Message::Agent(AgentMessage {
|
||||
content: vec![AgentMessageContent::ToolUse(tool_use)],
|
||||
tool_results,
|
||||
reasoning_details: None,
|
||||
})));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_set_model_propagates_to_subagents(cx: &mut TestAppContext) {
|
||||
let (parent, _event_stream) = setup_thread_for_test(cx).await;
|
||||
|
|
|
|||
|
|
@ -167,6 +167,7 @@ mod tests {
|
|||
thinking_effort: None,
|
||||
draft_prompt: None,
|
||||
ui_scroll_position: None,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ mod symbol_locator;
|
|||
mod terminal_tool;
|
||||
mod tool_permissions;
|
||||
mod update_plan_tool;
|
||||
mod update_title_tool;
|
||||
mod web_search_tool;
|
||||
mod write_file_tool;
|
||||
|
||||
|
|
@ -80,6 +81,7 @@ pub use symbol_locator::*;
|
|||
pub use terminal_tool::*;
|
||||
pub use tool_permissions::*;
|
||||
pub use update_plan_tool::*;
|
||||
pub use update_title_tool::*;
|
||||
pub use web_search_tool::*;
|
||||
pub use write_file_tool::*;
|
||||
|
||||
|
|
@ -172,6 +174,7 @@ tools! {
|
|||
SpawnAgentTool,
|
||||
TerminalTool,
|
||||
UpdatePlanTool,
|
||||
UpdateTitleTool,
|
||||
WebSearchTool,
|
||||
WriteFileTool,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
use super::tool_permissions::{
|
||||
authorize_symlink_escapes, canonicalize_worktree_roots, collect_symlink_escapes,
|
||||
resolve_creatable_global_skill_descendant_path, resolve_global_skill_descendant_path,
|
||||
sensitive_settings_kind,
|
||||
};
|
||||
use crate::{
|
||||
|
|
@ -23,6 +24,7 @@ use util::markdown::MarkdownInlineCode;
|
|||
///
|
||||
/// This tool should be used when it's desirable to create a copy of a file or directory without modifying the original.
|
||||
/// It's much more efficient than doing this by separately reading and then writing the file or directory's contents, so this tool should be preferred over that approach whenever copying is the goal.
|
||||
/// The only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct CopyPathToolInput {
|
||||
/// The source path of the file or directory to copy.
|
||||
|
|
@ -100,6 +102,15 @@ impl AgentTool for CopyPathTool {
|
|||
let fs = project.read_with(cx, |project, _cx| project.fs().clone());
|
||||
let canonical_roots = canonicalize_worktree_roots(&project, &fs, cx).await;
|
||||
|
||||
let global_source_path =
|
||||
resolve_global_skill_descendant_path(Path::new(&input.source_path), fs.as_ref())
|
||||
.await;
|
||||
let global_destination_path = resolve_creatable_global_skill_descendant_path(
|
||||
Path::new(&input.destination_path),
|
||||
fs.as_ref(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let symlink_escapes: Vec<(&str, std::path::PathBuf)> =
|
||||
project.read_with(cx, |project, cx| {
|
||||
collect_symlink_escapes(
|
||||
|
|
@ -160,6 +171,63 @@ impl AgentTool for CopyPathTool {
|
|||
authorize.await.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
if global_source_path.is_some() || global_destination_path.is_some() {
|
||||
let source_path = if let Some(global_source_path) = global_source_path {
|
||||
global_source_path
|
||||
} else {
|
||||
project.read_with(cx, |project, cx| {
|
||||
let project_path = project.find_project_path(&input.source_path, cx).ok_or_else(|| {
|
||||
format!("Source path {} was not found in the project.", input.source_path)
|
||||
})?;
|
||||
project.entry_for_path(&project_path, cx).ok_or_else(|| {
|
||||
format!("Source path {} was not found in the project.", input.source_path)
|
||||
})?;
|
||||
project.absolute_path(&project_path, cx).ok_or_else(|| {
|
||||
format!("Source path {} could not be resolved.", input.source_path)
|
||||
})
|
||||
})?
|
||||
};
|
||||
|
||||
let destination_path = if let Some(global_destination_path) = global_destination_path
|
||||
{
|
||||
global_destination_path
|
||||
} else {
|
||||
project.read_with(cx, |project, cx| {
|
||||
let project_path = project.find_project_path(&input.destination_path, cx).ok_or_else(|| {
|
||||
format!(
|
||||
"Destination path {} was outside the project.",
|
||||
input.destination_path
|
||||
)
|
||||
})?;
|
||||
project.absolute_path(&project_path, cx).ok_or_else(|| {
|
||||
format!(
|
||||
"Destination path {} could not be resolved.",
|
||||
input.destination_path
|
||||
)
|
||||
})
|
||||
})?
|
||||
};
|
||||
|
||||
futures::select! {
|
||||
result = fs::copy_recursive(
|
||||
fs.as_ref(),
|
||||
&source_path,
|
||||
&destination_path,
|
||||
fs::CopyOptions::default(),
|
||||
).fuse() => {
|
||||
result.map_err(|e| format!("Copying {} to {}: {e}", input.source_path, input.destination_path))?;
|
||||
}
|
||||
_ = event_stream.cancelled_by_user().fuse() => {
|
||||
return Err("Copy cancelled by user".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(format!(
|
||||
"Copied {} to {}",
|
||||
input.source_path, input.destination_path
|
||||
));
|
||||
}
|
||||
|
||||
let copy_task = project.update(cx, |project, cx| {
|
||||
match project
|
||||
.find_project_path(&input.source_path, cx)
|
||||
|
|
@ -222,6 +290,124 @@ mod tests {
|
|||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_copy_path_global_skill_directory_to_project(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root/project"), json!({})).await;
|
||||
let skill_dir = agent_skills::global_skills_dir().join("my-skill");
|
||||
fs.insert_tree(&skill_dir, json!({ "SKILL.md": "content" }))
|
||||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let tool = Arc::new(CopyPathTool::new(project));
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(CopyPathToolInput {
|
||||
source_path: input_path,
|
||||
destination_path: path!("/root/project/my-skill").to_string(),
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let result = task.await;
|
||||
assert!(result.is_ok(), "should copy after approval: {result:?}");
|
||||
assert!(fs.is_dir(&skill_dir).await);
|
||||
assert_eq!(
|
||||
fs.load(path!("/root/project/my-skill/SKILL.md").as_ref())
|
||||
.await
|
||||
.unwrap(),
|
||||
"content"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_copy_path_project_directory_to_global_skill_directory(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(
|
||||
path!("/root/project"),
|
||||
json!({ "exported-skill": { "SKILL.md": "content" } }),
|
||||
)
|
||||
.await;
|
||||
let skills_dir = agent_skills::global_skills_dir();
|
||||
fs.create_dir(&skills_dir).await.unwrap();
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let tool = Arc::new(CopyPathTool::new(project));
|
||||
let destination_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("exported-skill")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(CopyPathToolInput {
|
||||
source_path: path!("/root/project/exported-skill").to_string(),
|
||||
destination_path,
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let result = task.await;
|
||||
assert!(result.is_ok(), "should copy after approval: {result:?}");
|
||||
assert!(
|
||||
fs.is_dir(path!("/root/project/exported-skill").as_ref())
|
||||
.await
|
||||
);
|
||||
assert_eq!(
|
||||
fs.load(skills_dir.join("exported-skill").join("SKILL.md").as_ref())
|
||||
.await
|
||||
.unwrap(),
|
||||
"content"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_copy_path_symlink_escape_source_requests_authorization(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use super::tool_permissions::{
|
||||
authorize_symlink_access, canonicalize_worktree_roots, detect_symlink_escape,
|
||||
sensitive_settings_kind,
|
||||
resolve_creatable_global_skill_path, sensitive_settings_kind,
|
||||
};
|
||||
use agent_client_protocol::schema as acp;
|
||||
use agent_settings::AgentSettings;
|
||||
|
|
@ -22,6 +22,7 @@ use std::path::Path;
|
|||
/// Creates a new directory at the specified path within the project. Returns confirmation that the directory was created.
|
||||
///
|
||||
/// This tool creates a directory and all necessary parent directories. It should be used whenever you need to create new directories within the project.
|
||||
/// The only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct CreateDirectoryToolInput {
|
||||
/// The path of the new directory.
|
||||
|
|
@ -34,6 +35,10 @@ pub struct CreateDirectoryToolInput {
|
|||
///
|
||||
/// You can create a new directory by providing a path of "directory1/new_directory"
|
||||
/// </example>
|
||||
///
|
||||
/// <example>
|
||||
/// To create a global agent skill directory, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill`.
|
||||
/// </example>
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
|
|
@ -144,6 +149,21 @@ impl AgentTool for CreateDirectoryTool {
|
|||
authorize.await.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
if let Some(global_skill_directory) =
|
||||
resolve_creatable_global_skill_path(Path::new(&input.path), fs.as_ref()).await
|
||||
{
|
||||
futures::select! {
|
||||
result = fs.create_dir(&global_skill_directory).fuse() => {
|
||||
result.map_err(|e| format!("Creating directory {destination_path}: {e}"))?;
|
||||
}
|
||||
_ = event_stream.cancelled_by_user().fuse() => {
|
||||
return Err("Create directory cancelled by user".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(format!("Created directory {destination_path}"));
|
||||
}
|
||||
|
||||
let create_entry = project.update(cx, |project, cx| {
|
||||
match project.find_project_path(&input.path, cx) {
|
||||
Some(project_path) => Ok(project.create_entry(project_path, true, cx)),
|
||||
|
|
@ -190,6 +210,96 @@ mod tests {
|
|||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_create_directory_allows_global_skill_directory(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root/project"), json!({})).await;
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let tool = Arc::new(CreateDirectoryTool::new(project));
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let created_path = agent_skills::global_skills_dir().join("my-skill");
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(CreateDirectoryToolInput { path: input_path }),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let result = task.await;
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"Tool should create global skill directory: {result:?}"
|
||||
);
|
||||
assert!(fs.is_dir(&created_path).await);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_create_directory_rejects_other_global_paths(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root/project"), json!({})).await;
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let tool = Arc::new(CreateDirectoryTool::new(project));
|
||||
let outside_path = agent_skills::global_skills_dir()
|
||||
.parent()
|
||||
.expect("global skills directory should have a parent")
|
||||
.join("not-skills");
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let result = cx
|
||||
.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(CreateDirectoryToolInput {
|
||||
path: outside_path.to_string_lossy().into_owned(),
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
})
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"Tool should reject paths outside the project and global skills directory"
|
||||
);
|
||||
assert!(!fs.is_dir(&outside_path).await);
|
||||
assert!(
|
||||
!matches!(
|
||||
event_rx.try_recv(),
|
||||
Ok(Ok(crate::ThreadEvent::ToolCallAuthorization(_)))
|
||||
),
|
||||
"Non-skill global path should not emit an agent-skills authorization prompt",
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_create_directory_symlink_escape_requests_authorization(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use super::tool_permissions::{
|
||||
authorize_symlink_access, canonicalize_worktree_roots, detect_symlink_escape,
|
||||
sensitive_settings_kind,
|
||||
resolve_global_skill_descendant_path, resolves_to_global_skills_dir, sensitive_settings_kind,
|
||||
};
|
||||
use crate::{
|
||||
AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision,
|
||||
|
|
@ -20,6 +20,8 @@ use std::sync::Arc;
|
|||
use util::markdown::MarkdownInlineCode;
|
||||
|
||||
/// Deletes the file or directory (and the directory's contents, recursively) at the specified path in the project, and returns confirmation of the deletion.
|
||||
///
|
||||
/// The only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct DeletePathToolInput {
|
||||
/// The path of the file or directory to delete.
|
||||
|
|
@ -95,6 +97,16 @@ impl AgentTool for DeletePathTool {
|
|||
let fs = project.read_with(cx, |project, _cx| project.fs().clone());
|
||||
let canonical_roots = canonicalize_worktree_roots(&project, &fs, cx).await;
|
||||
|
||||
if resolves_to_global_skills_dir(Path::new(&path), fs.as_ref()).await {
|
||||
return Err(
|
||||
"Cannot delete the global agent skills directory itself. Delete a skill directory or file beneath it instead."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
let global_skill_path =
|
||||
resolve_global_skill_descendant_path(Path::new(&path), fs.as_ref()).await;
|
||||
|
||||
let symlink_escape_target = project.read_with(cx, |project, cx| {
|
||||
detect_symlink_escape(project, &path, &canonical_roots, cx)
|
||||
.map(|(_, target)| target)
|
||||
|
|
@ -147,6 +159,38 @@ impl AgentTool for DeletePathTool {
|
|||
authorize.await.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
if let Some(global_skill_path) = global_skill_path {
|
||||
let metadata = fs
|
||||
.metadata(&global_skill_path)
|
||||
.await
|
||||
.map_err(|e| format!("Deleting {path}: {e}"))?
|
||||
.ok_or_else(|| format!("Deleting {path}: path not found"))?;
|
||||
|
||||
futures::select! {
|
||||
result = async {
|
||||
if metadata.is_dir {
|
||||
fs.remove_dir(
|
||||
&global_skill_path,
|
||||
fs::RemoveOptions {
|
||||
recursive: true,
|
||||
..fs::RemoveOptions::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
fs.remove_file(&global_skill_path, fs::RemoveOptions::default()).await
|
||||
}
|
||||
}.fuse() => {
|
||||
result.map_err(|e| format!("Deleting {path}: {e}"))?;
|
||||
}
|
||||
_ = event_stream.cancelled_by_user().fuse() => {
|
||||
return Err("Delete cancelled by user".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(format!("Deleted {path}"));
|
||||
}
|
||||
|
||||
let (project_path, worktree_snapshot) = project.read_with(cx, |project, cx| {
|
||||
let project_path = project.find_project_path(&path, cx).ok_or_else(|| {
|
||||
format!("Couldn't delete {path} because that path isn't in this project.")
|
||||
|
|
@ -248,6 +292,145 @@ mod tests {
|
|||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_delete_path_global_skill_directory(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root/project"), json!({})).await;
|
||||
let skills_dir = agent_skills::global_skills_dir();
|
||||
let skill_dir = skills_dir.join("my-skill");
|
||||
fs.insert_tree(&skill_dir, json!({ "SKILL.md": "content" }))
|
||||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let action_log = cx.new(|_| ActionLog::new(project.clone()));
|
||||
let tool = Arc::new(DeletePathTool::new(project, action_log));
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(DeletePathToolInput { path: input_path }),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let result = task.await;
|
||||
assert!(result.is_ok(), "should delete after approval: {result:?}");
|
||||
assert!(fs.is_dir(&skills_dir).await);
|
||||
assert!(!fs.is_dir(&skill_dir).await);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_delete_path_global_skill_file(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root/project"), json!({})).await;
|
||||
let skill_file = agent_skills::global_skills_dir()
|
||||
.join("my-skill")
|
||||
.join("references")
|
||||
.join("notes.md");
|
||||
fs.create_dir(skill_file.parent().unwrap()).await.unwrap();
|
||||
fs.insert_file(&skill_file, b"notes".to_vec()).await;
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let action_log = cx.new(|_| ActionLog::new(project.clone()));
|
||||
let tool = Arc::new(DeletePathTool::new(project, action_log));
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.join("references")
|
||||
.join("notes.md")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(DeletePathToolInput { path: input_path }),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let result = task.await;
|
||||
assert!(result.is_ok(), "should delete after approval: {result:?}");
|
||||
assert!(!fs.is_file(&skill_file).await);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_delete_path_rejects_global_skills_root(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root/project"), json!({})).await;
|
||||
let skills_dir = agent_skills::global_skills_dir();
|
||||
fs.create_dir(&skills_dir).await.unwrap();
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let action_log = cx.new(|_| ActionLog::new(project.clone()));
|
||||
let tool = Arc::new(DeletePathTool::new(project, action_log));
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let result = cx
|
||||
.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(DeletePathToolInput { path: input_path }),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
})
|
||||
.await;
|
||||
|
||||
assert!(result.is_err(), "should reject deleting skills root");
|
||||
assert!(fs.is_dir(&skills_dir).await);
|
||||
assert!(
|
||||
!matches!(
|
||||
event_rx.try_recv(),
|
||||
Ok(Ok(crate::ThreadEvent::ToolCallAuthorization(_)))
|
||||
),
|
||||
"Deleting the skills root should fail before requesting authorization",
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_delete_path_symlink_escape_requests_authorization(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
|
|
|||
|
|
@ -23,13 +23,21 @@ const DEFAULT_UI_TEXT: &str = "Editing file";
|
|||
|
||||
/// This is a tool for applying edits to an existing file.
|
||||
///
|
||||
/// Before using this tool, use the `read_file` tool to understand the file's contents and context
|
||||
/// Before using this tool, use the `read_file` tool to understand the file's contents and context.
|
||||
/// To create a new file or overwrite an existing one with completely new contents, use the `write_file` tool instead.
|
||||
///
|
||||
/// The only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.
|
||||
///
|
||||
/// `read_file` prefixes each line of its output with a line number right-aligned in a
|
||||
/// 6-character field followed by a single tab, then the line's actual content. When you
|
||||
/// derive `old_text` or `new_text` from that output, strip this prefix and keep only what
|
||||
/// comes after the tab, preserving the original indentation (tabs and spaces) exactly.
|
||||
/// Never include any part of the line number prefix in `old_text` or `new_text`.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct EditFileToolInput {
|
||||
/// The full path of the file to edit in the project.
|
||||
///
|
||||
/// WARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories.
|
||||
/// WARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories, unless it's a global agent skill under `~/.agents/skills`.
|
||||
///
|
||||
/// The following examples assume we have two root directories in the project:
|
||||
/// - /a/b/backend
|
||||
|
|
@ -44,6 +52,10 @@ pub struct EditFileToolInput {
|
|||
/// <example>
|
||||
/// `frontend/db.js`
|
||||
/// </example>
|
||||
///
|
||||
/// <example>
|
||||
/// To edit a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.
|
||||
/// </example>
|
||||
pub path: PathBuf,
|
||||
|
||||
/// List of edit operations to apply sequentially.
|
||||
|
|
@ -253,6 +265,7 @@ impl AgentTool for EditFileTool {
|
|||
run_session(
|
||||
self.process_streaming_edits(&mut input, &event_stream, cx)
|
||||
.await,
|
||||
&event_stream,
|
||||
cx,
|
||||
)
|
||||
.await
|
||||
|
|
@ -457,6 +470,63 @@ mod tests {
|
|||
assert_eq!(input_path, None);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_streaming_edit_global_skill_file(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = project::FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root"), json!({})).await;
|
||||
let skill_dir = agent_skills::global_skills_dir().join("my-skill");
|
||||
fs.insert_tree(&skill_dir, json!({ "SKILL.md": "old content\n" }))
|
||||
.await;
|
||||
let (edit_tool, _project, _action_log, fs, _thread) =
|
||||
setup_test_with_fs(cx, fs, &[path!("/root").as_ref()]).await;
|
||||
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.join("SKILL.md");
|
||||
let skill_file = agent_skills::global_skills_dir()
|
||||
.join("my-skill")
|
||||
.join("SKILL.md");
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
edit_tool.clone().run(
|
||||
ToolInput::resolved(EditFileToolInput {
|
||||
path: input_path,
|
||||
edits: vec![Edit {
|
||||
old_text: "old content".into(),
|
||||
new_text: "new content".into(),
|
||||
}],
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
event_rx.expect_update_fields().await;
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let EditFileToolOutput::Success { new_text, .. } = task.await.unwrap() else {
|
||||
panic!("expected success");
|
||||
};
|
||||
assert_eq!(new_text, "new content\n");
|
||||
assert_eq!(fs.load(&skill_file).await.unwrap(), "new content\n");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_streaming_edit_failed_match(cx: &mut TestAppContext) {
|
||||
let (edit_tool, _project, _action_log, _fs, _thread) =
|
||||
|
|
@ -486,6 +556,69 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
/// When the edit fails after a session is created but before any edits are
|
||||
/// actually applied (e.g., the first `old_text` doesn't match), the empty
|
||||
/// diff placeholder in the UI should be replaced with the error message.
|
||||
#[gpui::test]
|
||||
async fn test_streaming_edit_surfaces_error_when_no_edits_applied(cx: &mut TestAppContext) {
|
||||
async fn find_first_text_content_in_events(
|
||||
receiver: &mut crate::ToolCallEventStreamReceiver,
|
||||
) -> Option<String> {
|
||||
use futures::StreamExt as _;
|
||||
while let Some(event) = receiver.next().await {
|
||||
let Ok(crate::ThreadEvent::ToolCallUpdate(
|
||||
acp_thread::ToolCallUpdate::UpdateFields(update),
|
||||
)) = event
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(content) = update.fields.content else {
|
||||
continue;
|
||||
};
|
||||
for item in content {
|
||||
if let acp::ToolCallContent::Content(c) = item
|
||||
&& let acp::ContentBlock::Text(text) = c.content
|
||||
{
|
||||
return Some(text.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
let (edit_tool, _project, _action_log, _fs, _thread) =
|
||||
setup_test(cx, json!({"file.txt": "hello world"})).await;
|
||||
let (event_stream, mut receiver) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
edit_tool.clone().run(
|
||||
ToolInput::resolved(EditFileToolInput {
|
||||
path: "root/file.txt".into(),
|
||||
edits: vec![Edit {
|
||||
old_text: "nonexistent text that is not in the file".into(),
|
||||
new_text: "replacement".into(),
|
||||
}],
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let EditFileToolOutput::Error { error, diff, .. } = task.await.unwrap_err() else {
|
||||
panic!("expected error");
|
||||
};
|
||||
assert!(
|
||||
diff.is_empty(),
|
||||
"sanity check: no edits should have been applied",
|
||||
);
|
||||
|
||||
let content_text = find_first_text_content_in_events(&mut receiver).await;
|
||||
assert_eq!(
|
||||
content_text.as_deref(),
|
||||
Some(error.as_str()),
|
||||
"expected the failure message to be surfaced as tool call content",
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_streaming_early_buffer_open(cx: &mut TestAppContext) {
|
||||
let (edit_tool, _project, _action_log, _fs, _thread) =
|
||||
|
|
@ -2475,7 +2608,8 @@ mod tests {
|
|||
|
||||
cx.run_until_parked();
|
||||
|
||||
let changed = action_log.read_with(cx, |log, cx| log.changed_buffers(cx));
|
||||
let changed =
|
||||
action_log.read_with(cx, |log, cx| log.changed_buffers(cx).collect::<Vec<_>>());
|
||||
assert!(
|
||||
!changed.is_empty(),
|
||||
"action_log.changed_buffers() should be non-empty after streaming edit,
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ mod reindent;
|
|||
mod streaming_fuzzy_matcher;
|
||||
mod streaming_parser;
|
||||
|
||||
use super::tool_permissions::resolve_creatable_global_skill_path;
|
||||
use crate::{Thread, ToolCallEventStream};
|
||||
use acp_thread::Diff;
|
||||
use action_log::ActionLog;
|
||||
|
|
@ -11,7 +12,7 @@ use collections::HashSet;
|
|||
use futures::{FutureExt, channel::oneshot};
|
||||
use gpui::{App, AppContext, AsyncApp, Entity, Task, WeakEntity};
|
||||
use language::language_settings::{self, FormatOnSave};
|
||||
use language::{Buffer, BufferEvent, LanguageRegistry};
|
||||
use language::{Buffer, BufferEditSource, BufferEvent, LanguageRegistry};
|
||||
use language_model::LanguageModelToolResultContent;
|
||||
use project::lsp_store::{FormatTrigger, LspFormatTarget};
|
||||
use project::{AgentLocation, Project, ProjectPath};
|
||||
|
|
@ -277,6 +278,7 @@ pub(crate) enum EditSessionResult {
|
|||
|
||||
pub(crate) async fn run_session(
|
||||
result: EditSessionResult,
|
||||
event_stream: &ToolCallEventStream,
|
||||
cx: &mut AsyncApp,
|
||||
) -> Result<EditSessionOutput, EditSessionOutput> {
|
||||
match result {
|
||||
|
|
@ -302,6 +304,11 @@ pub(crate) async fn run_session(
|
|||
.ensure_buffer_saved(&session.buffer, cx)
|
||||
.await;
|
||||
let (_new_text, diff) = session.compute_new_text_and_diff(cx).await;
|
||||
if diff.is_empty() {
|
||||
event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
|
||||
acp::ToolCallContent::Content(acp::Content::new(error.clone())),
|
||||
]));
|
||||
}
|
||||
Err(EditSessionOutput::Error {
|
||||
error,
|
||||
input_path: Some(session.input_path),
|
||||
|
|
@ -311,11 +318,16 @@ pub(crate) async fn run_session(
|
|||
EditSessionResult::Failed {
|
||||
error,
|
||||
session: None,
|
||||
} => Err(EditSessionOutput::Error {
|
||||
error,
|
||||
input_path: None,
|
||||
diff: String::new(),
|
||||
}),
|
||||
} => {
|
||||
event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
|
||||
acp::ToolCallContent::Content(acp::Content::new(error.clone())),
|
||||
]));
|
||||
Err(EditSessionOutput::Error {
|
||||
error,
|
||||
input_path: None,
|
||||
diff: String::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -352,6 +364,16 @@ pub(crate) struct EditSession {
|
|||
_finalize_diff_guard: Deferred<Box<dyn FnOnce()>>,
|
||||
}
|
||||
|
||||
/// The destination of an edit session, identified by its absolute path on
|
||||
/// disk. `project_path` is `Some` for files that live inside one of the
|
||||
/// project's worktrees (i.e. that the standard project-path machinery can
|
||||
/// resolve), and `None` for global skill files reached through the
|
||||
/// `~/.agents/skills` allowlist.
|
||||
struct EditSessionTarget {
|
||||
abs_path: PathBuf,
|
||||
project_path: Option<ProjectPath>,
|
||||
}
|
||||
|
||||
enum Pipeline {
|
||||
Write(WritePipeline),
|
||||
Edit(EditPipeline),
|
||||
|
|
@ -598,21 +620,14 @@ impl EditPipeline {
|
|||
|
||||
log::debug!("new_text_chunk: done=true, final_text='{}'", final_text);
|
||||
|
||||
if !final_text.is_empty() {
|
||||
let char_ops = streaming_diff.push_new(&final_text);
|
||||
apply_char_operations(
|
||||
&char_ops,
|
||||
buffer,
|
||||
&original_snapshot,
|
||||
&mut edit_cursor,
|
||||
&context.action_log,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
|
||||
let remaining_ops = streaming_diff.finish();
|
||||
let mut char_ops = if final_text.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
streaming_diff.push_new(&final_text)
|
||||
};
|
||||
char_ops.extend(streaming_diff.finish());
|
||||
apply_char_operations(
|
||||
&remaining_ops,
|
||||
&char_ops,
|
||||
buffer,
|
||||
&original_snapshot,
|
||||
&mut edit_cursor,
|
||||
|
|
@ -639,16 +654,34 @@ impl EditSession {
|
|||
event_stream: &ToolCallEventStream,
|
||||
cx: &mut AsyncApp,
|
||||
) -> Result<Self, String> {
|
||||
let project_path = cx.update(|cx| resolve_path(mode, &path, &context.project, cx))?;
|
||||
let target = if let Some(abs_path) =
|
||||
resolve_global_skill_path_for_edit_session(mode, &path, &context, cx).await?
|
||||
{
|
||||
EditSessionTarget {
|
||||
abs_path,
|
||||
project_path: None,
|
||||
}
|
||||
} else {
|
||||
let project_path = cx.update(|cx| resolve_path(mode, &path, &context.project, cx))?;
|
||||
|
||||
let Some(abs_path) =
|
||||
cx.update(|cx| context.project.read(cx).absolute_path(&project_path, cx))
|
||||
else {
|
||||
return Err(format!(
|
||||
"Worktree at '{}' does not exist",
|
||||
path.to_string_lossy()
|
||||
));
|
||||
let Some(abs_path) =
|
||||
cx.update(|cx| context.project.read(cx).absolute_path(&project_path, cx))
|
||||
else {
|
||||
return Err(format!(
|
||||
"Worktree at '{}' does not exist",
|
||||
path.to_string_lossy()
|
||||
));
|
||||
};
|
||||
|
||||
EditSessionTarget {
|
||||
abs_path,
|
||||
project_path: Some(project_path),
|
||||
}
|
||||
};
|
||||
let EditSessionTarget {
|
||||
abs_path,
|
||||
project_path,
|
||||
} = target;
|
||||
|
||||
event_stream.update_fields(
|
||||
ToolCallUpdateFields::new().locations(vec![ToolCallLocation::new(abs_path.clone())]),
|
||||
|
|
@ -658,11 +691,20 @@ impl EditSession {
|
|||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let buffer = context
|
||||
.project
|
||||
.update(cx, |project, cx| project.open_buffer(project_path, cx))
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let buffer = match project_path {
|
||||
Some(project_path) => context
|
||||
.project
|
||||
.update(cx, |project, cx| project.open_buffer(project_path, cx))
|
||||
.await
|
||||
.map_err(|e| e.to_string())?,
|
||||
None => context
|
||||
.project
|
||||
.update(cx, |project, cx| {
|
||||
project.open_local_buffer(abs_path.clone(), cx)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())?,
|
||||
};
|
||||
|
||||
let file_changed_since_last_read =
|
||||
ensure_buffer_saved(&buffer, &abs_path, mode, &context, event_stream, cx).await?;
|
||||
|
|
@ -853,16 +895,17 @@ fn apply_char_operations(
|
|||
action_log: &Entity<ActionLog>,
|
||||
cx: &mut AsyncApp,
|
||||
) {
|
||||
let mut edits: Vec<_> = Vec::new();
|
||||
for op in ops {
|
||||
match op {
|
||||
CharOperation::Insert { text } => {
|
||||
let anchor = snapshot.anchor_after(*edit_cursor);
|
||||
agent_edit_buffer(&buffer, [(anchor..anchor, text.as_str())], action_log, cx);
|
||||
edits.push((anchor..anchor, text.as_str().into()));
|
||||
}
|
||||
CharOperation::Delete { bytes } => {
|
||||
let delete_end = *edit_cursor + bytes;
|
||||
let anchor_range = snapshot.anchor_range_inside(*edit_cursor..delete_end);
|
||||
agent_edit_buffer(&buffer, [(anchor_range, "")], action_log, cx);
|
||||
edits.push((anchor_range, Arc::<str>::from("")));
|
||||
*edit_cursor = delete_end;
|
||||
}
|
||||
CharOperation::Keep { bytes } => {
|
||||
|
|
@ -870,6 +913,9 @@ fn apply_char_operations(
|
|||
}
|
||||
}
|
||||
}
|
||||
if !edits.is_empty() {
|
||||
agent_edit_buffer(buffer, edits, action_log, cx);
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_match(
|
||||
|
|
@ -926,7 +972,9 @@ fn agent_edit_buffer<I, S, T>(
|
|||
{
|
||||
cx.update(|cx| {
|
||||
buffer.update(cx, |buffer, cx| {
|
||||
buffer.start_transaction();
|
||||
buffer.edit(edits, None, cx);
|
||||
buffer.end_transaction_with_source(BufferEditSource::Agent, cx);
|
||||
});
|
||||
action_log.update(cx, |log, cx| log.buffer_edited(buffer.clone(), cx));
|
||||
});
|
||||
|
|
@ -1055,6 +1103,72 @@ async fn resolve_dirty_buffer(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Mirrors [`resolve_path`]'s pre-auth validation for the global-skill
|
||||
/// branch: returns `Ok(Some(abs_path))` if the path lives under
|
||||
/// `~/.agents/skills` and is in a valid state for the requested mode,
|
||||
/// `Ok(None)` if the path isn't a global skill at all (so the caller should
|
||||
/// fall through to project-path resolution), or `Err(message)` if the path
|
||||
/// is a global skill but can't be used (missing in Edit mode, parent
|
||||
/// missing in Write mode, etc.).
|
||||
///
|
||||
/// Errors returned from here surface to the model as tool-result errors
|
||||
/// without prompting the user — same contract as [`resolve_path`]. The
|
||||
/// idea is that "file doesn't exist" or "parent isn't a directory" are
|
||||
/// model mistakes, not decisions the user should be asked to approve.
|
||||
async fn resolve_global_skill_path_for_edit_session(
|
||||
mode: EditSessionMode,
|
||||
path: &PathBuf,
|
||||
context: &EditSessionContext,
|
||||
cx: &mut AsyncApp,
|
||||
) -> Result<Option<PathBuf>, String> {
|
||||
let fs = context
|
||||
.project
|
||||
.read_with(cx, |project, _cx| project.fs().clone());
|
||||
let Some(abs_path) = resolve_creatable_global_skill_path(path, fs.as_ref()).await else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
match mode {
|
||||
EditSessionMode::Edit => {
|
||||
let metadata = fs
|
||||
.metadata(&abs_path)
|
||||
.await
|
||||
.map_err(|e| format!("Can't edit file: {e}"))?
|
||||
.ok_or_else(|| "Can't edit file: path not found".to_string())?;
|
||||
if metadata.is_dir {
|
||||
return Err("Can't edit file: path is a directory".to_string());
|
||||
}
|
||||
}
|
||||
EditSessionMode::Write => {
|
||||
if let Some(metadata) = fs
|
||||
.metadata(&abs_path)
|
||||
.await
|
||||
.map_err(|e| format!("Can't write to file: {e}"))?
|
||||
{
|
||||
if metadata.is_dir {
|
||||
return Err("Can't write to file: path is a directory".to_string());
|
||||
}
|
||||
} else {
|
||||
let parent_path = abs_path
|
||||
.parent()
|
||||
.ok_or_else(|| "Can't create file: incorrect path".to_string())?;
|
||||
let parent_metadata = fs
|
||||
.metadata(parent_path)
|
||||
.await
|
||||
.map_err(|e| format!("Can't create file: {e}"))?
|
||||
.ok_or_else(|| {
|
||||
"Can't create file: parent directory doesn't exist".to_string()
|
||||
})?;
|
||||
if !parent_metadata.is_dir {
|
||||
return Err("Can't create file: parent is not a directory".to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(abs_path))
|
||||
}
|
||||
|
||||
fn resolve_path(
|
||||
mode: EditSessionMode,
|
||||
path: &PathBuf,
|
||||
|
|
|
|||
|
|
@ -361,7 +361,7 @@ impl EditToolTest {
|
|||
abs_path: Path::new("/path/to/root").into(),
|
||||
rules_file: None,
|
||||
}];
|
||||
let project_context = ProjectContext::new(worktrees, Vec::default());
|
||||
let project_context = ProjectContext::new(worktrees);
|
||||
let tool_names = tools
|
||||
.iter()
|
||||
.map(|tool| tool.name.clone().into())
|
||||
|
|
@ -372,6 +372,7 @@ impl EditToolTest {
|
|||
model_name: None,
|
||||
date: chrono::Local::now().format("%Y-%m-%d").to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: false,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
template.render(&templates)?
|
||||
|
|
|
|||
|
|
@ -220,7 +220,7 @@ impl TerminalToolTest {
|
|||
abs_path: Path::new("/path/to/root").into(),
|
||||
rules_file: None,
|
||||
}];
|
||||
let project_context = ProjectContext::new(worktrees, Vec::default());
|
||||
let project_context = ProjectContext::new(worktrees);
|
||||
let tool_names = tools
|
||||
.iter()
|
||||
.map(|tool| tool.name.clone().into())
|
||||
|
|
@ -231,6 +231,7 @@ impl TerminalToolTest {
|
|||
model_name: None,
|
||||
date: chrono::Local::now().format("%Y-%m-%d").to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: false,
|
||||
};
|
||||
template.render(&Templates::new())?
|
||||
};
|
||||
|
|
|
|||
|
|
@ -191,7 +191,7 @@ impl WriteToolTest {
|
|||
abs_path: Path::new("/path/to/root").into(),
|
||||
rules_file: None,
|
||||
}];
|
||||
let project_context = ProjectContext::new(worktrees, Vec::default());
|
||||
let project_context = ProjectContext::new(worktrees);
|
||||
let tool_names = tools
|
||||
.iter()
|
||||
.map(|tool| tool.name.clone().into())
|
||||
|
|
@ -202,6 +202,7 @@ impl WriteToolTest {
|
|||
model_name: None,
|
||||
date: chrono::Local::now().format("%Y-%m-%d").to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: false,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
template.render(&templates)?
|
||||
|
|
|
|||
|
|
@ -18,11 +18,13 @@ use std::sync::Arc;
|
|||
use util::markdown::MarkdownInlineCode;
|
||||
|
||||
/// Lists files and directories in a given path. Prefer the `grep` or `find_path` tools when searching the codebase.
|
||||
///
|
||||
/// The only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct ListDirectoryToolInput {
|
||||
/// The fully-qualified path of the directory to list in the project.
|
||||
///
|
||||
/// This path should never be absolute, and the first component of the path should always be a root directory in a project.
|
||||
/// This path should never be absolute, and the first component of the path should always be a root directory in a project, unless it's a global agent skill directory under `~/.agents/skills`.
|
||||
///
|
||||
/// <example>
|
||||
/// If the project has the following root directories:
|
||||
|
|
@ -41,6 +43,10 @@ pub struct ListDirectoryToolInput {
|
|||
///
|
||||
/// If you wanna list contents in the directory `foo/baz`, you should use the path `foo/baz`.
|
||||
/// </example>
|
||||
///
|
||||
/// <example>
|
||||
/// To list a global agent skill directory, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill`.
|
||||
/// </example>
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
|
|
@ -234,7 +240,7 @@ impl AgentTool for ListDirectoryTool {
|
|||
|
||||
// Fast path: a global skill resource lives outside any worktree, so
|
||||
// standard project-path resolution would refuse it. If the path
|
||||
// resolves under the global skills tree, list it directly.
|
||||
// expands and resolves under the global skills tree, list it directly.
|
||||
if let Some(skill_path) =
|
||||
resolve_global_skill_path(Path::new(&input.path), fs.as_ref()).await
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
use super::tool_permissions::{
|
||||
authorize_symlink_escapes, canonicalize_worktree_roots, collect_symlink_escapes,
|
||||
sensitive_settings_kind,
|
||||
resolve_creatable_global_skill_descendant_path, resolve_global_skill_descendant_path,
|
||||
resolves_to_global_skills_dir, sensitive_settings_kind,
|
||||
};
|
||||
use crate::{
|
||||
AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision,
|
||||
|
|
@ -22,6 +23,7 @@ use util::markdown::MarkdownInlineCode;
|
|||
/// If the source and destination directories are the same, but the filename is different, this performs a rename. Otherwise, it performs a move.
|
||||
///
|
||||
/// This tool should be used when it's desirable to move or rename a file or directory without changing its contents at all.
|
||||
/// The only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct MovePathToolInput {
|
||||
/// The source path of the file or directory to move/rename.
|
||||
|
|
@ -116,6 +118,28 @@ impl AgentTool for MovePathTool {
|
|||
let fs = project.read_with(cx, |project, _cx| project.fs().clone());
|
||||
let canonical_roots = canonicalize_worktree_roots(&project, &fs, cx).await;
|
||||
|
||||
if resolves_to_global_skills_dir(Path::new(&input.source_path), fs.as_ref()).await
|
||||
|| resolves_to_global_skills_dir(
|
||||
Path::new(&input.destination_path),
|
||||
fs.as_ref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Err(
|
||||
"Cannot move the global agent skills directory itself. Move a skill directory or file beneath it instead."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
let global_source_path =
|
||||
resolve_global_skill_descendant_path(Path::new(&input.source_path), fs.as_ref())
|
||||
.await;
|
||||
let global_destination_path = resolve_creatable_global_skill_descendant_path(
|
||||
Path::new(&input.destination_path),
|
||||
fs.as_ref(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let symlink_escapes: Vec<(&str, std::path::PathBuf)> =
|
||||
project.read_with(cx, |project, cx| {
|
||||
collect_symlink_escapes(
|
||||
|
|
@ -176,6 +200,65 @@ impl AgentTool for MovePathTool {
|
|||
authorize.await.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
if global_source_path.is_some() || global_destination_path.is_some() {
|
||||
let source_path = if let Some(global_source_path) = global_source_path {
|
||||
global_source_path
|
||||
} else {
|
||||
project.read_with(cx, |project, cx| {
|
||||
let project_path = project.find_project_path(&input.source_path, cx).ok_or_else(|| {
|
||||
format!("Source path {} was not found in the project.", input.source_path)
|
||||
})?;
|
||||
project.entry_for_path(&project_path, cx).ok_or_else(|| {
|
||||
format!("Source path {} was not found in the project.", input.source_path)
|
||||
})?;
|
||||
project.absolute_path(&project_path, cx).ok_or_else(|| {
|
||||
format!("Source path {} could not be resolved.", input.source_path)
|
||||
})
|
||||
})?
|
||||
};
|
||||
|
||||
let destination_path = if let Some(global_destination_path) = global_destination_path
|
||||
{
|
||||
global_destination_path
|
||||
} else {
|
||||
project.read_with(cx, |project, cx| {
|
||||
let project_path = project.find_project_path(&input.destination_path, cx).ok_or_else(|| {
|
||||
format!(
|
||||
"Destination path {} was outside the project.",
|
||||
input.destination_path
|
||||
)
|
||||
})?;
|
||||
project.absolute_path(&project_path, cx).ok_or_else(|| {
|
||||
format!(
|
||||
"Destination path {} could not be resolved.",
|
||||
input.destination_path
|
||||
)
|
||||
})
|
||||
})?
|
||||
};
|
||||
|
||||
futures::select! {
|
||||
result = fs.rename(
|
||||
&source_path,
|
||||
&destination_path,
|
||||
fs::RenameOptions {
|
||||
create_parents: true,
|
||||
..fs::RenameOptions::default()
|
||||
},
|
||||
).fuse() => {
|
||||
result.map_err(|e| format!("Moving {} to {}: {e}", input.source_path, input.destination_path))?;
|
||||
}
|
||||
_ = event_stream.cancelled_by_user().fuse() => {
|
||||
return Err("Move cancelled by user".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(format!(
|
||||
"Moved {} to {}",
|
||||
input.source_path, input.destination_path
|
||||
));
|
||||
}
|
||||
|
||||
let rename_task = project.update(cx, |project, cx| {
|
||||
match project
|
||||
.find_project_path(&input.source_path, cx)
|
||||
|
|
@ -232,6 +315,125 @@ mod tests {
|
|||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_move_path_global_skill_directory_to_project(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root/project"), json!({})).await;
|
||||
let skill_dir = agent_skills::global_skills_dir().join("my-skill");
|
||||
fs.insert_tree(&skill_dir, json!({ "SKILL.md": "content" }))
|
||||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let tool = Arc::new(MovePathTool::new(project));
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let destination_path = path!("/root/project/my-skill").to_string();
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(MovePathToolInput {
|
||||
source_path: input_path,
|
||||
destination_path,
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let result = task.await;
|
||||
assert!(result.is_ok(), "should move after approval: {result:?}");
|
||||
assert!(!fs.is_dir(&skill_dir).await);
|
||||
assert_eq!(
|
||||
fs.load(path!("/root/project/my-skill/SKILL.md").as_ref())
|
||||
.await
|
||||
.unwrap(),
|
||||
"content"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_move_path_project_directory_to_global_skill_directory(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(
|
||||
path!("/root/project"),
|
||||
json!({ "exported-skill": { "SKILL.md": "content" } }),
|
||||
)
|
||||
.await;
|
||||
let skills_dir = agent_skills::global_skills_dir();
|
||||
fs.create_dir(&skills_dir).await.unwrap();
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let tool = Arc::new(MovePathTool::new(project));
|
||||
let destination_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("exported-skill")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(MovePathToolInput {
|
||||
source_path: path!("/root/project/exported-skill").to_string(),
|
||||
destination_path,
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let result = task.await;
|
||||
assert!(result.is_ok(), "should move after approval: {result:?}");
|
||||
assert!(
|
||||
!fs.is_dir(path!("/root/project/exported-skill").as_ref())
|
||||
.await
|
||||
);
|
||||
assert_eq!(
|
||||
fs.load(skills_dir.join("exported-skill").join("SKILL.md").as_ref())
|
||||
.await
|
||||
.unwrap(),
|
||||
"content"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_move_path_symlink_escape_source_requests_authorization(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
|
|
|||
|
|
@ -18,6 +18,80 @@ fn tool_content_err(e: impl std::fmt::Display) -> LanguageModelToolResultContent
|
|||
LanguageModelToolResultContent::from(e.to_string())
|
||||
}
|
||||
|
||||
/// Resolves the optional `start_line` / `end_line` inputs from the tool schema
|
||||
/// to a concrete 1-indexed, inclusive `(start, end)` line range:
|
||||
///
|
||||
/// - `start` defaults to 1 and is clamped to `>= 1` (the model occasionally passes
|
||||
/// `0` despite instructions to be 1-indexed).
|
||||
/// - `end` defaults to `u32::MAX` and is clamped to `>= start`, so callers always
|
||||
/// read at least one line even when the model passes `end < start`.
|
||||
///
|
||||
/// Callers translate this 1-indexed inclusive range to whichever coordinate
|
||||
/// system their slicing API wants (e.g. 0-indexed exclusive row ranges for
|
||||
/// `Buffer::text_for_range`).
|
||||
fn resolve_line_range(start_line: Option<u32>, end_line: Option<u32>) -> (u32, u32) {
|
||||
let start = start_line.unwrap_or(1).max(1);
|
||||
let end = end_line.unwrap_or(u32::MAX).max(start);
|
||||
(start, end)
|
||||
}
|
||||
|
||||
/// Prefixes each line of `text` with its line number in `cat -n` format:
|
||||
/// the line number is right-aligned in a 6-character field, followed by a
|
||||
/// single tab, followed by the line's original content (including its
|
||||
/// trailing newline if present). Numbering starts at `start_line`.
|
||||
///
|
||||
/// This format matches what the model expects in the edit tool, where the
|
||||
/// line number prefix is `line number + tab` and everything after the tab is
|
||||
/// the actual file content to match.
|
||||
fn format_with_line_numbers(text: &str, start_line: u32) -> String {
|
||||
if text.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let mut output = String::with_capacity(text.len() + text.len() / 4);
|
||||
write_lines_numbered(&mut output, std::iter::once(text), start_line);
|
||||
output
|
||||
}
|
||||
|
||||
/// Streams `cat -n`-style line-numbered output directly into `output` from an
|
||||
/// iterator of string slices. Chunks do not need to align to line boundaries:
|
||||
/// a single chunk may contain multiple newlines, span multiple lines, or end
|
||||
/// mid-line. This lets callers consume `Buffer::text_for_range`'s `Chunks`
|
||||
/// iterator without materializing the unnumbered text first.
|
||||
fn write_lines_numbered<'a>(
|
||||
output: &mut String,
|
||||
chunks: impl IntoIterator<Item = &'a str>,
|
||||
start_line: u32,
|
||||
) {
|
||||
use std::fmt::Write as _;
|
||||
|
||||
let mut line_number = start_line;
|
||||
let mut at_line_start = true;
|
||||
for chunk in chunks {
|
||||
let mut rest = chunk;
|
||||
while !rest.is_empty() {
|
||||
if at_line_start {
|
||||
// Writes to a `String` are infallible, so the `Result` can be ignored.
|
||||
let _ = write!(output, "{line_number:>6}\t");
|
||||
at_line_start = false;
|
||||
}
|
||||
match rest.find('\n') {
|
||||
Some(nl) => {
|
||||
let (head, tail) = rest.split_at(nl + 1);
|
||||
output.push_str(head);
|
||||
line_number = line_number.saturating_add(1);
|
||||
at_line_start = true;
|
||||
rest = tail;
|
||||
}
|
||||
None => {
|
||||
output.push_str(rest);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a file under the global skills directory directly via the filesystem,
|
||||
/// bypassing project/worktree resolution. Used for skill resources that live
|
||||
/// outside any worktree.
|
||||
|
|
@ -40,26 +114,21 @@ async fn read_global_skill_file(
|
|||
.line(start_line.map(|line| line.saturating_sub(1))),
|
||||
]));
|
||||
|
||||
let result_text = if start_line.is_some() || end_line.is_some() {
|
||||
// Mirror the line-range semantics of the buffer-backed path: 1-indexed,
|
||||
// start clamped to >= 1, end exclusive of the next line, and always
|
||||
// returning at least one line. `split_inclusive` keeps each line's
|
||||
// terminator attached, so CRLF stays CRLF and the trailing newline of
|
||||
// the last returned line is preserved — matching `Buffer::text_for_range`.
|
||||
let start = start_line.unwrap_or(1).max(1);
|
||||
let mut end = end_line.unwrap_or(u32::MAX);
|
||||
if end < start {
|
||||
end = start;
|
||||
}
|
||||
|
||||
let (raw_text, first_line_number) = if start_line.is_some() || end_line.is_some() {
|
||||
// `split_inclusive` keeps each line's terminator attached, so CRLF stays
|
||||
// CRLF and the trailing newline of the last returned line is preserved —
|
||||
// matching `Buffer::text_for_range` in the buffer-backed path.
|
||||
let (start, end) = resolve_line_range(start_line, end_line);
|
||||
let lines: Vec<&str> = content.split_inclusive('\n').collect();
|
||||
let start_idx = (start as usize).saturating_sub(1).min(lines.len());
|
||||
let end_idx = (end as usize).min(lines.len()).max(start_idx);
|
||||
lines[start_idx..end_idx].concat()
|
||||
(lines[start_idx..end_idx].concat(), start)
|
||||
} else {
|
||||
content
|
||||
(content, 1)
|
||||
};
|
||||
|
||||
let result_text = format_with_line_numbers(&raw_text, first_line_number);
|
||||
|
||||
let markdown = MarkdownCodeBlock {
|
||||
tag: requested_path,
|
||||
text: &result_text,
|
||||
|
|
@ -86,11 +155,13 @@ use crate::{AgentTool, ToolCallEventStream, ToolInput, outline};
|
|||
/// Do NOT retry reading the same file without line numbers if you receive an outline.
|
||||
/// - This tool supports reading image files. Supported formats: PNG, JPEG, WebP, GIF, BMP, TIFF.
|
||||
/// Image files are returned as visual content that you can analyze directly.
|
||||
///
|
||||
/// The only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct ReadFileToolInput {
|
||||
/// The relative path of the file to read.
|
||||
///
|
||||
/// This path should never be absolute, and the first component of the path should always be a root directory in a project.
|
||||
/// This path should never be absolute, and the first component of the path should always be a root directory in a project, unless it's a global agent skill under `~/.agents/skills`.
|
||||
///
|
||||
/// <example>
|
||||
/// If the project has the following root directories:
|
||||
|
|
@ -101,6 +172,10 @@ pub struct ReadFileToolInput {
|
|||
/// If you want to access `file.txt` in `directory1`, you should use the path `directory1/file.txt`.
|
||||
/// If you want to access `file.txt` in `directory2`, you should use the path `directory2/file.txt`.
|
||||
/// </example>
|
||||
///
|
||||
/// <example>
|
||||
/// To read a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.
|
||||
/// </example>
|
||||
pub path: String,
|
||||
/// Optional line number to start reading on (1-based index)
|
||||
#[serde(default)]
|
||||
|
|
@ -182,8 +257,8 @@ impl AgentTool for ReadFileTool {
|
|||
.map_err(tool_content_err)?;
|
||||
let fs = project.read_with(cx, |project, _cx| project.fs().clone());
|
||||
|
||||
// Fast path: if the model passes an absolute path that resolves
|
||||
// under the global skills directory, read it directly via the
|
||||
// Fast path: if the model passes a path that resolves under the
|
||||
// global skills directory, read it directly via the
|
||||
// filesystem. Global skills live outside any worktree, so the
|
||||
// standard project-path machinery would refuse them.
|
||||
if let Some(skill_path) =
|
||||
|
|
@ -338,32 +413,42 @@ impl AgentTool for ReadFileTool {
|
|||
}
|
||||
|
||||
let mut anchor = None;
|
||||
let mut is_outline_response = false;
|
||||
|
||||
// Check if specific line ranges are provided
|
||||
let result = if input.start_line.is_some() || input.end_line.is_some() {
|
||||
let result = buffer.read_with(cx, |buffer, _cx| {
|
||||
// .max(1) because despite instructions to be 1-indexed, sometimes the model passes 0.
|
||||
let start = input.start_line.unwrap_or(1).max(1);
|
||||
let result_text = buffer.read_with(cx, |buffer, _cx| {
|
||||
let (start, end) = resolve_line_range(input.start_line, input.end_line);
|
||||
let start_row = start - 1;
|
||||
if start_row <= buffer.max_point().row {
|
||||
let column = buffer.line_indent_for_row(start_row).raw_len();
|
||||
anchor = Some(buffer.anchor_before(Point::new(start_row, column)));
|
||||
}
|
||||
|
||||
let mut end_row = input.end_line.unwrap_or(u32::MAX);
|
||||
if end_row <= start_row {
|
||||
end_row = start_row + 1; // read at least one lines
|
||||
}
|
||||
let start = buffer.anchor_before(Point::new(start_row, 0));
|
||||
let end = buffer.anchor_before(Point::new(end_row, 0));
|
||||
buffer.text_for_range(start..end).collect::<String>()
|
||||
// `end` is 1-indexed inclusive; `Point` rows are 0-indexed.
|
||||
// Using `end` directly as the (exclusive) end row is the
|
||||
// standard inclusive→exclusive translation, and since
|
||||
// `resolve_line_range` guarantees `end >= start`, we always
|
||||
// read at least one line.
|
||||
let start_anchor = buffer.anchor_before(Point::new(start_row, 0));
|
||||
let end_anchor = buffer.anchor_before(Point::new(end, 0));
|
||||
// Stream the numbered output directly from the buffer's
|
||||
// chunk iterator so the unnumbered range is never
|
||||
// materialized as its own `String`.
|
||||
let mut output = String::new();
|
||||
write_lines_numbered(
|
||||
&mut output,
|
||||
buffer.text_for_range(start_anchor..end_anchor),
|
||||
start,
|
||||
);
|
||||
output
|
||||
});
|
||||
|
||||
action_log.update(cx, |log, cx| {
|
||||
log.buffer_read(buffer.clone(), cx);
|
||||
});
|
||||
|
||||
Ok(result.into())
|
||||
Ok(result_text.into())
|
||||
} else {
|
||||
// No line ranges specified, so check file size to see if it's too big.
|
||||
let buffer_content = outline::get_buffer_content_or_outline(
|
||||
|
|
@ -377,7 +462,10 @@ impl AgentTool for ReadFileTool {
|
|||
log.buffer_read(buffer.clone(), cx);
|
||||
});
|
||||
|
||||
if buffer_content.is_outline {
|
||||
|
||||
is_outline_response = buffer_content.is_synthetic;
|
||||
|
||||
if buffer_content.is_synthetic {
|
||||
Ok(formatdoc! {"
|
||||
SUCCESS: File outline retrieved. This file is too large to read all at once, so the outline below shows the file's structure with line numbers.
|
||||
|
||||
|
|
@ -391,7 +479,7 @@ impl AgentTool for ReadFileTool {
|
|||
}
|
||||
.into())
|
||||
} else {
|
||||
Ok(buffer_content.text.into())
|
||||
Ok(format_with_line_numbers(&buffer_content.text, 1).into())
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -409,11 +497,12 @@ impl AgentTool for ReadFileTool {
|
|||
}
|
||||
if let Ok(LanguageModelToolResultContent::Text(text)) = &result {
|
||||
let text: &str = text;
|
||||
let markdown = MarkdownCodeBlock {
|
||||
tag: &input.path,
|
||||
text,
|
||||
}
|
||||
.to_string();
|
||||
// For outline responses, omit the path tag so the markdown renderer
|
||||
// does not invoke tree-sitter syntax highlighting against pseudo-code
|
||||
// outline text. The outline is not valid source for the file's language,
|
||||
// so highlighting would be both expensive and incorrect.
|
||||
let tag: &str = if is_outline_response { "" } else { &input.path };
|
||||
let markdown = MarkdownCodeBlock { tag, text }.to_string();
|
||||
event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
|
||||
acp::ToolCallContent::Content(acp::Content::new(markdown)),
|
||||
]));
|
||||
|
|
@ -423,6 +512,27 @@ impl AgentTool for ReadFileTool {
|
|||
result
|
||||
})
|
||||
}
|
||||
|
||||
fn replay(
|
||||
&self,
|
||||
input: Self::Input,
|
||||
output: Self::Output,
|
||||
event_stream: ToolCallEventStream,
|
||||
_cx: &mut App,
|
||||
) -> Result<()> {
|
||||
if let LanguageModelToolResultContent::Text(text) = output {
|
||||
let markdown = MarkdownCodeBlock {
|
||||
tag: &input.path,
|
||||
text: &text,
|
||||
}
|
||||
.to_string();
|
||||
event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
|
||||
acp::ToolCallContent::Content(acp::Content::new(markdown)),
|
||||
]));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -526,7 +636,10 @@ mod test {
|
|||
)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result.unwrap(), "This is a small file content".into());
|
||||
assert_eq!(
|
||||
result.unwrap(),
|
||||
" 1\tThis is a small file content".into()
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -610,6 +723,131 @@ mod test {
|
|||
);
|
||||
}
|
||||
|
||||
// The outline returned for a large file is not valid source for the file's
|
||||
// language, so the UI-side markdown wrapping must omit the path tag.
|
||||
// Otherwise the markdown renderer routes the fenced block through
|
||||
// `CodeBlockKind::FencedSrc`, resolves the file's language, and runs
|
||||
// tree-sitter against pseudo-code outline text on every paint.
|
||||
#[gpui::test]
|
||||
async fn test_outline_response_uses_untagged_code_block(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(
|
||||
path!("/root"),
|
||||
json!({
|
||||
"large_file.rs": (0..1000).map(|i| format!("struct Test{} {{\n a: u32,\n b: usize,\n}}", i)).collect::<Vec<_>>().join("\n")
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
|
||||
let language_registry = project.read_with(cx, |project, _| project.languages().clone());
|
||||
language_registry.add(language::rust_lang());
|
||||
let action_log = cx.new(|_| ActionLog::new(project.clone()));
|
||||
let tool = Arc::new(ReadFileTool::new(project, action_log, true));
|
||||
let (event_stream, mut rx) = ToolCallEventStream::test();
|
||||
|
||||
let result = cx
|
||||
.update(|cx| {
|
||||
let input = ReadFileToolInput {
|
||||
path: "root/large_file.rs".into(),
|
||||
start_line: None,
|
||||
end_line: None,
|
||||
};
|
||||
tool.clone()
|
||||
.run(ToolInput::resolved(input), event_stream, cx)
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Sanity-check: the file is large enough to trigger the outline branch.
|
||||
assert!(
|
||||
result
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("SUCCESS: File outline retrieved."),
|
||||
"expected outline response, got: {:?}",
|
||||
result.to_str().unwrap()
|
||||
);
|
||||
|
||||
// The first update carries the location; the second carries the
|
||||
// markdown content destined for the tool-call UI.
|
||||
let _location_update = rx.expect_update_fields().await;
|
||||
let content_update = rx.expect_update_fields().await;
|
||||
let content_blocks = content_update.content.expect("expected content update");
|
||||
let acp::ToolCallContent::Content(content) = content_blocks
|
||||
.first()
|
||||
.expect("expected at least one content block")
|
||||
else {
|
||||
panic!("expected ContentBlock, got {:?}", content_blocks.first());
|
||||
};
|
||||
let acp::ContentBlock::Text(text) = &content.content else {
|
||||
panic!("expected text content block, got {:?}", content.content);
|
||||
};
|
||||
|
||||
assert!(
|
||||
text.text.starts_with("```\n"),
|
||||
"outline response must use an untagged fenced code block; got first line: {:?}",
|
||||
text.text.lines().next()
|
||||
);
|
||||
assert!(
|
||||
!text.text.starts_with("```root/"),
|
||||
"outline response must not include the file path as a code block tag"
|
||||
);
|
||||
}
|
||||
|
||||
// The full-file (non-outline) response should still tag the code block
|
||||
// with the file path so the markdown renderer can resolve the file's
|
||||
// language for syntax highlighting.
|
||||
#[gpui::test]
|
||||
async fn test_full_file_response_keeps_path_tag(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(
|
||||
path!("/root"),
|
||||
json!({
|
||||
"small_file.rs": "fn main() {}"
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
|
||||
let action_log = cx.new(|_| ActionLog::new(project.clone()));
|
||||
let tool = Arc::new(ReadFileTool::new(project, action_log, true));
|
||||
let (event_stream, mut rx) = ToolCallEventStream::test();
|
||||
|
||||
cx.update(|cx| {
|
||||
let input = ReadFileToolInput {
|
||||
path: "root/small_file.rs".into(),
|
||||
start_line: None,
|
||||
end_line: None,
|
||||
};
|
||||
tool.clone()
|
||||
.run(ToolInput::resolved(input), event_stream, cx)
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let _location_update = rx.expect_update_fields().await;
|
||||
let content_update = rx.expect_update_fields().await;
|
||||
let content_blocks = content_update.content.expect("expected content update");
|
||||
let acp::ToolCallContent::Content(content) = content_blocks
|
||||
.first()
|
||||
.expect("expected at least one content block")
|
||||
else {
|
||||
panic!("expected ContentBlock, got {:?}", content_blocks.first());
|
||||
};
|
||||
let acp::ContentBlock::Text(text) = &content.content else {
|
||||
panic!("expected text content block, got {:?}", content.content);
|
||||
};
|
||||
|
||||
assert!(
|
||||
text.text.starts_with("```root/small_file.rs\n"),
|
||||
"full-file response must tag the code block with the file path; got first line: {:?}",
|
||||
text.text.lines().next()
|
||||
);
|
||||
}
|
||||
|
||||
// When a worktree is named "foo" and contains a subdirectory also named "foo",
|
||||
// read_file({"path": "foo/test.txt"}) should return the file at the worktree
|
||||
// root (as the tool schema promises), not the one inside the foo/ subdirectory.
|
||||
|
|
@ -648,7 +886,7 @@ mod test {
|
|||
)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result.unwrap(), "root content".into());
|
||||
assert_eq!(result.unwrap(), " 1\troot content".into());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -681,7 +919,10 @@ mod test {
|
|||
)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result.unwrap(), "Line 2\nLine 3\nLine 4\n".into());
|
||||
assert_eq!(
|
||||
result.unwrap(),
|
||||
" 2\tLine 2\n 3\tLine 3\n 4\tLine 4\n".into()
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -715,7 +956,7 @@ mod test {
|
|||
)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result.unwrap(), "Line 1\nLine 2\n".into());
|
||||
assert_eq!(result.unwrap(), " 1\tLine 1\n 2\tLine 2\n".into());
|
||||
|
||||
// end_line of 0 should result in at least 1 line
|
||||
let result = cx
|
||||
|
|
@ -732,7 +973,7 @@ mod test {
|
|||
)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result.unwrap(), "Line 1\n".into());
|
||||
assert_eq!(result.unwrap(), " 1\tLine 1\n".into());
|
||||
|
||||
// when start_line > end_line, should still return at least 1 line
|
||||
let result = cx
|
||||
|
|
@ -749,7 +990,7 @@ mod test {
|
|||
)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result.unwrap(), "Line 3\n".into());
|
||||
assert_eq!(result.unwrap(), " 3\tLine 3\n".into());
|
||||
}
|
||||
|
||||
fn error_text(content: LanguageModelToolResultContent) -> String {
|
||||
|
|
@ -983,7 +1224,7 @@ mod test {
|
|||
})
|
||||
.await;
|
||||
assert!(result.is_ok(), "Should be able to read normal files");
|
||||
assert_eq!(result.unwrap(), "Normal file content".into());
|
||||
assert_eq!(result.unwrap(), " 1\tNormal file content".into());
|
||||
|
||||
// Path traversal attempts with .. should fail
|
||||
let result = cx
|
||||
|
|
@ -1153,7 +1394,7 @@ mod test {
|
|||
|
||||
assert_eq!(
|
||||
result,
|
||||
"fn main() { println!(\"Hello from worktree1\"); }".into()
|
||||
" 1\tfn main() { println!(\"Hello from worktree1\"); }".into()
|
||||
);
|
||||
|
||||
// Test reading private file in worktree1 should fail
|
||||
|
|
@ -1219,7 +1460,7 @@ mod test {
|
|||
|
||||
assert_eq!(
|
||||
result,
|
||||
"export function greet() { return 'Hello from worktree2'; }".into()
|
||||
" 1\texport function greet() { return 'Hello from worktree2'; }".into()
|
||||
);
|
||||
|
||||
// Test reading private file in worktree2 should fail
|
||||
|
|
@ -1529,7 +1770,10 @@ mod test {
|
|||
let LanguageModelToolResultContent::Text(text) = content else {
|
||||
panic!("expected text content");
|
||||
};
|
||||
assert_eq!(text.as_ref(), "# Spec\n\nReference body.");
|
||||
assert_eq!(
|
||||
text.as_ref(),
|
||||
" 1\t# Spec\n 2\t\n 3\tReference body."
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -1576,7 +1820,7 @@ mod test {
|
|||
};
|
||||
// Mirrors the buffer-backed path: lines 2-3 inclusive, WITH trailing
|
||||
// newline of the last returned line.
|
||||
assert_eq!(text.as_ref(), "line two\nline three\n");
|
||||
assert_eq!(text.as_ref(), " 2\tline two\n 3\tline three\n");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -1621,7 +1865,7 @@ mod test {
|
|||
let LanguageModelToolResultContent::Text(text) = result.unwrap() else {
|
||||
panic!("expected text content");
|
||||
};
|
||||
assert_eq!(text.as_ref(), "Line 1\nLine 2\n");
|
||||
assert_eq!(text.as_ref(), " 1\tLine 1\n 2\tLine 2\n");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -1666,7 +1910,7 @@ mod test {
|
|||
let LanguageModelToolResultContent::Text(text) = result.unwrap() else {
|
||||
panic!("expected text content");
|
||||
};
|
||||
assert_eq!(text.as_ref(), "Line 1\n");
|
||||
assert_eq!(text.as_ref(), " 1\tLine 1\n");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -1711,7 +1955,7 @@ mod test {
|
|||
let LanguageModelToolResultContent::Text(text) = result.unwrap() else {
|
||||
panic!("expected text content");
|
||||
};
|
||||
assert_eq!(text.as_ref(), "Line 3\n");
|
||||
assert_eq!(text.as_ref(), " 3\tLine 3\n");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -1756,7 +2000,7 @@ mod test {
|
|||
let LanguageModelToolResultContent::Text(text) = result.unwrap() else {
|
||||
panic!("expected text content");
|
||||
};
|
||||
assert_eq!(text.as_ref(), "line one\r\nline two\r\n");
|
||||
assert_eq!(text.as_ref(), " 1\tline one\r\n 2\tline two\r\n");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ use std::{
|
|||
time::Duration,
|
||||
};
|
||||
|
||||
use crate::sandboxing::sandboxing_enabled;
|
||||
use crate::{AgentTool, ThreadEnvironment, ToolCallEventStream, ToolInput};
|
||||
|
||||
const COMMAND_OUTPUT_LIMIT: u64 = 16 * 1024;
|
||||
|
|
@ -39,7 +40,7 @@ const COMMAND_OUTPUT_LIMIT: u64 = 16 * 1024;
|
|||
/// - Always insert `--no-pager` immediately after `git` for any read-only git command, including `git log`, `git diff`, `git show`, `git blame`, and `git stash show`. Example: `git --no-pager log -n 5` (NOT `git log -n 5`).
|
||||
/// - Always prepend `GIT_EDITOR=true ` to any git command that may invoke an editor, including `git rebase`, `git commit`, `git merge`, and `git tag`. Example: `GIT_EDITOR=true git rebase origin/main` (NOT `git rebase origin/main`).
|
||||
/// - For other commands that may open a pager or editor, set `PAGER=cat` and/or `EDITOR=true` similarly.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct TerminalToolInput {
|
||||
/// The one-liner command to execute. Do not include shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`; resolve those values first or ask the user.
|
||||
///
|
||||
|
|
@ -49,6 +50,35 @@ pub struct TerminalToolInput {
|
|||
pub cd: String,
|
||||
/// Optional maximum runtime (in milliseconds). If exceeded, the running terminal task is killed.
|
||||
pub timeout_ms: Option<u64>,
|
||||
/// Request network access for this command.
|
||||
///
|
||||
/// Only meaningful when the system prompt's "Terminal sandbox" section
|
||||
/// is present — ignored otherwise. By default sandboxed commands
|
||||
/// cannot make outbound network connections; set this to `true` only
|
||||
/// when the command needs network access. The user will be prompted
|
||||
/// to approve before the command runs.
|
||||
#[serde(default)]
|
||||
pub allow_network: Option<bool>,
|
||||
/// Request unrestricted filesystem-write access for this command.
|
||||
///
|
||||
/// Only meaningful when the system prompt's "Terminal sandbox" section
|
||||
/// is present — ignored otherwise. By default sandboxed commands can
|
||||
/// only write to the project worktree directories and a per-command
|
||||
/// temporary directory; set this to `true` only when the command
|
||||
/// needs to write elsewhere. The user will be prompted to approve
|
||||
/// before the command runs.
|
||||
#[serde(default)]
|
||||
pub allow_fs_write: Option<bool>,
|
||||
/// Request to run this command outside the sandbox entirely.
|
||||
///
|
||||
/// Only meaningful when the system prompt's "Terminal sandbox" section
|
||||
/// is present — ignored otherwise. Prefer `allow_network: true` or
|
||||
/// `allow_fs_write: true` when one of those is enough. Set this to
|
||||
/// `true` ONLY when the command needs behavior that the sandbox can't
|
||||
/// grant on a per-permission basis. The user will be prompted to
|
||||
/// approve before the command runs without sandbox restrictions.
|
||||
#[serde(default)]
|
||||
pub unsandboxed: Option<bool>,
|
||||
}
|
||||
|
||||
pub struct TerminalTool {
|
||||
|
|
@ -96,24 +126,100 @@ impl AgentTool for TerminalTool {
|
|||
cx.spawn(async move |cx| {
|
||||
let input = input.recv().await.map_err(|e| e.to_string())?;
|
||||
|
||||
let (working_dir, authorize) = cx.update(|cx| {
|
||||
let (working_dir, authorize, sandboxing) = cx.update(|cx| {
|
||||
let working_dir =
|
||||
working_dir(&input, &self.project, cx).map_err(|err| err.to_string())?;
|
||||
let context =
|
||||
crate::ToolPermissionContext::new(Self::NAME, vec![input.command.clone()]);
|
||||
let authorize =
|
||||
event_stream.authorize(self.initial_title(Ok(input.clone()), cx), context, cx);
|
||||
Result::<_, String>::Ok((working_dir, authorize))
|
||||
let sandboxing = sandboxing_enabled(cx);
|
||||
Result::<_, String>::Ok((working_dir, authorize, sandboxing))
|
||||
})?;
|
||||
|
||||
authorize.await.map_err(|e| e.to_string())?;
|
||||
|
||||
// Sandbox flags only do anything when sandboxing is on. When
|
||||
// off, we treat them as `None` so the model can't surreptitiously
|
||||
// change runtime behavior by setting flags described as a no-op
|
||||
// in the system prompt.
|
||||
let want_network = sandboxing && input.allow_network == Some(true);
|
||||
let want_fs_write = sandboxing && input.allow_fs_write == Some(true);
|
||||
let want_unsandboxed = sandboxing && input.unsandboxed == Some(true);
|
||||
|
||||
// `unsandboxed: true` bypasses the wrap entirely; per-permission
|
||||
// requests are only meaningful when the command is still being
|
||||
// sandboxed.
|
||||
let escalate = !want_unsandboxed && (want_network || want_fs_write);
|
||||
|
||||
if want_unsandboxed || escalate {
|
||||
let title = sandbox_approval_title(want_network, want_fs_write, want_unsandboxed);
|
||||
let approve = cx.update(|cx| {
|
||||
let context = crate::ToolPermissionContext::new(
|
||||
Self::NAME,
|
||||
vec![input.command.clone()],
|
||||
);
|
||||
// Sandbox escalations always prompt, even if the user
|
||||
// has `always_allow` rules for this command — the
|
||||
// escalation is a stronger trust boundary than the
|
||||
// baseline command approval.
|
||||
event_stream.authorize_always_prompt(title, context, cx)
|
||||
});
|
||||
if let Err(error) = approve.await {
|
||||
return Ok(if want_unsandboxed {
|
||||
format!(
|
||||
"Command cancelled: user denied permission to run outside the sandbox ({error})."
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"Command cancelled: user denied the requested sandbox permissions ({error})."
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// The per-thread scratch directory (and the `$TMPDIR`/`TMP`/
|
||||
// `TEMP` environment variables pointing at it) is provisioned by
|
||||
// the thread environment in `create_terminal`, which also adds it
|
||||
// to the sandbox's writable scope. We must not set `$TMPDIR` here:
|
||||
// the environment overrides it with the per-thread directory, so a
|
||||
// per-command directory set here would never be the `$TMPDIR` the
|
||||
// command actually sees and would be left out of the writable
|
||||
// scope, breaking writes into `$TMPDIR`.
|
||||
let extra_env = Vec::new();
|
||||
|
||||
// Build the writable scope from the project's worktrees. The
|
||||
// per-thread temp directory is appended by the thread environment
|
||||
// (which owns it and points `$TMPDIR` at it). Crucially we do
|
||||
// *not* include the resolved `cd` working directory — that's
|
||||
// model-controlled, and using it as the writable scope would
|
||||
// let the model widen its own write permissions outside the
|
||||
// project.
|
||||
let sandbox_wrap = if sandboxing && !want_unsandboxed {
|
||||
let writable_paths: Vec<PathBuf> = cx.update(|cx| {
|
||||
self.project
|
||||
.read(cx)
|
||||
.worktrees(cx)
|
||||
.map(|w| w.read(cx).abs_path().to_path_buf())
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
Some(acp_thread::SandboxWrap {
|
||||
writable_paths,
|
||||
allow_network: want_network,
|
||||
allow_fs_write: want_fs_write,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let terminal = self
|
||||
.environment
|
||||
.create_terminal(
|
||||
input.command.clone(),
|
||||
extra_env,
|
||||
working_dir,
|
||||
Some(COMMAND_OUTPUT_LIMIT),
|
||||
sandbox_wrap,
|
||||
cx,
|
||||
)
|
||||
.await
|
||||
|
|
@ -182,6 +288,29 @@ impl AgentTool for TerminalTool {
|
|||
}
|
||||
}
|
||||
|
||||
/// User-facing title for the sandbox-escalation approval prompt.
|
||||
///
|
||||
/// `want_unsandboxed` wins over the per-permission flags because
|
||||
/// `unsandboxed: true` bypasses the per-permission machinery entirely.
|
||||
fn sandbox_approval_title(
|
||||
want_network: bool,
|
||||
want_fs_write: bool,
|
||||
want_unsandboxed: bool,
|
||||
) -> &'static str {
|
||||
if want_unsandboxed {
|
||||
"Allow this command to run outside the sandbox?"
|
||||
} else {
|
||||
match (want_network, want_fs_write) {
|
||||
(true, true) => "Allow network access and arbitrary filesystem writes?",
|
||||
(true, false) => "Allow network access?",
|
||||
(false, true) => "Allow arbitrary filesystem writes?",
|
||||
// Caller only invokes this when at least one flag is set, so
|
||||
// this fallback is unreachable in practice.
|
||||
(false, false) => "Allow this command to run?",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_content(
|
||||
output: acp::TerminalOutputResponse,
|
||||
command: &str,
|
||||
|
|
@ -310,6 +439,7 @@ mod tests {
|
|||
.to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let title = format_initial_title(Ok(input));
|
||||
|
|
@ -369,6 +499,7 @@ mod tests {
|
|||
command: cmd.to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let title = format_initial_title(Ok(input));
|
||||
|
|
@ -406,6 +537,7 @@ mod tests {
|
|||
command: "echo 'hello world'".to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let title = format_initial_title(Ok(input));
|
||||
|
|
@ -435,6 +567,7 @@ mod tests {
|
|||
command: long_command,
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let title = format_initial_title(Ok(input));
|
||||
|
|
@ -641,6 +774,7 @@ mod tests {
|
|||
command: "echo $HOME".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -708,6 +842,7 @@ mod tests {
|
|||
command: "echo $HOME".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -769,6 +904,7 @@ mod tests {
|
|||
command: "echo $(rm -rf /)".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -838,6 +974,7 @@ mod tests {
|
|||
command: "PAGER=blah git log --oneline".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -911,6 +1048,7 @@ mod tests {
|
|||
command: "PAGER=blah git log".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -1018,6 +1156,7 @@ mod tests {
|
|||
command: command.to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -1185,6 +1324,7 @@ mod tests {
|
|||
command: "echo $(whoami)".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -1257,6 +1397,7 @@ mod tests {
|
|||
command: "PAGER=other git log".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -1323,6 +1464,7 @@ mod tests {
|
|||
command: "A=1 B=2 git log".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -1400,6 +1542,7 @@ mod tests {
|
|||
command: "PAGER=\"less -R\" git log".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -1428,4 +1571,72 @@ mod tests {
|
|||
"unexpected terminal result: {result}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sandbox_approval_title_unsandboxed_wins() {
|
||||
// `unsandboxed: true` skips the sandbox entirely, so the title should
|
||||
// reflect that even when other flags are also set — they're moot.
|
||||
assert_eq!(
|
||||
sandbox_approval_title(true, true, true),
|
||||
"Allow this command to run outside the sandbox?"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox_approval_title(false, false, true),
|
||||
"Allow this command to run outside the sandbox?"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sandbox_approval_title_per_permission_flags() {
|
||||
assert_eq!(
|
||||
sandbox_approval_title(true, true, false),
|
||||
"Allow network access and arbitrary filesystem writes?"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox_approval_title(true, false, false),
|
||||
"Allow network access?"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox_approval_title(false, true, false),
|
||||
"Allow arbitrary filesystem writes?"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_input_schema_includes_sandbox_flags() {
|
||||
// The model only sees these fields when the sandboxing prompt
|
||||
// section is rendered, but they're always present in the schema so
|
||||
// input validation doesn't reject them when sent. Guard against
|
||||
// accidentally renaming or removing them.
|
||||
let schema = serde_json::to_string(&schemars::schema_for!(TerminalToolInput))
|
||||
.expect("input schema should serialize");
|
||||
assert!(
|
||||
schema.contains("allow_network"),
|
||||
"schema should advertise allow_network: {schema}"
|
||||
);
|
||||
assert!(
|
||||
schema.contains("allow_fs_write"),
|
||||
"schema should advertise allow_fs_write: {schema}"
|
||||
);
|
||||
assert!(
|
||||
schema.contains("unsandboxed"),
|
||||
"schema should advertise unsandboxed: {schema}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sandbox_flags_default_to_none_when_absent() {
|
||||
// The model is expected to omit the sandbox fields entirely on most
|
||||
// calls. Make sure deserialization doesn't reject the minimal
|
||||
// payload and that the fields default to `None` (which the tool
|
||||
// interprets as "no escalation requested").
|
||||
let input: TerminalToolInput = serde_json::from_value(serde_json::json!({
|
||||
"command": "echo hi",
|
||||
"cd": ".",
|
||||
}))
|
||||
.expect("minimal input should deserialize");
|
||||
assert_eq!(input.allow_network, None);
|
||||
assert_eq!(input.allow_fs_write, None);
|
||||
assert_eq!(input.unsandboxed, None);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,9 +9,9 @@ use fs::Fs;
|
|||
use gpui::{App, Entity, Task, WeakEntity};
|
||||
use project::{Project, ProjectPath};
|
||||
use settings::Settings;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use util::paths::component_matches_ignore_ascii_case;
|
||||
use util::{normalize_path, paths::component_matches_ignore_ascii_case};
|
||||
|
||||
pub enum SensitiveSettingsKind {
|
||||
Local,
|
||||
|
|
@ -116,25 +116,24 @@ fn is_within_any_worktree(canonical_path: &Path, canonical_worktree_roots: &[Pat
|
|||
.any(|root| canonical_path.starts_with(root))
|
||||
}
|
||||
|
||||
/// If `path` is an absolute path under the global skills directory
|
||||
/// (`~/.agents/skills`), return the canonicalized absolute path. Returns
|
||||
/// `None` for any path that resolves outside the global skills tree, for
|
||||
/// relative paths, or if the skills directory itself can't be canonicalized
|
||||
/// (fail closed — better to refuse access than to compare against a
|
||||
/// non-canonical path).
|
||||
/// If `path` names `~/.agents/skills` or one of its descendants, return the
|
||||
/// canonicalized absolute path. Returns `None` for any path that resolves
|
||||
/// outside the global skills tree, for relative paths that don't start with
|
||||
/// `~`, or if the skills directory itself can't be canonicalized (fail closed
|
||||
/// — better to refuse access than to compare against a non-canonical path).
|
||||
///
|
||||
/// This is the gate that lets `read_file` / `list_directory` reach into the
|
||||
/// global skills directory — which lives outside any worktree — without
|
||||
/// also opening up arbitrary external paths.
|
||||
pub async fn resolve_global_skill_path(path: &Path, fs: &dyn Fs) -> Option<PathBuf> {
|
||||
if !path.is_absolute() {
|
||||
return None;
|
||||
}
|
||||
let normalized_path = resolve_lexical_global_skill_path(path)?;
|
||||
|
||||
// Canonicalize both sides so symlinks and `..` segments can't sneak the
|
||||
// path out of the skills tree (and so different but equivalent path
|
||||
// representations match).
|
||||
let canonical_path = fs.canonicalize(path).await.ok()?;
|
||||
// Canonicalize both sides so symlinks can't sneak the path out of the
|
||||
// skills tree (and so different but equivalent path representations
|
||||
// match). The lexical check above intentionally runs first, so a
|
||||
// symlinked `~/.agents/skills` root can't broaden the allowlist to every
|
||||
// path under the symlink target.
|
||||
let canonical_path = fs.canonicalize(&normalized_path).await.ok()?;
|
||||
let canonical_skills_dir = canonical_global_skills_dir(fs).await?;
|
||||
|
||||
if canonical_path.starts_with(&canonical_skills_dir) {
|
||||
|
|
@ -144,6 +143,112 @@ pub async fn resolve_global_skill_path(path: &Path, fs: &dyn Fs) -> Option<PathB
|
|||
}
|
||||
}
|
||||
|
||||
fn expand_home_prefix(path: &Path) -> Option<PathBuf> {
|
||||
if path.is_absolute() {
|
||||
return Some(path.to_path_buf());
|
||||
}
|
||||
|
||||
let mut components = path.components();
|
||||
let first_component = components.next()?;
|
||||
if !matches!(first_component, Component::Normal(component) if component == "~") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut expanded = paths::home_dir().clone();
|
||||
for component in components {
|
||||
match component {
|
||||
Component::Normal(component) => expanded.push(component),
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => expanded.push(".."),
|
||||
Component::Prefix(_) | Component::RootDir => return None,
|
||||
}
|
||||
}
|
||||
Some(expanded)
|
||||
}
|
||||
|
||||
fn expand_and_normalize_absolute_path(path: &Path) -> Option<PathBuf> {
|
||||
let expanded_path = expand_home_prefix(path)?;
|
||||
let normalized_path = normalize_path(&expanded_path);
|
||||
normalized_path.is_absolute().then_some(normalized_path)
|
||||
}
|
||||
|
||||
fn resolve_lexical_global_skill_path(path: &Path) -> Option<PathBuf> {
|
||||
let normalized_path = expand_and_normalize_absolute_path(path)?;
|
||||
let normalized_skills_dir = normalize_path(&agent_skills::global_skills_dir());
|
||||
|
||||
normalized_path
|
||||
.starts_with(&normalized_skills_dir)
|
||||
.then_some(normalized_path)
|
||||
}
|
||||
|
||||
/// If `path` names `~/.agents/skills` or one of its descendants, return a
|
||||
/// canonical absolute path for it. Unlike [`resolve_global_skill_path`], the
|
||||
/// target path may or may not exist on disk yet — the caller decides whether
|
||||
/// to read, write, or create it. Returns `None` for any other path, including
|
||||
/// siblings of the global skills tree or paths that would escape it with `..`
|
||||
/// or symlinks.
|
||||
pub async fn resolve_creatable_global_skill_path(path: &Path, fs: &dyn Fs) -> Option<PathBuf> {
|
||||
let normalized_path = resolve_lexical_global_skill_path(path)?;
|
||||
let canonical_path = canonicalize_with_ancestors(&normalized_path, fs).await?;
|
||||
let canonical_skills_dir = canonical_global_skills_dir(fs).await?;
|
||||
|
||||
if canonical_path.starts_with(&canonical_skills_dir) {
|
||||
Some(canonical_path)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn is_strict_descendant(path: &Path, ancestor: &Path) -> bool {
|
||||
path != ancestor && path.starts_with(ancestor)
|
||||
}
|
||||
|
||||
/// Returns whether `path` resolves to the global agent skills directory itself.
|
||||
///
|
||||
/// This is used by destructive tools to reject operations targeting the root
|
||||
/// `~/.agents/skills` directory while still allowing operations on individual
|
||||
/// skills or resources beneath it.
|
||||
pub async fn resolves_to_global_skills_dir(path: &Path, fs: &dyn Fs) -> bool {
|
||||
let Some(normalized_path) = resolve_lexical_global_skill_path(path) else {
|
||||
return false;
|
||||
};
|
||||
let Some(canonical_path) = canonicalize_with_ancestors(&normalized_path, fs).await else {
|
||||
return false;
|
||||
};
|
||||
let Some(canonical_skills_dir) = canonical_global_skills_dir(fs).await else {
|
||||
return false;
|
||||
};
|
||||
|
||||
canonical_path == canonical_skills_dir
|
||||
}
|
||||
|
||||
/// Filters a previously-resolved global skills path so that callers which
|
||||
/// must never act on `~/.agents/skills` itself (move, delete) only see paths
|
||||
/// that point strictly below the skills root.
|
||||
async fn restrict_to_skill_descendant(
|
||||
canonical_path: Option<PathBuf>,
|
||||
fs: &dyn Fs,
|
||||
) -> Option<PathBuf> {
|
||||
let canonical_path = canonical_path?;
|
||||
let canonical_skills_dir = canonical_global_skills_dir(fs).await?;
|
||||
is_strict_descendant(&canonical_path, &canonical_skills_dir).then_some(canonical_path)
|
||||
}
|
||||
|
||||
/// Like [`resolve_global_skill_path`], but only succeeds for paths strictly
|
||||
/// below `~/.agents/skills`, not the skills directory itself.
|
||||
pub async fn resolve_global_skill_descendant_path(path: &Path, fs: &dyn Fs) -> Option<PathBuf> {
|
||||
restrict_to_skill_descendant(resolve_global_skill_path(path, fs).await, fs).await
|
||||
}
|
||||
|
||||
/// Like [`resolve_creatable_global_skill_path`], but only succeeds for paths
|
||||
/// strictly below `~/.agents/skills`, not the skills directory itself.
|
||||
pub async fn resolve_creatable_global_skill_descendant_path(
|
||||
path: &Path,
|
||||
fs: &dyn Fs,
|
||||
) -> Option<PathBuf> {
|
||||
restrict_to_skill_descendant(resolve_creatable_global_skill_path(path, fs).await, fs).await
|
||||
}
|
||||
|
||||
/// Returns the kind of sensitive settings or agent skills location this path targets, if any:
|
||||
/// either inside a `.zed/` local-settings directory, inside `.agents/skills/`, or inside
|
||||
/// the global config dir.
|
||||
|
|
@ -773,6 +878,189 @@ mod tests {
|
|||
roots
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_resolve_creatable_global_skill_path_allows_tilde_path(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill");
|
||||
let expected_path = agent_skills::global_skills_dir().join("my-skill");
|
||||
|
||||
let resolved = resolve_creatable_global_skill_path(&input_path, fs.as_ref())
|
||||
.await
|
||||
.expect("global skill path should resolve");
|
||||
|
||||
assert_eq!(resolved, expected_path);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_resolve_global_skill_path_allows_tilde_path(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
let skill_file = agent_skills::global_skills_dir()
|
||||
.join("my-skill")
|
||||
.join("SKILL.md");
|
||||
fs.insert_tree(
|
||||
skill_file
|
||||
.parent()
|
||||
.expect("skill file should have a parent"),
|
||||
json!({ "SKILL.md": "---\nname: my-skill\ndescription: test\n---" }),
|
||||
)
|
||||
.await;
|
||||
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.join("SKILL.md");
|
||||
let resolved = resolve_global_skill_path(&input_path, fs.as_ref())
|
||||
.await
|
||||
.expect("global skill file should resolve");
|
||||
|
||||
assert_eq!(resolved, skill_file);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_resolve_creatable_global_skill_path_rejects_other_home_paths(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
let sibling_path = PathBuf::from("~").join(".agents").join("not-skills");
|
||||
let escaped_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("..")
|
||||
.join("not-skills");
|
||||
|
||||
assert!(
|
||||
resolve_creatable_global_skill_path(&sibling_path, fs.as_ref())
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
resolve_creatable_global_skill_path(&escaped_path, fs.as_ref())
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_resolve_creatable_global_skill_path_rejects_symlink_escape(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
let skills_dir = agent_skills::global_skills_dir();
|
||||
fs.create_dir(&skills_dir)
|
||||
.await
|
||||
.expect("global skills directory should be created");
|
||||
fs.create_dir(path!("/external").as_ref())
|
||||
.await
|
||||
.expect("external directory should be created");
|
||||
fs.create_symlink(&skills_dir.join("link"), PathBuf::from(path!("/external")))
|
||||
.await
|
||||
.expect("symlink should be created");
|
||||
|
||||
let escaped_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("link")
|
||||
.join("new-dir");
|
||||
|
||||
assert!(
|
||||
resolve_creatable_global_skill_path(&escaped_path, fs.as_ref())
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_global_skill_path_resolvers_reject_absolute_paths_when_skills_dir_is_symlink_to_root(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(paths::home_dir(), json!({ ".agents": {} }))
|
||||
.await;
|
||||
fs.insert_tree(path!("/tmp"), json!({ "outside.txt": "outside" }))
|
||||
.await;
|
||||
|
||||
let skills_dir = agent_skills::global_skills_dir();
|
||||
fs.create_symlink(&skills_dir, PathBuf::from(path!("/")))
|
||||
.await
|
||||
.expect("global skills directory should be symlinked to root");
|
||||
|
||||
let outside_path = PathBuf::from(path!("/tmp/outside.txt"));
|
||||
assert!(
|
||||
resolve_global_skill_path(&outside_path, fs.as_ref())
|
||||
.await
|
||||
.is_none(),
|
||||
"existing absolute paths outside the lexical global skills tree should not resolve",
|
||||
);
|
||||
assert!(
|
||||
resolve_creatable_global_skill_path(&outside_path, fs.as_ref())
|
||||
.await
|
||||
.is_none(),
|
||||
"creatable absolute paths outside the lexical global skills tree should not resolve",
|
||||
);
|
||||
|
||||
let traversed_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("..")
|
||||
.join("outside");
|
||||
assert!(
|
||||
resolve_creatable_global_skill_path(&traversed_path, fs.as_ref())
|
||||
.await
|
||||
.is_none(),
|
||||
"paths that normalize outside the lexical global skills tree should not resolve",
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_global_skill_path_resolvers_reject_absolute_paths_when_skills_dir_is_symlink_to_home(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(
|
||||
paths::home_dir(),
|
||||
json!({
|
||||
".agents": {},
|
||||
"outside.txt": "outside",
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
let skills_dir = agent_skills::global_skills_dir();
|
||||
fs.create_symlink(&skills_dir, paths::home_dir().clone())
|
||||
.await
|
||||
.expect("global skills directory should be symlinked to home");
|
||||
|
||||
let outside_path = paths::home_dir().join("outside.txt");
|
||||
assert!(
|
||||
resolve_global_skill_path(&outside_path, fs.as_ref())
|
||||
.await
|
||||
.is_none(),
|
||||
"existing absolute paths outside the lexical global skills tree should not resolve",
|
||||
);
|
||||
assert!(
|
||||
resolve_creatable_global_skill_path(&outside_path, fs.as_ref())
|
||||
.await
|
||||
.is_none(),
|
||||
"creatable absolute paths outside the lexical global skills tree should not resolve",
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_resolve_project_path_safe_for_normal_files(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
|
|
|||
140
crates/agent/src/tools/update_title_tool.rs
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
use crate::{AgentTool, Thread, ToolCallEventStream, ToolInput};
|
||||
use agent_client_protocol::schema as acp;
|
||||
use gpui::{App, SharedString, Task, WeakEntity};
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
const MAX_TITLE_LEN: usize = 200;
|
||||
|
||||
/// Updates the current session title.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
|
||||
pub struct UpdateTitleToolInput {
|
||||
/// A concise, human-readable title for the current session.
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
pub struct UpdateTitleTool {
|
||||
thread: WeakEntity<Thread>,
|
||||
}
|
||||
|
||||
impl UpdateTitleTool {
|
||||
pub fn new(thread: WeakEntity<Thread>) -> Self {
|
||||
Self { thread }
|
||||
}
|
||||
|
||||
pub(crate) fn title_for_input(
|
||||
input: Result<UpdateTitleToolInput, serde_json::Value>,
|
||||
) -> SharedString {
|
||||
let Ok(input) = input else {
|
||||
return "Update title".into();
|
||||
};
|
||||
let Ok(title) = normalize_title(&input.title) else {
|
||||
return "Update title".into();
|
||||
};
|
||||
format!("Update title: {title}").into()
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentTool for UpdateTitleTool {
|
||||
type Input = UpdateTitleToolInput;
|
||||
type Output = String;
|
||||
|
||||
const NAME: &'static str = "update_title";
|
||||
|
||||
fn kind() -> acp::ToolKind {
|
||||
acp::ToolKind::Think
|
||||
}
|
||||
|
||||
fn initial_title(
|
||||
&self,
|
||||
input: Result<Self::Input, serde_json::Value>,
|
||||
_cx: &mut App,
|
||||
) -> SharedString {
|
||||
Self::title_for_input(input)
|
||||
}
|
||||
|
||||
fn run(
|
||||
self: Arc<Self>,
|
||||
input: ToolInput<Self::Input>,
|
||||
_event_stream: ToolCallEventStream,
|
||||
cx: &mut App,
|
||||
) -> Task<Result<Self::Output, Self::Output>> {
|
||||
let thread = self.thread.clone();
|
||||
cx.spawn(async move |cx| {
|
||||
let input = input.recv().await.map_err(|error| error.to_string())?;
|
||||
let title = normalize_title(&input.title)?;
|
||||
|
||||
thread
|
||||
.update(cx, |thread, cx| {
|
||||
thread.set_title(title.into(), cx);
|
||||
})
|
||||
.map_err(|error| error.to_string())?;
|
||||
|
||||
Ok("Session title updated".to_string())
|
||||
})
|
||||
}
|
||||
|
||||
fn replay(
|
||||
&self,
|
||||
input: Self::Input,
|
||||
_output: Self::Output,
|
||||
event_stream: ToolCallEventStream,
|
||||
cx: &mut App,
|
||||
) -> anyhow::Result<()> {
|
||||
let title = self.initial_title(Ok(input), cx).to_string();
|
||||
event_stream.update_fields(acp::ToolCallUpdateFields::new().title(title));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_title(title: &str) -> Result<String, String> {
|
||||
let title = title.lines().next().unwrap_or("").trim();
|
||||
if title.is_empty() {
|
||||
return Err("Title cannot be empty".to_string());
|
||||
}
|
||||
Ok(util::truncate_and_trailoff(title, MAX_TITLE_LEN))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gpui::TestAppContext;
|
||||
|
||||
#[test]
|
||||
fn test_normalize_title() {
|
||||
assert_eq!(
|
||||
normalize_title(" Title from model\nignored").unwrap(),
|
||||
"Title from model"
|
||||
);
|
||||
assert!(normalize_title(" \nignored").is_err());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_initial_title(cx: &mut TestAppContext) {
|
||||
let tool = UpdateTitleTool::new(WeakEntity::new_invalid());
|
||||
|
||||
let title = cx.update(|cx| {
|
||||
tool.initial_title(
|
||||
Ok(UpdateTitleToolInput {
|
||||
title: "Investigate title updates".to_string(),
|
||||
}),
|
||||
cx,
|
||||
)
|
||||
});
|
||||
assert_eq!(
|
||||
title,
|
||||
SharedString::from("Update title: Investigate title updates")
|
||||
);
|
||||
|
||||
let title = cx.update(|cx| {
|
||||
tool.initial_title(
|
||||
Ok(UpdateTitleToolInput {
|
||||
title: " ".to_string(),
|
||||
}),
|
||||
cx,
|
||||
)
|
||||
});
|
||||
assert_eq!(title, SharedString::from("Update title"));
|
||||
}
|
||||
}
|
||||
|
|
@ -22,11 +22,13 @@ const DEFAULT_UI_TEXT: &str = "Writing file";
|
|||
/// To make granular edits to an existing file, prefer the `edit_file` tool instead.
|
||||
///
|
||||
/// Before using this tool, verify the directory path is correct (only applicable when creating new files). Use the `list_directory` tool to verify the parent directory exists and is the correct location
|
||||
///
|
||||
/// The only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct WriteFileToolInput {
|
||||
/// The full path of the file to create or overwrite in the project.
|
||||
///
|
||||
/// WARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories.
|
||||
/// WARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories, unless it's a global agent skill under `~/.agents/skills`.
|
||||
///
|
||||
/// The following examples assume we have two root directories in the project:
|
||||
/// - /a/b/backend
|
||||
|
|
@ -41,6 +43,10 @@ pub struct WriteFileToolInput {
|
|||
/// <example>
|
||||
/// `frontend/db.js`
|
||||
/// </example>
|
||||
///
|
||||
/// <example>
|
||||
/// To create or overwrite a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.
|
||||
/// </example>
|
||||
pub path: PathBuf,
|
||||
|
||||
/// The entire content for the file.
|
||||
|
|
@ -237,6 +243,7 @@ impl AgentTool for WriteFileTool {
|
|||
run_session(
|
||||
self.process_streaming_writes(&mut input, &event_stream, cx)
|
||||
.await,
|
||||
&event_stream,
|
||||
cx,
|
||||
)
|
||||
.await
|
||||
|
|
@ -272,7 +279,7 @@ mod tests {
|
|||
use prompt_store::ProjectContext;
|
||||
use serde_json::json;
|
||||
use settings::{Settings, SettingsStore};
|
||||
use std::sync::Arc;
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
use util::path;
|
||||
use util::rel_path::{RelPath, rel_path};
|
||||
|
||||
|
|
@ -327,6 +334,62 @@ mod tests {
|
|||
assert_eq!(*old_text, "old content");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_streaming_write_global_skill_file(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = project::FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root"), json!({})).await;
|
||||
let skill_dir = agent_skills::global_skills_dir().join("my-skill");
|
||||
fs.insert_tree(&skill_dir, json!({})).await;
|
||||
let (write_tool, _project, _action_log, fs, _thread) =
|
||||
setup_test_with_fs(cx, fs, &[path!("/root").as_ref()]).await;
|
||||
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.join("SKILL.md");
|
||||
let skill_file = agent_skills::global_skills_dir()
|
||||
.join("my-skill")
|
||||
.join("SKILL.md");
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
write_tool.clone().run(
|
||||
ToolInput::resolved(WriteFileToolInput {
|
||||
path: input_path,
|
||||
content: "# My Skill\n".into(),
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
event_rx.expect_update_fields().await;
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let EditSessionOutput::Success { new_text, .. } = task.await.unwrap() else {
|
||||
panic!("expected success");
|
||||
};
|
||||
assert_eq!(new_text, "# My Skill\n");
|
||||
assert_eq!(
|
||||
fs.load(&skill_file).await.unwrap().replace("\r\n", "\n"),
|
||||
"# My Skill\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_streaming_path_completeness_heuristic(cx: &mut TestAppContext) {
|
||||
let (write_tool, _project, _action_log, _fs, _thread) =
|
||||
|
|
@ -998,7 +1061,8 @@ mod tests {
|
|||
|
||||
cx.run_until_parked();
|
||||
|
||||
let changed = action_log.read_with(cx, |log, cx| log.changed_buffers(cx));
|
||||
let changed =
|
||||
action_log.read_with(cx, |log, cx| log.changed_buffers(cx).collect::<Vec<_>>());
|
||||
assert!(
|
||||
!changed.is_empty(),
|
||||
"action_log.changed_buffers() should be non-empty after streaming write, \
|
||||
|
|
@ -1070,7 +1134,8 @@ mod tests {
|
|||
);
|
||||
|
||||
// Reject all edits — this should delete the newly created file
|
||||
let changed = action_log.read_with(cx, |log, cx| log.changed_buffers(cx));
|
||||
let changed =
|
||||
action_log.read_with(cx, |log, cx| log.changed_buffers(cx).collect::<Vec<_>>());
|
||||
assert!(
|
||||
!changed.is_empty(),
|
||||
"action_log should track the created file as changed"
|
||||
|
|
|
|||
|
|
@ -15,10 +15,13 @@ use futures::channel::mpsc;
|
|||
use futures::future::Shared;
|
||||
use futures::io::BufReader;
|
||||
use futures::{AsyncBufReadExt as _, Future, FutureExt as _, StreamExt as _};
|
||||
use project::agent_server_store::{AgentServerCommand, AgentServerStore};
|
||||
use project::agent_server_store::{
|
||||
AgentServerCommand, AgentServerStore, AllAgentServersSettings, CustomAgentServerSettings,
|
||||
};
|
||||
use project::{AgentId, Project};
|
||||
use remote::remote_client::Interactive;
|
||||
use serde::Deserialize;
|
||||
use settings::SettingsStore;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{ExitStatus, Stdio};
|
||||
use std::rc::Rc;
|
||||
|
|
@ -32,7 +35,7 @@ use util::path_list::PathList;
|
|||
use util::process::Child;
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
use gpui::{App, AppContext as _, AsyncApp, Entity, SharedString, Task, WeakEntity};
|
||||
use gpui::{App, AppContext as _, AsyncApp, Entity, SharedString, Subscription, Task, WeakEntity};
|
||||
|
||||
use acp_thread::{AcpThread, AuthRequired, LoadError, TerminalProviderEvent};
|
||||
use terminal::TerminalBuilder;
|
||||
|
|
@ -421,18 +424,101 @@ pub struct AcpConnection {
|
|||
auth_methods: Vec<acp::AuthMethod>,
|
||||
agent_server_store: WeakEntity<AgentServerStore>,
|
||||
agent_capabilities: acp::AgentCapabilities,
|
||||
default_mode: Option<acp::SessionModeId>,
|
||||
default_model: Option<acp::ModelId>,
|
||||
default_config_options: HashMap<String, String>,
|
||||
defaults: AcpConnectionDefaults,
|
||||
child: Option<Child>,
|
||||
session_list: Option<Rc<AcpSessionList>>,
|
||||
debug_log: AcpDebugLog,
|
||||
_settings_subscription: Subscription,
|
||||
_io_task: Task<()>,
|
||||
_dispatch_task: Task<()>,
|
||||
_wait_task: Task<Result<()>>,
|
||||
_stderr_task: Task<Result<()>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct AcpConnectionDefaults {
|
||||
mode: Rc<RefCell<Option<acp::SessionModeId>>>,
|
||||
model: Rc<RefCell<Option<acp::ModelId>>>,
|
||||
config_options: Rc<RefCell<HashMap<String, String>>>,
|
||||
}
|
||||
|
||||
impl AcpConnectionDefaults {
|
||||
fn new(
|
||||
mode: Option<acp::SessionModeId>,
|
||||
model: Option<acp::ModelId>,
|
||||
config_options: HashMap<String, String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
mode: Rc::new(RefCell::new(mode)),
|
||||
model: Rc::new(RefCell::new(model)),
|
||||
config_options: Rc::new(RefCell::new(config_options)),
|
||||
}
|
||||
}
|
||||
|
||||
fn mode(&self) -> Option<acp::SessionModeId> {
|
||||
self.mode.borrow().clone()
|
||||
}
|
||||
|
||||
fn model(&self) -> Option<acp::ModelId> {
|
||||
self.model.borrow().clone()
|
||||
}
|
||||
|
||||
fn config_option(&self, config_id: &str) -> Option<String> {
|
||||
self.config_options.borrow().get(config_id).cloned()
|
||||
}
|
||||
|
||||
fn set(
|
||||
&self,
|
||||
mode: Option<acp::SessionModeId>,
|
||||
model: Option<acp::ModelId>,
|
||||
config_options: HashMap<String, String>,
|
||||
) {
|
||||
*self.mode.borrow_mut() = mode;
|
||||
*self.model.borrow_mut() = model;
|
||||
*self.config_options.borrow_mut() = config_options;
|
||||
}
|
||||
|
||||
fn refresh_from_settings(&self, agent_id: &AgentId, cx: &App) {
|
||||
let Some(settings_store) = cx.try_global::<SettingsStore>() else {
|
||||
self.set(None, None, HashMap::default());
|
||||
return;
|
||||
};
|
||||
let settings = settings_store.get::<AllAgentServersSettings>(None);
|
||||
let Some(agent_settings) = settings.get(agent_id.as_ref()) else {
|
||||
self.set(None, None, HashMap::default());
|
||||
return;
|
||||
};
|
||||
|
||||
let default_config_options = match agent_settings {
|
||||
CustomAgentServerSettings::Custom {
|
||||
default_config_options,
|
||||
..
|
||||
}
|
||||
| CustomAgentServerSettings::Registry {
|
||||
default_config_options,
|
||||
..
|
||||
} => default_config_options.clone(),
|
||||
};
|
||||
self.set(
|
||||
agent_settings.default_mode().map(acp::SessionModeId::new),
|
||||
agent_settings.default_model().map(acp::ModelId::new),
|
||||
default_config_options,
|
||||
);
|
||||
}
|
||||
|
||||
fn observe_settings(&self, agent_id: AgentId, cx: &mut App) -> Subscription {
|
||||
if cx.try_global::<SettingsStore>().is_none() {
|
||||
return Subscription::new(|| {});
|
||||
}
|
||||
|
||||
self.refresh_from_settings(&agent_id, cx);
|
||||
let defaults = self.clone();
|
||||
cx.observe_global::<SettingsStore>(move |cx| {
|
||||
defaults.refresh_from_settings(&agent_id, cx);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct PendingAcpSession {
|
||||
task: Shared<Task<Result<Entity<AcpThread>, Arc<anyhow::Error>>>>,
|
||||
ref_count: usize,
|
||||
|
|
@ -509,7 +595,6 @@ impl AgentSessionList for AcpSessionList {
|
|||
cx: &mut App,
|
||||
) -> Task<Result<AgentSessionListResponse>> {
|
||||
let conn = self.connection.clone();
|
||||
let include_additional_directories = cx.has_flag::<AcpBetaFeatureFlag>();
|
||||
cx.foreground_executor().spawn(async move {
|
||||
let acp_request = acp::ListSessionsRequest::new()
|
||||
.cwd(request.cwd)
|
||||
|
|
@ -525,11 +610,7 @@ impl AgentSessionList for AcpSessionList {
|
|||
session_id: s.session_id,
|
||||
work_dirs: Some(work_dirs_from_session_info(
|
||||
s.cwd,
|
||||
if include_additional_directories {
|
||||
s.additional_directories
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
s.additional_directories,
|
||||
)),
|
||||
title: s.title.map(Into::into),
|
||||
updated_at: s.updated_at.and_then(|date_str| {
|
||||
|
|
@ -1001,6 +1082,14 @@ impl AcpConnection {
|
|||
} else {
|
||||
response.auth_methods
|
||||
};
|
||||
let defaults =
|
||||
AcpConnectionDefaults::new(default_mode, default_model, default_config_options);
|
||||
let settings_subscription = cx.update({
|
||||
let agent_id = agent_id.clone();
|
||||
let defaults = defaults.clone();
|
||||
move |cx| defaults.observe_settings(agent_id, cx)
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
id: agent_id,
|
||||
auth_methods,
|
||||
|
|
@ -1011,11 +1100,10 @@ impl AcpConnection {
|
|||
sessions,
|
||||
pending_sessions: Rc::new(RefCell::new(HashMap::default())),
|
||||
agent_capabilities: response.agent_capabilities,
|
||||
default_mode,
|
||||
default_model,
|
||||
default_config_options,
|
||||
defaults,
|
||||
session_list,
|
||||
debug_log,
|
||||
_settings_subscription: settings_subscription,
|
||||
_io_task: io_task,
|
||||
_dispatch_task: dispatch_task,
|
||||
_wait_task: wait_task,
|
||||
|
|
@ -1036,10 +1124,14 @@ impl AcpConnection {
|
|||
agent_server_store: WeakEntity<AgentServerStore>,
|
||||
io_task: Task<()>,
|
||||
dispatch_task: Task<()>,
|
||||
_cx: &mut App,
|
||||
cx: &mut App,
|
||||
) -> Self {
|
||||
let agent_id = AgentId::new("test");
|
||||
let defaults = AcpConnectionDefaults::default();
|
||||
let settings_subscription = defaults.observe_settings(agent_id.clone(), cx);
|
||||
|
||||
Self {
|
||||
id: AgentId::new("test"),
|
||||
id: agent_id,
|
||||
telemetry_id: "test".into(),
|
||||
agent_version: None,
|
||||
connection,
|
||||
|
|
@ -1048,12 +1140,11 @@ impl AcpConnection {
|
|||
auth_methods: vec![],
|
||||
agent_server_store,
|
||||
agent_capabilities,
|
||||
default_mode: None,
|
||||
default_model: None,
|
||||
default_config_options: HashMap::default(),
|
||||
defaults,
|
||||
child: None,
|
||||
session_list: None,
|
||||
debug_log: AcpDebugLog::default(),
|
||||
_settings_subscription: settings_subscription,
|
||||
_io_task: io_task,
|
||||
_dispatch_task: dispatch_task,
|
||||
_wait_task: Task::ready(Ok(())),
|
||||
|
|
@ -1064,9 +1155,8 @@ impl AcpConnection {
|
|||
fn session_directories_from_work_dirs(
|
||||
&self,
|
||||
work_dirs: &PathList,
|
||||
cx: &App,
|
||||
) -> Result<SessionDirectories> {
|
||||
let supports_additional_directories = self.supports_session_additional_directories(cx);
|
||||
let supports_additional_directories = self.supports_session_additional_directories();
|
||||
session_directories_from_work_dirs(work_dirs, supports_additional_directories)
|
||||
}
|
||||
|
||||
|
|
@ -1106,7 +1196,7 @@ impl AcpConnection {
|
|||
}
|
||||
}
|
||||
|
||||
let directories = match self.session_directories_from_work_dirs(&work_dirs, cx) {
|
||||
let directories = match self.session_directories_from_work_dirs(&work_dirs) {
|
||||
Ok(directories) => directories,
|
||||
Err(error) => return Task::ready(Err(error)),
|
||||
};
|
||||
|
|
@ -1221,7 +1311,7 @@ impl AcpConnection {
|
|||
config_opts_ref
|
||||
.iter()
|
||||
.filter_map(|config_option| {
|
||||
let default_value = self.default_config_options.get(&*config_option.id.0)?;
|
||||
let default_value = self.defaults.config_option(config_option.id.0.as_ref())?;
|
||||
|
||||
let is_valid = match &config_option.kind {
|
||||
acp::SessionConfigKind::Select(select) => match &select.options {
|
||||
|
|
@ -1247,11 +1337,7 @@ impl AcpConnection {
|
|||
}
|
||||
_ => None,
|
||||
};
|
||||
Some((
|
||||
config_option.id.clone(),
|
||||
default_value.clone(),
|
||||
initial_value,
|
||||
))
|
||||
Some((config_option.id.clone(), default_value, initial_value))
|
||||
} else {
|
||||
log::warn!(
|
||||
"`{}` is not a valid value for config option `{}` in {}",
|
||||
|
|
@ -1475,7 +1561,7 @@ impl AgentConnection for AcpConnection {
|
|||
work_dirs: PathList,
|
||||
cx: &mut App,
|
||||
) -> Task<Result<Entity<AcpThread>>> {
|
||||
let directories = match self.session_directories_from_work_dirs(&work_dirs, cx) {
|
||||
let directories = match self.session_directories_from_work_dirs(&work_dirs) {
|
||||
Ok(directories) => directories,
|
||||
Err(error) => return Task::ready(Err(error)),
|
||||
};
|
||||
|
|
@ -1494,7 +1580,8 @@ impl AgentConnection for AcpConnection {
|
|||
let (modes, models, config_options) =
|
||||
config_state(response.modes, response.models, response.config_options);
|
||||
|
||||
if let Some(default_mode) = self.default_mode.clone() {
|
||||
let default_mode = self.defaults.mode();
|
||||
if let Some(default_mode) = default_mode {
|
||||
if let Some(modes) = modes.as_ref() {
|
||||
let mut modes_ref = modes.borrow_mut();
|
||||
let has_mode = modes_ref
|
||||
|
|
@ -1543,7 +1630,8 @@ impl AgentConnection for AcpConnection {
|
|||
}
|
||||
}
|
||||
|
||||
if let Some(default_model) = self.default_model.clone() {
|
||||
let default_model = self.defaults.model();
|
||||
if let Some(default_model) = default_model {
|
||||
if let Some(models) = models.as_ref() {
|
||||
let mut models_ref = models.borrow_mut();
|
||||
let has_model = models_ref
|
||||
|
|
@ -1641,13 +1729,11 @@ impl AgentConnection for AcpConnection {
|
|||
.is_some()
|
||||
}
|
||||
|
||||
fn supports_session_additional_directories(&self, cx: &App) -> bool {
|
||||
cx.has_flag::<AcpBetaFeatureFlag>()
|
||||
&& self
|
||||
.agent_capabilities
|
||||
.session_capabilities
|
||||
.additional_directories
|
||||
.is_some()
|
||||
fn supports_session_additional_directories(&self) -> bool {
|
||||
self.agent_capabilities
|
||||
.session_capabilities
|
||||
.additional_directories
|
||||
.is_some()
|
||||
}
|
||||
|
||||
fn load_session(
|
||||
|
|
@ -1853,12 +1939,12 @@ impl AgentConnection for AcpConnection {
|
|||
})
|
||||
}
|
||||
|
||||
fn supports_logout(&self, cx: &App) -> bool {
|
||||
cx.has_flag::<AcpBetaFeatureFlag>() && self.agent_capabilities.auth.logout.is_some()
|
||||
fn supports_logout(&self) -> bool {
|
||||
self.agent_capabilities.auth.logout.is_some()
|
||||
}
|
||||
|
||||
fn logout(&self, cx: &mut App) -> Task<Result<()>> {
|
||||
if !self.supports_logout(cx) {
|
||||
if !self.supports_logout() {
|
||||
return Task::ready(Err(anyhow!("Logout is not supported by this agent.")));
|
||||
}
|
||||
|
||||
|
|
@ -2201,8 +2287,8 @@ pub mod test_support {
|
|||
self.inner.supports_resume_session()
|
||||
}
|
||||
|
||||
fn supports_session_additional_directories(&self, cx: &App) -> bool {
|
||||
self.inner.supports_session_additional_directories(cx)
|
||||
fn supports_session_additional_directories(&self) -> bool {
|
||||
self.inner.supports_session_additional_directories()
|
||||
}
|
||||
|
||||
fn resume_session(
|
||||
|
|
@ -2234,8 +2320,8 @@ pub mod test_support {
|
|||
self.inner.authenticate(method, cx)
|
||||
}
|
||||
|
||||
fn supports_logout(&self, cx: &App) -> bool {
|
||||
self.inner.supports_logout(cx)
|
||||
fn supports_logout(&self) -> bool {
|
||||
self.inner.supports_logout()
|
||||
}
|
||||
|
||||
fn logout(&self, cx: &mut App) -> Task<Result<()>> {
|
||||
|
|
@ -2509,6 +2595,7 @@ mod tests {
|
|||
|
||||
use super::*;
|
||||
use gpui::UpdateGlobal as _;
|
||||
use settings::Settings as _;
|
||||
|
||||
#[test]
|
||||
fn terminal_auth_task_builds_spawn_from_prebuilt_command() {
|
||||
|
|
@ -2768,10 +2855,9 @@ mod tests {
|
|||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn session_list_includes_additional_directories_in_work_dirs_when_beta_enabled(
|
||||
async fn session_list_includes_additional_directories_in_work_dirs(
|
||||
cx: &mut gpui::TestAppContext,
|
||||
) {
|
||||
cx.update(|cx| set_acp_beta_override(cx, "on"));
|
||||
let connection = connect_session_list_test_agent(
|
||||
vec![
|
||||
acp::SessionInfo::new("session-1", "/workspace-b").additional_directories(vec![
|
||||
|
|
@ -2809,43 +2895,6 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn session_list_excludes_additional_directories_in_work_dirs_when_beta_disabled(
|
||||
cx: &mut gpui::TestAppContext,
|
||||
) {
|
||||
cx.update(|cx| set_acp_beta_override(cx, "off"));
|
||||
|
||||
let connection = connect_session_list_test_agent(
|
||||
vec![
|
||||
acp::SessionInfo::new("session-1", "/workspace-b").additional_directories(vec![
|
||||
std::path::PathBuf::from("/workspace-a"),
|
||||
std::path::PathBuf::from("/workspace-c"),
|
||||
]),
|
||||
],
|
||||
cx,
|
||||
)
|
||||
.await;
|
||||
let session_list = AcpSessionList::new(connection, false);
|
||||
|
||||
let response = cx
|
||||
.update(|cx| session_list.list_sessions(AgentSessionListRequest::default(), cx))
|
||||
.await
|
||||
.expect("session list should load");
|
||||
let session = response
|
||||
.sessions
|
||||
.first()
|
||||
.expect("session list should include the returned session");
|
||||
let work_dirs = session
|
||||
.work_dirs
|
||||
.as_ref()
|
||||
.expect("session should include work dirs");
|
||||
|
||||
assert_eq!(
|
||||
work_dirs.ordered_paths().cloned().collect::<Vec<_>>(),
|
||||
vec![std::path::PathBuf::from("/workspace-b")]
|
||||
);
|
||||
}
|
||||
|
||||
fn set_acp_beta_override(cx: &mut App, value: &str) {
|
||||
let store = settings::SettingsStore::test(cx);
|
||||
cx.set_global(store);
|
||||
|
|
@ -2905,16 +2954,12 @@ mod tests {
|
|||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn additional_directories_support_requires_beta_flag_and_agent_capability(
|
||||
async fn additional_directories_support_respects_agent_capability(
|
||||
cx: &mut gpui::TestAppContext,
|
||||
) {
|
||||
cx.update(|cx| {
|
||||
let store = settings::SettingsStore::test(cx);
|
||||
cx.set_global(store);
|
||||
settings::SettingsStore::update_global(cx, |store, _| {
|
||||
store.register_setting::<feature_flags::FeatureFlagsSettings>();
|
||||
});
|
||||
feature_flags::FeatureFlagStore::init(cx);
|
||||
});
|
||||
|
||||
let fs = fs::FakeFs::new(cx.executor());
|
||||
|
|
@ -2922,24 +2967,15 @@ mod tests {
|
|||
.await;
|
||||
let project = project::Project::test(fs, [std::path::Path::new("/a")], cx).await;
|
||||
let mut harness = test_support::connect_fake_acp_connection(project, cx).await;
|
||||
cx.update(|cx| {
|
||||
settings::SettingsStore::update_global(cx, |store, _| {
|
||||
store.register_setting::<feature_flags::FeatureFlagsSettings>();
|
||||
});
|
||||
feature_flags::FeatureFlagStore::init(cx);
|
||||
});
|
||||
|
||||
let work_dirs = PathList::new(&[
|
||||
std::path::PathBuf::from("/workspace-b"),
|
||||
std::path::PathBuf::from("/workspace-a"),
|
||||
]);
|
||||
|
||||
let missing_capability = cx
|
||||
.update(|cx| {
|
||||
harness
|
||||
.connection
|
||||
.session_directories_from_work_dirs(&work_dirs, cx)
|
||||
})
|
||||
let missing_capability = harness
|
||||
.connection
|
||||
.session_directories_from_work_dirs(&work_dirs)
|
||||
.expect("work dirs should convert");
|
||||
assert!(missing_capability.additional_directories.is_empty());
|
||||
|
||||
|
|
@ -2949,44 +2985,12 @@ mod tests {
|
|||
.session_capabilities
|
||||
.additional_directories = Some(acp::SessionAdditionalDirectoriesCapabilities::new());
|
||||
|
||||
cx.update(|cx| {
|
||||
settings::SettingsStore::update_global(cx, |store, cx| {
|
||||
store.update_user_settings(cx, |content| {
|
||||
content
|
||||
.feature_flags
|
||||
.get_or_insert_default()
|
||||
.insert("acp-beta".to_string(), "off".to_string());
|
||||
});
|
||||
});
|
||||
});
|
||||
let disabled = cx
|
||||
.update(|cx| {
|
||||
harness
|
||||
.connection
|
||||
.session_directories_from_work_dirs(&work_dirs, cx)
|
||||
})
|
||||
.expect("work dirs should convert");
|
||||
assert!(disabled.additional_directories.is_empty());
|
||||
|
||||
cx.update(|cx| {
|
||||
settings::SettingsStore::update_global(cx, |store, cx| {
|
||||
store.update_user_settings(cx, |content| {
|
||||
content
|
||||
.feature_flags
|
||||
.get_or_insert_default()
|
||||
.insert("acp-beta".to_string(), "on".to_string());
|
||||
});
|
||||
});
|
||||
});
|
||||
let enabled = cx
|
||||
.update(|cx| {
|
||||
harness
|
||||
.connection
|
||||
.session_directories_from_work_dirs(&work_dirs, cx)
|
||||
})
|
||||
let supported = harness
|
||||
.connection
|
||||
.session_directories_from_work_dirs(&work_dirs)
|
||||
.expect("work dirs should convert");
|
||||
assert_eq!(
|
||||
enabled,
|
||||
supported,
|
||||
SessionDirectories {
|
||||
cwd: std::path::PathBuf::from("/workspace-b"),
|
||||
additional_directories: vec![std::path::PathBuf::from("/workspace-a")],
|
||||
|
|
@ -3061,6 +3065,68 @@ mod tests {
|
|||
.expect("failed to receive ACP connection")
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn settings_changes_refresh_active_connection_defaults(cx: &mut gpui::TestAppContext) {
|
||||
cx.update(|cx| {
|
||||
let store = settings::SettingsStore::test(cx);
|
||||
cx.set_global(store);
|
||||
});
|
||||
|
||||
let fs = fs::FakeFs::new(cx.executor());
|
||||
fs.insert_tree("/", serde_json::json!({ "a": {} })).await;
|
||||
let project = project::Project::test(fs, [std::path::Path::new("/a")], cx).await;
|
||||
let harness = test_support::connect_fake_acp_connection(project, cx).await;
|
||||
|
||||
cx.update(|cx| {
|
||||
AllAgentServersSettings::override_global(
|
||||
AllAgentServersSettings(HashMap::from_iter([(
|
||||
"test".to_string(),
|
||||
settings::CustomAgentServerSettings::Custom {
|
||||
path: PathBuf::from("test-agent"),
|
||||
args: Vec::new(),
|
||||
env: HashMap::default(),
|
||||
default_mode: Some("manual".to_string()),
|
||||
default_model: Some("claude-sonnet-4".to_string()),
|
||||
favorite_models: Vec::new(),
|
||||
default_config_options: HashMap::from_iter([(
|
||||
"mode".to_string(),
|
||||
"manual".to_string(),
|
||||
)]),
|
||||
favorite_config_option_values: HashMap::default(),
|
||||
}
|
||||
.into(),
|
||||
)])),
|
||||
cx,
|
||||
);
|
||||
});
|
||||
cx.run_until_parked();
|
||||
|
||||
assert_eq!(
|
||||
harness.connection.defaults.mode(),
|
||||
Some(acp::SessionModeId::new("manual"))
|
||||
);
|
||||
assert_eq!(
|
||||
harness.connection.defaults.model(),
|
||||
Some(acp::ModelId::new("claude-sonnet-4"))
|
||||
);
|
||||
assert_eq!(
|
||||
harness.connection.defaults.config_option("mode").as_deref(),
|
||||
Some("manual")
|
||||
);
|
||||
|
||||
cx.update(|cx| {
|
||||
AllAgentServersSettings::override_global(
|
||||
AllAgentServersSettings(HashMap::default()),
|
||||
cx,
|
||||
);
|
||||
});
|
||||
cx.run_until_parked();
|
||||
|
||||
assert_eq!(harness.connection.defaults.mode(), None);
|
||||
assert_eq!(harness.connection.defaults.model(), None);
|
||||
assert_eq!(harness.connection.defaults.config_option("mode"), None);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn session_list_delete_sends_session_delete_when_supported(
|
||||
cx: &mut gpui::TestAppContext,
|
||||
|
|
@ -3117,28 +3183,16 @@ mod tests {
|
|||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn logout_is_gated_by_beta_flag_and_agent_capability(cx: &mut gpui::TestAppContext) {
|
||||
cx.update(|cx| {
|
||||
let store = settings::SettingsStore::test(cx);
|
||||
cx.set_global(store);
|
||||
settings::SettingsStore::update_global(cx, |store, _| {
|
||||
store.register_setting::<feature_flags::FeatureFlagsSettings>();
|
||||
});
|
||||
feature_flags::FeatureFlagStore::init(cx);
|
||||
});
|
||||
async fn logout_support_requires_agent_capability(cx: &mut gpui::TestAppContext) {
|
||||
cx.update(|cx| set_acp_beta_override(cx, "off"));
|
||||
assert!(!cx.update(|cx| cx.has_flag::<AcpBetaFeatureFlag>()));
|
||||
|
||||
let fs = fs::FakeFs::new(cx.executor());
|
||||
fs.insert_tree("/", serde_json::json!({ "a": {} })).await;
|
||||
let project = project::Project::test(fs, [std::path::Path::new("/a")], cx).await;
|
||||
let mut harness = test_support::connect_fake_acp_connection(project, cx).await;
|
||||
cx.update(|cx| {
|
||||
settings::SettingsStore::update_global(cx, |store, _| {
|
||||
store.register_setting::<feature_flags::FeatureFlagsSettings>();
|
||||
});
|
||||
feature_flags::FeatureFlagStore::init(cx);
|
||||
});
|
||||
|
||||
assert!(!cx.update(|cx| harness.connection.supports_logout(cx)));
|
||||
assert!(!harness.connection.supports_logout());
|
||||
let unsupported_logout = cx.update(|cx| harness.connection.logout(cx));
|
||||
let error = unsupported_logout
|
||||
.await
|
||||
|
|
@ -3151,35 +3205,7 @@ mod tests {
|
|||
.agent_capabilities
|
||||
.auth = acp::AgentAuthCapabilities::new().logout(acp::LogoutCapabilities::new());
|
||||
|
||||
cx.update(|cx| {
|
||||
settings::SettingsStore::update_global(cx, |store, cx| {
|
||||
store.update_user_settings(cx, |content| {
|
||||
content
|
||||
.feature_flags
|
||||
.get_or_insert_default()
|
||||
.insert("acp-beta".to_string(), "off".to_string());
|
||||
});
|
||||
});
|
||||
});
|
||||
assert!(!cx.update(|cx| harness.connection.supports_logout(cx)));
|
||||
let disabled_logout = cx.update(|cx| harness.connection.logout(cx));
|
||||
let error = disabled_logout
|
||||
.await
|
||||
.expect_err("logout should be rejected when acp-beta is disabled");
|
||||
assert_eq!(error.to_string(), "Logout is not supported by this agent.");
|
||||
assert_eq!(harness.logout_count.load(Ordering::SeqCst), 0);
|
||||
|
||||
cx.update(|cx| {
|
||||
settings::SettingsStore::update_global(cx, |store, cx| {
|
||||
store.update_user_settings(cx, |content| {
|
||||
content
|
||||
.feature_flags
|
||||
.get_or_insert_default()
|
||||
.insert("acp-beta".to_string(), "on".to_string());
|
||||
});
|
||||
});
|
||||
});
|
||||
assert!(cx.update(|cx| harness.connection.supports_logout(cx)));
|
||||
assert!(harness.connection.supports_logout());
|
||||
cx.update(|cx| harness.connection.logout(cx))
|
||||
.await
|
||||
.expect("logout should be sent when the agent advertises support");
|
||||
|
|
|
|||
|
|
@ -88,22 +88,18 @@ impl AgentServer for CustomAgentServer {
|
|||
let config_id = config_id.to_string();
|
||||
let value_id = value_id.to_string();
|
||||
|
||||
update_settings_file(fs, cx, move |settings, cx| {
|
||||
update_settings_file(fs, cx, move |settings, _cx| {
|
||||
let settings = settings
|
||||
.agent_servers
|
||||
.get_or_insert_default()
|
||||
.entry(agent_id.0.to_string())
|
||||
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
|
||||
.or_insert_with(default_settings_for_agent);
|
||||
|
||||
match settings {
|
||||
settings::CustomAgentServerSettings::Custom {
|
||||
favorite_config_option_values,
|
||||
..
|
||||
}
|
||||
| settings::CustomAgentServerSettings::Extension {
|
||||
favorite_config_option_values,
|
||||
..
|
||||
}
|
||||
| settings::CustomAgentServerSettings::Registry {
|
||||
favorite_config_option_values,
|
||||
..
|
||||
|
|
@ -129,16 +125,15 @@ impl AgentServer for CustomAgentServer {
|
|||
|
||||
fn set_default_mode(&self, mode_id: Option<acp::SessionModeId>, fs: Arc<dyn Fs>, cx: &mut App) {
|
||||
let agent_id = self.agent_id();
|
||||
update_settings_file(fs, cx, move |settings, cx| {
|
||||
update_settings_file(fs, cx, move |settings, _cx| {
|
||||
let settings = settings
|
||||
.agent_servers
|
||||
.get_or_insert_default()
|
||||
.entry(agent_id.0.to_string())
|
||||
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
|
||||
.or_insert_with(default_settings_for_agent);
|
||||
|
||||
match settings {
|
||||
settings::CustomAgentServerSettings::Custom { default_mode, .. }
|
||||
| settings::CustomAgentServerSettings::Extension { default_mode, .. }
|
||||
| settings::CustomAgentServerSettings::Registry { default_mode, .. } => {
|
||||
*default_mode = mode_id.map(|m| m.to_string());
|
||||
}
|
||||
|
|
@ -161,16 +156,15 @@ impl AgentServer for CustomAgentServer {
|
|||
|
||||
fn set_default_model(&self, model_id: Option<acp::ModelId>, fs: Arc<dyn Fs>, cx: &mut App) {
|
||||
let agent_id = self.agent_id();
|
||||
update_settings_file(fs, cx, move |settings, cx| {
|
||||
update_settings_file(fs, cx, move |settings, _cx| {
|
||||
let settings = settings
|
||||
.agent_servers
|
||||
.get_or_insert_default()
|
||||
.entry(agent_id.0.to_string())
|
||||
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
|
||||
.or_insert_with(default_settings_for_agent);
|
||||
|
||||
match settings {
|
||||
settings::CustomAgentServerSettings::Custom { default_model, .. }
|
||||
| settings::CustomAgentServerSettings::Extension { default_model, .. }
|
||||
| settings::CustomAgentServerSettings::Registry { default_model, .. } => {
|
||||
*default_model = model_id.map(|m| m.to_string());
|
||||
}
|
||||
|
|
@ -205,20 +199,17 @@ impl AgentServer for CustomAgentServer {
|
|||
cx: &App,
|
||||
) {
|
||||
let agent_id = self.agent_id();
|
||||
update_settings_file(fs, cx, move |settings, cx| {
|
||||
update_settings_file(fs, cx, move |settings, _cx| {
|
||||
let settings = settings
|
||||
.agent_servers
|
||||
.get_or_insert_default()
|
||||
.entry(agent_id.0.to_string())
|
||||
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
|
||||
.or_insert_with(default_settings_for_agent);
|
||||
|
||||
let favorite_models = match settings {
|
||||
settings::CustomAgentServerSettings::Custom {
|
||||
favorite_models, ..
|
||||
}
|
||||
| settings::CustomAgentServerSettings::Extension {
|
||||
favorite_models, ..
|
||||
}
|
||||
| settings::CustomAgentServerSettings::Registry {
|
||||
favorite_models, ..
|
||||
} => favorite_models,
|
||||
|
|
@ -258,22 +249,18 @@ impl AgentServer for CustomAgentServer {
|
|||
let agent_id = self.agent_id();
|
||||
let config_id = config_id.to_string();
|
||||
let value_id = value_id.map(|s| s.to_string());
|
||||
update_settings_file(fs, cx, move |settings, cx| {
|
||||
update_settings_file(fs, cx, move |settings, _cx| {
|
||||
let settings = settings
|
||||
.agent_servers
|
||||
.get_or_insert_default()
|
||||
.entry(agent_id.0.to_string())
|
||||
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
|
||||
.or_insert_with(default_settings_for_agent);
|
||||
|
||||
match settings {
|
||||
settings::CustomAgentServerSettings::Custom {
|
||||
default_config_options,
|
||||
..
|
||||
}
|
||||
| settings::CustomAgentServerSettings::Extension {
|
||||
default_config_options,
|
||||
..
|
||||
}
|
||||
| settings::CustomAgentServerSettings::Registry {
|
||||
default_config_options,
|
||||
..
|
||||
|
|
@ -307,10 +294,6 @@ impl AgentServer for CustomAgentServer {
|
|||
default_config_options,
|
||||
..
|
||||
}
|
||||
| project::agent_server_store::CustomAgentServerSettings::Extension {
|
||||
default_config_options,
|
||||
..
|
||||
}
|
||||
| project::agent_server_store::CustomAgentServerSettings::Registry {
|
||||
default_config_options,
|
||||
..
|
||||
|
|
@ -422,28 +405,14 @@ fn is_registry_agent(agent_id: impl Into<AgentId>, cx: &App) -> bool {
|
|||
is_in_registry || is_settings_registry
|
||||
}
|
||||
|
||||
fn default_settings_for_agent(
|
||||
agent_id: impl Into<AgentId>,
|
||||
cx: &App,
|
||||
) -> settings::CustomAgentServerSettings {
|
||||
if is_registry_agent(agent_id, cx) {
|
||||
settings::CustomAgentServerSettings::Registry {
|
||||
default_model: None,
|
||||
default_mode: None,
|
||||
env: Default::default(),
|
||||
favorite_models: Vec::new(),
|
||||
default_config_options: Default::default(),
|
||||
favorite_config_option_values: Default::default(),
|
||||
}
|
||||
} else {
|
||||
settings::CustomAgentServerSettings::Extension {
|
||||
default_model: None,
|
||||
default_mode: None,
|
||||
env: Default::default(),
|
||||
favorite_models: Vec::new(),
|
||||
default_config_options: Default::default(),
|
||||
favorite_config_option_values: Default::default(),
|
||||
}
|
||||
fn default_settings_for_agent() -> settings::CustomAgentServerSettings {
|
||||
settings::CustomAgentServerSettings::Registry {
|
||||
default_model: None,
|
||||
default_mode: None,
|
||||
env: Default::default(),
|
||||
favorite_models: Vec::new(),
|
||||
default_config_options: Default::default(),
|
||||
favorite_config_option_values: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -547,53 +516,4 @@ mod tests {
|
|||
assert!(is_registry_agent("agent-from-settings", cx));
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn test_agent_with_extension_settings_type_is_not_registry(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
set_agent_server_settings(
|
||||
cx,
|
||||
vec![(
|
||||
"my-extension-agent",
|
||||
settings::CustomAgentServerSettings::Extension {
|
||||
env: HashMap::default(),
|
||||
default_mode: None,
|
||||
default_model: None,
|
||||
favorite_models: Vec::new(),
|
||||
default_config_options: HashMap::default(),
|
||||
favorite_config_option_values: HashMap::default(),
|
||||
},
|
||||
)],
|
||||
);
|
||||
cx.update(|cx| {
|
||||
assert!(!is_registry_agent("my-extension-agent", cx));
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn test_default_settings_for_extension_agent(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
cx.update(|cx| {
|
||||
assert!(matches!(
|
||||
default_settings_for_agent("some-extension-agent", cx),
|
||||
settings::CustomAgentServerSettings::Extension { .. }
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn test_default_settings_for_agent_in_registry(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
init_registry_with_agents(cx, &["new-registry-agent"]);
|
||||
cx.update(|cx| {
|
||||
assert!(matches!(
|
||||
default_settings_for_agent("new-registry-agent", cx),
|
||||
settings::CustomAgentServerSettings::Registry { .. }
|
||||
));
|
||||
assert!(matches!(
|
||||
default_settings_for_agent("not-in-registry", cx),
|
||||
settings::CustomAgentServerSettings::Extension { .. }
|
||||
));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ futures.workspace = true
|
|||
gpui.workspace = true
|
||||
language_model.workspace = true
|
||||
log.workspace = true
|
||||
paths.workspace = true
|
||||
project.workspace = true
|
||||
regex.workspace = true
|
||||
schemars.workspace = true
|
||||
|
|
@ -31,7 +32,6 @@ util.workspace = true
|
|||
[dev-dependencies]
|
||||
fs.workspace = true
|
||||
gpui = { workspace = true, features = ["test-support"] }
|
||||
paths.workspace = true
|
||||
|
||||
serde_json_lenient.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
mod agent_profile;
|
||||
mod user_agents_md;
|
||||
|
||||
use std::path::{Component, Path};
|
||||
use std::sync::{Arc, LazyLock};
|
||||
|
|
@ -20,6 +21,7 @@ use settings::{
|
|||
};
|
||||
|
||||
pub use crate::agent_profile::*;
|
||||
pub use crate::user_agents_md::{UserAgentsMd, UserAgentsMdState, init as init_user_agents_md};
|
||||
|
||||
pub const SUMMARIZE_THREAD_PROMPT: &str = include_str!("prompts/summarize_thread_prompt.txt");
|
||||
pub const SUMMARIZE_THREAD_DETAILED_PROMPT: &str =
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ path = "agent_skills.rs"
|
|||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
base64.workspace = true
|
||||
const_format.workspace = true
|
||||
fs.workspace = true
|
||||
futures.workspace = true
|
||||
|
|
@ -20,6 +21,7 @@ gpui.workspace = true
|
|||
paths.workspace = true
|
||||
serde.workspace = true
|
||||
serde_yaml_ng.workspace = true
|
||||
url.workspace = true
|
||||
util.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
|
|
|
|||
|
|
@ -4,9 +4,9 @@ use fs::Fs;
|
|||
use futures::StreamExt;
|
||||
use gpui::{Global, SharedString};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use url::Url;
|
||||
use util::paths::component_matches_ignore_ascii_case;
|
||||
|
||||
/// First segment of the skills directory path: `.agents`.
|
||||
|
|
@ -242,17 +242,7 @@ pub fn parse_skill_frontmatter(
|
|||
content: &str,
|
||||
source: SkillSource,
|
||||
) -> Result<Skill> {
|
||||
if content.len() > MAX_SKILL_FILE_SIZE {
|
||||
anyhow::bail!(
|
||||
"SKILL.md file exceeds maximum size of {}KB",
|
||||
MAX_SKILL_FILE_SIZE / 1024
|
||||
);
|
||||
}
|
||||
|
||||
let (metadata, _body) = extract_frontmatter(content)?;
|
||||
|
||||
validate_name(&metadata.name).map_err(anyhow::Error::msg)?;
|
||||
validate_description(&metadata.description).map_err(anyhow::Error::msg)?;
|
||||
let (metadata, _body) = parse_skill_file_content(content)?;
|
||||
|
||||
let directory_path = skill_file_path
|
||||
.parent()
|
||||
|
|
@ -270,6 +260,29 @@ pub fn parse_skill_frontmatter(
|
|||
})
|
||||
}
|
||||
|
||||
/// Extract the YAML frontmatter and body from a SKILL.md file without
|
||||
/// validating the metadata fields.
|
||||
pub fn extract_skill_frontmatter(content: &str) -> Result<(SkillMetadata, &str)> {
|
||||
if content.len() > MAX_SKILL_FILE_SIZE {
|
||||
anyhow::bail!(
|
||||
"SKILL.md file exceeds maximum size of {}KB",
|
||||
MAX_SKILL_FILE_SIZE / 1024
|
||||
);
|
||||
}
|
||||
|
||||
extract_frontmatter(content)
|
||||
}
|
||||
|
||||
/// Parse and validate the YAML frontmatter and body from a SKILL.md file.
|
||||
pub fn parse_skill_file_content(content: &str) -> Result<(SkillMetadata, &str)> {
|
||||
let (metadata, body) = extract_skill_frontmatter(content)?;
|
||||
|
||||
validate_name(&metadata.name).map_err(anyhow::Error::msg)?;
|
||||
validate_description(&metadata.description).map_err(anyhow::Error::msg)?;
|
||||
|
||||
Ok((metadata, body))
|
||||
}
|
||||
|
||||
fn extract_frontmatter(content: &str) -> Result<(SkillMetadata, &str)> {
|
||||
let content = content.trim_start();
|
||||
|
||||
|
|
@ -544,53 +557,15 @@ async fn find_skill_files(fs: &Arc<dyn Fs>, directory: &Path) -> Vec<PathBuf> {
|
|||
.await
|
||||
}
|
||||
|
||||
/// Returns the byte index ONE PAST the end of the closing frontmatter
|
||||
/// delimiter line in `bytes`, or `None` if no closing delimiter has been
|
||||
/// seen yet. Used by the chunked reader to know when it has enough
|
||||
/// bytes to stop pulling from disk.
|
||||
/// Read `skill_file_path` from disk and parse its frontmatter. The
|
||||
/// SKILL.md body is parsed away by `parse_skill_frontmatter` and not
|
||||
/// surfaced here; it's re-read on demand via `read_skill_body` when a
|
||||
/// skill is actually being loaded for the model.
|
||||
///
|
||||
/// Scans for the first `\n---` line followed by `\n`, `\r\n`, or EOF
|
||||
/// (excluding the opening line itself, which sits at byte 0 and is
|
||||
/// naturally skipped because we only consider lines following a `\n`).
|
||||
/// This may overshoot in pathological cases (e.g. `---` inside a quoted
|
||||
/// YAML string), but `parse_skill_frontmatter`'s candidate-and-validate
|
||||
/// logic still produces a correct result or a YAML parse error.
|
||||
fn closing_delimiter_end(bytes: &[u8]) -> Option<usize> {
|
||||
for (i, &b) in bytes.iter().enumerate() {
|
||||
if b != b'\n' {
|
||||
continue;
|
||||
}
|
||||
let line_start = i + 1;
|
||||
if line_start + 3 > bytes.len() {
|
||||
continue;
|
||||
}
|
||||
if &bytes[line_start..line_start + 3] != b"---" {
|
||||
continue;
|
||||
}
|
||||
let after_dashes = line_start + 3;
|
||||
if after_dashes == bytes.len() {
|
||||
return Some(after_dashes);
|
||||
}
|
||||
if bytes[after_dashes] == b'\n' {
|
||||
return Some(after_dashes + 1);
|
||||
}
|
||||
if after_dashes + 1 < bytes.len()
|
||||
&& bytes[after_dashes] == b'\r'
|
||||
&& bytes[after_dashes + 1] == b'\n'
|
||||
{
|
||||
return Some(after_dashes + 2);
|
||||
}
|
||||
// Line is `---trailing` or `----`; keep scanning.
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Read just enough of `skill_file_path` from disk to parse its
|
||||
/// frontmatter. The SKILL.md body is NOT loaded — that's deferred to
|
||||
/// `read_skill_body`, called only when a skill is actually being
|
||||
/// materialized for the model. Reading in 4KB chunks keeps the peak
|
||||
/// memory cost of loading N skills proportional to total frontmatter
|
||||
/// size, not total file size.
|
||||
/// We load the whole file in one go rather than streaming up to the
|
||||
/// closing `---`. `MAX_SKILL_FILE_SIZE` is 100KB and the metadata check
|
||||
/// below caps the worst case at that, so the peak transient cost is
|
||||
/// trivially small (≤ `MAX_SKILL_FILE_SIZE` × `SKILL_IO_CONCURRENCY`).
|
||||
pub async fn load_skill_frontmatter(
|
||||
fs: Arc<dyn Fs>,
|
||||
skill_file_path: PathBuf,
|
||||
|
|
@ -598,10 +573,15 @@ pub async fn load_skill_frontmatter(
|
|||
) -> Result<Skill, SkillLoadError> {
|
||||
// Short-circuit on oversized files before reading any of their
|
||||
// contents, so a stray multi-GB file named `SKILL.md` can't OOM the
|
||||
// app. We only act on a positive signal that the file is too large;
|
||||
// if metadata fails or is unavailable, we fall through to the read
|
||||
// loop, which is itself capped at `MAX_SKILL_FILE_SIZE`.
|
||||
if let Ok(Some(metadata)) = fs.metadata(&skill_file_path).await
|
||||
// app. If metadata is unavailable, refuse to read.
|
||||
let metadata = fs
|
||||
.metadata(&skill_file_path)
|
||||
.await
|
||||
.map_err(|e| SkillLoadError {
|
||||
path: skill_file_path.clone(),
|
||||
message: format!("Failed to read SKILL.md metadata: {}", e),
|
||||
})?;
|
||||
if let Some(metadata) = metadata
|
||||
&& metadata.len > MAX_SKILL_FILE_SIZE as u64
|
||||
{
|
||||
return Err(SkillLoadError {
|
||||
|
|
@ -613,51 +593,15 @@ pub async fn load_skill_frontmatter(
|
|||
});
|
||||
}
|
||||
|
||||
let mut reader = fs
|
||||
.open_sync(&skill_file_path)
|
||||
let content = fs
|
||||
.load(&skill_file_path)
|
||||
.await
|
||||
.map_err(|e| SkillLoadError {
|
||||
path: skill_file_path.clone(),
|
||||
message: format!("Failed to open file: {}", e),
|
||||
message: format!("Failed to read file: {}", e),
|
||||
})?;
|
||||
|
||||
// The chunked read is intentionally synchronous: `Fs::open_sync`
|
||||
// returns a synchronous `Read` (RealFs uses `std::fs::File`), and
|
||||
// production callers already wrap `load_skills_from_directory` in
|
||||
// `cx.background_spawn`, so any blocking happens on the background
|
||||
// executor — not on the foreground thread. Routing through
|
||||
// `smol::unblock` instead would schedule the work on smol's blocking
|
||||
// pool, whose wakeups don't drive GPUI's test scheduler and therefore
|
||||
// panic with "Parking forbidden" under `TestAppContext`.
|
||||
let read_result: Result<Vec<u8>, io::Error> = (|| {
|
||||
let mut accumulated: Vec<u8> = Vec::new();
|
||||
let mut chunk = [0u8; 4096];
|
||||
loop {
|
||||
let n = reader.read(&mut chunk)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
accumulated.extend_from_slice(&chunk[..n]);
|
||||
if closing_delimiter_end(&accumulated).is_some() {
|
||||
break;
|
||||
}
|
||||
if accumulated.len() > MAX_SKILL_FILE_SIZE {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(accumulated)
|
||||
})();
|
||||
let accumulated = read_result.map_err(|e| SkillLoadError {
|
||||
path: skill_file_path.clone(),
|
||||
message: format!("Failed to read file: {}", e),
|
||||
})?;
|
||||
|
||||
let content = std::str::from_utf8(&accumulated).map_err(|e| SkillLoadError {
|
||||
path: skill_file_path.clone(),
|
||||
message: format!("SKILL.md is not valid UTF-8: {}", e),
|
||||
})?;
|
||||
|
||||
parse_skill_frontmatter(&skill_file_path, content, source).map_err(|e| SkillLoadError {
|
||||
parse_skill_frontmatter(&skill_file_path, &content, source).map_err(|e| SkillLoadError {
|
||||
path: skill_file_path.clone(),
|
||||
message: e.to_string(),
|
||||
})
|
||||
|
|
@ -788,6 +732,58 @@ pub fn is_agents_skills_path(path: &Path) -> bool {
|
|||
false
|
||||
}
|
||||
|
||||
/// The `zed://` scheme used by share links.
|
||||
const SKILL_SHARE_LINK_SCHEME: &str = "zed";
|
||||
/// The host (the part after `zed://`) that identifies a skill share link.
|
||||
const SKILL_SHARE_LINK_HOST: &str = "skill";
|
||||
/// The query parameter that carries the embedded `SKILL.md` payload.
|
||||
const SKILL_SHARE_LINK_DATA_PARAM: &str = "data";
|
||||
|
||||
/// The `zed://` deep-link prefix for a shared skill. Opening a link with this
|
||||
/// prefix prompts the recipient to review and install the embedded skill.
|
||||
pub const SKILL_SHARE_LINK_PREFIX: &str =
|
||||
concatcp!(SKILL_SHARE_LINK_SCHEME, "://", SKILL_SHARE_LINK_HOST);
|
||||
|
||||
/// Build a shareable `zed://skill?data=…` link that fully embeds the given
|
||||
/// `SKILL.md` file contents.
|
||||
///
|
||||
/// The contents are base64url-encoded (no padding) so the link is
|
||||
/// self-contained and URL-safe: the recipient doesn't need the skill to be
|
||||
/// hosted anywhere. Recover the contents with [`decode_skill_share_link`].
|
||||
pub fn encode_skill_share_link(skill_file_content: &str) -> String {
|
||||
use base64::Engine as _;
|
||||
let data =
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(skill_file_content.as_bytes());
|
||||
let mut url = Url::parse(SKILL_SHARE_LINK_PREFIX).expect("skill share link prefix is valid");
|
||||
url.query_pairs_mut()
|
||||
.append_pair(SKILL_SHARE_LINK_DATA_PARAM, &data);
|
||||
url.into()
|
||||
}
|
||||
|
||||
/// Recover the `SKILL.md` contents embedded in a `zed://skill?data=…` link
|
||||
/// produced by [`encode_skill_share_link`].
|
||||
pub fn decode_skill_share_link(link: &str) -> Result<String> {
|
||||
use base64::Engine as _;
|
||||
let url = Url::parse(link).context("skill share link is not a valid URL")?;
|
||||
anyhow::ensure!(
|
||||
url.scheme() == SKILL_SHARE_LINK_SCHEME && url.host_str() == Some(SKILL_SHARE_LINK_HOST),
|
||||
"not a skill share link"
|
||||
);
|
||||
let data = url
|
||||
.query_pairs()
|
||||
.find_map(|(key, value)| (key == SKILL_SHARE_LINK_DATA_PARAM).then_some(value))
|
||||
.context("skill share link is missing the `data` parameter")?;
|
||||
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(data.as_bytes())
|
||||
.context("skill share link `data` is not valid base64")?;
|
||||
anyhow::ensure!(
|
||||
bytes.len() <= MAX_SKILL_FILE_SIZE,
|
||||
"shared skill exceeds the maximum size of {MAX_SKILL_FILE_SIZE} bytes"
|
||||
);
|
||||
let content = String::from_utf8(bytes).context("skill share link `data` is not valid UTF-8")?;
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -849,6 +845,26 @@ Do the thing.
|
|||
assert!(!skill.disable_model_invocation);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_skill_file_content_returns_body() {
|
||||
let content = r#"---
|
||||
name: my-skill
|
||||
description: A test skill for testing purposes
|
||||
---
|
||||
|
||||
# My Skill
|
||||
|
||||
Do the thing.
|
||||
"#;
|
||||
|
||||
let (metadata, body) = parse_skill_file_content(content)
|
||||
.expect("valid skill content should parse successfully");
|
||||
|
||||
assert_eq!(metadata.name, "my-skill");
|
||||
assert_eq!(metadata.description, "A test skill for testing purposes");
|
||||
assert_eq!(body.trim(), "# My Skill\n\nDo the thing.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_disable_model_invocation_true() {
|
||||
let content = r#"---
|
||||
|
|
@ -1996,4 +2012,25 @@ description: A skill with no body content
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skill_share_link_round_trips() {
|
||||
let content =
|
||||
"---\nname: my-skill\ndescription: Does a thing.\n---\n\n## Steps\n\nDo the thing.\n";
|
||||
let link = encode_skill_share_link(content);
|
||||
let data = link
|
||||
.strip_prefix("zed://skill?data=")
|
||||
.expect("link should start with the skill share prefix");
|
||||
// base64url (no-pad) output must not require percent-encoding.
|
||||
assert!(!data.contains('+') && !data.contains('/') && !data.contains('='));
|
||||
assert_eq!(decode_skill_share_link(&link).unwrap(), content);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_skill_share_link_rejects_non_skill_links() {
|
||||
assert!(decode_skill_share_link("zed://settings/agent.skills").is_err());
|
||||
assert!(decode_skill_share_link("zed://skill").is_err());
|
||||
assert!(decode_skill_share_link("zed://skill?other=1").is_err());
|
||||
assert!(decode_skill_share_link("zed://skill?data=!!!notbase64").is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
name: create-skill
|
||||
description: Helps users create new agent skills for Zed. Use this when a user wants to create a skill, asks about SKILL.md structure, or wants to package reusable agent instructions.
|
||||
description: Helps you create new agent skills for Zed. Use this to create a skill, ask about SKILLs.md, or package reusable agent instructions.
|
||||
---
|
||||
|
||||
# Creating a Zed Agent Skill
|
||||
|
|
@ -88,8 +88,8 @@ Reference these in the skill body. The agent can read them using the file path s
|
|||
|
||||
1. Decide on scope (global vs project-local) based on the user's needs.
|
||||
2. Choose a descriptive, hyphenated name.
|
||||
3. Create the directory structure.
|
||||
4. Write the `SKILL.md` with frontmatter and instructions.
|
||||
3. Create the directory structure. The `create_directory` tool normally only creates directories inside the current project, but it has a special allow case for global skills under `~/.agents/skills`.
|
||||
4. Write the `SKILL.md` with frontmatter and instructions. The `write_file` and `edit_file` tools also have a special allow case for creating or modifying files under `~/.agents/skills`.
|
||||
5. Optionally add supporting files (templates, examples, references).
|
||||
|
||||
After creating the skill, it will be automatically discovered by Zed's agent on the next conversation (no restart needed for global skills if the `~/.agents/skills/` directory already exists).
|
||||
|
|
|
|||
|
|
@ -69,6 +69,7 @@ language.workspace = true
|
|||
language_model.workspace = true
|
||||
language_models.workspace = true
|
||||
log.workspace = true
|
||||
lru.workspace = true
|
||||
lsp.workspace = true
|
||||
markdown.workspace = true
|
||||
menu.workspace = true
|
||||
|
|
@ -88,7 +89,6 @@ release_channel.workspace = true
|
|||
remote.workspace = true
|
||||
remote_connection.workspace = true
|
||||
rope.workspace = true
|
||||
rules_library.workspace = true
|
||||
skill_creator.workspace = true
|
||||
schemars.workspace = true
|
||||
serde.workspace = true
|
||||
|
|
|
|||
|
|
@ -1174,7 +1174,6 @@ impl AgentConfiguration {
|
|||
};
|
||||
|
||||
let source_kind = match source {
|
||||
ExternalAgentSource::Extension => AiSettingItemSource::Extension,
|
||||
ExternalAgentSource::Registry => AiSettingItemSource::Registry,
|
||||
ExternalAgentSource::Custom => AiSettingItemSource::Custom,
|
||||
};
|
||||
|
|
@ -1218,26 +1217,6 @@ impl AgentConfiguration {
|
|||
});
|
||||
|
||||
let uninstall_button = match source {
|
||||
ExternalAgentSource::Extension => Some(
|
||||
IconButton::new(
|
||||
SharedString::from(format!("uninstall-{}", id)),
|
||||
IconName::Trash,
|
||||
)
|
||||
.icon_color(Color::Muted)
|
||||
.icon_size(IconSize::Small)
|
||||
.tooltip(Tooltip::text("Uninstall Agent Extension"))
|
||||
.on_click(cx.listener(move |this, _, _window, cx| {
|
||||
let agent_name = agent_server_name.clone();
|
||||
|
||||
if let Some(ext_id) = this.agent_server_store.update(cx, |store, _cx| {
|
||||
store.get_extension_id_for_agent(&agent_name)
|
||||
}) {
|
||||
ExtensionStore::global(cx)
|
||||
.update(cx, |store, cx| store.uninstall_extension(ext_id, cx))
|
||||
.detach_and_log_err(cx);
|
||||
}
|
||||
})),
|
||||
),
|
||||
ExternalAgentSource::Registry => {
|
||||
let fs = self.fs.clone();
|
||||
Some(
|
||||
|
|
|
|||
|
|
@ -138,7 +138,7 @@ impl AgentDiffPane {
|
|||
.changed_buffers(cx);
|
||||
|
||||
// Sort edited files alphabetically for consistency with Git diff view
|
||||
let mut sorted_buffers: Vec<_> = changed_buffers.iter().collect();
|
||||
let mut sorted_buffers: Vec<_> = changed_buffers.collect();
|
||||
sorted_buffers.sort_by(|(buffer_a, _), (buffer_b, _)| {
|
||||
let path_a = buffer_a.read(cx).file().map(|f| f.path().clone());
|
||||
let path_b = buffer_b.read(cx).file().map(|f| f.path().clone());
|
||||
|
|
@ -566,6 +566,10 @@ impl Item for AgentDiffPane {
|
|||
.for_each_project_item(cx, f)
|
||||
}
|
||||
|
||||
fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
|
||||
self.editor.read(cx).active_project_path(cx)
|
||||
}
|
||||
|
||||
fn set_nav_history(
|
||||
&mut self,
|
||||
nav_history: ItemNavHistory,
|
||||
|
|
@ -1531,7 +1535,7 @@ impl AgentDiff {
|
|||
};
|
||||
|
||||
let action_log = thread.read(cx).action_log();
|
||||
let changed_buffers = action_log.read(cx).changed_buffers(cx);
|
||||
let changed_buffers = action_log.read(cx).changed_buffers(cx).collect::<Vec<_>>();
|
||||
|
||||
let mut unaffected = self.reviewing_editors.clone();
|
||||
|
||||
|
|
@ -1765,12 +1769,13 @@ impl AgentDiff {
|
|||
{
|
||||
let changed_buffers = thread.read(cx).action_log().read(cx).changed_buffers(cx);
|
||||
|
||||
let mut keys = changed_buffers.keys();
|
||||
keys.find(|k| *k == &curr_buffer);
|
||||
let mut keys = changed_buffers.map(|(buffer, _)| buffer);
|
||||
keys.find(|k| *k == curr_buffer);
|
||||
let next_project_path = keys
|
||||
.next()
|
||||
.filter(|k| *k != &curr_buffer)
|
||||
.filter(|k| *k != curr_buffer)
|
||||
.and_then(|after| after.read(cx).project_path(cx));
|
||||
drop(keys);
|
||||
|
||||
if let Some(path) = next_project_path {
|
||||
let task = workspace.open_path(path, None, true, window, cx);
|
||||
|
|
@ -2253,7 +2258,7 @@ mod tests {
|
|||
});
|
||||
|
||||
let editor2_path = editor2
|
||||
.read_with(cx, |editor, cx| editor.project_path(cx))
|
||||
.read_with(cx, |editor, cx| editor.active_project_path(cx))
|
||||
.unwrap();
|
||||
assert_eq!(editor2_path, buffer_path2);
|
||||
|
||||
|
|
|
|||
|
|
@ -34,7 +34,6 @@ enum RegistryInstallStatus {
|
|||
NotInstalled,
|
||||
InstalledRegistry,
|
||||
InstalledCustom,
|
||||
InstalledExtension,
|
||||
}
|
||||
|
||||
#[derive(IntoElement)]
|
||||
|
|
@ -155,9 +154,6 @@ impl AgentRegistryPage {
|
|||
RegistryInstallStatus::InstalledRegistry
|
||||
}
|
||||
CustomAgentServerSettings::Custom { .. } => RegistryInstallStatus::InstalledCustom,
|
||||
CustomAgentServerSettings::Extension { .. } => {
|
||||
RegistryInstallStatus::InstalledExtension
|
||||
}
|
||||
};
|
||||
self.installed_statuses.insert(id.clone(), status);
|
||||
}
|
||||
|
|
@ -560,9 +556,6 @@ impl AgentRegistryPage {
|
|||
RegistryInstallStatus::InstalledCustom => Button::new(button_id, "Installed")
|
||||
.style(ButtonStyle::OutlinedGhost)
|
||||
.disabled(true),
|
||||
RegistryInstallStatus::InstalledExtension => Button::new(button_id, "Installed")
|
||||
.style(ButtonStyle::OutlinedGhost)
|
||||
.disabled(true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,10 +43,12 @@ use ::ui::IconName;
|
|||
use agent_client_protocol::schema as acp;
|
||||
use agent_settings::{AgentProfileId, AgentSettings};
|
||||
use command_palette_hooks::CommandPaletteFilter;
|
||||
use editor::{Editor, SelectionEffects, scroll::Autoscroll};
|
||||
use feature_flags::FeatureFlagAppExt as _;
|
||||
use fs::Fs;
|
||||
use gpui::{
|
||||
Action, App, Context, Entity, ImageSource, Resource, SharedString, SharedUri, Window, actions,
|
||||
Action, App, Context, Entity, ImageSource, Resource, SharedString, SharedUri, TaskExt, Window,
|
||||
actions,
|
||||
};
|
||||
use language::{
|
||||
LanguageRegistry,
|
||||
|
|
@ -56,7 +58,8 @@ use language_model::{
|
|||
ConfiguredModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
|
||||
};
|
||||
use project::{AgentId, DisableAiSettings};
|
||||
use prompt_store::{PromptBuilder, rules_to_skills_migration};
|
||||
use prompt_store::{self, PromptBuilder, rules_to_skills_migration};
|
||||
use rope::Point;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use settings::{LanguageModelSelection, Settings as _, SettingsStore, SidebarSide};
|
||||
|
|
@ -112,6 +115,42 @@ pub(crate) fn resolve_agent_image(
|
|||
None
|
||||
}
|
||||
|
||||
pub(crate) fn open_abs_path_at_point(
|
||||
workspace: &mut Workspace,
|
||||
abs_path: PathBuf,
|
||||
point: Point,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Workspace>,
|
||||
) -> bool {
|
||||
let project = workspace.project();
|
||||
let Some(path) = project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let item = workspace.open_path(path, None, true, window, cx);
|
||||
window
|
||||
.spawn(cx, async move |cx| {
|
||||
let Some(editor) = item.await?.downcast::<Editor>() else {
|
||||
return Ok(());
|
||||
};
|
||||
let range = point..point;
|
||||
editor
|
||||
.update_in(cx, |editor, window, cx| {
|
||||
editor.change_selections(
|
||||
SelectionEffects::scroll(Autoscroll::center()),
|
||||
window,
|
||||
cx,
|
||||
|selections| selections.select_ranges([range]),
|
||||
);
|
||||
})
|
||||
.ok();
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.detach_and_log_err(cx);
|
||||
true
|
||||
}
|
||||
|
||||
pub const DEFAULT_THREAD_TITLE: &str = "New Agent Thread";
|
||||
const PARALLEL_AGENT_LAYOUT_BACKFILL_KEY: &str = "parallel_agent_layout_backfilled";
|
||||
|
||||
|
|
@ -160,6 +199,8 @@ actions!(
|
|||
ArchiveSelectedThread,
|
||||
/// Removes the currently selected thread.
|
||||
RemoveSelectedThread,
|
||||
/// Renames the currently selected thread.
|
||||
RenameSelectedThread,
|
||||
/// Starts a chat conversation with follow-up enabled.
|
||||
ChatWithFollow,
|
||||
/// Cycles to the next inline assist suggestion.
|
||||
|
|
@ -204,6 +245,8 @@ actions!(
|
|||
ResetTrialUpsell,
|
||||
/// Resets the trial end upsell notification.
|
||||
ResetTrialEndUpsell,
|
||||
/// Re-enables the fast mode warning for every provider and model.
|
||||
ResetFastModeWarnings,
|
||||
/// Opens the "Add Context" menu in the message editor.
|
||||
OpenAddContextMenu,
|
||||
/// Interrupts the current generation and sends the message immediately.
|
||||
|
|
@ -244,6 +287,8 @@ actions!(
|
|||
ScrollOutputToNextMessage,
|
||||
/// Import agent threads from other Zed release channels (e.g. Preview, Nightly).
|
||||
ImportThreadsFromOtherChannels,
|
||||
/// Starts a new terminal thread.
|
||||
NewTerminalThread,
|
||||
]
|
||||
);
|
||||
|
||||
|
|
@ -505,7 +550,7 @@ pub fn init(
|
|||
cx: &mut App,
|
||||
) {
|
||||
agent::ThreadStore::init_global(cx);
|
||||
rules_library::init(cx);
|
||||
prompt_store::init(cx);
|
||||
skill_creator::init(cx);
|
||||
if !is_eval {
|
||||
// Initializing the language model from the user settings messes with the eval, so we only initialize them when
|
||||
|
|
@ -643,7 +688,6 @@ fn update_command_palette_filter(cx: &mut App) {
|
|||
TypeId::of::<AcceptEditPrediction>(),
|
||||
TypeId::of::<AcceptNextWordEditPrediction>(),
|
||||
TypeId::of::<AcceptNextLineEditPrediction>(),
|
||||
TypeId::of::<AcceptEditPrediction>(),
|
||||
TypeId::of::<ShowEditPrediction>(),
|
||||
TypeId::of::<NextEditPrediction>(),
|
||||
TypeId::of::<PreviousEditPrediction>(),
|
||||
|
|
@ -651,7 +695,10 @@ fn update_command_palette_filter(cx: &mut App) {
|
|||
];
|
||||
|
||||
let open_rules_library_action = [TypeId::of::<zed_actions::assistant::OpenRulesLibrary>()];
|
||||
let open_skill_creator_action = [TypeId::of::<zed_actions::assistant::OpenSkillCreator>()];
|
||||
let skill_creator_actions = [
|
||||
TypeId::of::<zed_actions::assistant::OpenSkillCreator>(),
|
||||
TypeId::of::<zed_actions::assistant::CreateSkillFromUrl>(),
|
||||
];
|
||||
|
||||
if disable_ai {
|
||||
filter.hide_namespace("agent");
|
||||
|
|
@ -709,10 +756,10 @@ fn update_command_palette_filter(cx: &mut App) {
|
|||
// rest of that namespace's actions.
|
||||
if !disable_ai {
|
||||
filter.hide_action_types(&open_rules_library_action);
|
||||
filter.show_action_types(open_skill_creator_action.iter());
|
||||
filter.show_action_types(skill_creator_actions.iter());
|
||||
} else {
|
||||
filter.show_action_types(open_rules_library_action.iter());
|
||||
filter.hide_action_types(&open_skill_creator_action);
|
||||
filter.hide_action_types(&skill_creator_actions);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -850,6 +897,26 @@ mod tests {
|
|||
!filter.is_hidden(&NewThread),
|
||||
"NewThread should be visible by default"
|
||||
);
|
||||
assert!(
|
||||
!filter.is_hidden(&NewTerminalThread),
|
||||
"NewTerminalThread should be visible by default"
|
||||
);
|
||||
assert!(
|
||||
!filter.is_hidden(&zed_actions::assistant::OpenSkillCreator),
|
||||
"OpenSkillCreator should be visible by default"
|
||||
);
|
||||
assert!(
|
||||
!filter.is_hidden(&zed_actions::assistant::CreateSkillFromUrl),
|
||||
"CreateSkillFromUrl should be visible by default"
|
||||
);
|
||||
assert!(
|
||||
!filter.is_hidden(&zed_actions::assistant::OpenGlobalAgentsMdRules),
|
||||
"OpenGlobalAgentsMdRules should be visible by default"
|
||||
);
|
||||
assert!(
|
||||
!filter.is_hidden(&zed_actions::assistant::OpenProjectAgentsMdRules),
|
||||
"OpenProjectAgentsMdRules should be visible by default"
|
||||
);
|
||||
});
|
||||
|
||||
// Disable agent
|
||||
|
|
@ -869,6 +936,18 @@ mod tests {
|
|||
filter.is_hidden(&NewThread),
|
||||
"NewThread should be hidden when agent is disabled"
|
||||
);
|
||||
assert!(
|
||||
filter.is_hidden(&NewTerminalThread),
|
||||
"NewTerminalThread should be hidden when agent is disabled"
|
||||
);
|
||||
assert!(
|
||||
filter.is_hidden(&zed_actions::assistant::OpenGlobalAgentsMdRules),
|
||||
"OpenGlobalAgentsMdRules should be hidden when agent is disabled"
|
||||
);
|
||||
assert!(
|
||||
filter.is_hidden(&zed_actions::assistant::OpenProjectAgentsMdRules),
|
||||
"OpenProjectAgentsMdRules should be hidden when agent is disabled"
|
||||
);
|
||||
});
|
||||
|
||||
// Test EditPredictionProvider
|
||||
|
|
|
|||
|
|
@ -12,7 +12,9 @@ use futures::{
|
|||
stream::BoxStream,
|
||||
};
|
||||
use gpui::{App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Subscription, Task};
|
||||
use language::{Buffer, IndentKind, LanguageName, Point, TransactionId, line_diff};
|
||||
use language::{
|
||||
Buffer, BufferEditSource, IndentKind, LanguageName, Point, TransactionId, line_diff,
|
||||
};
|
||||
use language_model::{
|
||||
CompletionIntent, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
|
||||
LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
|
||||
|
|
@ -978,7 +980,7 @@ impl CodegenAlternative {
|
|||
buffer.finalize_last_transaction(cx);
|
||||
buffer.start_transaction(cx);
|
||||
buffer.edit(edits, None, cx);
|
||||
buffer.end_transaction(cx)
|
||||
buffer.end_transaction_with_source(BufferEditSource::Agent, cx)
|
||||
});
|
||||
|
||||
if let Some(transaction) = transaction {
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ use ui::{
|
|||
};
|
||||
use util::ResultExt as _;
|
||||
|
||||
use crate::ui::{HoldForDefault, documentation_aside_side};
|
||||
use crate::ui::documentation_aside_side;
|
||||
|
||||
const PICKER_THRESHOLD: usize = 5;
|
||||
|
||||
|
|
@ -101,6 +101,13 @@ impl ConfigOptionsView {
|
|||
return false;
|
||||
};
|
||||
|
||||
self.agent_server.set_default_config_option(
|
||||
config_id.0.as_ref(),
|
||||
Some(next_value.0.as_ref()),
|
||||
self.fs.clone(),
|
||||
cx,
|
||||
);
|
||||
|
||||
let task = self
|
||||
.config_options
|
||||
.set_config_option(config_id, next_value, cx);
|
||||
|
|
@ -412,7 +419,7 @@ struct ConfigOptionPickerDelegate {
|
|||
filtered_entries: Vec<ConfigOptionPickerEntry>,
|
||||
all_options: Vec<ConfigOptionValue>,
|
||||
selected_index: usize,
|
||||
selected_description: Option<(usize, SharedString, bool)>,
|
||||
selected_description: Option<(usize, SharedString)>,
|
||||
favorites: HashSet<acp::SessionConfigValueId>,
|
||||
_settings_subscription: Subscription,
|
||||
}
|
||||
|
|
@ -544,28 +551,16 @@ impl PickerDelegate for ConfigOptionPickerDelegate {
|
|||
})
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
|
||||
fn confirm(&mut self, _secondary: bool, _window: &mut Window, cx: &mut Context<Picker<Self>>) {
|
||||
if let Some(ConfigOptionPickerEntry::Option(option)) =
|
||||
self.filtered_entries.get(self.selected_index)
|
||||
{
|
||||
if window.modifiers().secondary() {
|
||||
let default_value = self
|
||||
.agent_server
|
||||
.default_config_option(self.config_id.0.as_ref(), cx);
|
||||
let is_default = default_value.as_deref() == Some(&*option.value.0);
|
||||
|
||||
self.agent_server.set_default_config_option(
|
||||
self.config_id.0.as_ref(),
|
||||
if is_default {
|
||||
None
|
||||
} else {
|
||||
Some(option.value.0.as_ref())
|
||||
},
|
||||
self.fs.clone(),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
|
||||
self.agent_server.set_default_config_option(
|
||||
self.config_id.0.as_ref(),
|
||||
Some(option.value.0.as_ref()),
|
||||
self.fs.clone(),
|
||||
cx,
|
||||
);
|
||||
let task = self.config_options.set_config_option(
|
||||
self.config_id.clone(),
|
||||
option.value.clone(),
|
||||
|
|
@ -614,11 +609,6 @@ impl PickerDelegate for ConfigOptionPickerDelegate {
|
|||
let current_value = self.current_value();
|
||||
let is_selected = current_value.as_ref() == Some(&option.value);
|
||||
|
||||
let default_value = self
|
||||
.agent_server
|
||||
.default_config_option(self.config_id.0.as_ref(), cx);
|
||||
let is_default = default_value.as_deref() == Some(&*option.value.0);
|
||||
|
||||
let is_favorite = self.favorites.contains(&option.value);
|
||||
|
||||
let option_name = option.name.clone();
|
||||
|
|
@ -631,9 +621,8 @@ impl PickerDelegate for ConfigOptionPickerDelegate {
|
|||
let desc: SharedString = desc.into();
|
||||
this.on_hover(cx.listener(move |menu, hovered, _, cx| {
|
||||
if *hovered {
|
||||
menu.delegate.selected_description =
|
||||
Some((ix, desc.clone(), is_default));
|
||||
} else if matches!(menu.delegate.selected_description, Some((id, _, _)) if id == ix)
|
||||
menu.delegate.selected_description = Some((ix, desc.clone()));
|
||||
} else if matches!(menu.delegate.selected_description, Some((id, _)) if id == ix)
|
||||
{
|
||||
menu.delegate.selected_description = None;
|
||||
}
|
||||
|
|
@ -688,29 +677,20 @@ impl PickerDelegate for ConfigOptionPickerDelegate {
|
|||
_window: &mut Window,
|
||||
cx: &mut Context<Picker<Self>>,
|
||||
) -> Option<ui::DocumentationAside> {
|
||||
self.selected_description
|
||||
.as_ref()
|
||||
.map(|(_, description, is_default)| {
|
||||
let description = description.clone();
|
||||
let is_default = *is_default;
|
||||
self.selected_description.as_ref().map(|(_, description)| {
|
||||
let description = description.clone();
|
||||
|
||||
let side = documentation_aside_side(cx);
|
||||
let side = documentation_aside_side(cx);
|
||||
|
||||
ui::DocumentationAside::new(
|
||||
side,
|
||||
Rc::new(move |_| {
|
||||
v_flex()
|
||||
.gap_1()
|
||||
.child(Label::new(description.clone()))
|
||||
.child(HoldForDefault::new(is_default))
|
||||
.into_any_element()
|
||||
}),
|
||||
)
|
||||
})
|
||||
ui::DocumentationAside::new(
|
||||
side,
|
||||
Rc::new(move |_| Label::new(description.clone()).into_any_element()),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn documentation_aside_index(&self) -> Option<usize> {
|
||||
self.selected_description.as_ref().map(|(ix, _, _)| *ix)
|
||||
self.selected_description.as_ref().map(|(ix, _)| *ix)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -878,3 +858,143 @@ fn count_config_options(option: &acp::SessionConfigOption) -> usize {
|
|||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use acp_thread::AgentConnection;
|
||||
use fs::FakeFs;
|
||||
use gpui::TestAppContext;
|
||||
use parking_lot::Mutex;
|
||||
use project::{AgentId, Project};
|
||||
use std::{any::Any, cell::RefCell};
|
||||
|
||||
#[gpui::test]
|
||||
fn cycling_config_option_saves_selected_value_as_default(cx: &mut TestAppContext) {
|
||||
let agent_server = Rc::new(TestAgentServer::default());
|
||||
let config_options = Rc::new(TestSessionConfigOptions::new(vec![
|
||||
acp::SessionConfigOption::select(
|
||||
"mode",
|
||||
"Mode",
|
||||
"auto",
|
||||
vec![
|
||||
acp::SessionConfigSelectOption::new("auto", "Auto"),
|
||||
acp::SessionConfigSelectOption::new("manual", "Manual"),
|
||||
],
|
||||
)
|
||||
.category(acp::SessionConfigOptionCategory::Mode),
|
||||
]));
|
||||
let fs: Arc<dyn Fs> = FakeFs::new(cx.executor());
|
||||
|
||||
cx.update(|cx| {
|
||||
let config_options: Rc<dyn AgentSessionConfigOptions> = config_options.clone();
|
||||
let agent_server: Rc<dyn AgentServer> = agent_server.clone();
|
||||
let fs = fs.clone();
|
||||
let view = cx.new(|_| ConfigOptionsView {
|
||||
config_option_ids: ConfigOptionsView::config_option_ids(&config_options),
|
||||
config_options,
|
||||
selectors: Vec::new(),
|
||||
agent_server,
|
||||
fs,
|
||||
_refresh_task: Task::ready(()),
|
||||
});
|
||||
|
||||
assert!(view.update(cx, |view, cx| {
|
||||
view.cycle_category_option(acp::SessionConfigOptionCategory::Mode, false, cx)
|
||||
}));
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
agent_server.saved_defaults.lock().as_slice(),
|
||||
&[("mode".to_string(), Some("manual".to_string()))]
|
||||
);
|
||||
assert_eq!(
|
||||
config_options.set_values.borrow().as_slice(),
|
||||
&[("mode".to_string(), "manual".to_string())]
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct TestAgentServer {
|
||||
saved_defaults: Arc<Mutex<Vec<(String, Option<String>)>>>,
|
||||
}
|
||||
|
||||
impl AgentServer for TestAgentServer {
|
||||
fn logo(&self) -> IconName {
|
||||
IconName::ZedAssistant
|
||||
}
|
||||
|
||||
fn agent_id(&self) -> AgentId {
|
||||
AgentId::new("test-agent")
|
||||
}
|
||||
|
||||
fn connect(
|
||||
&self,
|
||||
_delegate: agent_servers::AgentServerDelegate,
|
||||
_project: Entity<Project>,
|
||||
_cx: &mut App,
|
||||
) -> Task<anyhow::Result<Rc<dyn AgentConnection>>> {
|
||||
Task::ready(Err(anyhow::anyhow!("test agent server cannot connect")))
|
||||
}
|
||||
|
||||
fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
|
||||
self
|
||||
}
|
||||
|
||||
fn set_default_config_option(
|
||||
&self,
|
||||
config_id: &str,
|
||||
value_id: Option<&str>,
|
||||
_fs: Arc<dyn Fs>,
|
||||
_cx: &mut App,
|
||||
) {
|
||||
self.saved_defaults.lock().push((
|
||||
config_id.to_string(),
|
||||
value_id.map(|value| value.to_string()),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
struct TestSessionConfigOptions {
|
||||
options: RefCell<Vec<acp::SessionConfigOption>>,
|
||||
set_values: RefCell<Vec<(String, String)>>,
|
||||
}
|
||||
|
||||
impl TestSessionConfigOptions {
|
||||
fn new(options: Vec<acp::SessionConfigOption>) -> Self {
|
||||
Self {
|
||||
options: RefCell::new(options),
|
||||
set_values: RefCell::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentSessionConfigOptions for TestSessionConfigOptions {
|
||||
fn config_options(&self) -> Vec<acp::SessionConfigOption> {
|
||||
self.options.borrow().clone()
|
||||
}
|
||||
|
||||
fn set_config_option(
|
||||
&self,
|
||||
config_id: acp::SessionConfigId,
|
||||
value: acp::SessionConfigValueId,
|
||||
_cx: &mut App,
|
||||
) -> Task<anyhow::Result<Vec<acp::SessionConfigOption>>> {
|
||||
self.set_values
|
||||
.borrow_mut()
|
||||
.push((config_id.0.to_string(), value.0.to_string()));
|
||||
|
||||
let options = {
|
||||
let mut options = self.options.borrow_mut();
|
||||
if let Some(option) = options.iter_mut().find(|option| option.id == config_id)
|
||||
&& let acp::SessionConfigKind::Select(select) = &mut option.kind
|
||||
{
|
||||
select.current_value = value;
|
||||
}
|
||||
options.clone()
|
||||
};
|
||||
|
||||
Task::ready(Ok(options))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,8 +10,7 @@ use gpui::{
|
|||
ScrollHandle, TextStyleRefinement, WeakEntity, Window,
|
||||
};
|
||||
use language::language_settings::SoftWrap;
|
||||
use project::{AgentId, Project};
|
||||
use prompt_store::PromptStore;
|
||||
use project::{AgentId, Project, project_settings::DiagnosticSeverity};
|
||||
use rope::Point;
|
||||
use settings::Settings as _;
|
||||
use terminal_view::TerminalView;
|
||||
|
|
@ -25,7 +24,6 @@ pub struct EntryViewState {
|
|||
workspace: WeakEntity<Workspace>,
|
||||
project: WeakEntity<Project>,
|
||||
thread_store: Option<Entity<ThreadStore>>,
|
||||
prompt_store: Option<Entity<PromptStore>>,
|
||||
entries: Vec<Entry>,
|
||||
session_capabilities: SharedSessionCapabilities,
|
||||
agent_id: AgentId,
|
||||
|
|
@ -36,7 +34,6 @@ impl EntryViewState {
|
|||
workspace: WeakEntity<Workspace>,
|
||||
project: WeakEntity<Project>,
|
||||
thread_store: Option<Entity<ThreadStore>>,
|
||||
prompt_store: Option<Entity<PromptStore>>,
|
||||
session_capabilities: SharedSessionCapabilities,
|
||||
agent_id: AgentId,
|
||||
) -> Self {
|
||||
|
|
@ -44,7 +41,6 @@ impl EntryViewState {
|
|||
workspace,
|
||||
project,
|
||||
thread_store,
|
||||
prompt_store,
|
||||
entries: Vec::new(),
|
||||
session_capabilities,
|
||||
agent_id,
|
||||
|
|
@ -86,7 +82,6 @@ impl EntryViewState {
|
|||
self.workspace.clone(),
|
||||
self.project.clone(),
|
||||
self.thread_store.clone(),
|
||||
self.prompt_store.clone(),
|
||||
self.session_capabilities.clone(),
|
||||
self.agent_id.clone(),
|
||||
"Edit message - @ to include context",
|
||||
|
|
@ -444,7 +439,8 @@ fn create_editor_diff(
|
|||
cx,
|
||||
);
|
||||
editor.set_show_gutter(false, cx);
|
||||
editor.disable_inline_diagnostics();
|
||||
editor.disable_diagnostics(cx);
|
||||
editor.set_max_diagnostics_severity(DiagnosticSeverity::Off, cx);
|
||||
editor.disable_expand_excerpt_buttons(cx);
|
||||
editor.set_show_vertical_scrollbar(false, cx);
|
||||
editor.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
|
||||
|
|
@ -545,7 +541,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store,
|
||||
None,
|
||||
Arc::new(RwLock::new(SessionCapabilities::default())),
|
||||
"Test Agent".into(),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ use language_model::{ConfigurationError, ConfiguredModel, LanguageModelRegistry}
|
|||
use multi_buffer::MultiBufferRow;
|
||||
use parking_lot::Mutex;
|
||||
use project::{DisableAiSettings, Project};
|
||||
use prompt_store::{PromptBuilder, PromptStore};
|
||||
use prompt_store::PromptBuilder;
|
||||
use settings::{Settings, SettingsStore};
|
||||
|
||||
use terminal_view::{TerminalView, terminal_panel::TerminalPanel};
|
||||
|
|
@ -228,7 +228,6 @@ impl InlineAssistant {
|
|||
};
|
||||
let agent_panel = agent_panel.read(cx);
|
||||
|
||||
let prompt_store = agent_panel.prompt_store().as_ref().cloned();
|
||||
let thread_store = agent_panel.thread_store().clone();
|
||||
|
||||
let handle_assist =
|
||||
|
|
@ -240,7 +239,6 @@ impl InlineAssistant {
|
|||
cx.entity().downgrade(),
|
||||
workspace.project().downgrade(),
|
||||
thread_store,
|
||||
prompt_store,
|
||||
action.prompt.clone(),
|
||||
window,
|
||||
cx,
|
||||
|
|
@ -254,7 +252,6 @@ impl InlineAssistant {
|
|||
cx.entity().downgrade(),
|
||||
workspace.project().downgrade(),
|
||||
thread_store,
|
||||
prompt_store,
|
||||
action.prompt.clone(),
|
||||
window,
|
||||
cx,
|
||||
|
|
@ -437,7 +434,6 @@ impl InlineAssistant {
|
|||
workspace: WeakEntity<Workspace>,
|
||||
project: WeakEntity<Project>,
|
||||
thread_store: Entity<ThreadStore>,
|
||||
prompt_store: Option<Entity<PromptStore>>,
|
||||
initial_prompt: Option<String>,
|
||||
window: &mut Window,
|
||||
codegen_ranges: &[Range<Anchor>],
|
||||
|
|
@ -483,7 +479,6 @@ impl InlineAssistant {
|
|||
session_id,
|
||||
self.fs.clone(),
|
||||
thread_store.clone(),
|
||||
prompt_store.clone(),
|
||||
project.clone(),
|
||||
workspace.clone(),
|
||||
window,
|
||||
|
|
@ -574,7 +569,6 @@ impl InlineAssistant {
|
|||
workspace: WeakEntity<Workspace>,
|
||||
project: WeakEntity<Project>,
|
||||
thread_store: Entity<ThreadStore>,
|
||||
prompt_store: Option<Entity<PromptStore>>,
|
||||
initial_prompt: Option<String>,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
|
|
@ -592,7 +586,6 @@ impl InlineAssistant {
|
|||
workspace,
|
||||
project,
|
||||
thread_store,
|
||||
prompt_store,
|
||||
initial_prompt,
|
||||
window,
|
||||
&codegen_ranges,
|
||||
|
|
@ -1915,7 +1908,6 @@ pub mod evals {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store,
|
||||
None,
|
||||
Some(prompt),
|
||||
window,
|
||||
cx,
|
||||
|
|
|
|||
|
|
@ -17,7 +17,6 @@ use language_model::{LanguageModel, LanguageModelRegistry};
|
|||
use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
|
||||
use parking_lot::Mutex;
|
||||
use project::Project;
|
||||
use prompt_store::PromptStore;
|
||||
use settings::Settings;
|
||||
use std::cmp;
|
||||
use std::ops::Range;
|
||||
|
|
@ -1237,7 +1236,6 @@ impl PromptEditor<BufferCodegen> {
|
|||
session_id: Uuid,
|
||||
fs: Arc<dyn Fs>,
|
||||
thread_store: Entity<ThreadStore>,
|
||||
prompt_store: Option<Entity<PromptStore>>,
|
||||
project: WeakEntity<Project>,
|
||||
workspace: WeakEntity<Workspace>,
|
||||
window: &mut Window,
|
||||
|
|
@ -1276,8 +1274,7 @@ impl PromptEditor<BufferCodegen> {
|
|||
editor
|
||||
});
|
||||
|
||||
let mention_set = cx
|
||||
.new(|_cx| MentionSet::new(project, Some(thread_store.clone()), prompt_store.clone()));
|
||||
let mention_set = cx.new(|_cx| MentionSet::new(project, Some(thread_store.clone())));
|
||||
|
||||
let model_selector_menu_handle = PopoverMenuHandle::default();
|
||||
|
||||
|
|
@ -1393,7 +1390,6 @@ impl PromptEditor<TerminalCodegen> {
|
|||
session_id: Uuid,
|
||||
fs: Arc<dyn Fs>,
|
||||
thread_store: Entity<ThreadStore>,
|
||||
prompt_store: Option<Entity<PromptStore>>,
|
||||
project: WeakEntity<Project>,
|
||||
workspace: WeakEntity<Workspace>,
|
||||
window: &mut Window,
|
||||
|
|
@ -1427,8 +1423,7 @@ impl PromptEditor<TerminalCodegen> {
|
|||
editor
|
||||
});
|
||||
|
||||
let mention_set = cx
|
||||
.new(|_cx| MentionSet::new(project, Some(thread_store.clone()), prompt_store.clone()));
|
||||
let mention_set = cx.new(|_cx| MentionSet::new(project, Some(thread_store.clone())));
|
||||
|
||||
let model_selector_menu_handle = PopoverMenuHandle::default();
|
||||
|
||||
|
|
@ -1705,7 +1700,6 @@ mod tests {
|
|||
session_id,
|
||||
fs,
|
||||
thread_store,
|
||||
None,
|
||||
project,
|
||||
workspace.downgrade(),
|
||||
window,
|
||||
|
|
|
|||
|
|
@ -22,7 +22,6 @@ use language_model::{LanguageModelImage, LanguageModelImageExt};
|
|||
use multi_buffer::MultiBufferRow;
|
||||
use postage::stream::Stream as _;
|
||||
use project::{Project, ProjectItem, ProjectPath, Worktree};
|
||||
use prompt_store::{PromptId, PromptStore};
|
||||
use rope::Point;
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
|
|
@ -61,21 +60,15 @@ pub struct MentionImage {
|
|||
pub struct MentionSet {
|
||||
project: WeakEntity<Project>,
|
||||
thread_store: Option<Entity<ThreadStore>>,
|
||||
prompt_store: Option<Entity<PromptStore>>,
|
||||
mentions: HashMap<CreaseId, (MentionUri, MentionTask)>,
|
||||
crease_entities: HashMap<CreaseId, Entity<LoadingContext>>,
|
||||
}
|
||||
|
||||
impl MentionSet {
|
||||
pub fn new(
|
||||
project: WeakEntity<Project>,
|
||||
thread_store: Option<Entity<ThreadStore>>,
|
||||
prompt_store: Option<Entity<PromptStore>>,
|
||||
) -> Self {
|
||||
pub fn new(project: WeakEntity<Project>, thread_store: Option<Entity<ThreadStore>>) -> Self {
|
||||
Self {
|
||||
project,
|
||||
thread_store,
|
||||
prompt_store,
|
||||
mentions: HashMap::default(),
|
||||
crease_entities: HashMap::default(),
|
||||
}
|
||||
|
|
@ -153,7 +146,6 @@ impl MentionSet {
|
|||
line_range,
|
||||
..
|
||||
} => self.confirm_mention_for_symbol(abs_path, line_range, cx),
|
||||
MentionUri::Rule { id, .. } => self.confirm_mention_for_rule(id, cx),
|
||||
MentionUri::Skill {
|
||||
skill_file_path, ..
|
||||
} => self.confirm_mention_for_skill(skill_file_path, cx),
|
||||
|
|
@ -167,6 +159,7 @@ impl MentionSet {
|
|||
MentionUri::Selection {
|
||||
abs_path: Some(abs_path),
|
||||
line_range,
|
||||
..
|
||||
} => self.confirm_mention_for_symbol(abs_path, line_range, cx),
|
||||
MentionUri::Selection { abs_path: None, .. } => Task::ready(Err(anyhow!(
|
||||
"Untitled buffer selection mentions are not supported for paste"
|
||||
|
|
@ -326,7 +319,6 @@ impl MentionSet {
|
|||
line_range,
|
||||
..
|
||||
} => self.confirm_mention_for_symbol(abs_path, line_range, cx),
|
||||
MentionUri::Rule { id, .. } => self.confirm_mention_for_rule(id, cx),
|
||||
MentionUri::Skill {
|
||||
skill_file_path, ..
|
||||
} => self.confirm_mention_for_skill(skill_file_path, cx),
|
||||
|
|
@ -514,24 +506,6 @@ impl MentionSet {
|
|||
})
|
||||
}
|
||||
|
||||
fn confirm_mention_for_rule(
|
||||
&mut self,
|
||||
id: PromptId,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Task<Result<Mention>> {
|
||||
let Some(prompt_store) = self.prompt_store.as_ref() else {
|
||||
return Task::ready(Err(anyhow!("Missing prompt store")));
|
||||
};
|
||||
let prompt = prompt_store.read(cx).load(id, cx);
|
||||
cx.spawn(async move |_, _| {
|
||||
let prompt = prompt.await?;
|
||||
Ok(Mention::Text {
|
||||
content: prompt,
|
||||
tracked_buffers: Vec::new(),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn confirm_mention_for_selection(
|
||||
&mut self,
|
||||
source_range: Range<text::Anchor>,
|
||||
|
|
@ -570,6 +544,7 @@ impl MentionSet {
|
|||
let uri = MentionUri::Selection {
|
||||
abs_path: abs_path.clone(),
|
||||
line_range: line_range.clone(),
|
||||
column: None,
|
||||
};
|
||||
let crease = crease_for_mention(
|
||||
selection_name(abs_path.as_deref(), &line_range).into(),
|
||||
|
|
@ -771,7 +746,7 @@ mod tests {
|
|||
fs.insert_tree("/project", json!({"file": ""})).await;
|
||||
let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
|
||||
let thread_store = None;
|
||||
let mention_set = cx.new(|_cx| MentionSet::new(project.downgrade(), thread_store, None));
|
||||
let mention_set = cx.new(|_cx| MentionSet::new(project.downgrade(), thread_store));
|
||||
|
||||
let task = mention_set.update(cx, |mention_set, cx| {
|
||||
mention_set.confirm_mention_for_thread(acp::SessionId::new("thread-1"), cx)
|
||||
|
|
@ -797,7 +772,7 @@ mod tests {
|
|||
)
|
||||
.await;
|
||||
let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
|
||||
let mention_set = cx.new(|_cx| MentionSet::new(project.downgrade(), None, None));
|
||||
let mention_set = cx.new(|_cx| MentionSet::new(project.downgrade(), None));
|
||||
|
||||
let mention_task = mention_set.update(cx, |mention_set, cx| {
|
||||
let http_client = project.read(cx).client().http_client();
|
||||
|
|
@ -805,6 +780,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: Some(path!("/project/file.rs").into()),
|
||||
line_range: 1..=2,
|
||||
column: None,
|
||||
},
|
||||
false,
|
||||
http_client,
|
||||
|
|
|
|||
|
|
@ -33,7 +33,6 @@ use project::AgentId;
|
|||
use project::{
|
||||
CompletionIntent, InlayHint, InlayHintLabel, InlayId, Project, ProjectPath, Worktree,
|
||||
};
|
||||
use prompt_store::PromptStore;
|
||||
use rope::Point;
|
||||
use settings::Settings;
|
||||
use std::{cmp::min, fmt::Write, ops::Range, rc::Rc, sync::Arc};
|
||||
|
|
@ -453,7 +452,6 @@ impl MessageEditor {
|
|||
workspace: WeakEntity<Workspace>,
|
||||
project: WeakEntity<Project>,
|
||||
thread_store: Option<Entity<ThreadStore>>,
|
||||
prompt_store: Option<Entity<PromptStore>>,
|
||||
session_capabilities: SharedSessionCapabilities,
|
||||
agent_id: AgentId,
|
||||
placeholder: &str,
|
||||
|
|
@ -506,8 +504,7 @@ impl MessageEditor {
|
|||
|
||||
editor
|
||||
});
|
||||
let mention_set =
|
||||
cx.new(|_cx| MentionSet::new(project, thread_store.clone(), prompt_store.clone()));
|
||||
let mention_set = cx.new(|_cx| MentionSet::new(project, thread_store.clone()));
|
||||
let completion_provider = Rc::new(PromptCompletionProvider::new(
|
||||
MessageEditorCompletionDelegate {
|
||||
session_capabilities: session_capabilities.clone(),
|
||||
|
|
@ -1119,6 +1116,7 @@ impl MessageEditor {
|
|||
let mention_uri = MentionUri::Selection {
|
||||
abs_path: Some(file_path.clone()),
|
||||
line_range: line_range.clone(),
|
||||
column: None,
|
||||
};
|
||||
|
||||
let mention_text = mention_uri.as_link().to_string();
|
||||
|
|
@ -1514,6 +1512,61 @@ impl MessageEditor {
|
|||
.detach_and_log_err(cx);
|
||||
}
|
||||
|
||||
pub fn insert_skill_crease(
|
||||
&mut self,
|
||||
skill: &AvailableSkill,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let Some(workspace) = self.workspace.upgrade() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let mention_uri = MentionUri::Skill {
|
||||
name: skill.name.to_string(),
|
||||
source: skill.source.to_string(),
|
||||
skill_file_path: skill.skill_file_path.clone(),
|
||||
};
|
||||
|
||||
let link_text = mention_uri.as_link().to_string();
|
||||
let content_len = link_text.len();
|
||||
let mention_text = format!("{} ", link_text);
|
||||
let crease_text: SharedString = mention_uri.name().into();
|
||||
|
||||
let start_anchor = self.editor.update(cx, |editor, cx| {
|
||||
let snapshot = editor.buffer().read(cx).snapshot(cx);
|
||||
let buffer_snapshot = snapshot.as_singleton()?;
|
||||
let cursor = editor.selections.newest_anchor().start;
|
||||
let text_anchor = snapshot
|
||||
.anchor_to_buffer_anchor(cursor)?
|
||||
.0
|
||||
.bias_left(buffer_snapshot);
|
||||
|
||||
editor.insert(&mention_text, window, cx);
|
||||
Some(text_anchor)
|
||||
});
|
||||
|
||||
let Some(start_anchor) = start_anchor else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.mention_set
|
||||
.update(cx, |mention_set, cx| {
|
||||
mention_set.confirm_mention_completion(
|
||||
crease_text,
|
||||
start_anchor,
|
||||
content_len,
|
||||
mention_uri,
|
||||
false,
|
||||
self.editor.clone(),
|
||||
&workspace,
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
pub(crate) fn insert_selections(
|
||||
&mut self,
|
||||
selection: AgentContextSelection,
|
||||
|
|
@ -2419,7 +2472,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -2520,7 +2572,6 @@ mod tests {
|
|||
workspace_handle.clone(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
session_capabilities.clone(),
|
||||
"Claude Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -2686,7 +2737,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
session_capabilities.clone(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -2859,7 +2909,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
None,
|
||||
None,
|
||||
session_capabilities.clone(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3008,7 +3057,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
session_capabilities.clone(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3500,7 +3548,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3601,7 +3648,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3670,7 +3716,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3723,7 +3768,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3780,7 +3824,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3838,7 +3881,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3900,7 +3942,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -4060,7 +4101,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -4180,7 +4220,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
Some(thread_store.clone()),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -4259,7 +4298,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -4342,10 +4380,12 @@ mod tests {
|
|||
let first_uri = MentionUri::Selection {
|
||||
abs_path: Some(path!("/project/file.rs").into()),
|
||||
line_range: 0..=1,
|
||||
column: None,
|
||||
};
|
||||
let second_uri = MentionUri::Selection {
|
||||
abs_path: Some(path!("/project/file.rs").into()),
|
||||
line_range: 2..=3,
|
||||
column: None,
|
||||
};
|
||||
|
||||
source_message_editor.update_in(&mut cx, |message_editor, window, cx| {
|
||||
|
|
@ -4435,7 +4475,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -4503,10 +4542,12 @@ mod tests {
|
|||
let first_uri = MentionUri::Selection {
|
||||
abs_path: Some(path!("/project/file.rs").into()),
|
||||
line_range: 0..=1,
|
||||
column: None,
|
||||
};
|
||||
let second_uri = MentionUri::Selection {
|
||||
abs_path: Some(path!("/project/file.rs").into()),
|
||||
line_range: 2..=3,
|
||||
column: None,
|
||||
};
|
||||
|
||||
let buffer_len = message_editor.update_in(&mut cx, |message_editor, window, cx| {
|
||||
|
|
@ -4845,7 +4886,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -5100,7 +5140,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -5193,7 +5232,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
None,
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -5342,7 +5380,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
None,
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
|
|||
|
|
@ -11,10 +11,7 @@ use ui::{
|
|||
prelude::*,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
CycleModeSelector, ToggleProfileSelector,
|
||||
ui::{HoldForDefault, documentation_aside_side},
|
||||
};
|
||||
use crate::{CycleModeSelector, ToggleProfileSelector, ui::documentation_aside_side};
|
||||
|
||||
pub struct ModeSelector {
|
||||
connection: Rc<dyn AgentSessionModes>,
|
||||
|
|
@ -45,6 +42,10 @@ impl ModeSelector {
|
|||
|
||||
pub fn cycle_mode(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
|
||||
let all_modes = self.connection.all_modes();
|
||||
if all_modes.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let current_mode = self.connection.current_mode();
|
||||
|
||||
let current_index = all_modes
|
||||
|
|
@ -52,8 +53,9 @@ impl ModeSelector {
|
|||
.position(|mode| mode.id.0 == current_mode.0)
|
||||
.unwrap_or(0);
|
||||
|
||||
let next_index = (current_index + 1) % all_modes.len();
|
||||
self.set_mode(all_modes[next_index].id.clone(), cx);
|
||||
if let Some(next_mode) = all_modes.get((current_index + 1) % all_modes.len()) {
|
||||
self.set_mode(next_mode.id.clone(), cx);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mode(&self) -> acp::SessionModeId {
|
||||
|
|
@ -61,6 +63,9 @@ impl ModeSelector {
|
|||
}
|
||||
|
||||
pub fn set_mode(&mut self, mode: acp::SessionModeId, cx: &mut Context<Self>) {
|
||||
self.agent_server
|
||||
.set_default_mode(Some(mode.clone()), self.fs.clone(), cx);
|
||||
|
||||
let task = self.connection.set_mode(mode, cx);
|
||||
self.setting_mode = true;
|
||||
cx.notify();
|
||||
|
|
@ -88,13 +93,11 @@ impl ModeSelector {
|
|||
ContextMenu::build(window, cx, move |mut menu, _window, cx| {
|
||||
let all_modes = self.connection.all_modes();
|
||||
let current_mode = self.connection.current_mode();
|
||||
let default_mode = self.agent_server.default_mode(cx);
|
||||
|
||||
let side = documentation_aside_side(cx);
|
||||
|
||||
for mode in all_modes {
|
||||
let is_selected = &mode.id == ¤t_mode;
|
||||
let is_default = Some(&mode.id) == default_mode.as_ref();
|
||||
let entry = ContextMenuEntry::new(mode.name.clone())
|
||||
.toggleable(IconPosition::End, is_selected);
|
||||
|
||||
|
|
@ -102,13 +105,7 @@ impl ModeSelector {
|
|||
entry.documentation_aside(side, {
|
||||
let description = description.clone();
|
||||
|
||||
move |_| {
|
||||
v_flex()
|
||||
.gap_1()
|
||||
.child(Label::new(description.clone()))
|
||||
.child(HoldForDefault::new(is_default))
|
||||
.into_any_element()
|
||||
}
|
||||
move |_| Label::new(description.clone()).into_any_element()
|
||||
})
|
||||
} else {
|
||||
entry
|
||||
|
|
@ -117,21 +114,9 @@ impl ModeSelector {
|
|||
menu.push_item(entry.handler({
|
||||
let mode_id = mode.id.clone();
|
||||
let weak_self = weak_self.clone();
|
||||
move |window, cx| {
|
||||
move |_window, cx| {
|
||||
weak_self
|
||||
.update(cx, |this, cx| {
|
||||
if window.modifiers().secondary() {
|
||||
this.agent_server.set_default_mode(
|
||||
if is_default {
|
||||
None
|
||||
} else {
|
||||
Some(mode_id.clone())
|
||||
},
|
||||
this.fs.clone(),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
|
||||
this.set_mode(mode_id.clone(), cx);
|
||||
})
|
||||
.ok();
|
||||
|
|
@ -209,3 +194,110 @@ impl Render for ModeSelector {
|
|||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use acp_thread::AgentConnection;
|
||||
use fs::FakeFs;
|
||||
use gpui::{App, Task, TestAppContext};
|
||||
use parking_lot::Mutex;
|
||||
use project::{AgentId, Project};
|
||||
use std::{any::Any, cell::RefCell};
|
||||
|
||||
#[gpui::test]
|
||||
fn setting_mode_saves_selected_mode_as_default(cx: &mut TestAppContext) {
|
||||
let agent_server = Rc::new(TestAgentServer::default());
|
||||
let session_modes = Rc::new(TestSessionModes::new());
|
||||
let fs: Arc<dyn Fs> = FakeFs::new(cx.executor());
|
||||
|
||||
cx.update(|cx| {
|
||||
let session_modes: Rc<dyn AgentSessionModes> = session_modes.clone();
|
||||
let agent_server: Rc<dyn AgentServer> = agent_server.clone();
|
||||
let selector = cx.new(|_| ModeSelector::new(session_modes, agent_server, fs));
|
||||
|
||||
selector.update(cx, |selector, cx| {
|
||||
selector.set_mode(acp::SessionModeId::new("manual"), cx);
|
||||
});
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
agent_server.saved_defaults.lock().as_slice(),
|
||||
&[Some(acp::SessionModeId::new("manual"))]
|
||||
);
|
||||
assert_eq!(
|
||||
session_modes.set_modes.borrow().as_slice(),
|
||||
&[acp::SessionModeId::new("manual")]
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct TestAgentServer {
|
||||
saved_defaults: Arc<Mutex<Vec<Option<acp::SessionModeId>>>>,
|
||||
}
|
||||
|
||||
impl AgentServer for TestAgentServer {
|
||||
fn logo(&self) -> IconName {
|
||||
IconName::ZedAssistant
|
||||
}
|
||||
|
||||
fn agent_id(&self) -> AgentId {
|
||||
AgentId::new("test-agent")
|
||||
}
|
||||
|
||||
fn connect(
|
||||
&self,
|
||||
_delegate: agent_servers::AgentServerDelegate,
|
||||
_project: Entity<Project>,
|
||||
_cx: &mut App,
|
||||
) -> Task<anyhow::Result<Rc<dyn AgentConnection>>> {
|
||||
Task::ready(Err(anyhow::anyhow!("test agent server cannot connect")))
|
||||
}
|
||||
|
||||
fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
|
||||
self
|
||||
}
|
||||
|
||||
fn set_default_mode(
|
||||
&self,
|
||||
mode_id: Option<acp::SessionModeId>,
|
||||
_fs: Arc<dyn Fs>,
|
||||
_cx: &mut App,
|
||||
) {
|
||||
self.saved_defaults.lock().push(mode_id);
|
||||
}
|
||||
}
|
||||
|
||||
struct TestSessionModes {
|
||||
current_mode: RefCell<acp::SessionModeId>,
|
||||
set_modes: RefCell<Vec<acp::SessionModeId>>,
|
||||
}
|
||||
|
||||
impl TestSessionModes {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
current_mode: RefCell::new(acp::SessionModeId::new("auto")),
|
||||
set_modes: RefCell::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentSessionModes for TestSessionModes {
|
||||
fn current_mode(&self) -> acp::SessionModeId {
|
||||
self.current_mode.borrow().clone()
|
||||
}
|
||||
|
||||
fn all_modes(&self) -> Vec<acp::SessionMode> {
|
||||
vec![
|
||||
acp::SessionMode::new("auto", "Auto"),
|
||||
acp::SessionMode::new("manual", "Manual"),
|
||||
]
|
||||
}
|
||||
|
||||
fn set_mode(&self, mode: acp::SessionModeId, _cx: &mut App) -> Task<anyhow::Result<()>> {
|
||||
*self.current_mode.borrow_mut() = mode.clone();
|
||||
self.set_modes.borrow_mut().push(mode);
|
||||
Task::ready(Ok(()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,8 +22,7 @@ use util::ResultExt;
|
|||
use zed_actions::agent::OpenSettings;
|
||||
|
||||
use crate::ui::{
|
||||
HoldForDefault, ModelSelectorFooter, ModelSelectorHeader, ModelSelectorListItem,
|
||||
documentation_aside_side,
|
||||
ModelSelectorFooter, ModelSelectorHeader, ModelSelectorListItem, documentation_aside_side,
|
||||
};
|
||||
|
||||
pub type ModelSelector = Picker<ModelPickerDelegate>;
|
||||
|
|
@ -55,7 +54,7 @@ pub struct ModelPickerDelegate {
|
|||
filtered_entries: Vec<ModelPickerEntry>,
|
||||
models: Option<AgentModelList>,
|
||||
selected_index: usize,
|
||||
selected_description: Option<(usize, SharedString, bool)>,
|
||||
selected_description: Option<(usize, SharedString)>,
|
||||
selected_model: Option<AgentModelInfo>,
|
||||
favorites: HashSet<acp::ModelId>,
|
||||
_refresh_models_task: Task<()>,
|
||||
|
|
@ -182,6 +181,9 @@ impl ModelPickerDelegate {
|
|||
|
||||
let next_model = favorite_models[next_index].clone();
|
||||
|
||||
self.agent_server
|
||||
.set_default_model(Some(next_model.id.clone()), self.fs.clone(), cx);
|
||||
|
||||
self.selector
|
||||
.select_model(next_model.id.clone(), cx)
|
||||
.detach_and_log_err(cx);
|
||||
|
|
@ -277,20 +279,8 @@ impl PickerDelegate for ModelPickerDelegate {
|
|||
if let Some(ModelPickerEntry::Model(model_info, _)) =
|
||||
self.filtered_entries.get(self.selected_index)
|
||||
{
|
||||
if window.modifiers().secondary() {
|
||||
let default_model = self.agent_server.default_model(cx);
|
||||
let is_default = default_model.as_ref() == Some(&model_info.id);
|
||||
|
||||
self.agent_server.set_default_model(
|
||||
if is_default {
|
||||
None
|
||||
} else {
|
||||
Some(model_info.id.clone())
|
||||
},
|
||||
self.fs.clone(),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
self.agent_server
|
||||
.set_default_model(Some(model_info.id.clone()), self.fs.clone(), cx);
|
||||
|
||||
self.selector
|
||||
.select_model(model_info.id.clone(), cx)
|
||||
|
|
@ -322,8 +312,6 @@ impl PickerDelegate for ModelPickerDelegate {
|
|||
}
|
||||
ModelPickerEntry::Model(model_info, is_favorite) => {
|
||||
let is_selected = Some(model_info) == self.selected_model.as_ref();
|
||||
let default_model = self.agent_server.default_model(cx);
|
||||
let is_default = default_model.as_ref() == Some(&model_info.id);
|
||||
|
||||
let is_favorite = *is_favorite;
|
||||
let handle_action_click = {
|
||||
|
|
@ -350,8 +338,8 @@ impl PickerDelegate for ModelPickerDelegate {
|
|||
this.on_hover(cx.listener(move |menu, hovered, _, cx| {
|
||||
if *hovered {
|
||||
menu.delegate.selected_description =
|
||||
Some((ix, description.clone(), is_default));
|
||||
} else if matches!(menu.delegate.selected_description, Some((id, _, _)) if id == ix) {
|
||||
Some((ix, description.clone()));
|
||||
} else if matches!(menu.delegate.selected_description, Some((id, _)) if id == ix) {
|
||||
menu.delegate.selected_description = None;
|
||||
}
|
||||
cx.notify();
|
||||
|
|
@ -382,29 +370,20 @@ impl PickerDelegate for ModelPickerDelegate {
|
|||
_window: &mut Window,
|
||||
cx: &mut Context<Picker<Self>>,
|
||||
) -> Option<ui::DocumentationAside> {
|
||||
self.selected_description
|
||||
.as_ref()
|
||||
.map(|(_, description, is_default)| {
|
||||
let description = description.clone();
|
||||
let is_default = *is_default;
|
||||
self.selected_description.as_ref().map(|(_, description)| {
|
||||
let description = description.clone();
|
||||
|
||||
let side = documentation_aside_side(cx);
|
||||
let side = documentation_aside_side(cx);
|
||||
|
||||
DocumentationAside::new(
|
||||
side,
|
||||
Rc::new(move |_| {
|
||||
v_flex()
|
||||
.gap_1()
|
||||
.child(Label::new(description.clone()))
|
||||
.child(HoldForDefault::new(is_default))
|
||||
.into_any_element()
|
||||
}),
|
||||
)
|
||||
})
|
||||
DocumentationAside::new(
|
||||
side,
|
||||
Rc::new(move |_| Label::new(description.clone()).into_any_element()),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn documentation_aside_index(&self) -> Option<usize> {
|
||||
self.selected_description.as_ref().map(|(ix, _, _)| *ix)
|
||||
self.selected_description.as_ref().map(|(ix, _)| *ix)
|
||||
}
|
||||
|
||||
fn render_footer(
|
||||
|
|
@ -530,7 +509,12 @@ async fn fuzzy_search(
|
|||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gpui::TestAppContext;
|
||||
use acp_thread::AgentConnection;
|
||||
use fs::FakeFs;
|
||||
use gpui::{App, Entity, TestAppContext, VisualTestContext};
|
||||
use parking_lot::Mutex;
|
||||
use project::{AgentId, Project};
|
||||
use std::{any::Any, cell::RefCell};
|
||||
|
||||
use super::*;
|
||||
|
||||
|
|
@ -608,6 +592,138 @@ mod tests {
|
|||
.collect()
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn confirming_model_saves_selected_model_as_default(cx: &mut TestAppContext) {
|
||||
cx.update(|cx| {
|
||||
let settings_store = settings::SettingsStore::test(cx);
|
||||
cx.set_global(settings_store);
|
||||
theme_settings::init(theme::LoadThemes::JustBase, cx);
|
||||
editor::init(cx);
|
||||
});
|
||||
|
||||
let agent_server = Rc::new(TestAgentServer::default());
|
||||
let model_selector = Rc::new(TestModelSelector::new());
|
||||
let fs: Arc<dyn Fs> = FakeFs::new(cx.executor());
|
||||
|
||||
let window_handle = cx.add_window({
|
||||
let agent_server = agent_server.clone();
|
||||
let model_selector = model_selector.clone();
|
||||
move |window, cx| {
|
||||
let selector: Rc<dyn AgentModelSelector> = model_selector.clone();
|
||||
let agent_server: Rc<dyn AgentServer> = agent_server.clone();
|
||||
acp_model_selector(selector, agent_server, fs, cx.focus_handle(), window, cx)
|
||||
}
|
||||
});
|
||||
cx.run_until_parked();
|
||||
|
||||
let mut cx = VisualTestContext::from_window(window_handle.into(), cx);
|
||||
window_handle
|
||||
.update(&mut cx, |picker, window, cx| {
|
||||
picker.delegate.set_selected_index(1, window, cx);
|
||||
picker.delegate.confirm(false, window, cx);
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
agent_server.saved_defaults.lock().as_slice(),
|
||||
&[Some(acp::ModelId::new("manual"))]
|
||||
);
|
||||
assert_eq!(
|
||||
model_selector.selected_models.borrow().as_slice(),
|
||||
&[acp::ModelId::new("manual")]
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct TestAgentServer {
|
||||
saved_defaults: Arc<Mutex<Vec<Option<acp::ModelId>>>>,
|
||||
}
|
||||
|
||||
impl AgentServer for TestAgentServer {
|
||||
fn logo(&self) -> IconName {
|
||||
IconName::ZedAssistant
|
||||
}
|
||||
|
||||
fn agent_id(&self) -> AgentId {
|
||||
AgentId::new("test-agent")
|
||||
}
|
||||
|
||||
fn connect(
|
||||
&self,
|
||||
_delegate: agent_servers::AgentServerDelegate,
|
||||
_project: Entity<Project>,
|
||||
_cx: &mut App,
|
||||
) -> Task<anyhow::Result<Rc<dyn AgentConnection>>> {
|
||||
Task::ready(Err(anyhow::anyhow!("test agent server cannot connect")))
|
||||
}
|
||||
|
||||
fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
|
||||
self
|
||||
}
|
||||
|
||||
fn set_default_model(
|
||||
&self,
|
||||
model_id: Option<acp::ModelId>,
|
||||
_fs: Arc<dyn Fs>,
|
||||
_cx: &mut App,
|
||||
) {
|
||||
self.saved_defaults.lock().push(model_id);
|
||||
}
|
||||
}
|
||||
|
||||
struct TestModelSelector {
|
||||
models: Vec<AgentModelInfo>,
|
||||
selected_model: RefCell<AgentModelInfo>,
|
||||
selected_models: RefCell<Vec<acp::ModelId>>,
|
||||
}
|
||||
|
||||
impl TestModelSelector {
|
||||
fn new() -> Self {
|
||||
let models = vec![
|
||||
AgentModelInfo {
|
||||
id: acp::ModelId::new("auto"),
|
||||
name: "Auto".into(),
|
||||
description: None,
|
||||
icon: None,
|
||||
is_latest: false,
|
||||
cost: None,
|
||||
},
|
||||
AgentModelInfo {
|
||||
id: acp::ModelId::new("manual"),
|
||||
name: "Manual".into(),
|
||||
description: None,
|
||||
icon: None,
|
||||
is_latest: false,
|
||||
cost: None,
|
||||
},
|
||||
];
|
||||
|
||||
Self {
|
||||
selected_model: RefCell::new(models[0].clone()),
|
||||
models,
|
||||
selected_models: RefCell::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentModelSelector for TestModelSelector {
|
||||
fn list_models(&self, _cx: &mut App) -> Task<Result<AgentModelList>> {
|
||||
Task::ready(Ok(AgentModelList::Flat(self.models.clone())))
|
||||
}
|
||||
|
||||
fn select_model(&self, model_id: acp::ModelId, _cx: &mut App) -> Task<Result<()>> {
|
||||
self.selected_models.borrow_mut().push(model_id.clone());
|
||||
if let Some(model) = self.models.iter().find(|model| model.id == model_id) {
|
||||
*self.selected_model.borrow_mut() = model.clone();
|
||||
}
|
||||
Task::ready(Ok(()))
|
||||
}
|
||||
|
||||
fn selected_model(&self, _cx: &mut App) -> Task<Result<AgentModelInfo>> {
|
||||
Task::ready(Ok(self.selected_model.borrow().clone()))
|
||||
}
|
||||
}
|
||||
|
||||
fn get_entry_labels(entries: &[ModelPickerEntry]) -> Vec<&str> {
|
||||
entries
|
||||
.iter()
|
||||
|
|
|
|||
|
|
@ -541,7 +541,7 @@ impl PickerDelegate for ProfilePickerDelegate {
|
|||
provider.set_profile(profile_id.clone(), cx);
|
||||
|
||||
telemetry::event!(
|
||||
"agent_profile_switched",
|
||||
"Agent Profile Switched",
|
||||
profile_id = profile_id.as_str(),
|
||||
source = "picker"
|
||||
);
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ use language_models::provider::anthropic::telemetry::{
|
|||
AnthropicCompletionType, AnthropicEventData, AnthropicEventType, report_anthropic_event,
|
||||
};
|
||||
use project::Project;
|
||||
use prompt_store::{PromptBuilder, PromptStore};
|
||||
use prompt_store::PromptBuilder;
|
||||
use std::sync::Arc;
|
||||
use terminal_view::TerminalView;
|
||||
use ui::prelude::*;
|
||||
|
|
@ -64,7 +64,6 @@ impl TerminalInlineAssistant {
|
|||
workspace: WeakEntity<Workspace>,
|
||||
project: WeakEntity<Project>,
|
||||
thread_store: Entity<ThreadStore>,
|
||||
prompt_store: Option<Entity<PromptStore>>,
|
||||
initial_prompt: Option<String>,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
|
|
@ -89,7 +88,6 @@ impl TerminalInlineAssistant {
|
|||
session_id,
|
||||
self.fs.clone(),
|
||||
thread_store.clone(),
|
||||
prompt_store.clone(),
|
||||
project.clone(),
|
||||
workspace.clone(),
|
||||
window,
|
||||
|
|
|
|||
|
|
@ -63,6 +63,76 @@ impl TerminalThreadMetadata {
|
|||
pub fn main_worktree_paths(&self) -> &PathList {
|
||||
self.worktree_paths.main_worktree_path_list()
|
||||
}
|
||||
|
||||
pub fn display_title(&self) -> SharedString {
|
||||
compose_terminal_thread_title(
|
||||
self.title.as_ref(),
|
||||
self.custom_title.as_ref().map(|title| title.as_ref()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn compose_terminal_thread_title(
|
||||
terminal_title: &str,
|
||||
custom_title: Option<&str>,
|
||||
) -> SharedString {
|
||||
let Some(custom_title) = custom_title.filter(|title| !title.trim().is_empty()) else {
|
||||
return SharedString::from(terminal_title.to_string());
|
||||
};
|
||||
|
||||
if let Some(prefix) = terminal_title_prefix(terminal_title) {
|
||||
SharedString::from(format!("{prefix}{custom_title}"))
|
||||
} else {
|
||||
SharedString::from(custom_title.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn terminal_title_without_prefix(title: &str) -> &str {
|
||||
terminal_title_prefix(title)
|
||||
.map(|prefix| &title[prefix.len()..])
|
||||
.unwrap_or(title)
|
||||
}
|
||||
|
||||
fn terminal_title_prefix(title: &str) -> Option<&str> {
|
||||
let mut prefix_byte_len = 0;
|
||||
let mut saw_prefix_character = false;
|
||||
let mut saw_whitespace_after_prefix = false;
|
||||
|
||||
let mut chars = title.chars().peekable();
|
||||
while let Some(character) = chars.next() {
|
||||
if character.is_alphanumeric() {
|
||||
return None;
|
||||
}
|
||||
|
||||
if character.is_whitespace() {
|
||||
if !saw_prefix_character {
|
||||
return None;
|
||||
}
|
||||
|
||||
prefix_byte_len += character.len_utf8();
|
||||
saw_whitespace_after_prefix = true;
|
||||
|
||||
while let Some(character) = chars.peek() {
|
||||
if !character.is_whitespace() {
|
||||
break;
|
||||
}
|
||||
|
||||
prefix_byte_len += character.len_utf8();
|
||||
chars.next();
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
saw_prefix_character = true;
|
||||
prefix_byte_len += character.len_utf8();
|
||||
}
|
||||
|
||||
if saw_whitespace_after_prefix {
|
||||
Some(&title[..prefix_byte_len])
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TerminalThreadMetadataStore {
|
||||
|
|
@ -563,6 +633,32 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_terminal_title_prefix_preserves_non_alphanumeric_prefixes() {
|
||||
assert_eq!(terminal_title_prefix("✳ Thinking"), Some("✳ "));
|
||||
assert_eq!(terminal_title_prefix(">>> Thinking"), Some(">>> "));
|
||||
assert_eq!(terminal_title_prefix("⠋ Running"), Some("⠋ "));
|
||||
assert_eq!(terminal_title_prefix("* Claude"), Some("* "));
|
||||
assert_eq!(terminal_title_prefix("✳Thinking"), None);
|
||||
assert_eq!(terminal_title_prefix("Thinking"), None);
|
||||
assert_eq!(terminal_title_prefix(" Thinking"), None);
|
||||
assert_eq!(terminal_title_prefix("✳"), None);
|
||||
assert_eq!(terminal_title_prefix("v1 Running"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_terminal_thread_display_title_combines_raw_and_custom_titles() {
|
||||
let mut metadata = metadata(
|
||||
"⠋ Thinking",
|
||||
WorktreePaths::from_folder_paths(&PathList::default()),
|
||||
);
|
||||
metadata.custom_title = Some("Fix bug".into());
|
||||
assert_eq!(metadata.display_title().as_ref(), "⠋ Fix bug");
|
||||
|
||||
metadata.title = "Thinking".into();
|
||||
assert_eq!(metadata.display_title().as_ref(), "Fix bug");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_change_worktree_paths_reindexes_terminal_metadata(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
|
|
|||
|
|
@ -1831,6 +1831,7 @@ mod tests {
|
|||
thinking_effort: None,
|
||||
draft_prompt: None,
|
||||
ui_scroll_position: None,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1887,7 +1888,7 @@ mod tests {
|
|||
.unwrap();
|
||||
let mut vcx = VisualTestContext::from_window(multi_workspace.into(), cx);
|
||||
let panel = workspace_entity.update_in(&mut vcx, |workspace, window, cx| {
|
||||
cx.new(|cx| crate::AgentPanel::new(workspace, None, window, cx))
|
||||
cx.new(|cx| crate::AgentPanel::new(workspace, window, cx))
|
||||
});
|
||||
(panel, vcx)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,11 @@
|
|||
mod agent_notification;
|
||||
mod end_trial_upsell;
|
||||
mod hold_for_default;
|
||||
mod mention_crease;
|
||||
mod model_selector_components;
|
||||
mod undo_reject_toast;
|
||||
|
||||
pub use agent_notification::*;
|
||||
pub use end_trial_upsell::*;
|
||||
pub use hold_for_default::*;
|
||||
pub use mention_crease::*;
|
||||
pub use model_selector_components::*;
|
||||
pub use undo_reject_toast::*;
|
||||
|
|
|
|||
|
|
@ -103,13 +103,16 @@ impl Component for EndTrialUpsell {
|
|||
"End of Trial Upsell Banner"
|
||||
}
|
||||
|
||||
fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
|
||||
Some(
|
||||
v_flex()
|
||||
.child(EndTrialUpsell {
|
||||
dismiss_upsell: Arc::new(|_, _| {}),
|
||||
})
|
||||
.into_any_element(),
|
||||
)
|
||||
fn description() -> &'static str {
|
||||
"A banner shown in the agent panel when a user's trial has ended, \
|
||||
inviting them to upgrade to a paid plan to continue using the agent."
|
||||
}
|
||||
|
||||
fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
|
||||
v_flex()
|
||||
.child(EndTrialUpsell {
|
||||
dismiss_upsell: Arc::new(|_, _| {}),
|
||||
})
|
||||
.into_any_element()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,52 +0,0 @@
|
|||
use gpui::{App, IntoElement, Modifiers, RenderOnce, Window};
|
||||
use ui::{prelude::*, render_modifiers};
|
||||
|
||||
#[derive(IntoElement)]
|
||||
pub struct HoldForDefault {
|
||||
is_default: bool,
|
||||
more_content: bool,
|
||||
}
|
||||
|
||||
impl HoldForDefault {
|
||||
pub fn new(is_default: bool) -> Self {
|
||||
Self {
|
||||
is_default,
|
||||
more_content: true,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn more_content(mut self, more_content: bool) -> Self {
|
||||
self.more_content = more_content;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for HoldForDefault {
|
||||
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
h_flex()
|
||||
.when(self.more_content, |this| {
|
||||
this.pt_1()
|
||||
.border_t_1()
|
||||
.border_color(cx.theme().colors().border_variant)
|
||||
})
|
||||
.gap_0p5()
|
||||
.text_sm()
|
||||
.text_color(Color::Muted.color(cx))
|
||||
.child("Hold")
|
||||
.child(h_flex().flex_shrink_0().children(render_modifiers(
|
||||
&Modifiers::secondary_key(),
|
||||
PlatformStyle::platform(),
|
||||
None,
|
||||
Some(TextSize::Default.rems(cx).into()),
|
||||
false,
|
||||
)))
|
||||
.child(div().map(|this| {
|
||||
if self.is_default {
|
||||
this.child("to unset as default")
|
||||
} else {
|
||||
this.child("to set as default")
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
|
@ -1,19 +1,21 @@
|
|||
use std::{ops::RangeInclusive, path::PathBuf, time::Duration};
|
||||
use std::{path::PathBuf, time::Duration};
|
||||
|
||||
use acp_thread::MentionUri;
|
||||
use agent_client_protocol::schema as acp;
|
||||
use editor::{Editor, SelectionEffects, scroll::Autoscroll};
|
||||
use editor::Editor;
|
||||
use gpui::{
|
||||
Animation, AnimationExt, AnyView, Context, IntoElement, TaskExt, WeakEntity, Window,
|
||||
pulsating_between,
|
||||
};
|
||||
use prompt_store::PromptId;
|
||||
use language::Buffer;
|
||||
use rope::Point;
|
||||
use settings::Settings;
|
||||
use theme_settings::ThemeSettings;
|
||||
use ui::{ButtonLike, TintColor, Tooltip, prelude::*};
|
||||
use workspace::{OpenOptions, Workspace};
|
||||
|
||||
use crate::open_abs_path_at_point;
|
||||
|
||||
#[derive(IntoElement)]
|
||||
pub struct MentionCrease {
|
||||
id: ElementId,
|
||||
|
|
@ -164,12 +166,27 @@ fn open_mention_uri(
|
|||
abs_path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
open_file(
|
||||
workspace,
|
||||
abs_path,
|
||||
Some(Point::new(*line_range.start(), 0)),
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
| MentionUri::Selection {
|
||||
MentionUri::Selection {
|
||||
abs_path: Some(abs_path),
|
||||
line_range,
|
||||
column,
|
||||
} => {
|
||||
open_file(workspace, abs_path, Some(line_range), window, cx);
|
||||
open_file(
|
||||
workspace,
|
||||
abs_path,
|
||||
Some(Point::new(*line_range.start(), column.unwrap_or(0))),
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
MentionUri::Directory { abs_path } => {
|
||||
reveal_in_project_panel(workspace, abs_path, cx);
|
||||
|
|
@ -177,9 +194,6 @@ fn open_mention_uri(
|
|||
MentionUri::Thread { id, name } => {
|
||||
open_thread(workspace, id, name, window, cx);
|
||||
}
|
||||
MentionUri::Rule { id, .. } => {
|
||||
open_rule(workspace, id, window, cx);
|
||||
}
|
||||
MentionUri::Skill {
|
||||
skill_file_path, ..
|
||||
} => {
|
||||
|
|
@ -205,12 +219,15 @@ fn open_skill_file(
|
|||
) {
|
||||
// Built-in skills have synthetic paths that don't exist on disk.
|
||||
// Open a read-only buffer with the embedded content instead.
|
||||
//
|
||||
// The buffer is intentionally not registered with the project's buffer
|
||||
// store: it has no on-disk backing, isn't searchable, and `Project::
|
||||
// create_local_buffer` panics for remote projects (SSH/collab), which
|
||||
// would crash Zed if a user clicked a built-in skill mention while
|
||||
// connected to a remote project.
|
||||
if let Some(content) = agent_skills::builtin_skill_content(&skill_file_path) {
|
||||
let project = workspace.project().clone();
|
||||
let languages = project.read(cx).languages().clone();
|
||||
let buffer = project.update(cx, |project, cx| {
|
||||
project.create_local_buffer(content, None, false, cx)
|
||||
});
|
||||
let languages = workspace.project().read(cx).languages().clone();
|
||||
let buffer = cx.new(|cx| Buffer::local(content, cx));
|
||||
// Set markdown highlighting asynchronously — the buffer
|
||||
// opens instantly and the highlighting appears once loaded.
|
||||
cx.spawn({
|
||||
|
|
@ -256,40 +273,23 @@ fn open_skill_file(
|
|||
fn open_file(
|
||||
workspace: &mut Workspace,
|
||||
abs_path: PathBuf,
|
||||
line_range: Option<RangeInclusive<u32>>,
|
||||
point: Option<Point>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Workspace>,
|
||||
) {
|
||||
let project = workspace.project();
|
||||
if let Some(point) = point {
|
||||
if open_abs_path_at_point(workspace, abs_path.clone(), point, window, cx) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let project = workspace.project();
|
||||
if let Some(project_path) =
|
||||
project.update(cx, |project, cx| project.find_project_path(&abs_path, cx))
|
||||
{
|
||||
let item = workspace.open_path(project_path, None, true, window, cx);
|
||||
if let Some(line_range) = line_range {
|
||||
window
|
||||
.spawn(cx, async move |cx| {
|
||||
let Some(editor) = item.await?.downcast::<Editor>() else {
|
||||
return Ok(());
|
||||
};
|
||||
editor
|
||||
.update_in(cx, |editor, window, cx| {
|
||||
let range = Point::new(*line_range.start(), 0)
|
||||
..Point::new(*line_range.start(), 0);
|
||||
editor.change_selections(
|
||||
SelectionEffects::scroll(Autoscroll::center()),
|
||||
window,
|
||||
cx,
|
||||
|selections| selections.select_ranges(vec![range]),
|
||||
);
|
||||
})
|
||||
.ok();
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.detach_and_log_err(cx);
|
||||
} else {
|
||||
item.detach_and_log_err(cx);
|
||||
}
|
||||
workspace
|
||||
.open_path(project_path, None, true, window, cx)
|
||||
.detach_and_log_err(cx);
|
||||
} else if abs_path.exists() {
|
||||
workspace
|
||||
.open_abs_path(
|
||||
|
|
@ -356,23 +356,3 @@ fn open_thread(
|
|||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn open_rule(
|
||||
_workspace: &mut Workspace,
|
||||
id: PromptId,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Workspace>,
|
||||
) {
|
||||
use zed_actions::assistant::OpenRulesLibrary;
|
||||
|
||||
let PromptId::User { uuid } = id else {
|
||||
return;
|
||||
};
|
||||
|
||||
window.dispatch_action(
|
||||
Box::new(OpenRulesLibrary {
|
||||
prompt_to_select: Some(uuid.0),
|
||||
}),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -73,6 +73,7 @@ impl Render for ApiKeysWithProviders {
|
|||
offset: point(px(1.), px(-1.)),
|
||||
blur_radius: px(3.),
|
||||
spread_radius: px(0.),
|
||||
inset: false,
|
||||
}])
|
||||
.child(
|
||||
h_flex()
|
||||
|
|
|
|||
|
|
@ -376,7 +376,13 @@ impl Component for ZedAiOnboarding {
|
|||
"Agent New User Onboarding"
|
||||
}
|
||||
|
||||
fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
|
||||
fn description() -> &'static str {
|
||||
"The onboarding surface shown to new agent panel users, \
|
||||
guiding them through signing in to Zed and selecting a plan \
|
||||
before they can start using the agent."
|
||||
}
|
||||
|
||||
fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
|
||||
fn onboarding(
|
||||
sign_in_status: SignInStatus,
|
||||
plan: Option<Plan>,
|
||||
|
|
@ -402,41 +408,39 @@ impl Component for ZedAiOnboarding {
|
|||
.into_any_element()
|
||||
}
|
||||
|
||||
Some(
|
||||
v_flex()
|
||||
.min_w_0()
|
||||
.gap_4()
|
||||
.children(vec![
|
||||
single_example(
|
||||
"Not Signed-in",
|
||||
onboarding(SignInStatus::SignedOut, None, false),
|
||||
),
|
||||
single_example(
|
||||
"Young Account",
|
||||
onboarding(SignInStatus::SignedIn, None, true),
|
||||
),
|
||||
single_example(
|
||||
"Free Plan",
|
||||
onboarding(SignInStatus::SignedIn, Some(Plan::ZedFree), false),
|
||||
),
|
||||
single_example(
|
||||
"Pro Trial",
|
||||
onboarding(SignInStatus::SignedIn, Some(Plan::ZedProTrial), false),
|
||||
),
|
||||
single_example(
|
||||
"Pro Plan",
|
||||
onboarding(SignInStatus::SignedIn, Some(Plan::ZedPro), false),
|
||||
),
|
||||
single_example(
|
||||
"Business Plan",
|
||||
onboarding(SignInStatus::SignedIn, Some(Plan::ZedBusiness), false),
|
||||
),
|
||||
single_example(
|
||||
"Student Plan",
|
||||
onboarding(SignInStatus::SignedIn, Some(Plan::ZedStudent), false),
|
||||
),
|
||||
])
|
||||
.into_any_element(),
|
||||
)
|
||||
v_flex()
|
||||
.min_w_0()
|
||||
.gap_4()
|
||||
.children(vec![
|
||||
single_example(
|
||||
"Not Signed-in",
|
||||
onboarding(SignInStatus::SignedOut, None, false),
|
||||
),
|
||||
single_example(
|
||||
"Young Account",
|
||||
onboarding(SignInStatus::SignedIn, None, true),
|
||||
),
|
||||
single_example(
|
||||
"Free Plan",
|
||||
onboarding(SignInStatus::SignedIn, Some(Plan::ZedFree), false),
|
||||
),
|
||||
single_example(
|
||||
"Pro Trial",
|
||||
onboarding(SignInStatus::SignedIn, Some(Plan::ZedProTrial), false),
|
||||
),
|
||||
single_example(
|
||||
"Pro Plan",
|
||||
onboarding(SignInStatus::SignedIn, Some(Plan::ZedPro), false),
|
||||
),
|
||||
single_example(
|
||||
"Business Plan",
|
||||
onboarding(SignInStatus::SignedIn, Some(Plan::ZedBusiness), false),
|
||||
),
|
||||
single_example(
|
||||
"Student Plan",
|
||||
onboarding(SignInStatus::SignedIn, Some(Plan::ZedStudent), false),
|
||||
),
|
||||
])
|
||||
.into_any_element()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ pub mod batches;
|
|||
pub mod completion;
|
||||
|
||||
pub const ANTHROPIC_API_URL: &str = "https://api.anthropic.com";
|
||||
const FAST_MODE_BETA_HEADER: &str = "fast-mode-2026-02-01";
|
||||
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
|
||||
|
|
@ -121,9 +122,6 @@ impl Model {
|
|||
|
||||
let mut supported_effort_levels = Vec::new();
|
||||
if let Some(effort) = entry.capabilities.as_ref().and_then(|e| e.effort.as_ref()) {
|
||||
// The `xhigh` effort level reported by the API has no
|
||||
// corresponding `Effort` variant in the request enum, so it is
|
||||
// intentionally dropped here.
|
||||
for (level, supported) in [
|
||||
(Effort::Low, effort.low.as_ref()),
|
||||
(Effort::Medium, effort.medium.as_ref()),
|
||||
|
|
@ -147,7 +145,15 @@ impl Model {
|
|||
AnthropicModelMode::Default
|
||||
};
|
||||
|
||||
let supports_speed = matches!(entry.id.as_str(), "claude-opus-4-6" | "claude-opus-4-7");
|
||||
let supports_speed = matches!(
|
||||
entry.id.as_str(),
|
||||
"claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8"
|
||||
);
|
||||
|
||||
let mut extra_beta_headers = Vec::new();
|
||||
if supports_speed {
|
||||
extra_beta_headers.push(FAST_MODE_BETA_HEADER.to_string());
|
||||
}
|
||||
|
||||
Self {
|
||||
display_name: entry.display_name,
|
||||
|
|
@ -162,7 +168,7 @@ impl Model {
|
|||
supports_speed,
|
||||
supported_effort_levels,
|
||||
tool_override: None,
|
||||
extra_beta_headers: Vec::new(),
|
||||
extra_beta_headers,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -670,6 +676,8 @@ pub enum Effort {
|
|||
Low,
|
||||
Medium,
|
||||
High,
|
||||
#[serde(rename = "xhigh")]
|
||||
#[strum(serialize = "xhigh")]
|
||||
XHigh,
|
||||
Max,
|
||||
}
|
||||
|
|
@ -1050,6 +1058,17 @@ mod tests {
|
|||
assert_eq!(model.mode, AnthropicModelMode::Default);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_listed_enables_fast_mode_for_opus_4_8() {
|
||||
let model = Model::from_listed(listed_entry(
|
||||
"claude-opus-4-8",
|
||||
ModelCapabilities::default(),
|
||||
));
|
||||
|
||||
assert!(model.supports_speed);
|
||||
assert_eq!(model.beta_headers().as_deref(), Some(FAST_MODE_BETA_HEADER));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_listed_collects_supported_effort_levels() {
|
||||
let entry = listed_entry(
|
||||
|
|
|
|||
|
|
@ -300,6 +300,7 @@ pub fn into_anthropic(
|
|||
"low" => Some(crate::Effort::Low),
|
||||
"medium" => Some(crate::Effort::Medium),
|
||||
"high" => Some(crate::Effort::High),
|
||||
"xhigh" => Some(crate::Effort::XHigh),
|
||||
"max" => Some(crate::Effort::Max),
|
||||
_ => None,
|
||||
};
|
||||
|
|
@ -705,6 +706,44 @@ mod tests {
|
|||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_xhigh_effort_is_serialized_for_adaptive_thinking() {
|
||||
let request = LanguageModelRequest {
|
||||
messages: vec![LanguageModelRequestMessage {
|
||||
role: Role::User,
|
||||
content: vec![MessageContent::Text("Hi".to_string())],
|
||||
cache: false,
|
||||
reasoning_details: None,
|
||||
}],
|
||||
thread_id: None,
|
||||
prompt_id: None,
|
||||
intent: None,
|
||||
stop: vec![],
|
||||
temperature: None,
|
||||
tools: vec![],
|
||||
tool_choice: None,
|
||||
thinking_allowed: true,
|
||||
thinking_effort: Some("xhigh".into()),
|
||||
speed: None,
|
||||
};
|
||||
|
||||
let anthropic_request = into_anthropic(
|
||||
request,
|
||||
"claude-opus-4-8".to_string(),
|
||||
1.0,
|
||||
128_000,
|
||||
AnthropicModelMode::AdaptiveThinking,
|
||||
AnthropicPromptCacheMode::Automatic,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
anthropic_request
|
||||
.output_config
|
||||
.and_then(|config| config.effort),
|
||||
Some(crate::Effort::XHigh)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_cache_control_when_caching_disabled() {
|
||||
let request = LanguageModelRequest {
|
||||
|
|
|
|||