mirror of
https://github.com/zed-industries/zed.git
synced 2026-05-31 19:05:00 +07:00
Merge branch 'main' into fix_hover_hiding_delay_when_hover_at_fallback
This commit is contained in:
commit
a29d9b807e
313 changed files with 23514 additions and 10795 deletions
160
.agents/skills/gpui-test/SKILL.md
Normal file
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
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
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
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
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
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
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
|
||||
|
|
|
|||
3
.gitignore
vendored
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
|
||||
|
|
|
|||
1317
Cargo.lock
generated
1317
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
25
Cargo.toml
25
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,7 +559,7 @@ 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"] }
|
||||
|
|
@ -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"
|
||||
|
|
@ -888,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
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:
|
||||
|
|
|
|||
|
|
@ -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": {
|
||||
|
|
@ -1563,6 +1555,7 @@
|
|||
"context": "SkillCreator",
|
||||
"bindings": {
|
||||
"ctrl-w": "workspace::CloseWindow",
|
||||
"ctrl-enter": "skill_creator::SaveSkill",
|
||||
"tab": "skill_creator::FocusNextField",
|
||||
"shift-tab": "skill_creator::FocusPreviousField",
|
||||
},
|
||||
|
|
@ -1571,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,
|
||||
|
|
@ -1657,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",
|
||||
},
|
||||
|
|
@ -1666,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,
|
||||
|
|
@ -1583,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",
|
||||
},
|
||||
|
|
@ -1592,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",
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
)
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
@ -205,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;
|
||||
|
|
@ -342,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 {
|
||||
|
|
@ -443,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(),
|
||||
|
|
@ -526,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,
|
||||
|
|
@ -811,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 {
|
||||
|
|
|
|||
|
|
@ -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(),
|
||||
|
|
|
|||
|
|
@ -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
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>,
|
||||
|
|
@ -2669,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();
|
||||
|
|
@ -3501,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());
|
||||
|
|
@ -3592,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
|
||||
|
|
@ -3655,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| {
|
||||
|
|
@ -3732,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| {
|
||||
|
|
@ -3878,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
|
||||
|
|
@ -3991,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
|
||||
|
|
@ -4096,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
|
||||
|
|
@ -4177,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
|
||||
|
|
@ -4254,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
|
||||
|
|
@ -4351,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
|
||||
|
|
@ -4442,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
|
||||
|
|
@ -4493,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.
|
||||
|
|
@ -4596,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
|
||||
|
|
@ -4712,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
|
||||
|
|
@ -4894,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
|
||||
|
|
@ -4975,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
|
||||
|
|
@ -5059,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
|
||||
|
|
@ -5204,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;
|
||||
|
|
@ -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)]
|
||||
|
|
@ -130,6 +132,7 @@ impl SharedThread {
|
|||
thinking_effort: None,
|
||||
draft_prompt: None,
|
||||
ui_scroll_position: None,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -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);
|
||||
|
|
|
|||
25
crates/agent/src/sandboxing.rs
Normal file
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<'_> {
|
||||
|
|
@ -87,6 +93,7 @@ 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();
|
||||
|
|
@ -112,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();
|
||||
|
|
@ -136,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();
|
||||
|
|
@ -145,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:"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -173,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}}
|
||||
|
|
@ -189,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
|
||||
|
|
@ -189,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
|
||||
|
||||
|
|
@ -223,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}}.
|
||||
|
|
@ -254,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
|
||||
|
|
@ -4892,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,
|
||||
|
|
@ -4944,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,
|
||||
|
|
@ -5002,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,
|
||||
|
|
@ -5049,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,
|
||||
|
|
@ -5091,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
|
||||
|
|
@ -5226,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
|
||||
|
|
@ -5374,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
|
||||
|
|
@ -5504,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
|
||||
|
|
@ -6037,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
|
||||
|
|
@ -6163,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
|
||||
|
|
@ -6337,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,11 +4,11 @@ use crate::{
|
|||
FindPathTool, FindReferencesTool, GetCodeActionsTool, GoToDefinitionTool, GrepTool,
|
||||
ListDirectoryTool, MovePathTool, ProjectSnapshot, ReadFileTool, RenameTool, SpawnAgentTool,
|
||||
SystemPromptTemplate, Template, Templates, TerminalTool, ToolPermissionDecision,
|
||||
UpdatePlanTool, UpdateTitleTool, 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,
|
||||
|
|
@ -51,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;
|
||||
|
||||
|
|
@ -316,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();
|
||||
}
|
||||
|
|
@ -668,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>>>;
|
||||
|
||||
|
|
@ -1005,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 {
|
||||
|
|
@ -1131,6 +1123,7 @@ impl Thread {
|
|||
ui_scroll_position: None,
|
||||
running_subagents: Vec::new(),
|
||||
inherits_parent_model_settings: true,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1174,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
|
||||
|
|
@ -1449,6 +1466,7 @@ impl Thread {
|
|||
}),
|
||||
running_subagents: Vec::new(),
|
||||
inherits_parent_model_settings: true,
|
||||
sandboxed_terminal_temp_dir: db_thread.sandboxed_terminal_temp_dir,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1479,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 {
|
||||
|
|
@ -3171,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")
|
||||
|
|
|
|||
|
|
@ -167,6 +167,7 @@ mod tests {
|
|||
thinking_effort: None,
|
||||
draft_prompt: None,
|
||||
ui_scroll_position: None,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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_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);
|
||||
|
|
|
|||
|
|
@ -12,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};
|
||||
|
|
@ -620,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,
|
||||
|
|
@ -902,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 } => {
|
||||
|
|
@ -919,6 +913,9 @@ fn apply_char_operations(
|
|||
}
|
||||
}
|
||||
}
|
||||
if !edits.is_empty() {
|
||||
agent_edit_buffer(buffer, edits, action_log, cx);
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_match(
|
||||
|
|
@ -975,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));
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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)?
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -199,6 +199,56 @@ pub async fn resolve_creatable_global_skill_path(path: &Path, fs: &dyn Fs) -> Op
|
|||
}
|
||||
}
|
||||
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -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`.
|
||||
|
|
@ -41,7 +41,6 @@ pub struct SkillScopeId(pub usize);
|
|||
/// entries would fan out an equally large number of concurrent OS-level I/O
|
||||
/// operations, potentially exhausting file descriptors or stalling the app.
|
||||
const SKILL_IO_CONCURRENCY: usize = 16;
|
||||
const SKILL_READ_CHUNK_SIZE: usize = 4096;
|
||||
|
||||
/// Maximum size for a single SKILL.md file (100KB)
|
||||
pub const MAX_SKILL_FILE_SIZE: usize = 100 * 1024;
|
||||
|
|
@ -558,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,
|
||||
|
|
@ -612,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 {
|
||||
|
|
@ -627,54 +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; SKILL_READ_CHUNK_SIZE];
|
||||
loop {
|
||||
let n = reader.read(&mut chunk)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
accumulated.extend_from_slice(&chunk[..n]);
|
||||
if let Some(end) = closing_delimiter_end(&accumulated) {
|
||||
// Discard body bytes swept up in the last chunk so that e.g. multi-byte
|
||||
// graphemes split at the boundary won't cause `str::from_utf8` to fail.
|
||||
accumulated.truncate(end);
|
||||
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(),
|
||||
})
|
||||
|
|
@ -805,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::*;
|
||||
|
|
@ -1836,46 +1815,6 @@ description: A skill with no body content
|
|||
assert_eq!(skill.directory_path, PathBuf::from("/skills/my-skill"));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_load_skill_frontmatter_with_emoji_at_chunk_boundary(cx: &mut TestAppContext) {
|
||||
// We must be able to load skill frontmatter even when a
|
||||
// multipoint grapheme crosses the chunk read boundary.
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
let frontmatter = "---\nname: my-skill\ndescription: Example skill testing multipoint graphemes at chunk boundary\n---\n";
|
||||
|
||||
// Pad contents so that the emoji's first byte lands
|
||||
// at the last byte of the first read chunk.
|
||||
let padding = "a".repeat(SKILL_READ_CHUNK_SIZE - frontmatter.len() - 1);
|
||||
let content = format!("{frontmatter}{padding}✅");
|
||||
|
||||
assert!(
|
||||
(frontmatter.len() + padding.len()) < SKILL_READ_CHUNK_SIZE,
|
||||
"emoji must start before the second chunk"
|
||||
);
|
||||
assert!(
|
||||
content.len() > SKILL_READ_CHUNK_SIZE,
|
||||
"skill is longer than a chunk, so we know that the emoji crosses chunk boundaries"
|
||||
);
|
||||
|
||||
fs.insert_tree(
|
||||
"/skills",
|
||||
serde_json::json!({
|
||||
"my-skill": {
|
||||
"SKILL.md": content,
|
||||
}
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
load_skill_frontmatter(
|
||||
fs as Arc<dyn Fs>,
|
||||
PathBuf::from("/skills/my-skill/SKILL.md"),
|
||||
SkillSource::Global,
|
||||
)
|
||||
.await
|
||||
.expect("frontmatter should parse even when a multipoint grapheme such as an emoji crosses the byte chunk boundary");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_read_skill_body_returns_trimmed_body(cx: &mut TestAppContext) {
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
|
|
@ -2073,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());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -89,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
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -58,7 +58,7 @@ 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};
|
||||
|
|
@ -550,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
|
||||
|
|
@ -688,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>(),
|
||||
|
|
@ -910,6 +909,14 @@ mod tests {
|
|||
!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
|
||||
|
|
@ -933,6 +940,14 @@ mod tests {
|
|||
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 {
|
||||
|
|
|
|||
|
|
@ -42,7 +42,6 @@ use markdown::{
|
|||
};
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use project::{AgentId, AgentServerStore, Project, ProjectEntryId, ProjectPath};
|
||||
use prompt_store::{PromptId, PromptStore};
|
||||
|
||||
use crate::message_editor::SessionCapabilities;
|
||||
use crate::{AgentThreadSource, DEFAULT_THREAD_TITLE, resolve_agent_image};
|
||||
|
|
@ -75,7 +74,6 @@ use workspace::{
|
|||
path_link::sanitize_path_text,
|
||||
};
|
||||
use zed_actions::agent::{Chat, ToggleModelSelector};
|
||||
use zed_actions::assistant::OpenRulesLibrary;
|
||||
|
||||
use super::config_options::ConfigOptionsView;
|
||||
use super::entry_view_state::EntryViewState;
|
||||
|
|
@ -531,7 +529,6 @@ pub struct ConversationView {
|
|||
workspace: WeakEntity<Workspace>,
|
||||
project: Entity<Project>,
|
||||
thread_store: Option<Entity<ThreadStore>>,
|
||||
prompt_store: Option<Entity<PromptStore>>,
|
||||
pub(crate) thread_id: ThreadId,
|
||||
pub(crate) root_session_id: Option<acp::SessionId>,
|
||||
server_state: ServerState,
|
||||
|
|
@ -738,7 +735,6 @@ impl ConversationView {
|
|||
workspace: WeakEntity<Workspace>,
|
||||
project: Entity<Project>,
|
||||
thread_store: Option<Entity<ThreadStore>>,
|
||||
prompt_store: Option<Entity<PromptStore>>,
|
||||
source: AgentThreadSource,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
|
|
@ -795,7 +791,6 @@ impl ConversationView {
|
|||
workspace,
|
||||
project: project.clone(),
|
||||
thread_store,
|
||||
prompt_store,
|
||||
thread_id,
|
||||
root_session_id: resume_session_id.clone(),
|
||||
server_state: Self::initial_state(
|
||||
|
|
@ -1104,7 +1099,6 @@ impl ConversationView {
|
|||
self.workspace.clone(),
|
||||
self.project.downgrade(),
|
||||
self.thread_store.clone(),
|
||||
self.prompt_store.clone(),
|
||||
session_capabilities.clone(),
|
||||
self.agent.agent_id(),
|
||||
)
|
||||
|
|
@ -1273,7 +1267,6 @@ impl ConversationView {
|
|||
self.project.downgrade(),
|
||||
self.code_span_resolver.clone(),
|
||||
self.thread_store.clone(),
|
||||
self.prompt_store.clone(),
|
||||
initial_content,
|
||||
subscriptions,
|
||||
window,
|
||||
|
|
@ -2492,7 +2485,6 @@ impl ConversationView {
|
|||
workspace.clone(),
|
||||
project.clone(),
|
||||
None,
|
||||
None,
|
||||
session_capabilities.clone(),
|
||||
agent_name.clone(),
|
||||
"",
|
||||
|
|
@ -3721,7 +3713,6 @@ pub(crate) mod tests {
|
|||
workspace.downgrade(),
|
||||
project,
|
||||
Some(thread_store),
|
||||
None,
|
||||
AgentThreadSource::AgentPanel,
|
||||
window,
|
||||
cx,
|
||||
|
|
@ -3858,7 +3849,6 @@ pub(crate) mod tests {
|
|||
workspace.downgrade(),
|
||||
project,
|
||||
Some(thread_store),
|
||||
None,
|
||||
AgentThreadSource::AgentPanel,
|
||||
window,
|
||||
cx,
|
||||
|
|
@ -3940,7 +3930,6 @@ pub(crate) mod tests {
|
|||
workspace.downgrade(),
|
||||
project,
|
||||
Some(thread_store),
|
||||
None,
|
||||
AgentThreadSource::AgentPanel,
|
||||
window,
|
||||
cx,
|
||||
|
|
@ -4079,7 +4068,6 @@ pub(crate) mod tests {
|
|||
workspace.downgrade(),
|
||||
project.clone(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
AgentThreadSource::AgentPanel,
|
||||
window,
|
||||
cx,
|
||||
|
|
@ -4364,7 +4352,7 @@ pub(crate) mod tests {
|
|||
let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
|
||||
|
||||
let panel = workspace.update_in(cx, |workspace, window, cx| {
|
||||
let panel = cx.new(|cx| crate::AgentPanel::new(workspace, None, window, cx));
|
||||
let panel = cx.new(|cx| crate::AgentPanel::new(workspace, window, cx));
|
||||
workspace.add_panel(panel.clone(), window, cx);
|
||||
workspace.focus_panel::<crate::AgentPanel>(window, cx);
|
||||
panel
|
||||
|
|
@ -4405,7 +4393,6 @@ pub(crate) mod tests {
|
|||
workspace.downgrade(),
|
||||
project.clone(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
AgentThreadSource::AgentPanel,
|
||||
window,
|
||||
cx,
|
||||
|
|
@ -4504,7 +4491,6 @@ pub(crate) mod tests {
|
|||
workspace.downgrade(),
|
||||
project.clone(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
AgentThreadSource::AgentPanel,
|
||||
window,
|
||||
cx,
|
||||
|
|
@ -4580,7 +4566,6 @@ pub(crate) mod tests {
|
|||
workspace.downgrade(),
|
||||
project.clone(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
AgentThreadSource::AgentPanel,
|
||||
window,
|
||||
cx,
|
||||
|
|
@ -4648,7 +4633,6 @@ pub(crate) mod tests {
|
|||
workspace.downgrade(),
|
||||
project.clone(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
AgentThreadSource::AgentPanel,
|
||||
window,
|
||||
cx,
|
||||
|
|
@ -4724,7 +4708,7 @@ pub(crate) mod tests {
|
|||
let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
|
||||
|
||||
let panel = workspace1.update_in(cx, |workspace, window, cx| {
|
||||
let panel = cx.new(|cx| crate::AgentPanel::new(workspace, None, window, cx));
|
||||
let panel = cx.new(|cx| crate::AgentPanel::new(workspace, window, cx));
|
||||
workspace.add_panel(panel.clone(), window, cx);
|
||||
|
||||
// Open the dock and activate the agent panel so it's visible
|
||||
|
|
@ -4770,7 +4754,6 @@ pub(crate) mod tests {
|
|||
workspace1.downgrade(),
|
||||
project1.clone(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
AgentThreadSource::AgentPanel,
|
||||
window,
|
||||
cx,
|
||||
|
|
@ -4992,7 +4975,6 @@ pub(crate) mod tests {
|
|||
workspace.downgrade(),
|
||||
project,
|
||||
Some(thread_store),
|
||||
None,
|
||||
AgentThreadSource::AgentPanel,
|
||||
window,
|
||||
cx,
|
||||
|
|
@ -5651,7 +5633,6 @@ pub(crate) mod tests {
|
|||
workspace.downgrade(),
|
||||
project.clone(),
|
||||
Some(thread_store.clone()),
|
||||
None,
|
||||
AgentThreadSource::AgentPanel,
|
||||
window,
|
||||
cx,
|
||||
|
|
@ -8113,9 +8094,17 @@ pub(crate) mod tests {
|
|||
async fn test_permission_row_hidden_when_inline_bounds_unavailable(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let (_view, thread_view, _entry_ix, cx) =
|
||||
let (_view, thread_view, entry_ix, cx) =
|
||||
setup_pending_permission_thread("perm-no-bounds", cx).await;
|
||||
|
||||
// Pin the scroll top to the entry so it isn't treated as above the
|
||||
// viewport, forcing the unmeasured-bounds path we want to exercise.
|
||||
thread_view.read_with(cx, |view, _cx| {
|
||||
view.list_state.scroll_to(ListOffset {
|
||||
item_ix: entry_ix,
|
||||
offset_in_item: px(0.0),
|
||||
});
|
||||
});
|
||||
thread_view.update_in(cx, |view, window, cx| {
|
||||
assert!(
|
||||
view.render_main_agent_awaiting_permission(window, cx)
|
||||
|
|
@ -8176,8 +8165,8 @@ pub(crate) mod tests {
|
|||
let (_view, thread_view, entry_ix, cx) =
|
||||
setup_pending_permission_thread("perm-scroll", cx).await;
|
||||
|
||||
// Start off-screen below the viewport — row visible because the item
|
||||
// has bounds that do not intersect the viewport.
|
||||
// Start off-screen below the viewport. The row is visible because the
|
||||
// item has bounds that do not intersect the viewport.
|
||||
draw_thread_list_at(
|
||||
&thread_view,
|
||||
ListOffset {
|
||||
|
|
@ -8221,6 +8210,69 @@ pub(crate) mod tests {
|
|||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_permission_row_shown_when_inline_prompt_is_above_viewport(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
init_test(cx);
|
||||
|
||||
let (_view, thread_view, entry_ix, cx) =
|
||||
setup_pending_permission_thread("perm-above", cx).await;
|
||||
|
||||
let thread = thread_view.read_with(cx, |view, _cx| view.thread.clone());
|
||||
thread.update(cx, |thread, cx| {
|
||||
let result = thread.handle_session_update(
|
||||
acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
|
||||
"More content".into(),
|
||||
)),
|
||||
cx,
|
||||
);
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"following assistant message should be accepted"
|
||||
);
|
||||
});
|
||||
|
||||
draw_thread_list_at(
|
||||
&thread_view,
|
||||
ListOffset {
|
||||
item_ix: entry_ix + 1,
|
||||
offset_in_item: px(0.0),
|
||||
},
|
||||
cx,
|
||||
);
|
||||
thread_view.read_with(cx, |view, _cx| {
|
||||
assert!(
|
||||
entry_ix < view.list_state.logical_scroll_top().item_ix,
|
||||
"The tool call entry should be above the logical scroll top"
|
||||
);
|
||||
});
|
||||
thread_view.update_in(cx, |view, window, cx| {
|
||||
assert!(
|
||||
view.render_main_agent_awaiting_permission(window, cx)
|
||||
.is_some(),
|
||||
"Floating row should be visible when the inline prompt is above the viewport"
|
||||
);
|
||||
});
|
||||
|
||||
// Scrolling up to the entry brings it back into view.
|
||||
draw_thread_list_at(
|
||||
&thread_view,
|
||||
ListOffset {
|
||||
item_ix: entry_ix,
|
||||
offset_in_item: px(0.0),
|
||||
},
|
||||
cx,
|
||||
);
|
||||
thread_view.update_in(cx, |view, window, cx| {
|
||||
assert!(
|
||||
view.render_main_agent_awaiting_permission(window, cx)
|
||||
.is_none(),
|
||||
"Floating row should disappear after scrolling brings the inline prompt into view"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_permission_row_disappears_when_authorized(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
|
@ -8556,7 +8608,6 @@ pub(crate) mod tests {
|
|||
workspace.downgrade(),
|
||||
project,
|
||||
Some(thread_store),
|
||||
None,
|
||||
AgentThreadSource::AgentPanel,
|
||||
window,
|
||||
cx,
|
||||
|
|
|
|||
|
|
@ -8,7 +8,8 @@ use agent_client_protocol::schema as acp;
|
|||
use std::cell::RefCell;
|
||||
|
||||
use acp_thread::{ContentBlock, PlanEntry};
|
||||
use agent::{SkillLoadingError, SkillLoadingErrorsUpdated, UserAgentsMd};
|
||||
use agent::{SkillLoadingError, SkillLoadingErrorsUpdated};
|
||||
use agent_settings::UserAgentsMd;
|
||||
use cloud_api_types::{SubmitAgentThreadFeedbackBody, SubmitAgentThreadFeedbackCommentsBody};
|
||||
use editor::actions::OpenExcerpts;
|
||||
use feature_flags::AcpBetaFeatureFlag;
|
||||
|
|
@ -682,7 +683,6 @@ impl ThreadView {
|
|||
project: WeakEntity<Project>,
|
||||
code_span_resolver: AgentCodeSpanResolver,
|
||||
thread_store: Option<Entity<ThreadStore>>,
|
||||
prompt_store: Option<Entity<PromptStore>>,
|
||||
initial_content: Option<AgentInitialContent>,
|
||||
mut subscriptions: Vec<Subscription>,
|
||||
window: &mut Window,
|
||||
|
|
@ -702,7 +702,6 @@ impl ThreadView {
|
|||
workspace.clone(),
|
||||
project.clone(),
|
||||
thread_store,
|
||||
prompt_store,
|
||||
session_capabilities.clone(),
|
||||
agent_id.clone(),
|
||||
&placeholder,
|
||||
|
|
@ -3046,15 +3045,6 @@ impl ThreadView {
|
|||
)
|
||||
}
|
||||
|
||||
/// Returns true when the entry has been measured and sits entirely below
|
||||
/// the current viewport.
|
||||
fn entry_is_below_viewport(&self, entry_ix: usize) -> bool {
|
||||
let viewport_bounds = self.list_state.viewport_bounds();
|
||||
self.list_state
|
||||
.bounds_for_item(entry_ix)
|
||||
.is_some_and(|entry_bounds| entry_bounds.top() >= viewport_bounds.bottom())
|
||||
}
|
||||
|
||||
pub(crate) fn render_main_agent_awaiting_permission(
|
||||
&self,
|
||||
window: &Window,
|
||||
|
|
@ -3072,9 +3062,13 @@ impl ThreadView {
|
|||
let thread = self.thread.read(cx);
|
||||
let (entry_ix, tool_call) = thread.tool_call(&tool_call_id)?;
|
||||
|
||||
if !self.entry_is_below_viewport(entry_ix) {
|
||||
let scroll_icon = if self.list_state.item_is_above_viewport(entry_ix)? {
|
||||
IconName::ArrowUp
|
||||
} else if self.list_state.item_is_below_viewport(entry_ix)? {
|
||||
IconName::ArrowDown
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let focus_handle = self.focus_handle(cx);
|
||||
|
||||
|
|
@ -3117,7 +3111,7 @@ impl ThreadView {
|
|||
Button::new("main-agent-permission-scroll-to", "Scroll")
|
||||
.label_size(LabelSize::Small)
|
||||
.end_icon(
|
||||
Icon::new(IconName::ArrowDown)
|
||||
Icon::new(scroll_icon)
|
||||
.size(IconSize::XSmall)
|
||||
.color(Color::Default),
|
||||
)
|
||||
|
|
@ -9463,17 +9457,15 @@ impl ThreadView {
|
|||
.map(|name| name.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "one folder".to_string());
|
||||
|
||||
let description = format!(
|
||||
"This agent only operates on \"{}\". Other folders in this workspace are not accessible to it.",
|
||||
active_dir
|
||||
);
|
||||
|
||||
Some(
|
||||
Callout::new()
|
||||
.severity(Severity::Warning)
|
||||
.icon(IconName::Warning)
|
||||
.title("External Agents currently don't support multi-root workspaces")
|
||||
.description(description)
|
||||
.title("This agent doesn't currently support multi-root workspaces")
|
||||
.description(format!(
|
||||
"It currently only operates by default on \"{}\".",
|
||||
active_dir
|
||||
))
|
||||
.border_position(ui::BorderPosition::Bottom)
|
||||
.dismiss_action(
|
||||
IconButton::new("dismiss-multi-root-callout", IconName::Close)
|
||||
|
|
@ -10015,17 +10007,6 @@ pub(crate) fn open_link(
|
|||
});
|
||||
}
|
||||
}
|
||||
MentionUri::Rule { id, .. } => {
|
||||
let PromptId::User { uuid } = id else {
|
||||
return;
|
||||
};
|
||||
window.dispatch_action(
|
||||
Box::new(OpenRulesLibrary {
|
||||
prompt_to_select: Some(uuid.0),
|
||||
}),
|
||||
cx,
|
||||
)
|
||||
}
|
||||
MentionUri::Fetch { url } => {
|
||||
cx.open_url(url.as_str());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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),
|
||||
|
|
@ -327,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),
|
||||
|
|
@ -515,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>,
|
||||
|
|
@ -773,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)
|
||||
|
|
@ -799,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();
|
||||
|
|
|
|||
|
|
@ -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(),
|
||||
|
|
@ -2475,7 +2472,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -2576,7 +2572,6 @@ mod tests {
|
|||
workspace_handle.clone(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
session_capabilities.clone(),
|
||||
"Claude Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -2742,7 +2737,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
session_capabilities.clone(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -2915,7 +2909,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
None,
|
||||
None,
|
||||
session_capabilities.clone(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3064,7 +3057,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
session_capabilities.clone(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3556,7 +3548,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3657,7 +3648,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3726,7 +3716,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3779,7 +3768,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3836,7 +3824,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3894,7 +3881,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -3956,7 +3942,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -4116,7 +4101,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
thread_store.clone(),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -4236,7 +4220,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
Some(thread_store.clone()),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -4315,7 +4298,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -4493,7 +4475,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -4905,7 +4886,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -5160,7 +5140,6 @@ mod tests {
|
|||
workspace_handle,
|
||||
project.downgrade(),
|
||||
Some(thread_store),
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -5253,7 +5232,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
None,
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
@ -5402,7 +5380,6 @@ mod tests {
|
|||
workspace.downgrade(),
|
||||
project.downgrade(),
|
||||
None,
|
||||
None,
|
||||
Default::default(),
|
||||
"Test Agent".into(),
|
||||
"Test",
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ use gpui::{
|
|||
pulsating_between,
|
||||
};
|
||||
use language::Buffer;
|
||||
use prompt_store::PromptId;
|
||||
use rope::Point;
|
||||
use settings::Settings;
|
||||
use theme_settings::ThemeSettings;
|
||||
|
|
@ -195,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, ..
|
||||
} => {
|
||||
|
|
@ -360,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,
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -122,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()),
|
||||
|
|
@ -148,7 +145,10 @@ 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 {
|
||||
|
|
@ -676,6 +676,8 @@ pub enum Effort {
|
|||
Low,
|
||||
Medium,
|
||||
High,
|
||||
#[serde(rename = "xhigh")]
|
||||
#[strum(serialize = "xhigh")]
|
||||
XHigh,
|
||||
Max,
|
||||
}
|
||||
|
|
@ -1056,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 {
|
||||
|
|
|
|||
|
|
@ -12,9 +12,12 @@ mod real_implementation {
|
|||
|
||||
impl Default for EchoCanceller {
|
||||
fn default() -> Self {
|
||||
Self(Arc::new(Mutex::new(apm::AudioProcessingModule::new(
|
||||
true, false, false, false,
|
||||
))))
|
||||
// Sound-effect playback only feeds this APM through `process_reverse_stream`
|
||||
// for AEC reference; gain/HPF/NS would be no-ops here, so we keep the
|
||||
// original (echo only) configuration via the legacy flag form.
|
||||
Self(Arc::new(Mutex::new(
|
||||
apm::AudioProcessingModule::from_flags(true, false, false, false),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ pub enum BedrockAdaptiveThinkingEffort {
|
|||
Medium,
|
||||
#[default]
|
||||
High,
|
||||
XHigh,
|
||||
Max,
|
||||
}
|
||||
|
||||
|
|
@ -17,6 +18,7 @@ impl BedrockAdaptiveThinkingEffort {
|
|||
Self::Low => "low",
|
||||
Self::Medium => "medium",
|
||||
Self::High => "high",
|
||||
Self::XHigh => "xhigh",
|
||||
Self::Max => "max",
|
||||
}
|
||||
}
|
||||
|
|
@ -91,6 +93,13 @@ pub enum Model {
|
|||
alias = "claude-opus-4-7-thinking-latest"
|
||||
)]
|
||||
ClaudeOpus4_7,
|
||||
#[serde(
|
||||
rename = "claude-opus-4-8",
|
||||
alias = "claude-opus-4-8-latest",
|
||||
alias = "claude-opus-4-8-thinking",
|
||||
alias = "claude-opus-4-8-thinking-latest"
|
||||
)]
|
||||
ClaudeOpus4_8,
|
||||
#[serde(
|
||||
rename = "claude-sonnet-4-6",
|
||||
alias = "claude-sonnet-4-6-latest",
|
||||
|
|
@ -210,7 +219,9 @@ impl Model {
|
|||
}
|
||||
|
||||
pub fn from_id(id: &str) -> anyhow::Result<Self> {
|
||||
if id.starts_with("claude-opus-4-7") {
|
||||
if id.starts_with("claude-opus-4-8") {
|
||||
Ok(Self::ClaudeOpus4_8)
|
||||
} else if id.starts_with("claude-opus-4-7") {
|
||||
Ok(Self::ClaudeOpus4_7)
|
||||
} else if id.starts_with("claude-opus-4-6") {
|
||||
Ok(Self::ClaudeOpus4_6)
|
||||
|
|
@ -240,6 +251,7 @@ impl Model {
|
|||
Self::ClaudeOpus4_5 => "claude-opus-4-5",
|
||||
Self::ClaudeOpus4_6 => "claude-opus-4-6",
|
||||
Self::ClaudeOpus4_7 => "claude-opus-4-7",
|
||||
Self::ClaudeOpus4_8 => "claude-opus-4-8",
|
||||
Self::ClaudeSonnet4_6 => "claude-sonnet-4-6",
|
||||
Self::Llama4Scout17B => "llama-4-scout-17b",
|
||||
Self::Llama4Maverick17B => "llama-4-maverick-17b",
|
||||
|
|
@ -290,6 +302,7 @@ impl Model {
|
|||
Self::ClaudeOpus4_5 => "anthropic.claude-opus-4-5-20251101-v1:0",
|
||||
Self::ClaudeOpus4_6 => "anthropic.claude-opus-4-6-v1",
|
||||
Self::ClaudeOpus4_7 => "anthropic.claude-opus-4-7",
|
||||
Self::ClaudeOpus4_8 => "anthropic.claude-opus-4-8",
|
||||
Self::ClaudeSonnet4_6 => "anthropic.claude-sonnet-4-6",
|
||||
Self::Llama4Scout17B => "meta.llama4-scout-17b-instruct-v1:0",
|
||||
Self::Llama4Maverick17B => "meta.llama4-maverick-17b-instruct-v1:0",
|
||||
|
|
@ -340,6 +353,7 @@ impl Model {
|
|||
Self::ClaudeOpus4_5 => "Claude Opus 4.5",
|
||||
Self::ClaudeOpus4_6 => "Claude Opus 4.6",
|
||||
Self::ClaudeOpus4_7 => "Claude Opus 4.7",
|
||||
Self::ClaudeOpus4_8 => "Claude Opus 4.8",
|
||||
Self::ClaudeSonnet4_6 => "Claude Sonnet 4.6",
|
||||
Self::Llama4Scout17B => "Llama 4 Scout 17B",
|
||||
Self::Llama4Maverick17B => "Llama 4 Maverick 17B",
|
||||
|
|
@ -391,6 +405,7 @@ impl Model {
|
|||
| Self::ClaudeOpus4_5
|
||||
| Self::ClaudeOpus4_6
|
||||
| Self::ClaudeOpus4_7
|
||||
| Self::ClaudeOpus4_8
|
||||
| Self::ClaudeSonnet4_6 => 1_000_000,
|
||||
Self::ClaudeOpus4_1 => 200_000,
|
||||
Self::Llama4Scout17B | Self::Llama4Maverick17B => 128_000,
|
||||
|
|
@ -425,7 +440,7 @@ impl Model {
|
|||
| Self::ClaudeOpus4_5
|
||||
| Self::ClaudeSonnet4_6 => 64_000,
|
||||
Self::ClaudeOpus4_1 => 32_000,
|
||||
Self::ClaudeOpus4_6 | Self::ClaudeOpus4_7 => 128_000,
|
||||
Self::ClaudeOpus4_6 | Self::ClaudeOpus4_7 | Self::ClaudeOpus4_8 => 128_000,
|
||||
Self::Llama4Scout17B
|
||||
| Self::Llama4Maverick17B
|
||||
| Self::Gemma3_4B
|
||||
|
|
@ -464,6 +479,7 @@ impl Model {
|
|||
| Self::ClaudeOpus4_5
|
||||
| Self::ClaudeOpus4_6
|
||||
| Self::ClaudeOpus4_7
|
||||
| Self::ClaudeOpus4_8
|
||||
| Self::ClaudeSonnet4_6 => 1.0,
|
||||
Self::Custom {
|
||||
default_temperature,
|
||||
|
|
@ -482,6 +498,7 @@ impl Model {
|
|||
| Self::ClaudeOpus4_5
|
||||
| Self::ClaudeOpus4_6
|
||||
| Self::ClaudeOpus4_7
|
||||
| Self::ClaudeOpus4_8
|
||||
| Self::ClaudeSonnet4_6 => true,
|
||||
Self::NovaLite | Self::NovaPro | Self::NovaPremier | Self::Nova2Lite => true,
|
||||
Self::MistralLarge3 | Self::PixtralLarge | Self::MagistralSmall => true,
|
||||
|
|
@ -513,6 +530,7 @@ impl Model {
|
|||
| Self::ClaudeOpus4_5
|
||||
| Self::ClaudeOpus4_6
|
||||
| Self::ClaudeOpus4_7
|
||||
| Self::ClaudeOpus4_8
|
||||
| Self::ClaudeSonnet4_6 => true,
|
||||
Self::NovaLite | Self::NovaPro => true,
|
||||
Self::PixtralLarge => true,
|
||||
|
|
@ -531,6 +549,7 @@ impl Model {
|
|||
| Self::ClaudeOpus4_5
|
||||
| Self::ClaudeOpus4_6
|
||||
| Self::ClaudeOpus4_7
|
||||
| Self::ClaudeOpus4_8
|
||||
| Self::ClaudeSonnet4_6 => true,
|
||||
Self::Custom {
|
||||
cache_configuration,
|
||||
|
|
@ -550,6 +569,7 @@ impl Model {
|
|||
| Self::ClaudeOpus4_5
|
||||
| Self::ClaudeOpus4_6
|
||||
| Self::ClaudeOpus4_7
|
||||
| Self::ClaudeOpus4_8
|
||||
| Self::ClaudeSonnet4_6
|
||||
)
|
||||
}
|
||||
|
|
@ -557,10 +577,14 @@ impl Model {
|
|||
pub fn supports_adaptive_thinking(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::ClaudeOpus4_6 | Self::ClaudeOpus4_7 | Self::ClaudeSonnet4_6
|
||||
Self::ClaudeOpus4_6 | Self::ClaudeOpus4_7 | Self::ClaudeOpus4_8 | Self::ClaudeSonnet4_6
|
||||
)
|
||||
}
|
||||
|
||||
pub fn supports_xhigh_adaptive_thinking(&self) -> bool {
|
||||
matches!(self, Self::ClaudeOpus4_8)
|
||||
}
|
||||
|
||||
pub fn thinking_mode(&self) -> BedrockModelMode {
|
||||
if self.supports_adaptive_thinking() {
|
||||
BedrockModelMode::AdaptiveThinking {
|
||||
|
|
@ -590,6 +614,7 @@ impl Model {
|
|||
| Self::ClaudeOpus4_5
|
||||
| Self::ClaudeOpus4_6
|
||||
| Self::ClaudeOpus4_7
|
||||
| Self::ClaudeOpus4_8
|
||||
| Self::ClaudeSonnet4_6
|
||||
| Self::Nova2Lite
|
||||
);
|
||||
|
|
@ -650,6 +675,7 @@ impl Model {
|
|||
| Self::ClaudeOpus4_5
|
||||
| Self::ClaudeOpus4_6
|
||||
| Self::ClaudeOpus4_7
|
||||
| Self::ClaudeOpus4_8
|
||||
| Self::ClaudeSonnet4_6
|
||||
| Self::Nova2Lite,
|
||||
"global",
|
||||
|
|
@ -667,6 +693,7 @@ impl Model {
|
|||
| Self::ClaudeOpus4_5
|
||||
| Self::ClaudeOpus4_6
|
||||
| Self::ClaudeOpus4_7
|
||||
| Self::ClaudeOpus4_8
|
||||
| Self::ClaudeSonnet4_6
|
||||
| Self::Llama4Scout17B
|
||||
| Self::Llama4Maverick17B
|
||||
|
|
@ -689,6 +716,7 @@ impl Model {
|
|||
| Self::ClaudeSonnet4_5
|
||||
| Self::ClaudeOpus4_6
|
||||
| Self::ClaudeOpus4_7
|
||||
| Self::ClaudeOpus4_8
|
||||
| Self::ClaudeSonnet4_6
|
||||
| Self::NovaLite
|
||||
| Self::NovaPro
|
||||
|
|
@ -702,6 +730,7 @@ impl Model {
|
|||
| Self::ClaudeSonnet4_5
|
||||
| Self::ClaudeOpus4_6
|
||||
| Self::ClaudeOpus4_7
|
||||
| Self::ClaudeOpus4_8
|
||||
| Self::ClaudeSonnet4_6,
|
||||
"au",
|
||||
) => Ok(format!("{}.{}", region_group, model_id)),
|
||||
|
|
@ -779,6 +808,10 @@ mod tests {
|
|||
Model::ClaudeOpus4_7.cross_region_inference_id("eu-west-1", false)?,
|
||||
"eu.anthropic.claude-opus-4-7"
|
||||
);
|
||||
assert_eq!(
|
||||
Model::ClaudeOpus4_8.cross_region_inference_id("eu-west-1", false)?,
|
||||
"eu.anthropic.claude-opus-4-8"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -813,6 +846,10 @@ mod tests {
|
|||
Model::ClaudeOpus4_7.cross_region_inference_id("ap-southeast-2", false)?,
|
||||
"au.anthropic.claude-opus-4-7"
|
||||
);
|
||||
assert_eq!(
|
||||
Model::ClaudeOpus4_8.cross_region_inference_id("ap-southeast-2", false)?,
|
||||
"au.anthropic.claude-opus-4-8"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -877,6 +914,10 @@ mod tests {
|
|||
Model::ClaudeOpus4_7.cross_region_inference_id("us-east-1", true)?,
|
||||
"global.anthropic.claude-opus-4-7"
|
||||
);
|
||||
assert_eq!(
|
||||
Model::ClaudeOpus4_8.cross_region_inference_id("us-east-1", true)?,
|
||||
"global.anthropic.claude-opus-4-8"
|
||||
);
|
||||
assert_eq!(
|
||||
Model::Nova2Lite.cross_region_inference_id("us-east-1", true)?,
|
||||
"global.amazon.nova-2-lite-v1:0"
|
||||
|
|
@ -978,6 +1019,9 @@ mod tests {
|
|||
assert!(!Model::ClaudeSonnet4.supports_adaptive_thinking());
|
||||
assert!(Model::ClaudeOpus4_6.supports_adaptive_thinking());
|
||||
assert!(Model::ClaudeSonnet4_6.supports_adaptive_thinking());
|
||||
assert!(!Model::ClaudeOpus4_7.supports_xhigh_adaptive_thinking());
|
||||
assert!(Model::ClaudeOpus4_8.supports_xhigh_adaptive_thinking());
|
||||
assert_eq!(BedrockAdaptiveThinkingEffort::XHigh.as_str(), "xhigh");
|
||||
|
||||
assert_eq!(
|
||||
Model::ClaudeSonnet4.thinking_mode(),
|
||||
|
|
|
|||
|
|
@ -143,7 +143,7 @@ pub enum ChannelEvent {
|
|||
|
||||
impl EventEmitter<ChannelEvent> for ChannelStore {}
|
||||
|
||||
enum OpenEntityHandle<E> {
|
||||
enum OpenEntityHandle<E: 'static> {
|
||||
Open(WeakEntity<E>),
|
||||
Loading(Shared<Task<Result<Entity<E>, Arc<anyhow::Error>>>>),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -333,6 +333,9 @@ impl Status {
|
|||
struct ClientState {
|
||||
credentials: Option<Credentials>,
|
||||
status: (watch::Sender<Status>, watch::Receiver<Status>),
|
||||
/// Bumped each time the cloud websocket finishes its handshake. Starts at `0` so
|
||||
/// subscribers can distinguish "no connection yet" from a real reconnect.
|
||||
cloud_connection_id: (watch::Sender<u64>, watch::Receiver<u64>),
|
||||
_reconnect_task: Option<Task<()>>,
|
||||
_cloud_connection_task: Option<Task<()>>,
|
||||
}
|
||||
|
|
@ -435,6 +438,7 @@ impl Default for ClientState {
|
|||
Self {
|
||||
credentials: None,
|
||||
status: watch::channel_with(Status::SignedOut),
|
||||
cloud_connection_id: watch::channel_with(0),
|
||||
_reconnect_task: None,
|
||||
_cloud_connection_task: None,
|
||||
}
|
||||
|
|
@ -668,6 +672,14 @@ impl Client {
|
|||
self.state.read().status.1.clone()
|
||||
}
|
||||
|
||||
/// Watches successful cloud websocket reconnections.
|
||||
///
|
||||
/// The value is bumped each time the websocket handshake completes. The
|
||||
/// initial `0` means no reconnection yet.
|
||||
pub fn cloud_connection_id(&self) -> watch::Receiver<u64> {
|
||||
self.state.read().cloud_connection_id.1.clone()
|
||||
}
|
||||
|
||||
fn set_status(self: &Arc<Self>, status: Status, cx: &AsyncApp) {
|
||||
log::info!("set status on client {}: {:?}", self.id(), status);
|
||||
let mut state = self.state.write();
|
||||
|
|
@ -1006,6 +1018,12 @@ impl Client {
|
|||
|
||||
let (mut messages, _cloud_io_task) = cx.update(|cx| connection.spawn(cx));
|
||||
|
||||
{
|
||||
let mut state = self.state.write();
|
||||
let mut cloud_connection_id = state.cloud_connection_id.0.borrow_mut();
|
||||
*cloud_connection_id = cloud_connection_id.saturating_add(1);
|
||||
}
|
||||
|
||||
while let Some(message) = messages.next().await {
|
||||
if let Some(message) = message.log_err() {
|
||||
self.handle_message_to_client(message, cx);
|
||||
|
|
|
|||
|
|
@ -56,6 +56,10 @@ pub fn skills_docs(cx: &App) -> String {
|
|||
format!("{server_url}/docs/ai/skills", server_url = server_url(cx))
|
||||
}
|
||||
|
||||
pub fn rules_docs(cx: &App) -> String {
|
||||
format!("{server_url}/docs/ai/rules", server_url = server_url(cx))
|
||||
}
|
||||
|
||||
/// Returns the URL to Zed's ACP registry blog post.
|
||||
pub fn acp_registry_blog(cx: &App) -> String {
|
||||
format!(
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ edition.workspace = true
|
|||
name = "collab"
|
||||
version = "0.44.0"
|
||||
publish.workspace = true
|
||||
license = "AGPL-3.0-or-later"
|
||||
license = "GPL-3.0-or-later"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
../../LICENSE-AGPL
|
||||
|
|
@ -695,26 +695,69 @@ impl PickerDelegate for CommandPaletteDelegate {
|
|||
}
|
||||
|
||||
pub fn humanize_action_name(name: &str) -> String {
|
||||
let capacity = name.len() + name.chars().filter(|c| c.is_uppercase()).count();
|
||||
let chars = name.chars().collect::<Vec<_>>();
|
||||
let capacity = name.len() + chars.iter().filter(|c| c.is_uppercase()).count();
|
||||
let mut result = String::with_capacity(capacity);
|
||||
for char in name.chars() {
|
||||
let mut index = 0;
|
||||
|
||||
while index < chars.len() {
|
||||
let char = chars[index];
|
||||
if char == ':' {
|
||||
if result.ends_with(':') {
|
||||
result.push(' ');
|
||||
} else {
|
||||
result.push(':');
|
||||
}
|
||||
index += 1;
|
||||
} else if char == '_' {
|
||||
result.push(' ');
|
||||
index += 1;
|
||||
} else if char.is_uppercase() {
|
||||
if !result.ends_with(' ') {
|
||||
result.push(' ');
|
||||
let start = index;
|
||||
index += 1;
|
||||
while chars
|
||||
.get(index)
|
||||
.is_some_and(|next_char| next_char.is_uppercase())
|
||||
{
|
||||
index += 1;
|
||||
}
|
||||
|
||||
let uppercase_run = &chars[start..index];
|
||||
if uppercase_run.len() > 1 {
|
||||
let split_before_last = chars
|
||||
.get(index)
|
||||
.is_some_and(|next_char| next_char.is_lowercase());
|
||||
let acronym_end = if split_before_last {
|
||||
uppercase_run.len() - 1
|
||||
} else {
|
||||
uppercase_run.len()
|
||||
};
|
||||
|
||||
if acronym_end > 0 {
|
||||
if !result.ends_with(' ') {
|
||||
result.push(' ');
|
||||
}
|
||||
result.extend(&uppercase_run[..acronym_end]);
|
||||
}
|
||||
|
||||
if split_before_last {
|
||||
if !result.ends_with(' ') {
|
||||
result.push(' ');
|
||||
}
|
||||
result.extend(uppercase_run[acronym_end].to_lowercase());
|
||||
}
|
||||
} else {
|
||||
if !result.ends_with(' ') {
|
||||
result.push(' ');
|
||||
}
|
||||
result.extend(char.to_lowercase());
|
||||
}
|
||||
result.extend(char.to_lowercase());
|
||||
} else {
|
||||
result.push(char);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
|
|
@ -753,6 +796,19 @@ mod tests {
|
|||
humanize_action_name("go_to_line::Deploy"),
|
||||
"go to line: deploy"
|
||||
);
|
||||
assert_eq!(
|
||||
humanize_action_name("agent::OpenGlobalAGENTS.mdRules"),
|
||||
"agent: open global AGENTS.md rules"
|
||||
);
|
||||
assert_eq!(
|
||||
humanize_action_name("agent::OpenProjectAGENTS.mdRules"),
|
||||
"agent: open project AGENTS.md rules"
|
||||
);
|
||||
assert_eq!(humanize_action_name("editor::OpenURL"), "editor: open URL");
|
||||
assert_eq!(
|
||||
humanize_action_name("editor::OpenURLParser"),
|
||||
"editor: open URL parser"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -48,9 +48,9 @@ pub fn register_component<T: Component>() {
|
|||
let id = T::id();
|
||||
let metadata = ComponentMetadata {
|
||||
id: id.clone(),
|
||||
description: T::description().map(Into::into),
|
||||
description: SharedString::new_static(T::description()),
|
||||
name: SharedString::new_static(T::name()),
|
||||
preview: Some(T::preview),
|
||||
preview: T::preview,
|
||||
scope: T::scope(),
|
||||
sort_name: SharedString::new_static(T::sort_name()),
|
||||
status: T::status(),
|
||||
|
|
@ -69,15 +69,12 @@ pub struct ComponentRegistry {
|
|||
}
|
||||
|
||||
impl ComponentRegistry {
|
||||
pub fn previews(&self) -> Vec<&ComponentMetadata> {
|
||||
self.components
|
||||
.values()
|
||||
.filter(|c| c.preview.is_some())
|
||||
.collect()
|
||||
pub fn previews(&self) -> impl Iterator<Item = &ComponentMetadata> {
|
||||
self.components.values()
|
||||
}
|
||||
|
||||
pub fn sorted_previews(&self) -> Vec<ComponentMetadata> {
|
||||
let mut previews: Vec<ComponentMetadata> = self.previews().into_iter().cloned().collect();
|
||||
let mut previews: Vec<_> = self.previews().cloned().collect();
|
||||
previews.sort_by_key(|a| a.name());
|
||||
previews
|
||||
}
|
||||
|
|
@ -112,9 +109,9 @@ pub struct ComponentId(pub &'static str);
|
|||
#[derive(Clone)]
|
||||
pub struct ComponentMetadata {
|
||||
id: ComponentId,
|
||||
description: Option<SharedString>,
|
||||
description: SharedString,
|
||||
name: SharedString,
|
||||
preview: Option<fn(&mut Window, &mut App) -> Option<AnyElement>>,
|
||||
preview: fn(&mut Window, &mut App) -> AnyElement,
|
||||
scope: ComponentScope,
|
||||
sort_name: SharedString,
|
||||
status: ComponentStatus,
|
||||
|
|
@ -125,7 +122,7 @@ impl ComponentMetadata {
|
|||
self.id.clone()
|
||||
}
|
||||
|
||||
pub fn description(&self) -> Option<SharedString> {
|
||||
pub fn description(&self) -> SharedString {
|
||||
self.description.clone()
|
||||
}
|
||||
|
||||
|
|
@ -133,7 +130,7 @@ impl ComponentMetadata {
|
|||
self.name.clone()
|
||||
}
|
||||
|
||||
pub fn preview(&self) -> Option<fn(&mut Window, &mut App) -> Option<AnyElement>> {
|
||||
pub fn preview(&self) -> fn(&mut Window, &mut App) -> AnyElement {
|
||||
self.preview
|
||||
}
|
||||
|
||||
|
|
@ -234,17 +231,15 @@ pub trait Component {
|
|||
/// struct MyComponent;
|
||||
///
|
||||
/// impl MyComponent {
|
||||
/// fn description() -> Option<&'static str> {
|
||||
/// Some(Self::DOCS)
|
||||
/// fn description() -> &'static str {
|
||||
/// Self::DOCS
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This will result in "This is a doc comment." being passed
|
||||
/// to the component's description.
|
||||
fn description() -> Option<&'static str> {
|
||||
None
|
||||
}
|
||||
fn description() -> &'static str;
|
||||
/// The component's preview.
|
||||
///
|
||||
/// An element returned here will be shown in the component's preview.
|
||||
|
|
@ -259,9 +254,7 @@ pub trait Component {
|
|||
/// This is useful for displaying related UI to the component you are
|
||||
/// trying to preview, such as a button that opens a modal or shows a
|
||||
/// tooltip on hover, or a grid of icons showcasing all the icons available.
|
||||
fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
|
||||
None
|
||||
}
|
||||
fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement;
|
||||
}
|
||||
|
||||
/// The ready status of this component.
|
||||
|
|
@ -286,14 +279,17 @@ impl ComponentStatus {
|
|||
pub fn description(&self) -> &str {
|
||||
match self {
|
||||
ComponentStatus::WorkInProgress => {
|
||||
"These components are still being designed or refined. They shouldn't be used in the app yet."
|
||||
"These components are still being designed or refined. \
|
||||
They shouldn't be used in the app yet."
|
||||
}
|
||||
ComponentStatus::EngineeringReady => {
|
||||
"These components are design complete or partially implemented, and are ready for an engineer to complete their implementation."
|
||||
"These components are design complete or partially implemented, \
|
||||
and are ready for an engineer to complete their implementation."
|
||||
}
|
||||
ComponentStatus::Live => "These components are ready for use in the app.",
|
||||
ComponentStatus::Deprecated => {
|
||||
"These components are no longer recommended for use in the app, and may be removed in a future release."
|
||||
"These components are no longer recommended for use in the app, \
|
||||
and may be removed in a future release."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,10 @@ use notifications::status_toast::StatusToast;
|
|||
use persistence::ComponentPreviewDb;
|
||||
use project::Project;
|
||||
use std::{iter::Iterator, ops::Range, sync::Arc};
|
||||
use ui::{ButtonLike, Divider, HighlightedLabel, ListItem, ListSubHeader, Tooltip, prelude::*};
|
||||
use ui::{
|
||||
ButtonLike, Divider, HighlightedLabel, ListItem, ListSubHeader, Scrollbars, Tooltip,
|
||||
WithScrollbar, prelude::*,
|
||||
};
|
||||
use ui_input::InputField;
|
||||
use workspace::AppState;
|
||||
use workspace::{
|
||||
|
|
@ -197,10 +200,7 @@ impl ComponentPreview {
|
|||
.filter(|component| {
|
||||
let component_name = component.name().to_lowercase();
|
||||
let scope_name = component.scope().to_string().to_lowercase();
|
||||
let description = component
|
||||
.description()
|
||||
.map(|d| d.to_lowercase())
|
||||
.unwrap_or_default();
|
||||
let description = component.description().to_lowercase();
|
||||
|
||||
component_name.contains(&filter)
|
||||
|| scope_name.contains(&filter)
|
||||
|
|
@ -231,7 +231,7 @@ impl ComponentPreview {
|
|||
// let full_component_name = component.name();
|
||||
let scopeless_name = component.scopeless_name();
|
||||
let scope_name = component.scope().to_string();
|
||||
let description = component.description().unwrap_or_default();
|
||||
let description = component.description();
|
||||
|
||||
let lowercase_scopeless = scopeless_name.to_lowercase();
|
||||
let lowercase_scope = scope_name.to_lowercase();
|
||||
|
|
@ -445,45 +445,40 @@ impl ComponentPreview {
|
|||
let description = component.description();
|
||||
|
||||
// Build the content container
|
||||
let mut preview_container = v_flex().py_2().child(
|
||||
v_flex()
|
||||
.border_1()
|
||||
.border_color(cx.theme().colors().border)
|
||||
.rounded_sm()
|
||||
.w_full()
|
||||
.gap_4()
|
||||
.py_4()
|
||||
.px_6()
|
||||
.flex_none()
|
||||
.child(
|
||||
v_flex()
|
||||
.gap_1()
|
||||
.child(
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.text_xl()
|
||||
.child(div().child(name))
|
||||
.when(!matches!(scope, ComponentScope::None), |this| {
|
||||
this.child(div().opacity(0.5).child(format!("({})", scope)))
|
||||
}),
|
||||
)
|
||||
.when_some(description, |this, description| {
|
||||
this.child(
|
||||
v_flex()
|
||||
.py_2()
|
||||
.child(
|
||||
v_flex()
|
||||
.border_1()
|
||||
.border_color(cx.theme().colors().border)
|
||||
.rounded_sm()
|
||||
.w_full()
|
||||
.gap_4()
|
||||
.py_4()
|
||||
.px_6()
|
||||
.flex_none()
|
||||
.child(
|
||||
v_flex()
|
||||
.gap_1()
|
||||
.child(
|
||||
h_flex().gap_1().text_xl().child(div().child(name)).when(
|
||||
scope != ComponentScope::None,
|
||||
|this| {
|
||||
this.child(div().opacity(0.5).child(format!("({})", scope)))
|
||||
},
|
||||
),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_ui_sm(cx)
|
||||
.text_color(cx.theme().colors().text_muted)
|
||||
.max_w(px(600.0))
|
||||
.child(description),
|
||||
)
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if let Some(preview) = component.preview() {
|
||||
preview_container = preview_container.children(preview(window, cx));
|
||||
}
|
||||
|
||||
preview_container.into_any_element()
|
||||
),
|
||||
),
|
||||
)
|
||||
.child((component.preview())(window, cx))
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
fn render_all_components(&self, cx: &Context<Self>) -> impl IntoElement {
|
||||
|
|
@ -593,6 +588,7 @@ impl Render for ComponentPreview {
|
|||
}
|
||||
let sidebar_entries = self.scope_ordered_entries();
|
||||
let active_page = self.active_page.clone();
|
||||
let background_color = cx.theme().colors().editor_background;
|
||||
|
||||
h_flex()
|
||||
.id("component-preview")
|
||||
|
|
@ -601,37 +597,45 @@ impl Render for ComponentPreview {
|
|||
.overflow_hidden()
|
||||
.size_full()
|
||||
.track_focus(&self.focus_handle)
|
||||
.bg(cx.theme().colors().editor_background)
|
||||
.bg(background_color)
|
||||
.child(
|
||||
v_flex()
|
||||
.h_full()
|
||||
.border_r_1()
|
||||
.border_color(cx.theme().colors().border)
|
||||
.child(
|
||||
gpui::uniform_list(
|
||||
"component-nav",
|
||||
sidebar_entries.len(),
|
||||
cx.processor(move |this, range: Range<usize>, _window, cx| {
|
||||
range
|
||||
.filter_map(|ix| {
|
||||
if ix < sidebar_entries.len() {
|
||||
Some(this.render_sidebar_entry(
|
||||
ix,
|
||||
&sidebar_entries[ix],
|
||||
cx,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}),
|
||||
)
|
||||
.track_scroll(&self.nav_scroll_handle)
|
||||
.p_2p5()
|
||||
.w(px(231.)) // Matches perfectly with the size of the "Component Preview" tab, if that's the first one in the pane
|
||||
.h_full()
|
||||
.flex_1(),
|
||||
div()
|
||||
.size_full()
|
||||
.child(
|
||||
gpui::uniform_list(
|
||||
"component-nav",
|
||||
sidebar_entries.len(),
|
||||
cx.processor(move |this, range: Range<usize>, _window, cx| {
|
||||
range
|
||||
.filter(|ix| ix < &sidebar_entries.len())
|
||||
.map(|ix| {
|
||||
this.render_sidebar_entry(
|
||||
ix,
|
||||
&sidebar_entries[ix],
|
||||
cx,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}),
|
||||
)
|
||||
.track_scroll(&self.nav_scroll_handle)
|
||||
.p_2p5()
|
||||
.w(px(231.)) // Matches perfectly with the size of the "Component Preview" tab, if that's the first one in the pane
|
||||
.h_full()
|
||||
.flex_1(),
|
||||
)
|
||||
.custom_scrollbars(
|
||||
Scrollbars::new(ui::ScrollAxes::Vertical)
|
||||
.with_track_along(ui::ScrollAxes::Vertical, background_color)
|
||||
.tracked_scroll_handle(&self.nav_scroll_handle),
|
||||
window,
|
||||
cx,
|
||||
),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
|
|
@ -961,23 +965,10 @@ impl ComponentPreviewPage {
|
|||
.children(self.render_component_status(cx)),
|
||||
),
|
||||
)
|
||||
.when_some(self.component.description(), |this, description| {
|
||||
this.child(Label::new(description).size(LabelSize::Small))
|
||||
})
|
||||
.child(Label::new(self.component.description()).size(LabelSize::Small))
|
||||
}
|
||||
|
||||
fn render_preview(&self, window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let content = if let Some(preview) = self.component.preview() {
|
||||
// Fall back to component preview
|
||||
preview(window, cx).unwrap_or_else(|| {
|
||||
div()
|
||||
.child("Failed to load preview. This path should be unreachable")
|
||||
.into_any_element()
|
||||
})
|
||||
} else {
|
||||
div().child("No preview available").into_any_element()
|
||||
};
|
||||
|
||||
v_flex()
|
||||
.id(("component-preview", self.reset_key))
|
||||
.size_full()
|
||||
|
|
@ -985,7 +976,7 @@ impl ComponentPreviewPage {
|
|||
.px_12()
|
||||
.py_6()
|
||||
.bg(cx.theme().colors().editor_background)
|
||||
.child(content)
|
||||
.child((self.component.preview())(window, cx))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -511,8 +511,14 @@ impl Copilot {
|
|||
};
|
||||
}
|
||||
|
||||
if let Ok(oauth_token) = env::var(copilot_chat::COPILOT_OAUTH_ENV_VAR) {
|
||||
env.insert(copilot_chat::COPILOT_OAUTH_ENV_VAR.to_string(), oauth_token);
|
||||
for env_var in [
|
||||
copilot_chat::COPILOT_OAUTH_ENV_VAR,
|
||||
copilot_chat::GITHUB_COPILOT_OAUTH_ENV_VAR,
|
||||
] {
|
||||
if let Ok(oauth_token) = env::var(env_var) {
|
||||
env.insert(env_var.to_string(), oauth_token);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if env.is_empty() { None } else { Some(env) }
|
||||
|
|
@ -1259,6 +1265,7 @@ impl Copilot {
|
|||
| request::SignInStatus::AlreadySignedIn { .. } => {
|
||||
server.sign_in_status = SignInStatus::Authorized;
|
||||
cx.emit(Event::CopilotAuthSignedIn);
|
||||
notify_copilot_chat_auth_changed(cx);
|
||||
for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
|
||||
if let Some(buffer) = buffer.upgrade() {
|
||||
self.register_buffer(&buffer, cx);
|
||||
|
|
@ -1278,6 +1285,7 @@ impl Copilot {
|
|||
};
|
||||
}
|
||||
cx.emit(Event::CopilotAuthSignedOut);
|
||||
notify_copilot_chat_auth_changed(cx);
|
||||
for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
|
||||
self.unregister_buffer(&buffer);
|
||||
}
|
||||
|
|
@ -1381,6 +1389,15 @@ fn notify_did_change_config_to_server(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Notify Copilot Chat after the Copilot LSP reports an auth state change.
|
||||
/// This replaces watching the SDK's token files, which is unreliable for
|
||||
/// SQLite backed auth because writes may go through WAL files.
|
||||
fn notify_copilot_chat_auth_changed(cx: &mut Context<Copilot>) {
|
||||
if let Some(copilot_chat) = copilot_chat::CopilotChat::global(cx) {
|
||||
copilot_chat.update(cx, |chat, cx| chat.reload_auth(cx));
|
||||
}
|
||||
}
|
||||
|
||||
async fn clear_copilot_dir() {
|
||||
remove_matching(paths::copilot_dir(), |_| true).await
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,7 +34,9 @@ paths.workspace = true
|
|||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
settings.workspace = true
|
||||
sqlez.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
gpui = { workspace = true, features = ["test-support"] }
|
||||
serde_json.workspace = true
|
||||
tempfile.workspace = true
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
pub mod responses;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
|
|
@ -17,9 +17,10 @@ use http_client::{AsyncBody, HttpClient, Method, Request as HttpRequest};
|
|||
use paths::home_dir;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use settings::watch_config_dir;
|
||||
|
||||
// The Copilot language server unofficially supports both token env vars:
|
||||
// https://github.com/github/copilot-language-server-release/issues/3#issuecomment-2699433055
|
||||
pub const COPILOT_OAUTH_ENV_VAR: &str = "GH_COPILOT_TOKEN";
|
||||
pub const GITHUB_COPILOT_OAUTH_ENV_VAR: &str = "GITHUB_COPILOT_TOKEN";
|
||||
const DEFAULT_COPILOT_API_ENDPOINT: &str = "https://api.githubcopilot.com";
|
||||
|
||||
#[derive(Default, Clone, Debug, PartialEq)]
|
||||
|
|
@ -501,6 +502,7 @@ pub struct CopilotChat {
|
|||
configuration: CopilotChatConfiguration,
|
||||
models: Option<Vec<Model>>,
|
||||
client: Arc<dyn HttpClient>,
|
||||
fs: Arc<dyn Fs>,
|
||||
}
|
||||
|
||||
pub fn init(
|
||||
|
|
@ -529,11 +531,19 @@ pub fn copilot_chat_config_dir() -> &'static PathBuf {
|
|||
})
|
||||
}
|
||||
|
||||
/// Legacy JSON token-storage paths used by older Copilot SDK builds.
|
||||
/// TODO(copilot): once Copilot SDK supports `auth.db`, remove these paths.
|
||||
fn copilot_chat_config_paths() -> [PathBuf; 2] {
|
||||
let base_dir = copilot_chat_config_dir();
|
||||
[base_dir.join("hosts.json"), base_dir.join("apps.json")]
|
||||
}
|
||||
|
||||
fn oauth_token_from_env() -> Option<String> {
|
||||
std::env::var(COPILOT_OAUTH_ENV_VAR)
|
||||
.ok()
|
||||
.or_else(|| std::env::var(GITHUB_COPILOT_OAUTH_ENV_VAR).ok())
|
||||
}
|
||||
|
||||
impl CopilotChat {
|
||||
pub fn global(cx: &App) -> Option<gpui::Entity<Self>> {
|
||||
cx.try_global::<GlobalCopilotChat>()
|
||||
|
|
@ -546,40 +556,42 @@ impl CopilotChat {
|
|||
configuration: CopilotChatConfiguration,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let config_paths: HashSet<PathBuf> = copilot_chat_config_paths().into_iter().collect();
|
||||
let dir_path = copilot_chat_config_dir();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let mut parent_watch_rx = watch_config_dir(
|
||||
cx.background_executor(),
|
||||
fs.clone(),
|
||||
dir_path.clone(),
|
||||
config_paths,
|
||||
);
|
||||
while let Some(contents) = parent_watch_rx.next().await {
|
||||
// Initial async scan of token sources. Live reload is driven by the
|
||||
// Copilot LSP's auth status notifications instead of watching files,
|
||||
// because SQLite WAL writes can make directory watchers racy.
|
||||
cx.spawn({
|
||||
let fs = fs.clone();
|
||||
async move |this, cx| {
|
||||
let oauth_domain =
|
||||
this.read_with(cx, |this, _| this.configuration.oauth_domain())?;
|
||||
let oauth_token = extract_oauth_token(contents, &oauth_domain);
|
||||
let config_paths: HashSet<PathBuf> =
|
||||
copilot_chat_config_paths().into_iter().collect();
|
||||
let auth_db_path = copilot_chat_config_dir().join("auth.db");
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
this.oauth_token = oauth_token.clone();
|
||||
cx.notify();
|
||||
})?;
|
||||
let oauth_token =
|
||||
read_oauth_token(&fs, &config_paths, &oauth_domain, &auth_db_path, cx).await;
|
||||
|
||||
if oauth_token.is_some() {
|
||||
this.update(cx, |this, cx| {
|
||||
this.oauth_token = oauth_token;
|
||||
cx.notify();
|
||||
})?;
|
||||
Self::update_models(&this, cx).await?;
|
||||
}
|
||||
anyhow::Ok(())
|
||||
}
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.detach_and_log_err(cx);
|
||||
|
||||
// Initial state uses env var because it's cheap. The others do IO, so
|
||||
// are on the background.
|
||||
let this = Self {
|
||||
oauth_token: std::env::var(COPILOT_OAUTH_ENV_VAR).ok(),
|
||||
oauth_token: oauth_token_from_env(),
|
||||
api_endpoint: None,
|
||||
models: None,
|
||||
configuration,
|
||||
client,
|
||||
fs,
|
||||
};
|
||||
|
||||
if this.oauth_token.is_some() {
|
||||
|
|
@ -764,6 +776,39 @@ impl CopilotChat {
|
|||
.detach();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reload_auth(&mut self, cx: &mut Context<Self>) {
|
||||
let fs = self.fs.clone();
|
||||
let oauth_domain = self.configuration.oauth_domain();
|
||||
cx.spawn(async move |this, cx| {
|
||||
let config_paths: HashSet<PathBuf> = copilot_chat_config_paths().into_iter().collect();
|
||||
let auth_db_path = copilot_chat_config_dir().join("auth.db");
|
||||
|
||||
let new_token =
|
||||
read_oauth_token(&fs, &config_paths, &oauth_domain, &auth_db_path, cx).await;
|
||||
|
||||
let token_present = this.update(cx, |this, cx| {
|
||||
let changed = this.oauth_token != new_token;
|
||||
if changed {
|
||||
this.oauth_token = new_token.clone();
|
||||
if new_token.is_none() {
|
||||
// Sign-out: drop derived state so a future sign-in
|
||||
// re-discovers the endpoint and re-fetches models.
|
||||
this.api_endpoint = None;
|
||||
this.models = None;
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
new_token.is_some()
|
||||
})?;
|
||||
|
||||
if token_present {
|
||||
Self::update_models(&this, cx).await?;
|
||||
}
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.detach_and_log_err(cx);
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_models(
|
||||
|
|
@ -917,6 +962,40 @@ async fn request_models(
|
|||
Ok(models)
|
||||
}
|
||||
|
||||
async fn read_oauth_token(
|
||||
fs: &Arc<dyn Fs>,
|
||||
config_paths: &HashSet<PathBuf>,
|
||||
oauth_domain: &str,
|
||||
auth_db_path: &std::path::Path,
|
||||
cx: &AsyncApp,
|
||||
) -> Option<String> {
|
||||
if let Some(token) = oauth_token_from_env() {
|
||||
return Some(token);
|
||||
}
|
||||
|
||||
let token_from_db = cx
|
||||
.background_spawn({
|
||||
let auth_db_path = auth_db_path.to_path_buf();
|
||||
let oauth_domain = oauth_domain.to_string();
|
||||
async move { extract_oauth_token_from_db(&auth_db_path, &oauth_domain) }
|
||||
})
|
||||
.await;
|
||||
|
||||
if let Some(token) = token_from_db {
|
||||
return Some(token);
|
||||
}
|
||||
|
||||
for file_path in config_paths {
|
||||
if let Ok(contents) = fs.load(file_path).await {
|
||||
if let Some(token) = extract_oauth_token(contents, oauth_domain) {
|
||||
return Some(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn extract_oauth_token(contents: String, domain: &str) -> Option<String> {
|
||||
serde_json::from_str::<serde_json::Value>(&contents)
|
||||
.map(|v| {
|
||||
|
|
@ -934,6 +1013,36 @@ fn extract_oauth_token(contents: String, domain: &str) -> Option<String> {
|
|||
.flatten()
|
||||
}
|
||||
|
||||
fn extract_oauth_token_from_db(db_path: &Path, auth_authority: &str) -> Option<String> {
|
||||
if !db_path.exists() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let db = sqlez::connection::Connection::open_file(db_path.to_str()?);
|
||||
|
||||
let token_bytes: Option<Vec<u8>> = db
|
||||
.select_row_bound::<&str, Vec<u8>>(
|
||||
"SELECT token_ciphertext FROM oauth_tokens WHERE auth_authority = ? ORDER BY last_used_at DESC, token_id DESC LIMIT 1",
|
||||
)
|
||||
.ok()
|
||||
.and_then(|mut select| select(auth_authority).ok().flatten());
|
||||
|
||||
let token = token_bytes.and_then(|bytes| String::from_utf8(bytes).ok())?;
|
||||
|
||||
if token.starts_with("ghu_")
|
||||
&& token.len() >= 36
|
||||
&& token.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
|
||||
{
|
||||
log::debug!("Copilot OAuth token loaded from auth.db");
|
||||
Some(token)
|
||||
} else {
|
||||
log::warn!(
|
||||
"Copilot auth.db: token does not match expected GitHub OAuth format (ghu_<alphanumeric>)"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
async fn stream_completion(
|
||||
client: Arc<dyn HttpClient>,
|
||||
oauth_token: String,
|
||||
|
|
@ -1751,4 +1860,61 @@ mod tests {
|
|||
"\"none\""
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_oauth_token_from_db_matches_auth_authority_and_recency() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db_path = dir.path().join("auth.db");
|
||||
let older_github_token = "ghu_oldergithubtokenvalue000000000000";
|
||||
let newer_github_token = "ghu_newergithubtokenvalue000000000000";
|
||||
let enterprise_token = "ghu_enterprisetokenvalue0000000000000";
|
||||
|
||||
let connection = sqlez::connection::Connection::open_file(db_path.to_str().unwrap());
|
||||
connection
|
||||
.exec(
|
||||
"CREATE TABLE oauth_tokens (
|
||||
token_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
auth_authority TEXT NOT NULL,
|
||||
token_ciphertext BLOB NOT NULL,
|
||||
last_used_at INTEGER NOT NULL
|
||||
);",
|
||||
)
|
||||
.unwrap()()
|
||||
.unwrap();
|
||||
|
||||
{
|
||||
let mut insert_token = connection
|
||||
.exec_bound::<(&str, Vec<u8>, i64)>(
|
||||
"INSERT INTO oauth_tokens (auth_authority, token_ciphertext, last_used_at) VALUES (?, ?, ?);",
|
||||
)
|
||||
.unwrap();
|
||||
insert_token(("github.com", older_github_token.as_bytes().to_vec(), 10)).unwrap();
|
||||
insert_token((
|
||||
"github.enterprise.test",
|
||||
enterprise_token.as_bytes().to_vec(),
|
||||
30,
|
||||
))
|
||||
.unwrap();
|
||||
insert_token(("github.com", newer_github_token.as_bytes().to_vec(), 20)).unwrap();
|
||||
}
|
||||
drop(connection);
|
||||
|
||||
assert_eq!(
|
||||
extract_oauth_token_from_db(&db_path, "github.com").as_deref(),
|
||||
Some(newer_github_token)
|
||||
);
|
||||
assert_eq!(
|
||||
extract_oauth_token_from_db(&db_path, "github.enterprise.test").as_deref(),
|
||||
Some(enterprise_token)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_oauth_token_from_db_missing_db_does_not_create_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db_path = dir.path().join("auth.db");
|
||||
|
||||
assert_eq!(extract_oauth_token_from_db(&db_path, "github.com"), None);
|
||||
assert!(!db_path.exists());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -211,7 +211,7 @@ pub(crate) struct DevContainer {
|
|||
#[serde(rename = "updateRemoteUserUID")]
|
||||
pub(crate) update_remote_user_uid: Option<bool>,
|
||||
user_env_probe: Option<UserEnvProbe>,
|
||||
override_command: Option<bool>,
|
||||
pub(crate) override_command: Option<bool>,
|
||||
shutdown_action: Option<ShutdownAction>,
|
||||
init: Option<bool>,
|
||||
pub(crate) privileged: Option<bool>,
|
||||
|
|
@ -232,7 +232,7 @@ pub(crate) struct DevContainer {
|
|||
#[serde(default, deserialize_with = "deserialize_string_or_array")]
|
||||
pub(crate) docker_compose_file: Option<Vec<String>>,
|
||||
pub(crate) service: Option<String>,
|
||||
run_services: Option<Vec<String>>,
|
||||
pub(crate) run_services: Option<Vec<String>>,
|
||||
pub(crate) initialize_command: Option<LifecycleScript>,
|
||||
pub(crate) on_create_command: Option<LifecycleScript>,
|
||||
pub(crate) update_content_command: Option<LifecycleScript>,
|
||||
|
|
|
|||
|
|
@ -794,24 +794,30 @@ RUN sed -i -E 's/((^|\s)PATH=)([^\$]*)$/\1\${{PATH:-\3}}/g' /etc/profile || true
|
|||
let privileged = dev_container.privileged.unwrap_or(false)
|
||||
|| self.features.iter().any(|f| f.privileged());
|
||||
|
||||
let mut entrypoint_script_lines = vec![
|
||||
"echo Container started".to_string(),
|
||||
"trap \"exit 0\" 15".to_string(),
|
||||
];
|
||||
let entrypoint_script = if dev_container.override_command == Some(false) {
|
||||
None
|
||||
} else {
|
||||
let mut entrypoint_script_lines = vec![
|
||||
"echo Container started".to_string(),
|
||||
"trap \"exit 0\" 15".to_string(),
|
||||
];
|
||||
|
||||
for entrypoint in self.features.iter().filter_map(|f| f.entrypoint()) {
|
||||
entrypoint_script_lines.push(entrypoint.clone());
|
||||
}
|
||||
entrypoint_script_lines.append(&mut vec![
|
||||
"exec \"$@\"".to_string(),
|
||||
"while sleep 1 & wait $!; do :; done".to_string(),
|
||||
]);
|
||||
for entrypoint in self.features.iter().filter_map(|f| f.entrypoint()) {
|
||||
entrypoint_script_lines.push(entrypoint.clone());
|
||||
}
|
||||
entrypoint_script_lines.append(&mut vec![
|
||||
"exec \"$@\"".to_string(),
|
||||
"while sleep 1 & wait $!; do :; done".to_string(),
|
||||
]);
|
||||
|
||||
Some(entrypoint_script_lines.join("\n").trim().to_string())
|
||||
};
|
||||
|
||||
Ok(DockerBuildResources {
|
||||
image: base_image,
|
||||
additional_mounts: mounts,
|
||||
privileged,
|
||||
entrypoint_script: entrypoint_script_lines.join("\n").trim().to_string(),
|
||||
entrypoint_script,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -1052,7 +1058,11 @@ RUN sed -i -E 's/((^|\s)PATH=)([^\$]*)$/\1\${{PATH:-\3}}/g' /etc/profile || true
|
|||
|
||||
let project_name = self.project_name().await?;
|
||||
self.docker_client
|
||||
.docker_compose_build(&docker_compose_resources.files, &project_name)
|
||||
.docker_compose_build(
|
||||
&docker_compose_resources.files,
|
||||
&project_name,
|
||||
dev_container.run_services.as_ref(),
|
||||
)
|
||||
.await?;
|
||||
(
|
||||
self.docker_client
|
||||
|
|
@ -1145,7 +1155,11 @@ RUN sed -i -E 's/((^|\s)PATH=)([^\$]*)$/\1\${{PATH:-\3}}/g' /etc/profile || true
|
|||
|
||||
let project_name = self.project_name().await?;
|
||||
self.docker_client
|
||||
.docker_compose_build(&docker_compose_resources.files, &project_name)
|
||||
.docker_compose_build(
|
||||
&docker_compose_resources.files,
|
||||
&project_name,
|
||||
dev_container.run_services.as_ref(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
(
|
||||
|
|
@ -1255,13 +1269,17 @@ RUN sed -i -E 's/((^|\s)PATH=)([^\$]*)$/\1\${{PATH:-\3}}/g' /etc/profile || true
|
|||
})
|
||||
.collect();
|
||||
|
||||
let mut main_service = DockerComposeService {
|
||||
entrypoint: Some(vec![
|
||||
let entrypoint = resources.entrypoint_script.map(|script| {
|
||||
vec![
|
||||
"/bin/sh".to_string(),
|
||||
"-c".to_string(),
|
||||
resources.entrypoint_script,
|
||||
script,
|
||||
"-".to_string(),
|
||||
]),
|
||||
]
|
||||
});
|
||||
|
||||
let mut main_service = DockerComposeService {
|
||||
entrypoint,
|
||||
cap_add: Some(vec!["SYS_PTRACE".to_string()]),
|
||||
security_opt: Some(vec!["seccomp=unconfined".to_string()]),
|
||||
labels: Some(runtime_labels),
|
||||
|
|
@ -1775,6 +1793,9 @@ RUN sed -i -E 's/((^|\s)PATH=)([^\$]*)$/\1\${PATH:-\3}/g' /etc/profile || true
|
|||
command.args(&["-f", &docker_compose_file.display().to_string()]);
|
||||
}
|
||||
command.args(&["up", "-d"]);
|
||||
if let Some(run_services) = self.dev_container().run_services.as_ref() {
|
||||
command.args(run_services);
|
||||
}
|
||||
|
||||
let output = self
|
||||
.command_runner
|
||||
|
|
@ -1977,13 +1998,16 @@ RUN sed -i -E 's/((^|\s)PATH=)([^\$]*)$/\1\${PATH:-\3}/g' /etc/profile || true
|
|||
command.arg(app_port);
|
||||
}
|
||||
|
||||
command.arg("--entrypoint");
|
||||
command.arg("/bin/sh");
|
||||
command.arg(&build_resources.image.id);
|
||||
command.arg("-c");
|
||||
|
||||
command.arg(build_resources.entrypoint_script);
|
||||
command.arg("-");
|
||||
if let Some(entrypoint_script) = build_resources.entrypoint_script {
|
||||
command.arg("--entrypoint");
|
||||
command.arg("/bin/sh");
|
||||
command.arg(&build_resources.image.id);
|
||||
command.arg("-c");
|
||||
command.arg(entrypoint_script);
|
||||
command.arg("-");
|
||||
} else {
|
||||
command.arg(&build_resources.image.id);
|
||||
}
|
||||
|
||||
Ok(command)
|
||||
}
|
||||
|
|
@ -2409,7 +2433,7 @@ struct DockerBuildResources {
|
|||
image: DockerInspect,
|
||||
additional_mounts: Vec<MountDefinition>,
|
||||
privileged: bool,
|
||||
entrypoint_script: String,
|
||||
entrypoint_script: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
|
@ -3166,7 +3190,7 @@ mod test {
|
|||
},
|
||||
additional_mounts: vec![],
|
||||
privileged: false,
|
||||
entrypoint_script: "echo Container started\n trap \"exit 0\" 15\n exec \"$@\"\n while sleep 1 & wait $!; do :; done".to_string(),
|
||||
entrypoint_script: Some("echo Container started\n trap \"exit 0\" 15\n exec \"$@\"\n while sleep 1 & wait $!; do :; done".to_string()),
|
||||
};
|
||||
let docker_run_command = devcontainer_manifest.create_docker_run_command(build_resources);
|
||||
|
||||
|
|
@ -3212,6 +3236,56 @@ mod test {
|
|||
)
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn should_not_override_entrypoint_when_override_command_is_false(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let (_, mut devcontainer_manifest) = init_default_devcontainer_manifest(
|
||||
cx,
|
||||
r#"{
|
||||
"name": "test",
|
||||
"image": "mcr.microsoft.com/devcontainers/base:ubuntu",
|
||||
"overrideCommand": false
|
||||
}"#,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
devcontainer_manifest.parse_nonremote_vars().unwrap();
|
||||
|
||||
let base_image = DockerInspect {
|
||||
id: "mcr.microsoft.com/devcontainers/base:ubuntu".to_string(),
|
||||
config: DockerInspectConfig {
|
||||
labels: DockerConfigLabels { metadata: None },
|
||||
image_user: None,
|
||||
env: Vec::new(),
|
||||
},
|
||||
mounts: None,
|
||||
state: None,
|
||||
};
|
||||
|
||||
let resources = devcontainer_manifest
|
||||
.build_merged_resources(base_image)
|
||||
.unwrap();
|
||||
assert!(
|
||||
resources.entrypoint_script.is_none(),
|
||||
"overrideCommand: false must not produce an entrypoint script"
|
||||
);
|
||||
|
||||
let docker_run_command = devcontainer_manifest
|
||||
.create_docker_run_command(resources)
|
||||
.unwrap();
|
||||
let args: Vec<&OsStr> = docker_run_command.get_args().collect();
|
||||
assert!(
|
||||
!args.contains(&OsStr::new("--entrypoint")),
|
||||
"overrideCommand: false must not pass --entrypoint to docker run"
|
||||
);
|
||||
assert!(
|
||||
args.contains(&OsStr::new("mcr.microsoft.com/devcontainers/base:ubuntu")),
|
||||
"image id must still be present in docker run command"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn should_find_primary_service_in_docker_compose(cx: &mut TestAppContext) {
|
||||
// State where service not defined in dev container
|
||||
|
|
@ -4720,6 +4794,111 @@ ENV DOCKER_BUILDKIT=1
|
|||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_spawns_only_requested_compose_services(cx: &mut TestAppContext) {
|
||||
cx.executor().allow_parking();
|
||||
env_logger::try_init().ok();
|
||||
let given_devcontainer_contents = r#"
|
||||
{
|
||||
"name": "Devcontainer and PostgreSQL",
|
||||
"dockerComposeFile": "docker-compose.yml",
|
||||
"service": "devcontainer",
|
||||
"runServices": ["devcontainer", "db"],
|
||||
"workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",
|
||||
"updateRemoteUserUID": false
|
||||
}
|
||||
"#;
|
||||
let (test_dependencies, mut devcontainer_manifest) =
|
||||
init_default_devcontainer_manifest(cx, given_devcontainer_contents)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
test_dependencies
|
||||
.fs
|
||||
.atomic_write(
|
||||
PathBuf::from(TEST_PROJECT_PATH).join(".devcontainer/docker-compose.yml"),
|
||||
r#"
|
||||
version: '3.8'
|
||||
|
||||
x-base: &base
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
env_file:
|
||||
- .env
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
|
||||
services:
|
||||
app:
|
||||
<<: *base
|
||||
ports:
|
||||
- "3000:3000"
|
||||
|
||||
devcontainer:
|
||||
<<: *base
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- ../..:/workspaces:cached
|
||||
|
||||
db:
|
||||
image: postgres:14.1
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
env_file:
|
||||
- .env
|
||||
"#
|
||||
.trim()
|
||||
.to_string(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
test_dependencies
|
||||
.fs
|
||||
.atomic_write(
|
||||
PathBuf::from(TEST_PROJECT_PATH).join(".devcontainer/Dockerfile"),
|
||||
r#"
|
||||
FROM mcr.microsoft.com/devcontainers/rust:2-1-bookworm
|
||||
|
||||
RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
|
||||
&& apt-get -y install clang lld \
|
||||
&& apt-get autoremove -y && apt-get clean -y
|
||||
"#
|
||||
.trim()
|
||||
.to_string(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
devcontainer_manifest.parse_nonremote_vars().unwrap();
|
||||
let _devcontainer_up = devcontainer_manifest.build_and_run().await.unwrap();
|
||||
|
||||
let docker_commands = test_dependencies
|
||||
.command_runner
|
||||
.commands_by_program("docker");
|
||||
let compose_up = docker_commands
|
||||
.iter()
|
||||
.find(|c| {
|
||||
c.args.first().map(String::as_str) == Some("compose")
|
||||
&& c.args.iter().any(|a| a == "up")
|
||||
})
|
||||
.expect("docker compose up command recorded");
|
||||
assert!(
|
||||
compose_up.args.ends_with(&[
|
||||
"up".to_string(),
|
||||
"-d".to_string(),
|
||||
"devcontainer".to_string(),
|
||||
"db".to_string(),
|
||||
]),
|
||||
"compose up should target only the requested service, got: {:?}",
|
||||
compose_up.args
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
#[gpui::test]
|
||||
async fn test_spawns_devcontainer_with_docker_compose_and_podman(cx: &mut TestAppContext) {
|
||||
|
|
@ -6004,6 +6183,19 @@ FROM docker.io/hexpm/elixir:1.21-erlang-28.4.1-debian-trixie-20260316-slim AS de
|
|||
return Ok(Some(DockerComposeConfig {
|
||||
name: None,
|
||||
services: HashMap::from([
|
||||
(
|
||||
"devcontainer".to_string(),
|
||||
DockerComposeService {
|
||||
image: Some("test_image:latest".to_string()),
|
||||
volumes: vec![MountDefinition {
|
||||
source: Some("../..".to_string()),
|
||||
target: "/workspaces".to_string(),
|
||||
mount_type: Some("bind".to_string()),
|
||||
}],
|
||||
command: vec!["sleep".to_string(), "infinity".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
"app".to_string(),
|
||||
DockerComposeService {
|
||||
|
|
@ -6130,6 +6322,7 @@ FROM docker.io/hexpm/elixir:1.21-erlang-28.4.1-debian-trixie-20260316-slim AS de
|
|||
&self,
|
||||
_config_files: &Vec<PathBuf>,
|
||||
_project_name: &str,
|
||||
_services: Option<&Vec<String>>,
|
||||
) -> Result<(), DevContainerError> {
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -291,6 +291,7 @@ impl DockerClient for Docker {
|
|||
&self,
|
||||
config_files: &Vec<PathBuf>,
|
||||
project_name: &str,
|
||||
services: Option<&Vec<String>>,
|
||||
) -> Result<(), DevContainerError> {
|
||||
let mut command = Command::new(&self.docker_cli);
|
||||
if !self.is_podman() {
|
||||
|
|
@ -301,6 +302,9 @@ impl DockerClient for Docker {
|
|||
command.args(&["-f", &docker_compose_file.display().to_string()]);
|
||||
}
|
||||
command.arg("build");
|
||||
if let Some(services) = services {
|
||||
command.args(services);
|
||||
}
|
||||
|
||||
let output = command.output().await.map_err(|e| {
|
||||
log::error!("Error running docker compose up: {e}");
|
||||
|
|
@ -457,6 +461,7 @@ pub(crate) trait DockerClient {
|
|||
&self,
|
||||
config_files: &Vec<PathBuf>,
|
||||
project_name: &str,
|
||||
services: Option<&Vec<String>>,
|
||||
) -> Result<(), DevContainerError>;
|
||||
async fn run_docker_exec(
|
||||
&self,
|
||||
|
|
|
|||
|
|
@ -1550,6 +1550,8 @@ async fn go_to_diagnostic_with_severity(cx: &mut TestAppContext) {
|
|||
|
||||
// Default, should cycle through all diagnostics
|
||||
go!(GoToDiagnosticSeverityFilter::default());
|
||||
cx.assert_editor_state(indoc! {"error warning info ˇhint"});
|
||||
go!(GoToDiagnosticSeverityFilter::default());
|
||||
cx.assert_editor_state(indoc! {"ˇerror warning info hint"});
|
||||
go!(GoToDiagnosticSeverityFilter::default());
|
||||
cx.assert_editor_state(indoc! {"error ˇwarning info hint"});
|
||||
|
|
|
|||
|
|
@ -64,13 +64,19 @@ impl Render for DiagnosticIndicator {
|
|||
.message
|
||||
.split_once('\n')
|
||||
.map_or(&*diagnostic.message, |(first, _)| first);
|
||||
let diagnostics_already_active = self.any_active_diagnostics(cx);
|
||||
let tooltip = if !diagnostics_already_active {
|
||||
"Expand Diagnostics"
|
||||
} else {
|
||||
"Next Diagnostic"
|
||||
};
|
||||
Some(
|
||||
Button::new("diagnostic_message", SharedString::new(message))
|
||||
.label_size(LabelSize::Small)
|
||||
.truncate(true)
|
||||
.tooltip(|_window, cx| {
|
||||
.tooltip(move |_window, cx| {
|
||||
Tooltip::for_action(
|
||||
"Next Diagnostic",
|
||||
tooltip,
|
||||
&editor::actions::GoToDiagnostic::default(),
|
||||
cx,
|
||||
)
|
||||
|
|
@ -154,10 +160,18 @@ impl DiagnosticIndicator {
|
|||
}
|
||||
}
|
||||
|
||||
fn any_active_diagnostics(&self, cx: &mut Context<Self>) -> bool {
|
||||
if let Some(editor) = self.active_editor.as_ref().and_then(|e| e.upgrade()) {
|
||||
editor.read(cx).any_active_diagnostics()
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn go_to_next_diagnostic(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if let Some(editor) = self.active_editor.as_ref().and_then(|e| e.upgrade()) {
|
||||
editor.update(cx, |editor, cx| {
|
||||
editor.go_to_diagnostic_impl(
|
||||
editor.go_to_diagnostic_at_cursor(
|
||||
editor::Direction::Next,
|
||||
GoToDiagnosticSeverityFilter::default(),
|
||||
window,
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ credentials_provider.workspace = true
|
|||
db.workspace = true
|
||||
edit_prediction_types.workspace = true
|
||||
edit_prediction_context.workspace = true
|
||||
edit_prediction_metrics.workspace = true
|
||||
edit_prediction_metrics = { workspace = true, features = ["tree-sitter"] }
|
||||
feature_flags.workspace = true
|
||||
fs.workspace = true
|
||||
futures.workspace = true
|
||||
|
|
|
|||
|
|
@ -38,9 +38,9 @@ use gpui::{
|
|||
};
|
||||
use heapless::Vec as ArrayVec;
|
||||
use language::{
|
||||
Anchor, Buffer, BufferSnapshot, EditPredictionPromptFormat, EditPredictionsMode, EditPreview,
|
||||
File, OffsetRangeExt, Point, TextBufferSnapshot, ToOffset, ToPoint,
|
||||
language_settings::all_language_settings,
|
||||
Anchor, Buffer, BufferEditSource, BufferSnapshot, EditPredictionPromptFormat,
|
||||
EditPredictionsMode, EditPreview, File, OffsetRangeExt, Point, TextBufferSnapshot, ToOffset,
|
||||
ToPoint, language_settings::all_language_settings,
|
||||
};
|
||||
use project::{DisableAiSettings, Project, ProjectPath, WorktreeId};
|
||||
use release_channel::AppVersion;
|
||||
|
|
@ -324,6 +324,7 @@ struct ProjectState {
|
|||
recent_paths: VecDeque<ProjectPath>,
|
||||
registered_buffers: HashMap<gpui::EntityId, RegisteredBuffer>,
|
||||
current_prediction: Option<CurrentEditPrediction>,
|
||||
last_edit_source: Option<BufferEditSource>,
|
||||
next_pending_prediction_id: usize,
|
||||
pending_predictions: ArrayVec<PendingPrediction, 2, u8>,
|
||||
debug_tx: Option<mpsc::UnboundedSender<DebugEvent>>,
|
||||
|
|
@ -1212,6 +1213,7 @@ impl EditPredictionStore {
|
|||
debug_tx: None,
|
||||
registered_buffers: HashMap::default(),
|
||||
current_prediction: None,
|
||||
last_edit_source: None,
|
||||
cancelled_predictions: HashSet::default(),
|
||||
pending_predictions: ArrayVec::new(),
|
||||
next_pending_prediction_id: 0,
|
||||
|
|
@ -1315,6 +1317,9 @@ impl EditPredictionStore {
|
|||
}
|
||||
// TODO [zeta2] init with recent paths
|
||||
match event {
|
||||
project::Event::BufferEdited { source } => {
|
||||
self.get_or_init_project(&project, cx).last_edit_source = Some(*source);
|
||||
}
|
||||
project::Event::ActiveEntryChanged(Some(active_entry_id)) => {
|
||||
let Some(project_state) = self.projects.get_mut(&project.entity_id()) else {
|
||||
return;
|
||||
|
|
@ -1332,6 +1337,15 @@ impl EditPredictionStore {
|
|||
}
|
||||
}
|
||||
project::Event::DiagnosticsUpdated { .. } => {
|
||||
if self
|
||||
.projects
|
||||
.get(&project.entity_id())
|
||||
.and_then(|project_state| project_state.last_edit_source)
|
||||
== Some(BufferEditSource::Agent)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if cx.has_flag::<EditPredictionJumpsFeatureFlag>() {
|
||||
self.refresh_prediction_from_diagnostics(
|
||||
project,
|
||||
|
|
@ -1391,11 +1405,17 @@ impl EditPredictionStore {
|
|||
cx.subscribe(buffer, {
|
||||
let project = project.downgrade();
|
||||
move |this, buffer, event, cx| {
|
||||
if let language::BufferEvent::Edited { is_local } = event
|
||||
if let language::BufferEvent::Edited { source } = event
|
||||
&& let Some(project) = project.upgrade()
|
||||
{
|
||||
let project_state = this.get_or_init_project(&project, cx);
|
||||
project_state.last_edit_source = Some(*source);
|
||||
this.report_changes_for_buffer(
|
||||
&buffer, &project, false, *is_local, cx,
|
||||
&buffer,
|
||||
&project,
|
||||
false,
|
||||
source.is_local(),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -2530,6 +2550,15 @@ impl EditPredictionStore {
|
|||
allow_jump: bool,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Task<Result<Option<EditPredictionResult>>> {
|
||||
let is_cloud_zeta = matches!(self.edit_prediction_model, EditPredictionModel::Zeta)
|
||||
&& !matches!(
|
||||
all_language_settings(None, cx).edit_predictions.provider,
|
||||
EditPredictionProvider::Ollama | EditPredictionProvider::OpenAiCompatibleApi
|
||||
);
|
||||
if is_cloud_zeta && !self.client.cloud_client().has_credentials() {
|
||||
return Task::ready(Ok(None));
|
||||
}
|
||||
|
||||
self.get_or_init_project(&project, cx);
|
||||
let project_state = self.projects.get(&project.entity_id()).unwrap();
|
||||
let stored_events = project_state.events(cx);
|
||||
|
|
@ -2551,11 +2580,24 @@ impl EditPredictionStore {
|
|||
EditPredictionsMode::Subtle => PredictEditsMode::Subtle,
|
||||
};
|
||||
|
||||
let is_open_source = snapshot
|
||||
.file()
|
||||
.map_or(false, |file| self.is_file_open_source(&project, file, cx))
|
||||
&& events.iter().all(|event| event.in_open_source_repo())
|
||||
&& related_files.iter().all(|file| file.in_open_source_repo);
|
||||
let buffer_id = active_buffer.read(cx).remote_id();
|
||||
let repo_url = project
|
||||
.read(cx)
|
||||
.git_store()
|
||||
.read(cx)
|
||||
.repository_and_path_for_buffer_id(buffer_id, cx)
|
||||
.and_then(|(repo, _)| repo.read(cx).default_remote_url());
|
||||
|
||||
let is_staff_zed_repo = cx.is_staff()
|
||||
&& repo_url
|
||||
.as_ref()
|
||||
.is_some_and(|url| is_zed_industries_repo(url));
|
||||
let is_open_source = is_staff_zed_repo
|
||||
|| (snapshot
|
||||
.file()
|
||||
.map_or(false, |file| self.is_file_open_source(&project, file, cx))
|
||||
&& events.iter().all(|event| event.in_open_source_repo())
|
||||
&& related_files.iter().all(|file| file.in_open_source_repo));
|
||||
|
||||
let can_collect_data = !cfg!(test)
|
||||
&& is_open_source
|
||||
|
|
@ -2594,7 +2636,7 @@ impl EditPredictionStore {
|
|||
)
|
||||
});
|
||||
|
||||
zeta::request_prediction_with_zeta(self, inputs, capture_events, cx)
|
||||
zeta::request_prediction_with_zeta(self, inputs, capture_events, repo_url, cx)
|
||||
}
|
||||
EditPredictionModel::Fim { format } => fim::request_prediction(inputs, format, cx),
|
||||
EditPredictionModel::Mercury => {
|
||||
|
|
@ -3286,3 +3328,11 @@ pub fn init(cx: &mut App) {
|
|||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn is_zed_industries_repo(url: &str) -> bool {
|
||||
url.strip_prefix("https://github.com/zed-industries/")
|
||||
.or_else(|| url.strip_prefix("http://github.com/zed-industries/"))
|
||||
.or_else(|| url.strip_prefix("git@github.com:zed-industries/"))
|
||||
.or_else(|| url.strip_prefix("ssh://git@github.com/zed-industries/"))
|
||||
.is_some_and(|repo| !repo.is_empty())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,8 +26,8 @@ use gpui::{
|
|||
};
|
||||
use indoc::indoc;
|
||||
use language::{
|
||||
Anchor, Buffer, Capability, CursorShape, Diagnostic, DiagnosticEntry, DiagnosticSet,
|
||||
DiagnosticSeverity, Operation, Point, Selection, SelectionGoal,
|
||||
Anchor, Buffer, BufferEditSource, Capability, CursorShape, Diagnostic, DiagnosticEntry,
|
||||
DiagnosticSet, DiagnosticSeverity, Operation, Point, Selection, SelectionGoal,
|
||||
};
|
||||
|
||||
use lsp::LanguageServerId;
|
||||
|
|
@ -352,6 +352,70 @@ async fn test_diagnostics_refresh_suppressed_while_following(cx: &mut TestAppCon
|
|||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_diagnostics_refresh_suppressed_after_agent_edit(cx: &mut TestAppContext) {
|
||||
let (ep_store, mut requests) = init_test_with_fake_client(cx);
|
||||
|
||||
cx.update(|cx| {
|
||||
cx.update_flags(
|
||||
false,
|
||||
vec![EditPredictionJumpsFeatureFlag::NAME.to_string()],
|
||||
);
|
||||
});
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(
|
||||
"/root",
|
||||
json!({
|
||||
"1.txt": "Hello!\nHow\nBye\n",
|
||||
"2.txt": "Hola!\nComo\nAdios\n"
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
|
||||
|
||||
let buffer = project
|
||||
.update(cx, |project, cx| {
|
||||
let path = project.find_project_path(path!("root/1.txt"), cx).unwrap();
|
||||
project.set_active_path(Some(path.clone()), cx);
|
||||
project.open_buffer(path, cx)
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
ep_store.update(cx, |ep_store, cx| {
|
||||
ep_store.register_project(&project, cx);
|
||||
ep_store.register_buffer(&buffer, &project, cx);
|
||||
});
|
||||
|
||||
buffer.update(cx, |buffer, cx| {
|
||||
buffer.start_transaction();
|
||||
buffer.edit([(Point::new(1, 3)..Point::new(1, 3), "!")], None, cx);
|
||||
buffer.end_transaction_with_source(BufferEditSource::Agent, cx);
|
||||
});
|
||||
cx.run_until_parked();
|
||||
|
||||
update_test_diagnostics(&project, path!("/root/2.txt"), "Sentence is incomplete", cx);
|
||||
cx.run_until_parked();
|
||||
assert_no_predict_request_ready(&mut requests.predict);
|
||||
|
||||
buffer.update(cx, |buffer, cx| {
|
||||
buffer.edit([(Point::new(1, 4)..Point::new(1, 4), "?")], None, cx);
|
||||
});
|
||||
cx.run_until_parked();
|
||||
|
||||
update_test_diagnostics(
|
||||
&project,
|
||||
path!("/root/2.txt"),
|
||||
"Sentence is still incomplete",
|
||||
cx,
|
||||
);
|
||||
|
||||
let (_request, respond_tx) = requests.predict.next().await.unwrap();
|
||||
respond_tx.send(empty_response()).unwrap();
|
||||
cx.run_until_parked();
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_simple_request(cx: &mut TestAppContext) {
|
||||
let (ep_store, mut requests) = init_test_with_fake_client(cx);
|
||||
|
|
@ -2498,6 +2562,39 @@ fn assert_no_predict_request_ready(
|
|||
}
|
||||
}
|
||||
|
||||
fn update_test_diagnostics(
|
||||
project: &Entity<Project>,
|
||||
path: &str,
|
||||
message: &str,
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let diagnostic = lsp::Diagnostic {
|
||||
range: lsp::Range::new(lsp::Position::new(1, 1), lsp::Position::new(1, 5)),
|
||||
severity: Some(lsp::DiagnosticSeverity::ERROR),
|
||||
message: message.to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
project.update(cx, |project, cx| {
|
||||
project.lsp_store().update(cx, |lsp_store, cx| {
|
||||
lsp_store
|
||||
.update_diagnostics(
|
||||
LanguageServerId(0),
|
||||
lsp::PublishDiagnosticsParams {
|
||||
uri: lsp::Uri::from_file_path(path).unwrap(),
|
||||
diagnostics: vec![diagnostic],
|
||||
version: None,
|
||||
},
|
||||
None,
|
||||
language::DiagnosticSourceKind::Pushed,
|
||||
&[],
|
||||
cx,
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
struct RequestChannels {
|
||||
predict: mpsc::UnboundedReceiver<(
|
||||
PredictEditsV3Request,
|
||||
|
|
@ -3107,11 +3204,18 @@ async fn test_unauthenticated_without_custom_url_blocks_prediction_impl(cx: &mut
|
|||
|
||||
let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
|
||||
|
||||
let http_client = FakeHttpClient::create(|_req| async move {
|
||||
Ok(gpui::http_client::Response::builder()
|
||||
.status(401)
|
||||
.body("Unauthorized".into())
|
||||
.unwrap())
|
||||
let request_count = Arc::new(std::sync::atomic::AtomicUsize::default());
|
||||
let http_client = FakeHttpClient::create({
|
||||
let request_count = request_count.clone();
|
||||
move |_req| {
|
||||
request_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
async move {
|
||||
Ok(gpui::http_client::Response::builder()
|
||||
.status(401)
|
||||
.body("Unauthorized".into())
|
||||
.unwrap())
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let client =
|
||||
|
|
@ -3144,11 +3248,8 @@ async fn test_unauthenticated_without_custom_url_blocks_prediction_impl(cx: &mut
|
|||
ep_store.request_prediction(&project, &buffer, cursor, Default::default(), cx)
|
||||
});
|
||||
|
||||
let result = completion_task.await;
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"Without authentication and without custom URL, prediction should fail"
|
||||
);
|
||||
assert!(completion_task.await.unwrap().is_none());
|
||||
assert_eq!(request_count.load(std::sync::atomic::Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
|
|||
|
|
@ -53,6 +53,7 @@ pub fn request_prediction_with_zeta(
|
|||
Vec<crate::StoredEvent>,
|
||||
Task<Result<collections::HashMap<Arc<Path>, Entity<BufferDiff>>>>,
|
||||
)>,
|
||||
repo_url: Option<String>,
|
||||
cx: &mut Context<EditPredictionStore>,
|
||||
) -> Task<Result<Option<EditPredictionResult>>> {
|
||||
let settings = &all_language_settings(None, cx).edit_predictions;
|
||||
|
|
@ -73,17 +74,7 @@ pub fn request_prediction_with_zeta(
|
|||
|
||||
let excerpt_path = buffer_path_with_id_fallback(snapshot.file(), &snapshot.text, cx);
|
||||
|
||||
let repo_url = if can_collect_data {
|
||||
let buffer_id = buffer.read(cx).remote_id();
|
||||
project
|
||||
.read(cx)
|
||||
.git_store()
|
||||
.read(cx)
|
||||
.repository_and_path_for_buffer_id(buffer_id, cx)
|
||||
.and_then(|(repo, _)| repo.read(cx).default_remote_url())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let repo_url = repo_url.filter(|_| can_collect_data);
|
||||
let client = store.client.clone();
|
||||
let llm_token = store.llm_token.clone();
|
||||
let organization_id = store
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ terminal_view.workspace = true
|
|||
util.workspace = true
|
||||
watch.workspace = true
|
||||
edit_prediction = { workspace = true, features = ["cli-support"] }
|
||||
edit_prediction_metrics.workspace = true
|
||||
edit_prediction_metrics = { workspace = true, features = ["tree-sitter"] }
|
||||
telemetry_events.workspace = true
|
||||
wasmtime.workspace = true
|
||||
zeta_prompt.workspace = true
|
||||
|
|
|
|||
|
|
@ -11,12 +11,15 @@ workspace = true
|
|||
[lib]
|
||||
path = "src/edit_prediction_metrics.rs"
|
||||
|
||||
[features]
|
||||
tree-sitter = ["dep:tree-sitter"]
|
||||
|
||||
[dependencies]
|
||||
imara-diff.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json = "1.0"
|
||||
similar = "2.7.0"
|
||||
tree-sitter.workspace = true
|
||||
tree-sitter = { workspace = true, optional = true }
|
||||
zeta_prompt.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ mod prediction_score;
|
|||
mod reversal;
|
||||
mod summary;
|
||||
mod tokenize;
|
||||
#[cfg(feature = "tree-sitter")]
|
||||
mod tree_sitter;
|
||||
|
||||
pub use kept_rate::AnnotatedToken;
|
||||
|
|
@ -30,4 +31,5 @@ pub use prediction_score::{
|
|||
};
|
||||
pub use reversal::compute_prediction_reversal_ratio_from_history;
|
||||
pub use summary::{PredictionSummaryInput, QaSummaryData, SummaryJson, compute_summary};
|
||||
#[cfg(feature = "tree-sitter")]
|
||||
pub use tree_sitter::count_tree_sitter_errors;
|
||||
|
|
|
|||
|
|
@ -323,7 +323,8 @@ pub struct SplitSelectionIntoLines {
|
|||
pub keep_selections: bool,
|
||||
}
|
||||
|
||||
/// Goes to the next diagnostic in the file.
|
||||
/// Expands the diagnostic under the cursor, if any, in case diagnostics are not
|
||||
/// yet active. Otherwise, goes to the next diagnostic in the file.
|
||||
#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
|
||||
#[action(namespace = editor)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
|
|
@ -332,7 +333,8 @@ pub struct GoToDiagnostic {
|
|||
pub severity: GoToDiagnosticSeverityFilter,
|
||||
}
|
||||
|
||||
/// Goes to the previous diagnostic in the file.
|
||||
/// Expands the diagnostic under the cursor, if any, in case diagnostics are not
|
||||
/// yet active. Otherwise, goes to the previous diagnostic in the file.
|
||||
#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
|
||||
#[action(namespace = editor)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
|
|
|
|||
|
|
@ -77,7 +77,8 @@ impl Editor {
|
|||
if !self.diagnostics_enabled() {
|
||||
return;
|
||||
}
|
||||
self.go_to_diagnostic_impl(Direction::Next, action.severity, window, cx)
|
||||
|
||||
self.go_to_diagnostic_at_cursor(Direction::Next, action.severity, window, cx);
|
||||
}
|
||||
|
||||
pub fn go_to_prev_diagnostic(
|
||||
|
|
@ -89,10 +90,43 @@ impl Editor {
|
|||
if !self.diagnostics_enabled() {
|
||||
return;
|
||||
}
|
||||
self.go_to_diagnostic_impl(Direction::Prev, action.severity, window, cx)
|
||||
|
||||
self.go_to_diagnostic_at_cursor(Direction::Prev, action.severity, window, cx);
|
||||
}
|
||||
|
||||
pub fn go_to_diagnostic_impl(
|
||||
fn diagnostics_before_cursor<'a>(
|
||||
buffer: &'a MultiBufferSnapshot,
|
||||
cursor: MultiBufferOffset,
|
||||
severity: GoToDiagnosticSeverityFilter,
|
||||
) -> impl Iterator<Item = DiagnosticEntryRef<'a, MultiBufferOffset>> {
|
||||
buffer
|
||||
.diagnostics_in_range(MultiBufferOffset(0)..cursor)
|
||||
.filter(move |entry| entry.range.start <= cursor)
|
||||
.filter(move |entry| severity.matches(entry.diagnostic.severity))
|
||||
.filter(|entry| entry.range.start != entry.range.end)
|
||||
.filter(|entry| !entry.diagnostic.is_unnecessary)
|
||||
}
|
||||
|
||||
fn diagnostics_after_cursor<'a>(
|
||||
buffer: &'a MultiBufferSnapshot,
|
||||
cursor: MultiBufferOffset,
|
||||
severity: GoToDiagnosticSeverityFilter,
|
||||
) -> impl Iterator<Item = DiagnosticEntryRef<'a, MultiBufferOffset>> {
|
||||
buffer
|
||||
.diagnostics_in_range(cursor..buffer.len())
|
||||
.filter(move |entry| entry.range.start >= cursor)
|
||||
.filter(move |entry| severity.matches(entry.diagnostic.severity))
|
||||
.filter(|entry| entry.range.start != entry.range.end)
|
||||
.filter(|entry| !entry.diagnostic.is_unnecessary)
|
||||
}
|
||||
|
||||
/// Attempts to expand the diagnostic at the current cursor position,
|
||||
/// updating the cursor position to the diagnostic's start point.
|
||||
///
|
||||
/// In case there's no diagnostic at the current cursor position, this will
|
||||
/// fallback to finding the next or previous diagnostic instead, depending
|
||||
/// on the provided `direction`.
|
||||
pub fn go_to_diagnostic_at_cursor(
|
||||
&mut self,
|
||||
direction: Direction,
|
||||
severity: GoToDiagnosticSeverityFilter,
|
||||
|
|
@ -104,6 +138,71 @@ impl Editor {
|
|||
.selections
|
||||
.newest::<MultiBufferOffset>(&self.display_snapshot(cx));
|
||||
|
||||
let before = Self::diagnostics_before_cursor(&buffer, selection.start, severity);
|
||||
let after = Self::diagnostics_after_cursor(&buffer, selection.start, severity);
|
||||
let active_group_id = match &self.active_diagnostics {
|
||||
ActiveDiagnostic::Group(group) => Some(group.group_id),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let mut cursor_on_active = false;
|
||||
let mut target = None;
|
||||
|
||||
for diagnostic in after.chain(before) {
|
||||
let contains_cursor = diagnostic.range.contains(&selection.start)
|
||||
|| diagnostic.range.end == selection.head();
|
||||
|
||||
if !contains_cursor {
|
||||
continue;
|
||||
}
|
||||
|
||||
if active_group_id == Some(diagnostic.diagnostic.group_id) {
|
||||
cursor_on_active = true;
|
||||
} else if target.is_none() {
|
||||
target = Some(diagnostic);
|
||||
}
|
||||
}
|
||||
|
||||
match (target, cursor_on_active) {
|
||||
(Some(diagnostic), false) => self.activate_diagnostic(&buffer, diagnostic, window, cx),
|
||||
_ => self.go_to_diagnostic_in_direction(
|
||||
&buffer, &selection, direction, severity, window, cx,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn activate_diagnostic(
|
||||
&mut self,
|
||||
buffer: &MultiBufferSnapshot,
|
||||
diagnostic: DiagnosticEntryRef<MultiBufferOffset>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let diagnostic_start = buffer.anchor_after(diagnostic.range.start);
|
||||
let Some((buffer_anchor, _)) = buffer.anchor_to_buffer_anchor(diagnostic_start) else {
|
||||
return;
|
||||
};
|
||||
let buffer_id = buffer_anchor.buffer_id;
|
||||
let snapshot = self.snapshot(window, cx);
|
||||
if snapshot.intersects_fold(diagnostic.range.start) {
|
||||
self.unfold_ranges(std::slice::from_ref(&diagnostic.range), true, false, cx);
|
||||
}
|
||||
self.change_selections(Default::default(), window, cx, |s| {
|
||||
s.select_ranges(vec![diagnostic.range.start..diagnostic.range.start])
|
||||
});
|
||||
self.activate_diagnostics(buffer_id, diagnostic, window, cx);
|
||||
self.refresh_edit_prediction(false, true, window, cx);
|
||||
}
|
||||
|
||||
pub fn go_to_diagnostic_in_direction(
|
||||
&mut self,
|
||||
buffer: &MultiBufferSnapshot,
|
||||
selection: &Selection<MultiBufferOffset>,
|
||||
direction: Direction,
|
||||
severity: GoToDiagnosticSeverityFilter,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let mut active_group_id = None;
|
||||
if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics
|
||||
&& active_group.active_range.start.to_offset(&buffer) == selection.start
|
||||
|
|
@ -111,28 +210,8 @@ impl Editor {
|
|||
active_group_id = Some(active_group.group_id);
|
||||
}
|
||||
|
||||
fn filtered<'a>(
|
||||
severity: GoToDiagnosticSeverityFilter,
|
||||
diagnostics: impl Iterator<Item = DiagnosticEntryRef<'a, MultiBufferOffset>>,
|
||||
) -> impl Iterator<Item = DiagnosticEntryRef<'a, MultiBufferOffset>> {
|
||||
diagnostics
|
||||
.filter(move |entry| severity.matches(entry.diagnostic.severity))
|
||||
.filter(|entry| entry.range.start != entry.range.end)
|
||||
.filter(|entry| !entry.diagnostic.is_unnecessary)
|
||||
}
|
||||
|
||||
let before = filtered(
|
||||
severity,
|
||||
buffer
|
||||
.diagnostics_in_range(MultiBufferOffset(0)..selection.start)
|
||||
.filter(|entry| entry.range.start <= selection.start),
|
||||
);
|
||||
let after = filtered(
|
||||
severity,
|
||||
buffer
|
||||
.diagnostics_in_range(selection.start..buffer.len())
|
||||
.filter(|entry| entry.range.start >= selection.start),
|
||||
);
|
||||
let before = Self::diagnostics_before_cursor(&buffer, selection.start, severity);
|
||||
let after = Self::diagnostics_after_cursor(&buffer, selection.start, severity);
|
||||
|
||||
let mut found: Option<DiagnosticEntryRef<MultiBufferOffset>> = None;
|
||||
if direction == Direction::Prev {
|
||||
|
|
@ -158,31 +237,12 @@ impl Editor {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(next_diagnostic) = found else {
|
||||
return;
|
||||
};
|
||||
|
||||
let next_diagnostic_start = buffer.anchor_after(next_diagnostic.range.start);
|
||||
let Some((buffer_anchor, _)) = buffer.anchor_to_buffer_anchor(next_diagnostic_start) else {
|
||||
return;
|
||||
};
|
||||
let buffer_id = buffer_anchor.buffer_id;
|
||||
let snapshot = self.snapshot(window, cx);
|
||||
if snapshot.intersects_fold(next_diagnostic.range.start) {
|
||||
self.unfold_ranges(
|
||||
std::slice::from_ref(&next_diagnostic.range),
|
||||
true,
|
||||
false,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
self.change_selections(Default::default(), window, cx, |s| {
|
||||
s.select_ranges(vec![
|
||||
next_diagnostic.range.start..next_diagnostic.range.start,
|
||||
])
|
||||
});
|
||||
self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
|
||||
self.refresh_edit_prediction(false, true, window, cx);
|
||||
self.activate_diagnostic(&buffer, next_diagnostic, window, cx);
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
|
|
@ -324,32 +384,37 @@ impl Editor {
|
|||
return;
|
||||
}
|
||||
self.dismiss_diagnostics(cx);
|
||||
let snapshot = self.snapshot(window, cx);
|
||||
let buffer = self.buffer.read(cx).snapshot(cx);
|
||||
let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
|
||||
return;
|
||||
|
||||
let blocks = if let Some(renderer) = GlobalDiagnosticRenderer::global(cx) {
|
||||
let snapshot = self.snapshot(window, cx);
|
||||
let diagnostic_group = buffer
|
||||
.diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let language_registry = self
|
||||
.project()
|
||||
.map(|project| project.read(cx).languages().clone());
|
||||
|
||||
let blocks = renderer.render_group(
|
||||
diagnostic_group,
|
||||
buffer_id,
|
||||
snapshot,
|
||||
cx.weak_entity(),
|
||||
language_registry,
|
||||
cx,
|
||||
);
|
||||
|
||||
self.display_map.update(cx, |display_map, cx| {
|
||||
display_map.insert_blocks(blocks, cx).into_iter().collect()
|
||||
})
|
||||
} else {
|
||||
// Ensure that, even if there's no global renderer set, we still use
|
||||
// an empty set of blocks, such that we can record the active group
|
||||
// below instead of bailing out.
|
||||
HashSet::default()
|
||||
};
|
||||
|
||||
let diagnostic_group = buffer
|
||||
.diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let language_registry = self
|
||||
.project()
|
||||
.map(|project| project.read(cx).languages().clone());
|
||||
|
||||
let blocks = renderer.render_group(
|
||||
diagnostic_group,
|
||||
buffer_id,
|
||||
snapshot,
|
||||
cx.weak_entity(),
|
||||
language_registry,
|
||||
cx,
|
||||
);
|
||||
|
||||
let blocks = self.display_map.update(cx, |display_map, cx| {
|
||||
display_map.insert_blocks(blocks, cx).into_iter().collect()
|
||||
});
|
||||
self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
|
||||
active_range: buffer.anchor_before(diagnostic.range.start)
|
||||
..buffer.anchor_after(diagnostic.range.end),
|
||||
|
|
@ -516,4 +581,12 @@ impl Editor {
|
|||
self.scrollbar_marker_state.dirty = true;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub fn any_active_diagnostics(&self) -> bool {
|
||||
match &self.active_diagnostics {
|
||||
ActiveDiagnostic::None => false,
|
||||
ActiveDiagnostic::All => true,
|
||||
ActiveDiagnostic::Group(_) => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9231,7 +9231,7 @@ impl Editor {
|
|||
match event {
|
||||
multi_buffer::Event::Edited {
|
||||
edited_buffer,
|
||||
is_local,
|
||||
source,
|
||||
} => {
|
||||
self.scrollbar_marker_state.dirty = true;
|
||||
self.active_indent_guides_state.dirty = true;
|
||||
|
|
@ -9242,7 +9242,7 @@ impl Editor {
|
|||
self.refresh_matching_bracket_highlights(&snapshot, cx);
|
||||
self.refresh_outline_symbols_at_cursor(cx);
|
||||
self.refresh_sticky_headers(&snapshot, cx);
|
||||
if *is_local && self.has_active_edit_prediction() {
|
||||
if source.is_local() && self.has_active_edit_prediction() {
|
||||
self.update_visible_edit_prediction(window, cx);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -20506,6 +20506,130 @@ async fn go_to_prev_overlapping_diagnostic(executor: BackgroundExecutor, cx: &mu
|
|||
"});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn go_to_diagnostic(executor: BackgroundExecutor, cx: &mut TestAppContext) {
|
||||
init_test(cx, |_| {});
|
||||
|
||||
let mut cx = EditorTestContext::new(cx).await;
|
||||
let lsp_store =
|
||||
cx.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).lsp_store());
|
||||
|
||||
// Place the cursor inside the `def` diagnostic (`[12, 15)`) before any
|
||||
// diagnostic is active so we can later confirm that running `editor: go to
|
||||
// diagnostic` will activate this diagnostic instead of advancing to the
|
||||
// next one.
|
||||
cx.set_state(indoc! {"
|
||||
fn func(abc dˇef: i32) -> u32 {
|
||||
}
|
||||
"});
|
||||
|
||||
// Set up the diagnostics:
|
||||
//
|
||||
// * `[11, 12)` (the space before `def`),
|
||||
// * `[12, 15)` (`def`),
|
||||
// * `[25, 28)` (`u32`).
|
||||
cx.update(|_, cx| {
|
||||
lsp_store.update(cx, |lsp_store, cx| {
|
||||
lsp_store
|
||||
.update_diagnostics(
|
||||
LanguageServerId(0),
|
||||
lsp::PublishDiagnosticsParams {
|
||||
uri: lsp::Uri::from_file_path(path!("/root/file")).unwrap(),
|
||||
version: None,
|
||||
diagnostics: vec![
|
||||
lsp::Diagnostic {
|
||||
range: lsp::Range::new(
|
||||
lsp::Position::new(0, 11),
|
||||
lsp::Position::new(0, 12),
|
||||
),
|
||||
severity: Some(lsp::DiagnosticSeverity::ERROR),
|
||||
..Default::default()
|
||||
},
|
||||
lsp::Diagnostic {
|
||||
range: lsp::Range::new(
|
||||
lsp::Position::new(0, 12),
|
||||
lsp::Position::new(0, 15),
|
||||
),
|
||||
severity: Some(lsp::DiagnosticSeverity::ERROR),
|
||||
..Default::default()
|
||||
},
|
||||
lsp::Diagnostic {
|
||||
range: lsp::Range::new(
|
||||
lsp::Position::new(0, 25),
|
||||
lsp::Position::new(0, 28),
|
||||
),
|
||||
severity: Some(lsp::DiagnosticSeverity::ERROR),
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
},
|
||||
None,
|
||||
DiagnosticSourceKind::Pushed,
|
||||
&[],
|
||||
cx,
|
||||
)
|
||||
.unwrap()
|
||||
});
|
||||
});
|
||||
|
||||
executor.run_until_parked();
|
||||
|
||||
// When the cursor is at an inactive diagnostic, cursor should be moved to
|
||||
// the start of that same diagnostic and activate it.
|
||||
cx.update_editor(|editor, window, cx| {
|
||||
editor.go_to_diagnostic(&GoToDiagnostic::default(), window, cx);
|
||||
});
|
||||
cx.assert_editor_state(indoc! {"
|
||||
fn func(abc ˇdef: i32) -> u32 {
|
||||
}
|
||||
"});
|
||||
|
||||
cx.update_editor(|editor, window, cx| {
|
||||
editor.go_to_diagnostic(&GoToDiagnostic::default(), window, cx);
|
||||
});
|
||||
cx.assert_editor_state(indoc! {"
|
||||
fn func(abc def: i32) -> ˇu32 {
|
||||
}
|
||||
"});
|
||||
|
||||
cx.update_editor(|editor, window, cx| {
|
||||
editor.go_to_diagnostic(&GoToDiagnostic::default(), window, cx);
|
||||
});
|
||||
cx.assert_editor_state(indoc! {"
|
||||
fn func(abcˇ def: i32) -> u32 {
|
||||
}
|
||||
"});
|
||||
|
||||
// Manually move the cursor to a different, not yet active diagnostic to
|
||||
// confirm that using `editor: go to diagnostic` will now activate this one.
|
||||
cx.update_editor(|editor, window, cx| {
|
||||
editor.change_selections(Default::default(), window, cx, |s| {
|
||||
s.select_ranges([Point::new(0, 26)..Point::new(0, 26)])
|
||||
});
|
||||
});
|
||||
|
||||
cx.update_editor(|editor, window, cx| {
|
||||
editor.go_to_diagnostic(&GoToDiagnostic::default(), window, cx);
|
||||
});
|
||||
cx.assert_editor_state(indoc! {"
|
||||
fn func(abc def: i32) -> ˇu32 {
|
||||
}
|
||||
"});
|
||||
|
||||
cx.update_editor(|editor, window, cx| {
|
||||
editor.change_selections(Default::default(), window, cx, |s| {
|
||||
s.select_ranges([Point::new(0, 0)..Point::new(0, 0)])
|
||||
});
|
||||
});
|
||||
cx.update_editor(|editor, window, cx| {
|
||||
editor.go_to_diagnostic(&GoToDiagnostic::default(), window, cx);
|
||||
});
|
||||
cx.assert_editor_state(indoc! {"
|
||||
fn func(abcˇ def: i32) -> u32 {
|
||||
}
|
||||
"});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_go_to_hunk(executor: BackgroundExecutor, cx: &mut TestAppContext) {
|
||||
init_test(cx, |_| {});
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
1055
crates/editor/src/element/header.rs
Normal file
1055
crates/editor/src/element/header.rs
Normal file
File diff suppressed because it is too large
Load diff
1187
crates/editor/src/element/mouse.rs
Normal file
1187
crates/editor/src/element/mouse.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1162,6 +1162,7 @@ impl InfoPopover {
|
|||
.track_scroll(&self.scroll_handle)
|
||||
.child(
|
||||
MarkdownElement::new(markdown, hover_markdown_style(window, cx))
|
||||
.scroll_handle(self.scroll_handle.clone())
|
||||
.code_block_renderer(markdown::CodeBlockRenderer::Default {
|
||||
copy_button_visibility: CopyButtonVisibility::Hidden,
|
||||
wrap_button_visibility: markdown::WrapButtonVisibility::Hidden,
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue