mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 18:43:16 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19207f1102 |
No files matched your search
@@ -0,0 +1,83 @@
|
||||
---
|
||||
name: eval
|
||||
description: Run the code-intelligence evals (`pnpm eval`), pick the worst failing scenario, diagnose it from the attached timeline, fix it, prove the fix with before / after numbers measured on this machine without regressing other scenarios, and open one PR. Use for "跑 eval", "优化 Java 代码智能", "eval 失败了", an issue labelled `eval`, or any change to Java navigation / usages / gutter markers that needs numbers.
|
||||
---
|
||||
|
||||
# Eval loop: measure → fix → prove
|
||||
|
||||
`pnpm eval` drives the production workbench in Chromium against a release `openidea-server`
|
||||
with real language servers (Java / jdtls for now) and judges every scenario on what the user
|
||||
sees: time to feedback, to the first result, to the final one, and the results themselves vs
|
||||
`evals/<language>/golden/`. One machine, before and after: numbers from different machines or
|
||||
from the nightly host don't judge a fix.
|
||||
|
||||
## 0. Preconditions
|
||||
|
||||
- `jdtls` on PATH and `JAVA_HOME` pointing at a JDK of the pinned `JAVA` version (projects
|
||||
compile against it, and the JDK scenarios' results are in its sources; jdtls itself runs on
|
||||
a newer installed JDK when it needs one). Pinned versions: `.github/tool-versions.env`. A
|
||||
mismatch prints a warning and the report records both: say so in the PR when it applies.
|
||||
- First run builds `cargo build --release -p ide-host --bin openidea-server` and the perf
|
||||
bundle; later iterations of a frontend-only change can use `--no-build` after a
|
||||
`pnpm exec vite build --mode perf --outDir target/eval/dist`, a backend-only one after the
|
||||
cargo build alone.
|
||||
- Run evals one at a time on this machine, with nothing heavy (builds, other evals) beside them.
|
||||
|
||||
## 1. Baseline on the base commit
|
||||
|
||||
```sh
|
||||
git switch --detach origin/main # or the fix branch's merge base
|
||||
pnpm eval --save-baseline # target/eval/baseline.json, this machine only
|
||||
```
|
||||
|
||||
Read `target/eval/report.json`. Each verdict has `status`, `failures` (`kind`: `error`,
|
||||
`timeout`, `degraded`, `correctness`, `budget`, `golden`), `regressions`, `repro` (the command
|
||||
that reruns it) and, for failures, `diagnostics`: every command sent to the server in the
|
||||
slowest run's window (`cmd`, `start`, `ms`, `ok`, `bytes`, `items`), background tasks, server
|
||||
status changes and the server's log tail.
|
||||
|
||||
## 2. Pick one problem
|
||||
|
||||
Worst first: wrong or missing results and silent degradation, then timeouts, then the
|
||||
feedback budget (100 ms), then the slowest `completeMs`. One problem per PR. Say which
|
||||
scenario and metric, with its value vs budget.
|
||||
|
||||
## 3. Diagnose from the timeline
|
||||
|
||||
- Commands in the window ordered by `start`: what ran, what waited on what, what's serial
|
||||
that could overlap, which request returned many `items`/`bytes`, which failed.
|
||||
- `feedbackMs` far above 16 ms with a fast `firstResultMs`: the UI shows nothing while it
|
||||
waits (a hint or popup that only appears after a delay).
|
||||
- A task still running across the window: background work competing with the request.
|
||||
- For the frontend side rerun with `--trace` and open `target/eval/traces/<id>@<cond>.json`
|
||||
in Chrome's Performance panel.
|
||||
- Name the cause at class level (as in `issue-fix`): it usually affects sibling scenarios.
|
||||
|
||||
## 4. Fix, then rerun that scenario until it passes
|
||||
|
||||
```sh
|
||||
pnpm eval --only <scenario> --condition <warm|cold> # the verdict's `repro`
|
||||
```
|
||||
|
||||
Correctness is enforced, so a faster answer that drops, truncates or serves stale results
|
||||
fails. Don't trade a budget miss for a degraded answer.
|
||||
|
||||
## 5. Full suite, then PR
|
||||
|
||||
```sh
|
||||
pnpm eval # vs the baseline from step 1: no new failures or regressions
|
||||
```
|
||||
|
||||
PR per `issue-fix` §6, plus in **How it was verified** the before / after table from
|
||||
`target/eval/report.md` (both on this machine, commits named) and the tool versions line.
|
||||
|
||||
## Guard rails
|
||||
|
||||
- Goldens (`evals/*/golden/`) and budgets (`evals/budgets.json`) are human-owned. Don't edit
|
||||
them, and don't run `--update-golden`, to make a scenario pass. When a golden looks wrong
|
||||
(a tool bump, a deliberate behaviour change), stop and say so: a PR that touches them gets
|
||||
`needs-decision`.
|
||||
- Don't weaken a scenario's checks or timeouts in `evals/<language>/scenarios.ts` to pass.
|
||||
Adding a scenario (for a case the sweep or a user found) is fine; record its golden with
|
||||
`--update-golden --only <id>` and ask a person to review the file.
|
||||
- A flaky timing (passes on rerun) is not a regression: rerun once before acting on one.
|
||||
@@ -0,0 +1,91 @@
|
||||
---
|
||||
name: issue-fix
|
||||
description: Triage and fix a GitHub issue (or a user-reported bug) end to end — reproduce, find the root cause, generalise it to every sibling case, fix the class rather than the instance, verify, and open one PR. Use when given an issue URL/number or asked to fix a reported bug and open a PR ("看看这个 issue", "修一下这个 bug", "提 pr").
|
||||
---
|
||||
|
||||
# Fix an issue: from one case to the whole class
|
||||
|
||||
The reported case is one sample of a defect class. A fix that only makes the
|
||||
screenshot go away is not done: the next question is always "does this break for other
|
||||
languages / platforms / entry points too?". Answer that before anyone asks.
|
||||
|
||||
## 1. Read and reproduce
|
||||
|
||||
- `gh issue view <n> --comments` (repo `l0ng-ai/openidea`). Read attached logs/screenshots
|
||||
closely: OS, language, toolchain versions, exact error text.
|
||||
- Locate the code path and confirm the claim in code, with `file:line` evidence.
|
||||
Say plainly whether it is a real bug, a missing feature, or user environment.
|
||||
- Reproduce locally when possible (`fixtures/` projects, `/verify` for runtime). If the
|
||||
reporter's platform (often Windows/Linux) can't be reproduced here, say so up front.
|
||||
- Do not ask for a generic environment/log checklist before trying the flow and inspecting the code.
|
||||
Record the attempt and result; ask only for a fact that actually blocks the next diagnostic step.
|
||||
Missing fields, limited time, or unavailable automation are not by themselves reasons to ask the reporter.
|
||||
- Treat a maintainer-confirmed bug as an investigation task even if local reproduction fails. Distinguish
|
||||
“not reproduced here” from “not a bug”, and do not require the reporter to prove its existence again.
|
||||
|
||||
## 2. Name the root cause as a class
|
||||
|
||||
Write one sentence of the form "<mechanism> is missing/wrong, so any <X> hits it",
|
||||
not "<this button> is broken". Typical classes in this codebase:
|
||||
|
||||
- Per-language config handled for one language only (`languages/*.toml`, `ide-sdk`).
|
||||
- Platform gaps: paths, executables, shells, `.cmd`/`.exe`, separators — macOS-only code.
|
||||
- Toolchain/version discovery: one probe location, no version check, no rescan.
|
||||
- Two features each implementing half a flow and never joined (feature isolation →
|
||||
should go through an action/service).
|
||||
- State not reset on project switch / window reuse; events not scoped per window.
|
||||
- Failure surfaced as raw stderr/stack trace or retried until "crashed" instead of a
|
||||
clear status with an action.
|
||||
- UI: same primitive styled differently in N places.
|
||||
|
||||
## 3. Sweep for siblings
|
||||
|
||||
Search systematically, not by memory:
|
||||
|
||||
- Same pattern elsewhere: `git grep` the function, the config key, the error string,
|
||||
the hard-coded path/flag. Check every `languages/*.toml` entry and every platform branch.
|
||||
- Same flow for other languages/runtimes (Java ↔ Kotlin/Gradle, Python ↔ venv/uv,
|
||||
Node ↔ Deno/Bun, Go, Rust …): would they fail the same way?
|
||||
- Other callers/entry points of the same flow (menu, context menu, gutter, shortcut, CLI arg).
|
||||
- Neighbouring failure modes of the same mechanism (not installed / wrong version /
|
||||
installed but crashes / slow start / installed mid-session).
|
||||
For broad sweeps spawn one Explore agent with the class description, not the instance.
|
||||
|
||||
## 4. Decide the fix at the right altitude
|
||||
|
||||
- Fix the mechanism once (shared helper, action, config hook) so siblings are fixed
|
||||
by construction; don't patch each call site.
|
||||
- Respect `AGENTS.md` rules (crate boundaries, no cross-feature imports, `IdeResult`,
|
||||
UTF-16). If the right fix breaks a rule, pick the rule-respecting design and say why.
|
||||
- Compare with how established IDEs solve it when relevant; prefer the established answer.
|
||||
- Present: root cause, sibling table, proposed fix, what's deferred. When the user leaves
|
||||
the choice to you, go ahead without asking again.
|
||||
|
||||
## 5. Implement and test the class
|
||||
|
||||
- Tests cover the class: table-driven over languages/platforms/states, not just the
|
||||
reported input. Include the reporter's case verbatim.
|
||||
- Run the scoped checks (`pnpm vitest run <path>`, `cargo nextest run -p <crate>`), then
|
||||
`/verify` in the app for UI or runtime behaviour.
|
||||
|
||||
## 6. PR
|
||||
|
||||
- One branch `fix/<slug>`, one PR unless the user asks otherwise; `Fixes #<n>` in the body.
|
||||
- Don't stage untracked IDE-state dirs (`.ideal/`, `.openidea/`) or screenshots.
|
||||
- PR body follows `.github/pull_request_template.md`: `Closes #<n>`, then
|
||||
**What and why** (user-visible change + root cause at class level, 2–4 sentences),
|
||||
**How it was verified** (commands run and results, siblings fixed/deferred, what could break and how
|
||||
it was checked, what was not verified, e.g. "Windows not tested"; for UI changes the before/after
|
||||
screenshot paths from `/verify`), **Review focus** (optional). Short and plain.
|
||||
|
||||
## Report format
|
||||
|
||||
Reply in the user's language:
|
||||
|
||||
```
|
||||
Root cause: <one sentence, class level>
|
||||
Sibling sweep:
|
||||
| Location / case | Affected? | Action |
|
||||
Fixed / not covered (why) / not verified (platform)
|
||||
PR: <url>
|
||||
```
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
name: verify
|
||||
description: Build, launch and drive the OpenIDEA desktop app through the Tauri MCP bridge to verify a change at runtime.
|
||||
---
|
||||
|
||||
# Verify OpenIDEA in the running app
|
||||
|
||||
## Launch
|
||||
|
||||
- Run the app from the worktree that holds the change: `pnpm tauri dev` in the background, logging
|
||||
into your task's scratch subdirectory. Use `pnpm dev:app` instead when your checks call
|
||||
`window.__TAURI__` from `execute_js`. The wrapper gives each worktree its own app identity, data,
|
||||
settings and Vite port, so other worktrees and the installed app don't interfere. If it reports a
|
||||
session already running for this worktree, reuse that one.
|
||||
- Once the app is up, `pnpm dev:status` lists this worktree's MCP bridges. Pass the reported
|
||||
`appIdentifier` (the port) on every `mcp__tauri__*` call. The MCP server is shared between
|
||||
sessions: never `driver_session stop` without an `appIdentifier`, and re-check `document.title` /
|
||||
`location.href` before acting if anything looks off.
|
||||
- Make sure the binary contains the change: a session already running for this worktree may be an
|
||||
older build. Restart it after Rust changes; frontend changes reload through Vite.
|
||||
- After the app restarts, `driver_session start` again for your port (a stale session says "Already connected").
|
||||
- If the `pnpm tauri dev` process exits while the app window stays open, Vite is gone and any webview
|
||||
reload shows an empty `#root`. Stop that app and start the session again.
|
||||
- Stop everything you started when done and nothing else; never use process-name kills.
|
||||
|
||||
## Driving
|
||||
|
||||
- `manage_window focus` before screenshots / timing-sensitive steps: a background window throttles timers
|
||||
(debounced LSP / VCS refreshes stall, `setTimeout` promises in `execute_js` time out) and native
|
||||
screenshots come back black.
|
||||
- Settings is a separate native window `settings-main`; pass `windowId`, focus it before screenshotting.
|
||||
- CodeMirror / xterm ignore MCP `type`. Focus the element, then `document.execCommand('insertText', false, text)`.
|
||||
For xterm Enter, dispatch a `keydown` (`key: 'Enter', keyCode: 13`) on `.xterm-helper-textarea`.
|
||||
- MCP clicks arrive with `event.detail === 0`; CodeMirror treats them as line-select clicks. Set the caret
|
||||
through the view instead: `document.querySelector('.cm-content').cmTile.view`.
|
||||
- MCP `text` strategy can resolve to a hidden node; prefer coordinates (CSS px = image px × 0.9) or CSS selectors.
|
||||
- CSS-module edits often trigger a full page reload in dev: dialogs close, Run sessions and terminal
|
||||
scrollback reset, and each reload spawns a fresh shell. Re-open what you were testing.
|
||||
|
||||
## Evidence
|
||||
|
||||
- For UI or interaction changes, capture `before.png` (on `main` or with the fix reverted) and
|
||||
`after.png` at the same state and window size, into your task's scratch subdirectory. Multi-step
|
||||
flows: a numbered series (`after-1.png`, `after-2.png`, ...).
|
||||
- Report the absolute paths; they go into the PR's **How it was verified** section and the triage
|
||||
acceptance entry. Never commit screenshots to the feature branch.
|
||||
|
||||
## Fixture
|
||||
|
||||
`fixtures/` has sample projects (go-app, rust-app, ts-app, kotlin-gradle, polyglot). Copy one into
|
||||
your scratch directory before editing it, and don't commit the IDE state it creates (`.openidea/`).
|
||||
|
||||
## Flows worth driving
|
||||
|
||||
⌘⇧O Goto File · ⌘⇧F Find in Files (preview scroll + highlight) · ⌘⇧A Find Action · editor edit/undo/autosave ·
|
||||
Terminal (Unicode, venv) · Commit view at the default narrow width · Problems · Run → Stop · Project view
|
||||
New / Delete (nested `a/b.txt` names) · ⌘, Settings search (+ Keymap filter) · Git Log on a repo without commits.
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/eval
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/issue-fix
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/verify
|
||||
+29
-65
@@ -28,9 +28,7 @@ jobs:
|
||||
# shared runners to others. Pushes, the merge queue and manual runs always run everything.
|
||||
changes:
|
||||
name: Changes
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
pull-requests: read
|
||||
@@ -110,10 +108,10 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [macos-latest, ubuntu-latest, windows-latest]
|
||||
os: [macos-latest, ubuntu-22.04, windows-latest]
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
|
||||
runs-on: ${{ matrix.os == 'ubuntu-22.04' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
@@ -146,8 +144,8 @@ jobs:
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf)
|
||||
dpkg -s "${pkgs[@]}" >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y "${pkgs[@]}"; }
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf
|
||||
# tauri-build checks that frontendDist exists.
|
||||
- run: pnpm install --frozen-lockfile && mkdir -p dist
|
||||
shell: bash
|
||||
@@ -158,8 +156,7 @@ jobs:
|
||||
- run: git config --global core.autocrlf false
|
||||
- run: cargo nextest run --workspace --no-fail-fast
|
||||
- name: Remote backend with Docker Compose
|
||||
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
|
||||
if: runner.os == 'Linux' && runner.environment != 'self-hosted'
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
docker pull busybox:latest
|
||||
cargo nextest run -p ide-host --test remote_daemon --run-ignored only \
|
||||
@@ -178,7 +175,7 @@ jobs:
|
||||
name: Rust checks
|
||||
needs: [changes, rust]
|
||||
if: always()
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- env:
|
||||
@@ -195,27 +192,16 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.server == 'true'
|
||||
timeout-minutes: 40
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { targets: x86_64-unknown-linux-musl }
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with: { key: server-musl }
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
- run: dpkg -s musl-tools >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y musl-tools; }
|
||||
- run: sudo apt-get update && sudo apt-get install -y musl-tools
|
||||
- run: cargo build --locked -p ide-host --bin openidea-server --target x86_64-unknown-linux-musl
|
||||
- run: '"${CARGO_TARGET_DIR:-target}/x86_64-unknown-linux-musl/debug/openidea-server" --version'
|
||||
- run: target/x86_64-unknown-linux-musl/debug/openidea-server --version
|
||||
|
||||
# The plugin SDK, the official plugins and the test fixtures build in their
|
||||
# own workspaces (the root excludes them), so the jobs above don't see them.
|
||||
@@ -224,31 +210,18 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.plugins == 'true'
|
||||
timeout-minutes: 30
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-22.04
|
||||
env:
|
||||
CARGO_TARGET_DIR: ${{ github.workspace }}/target-plugins
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { targets: wasm32-wasip2, components: "clippy, rustfmt" }
|
||||
- if: runner.environment != 'self-hosted'
|
||||
shell: bash
|
||||
run: echo "CARGO_TARGET_DIR=$GITHUB_WORKSPACE/target-plugins" >> "$GITHUB_ENV"
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
key: plugins
|
||||
cache-directories: target-plugins
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
echo "CARGO_TARGET_DIR=$CARGO_TARGET_DIR/plugins" >> "$GITHUB_ENV"
|
||||
- name: Format, lint (host and wasm) and test each crate
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -265,7 +238,7 @@ jobs:
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with: { node-version: 22, package-manager-cache: false }
|
||||
with: { node-version: 22 }
|
||||
# Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test.
|
||||
- name: Web pages typecheck and test
|
||||
shell: bash
|
||||
@@ -289,7 +262,7 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.deny == 'true'
|
||||
timeout-minutes: 15
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
@@ -301,19 +274,13 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.frontend == 'true'
|
||||
timeout-minutes: 30
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
if: runner.environment == 'self-hosted'
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm typecheck
|
||||
- run: pnpm lint
|
||||
@@ -328,41 +295,38 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.catalog == 'true'
|
||||
timeout-minutes: 15
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm vitest run src/platform/locales/textCatalog.test.ts
|
||||
|
||||
e2e:
|
||||
name: E2E (${{ matrix.shard }}/4)
|
||||
name: E2E (${{ matrix.shard }}/2)
|
||||
needs: changes
|
||||
if: needs.changes.outputs.e2e == 'true'
|
||||
timeout-minutes: 45
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
timeout-minutes: 30
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4]
|
||||
shard: [1, 2]
|
||||
# Browsers and their system libraries are preinstalled; keep the tag in step with @playwright/test.
|
||||
container: mcr.microsoft.com/playwright:v1.64.1-noble
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm exec playwright install --with-deps chromium
|
||||
- run: pnpm e2e --shard=${{ matrix.shard }}/4
|
||||
- run: pnpm e2e --shard=${{ matrix.shard }}/2
|
||||
env:
|
||||
HOME: /root
|
||||
- uses: actions/upload-artifact@v6
|
||||
if: failure()
|
||||
with:
|
||||
|
||||
@@ -57,9 +57,6 @@ on:
|
||||
paths: *paths
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: language-smoke-${{ github.ref }}
|
||||
# A new push supersedes a PR's run; on main every merge runs to the end (and saves the cache).
|
||||
@@ -68,6 +65,8 @@ concurrency:
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
# Line tables keep test backtraces readable and the binaries the build job hands on small.
|
||||
CARGO_PROFILE_DEV_DEBUG: line-tables-only
|
||||
|
||||
jobs:
|
||||
# The languages a pull request can affect: a change to one language's fixture, definition or
|
||||
@@ -75,9 +74,7 @@ jobs:
|
||||
# run none; anything else runs them all. Pushes and manual runs always run them all.
|
||||
changes:
|
||||
name: Changes
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
pull-requests: read
|
||||
@@ -142,32 +139,17 @@ jobs:
|
||||
name: Build
|
||||
needs: changes
|
||||
if: needs.changes.outputs.languages != '[]'
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
# The tests find the fixtures through the checkout path compiled into them (CARGO_MANIFEST_DIR),
|
||||
# which is the same on every GitHub-hosted runner.
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
# Line tables keep test backtraces readable and the binaries handed on small without
|
||||
# stripping local-variable debuginfo from fixtures debugged in the smoke job (CodeLLDB).
|
||||
CARGO_PROFILE_DEV_DEBUG: line-tables-only
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
shared-key: language-smoke
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
- run: |
|
||||
set -euo pipefail
|
||||
mkdir -p smoke-bin
|
||||
@@ -175,7 +157,7 @@ jobs:
|
||||
| jq -r 'select(.reason == "compiler-artifact" and .executable != null and .target.kind == ["test"]) | "\(.target.name) \(.executable)"' \
|
||||
| while read -r name exe; do cp "$exe" "smoke-bin/$name"; done
|
||||
cargo build --locked -p ide-host --bin openidea-server
|
||||
cp "${CARGO_TARGET_DIR:-target}/debug/openidea-server" smoke-bin/
|
||||
cp target/debug/openidea-server smoke-bin/
|
||||
ls -l smoke-bin
|
||||
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
|
||||
# A tar keeps the executable bits, which artifacts drop.
|
||||
@@ -190,16 +172,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: ${{ fromJSON(needs.changes.outputs.languages) }}
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
# C/C++ debug with GDB, whose DAP interpreter needs 14+: 22.04 ships 12.1, 24.04 ships 15.
|
||||
runs-on: ${{ (matrix.language == 'c' || matrix.language == 'cpp') && 'ubuntu-24.04' || 'ubuntu-22.04' }}
|
||||
timeout-minutes: 40
|
||||
# Self-hosted runner slots have distinct checkout paths (/persist/slot-<N>/work/...); override
|
||||
# the compiled-in CARGO_MANIFEST_DIR so binaries from the Build job find this slot's fixtures.
|
||||
env:
|
||||
CARGO_MANIFEST_DIR: ${{ github.workspace }}/crates/ide-host
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
# Tool versions, shared with the evals (pnpm eval).
|
||||
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
@@ -210,32 +187,18 @@ jobs:
|
||||
tar -xf smoke-bin.tar && rm smoke-bin.tar
|
||||
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
|
||||
|
||||
- uses: pnpm/action-setup@v5
|
||||
- uses: pnpm/action-setup@v4
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- if: matrix.language == 'typescript'
|
||||
run: npm install --global "@vtsls/language-server@$VTSLS" "typescript@$TYPESCRIPT"
|
||||
|
||||
# The smoke checks C/C++ with clangd and debugs c-app with GDB's own DAP interpreter (GDB 14+).
|
||||
# The smoke builds the c-app fixture and debugs it with GDB's own DAP interpreter.
|
||||
- if: matrix.language == 'c' || matrix.language == 'cpp'
|
||||
shell: bash
|
||||
run: |
|
||||
pkgs=()
|
||||
command -v clangd >/dev/null || pkgs+=(clangd)
|
||||
command -v gdb >/dev/null || pkgs+=(gdb)
|
||||
if [ "${#pkgs[@]}" -gt 0 ]; then
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y "${pkgs[@]}"
|
||||
fi
|
||||
major=$(gdb --version | head -n1 | grep -Eo '[0-9]+\.[0-9]+' | head -n1 | cut -d. -f1)
|
||||
if [ "${major:-0}" -lt 14 ]; then
|
||||
echo "::error::GDB 14+ is required for its DAP interpreter; recreate the runner from scripts/selfhost-runner (Ubuntu 24.04)."
|
||||
exit 1
|
||||
fi
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y gdb
|
||||
|
||||
- if: matrix.language == 'python'
|
||||
uses: actions/setup-python@v5
|
||||
@@ -254,7 +217,6 @@ jobs:
|
||||
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
|
||||
- if: matrix.language == 'java'
|
||||
run: |
|
||||
command -v mvn >/dev/null || { sudo apt-get update && sudo apt-get install -y maven; }
|
||||
mkdir -p "$RUNNER_TEMP/jdtls"
|
||||
curl -fsSL "https://download.eclipse.org/jdtls/milestones/${JDTLS%-*}/jdt-language-server-$JDTLS.tar.gz" \
|
||||
| tar xz -C "$RUNNER_TEMP/jdtls"
|
||||
|
||||
+7
-5
@@ -33,12 +33,14 @@ target/
|
||||
test-results/
|
||||
playwright-report/
|
||||
|
||||
# Local AI agent files
|
||||
AGENTS.md
|
||||
CLAUDE.md
|
||||
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
|
||||
CLAUDE.local.md
|
||||
.agents/
|
||||
.claude/
|
||||
.claude/*
|
||||
!.claude/skills/
|
||||
.claude/skills/*
|
||||
!.claude/skills/verify
|
||||
!.claude/skills/issue-fix
|
||||
!.claude/skills/eval
|
||||
|
||||
# Local reference screenshots
|
||||
pycharm-screenshots/
|
||||
@@ -0,0 +1,152 @@
|
||||
# OpenIDEA — contributor guide
|
||||
|
||||
Rust + Tauri 2 desktop IDE with full-featured, multi-language code intelligence.
|
||||
Visual style: dark, low-contrast greys, one cool accent
|
||||
(`src/styles/tokens.css` is the source of truth for colours and metrics).
|
||||
|
||||
## Layout
|
||||
|
||||
- `crates/ide-*` — backend crates; one domain each. Depend on `ide-core` for shared
|
||||
types; never reach into another crate's internals.
|
||||
- `src-tauri/` — glue only: `state.rs` (AppState / Project), `commands/<domain>.rs`
|
||||
(desktop-only commands; the adapters of `ide-host` commands are derived), `events.rs`.
|
||||
No domain logic here.
|
||||
- `src/bindings.ts` — generated by tauri-specta (`pnpm gen:bindings`). Never edit.
|
||||
- `src/platform/` — ipc (`call`, `onIdeEvent`, `nextRequestId`), actions registry,
|
||||
keymap + dispatcher, context keys / `when` clauses, project store.
|
||||
- `src/workbench/contributions.ts` — extension points (tool windows, status items,
|
||||
overlays, editor kinds) and cross-feature services (editor, tool windows, notifications).
|
||||
- `src/ui/` — design-system primitives. `src/features/<name>/` — one feature each,
|
||||
exporting `activate()` registered in `src/features/index.ts`.
|
||||
- `languages/<id>.toml` — language definitions (detection, comments, LSP, DAP).
|
||||
- `crates/ide-host` — the `openidea-server` binary for remote development and the
|
||||
`openidea-plugin` CLI (plugin starter templates live in its `templates.rs`).
|
||||
- `wit/` — plugin interface definitions; `plugins/` — sample and bundled plugins.
|
||||
Plugin docs: `plugins/README.md`, `plugins/themes.md`.
|
||||
- `java/` — JDT LS extension bundles (`java-usages`, `kotlin-bridge`) and the patched
|
||||
Lombok agent, embedded into the app by `ide-sdk` / `ide-tools`.
|
||||
- `e2e/` — Playwright UI tests (`pnpm e2e`). `evals/` — code-intelligence evals (`pnpm eval`).
|
||||
`fixtures/` — sample projects per language for manual and automated testing.
|
||||
- `docs/` — the Mintlify documentation site (`docs.json` navigation, `en/` and `zh/` pages);
|
||||
preview with `npx mint dev` in `docs/`.
|
||||
|
||||
## Rules
|
||||
|
||||
- IPC coordinates: 0-based lines, **UTF-16** columns/offsets everywhere (`ide-core::text`).
|
||||
- Every command returns `IdeResult<T>`; convert internal errors at the crate edge.
|
||||
- Declare a command once, on its implementation: `#[command(trust = …)]` in `ide-host::ops`
|
||||
plus its module's `domain!` list (Tauri adapter, server handler and bindings are derived);
|
||||
desktop-only commands use `#[desktop_command(trust = …)]` and `desktop_domain!`.
|
||||
- Streaming → `tauri::ipc::Channel<T>`; cancellable → UI-allocated `RequestId` +
|
||||
`cancel_request`. Backend → UI notifications → `IdeEvent` via `EventSink`.
|
||||
- Long work never blocks the UI thread or a Tauri command thread: use
|
||||
`spawn_blocking`/rayon, honour `CancellationToken`.
|
||||
- Frontend features never import each other; communicate via actions, contributions
|
||||
and services. All user-invocable behaviour is an action with a stable id; default
|
||||
shortcuts live in `src/platform/keymaps/`.
|
||||
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG
|
||||
icons from `src/ui/icons.tsx`, never emoji. Real `<button>`/`<input>`; `aria-label` on icon buttons.
|
||||
`gap` uses the `--space-*` scale (`src/styles/tokens.css`, 4px grid) where a value is on it.
|
||||
- User-visible text goes through the text catalog: add every new string to both
|
||||
`src/platform/locales/text/en.json` and `zh.json` (`textCatalog.test.ts` enforces it).
|
||||
Other locales may lack entries; their UI shows the English text until a translator adds it.
|
||||
- Keep comments sparse and purposeful; match surrounding style.
|
||||
- For GUI verification, prefer Tauri MCP; use Computer Use only when Tauri MCP is
|
||||
unavailable or cannot cover the required checks.
|
||||
|
||||
## Issues & PRs
|
||||
|
||||
Follow `CONTRIBUTING.md` and `.github/pull_request_template.md`: one problem per PR
|
||||
(`Closes #<n>` when it resolves an issue), reproduce first, keep the diff focused, short plain description, and a
|
||||
**How it was verified** section with commands run, results and, when the change alters what users
|
||||
see, before/after screenshots (not for UI removed along with a feature, copy-only or non-visual changes).
|
||||
Unclear product decisions → `needs-decision` and stop.
|
||||
|
||||
## Skills
|
||||
|
||||
Do not use Impeccable or its related skills in this repository, including globally installed copies.
|
||||
|
||||
Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
|
||||
`verify` drives the running app through Tauri MCP and captures screenshot evidence;
|
||||
`issue-fix` takes an issue from reproduction to one PR;
|
||||
`eval` takes a failing code-intelligence eval to a fix with before / after numbers.
|
||||
|
||||
## Commands
|
||||
|
||||
- Optional: `mise install` provisions the contributor toolchain; `mise tasks` lists the task aliases.
|
||||
See [Development setup](docs/en/contribute/setup.mdx). The direct commands below still work without mise.
|
||||
- `pnpm tauri dev` — run the app with worktree isolation. Use Node 22.22.2 or later on the 22.x line.
|
||||
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
|
||||
this worktree's running MCP bridges and actual ports.
|
||||
- `pnpm build` — typecheck + bundle frontend.
|
||||
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
|
||||
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
|
||||
- `pnpm dogfood:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
|
||||
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
|
||||
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
|
||||
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
|
||||
- `pnpm smoke smoke/run.test.ts -t <language>` — run and test that language's fixture through the
|
||||
run store and a real `openidea-server` (build it first: `cargo build -p ide-host --bin openidea-server`).
|
||||
- `pnpm smoke smoke/debug.test.ts -t <language>` — debug that fixture's entry point the same way, with
|
||||
the debugger the IDE installs (on macOS, CodeLLDB and Delve may need Developer Mode:
|
||||
`sudo DevToolsSecurity -enable`).
|
||||
- `pnpm test`, `pnpm e2e`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm typecheck`,
|
||||
`pnpm gen:bindings`.
|
||||
- `pnpm perf` (UI interaction latency / frames / leaks), `pnpm perf:rust` (criterion
|
||||
benches vs budgets). Budgets: `perf/budgets.json`.
|
||||
- `pnpm eval [--only <id>] [--runs n] [--save-baseline]` — Java code intelligence (navigation,
|
||||
usages, gutter markers) in the production workbench against a release `openidea-server` and
|
||||
jdtls: time to feedback / first result / complete, results vs `evals/<language>/golden/`.
|
||||
Report: `target/eval/report.json`. Goldens and `evals/budgets.json` are changed by people only.
|
||||
Tool versions: `.github/tool-versions.env` (shared with Language smoke).
|
||||
- `pnpm release:prepare <version>` — the release commit's changes: app version everywhere,
|
||||
`Cargo.lock`, and the plugin API snapshot when `wit/` moved to a new version.
|
||||
|
||||
## Before opening a PR
|
||||
|
||||
Run what CI runs for the parts you touched:
|
||||
|
||||
- Rust: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,
|
||||
`cargo nextest run --workspace`. After changing IPC types, run `pnpm gen:bindings` and
|
||||
commit `src/bindings.ts`; CI fails if it differs.
|
||||
- Frontend: `pnpm typecheck`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm test`,
|
||||
`pnpm build`, and `pnpm e2e` for UI flows.
|
||||
- UI or runtime behaviour: verify in the running app (`.agents/skills/verify`).
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- Run a subset of frontend tests with `pnpm vitest run <path>`. `pnpm test -- <path>` ignores
|
||||
the filter and runs the whole suite, which takes several minutes.
|
||||
- Don't run clippy while iterating: `pnpm tauri dev` compiles anyway. Run
|
||||
`cargo fmt --all` + `cargo clippy -p <crate> --all-targets -- -D warnings` once, right
|
||||
before committing. A cold build cache can take around 5 minutes. Run long checks one at
|
||||
a time, not chained in one shell call that may hit the 10-minute tool timeout.
|
||||
- `pnpm tauri dev` does a full debug build. Clippy only checks the code, so a passing clippy
|
||||
doesn't make the first launch fast.
|
||||
|
||||
## Parallel worktrees
|
||||
|
||||
Several worktrees can be developed and run side by side.
|
||||
|
||||
- Create one per task: `git worktree add ../<name> -b <branch> origin/main`, then
|
||||
`pnpm install` in it.
|
||||
- Launch with `pnpm tauri dev` / `pnpm dev:app`, not the raw `pnpm exec tauri dev` CLI. The
|
||||
wrapper starts Vite on a worktree-derived port (advancing if occupied), passes its actual
|
||||
URL to Tauri, and reports an existing launcher instead of starting another for the same
|
||||
worktree. HMR uses the Vite port.
|
||||
- Debug app identity, data, settings, logs and single-instance scope follow the canonical
|
||||
worktree path captured at build time, independent of launch cwd. Launching the same debug
|
||||
binary again focuses its existing instance and forwards its path argument. Different
|
||||
worktrees and the installed release can coexist. `--release` uses normal release identity
|
||||
and bypasses the development wrapper.
|
||||
- MCP bridge ports are dynamic (9223–9322). Use `pnpm dev:status`, connect to the reported
|
||||
port, verify identifier/cwd, and pass `appIdentifier: <port>` explicitly. Do not assume the
|
||||
default MCP session belongs to this worktree.
|
||||
- Keep each worktree's Cargo output directory separate; do not point `CARGO_TARGET_DIR` or
|
||||
`target` symlinks at a shared directory.
|
||||
- Each worktree's first build is cold (several minutes) and `cargo build` output takes
|
||||
around 9 GB; tests, clippy and incremental builds add more. Avoid running several heavy builds on one machine at the same time.
|
||||
- Stop only processes started for the current worktree/session. Never use broad
|
||||
process-name kills such as `pkill openidea`.
|
||||
- When done: stop that worktree's app and dev session, delete its build output, then
|
||||
`git worktree remove ../<name>`.
|
||||
@@ -1,6 +1,7 @@
|
||||
# Contributing to OpenIDEA
|
||||
|
||||
These rules apply to everyone, and to any coding agent working on their behalf.
|
||||
Project layout, coding rules, commands and checks are in [AGENTS.md](AGENTS.md).
|
||||
|
||||
## Issues
|
||||
|
||||
|
||||
Generated
+48
-48
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4172,7 +4172,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4184,7 +4184,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4194,7 +4194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4212,7 +4212,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4226,7 +4226,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4237,7 +4237,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4248,7 +4248,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dunce",
|
||||
@@ -4266,7 +4266,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4279,7 +4279,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4308,7 +4308,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4345,7 +4345,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4358,7 +4358,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4372,7 +4372,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4392,7 +4392,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4403,7 +4403,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4415,7 +4415,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4428,7 +4428,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4447,7 +4447,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4522,7 +4522,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
@@ -4541,7 +4541,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4564,7 +4564,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4576,7 +4576,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4592,7 +4592,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4601,7 +4601,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4612,7 +4612,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4671,7 +4671,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4700,7 +4700,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4719,7 +4719,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4740,7 +4740,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4762,7 +4762,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4776,7 +4776,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4796,7 +4796,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4820,7 +4820,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4836,7 +4836,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4862,7 +4862,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4883,7 +4883,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4896,7 +4896,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4921,7 +4921,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4934,7 +4934,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4949,7 +4949,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4963,7 +4963,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4976,7 +4976,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4997,7 +4997,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5019,7 +5019,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5046,7 +5046,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5062,7 +5062,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6691,7 +6691,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.51"
|
||||
version = "0.1.50"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
+80
-329
@@ -44,9 +44,7 @@ use ide_vcs::Repo;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
|
||||
use std::hash::Hasher;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
@@ -70,8 +68,6 @@ pub type GitExecutableHook = Arc<dyn Fn() -> Option<PathBuf> + Send + Sync>;
|
||||
|
||||
/// Entry changes are batched for this long before they are sent.
|
||||
const FLUSH_DELAY: Duration = Duration::from_millis(40);
|
||||
/// A save asked for with `persist_soon` waits this long for others to join it.
|
||||
const SAVE_DELAY: Duration = Duration::from_millis(250);
|
||||
/// Updates that arrive this late after `session/load` returns are still replayed history.
|
||||
const REPLAY_GRACE: Duration = Duration::from_millis(300);
|
||||
/// Notifications are delivered on their own thread: the last `session/update`s of a turn
|
||||
@@ -549,11 +545,8 @@ struct Task {
|
||||
/// Unanswered permission requests: where to send the chosen option id.
|
||||
permissions: Mutex<HashMap<u32, std::sync::mpsc::Sender<Option<String>>>>,
|
||||
next_permission: AtomicU32,
|
||||
/// Set while `session/load` replays the session's history.
|
||||
/// Set while `session/load` replays history we already have.
|
||||
replaying: AtomicBool,
|
||||
/// The task has a session but none of its history (an imported session): the next load's
|
||||
/// replay becomes the task's history instead of being dropped.
|
||||
adopting_replay: AtomicBool,
|
||||
/// The saved session failed to load and the user was told: the next start opens a new one.
|
||||
start_fresh: AtomicBool,
|
||||
/// The current turn is being cancelled to send the first queued message right away.
|
||||
@@ -575,24 +568,12 @@ struct Task {
|
||||
/// Settings already sent this session (`(option, value)`), so a refusal is not retried.
|
||||
config_sent: Mutex<HashSet<(String, String)>>,
|
||||
dirty: Mutex<BTreeSet<(Session, usize)>>,
|
||||
/// What was last sent of the entries that stream, so the next flush sends the rest.
|
||||
streamed: Mutex<Streamed>,
|
||||
/// How much of each session's streaming message was last sent, so the next flush sends the rest.
|
||||
streamed: Mutex<HashMap<Session, Sent>>,
|
||||
flush_scheduled: AtomicBool,
|
||||
stderr: Mutex<VecDeque<String>>,
|
||||
/// Saves asked for (see `persist`); the file holds those up to `file.saved`.
|
||||
saves_asked: AtomicU64,
|
||||
save_scheduled: AtomicBool,
|
||||
/// Held while the file is written, so saves land in order and none follows a delete.
|
||||
file: Mutex<SavedFile>,
|
||||
}
|
||||
|
||||
/// What the task's file on disk holds.
|
||||
#[derive(Default)]
|
||||
struct SavedFile {
|
||||
/// Set by `delete`: nothing is written any more.
|
||||
deleted: bool,
|
||||
/// The saves asked for that the file holds.
|
||||
saved: u64,
|
||||
/// Set by `delete`; held while saving.
|
||||
deleted: Mutex<bool>,
|
||||
}
|
||||
|
||||
impl AgentManager {
|
||||
@@ -932,7 +913,7 @@ impl AgentManager {
|
||||
out
|
||||
}
|
||||
|
||||
/// Imports an external session as a task, loading it in the background to show its history (#312).
|
||||
/// Imports an external session as a task: its first turn loads and replays it (#312).
|
||||
pub fn import_session(&self, provider: &str, session_id: &str) -> IdeResult<AgentTask> {
|
||||
if !matches!(provider, "claude" | "codex") {
|
||||
return Err(IdeError::invalid(format!("cannot import {provider} sessions")));
|
||||
@@ -997,13 +978,6 @@ impl AgentManager {
|
||||
self.tasks.write().insert(task.id.clone(), handle.clone());
|
||||
handle.emit_task();
|
||||
handle.persist();
|
||||
// Loading the session replays its history into the task, so it shows before a first message.
|
||||
self.shared.runtime.spawn(async move {
|
||||
match handle.ensure_session().await {
|
||||
Ok(_) => handle.release_when_idle(),
|
||||
Err(e) => tracing::info!("agent task {}: loading the imported session failed: {e}", handle.id),
|
||||
}
|
||||
});
|
||||
Ok(task)
|
||||
}
|
||||
|
||||
@@ -1832,7 +1806,7 @@ impl AgentManager {
|
||||
// A copy of the task (a fork) may work in the same worktree.
|
||||
let shared = self.tasks.read().values().any(|t| t.id != id && t.state.lock().task.cwd.0 == cwd);
|
||||
self.tasks.write().remove(id);
|
||||
task.file.lock().deleted = true;
|
||||
*task.deleted.lock() = true;
|
||||
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
|
||||
let _ = std::fs::remove_dir_all(task.turn_dir());
|
||||
skills::remove_farm(&self.shared.paths.store_dir, id);
|
||||
@@ -2222,7 +2196,6 @@ impl Task {
|
||||
fn restore(file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
|
||||
let mut task = file.task;
|
||||
config::add_client_options(&task.provider, &mut task.config);
|
||||
let adopt = file.entries.is_empty() && file.session_id.is_some();
|
||||
let conversation = Conversation::restore(file.entries, file.subagents);
|
||||
let mut wanted = file.wanted;
|
||||
let pending_model = file.pending_switch.or_else(|| {
|
||||
@@ -2269,7 +2242,6 @@ impl Task {
|
||||
permissions: Mutex::new(HashMap::new()),
|
||||
next_permission: AtomicU32::new(1),
|
||||
replaying: AtomicBool::new(false),
|
||||
adopting_replay: AtomicBool::new(adopt),
|
||||
start_fresh: AtomicBool::new(false),
|
||||
send_now: AtomicBool::new(false),
|
||||
cancel_pending: AtomicBool::new(false),
|
||||
@@ -2280,12 +2252,10 @@ impl Task {
|
||||
skills_reload_pending: AtomicBool::new(false),
|
||||
config_sent: Mutex::new(HashSet::new()),
|
||||
dirty: Mutex::new(BTreeSet::new()),
|
||||
streamed: Mutex::new(Streamed::default()),
|
||||
streamed: Mutex::new(HashMap::new()),
|
||||
flush_scheduled: AtomicBool::new(false),
|
||||
stderr: Mutex::new(VecDeque::new()),
|
||||
saves_asked: AtomicU64::new(0),
|
||||
save_scheduled: AtomicBool::new(false),
|
||||
file: Mutex::new(SavedFile::default()),
|
||||
deleted: Mutex::new(false),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2307,7 +2277,7 @@ impl Task {
|
||||
}
|
||||
|
||||
/// Records the checkout as a turn starts: what the turn's changes are compared with.
|
||||
async fn checkout_before_turn(self: &Arc<Self>) {
|
||||
async fn checkout_before_turn(&self) {
|
||||
let (cwd, previous, dir) = self.last_turn();
|
||||
let turn = match vcs(&self.shared, move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await {
|
||||
Ok(turn) => Some(Arc::new(turn)),
|
||||
@@ -2317,12 +2287,12 @@ impl Task {
|
||||
}
|
||||
};
|
||||
self.state.lock().turn = turn;
|
||||
self.persist_soon();
|
||||
self.persist();
|
||||
}
|
||||
|
||||
/// Records the files that changed in the checkout while the turn ran: the turn's, and in
|
||||
/// the project's own checkout also the task's.
|
||||
async fn record_turn_changes(self: &Arc<Self>) {
|
||||
async fn record_turn_changes(&self) {
|
||||
let (cwd, turn, _) = self.last_turn();
|
||||
let Some(turn) = turn else { return };
|
||||
let start = turn.clone();
|
||||
@@ -2340,7 +2310,7 @@ impl Task {
|
||||
}
|
||||
s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() }));
|
||||
}
|
||||
self.persist_soon();
|
||||
self.persist();
|
||||
}
|
||||
|
||||
fn base(&self) -> worktree::TaskBase {
|
||||
@@ -2421,29 +2391,19 @@ impl Task {
|
||||
}
|
||||
}
|
||||
|
||||
fn change_status(&self, status: AgentStatus, error: Option<String>) {
|
||||
let mut s = self.state.lock();
|
||||
s.task.retry = None;
|
||||
s.task.status = status;
|
||||
s.task.error = error;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
|
||||
fn set_status(&self, status: AgentStatus, error: Option<String>) {
|
||||
self.change_status(status, error);
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
s.task.retry = None;
|
||||
s.task.status = status;
|
||||
s.task.error = error;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
// Saved first: whoever reacts to the status change finds it on disk.
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
}
|
||||
|
||||
/// `Running` again after the agent started or a request was answered: the turn's next stop
|
||||
/// saves what changed, and the turn start saved the message that began it.
|
||||
fn resume_running(self: &Arc<Self>) {
|
||||
self.change_status(AgentStatus::Running, None);
|
||||
self.persist_soon();
|
||||
self.emit_task();
|
||||
}
|
||||
|
||||
fn emit_attention(&self, reason: AgentAttentionReason) {
|
||||
let n = self.shared.attention_seq.fetch_add(1, Ordering::Relaxed);
|
||||
let tag = match reason {
|
||||
@@ -2466,40 +2426,15 @@ impl Task {
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the task file, with everything changed so far, before it returns.
|
||||
fn persist(&self) {
|
||||
self.saves_asked.fetch_add(1, Ordering::AcqRel);
|
||||
self.save();
|
||||
}
|
||||
|
||||
/// Has the task file written within `SAVE_DELAY`, once for every change asked for by then:
|
||||
/// for what the next `persist` (the turn's next stop, shutdown) saves anyway, and a crash
|
||||
/// before it costs at most what changed in this window.
|
||||
fn persist_soon(self: &Arc<Self>) {
|
||||
self.saves_asked.fetch_add(1, Ordering::AcqRel);
|
||||
if !self.save_scheduled.swap(true, Ordering::AcqRel) {
|
||||
let task = self.clone();
|
||||
self.shared.runtime.spawn(async move {
|
||||
tokio::time::sleep(SAVE_DELAY).await;
|
||||
task.save_scheduled.store(false, Ordering::Release);
|
||||
let _ = tokio::task::spawn_blocking(move || task.save()).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the file unless it holds every save asked for. The state is locked only to copy
|
||||
/// it: turning a long transcript into JSON and writing it is no reader's wait.
|
||||
fn save(&self) {
|
||||
// Held from the copy to the rename, so saves land in order and none follows a delete.
|
||||
let mut file = self.file.lock();
|
||||
// Read before the copy: whatever was asked for up to now is in it.
|
||||
let asked = self.saves_asked.load(Ordering::Acquire);
|
||||
if file.deleted || file.saved >= asked {
|
||||
// Held from snapshot to rename, so saves land in order and none follows a delete.
|
||||
let deleted = self.deleted.lock();
|
||||
if *deleted {
|
||||
return;
|
||||
}
|
||||
let copy = {
|
||||
let bytes = {
|
||||
let s = self.state.lock();
|
||||
TaskFile {
|
||||
serde_json::to_vec(&TaskFile {
|
||||
task: s.task.clone(),
|
||||
session_id: s.session_id.clone(),
|
||||
entries: s.conversation.main.entries.clone(),
|
||||
@@ -2513,14 +2448,11 @@ impl Task {
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
pending_rollback: s.pending_rollback,
|
||||
title_renamed: s.title_renamed,
|
||||
}
|
||||
})
|
||||
};
|
||||
let bytes = serde_json::to_vec(©);
|
||||
drop(copy);
|
||||
let path = self.shared.paths.store_dir.join(format!("{}.json", self.id));
|
||||
match bytes.map_err(|e| e.to_string()).and_then(|b| write_file(&path, &b)) {
|
||||
Ok(()) => file.saved = asked,
|
||||
Err(e) => tracing::warn!("saving agent task {}: {e}", self.id),
|
||||
if let Err(e) = bytes.map_err(|e| e.to_string()).and_then(|b| write_file(&path, &b)) {
|
||||
tracing::warn!("saving agent task {}: {e}", self.id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2545,7 +2477,7 @@ impl Task {
|
||||
.into_iter()
|
||||
.filter_map(|(subagent, i)| {
|
||||
let entry = s.conversation.timeline(&subagent)?.entries.get(i)?;
|
||||
entry_event(&self.id, &mut streamed, subagent, i, entry)
|
||||
Some(entry_event(&self.id, &mut streamed, subagent, i, entry))
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
@@ -2581,19 +2513,6 @@ impl Task {
|
||||
self.persist();
|
||||
}
|
||||
|
||||
/// Removes the task's own entries and returns them.
|
||||
fn take_entries(self: &Arc<Self>) -> Vec<AgentEntry> {
|
||||
let entries = {
|
||||
let mut s = self.state.lock();
|
||||
let entries = s.conversation.main.entries.clone();
|
||||
s.conversation.truncate(0);
|
||||
entries
|
||||
};
|
||||
self.streamed.lock().clear();
|
||||
self.shared.emit(AgentEvent::Truncated { task: self.id.clone(), length: 0 });
|
||||
entries
|
||||
}
|
||||
|
||||
fn push_entry(self: &Arc<Self>, entry: AgentEntry) -> usize {
|
||||
let i = self.state.lock().conversation.main.push(entry);
|
||||
self.mark_dirty([(None, i)]);
|
||||
@@ -2950,7 +2869,7 @@ impl Task {
|
||||
if self.cancel_pending.load(Ordering::Acquire) {
|
||||
return Ok("cancelled".into());
|
||||
}
|
||||
self.resume_running();
|
||||
self.set_status(AgentStatus::Running, None);
|
||||
if !prompt.images.is_empty() && !live.capabilities.images {
|
||||
return Err(Failure::from("This agent can't read images.".to_owned()));
|
||||
}
|
||||
@@ -3186,27 +3105,12 @@ impl Task {
|
||||
});
|
||||
}
|
||||
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
|
||||
// The replay goes before what this turn already showed (the user's message).
|
||||
let shown = self.adopts_replay().then(|| self.take_entries());
|
||||
self.replaying.store(true, Ordering::Release);
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
|
||||
params["sessionId"] = json!(&id);
|
||||
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
|
||||
tokio::time::sleep(REPLAY_GRACE).await;
|
||||
self.replaying.store(false, Ordering::Release);
|
||||
if let Some(shown) = shown {
|
||||
if loaded.is_ok() {
|
||||
self.adopting_replay.store(false, Ordering::Release);
|
||||
let changed = self.state.lock().conversation.end_turn(None);
|
||||
self.mark_dirty(changed);
|
||||
} else {
|
||||
// A failed load may still have replayed part of it.
|
||||
self.take_entries();
|
||||
}
|
||||
for entry in shown {
|
||||
self.push_entry(entry);
|
||||
}
|
||||
}
|
||||
match loaded {
|
||||
Ok(v) => session = Some((id, v)),
|
||||
// Not silently: a new session would lose the conversation and replace the saved id.
|
||||
@@ -3428,7 +3332,7 @@ impl Task {
|
||||
s.task.background.clear();
|
||||
*client.opening_config.lock() = None;
|
||||
}
|
||||
self.persist_soon();
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
stop_on_err.0 = None;
|
||||
Ok(Live {
|
||||
@@ -3498,7 +3402,7 @@ impl Task {
|
||||
}
|
||||
}
|
||||
task.approve_pending();
|
||||
task.persist_soon();
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
});
|
||||
}
|
||||
@@ -3524,7 +3428,7 @@ impl Task {
|
||||
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
|
||||
// A subagent's title, settings and usage are its own, not the task's.
|
||||
if self.state.lock().conversation.owner(session).is_some() {
|
||||
if !SESSION_STATE.contains(&kind) && (!self.replaying.load(Ordering::Acquire) || self.adopts_replay()) {
|
||||
if !SESSION_STATE.contains(&kind) && !self.replaying.load(Ordering::Acquire) {
|
||||
self.apply(session, kind, update);
|
||||
}
|
||||
return;
|
||||
@@ -3560,7 +3464,7 @@ impl Task {
|
||||
std::mem::replace(&mut s.task.stats.compressions, depth) != depth
|
||||
};
|
||||
if changed {
|
||||
self.persist_soon();
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
}
|
||||
}
|
||||
@@ -3578,11 +3482,11 @@ impl Task {
|
||||
if (user_named || !s.title_renamed) && s.task.title != title {
|
||||
s.task.title = title.to_owned();
|
||||
drop(s);
|
||||
self.persist_soon();
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
} else if flag_changed {
|
||||
drop(s);
|
||||
self.persist_soon();
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
}
|
||||
}
|
||||
@@ -3628,7 +3532,7 @@ impl Task {
|
||||
};
|
||||
self.shared.remember(&provider, Some(&config), Some(&commands), model.as_deref());
|
||||
if kind != "usage_update" {
|
||||
self.persist_soon();
|
||||
self.persist();
|
||||
}
|
||||
self.emit_task();
|
||||
if kind == "config_option_update" && !self.replaying.load(Ordering::Acquire) {
|
||||
@@ -3640,13 +3544,6 @@ impl Task {
|
||||
return;
|
||||
}
|
||||
if self.replaying.load(Ordering::Acquire) {
|
||||
if self.adopts_replay() {
|
||||
if kind == "user_message_chunk" {
|
||||
self.adopt_user_chunk(update);
|
||||
} else {
|
||||
self.apply(session, kind, update);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
// The first sign that the agent took the prompt: a stop sent before it is repeated.
|
||||
@@ -3659,52 +3556,14 @@ impl Task {
|
||||
self.apply(session, kind, update);
|
||||
}
|
||||
|
||||
fn adopts_replay(&self) -> bool {
|
||||
self.adopting_replay.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// A user message of the adopted history: live turns show the user's own, so only a replay's count.
|
||||
fn adopt_user_chunk(self: &Arc<Self>, update: &Value) {
|
||||
let content = update.get("content");
|
||||
let image = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image")).map(|c| AgentImage {
|
||||
mime_type: c.get("mimeType").and_then(Value::as_str).unwrap_or_default().to_owned(),
|
||||
data: c.get("data").and_then(Value::as_str).unwrap_or_default().to_owned(),
|
||||
name: None,
|
||||
});
|
||||
let text = timeline::content_text(content).unwrap_or_default();
|
||||
if text.is_empty() && image.is_none() {
|
||||
return;
|
||||
}
|
||||
let changed = {
|
||||
let mut s = self.state.lock();
|
||||
let entries = &mut s.conversation.main.entries;
|
||||
// The chunks of one message arrive in a row.
|
||||
if let Some(AgentEntry::User { text: shown, images, .. }) = entries.last_mut() {
|
||||
shown.push_str(&text);
|
||||
images.extend(image);
|
||||
entries.len() - 1
|
||||
} else {
|
||||
s.conversation.main.push(AgentEntry::User {
|
||||
text,
|
||||
attachments: Vec::new(),
|
||||
images: image.into_iter().collect(),
|
||||
sent_ms: None,
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
})
|
||||
}
|
||||
};
|
||||
self.mark_dirty([(None, changed)]);
|
||||
}
|
||||
|
||||
fn apply(self: &Arc<Self>, session: Option<&str>, kind: &str, update: &Value) {
|
||||
// Output again: the retried request went through.
|
||||
self.set_retry(None);
|
||||
let applied = self.state.lock().conversation.apply(session, update, now_ms());
|
||||
self.mark_dirty(applied);
|
||||
// A subagent can start or finish after the turn that started it: nothing else saves it then.
|
||||
// A subagent can start or finish after the turn that started it: saved right away.
|
||||
if matches!(kind, "subagent_update" | "user_question") {
|
||||
self.persist_soon();
|
||||
self.persist();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3887,7 +3746,6 @@ impl Task {
|
||||
}
|
||||
|
||||
/// Records the answer to the request at `entry`; the turn runs on once nothing else waits.
|
||||
/// Saved before it returns, which is before the agent is told: a restart after that keeps the answer.
|
||||
fn settle(self: &Arc<Self>, entry: usize, chosen: String) {
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
@@ -3897,13 +3755,8 @@ impl Task {
|
||||
}
|
||||
self.mark_dirty([(None, entry)]);
|
||||
let still_asking = !self.permissions.lock().is_empty();
|
||||
let resumed = !still_asking && self.state.lock().task.status == AgentStatus::NeedsInput;
|
||||
if resumed {
|
||||
self.change_status(AgentStatus::Running, None);
|
||||
}
|
||||
self.persist();
|
||||
if resumed {
|
||||
self.emit_task();
|
||||
if !still_asking && self.state.lock().task.status == AgentStatus::NeedsInput {
|
||||
self.set_status(AgentStatus::Running, None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3987,7 +3840,7 @@ impl Handler for Client {
|
||||
&& let Some(message) = params.get("message").and_then(Value::as_str).filter(|s| !s.trim().is_empty())
|
||||
{
|
||||
task.push_entry(AgentEntry::Error { message: message.to_owned() });
|
||||
task.persist_soon();
|
||||
task.persist();
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -4392,24 +4245,11 @@ fn file_uri(path: &Path) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// The title of a task: the first line of the prompt that says something. Text inside a code
|
||||
/// fence (```` ```text ````) is pasted material, so a line outside the fences wins; a prompt
|
||||
/// that is all one pasted block still names its task from inside it.
|
||||
/// The title of a task: the first line of the prompt that says something. A pasted Markdown
|
||||
/// block opens with a code fence (```` ```text ````), which names no task.
|
||||
fn title_of(prompt: &AgentPrompt) -> String {
|
||||
let is_fence = |l: &str| l.starts_with("```") || l.starts_with("~~~");
|
||||
let (mut outside, mut inside, mut fenced) = (None, None, false);
|
||||
for l in prompt.text.lines().map(str::trim) {
|
||||
if is_fence(l) {
|
||||
fenced = !fenced;
|
||||
} else if !l.is_empty() {
|
||||
let slot = if fenced { &mut inside } else { &mut outside };
|
||||
slot.get_or_insert(l);
|
||||
if outside.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let line = outside.or(inside);
|
||||
let line = prompt.text.lines().map(str::trim).find(|l| !l.is_empty() && !is_fence(l));
|
||||
let line = match line {
|
||||
Some(l) => l.to_owned(),
|
||||
None => prompt.files.first().map(|f| file_name(&f.0)).unwrap_or_else(|| "Image".into()),
|
||||
@@ -4429,21 +4269,12 @@ fn home_dir() -> Option<PathBuf> {
|
||||
std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from)
|
||||
}
|
||||
|
||||
/// How many times each file was written, in test builds: lets a test count a task's saves.
|
||||
#[cfg(test)]
|
||||
static FILE_WRITES: std::sync::LazyLock<Mutex<HashMap<PathBuf, u32>>> = std::sync::LazyLock::new(Mutex::default);
|
||||
|
||||
fn write_file(path: &Path, bytes: &[u8]) -> Result<(), String> {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path)).map_err(|e| e.to_string())?;
|
||||
#[cfg(test)]
|
||||
{
|
||||
*FILE_WRITES.lock().entry(path.to_owned()).or_default() += 1;
|
||||
}
|
||||
Ok(())
|
||||
std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path)).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
@@ -4489,160 +4320,80 @@ fn stdio_mcp_servers(executable: Option<&std::path::Path>, supported: bool, root
|
||||
vec![json!({ "name": BUILTIN_SERVER, "command": command[0], "args": command[1..], "env": env })]
|
||||
}
|
||||
|
||||
/// What was sent of a streaming text: its first `bytes` (`utf16` UTF-16 units), hashed. The
|
||||
/// text only grows while it streams; the hash tells one that went on from one that was replaced
|
||||
/// (at its end or anywhere before) without keeping a copy of it.
|
||||
/// What was sent of a streaming message: its first `bytes` (`utf16` UTF-16 units), which
|
||||
/// ended with `tail`. A message only grows while it streams, so its tail tells a message
|
||||
/// that went on from one that was replaced without comparing (or keeping) all of it.
|
||||
struct Sent {
|
||||
index: usize,
|
||||
bytes: usize,
|
||||
utf16: usize,
|
||||
hash: u64,
|
||||
tail: String,
|
||||
}
|
||||
|
||||
const SENT_TAIL: usize = 64;
|
||||
|
||||
impl Sent {
|
||||
fn new(index: usize, text: &str) -> Self {
|
||||
Self { index, bytes: text.len(), utf16: text.encode_utf16().count(), hash: Self::digest(text) }
|
||||
Self::after(index, text, 0, 0)
|
||||
}
|
||||
|
||||
fn digest(text: &str) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
hasher.write(text.as_bytes());
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// `text` at `index` as sent after this, when it is this text with more at the end.
|
||||
fn extended(&self, index: usize, text: &str) -> Option<Self> {
|
||||
if self.index != index || text.len() <= self.bytes || !text.is_char_boundary(self.bytes) {
|
||||
return None;
|
||||
/// `text` as sent, of which the first `bytes` (`utf16` units) were sent before.
|
||||
fn after(index: usize, text: &str, bytes: usize, utf16: usize) -> Self {
|
||||
let mut start = text.len().saturating_sub(SENT_TAIL);
|
||||
while !text.is_char_boundary(start) {
|
||||
start -= 1;
|
||||
}
|
||||
let mut hasher = DefaultHasher::new();
|
||||
hasher.write(&text.as_bytes()[..self.bytes]);
|
||||
if hasher.finish() != self.hash {
|
||||
return None;
|
||||
}
|
||||
let more = &text[self.bytes..];
|
||||
hasher.write(more.as_bytes());
|
||||
Some(Self { index, bytes: text.len(), utf16: self.utf16 + more.encode_utf16().count(), hash: hasher.finish() })
|
||||
let utf16 = utf16 + text[bytes..].encode_utf16().count();
|
||||
Self { index, bytes: text.len(), utf16, tail: text[start..].to_owned() }
|
||||
}
|
||||
|
||||
/// Whether `text` is exactly what was sent.
|
||||
fn is(&self, text: &str) -> bool {
|
||||
text.len() == self.bytes && Self::digest(text) == self.hash
|
||||
}
|
||||
}
|
||||
|
||||
/// A running tool call as last sent: the entry without its output, and what was sent of that.
|
||||
struct SentTool {
|
||||
call: AgentEntry,
|
||||
output: Sent,
|
||||
}
|
||||
|
||||
/// What each window was last sent of the entries that stream, so the next flush sends the rest.
|
||||
#[derive(Default)]
|
||||
struct Streamed {
|
||||
/// The message each session streams now.
|
||||
messages: HashMap<Session, Sent>,
|
||||
/// The tool calls still running, by session and entry index.
|
||||
tools: HashMap<(Session, usize), SentTool>,
|
||||
}
|
||||
|
||||
impl Streamed {
|
||||
fn clear(&mut self) {
|
||||
self.messages.clear();
|
||||
self.tools.clear();
|
||||
/// Whether `text` at `index` is this message, gone on.
|
||||
fn extended_by(&self, index: usize, text: &str) -> bool {
|
||||
self.index == index
|
||||
&& text.len() > self.bytes
|
||||
&& text.is_char_boundary(self.bytes)
|
||||
&& text[..self.bytes].ends_with(&self.tail)
|
||||
}
|
||||
}
|
||||
|
||||
/// The event that brings the UI's copy of entry `i` up to date: only the new text when
|
||||
/// it extends the message (or the tool output) last sent, else the whole entry; `None`
|
||||
/// when the UI's copy of a tool already is the entry.
|
||||
/// it extends the message last sent for the session, else the whole entry.
|
||||
fn entry_event(
|
||||
task: &str,
|
||||
streamed: &mut Streamed,
|
||||
streamed: &mut HashMap<Session, Sent>,
|
||||
subagent: Session,
|
||||
i: usize,
|
||||
entry: &AgentEntry,
|
||||
) -> Option<AgentEvent> {
|
||||
let whole = |subagent| AgentEvent::Entry { task: task.to_owned(), subagent, index: i as u32, entry: entry.clone() };
|
||||
) -> AgentEvent {
|
||||
let text = match entry {
|
||||
AgentEntry::Agent { text } | AgentEntry::Thought { text, .. } => Some(text),
|
||||
AgentEntry::Tool { .. } => return tool_event(task, streamed, subagent, i, entry),
|
||||
_ => None,
|
||||
};
|
||||
let Some(text) = text else {
|
||||
if streamed.messages.get(&subagent).is_some_and(|sent| sent.index == i) {
|
||||
streamed.messages.remove(&subagent);
|
||||
if streamed.get(&subagent).is_some_and(|sent| sent.index == i) {
|
||||
streamed.remove(&subagent);
|
||||
}
|
||||
return Some(whole(subagent));
|
||||
return AgentEvent::Entry { task: task.to_owned(), subagent, index: i as u32, entry: entry.clone() };
|
||||
};
|
||||
match streamed.messages.get(&subagent).and_then(|sent| Some((sent.bytes, sent.utf16, sent.extended(i, text)?))) {
|
||||
Some((bytes, from, sent)) => {
|
||||
streamed.messages.insert(subagent.clone(), sent);
|
||||
Some(AgentEvent::Append {
|
||||
match streamed.get(&subagent).filter(|sent| sent.extended_by(i, text)) {
|
||||
Some(sent) => {
|
||||
let (bytes, from) = (sent.bytes, sent.utf16);
|
||||
streamed.insert(subagent.clone(), Sent::after(i, text, bytes, from));
|
||||
AgentEvent::Append {
|
||||
task: task.to_owned(),
|
||||
subagent,
|
||||
index: i as u32,
|
||||
from: from as u32,
|
||||
text: text[bytes..].to_owned(),
|
||||
})
|
||||
}
|
||||
}
|
||||
None => {
|
||||
streamed.messages.insert(subagent.clone(), Sent::new(i, text));
|
||||
Some(whole(subagent))
|
||||
streamed.insert(subagent.clone(), Sent::new(i, text));
|
||||
AgentEvent::Entry { task: task.to_owned(), subagent, index: i as u32, entry: entry.clone() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`entry_event`] for a tool call: the output it grew by while the rest of it is unchanged.
|
||||
fn tool_event(
|
||||
task: &str,
|
||||
streamed: &mut Streamed,
|
||||
subagent: Session,
|
||||
i: usize,
|
||||
entry: &AgentEntry,
|
||||
) -> Option<AgentEvent> {
|
||||
let AgentEntry::Tool { id, title, kind, status, locations, images, output, diffs, started_ms, ended_ms } = entry
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let call = AgentEntry::Tool {
|
||||
id: id.clone(),
|
||||
title: title.clone(),
|
||||
kind: kind.clone(),
|
||||
status: *status,
|
||||
locations: locations.clone(),
|
||||
images: images.clone(),
|
||||
output: None,
|
||||
diffs: diffs.clone(),
|
||||
started_ms: *started_ms,
|
||||
ended_ms: *ended_ms,
|
||||
};
|
||||
let text = output.as_deref().unwrap_or_default();
|
||||
let key = (subagent, i);
|
||||
if let Some(sent) = streamed.tools.get_mut(&key).filter(|sent| sent.call == call) {
|
||||
if let Some(output) = sent.output.extended(i, text) {
|
||||
let (bytes, from) = (sent.output.bytes, sent.output.utf16);
|
||||
sent.output = output;
|
||||
return Some(AgentEvent::ToolOutput {
|
||||
task: task.to_owned(),
|
||||
subagent: key.0,
|
||||
index: i as u32,
|
||||
from: from as u32,
|
||||
text: text[bytes..].to_owned(),
|
||||
});
|
||||
}
|
||||
if sent.output.is(text) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if matches!(status, AgentToolStatus::Pending | AgentToolStatus::Running) {
|
||||
streamed.tools.insert(key.clone(), SentTool { call, output: Sent::new(i, text) });
|
||||
} else {
|
||||
streamed.tools.remove(&key);
|
||||
}
|
||||
Some(AgentEvent::Entry { task: task.to_owned(), subagent: key.0, index: i as u32, entry: entry.clone() })
|
||||
}
|
||||
|
||||
struct SessionOpenError {
|
||||
message: String,
|
||||
allow_acp_fallback: bool,
|
||||
|
||||
@@ -801,16 +801,6 @@ pub enum AgentEvent {
|
||||
from: u32,
|
||||
text: String,
|
||||
},
|
||||
/// Text was appended to the output of tool entry `index`: it read the first `from` UTF-16
|
||||
/// units of its output when the previous event for it was sent. Any other change of the
|
||||
/// tool (status, title, diffs…) arrives as an `Entry`.
|
||||
ToolOutput {
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
index: u32,
|
||||
from: u32,
|
||||
text: String,
|
||||
},
|
||||
/// An agent reported the usage limits of its account (shared by every task of `provider`).
|
||||
Limits {
|
||||
provider: String,
|
||||
|
||||
+13
-730
@@ -32,10 +32,6 @@ struct FakeAgent {
|
||||
servers: Mutex<Vec<Peer>>,
|
||||
calls: Mutex<Vec<String>>,
|
||||
permission_replies: Mutex<Vec<Value>>,
|
||||
/// The tasks' store directory: when set, a "decide" prompt notes what the task file holds
|
||||
/// for the answered request at the moment its reply arrives.
|
||||
store_dir: Mutex<Option<PathBuf>>,
|
||||
file_at_reply: Mutex<Vec<Value>>,
|
||||
/// Without `loadSession` (a session lives only as long as its process).
|
||||
no_load: bool,
|
||||
auth_on_new: bool,
|
||||
@@ -222,10 +218,6 @@ impl Handler for FakeAgent {
|
||||
}
|
||||
"session/load" if self.load_error.is_some() => Err(self.load_error.clone().unwrap()),
|
||||
"session/load" => {
|
||||
self.update(
|
||||
&session,
|
||||
json!({"sessionUpdate": "user_message_chunk", "content": {"type": "text", "text": "earlier question"}}),
|
||||
);
|
||||
self.say(&session, "replayed history");
|
||||
Ok(json!({}))
|
||||
}
|
||||
@@ -286,24 +278,6 @@ impl Handler for FakeAgent {
|
||||
self.say(&session, "running it in the background");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "stream tool output" {
|
||||
// A long command whose output grows: every update carries all of it so far.
|
||||
let update = |kind: &str, status: &str, output: &str| {
|
||||
json!({"sessionUpdate": kind, "toolCallId": "build", "title": "cargo build",
|
||||
"kind": "execute", "status": status,
|
||||
"content": [{"type": "content", "content": {"type": "text", "text": output}}]})
|
||||
};
|
||||
self.update(&session, update("tool_call", "in_progress", "$ cargo build"));
|
||||
let mut output = String::from("$ cargo build");
|
||||
for i in 0..40 {
|
||||
output.push_str(&format!("\n{i:04} {}", "x".repeat(1500)));
|
||||
self.update(&session, update("tool_call_update", "in_progress", &output));
|
||||
// Longer than the flush interval: every update reaches the window on its own.
|
||||
std::thread::sleep(FLUSH_DELAY + Duration::from_millis(30));
|
||||
}
|
||||
self.update(&session, update("tool_call_update", "completed", &output));
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "delegate" {
|
||||
self.delegate(&session);
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
@@ -344,29 +318,6 @@ impl Handler for FakeAgent {
|
||||
self.say(&session, &format!("late chose {chosen}"));
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "decide" {
|
||||
let peer = self.latest();
|
||||
let _: Value = tokio::runtime::Handle::current()
|
||||
.block_on(peer.request(
|
||||
"session/request_permission",
|
||||
json!({"sessionId": session, "toolCall": {"toolCallId": "d1", "title": "Run cargo test"},
|
||||
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"},
|
||||
{"optionId": "no", "name": "Reject", "kind": "reject_once"}]}),
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
if let Some(dir) = self.store_dir.lock().clone() {
|
||||
let held = std::fs::read_dir(dir)
|
||||
.unwrap()
|
||||
.filter_map(|f| serde_json::from_slice::<Value>(&std::fs::read(f.ok()?.path()).ok()?).ok())
|
||||
.flat_map(|file| file["entries"].as_array().cloned().unwrap_or_default())
|
||||
.find_map(|entry| entry.get("chosen").cloned())
|
||||
.unwrap_or(Value::Null);
|
||||
self.file_at_reply.lock().push(held);
|
||||
}
|
||||
self.say(&session, "decided");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "escalate" {
|
||||
// A request for wider access, titled with text the model wrote.
|
||||
let peer = self.latest();
|
||||
@@ -1317,408 +1268,6 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
assert!(calls.contains(&"session/set_mode \"code\"".to_owned()), "{calls:?}");
|
||||
}
|
||||
|
||||
fn task_file(dir: &Path, id: &str) -> PathBuf {
|
||||
dir.join("store").join(format!("{id}.json"))
|
||||
}
|
||||
|
||||
fn saves(path: &Path) -> u32 {
|
||||
FILE_WRITES.lock().get(path).copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// What a task's file holds: its status and how many entries it has.
|
||||
fn saved_task(path: &Path) -> Option<(Value, usize)> {
|
||||
let file: Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
|
||||
Some((file["task"]["status"].clone(), file["entries"].as_array()?.len()))
|
||||
}
|
||||
|
||||
/// Shuts the manager down when the test ends, a failed assertion included: a failing test
|
||||
/// would otherwise never return while its turn is still running.
|
||||
struct ShutDown<'a>(&'a AgentManager);
|
||||
|
||||
impl Drop for ShutDown<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
/// A turn does not rewrite the whole task file for every step it goes through, and where the
|
||||
/// task stops for the user (a question, the end) the file already holds everything, as the
|
||||
/// window that was told finds it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_turn_saves_the_task_file_once_per_stop() {
|
||||
struct Stop {
|
||||
status: AgentStatus,
|
||||
saves: u32,
|
||||
file: Option<(Value, usize)>,
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _shut_down = ShutDown(&mgr);
|
||||
let stops = Arc::new(Mutex::new(Vec::<Stop>::new()));
|
||||
let (sink, dir) = (stops.clone(), tmp.path().to_path_buf());
|
||||
mgr.subscribe_as(
|
||||
"",
|
||||
Arc::new(move |event| {
|
||||
if let AgentEvent::Task { task } = event
|
||||
&& matches!(task.status, AgentStatus::NeedsInput | AgentStatus::Ready)
|
||||
{
|
||||
let path = task_file(&dir, &task.id);
|
||||
sink.lock().push(Stop { status: task.status, saves: saves(&path), file: saved_task(&path) });
|
||||
}
|
||||
}),
|
||||
);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("Fix the lexer"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// The first time the task stopped as `status` after the `from`th stop: what its file held then.
|
||||
let stopped = |status: AgentStatus, from: usize| {
|
||||
let stops = stops.clone();
|
||||
async move {
|
||||
for _ in 0..500 {
|
||||
if let Some(stop) = stops.lock().iter().skip(from).find(|s| s.status == status) {
|
||||
return (stop.saves, stop.file.clone());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
panic!("the task never stopped as {status:?}");
|
||||
}
|
||||
};
|
||||
let status = |s: AgentStatus| serde_json::to_value(s).unwrap();
|
||||
|
||||
let (first_turn, asked) = stopped(AgentStatus::NeedsInput, 0).await;
|
||||
// The user's message, "Hi", the edit and the pending permission are all in the file.
|
||||
assert_eq!(asked, Some((status(AgentStatus::NeedsInput), 4)));
|
||||
|
||||
let permission = mgr
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|e| match e {
|
||||
AgentEntry::Permission { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let seen = stops.lock().len();
|
||||
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
|
||||
let (ready_at, ready) = stopped(AgentStatus::Ready, seen).await;
|
||||
assert_eq!(ready, Some((status(AgentStatus::Ready), 5)));
|
||||
let answered = ready_at - first_turn;
|
||||
|
||||
let seen = stops.lock().len();
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
let (again_at, again) = stopped(AgentStatus::Ready, seen).await;
|
||||
assert_eq!(again, Some((status(AgentStatus::Ready), 7)));
|
||||
let second_turn = again_at - ready_at;
|
||||
eprintln!(
|
||||
"task file saves: {first_turn} to the first question, {answered} to answer it and finish, {second_turn} for a second turn"
|
||||
);
|
||||
assert!(
|
||||
first_turn <= 4 && answered <= 2 && second_turn <= 3,
|
||||
"task file saves: {first_turn} to the first question (4 or fewer), {answered} to answer it and finish (2 or fewer), {second_turn} for a second turn (3 or fewer)"
|
||||
);
|
||||
}
|
||||
|
||||
/// A reader of the task's state waits only for a copy of it, not for the whole transcript to
|
||||
/// be turned into JSON and written.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn saving_a_large_task_does_not_hold_up_readers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let path = task_file(tmp.path(), &task.id);
|
||||
for i in 0..24 {
|
||||
let text = format!("output {i}: \"quoted\"\n").repeat(40_000);
|
||||
handle.state.lock().conversation.main.push(AgentEntry::Agent { text });
|
||||
}
|
||||
let entries = handle.state.lock().conversation.main.entries.clone();
|
||||
let started = std::time::Instant::now();
|
||||
let json = serde_json::to_vec(&entries).unwrap();
|
||||
let serialising = started.elapsed();
|
||||
eprintln!("large task: {} MB of JSON, {serialising:?} to serialise", json.len() >> 20);
|
||||
|
||||
// The longest wait for the state lock while a save runs: the best of a few saves, so a
|
||||
// reader that was descheduled once does not fail the test.
|
||||
let mut waits = Vec::new();
|
||||
for _ in 0..3 {
|
||||
let writes = saves(&path);
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let reader = {
|
||||
let (handle, stop) = (handle.clone(), stop.clone());
|
||||
std::thread::spawn(move || {
|
||||
let mut longest = Duration::ZERO;
|
||||
while !stop.load(Ordering::Acquire) {
|
||||
let asked = std::time::Instant::now();
|
||||
drop(handle.state.lock());
|
||||
longest = longest.max(asked.elapsed());
|
||||
std::thread::sleep(Duration::from_micros(200));
|
||||
}
|
||||
longest
|
||||
})
|
||||
};
|
||||
handle.persist();
|
||||
while saves(&path) == writes {
|
||||
tokio::time::sleep(Duration::from_millis(1)).await;
|
||||
}
|
||||
stop.store(true, Ordering::Release);
|
||||
waits.push(reader.join().unwrap());
|
||||
}
|
||||
let shortest = waits.iter().min().copied().unwrap();
|
||||
eprintln!("longest wait for the state lock while saving: {waits:?}");
|
||||
assert!(shortest * 3 < serialising, "readers waited {shortest:?} while the task was saved ({serialising:?})");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
async fn idle_task(mgr: &AgentManager, title: &str) -> AgentTask {
|
||||
let request = NewAgentTask {
|
||||
prompt: text(title),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
idle: true,
|
||||
..Default::default()
|
||||
};
|
||||
mgr.create(request).await.unwrap()
|
||||
}
|
||||
|
||||
fn saved_title(path: &Path) -> Option<String> {
|
||||
let file: Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
|
||||
file["task"]["title"].as_str().map(str::to_owned)
|
||||
}
|
||||
|
||||
/// Changes asked for in a burst are written once, as the latest state, and no older state is
|
||||
/// written after it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn saves_asked_for_in_a_burst_write_the_latest_state_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = idle_task(&mgr, "first").await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let path = task_file(tmp.path(), &task.id);
|
||||
let before = saves(&path);
|
||||
for i in 0..50 {
|
||||
handle.state.lock().task.title = format!("title {i}");
|
||||
handle.persist_soon();
|
||||
}
|
||||
for _ in 0..500 {
|
||||
if saved_title(&path).as_deref() == Some("title 49") {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(saved_title(&path).as_deref(), Some("title 49"));
|
||||
tokio::time::sleep(SAVE_DELAY * 2).await;
|
||||
assert_eq!(saved_title(&path).as_deref(), Some("title 49"), "an older state was written back");
|
||||
let written = saves(&path) - before;
|
||||
mgr.shutdown();
|
||||
assert!(written <= 2, "50 changes in a burst were saved {written} times");
|
||||
}
|
||||
|
||||
/// Saves of one task from several threads, whether they wait or not, never put an older
|
||||
/// state back over a newer one, and saves of other tasks never mix in.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn concurrent_saves_keep_the_newest_state_of_each_task() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let mut tasks = Vec::new();
|
||||
for name in ["alpha", "beta"] {
|
||||
let task = idle_task(&mgr, name).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
// Long enough that a save takes a while between the copy and the write.
|
||||
handle.state.lock().conversation.main.push(AgentEntry::Agent { text: "text ".repeat(60_000) });
|
||||
tasks.push((name, handle, task_file(tmp.path(), &task.id)));
|
||||
}
|
||||
// "<name> <n>", n growing with every change made under the state lock.
|
||||
let change = |name: &str, handle: &Task, n: &AtomicU64| {
|
||||
let mut s = handle.state.lock();
|
||||
s.task.title = format!("{name} {}", n.fetch_add(1, Ordering::AcqRel) + 1);
|
||||
};
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let mut watchers = Vec::new();
|
||||
let mut writers = Vec::new();
|
||||
for (name, handle, path) in &tasks {
|
||||
let counter = Arc::new(AtomicU64::new(0));
|
||||
for pace in 0..2 {
|
||||
let (name, handle, counter) = (*name, handle.clone(), counter.clone());
|
||||
writers.push(std::thread::spawn(move || {
|
||||
for i in 0..40 {
|
||||
change(name, &handle, &counter);
|
||||
if (i + pace) % 2 == 0 {
|
||||
handle.persist();
|
||||
} else {
|
||||
handle.persist_soon();
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
let (name, path, stop) = (*name, path.clone(), stop.clone());
|
||||
watchers.push(std::thread::spawn(move || {
|
||||
let mut newest = 0;
|
||||
while !stop.load(Ordering::Acquire) {
|
||||
if let Some(title) = saved_title(&path) {
|
||||
// Nothing was saved yet but the task's name, before the first change.
|
||||
let n: u64 = match title.strip_prefix(&format!("{name} ")) {
|
||||
Some(n) => n.parse().unwrap(),
|
||||
None => {
|
||||
assert_eq!(title, name, "another task's state");
|
||||
0
|
||||
}
|
||||
};
|
||||
assert!(n >= newest, "{name}: state {n} was written after state {newest}");
|
||||
newest = n;
|
||||
}
|
||||
std::thread::sleep(Duration::from_micros(100));
|
||||
}
|
||||
}));
|
||||
}
|
||||
for writer in writers {
|
||||
writer.join().unwrap();
|
||||
}
|
||||
for (_, handle, _) in &tasks {
|
||||
handle.persist();
|
||||
}
|
||||
stop.store(true, Ordering::Release);
|
||||
for watcher in watchers {
|
||||
watcher.join().unwrap();
|
||||
}
|
||||
tokio::time::sleep(SAVE_DELAY * 2).await;
|
||||
for (name, handle, path) in &tasks {
|
||||
let title = handle.state.lock().task.title.clone();
|
||||
assert_eq!(title, format!("{name} 80"));
|
||||
assert_eq!(saved_title(path), Some(title));
|
||||
}
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// What was asked to be saved soon is written when the manager shuts down, and a task that
|
||||
/// is deleted meanwhile stays deleted.
|
||||
#[tokio::test]
|
||||
async fn shutdown_writes_the_saves_still_waiting_and_a_delete_drops_them() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let kept = idle_task(&mgr, "kept").await;
|
||||
let gone = idle_task(&mgr, "gone").await;
|
||||
let (kept_path, gone_path) = (task_file(tmp.path(), &kept.id), task_file(tmp.path(), &gone.id));
|
||||
for id in [&kept.id, &gone.id] {
|
||||
let handle = mgr.task(id).unwrap();
|
||||
handle.state.lock().task.title = "renamed".into();
|
||||
handle.persist_soon();
|
||||
}
|
||||
// This runtime runs one thing at a time and nothing has yielded to it: the saves wait.
|
||||
assert_eq!(saved_title(&kept_path).as_deref(), Some("kept"));
|
||||
mgr.delete(&gone.id, false).await.unwrap();
|
||||
mgr.shutdown();
|
||||
assert_eq!(saved_title(&kept_path).as_deref(), Some("renamed"), "shutdown left the task unsaved");
|
||||
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
assert_eq!(restored.task(&kept.id).unwrap().state.lock().task.title, "renamed");
|
||||
assert!(restored.task(&gone.id).is_err());
|
||||
tokio::time::sleep(SAVE_DELAY * 2).await;
|
||||
assert!(!gone_path.exists(), "the save that was waiting brought the deleted task back");
|
||||
assert_eq!(saved_title(&kept_path).as_deref(), Some("renamed"));
|
||||
}
|
||||
|
||||
/// Archiving saves the task as it is, including changes nobody asked to be saved.
|
||||
#[tokio::test]
|
||||
async fn archiving_saves_the_task_before_it_returns() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = idle_task(&mgr, "task").await;
|
||||
let path = task_file(tmp.path(), &task.id);
|
||||
mgr.task(&task.id).unwrap().state.lock().task.title = "changed meanwhile".into();
|
||||
mgr.archive(&task.id).unwrap();
|
||||
assert_eq!(saved_task(&path).map(|(status, _)| status), Some(serde_json::to_value(AgentStatus::Archived).unwrap()));
|
||||
assert_eq!(saved_title(&path).as_deref(), Some("changed meanwhile"));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// The answer to a request is in the task file before the agent hears it: a restart right
|
||||
/// after still shows the request as answered, not cancelled.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_answer_is_saved_before_the_agent_is_told() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.store_dir.lock() = Some(tmp.path().join("store"));
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let _shut_down = ShutDown(&mgr);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("decide"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let permission = mgr
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|e| match e {
|
||||
AgentEntry::Permission { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(*agent.file_at_reply.lock(), [json!("Allow")]);
|
||||
}
|
||||
|
||||
/// A turn that fails or hits the usage limit is in the task file by the time the window is
|
||||
/// told, like the end of a turn.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_failed_turn_is_saved_before_the_window_hears_of_it() {
|
||||
for (message, status) in [("auth", AgentStatus::Failed), ("limit", AgentStatus::Limited)] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _shut_down = ShutDown(&mgr);
|
||||
let told = Arc::new(Mutex::new(None));
|
||||
let (sink, dir) = (told.clone(), tmp.path().to_path_buf());
|
||||
mgr.subscribe_as(
|
||||
"",
|
||||
Arc::new(move |event| {
|
||||
if let AgentEvent::Task { task } = event
|
||||
&& task.status == status
|
||||
{
|
||||
*sink.lock() = Some(saved_task(&task_file(&dir, &task.id)).map(|(status, _)| status));
|
||||
}
|
||||
}),
|
||||
);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text(message),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, status).await;
|
||||
for _ in 0..500 {
|
||||
if told.lock().is_some() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(*told.lock(), Some(Some(serde_json::to_value(status).unwrap())), "{status:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_again() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -2187,9 +1736,6 @@ fn prompts_become_acp_content_blocks() {
|
||||
assert_eq!(title_of(&AgentPrompt { files: p.files.clone(), ..AgentPrompt::default() }), "my file.rs");
|
||||
let pasted = AgentPrompt { text: "```text\n\n ## Fix the tab title\n```".into(), ..AgentPrompt::default() };
|
||||
assert_eq!(title_of(&pasted), "## Fix the tab title");
|
||||
let fenced_first =
|
||||
AgentPrompt { text: "```txt\nlog line\n```\nWhy does this fail?".into(), ..AgentPrompt::default() };
|
||||
assert_eq!(title_of(&fenced_first), "Why does this fail?");
|
||||
assert!(clean(text(" ")).is_none());
|
||||
}
|
||||
|
||||
@@ -2546,55 +2092,6 @@ async fn renamed_titles_survive_updates_forks_and_restart() {
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_session_without_history_takes_it_from_the_replay_before_the_first_message() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = {
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
task_file(tmp.path(), &task.id)
|
||||
};
|
||||
let id = path.file_stem().unwrap().to_string_lossy().into_owned();
|
||||
// As an imported session is saved: its session id, none of its history.
|
||||
let mut file: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
|
||||
file["entries"] = json!([]);
|
||||
std::fs::write(&path, serde_json::to_vec(&file).unwrap()).unwrap();
|
||||
|
||||
{
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
mgr.prompt(&id, text("again"), false).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
wait_for(&mgr, &id, AgentStatus::Ready).await;
|
||||
let entries = mgr.entries(&id, None).unwrap();
|
||||
assert!(
|
||||
matches!(&entries[0], AgentEntry::User { text, sent_ms: None, .. } if text == "earlier question"),
|
||||
"{entries:?}"
|
||||
);
|
||||
assert_eq!(entries[1], AgentEntry::Agent { text: "replayed history".into() }, "{entries:?}");
|
||||
assert!(
|
||||
matches!(&entries[2], AgentEntry::User { text, sent_ms: Some(_), .. } if text == "again"),
|
||||
"{entries:?}"
|
||||
);
|
||||
assert_eq!(entries.last(), Some(&AgentEntry::Agent { text: "second turn".into() }), "{entries:?}");
|
||||
}
|
||||
assert_eq!(saved_task(&path).unwrap().1, 4);
|
||||
|
||||
// From then on the task has its history: a later reload's replay is dropped again.
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
mgr.prompt(&id, text("again"), false).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
wait_for(&mgr, &id, AgentStatus::Ready).await;
|
||||
let entries = mgr.entries(&id, None).unwrap();
|
||||
assert_eq!(entries.len(), 6, "{entries:?}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn startup_warnings_survive_replay_and_restart_without_failing_the_task() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -4006,256 +3503,42 @@ async fn discovery_times_out_when_session_new_hangs() {
|
||||
assert!(!cursor.config.iter().any(|o| o.category.as_deref() == Some("model")));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_growing_tool_output_is_not_sent_whole_on_every_flush() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
// What a window receives of the tool's entry: events, and the bytes they take.
|
||||
let sent = Arc::new(Mutex::new((0usize, Vec::<AgentEvent>::new())));
|
||||
let sink = sent.clone();
|
||||
mgr.subscribe_as(
|
||||
"",
|
||||
Arc::new(move |e| {
|
||||
let json = serde_json::to_value(&e).unwrap();
|
||||
if json["entry"]["type"] == "tool" || json["type"] == "toolOutput" {
|
||||
let mut sent = sink.lock();
|
||||
sent.0 += json.to_string().len();
|
||||
sent.1.push(e);
|
||||
}
|
||||
}),
|
||||
);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("stream tool output"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// The turn takes a few seconds: the agent paces its updates by the flush interval.
|
||||
let finished = |mgr: &AgentManager| {
|
||||
mgr.entries(&task.id, None).unwrap().into_iter().find_map(|e| match e {
|
||||
AgentEntry::Tool { output, status: AgentToolStatus::Completed, .. } => output,
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
for _ in 0..6000 {
|
||||
if finished(&mgr).is_some() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
tokio::time::sleep(FLUSH_DELAY * 3).await;
|
||||
|
||||
let output = finished(&mgr).expect("the command's output was kept");
|
||||
assert!(output.len() > 60_000, "a long output that the timeline keeps whole: {}", output.len());
|
||||
let (bytes, events) = {
|
||||
let sent = sent.lock();
|
||||
(sent.0, sent.1.len())
|
||||
};
|
||||
assert!(events >= 30, "the output reached the window in many flushes: {events}");
|
||||
assert!(bytes < 3 * output.len(), "{bytes} bytes sent for {} bytes of output over {events} events", output.len());
|
||||
|
||||
// The window's copy, built as the UI does, ends as the conversation holds it.
|
||||
let mut shown: Option<String> = None;
|
||||
for e in &sent.lock().1 {
|
||||
match e {
|
||||
AgentEvent::Entry { entry: AgentEntry::Tool { output, .. }, .. } => shown = output.clone(),
|
||||
AgentEvent::ToolOutput { from, text, .. } => {
|
||||
let have = shown.get_or_insert_default();
|
||||
assert_eq!(*from as usize, have.encode_utf16().count(), "a delta goes on where the last one ended");
|
||||
have.push_str(text);
|
||||
}
|
||||
_ => unreachable!("{e:?}"),
|
||||
}
|
||||
}
|
||||
assert_eq!(shown, Some(output));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_text_is_sent_as_appends() {
|
||||
let mut streamed = Streamed::default();
|
||||
let mut streamed = HashMap::new();
|
||||
let agent = |t: &str| AgentEntry::Agent { text: t.into() };
|
||||
let first = entry_event("t", &mut streamed, None, 3, &agent("Hé")).unwrap();
|
||||
let first = entry_event("t", &mut streamed, None, 3, &agent("Hé"));
|
||||
assert!(matches!(first, AgentEvent::Entry { index: 3, .. }), "the first sight of a message is whole");
|
||||
let next = entry_event("t", &mut streamed, None, 3, &agent("Hé 👋 there")).unwrap();
|
||||
let next = entry_event("t", &mut streamed, None, 3, &agent("Hé 👋 there"));
|
||||
assert!(
|
||||
matches!(&next, AgentEvent::Append { subagent: None, index: 3, from: 2, text, .. } if text == " 👋 there"),
|
||||
"{next:?}"
|
||||
);
|
||||
let sub = entry_event("t", &mut streamed, Some("s".into()), 3, &agent("Hé 👋 there!")).unwrap();
|
||||
let sub = entry_event("t", &mut streamed, Some("s".into()), 3, &agent("Hé 👋 there!"));
|
||||
assert!(matches!(sub, AgentEvent::Entry { .. }), "each session streams on its own");
|
||||
let after = entry_event("t", &mut streamed, None, 3, &agent("Hé 👋 there.")).unwrap();
|
||||
let after = entry_event("t", &mut streamed, None, 3, &agent("Hé 👋 there."));
|
||||
assert!(
|
||||
matches!(&after, AgentEvent::Append { from: 11, text, .. } if text == "."),
|
||||
"from counts UTF-16 units: {after:?}"
|
||||
);
|
||||
let replaced = entry_event("t", &mut streamed, None, 3, &agent("Other")).unwrap();
|
||||
let replaced = entry_event("t", &mut streamed, None, 3, &agent("Other"));
|
||||
assert!(matches!(replaced, AgentEvent::Entry { .. }), "text that doesn't extend the sent text is sent whole");
|
||||
let thought = AgentEntry::Thought { text: "hmm…".into(), started_ms: None };
|
||||
let thought = entry_event("t", &mut streamed, None, 4, &thought).unwrap();
|
||||
let thought = entry_event("t", &mut streamed, None, 4, &thought);
|
||||
assert!(matches!(thought, AgentEvent::Entry { index: 4, .. }), "a new message starts whole");
|
||||
let tool = AgentEntry::Error { message: "x".into() };
|
||||
entry_event("t", &mut streamed, None, 4, &tool).unwrap();
|
||||
entry_event("t", &mut streamed, None, 4, &tool);
|
||||
let again = AgentEntry::Thought { text: "hmm… ok".into(), started_ms: None };
|
||||
let again = entry_event("t", &mut streamed, None, 4, &again).unwrap();
|
||||
let again = entry_event("t", &mut streamed, None, 4, &again);
|
||||
assert!(matches!(again, AgentEvent::Entry { .. }), "an entry replaced by another kind forgets its text");
|
||||
|
||||
let long = "é".repeat(5000);
|
||||
entry_event("t", &mut streamed, None, 5, &agent(&long)).unwrap();
|
||||
let on = entry_event("t", &mut streamed, None, 5, &agent(&format!("{long}!"))).unwrap();
|
||||
entry_event("t", &mut streamed, None, 5, &agent(&long));
|
||||
assert!(streamed[&None].tail.len() <= 64, "only the end of what was sent is kept");
|
||||
let on = entry_event("t", &mut streamed, None, 5, &agent(&format!("{long}!")));
|
||||
assert!(matches!(&on, AgentEvent::Append { from: 5000, text, .. } if text == "!"), "{on:?}");
|
||||
let rewritten = entry_event("t", &mut streamed, None, 5, &agent(&format!("{}x!??", "é".repeat(4999)))).unwrap();
|
||||
let rewritten = entry_event("t", &mut streamed, None, 5, &agent(&format!("{}x!??", "é".repeat(4999))));
|
||||
assert!(matches!(rewritten, AgentEvent::Entry { .. }), "a rewritten end is sent whole");
|
||||
// A text that goes on with its end as sent but an edited start is not an append.
|
||||
let kept_end =
|
||||
entry_event("t", &mut streamed, None, 5, &agent(&format!("{}{}", "e".repeat(5000), "é".repeat(5000))));
|
||||
assert!(matches!(kept_end, Some(AgentEvent::Entry { .. })), "{kept_end:?}");
|
||||
let edited_start =
|
||||
entry_event("t", &mut streamed, None, 5, &agent(&format!("{}{}!", "x".repeat(5000), "é".repeat(5000))));
|
||||
assert!(
|
||||
matches!(edited_start, Some(AgentEvent::Entry { .. })),
|
||||
"a rewritten start is sent whole even when the end is as sent: {edited_start:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_running_tools_output_is_sent_as_appends() {
|
||||
let mut streamed = Streamed::default();
|
||||
let call = |status, output: Option<&str>| AgentEntry::Tool {
|
||||
id: "t1".into(),
|
||||
title: "cargo build".into(),
|
||||
kind: "execute".into(),
|
||||
status,
|
||||
locations: Vec::new(),
|
||||
images: Vec::new(),
|
||||
output: output.map(str::to_owned),
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(1.0),
|
||||
ended_ms: None,
|
||||
};
|
||||
let running = |output| call(AgentToolStatus::Running, output);
|
||||
let event = |streamed: &mut Streamed, session: Session, i, entry: &AgentEntry| {
|
||||
entry_event("t", streamed, session, i, entry)
|
||||
};
|
||||
|
||||
let first = event(&mut streamed, None, 2, &running(None)).unwrap();
|
||||
assert!(matches!(first, AgentEvent::Entry { index: 2, .. }), "the first sight of a call is whole");
|
||||
let output = event(&mut streamed, None, 2, &running(Some("$ make"))).unwrap();
|
||||
assert!(
|
||||
matches!(&output, AgentEvent::ToolOutput { subagent: None, index: 2, from: 0, text, .. } if text == "$ make"),
|
||||
"{output:?}"
|
||||
);
|
||||
let next = event(&mut streamed, None, 2, &running(Some("$ make\ncc é.c 👋"))).unwrap();
|
||||
assert!(
|
||||
matches!(&next, AgentEvent::ToolOutput { from: 6, text, .. } if text == "\ncc é.c 👋"),
|
||||
"from counts UTF-16 units: {next:?}"
|
||||
);
|
||||
let after = event(&mut streamed, None, 2, &running(Some("$ make\ncc é.c 👋\nok"))).unwrap();
|
||||
assert!(matches!(&after, AgentEvent::ToolOutput { from: 16, text, .. } if text == "\nok"), "{after:?}");
|
||||
assert!(
|
||||
event(&mut streamed, None, 2, &running(Some("$ make\ncc é.c 👋\nok"))).is_none(),
|
||||
"what the window has is not sent again"
|
||||
);
|
||||
|
||||
// Anything else about the call goes whole, output included.
|
||||
let mut titled = running(Some("$ make\ncc é.c 👋\nok\n"));
|
||||
if let AgentEntry::Tool { title, .. } = &mut titled {
|
||||
*title = "make".into();
|
||||
}
|
||||
let renamed = event(&mut streamed, None, 2, &titled).unwrap();
|
||||
assert!(
|
||||
matches!(&renamed, AgentEvent::Entry { entry: AgentEntry::Tool { output: Some(o), .. }, .. } if o.ends_with("ok\n")),
|
||||
"{renamed:?}"
|
||||
);
|
||||
let on = event(&mut streamed, None, 2, &titled);
|
||||
assert!(on.is_none(), "the entry the window holds now is this one");
|
||||
if let AgentEntry::Tool { output, .. } = &mut titled {
|
||||
output.as_mut().unwrap().push_str("more");
|
||||
}
|
||||
let on = event(&mut streamed, None, 2, &titled).unwrap();
|
||||
assert!(matches!(&on, AgentEvent::ToolOutput { from: 20, text, .. } if text == "more"), "{on:?}");
|
||||
|
||||
// An image the tool returned is not part of the appended text: it goes with the whole entry.
|
||||
let mut shown = titled.clone();
|
||||
if let AgentEntry::Tool { images, output, .. } = &mut shown {
|
||||
images.push(AgentImage { mime_type: "image/png".into(), data: "AAAA".into(), name: None });
|
||||
output.as_mut().unwrap().push('!');
|
||||
}
|
||||
let imaged = event(&mut streamed, None, 2, &shown).unwrap();
|
||||
assert!(
|
||||
matches!(&imaged, AgentEvent::Entry { entry: AgentEntry::Tool { images, .. }, .. } if images.len() == 1),
|
||||
"{imaged:?}"
|
||||
);
|
||||
titled = shown;
|
||||
|
||||
// Output the call replaced rather than extended goes whole.
|
||||
let make = |output: &str| {
|
||||
let mut entry = titled.clone();
|
||||
if let AgentEntry::Tool { output: o, .. } = &mut entry {
|
||||
*o = Some(output.to_owned());
|
||||
}
|
||||
entry
|
||||
};
|
||||
let replaced = event(&mut streamed, None, 2, &make("$ make\nother")).unwrap();
|
||||
assert!(matches!(replaced, AgentEvent::Entry { .. }), "a rewritten output is sent whole");
|
||||
let on = event(&mut streamed, None, 2, &make("$ make\nother, but longer")).unwrap();
|
||||
assert!(matches!(on, AgentEvent::ToolOutput { from: 12, .. }), "and the next growth is appended to it: {on:?}");
|
||||
|
||||
// A replacement that keeps the old end, or the old length, is not mistaken for growth.
|
||||
let mut kept = make("$ make\nother, but longer");
|
||||
let swap = |entry: &mut AgentEntry, output: String| {
|
||||
if let AgentEntry::Tool { output: o, .. } = entry {
|
||||
*o = Some(output);
|
||||
}
|
||||
};
|
||||
let (long_tail, same_length) =
|
||||
(format!("{}{}", "X".repeat(100), "z".repeat(100)), "Y".repeat(100) + &"z".repeat(100));
|
||||
swap(&mut kept, long_tail.clone());
|
||||
event(&mut streamed, None, 2, &kept).unwrap();
|
||||
swap(&mut kept, same_length);
|
||||
let same = event(&mut streamed, None, 2, &kept).unwrap();
|
||||
assert!(
|
||||
matches!(&same, AgentEvent::Entry { entry: AgentEntry::Tool { output: Some(o), .. }, .. } if o.starts_with('Y')),
|
||||
"same length, same end, different start is sent whole: {same:?}"
|
||||
);
|
||||
swap(&mut kept, format!("{}{}!", "W".repeat(100), "z".repeat(100)));
|
||||
let grown = event(&mut streamed, None, 2, &kept).unwrap();
|
||||
assert!(
|
||||
matches!(grown, AgentEvent::Entry { .. }),
|
||||
"a replacement that also grows, with the old end, is sent whole: {grown:?}"
|
||||
);
|
||||
|
||||
// Calls run side by side, each in its own session.
|
||||
let whole = |e: &AgentEvent| matches!(e, AgentEvent::Entry { .. });
|
||||
let (a, b) = (
|
||||
event(&mut streamed, None, 3, &running(Some("a"))),
|
||||
event(&mut streamed, Some("s".into()), 3, &running(Some("b"))),
|
||||
);
|
||||
let c = event(&mut streamed, None, 4, &running(Some("c")));
|
||||
assert!([&a, &b, &c].into_iter().all(|e| whole(e.as_ref().unwrap())), "each call starts whole");
|
||||
let a = event(&mut streamed, None, 3, &running(Some("ab"))).unwrap();
|
||||
let c = event(&mut streamed, None, 4, &running(Some("cd"))).unwrap();
|
||||
let b = event(&mut streamed, Some("s".into()), 3, &running(Some("bc"))).unwrap();
|
||||
assert!(
|
||||
[&a, &b, &c].into_iter().all(|e| matches!(e, AgentEvent::ToolOutput { from: 1, .. })),
|
||||
"one call's flush does not end another's: {a:?} {b:?} {c:?}"
|
||||
);
|
||||
|
||||
// A call that ended is sent whole, and forgotten.
|
||||
let done = call(AgentToolStatus::Completed, Some("ab\ndone"));
|
||||
let done_event = event(&mut streamed, None, 3, &done).unwrap();
|
||||
assert!(matches!(done_event, AgentEvent::Entry { .. }));
|
||||
assert!(!streamed.tools.contains_key(&(None, 3)));
|
||||
let late = event(&mut streamed, None, 3, &call(AgentToolStatus::Completed, Some("ab\ndone\nlate"))).unwrap();
|
||||
assert!(matches!(late, AgentEvent::Entry { .. }), "an ended call's output is not appended to");
|
||||
|
||||
// A rollback forgets what was sent.
|
||||
streamed.clear();
|
||||
let again = event(&mut streamed, None, 4, &running(Some("cdef"))).unwrap();
|
||||
assert!(matches!(again, AgentEvent::Entry { .. }), "after the conversation was cut, calls start whole");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -41,11 +41,6 @@ pub enum ErrorData {
|
||||
AmendConflict {
|
||||
commit: String,
|
||||
},
|
||||
/// jdtls could not set a module up as a Java project: the errors on its build files and
|
||||
/// the builds enclosing it (`path: message`, the path relative to the project), nearest first.
|
||||
JavaBuildProblems {
|
||||
problems: Vec<String>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Git's reported result for each destination ref. A remote with several push URLs can
|
||||
|
||||
@@ -316,7 +316,6 @@ impl ClickhousePool {
|
||||
has_more,
|
||||
elapsed_ms: started.elapsed().as_secs_f64() * 1000.0,
|
||||
execution_ms,
|
||||
truncated: Vec::new(),
|
||||
})
|
||||
};
|
||||
let result = tokio::select! {
|
||||
|
||||
+48
-241
@@ -48,65 +48,6 @@ pub struct QueryResult {
|
||||
pub elapsed_ms: f64,
|
||||
/// Until the server's first answer; the rest of `elapsed_ms` is fetching.
|
||||
pub execution_ms: f64,
|
||||
/// Cells of `rows` cut short by [`QueryResult::cap_cells`], in row order.
|
||||
pub truncated: Vec<TruncatedCell>,
|
||||
}
|
||||
|
||||
/// A cell of a [`QueryResult`] whose text was cut to a prefix.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbTruncatedCell")]
|
||||
pub struct TruncatedCell {
|
||||
pub row: u32,
|
||||
pub column: u32,
|
||||
/// Length of the whole value in UTF-16 code units (what a JavaScript string counts).
|
||||
pub length: u32,
|
||||
/// FNV-1a (32 bits) of the whole value's UTF-16 code units, each taken as one 16-bit step,
|
||||
/// so a client that reads the value again can tell whether it is the one that was cut.
|
||||
pub hash: u32,
|
||||
}
|
||||
|
||||
/// FNV-1a over UTF-16 code units, one step per unit (the same on the client: see `cutCells.ts`).
|
||||
fn fnv1a_utf16(text: &str) -> u32 {
|
||||
let mut hash: u32 = 0x811c_9dc5;
|
||||
let mut pair = [0u16; 2];
|
||||
for ch in text.chars() {
|
||||
for unit in ch.encode_utf16(&mut pair) {
|
||||
hash = (hash ^ u32::from(*unit)).wrapping_mul(0x0100_0193);
|
||||
}
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
impl QueryResult {
|
||||
/// Cuts every cell longer than `limit` UTF-16 code units to its first `limit` (never inside a
|
||||
/// surrogate pair) and lists it in `truncated`, so a page's size no longer depends on how
|
||||
/// wide its values are. The full value is read again, one row at a time, when it is needed.
|
||||
pub fn cap_cells(&mut self, limit: usize) {
|
||||
for (r, row) in self.rows.iter_mut().enumerate() {
|
||||
for (c, cell) in row.iter_mut().enumerate() {
|
||||
let Some(text) = cell else { continue };
|
||||
// A UTF-16 length never exceeds the UTF-8 one.
|
||||
if text.len() <= limit {
|
||||
continue;
|
||||
}
|
||||
let mut units = 0;
|
||||
let mut cut = text.len();
|
||||
for (at, ch) in text.char_indices() {
|
||||
if units + ch.len_utf16() > limit && cut == text.len() {
|
||||
cut = at;
|
||||
}
|
||||
units += ch.len_utf16();
|
||||
}
|
||||
if units <= limit {
|
||||
continue;
|
||||
}
|
||||
let hash = fnv1a_utf16(text);
|
||||
text.truncate(cut);
|
||||
self.truncated.push(TruncatedCell { row: r as u32, column: c as u32, length: units as u32, hash });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Session context belongs to the physical connection, including across pool checkouts.
|
||||
@@ -545,86 +486,6 @@ fn result_columns<R: Row>(row: &R) -> Vec<ResultColumn> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How far a statement's stream has been read: the columns seen so far, and the row that
|
||||
/// showed more were coming, which the next read starts with.
|
||||
pub(crate) struct Reader<R> {
|
||||
columns: Vec<ResultColumn>,
|
||||
carry: Option<R>,
|
||||
}
|
||||
|
||||
impl<R> Default for Reader<R> {
|
||||
fn default() -> Self {
|
||||
Self { columns: Vec::new(), carry: None }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Rows pulled from statement streams on this thread (tests count what paging reads).
|
||||
pub(crate) static ROWS_PULLED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Reads on from `stream`: past the next `skip` rows without decoding them, then keeping at
|
||||
/// most `max` rows with their cells read as `mode`. `rows_affected` reads a command's count.
|
||||
async fn drain<S, D, R>(
|
||||
stream: &mut S,
|
||||
reader: &mut Reader<R>,
|
||||
skip: usize,
|
||||
max: usize,
|
||||
mode: Cells,
|
||||
rows_affected: impl Fn(&D) -> u64,
|
||||
) -> IdeResult<Fetched>
|
||||
where
|
||||
S: futures::Stream<Item = Result<sqlx::Either<D, R>, sqlx::Error>> + Unpin,
|
||||
R: Row,
|
||||
usize: ColumnIndex<R>,
|
||||
String: sqlx::Type<R::Database>,
|
||||
for<'r> String: Decode<'r, R::Database>,
|
||||
for<'r> Vec<u8>: Decode<'r, R::Database>,
|
||||
{
|
||||
let mut rows: Vec<Vec<Option<String>>> = Vec::new();
|
||||
let mut affected: Option<u64> = None;
|
||||
let mut has_more = false;
|
||||
let mut first: Option<Instant> = None;
|
||||
let mut to_skip = skip;
|
||||
loop {
|
||||
let item = match reader.carry.take() {
|
||||
Some(row) => Ok(sqlx::Either::Right(row)),
|
||||
None => match stream.next().await {
|
||||
Some(item) => {
|
||||
#[cfg(test)]
|
||||
if matches!(item, Ok(sqlx::Either::Right(_))) {
|
||||
ROWS_PULLED.with(|n| n.set(n.get() + 1));
|
||||
}
|
||||
item
|
||||
}
|
||||
None => break,
|
||||
},
|
||||
};
|
||||
first.get_or_insert_with(Instant::now);
|
||||
match item {
|
||||
Ok(sqlx::Either::Left(done)) => affected = Some(affected.unwrap_or(0) + rows_affected(&done)),
|
||||
Ok(sqlx::Either::Right(row)) => {
|
||||
if reader.columns.is_empty() {
|
||||
reader.columns = result_columns(&row);
|
||||
}
|
||||
if to_skip > 0 {
|
||||
to_skip -= 1;
|
||||
continue;
|
||||
}
|
||||
if rows.len() >= max {
|
||||
reader.carry = Some(row);
|
||||
has_more = true;
|
||||
break;
|
||||
}
|
||||
rows.push((0..row.len()).map(|i| cell(&row, i, mode)).collect());
|
||||
}
|
||||
Err(e) => return Err(db_err(e)),
|
||||
}
|
||||
}
|
||||
Ok((reader.columns.clone(), rows, affected, has_more, first))
|
||||
}
|
||||
|
||||
/// Streams the results of `$sql` on executor `$exec`, reading past the first `$skip`
|
||||
/// rows without decoding them, then keeping at most `$max` rows with their cells read as `$mode`.
|
||||
macro_rules! fetch {
|
||||
@@ -632,8 +493,44 @@ macro_rules! fetch {
|
||||
fetch!($exec, $sql, 0usize, $max, $mode)
|
||||
};
|
||||
($exec:expr, $sql:expr, $skip:expr, $max:expr, $mode:expr) => {{
|
||||
use futures::StreamExt;
|
||||
let mut stream = sqlx::raw_sql(sqlx::AssertSqlSafe($sql.to_owned())).fetch_many($exec);
|
||||
drain(&mut stream, &mut Reader::default(), $skip, $max, $mode, |done| done.rows_affected()).await
|
||||
let mut columns: Vec<ResultColumn> = Vec::new();
|
||||
let mut rows: Vec<Vec<Option<String>>> = Vec::new();
|
||||
let mut affected: Option<u64> = None;
|
||||
let mut has_more = false;
|
||||
let mut failure = None;
|
||||
let mut first: Option<Instant> = None;
|
||||
let mut to_skip: usize = $skip;
|
||||
while let Some(item) = stream.next().await {
|
||||
first.get_or_insert_with(Instant::now);
|
||||
match item {
|
||||
Ok(sqlx::Either::Left(done)) => affected = Some(affected.unwrap_or(0) + done.rows_affected()),
|
||||
Ok(sqlx::Either::Right(row)) => {
|
||||
if columns.is_empty() {
|
||||
columns = result_columns(&row);
|
||||
}
|
||||
if to_skip > 0 {
|
||||
to_skip -= 1;
|
||||
continue;
|
||||
}
|
||||
if rows.len() >= $max {
|
||||
has_more = true;
|
||||
break;
|
||||
}
|
||||
rows.push((0..row.len()).map(|i| cell(&row, i, $mode)).collect());
|
||||
}
|
||||
Err(e) => {
|
||||
failure = Some(db_err(e));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(stream);
|
||||
match failure {
|
||||
Some(e) => Err(e),
|
||||
None => Ok((columns, rows, affected, has_more, first)),
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
@@ -689,31 +586,6 @@ macro_rules! backend_id {
|
||||
}};
|
||||
}
|
||||
|
||||
mod cursor;
|
||||
pub(crate) use cursor::{Cursors, Key as CursorKey};
|
||||
|
||||
/// Whether the pages of `sql`'s result can be read by a cursor (see [`cursor`]): a query that
|
||||
/// leaves the session as it was.
|
||||
pub(crate) fn cursor_statement(sql: &str) -> bool {
|
||||
looks_like_query(sql) && !context_may_change(sql)
|
||||
}
|
||||
|
||||
/// A [`QueryResult`] of what `fetched` read of `sql`, run since `started`.
|
||||
pub(crate) fn query_result(sql: &str, fetched: Fetched, started: Instant) -> QueryResult {
|
||||
let (columns, rows, affected, has_more, first) = fetched;
|
||||
let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
QueryResult {
|
||||
statement: sql.to_owned(),
|
||||
affected: if columns.is_empty() { Some(affected.unwrap_or(0) as f64) } else { None },
|
||||
columns,
|
||||
rows,
|
||||
has_more,
|
||||
elapsed_ms,
|
||||
execution_ms: first.map_or(elapsed_ms, |t| t.duration_since(started).as_secs_f64() * 1000.0),
|
||||
truncated: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
// Session control, scripts and PostgreSQL set_config can invalidate the tracked context.
|
||||
fn context_may_change(sql: &str) -> bool {
|
||||
let text = sql.trim().trim_end_matches(';');
|
||||
@@ -1113,12 +985,6 @@ impl Pool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a later page of a result can be read from a cursor instead of by running the statement
|
||||
/// again: the drivers whose rows stream from one connection that can wait for the next page.
|
||||
pub(crate) fn keeps_cursors(&self) -> bool {
|
||||
matches!(self, Pool::Sqlite(_) | Pool::Postgres(_) | Pool::Mysql(_))
|
||||
}
|
||||
|
||||
/// Runs `sql` (no row limit beyond `max`), for introspection: cells are text (see [`Cells::Text`]).
|
||||
pub async fn rows(&self, sql: &str, max: usize) -> IdeResult<Vec<Vec<Option<String>>>> {
|
||||
if let Pool::Jdbc(p) = self {
|
||||
@@ -1537,7 +1403,17 @@ impl Held {
|
||||
Held::Clickhouse(_) | Held::Snowflake(..) => unreachable!(),
|
||||
};
|
||||
self.after_statement(sql);
|
||||
Ok(query_result(sql, fetched, started))
|
||||
let (columns, rows, affected, has_more, first) = fetched;
|
||||
let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
Ok(QueryResult {
|
||||
statement: sql.to_owned(),
|
||||
affected: if columns.is_empty() { Some(affected.unwrap_or(0) as f64) } else { None },
|
||||
columns,
|
||||
rows,
|
||||
has_more,
|
||||
elapsed_ms,
|
||||
execution_ms: first.map_or(elapsed_ms, |t| t.duration_since(started).as_secs_f64() * 1000.0),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1563,75 +1439,6 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::source::{DbOptions, DbProperty};
|
||||
|
||||
fn rows(cells: Vec<Vec<Option<String>>>) -> QueryResult {
|
||||
query_result("select", (Vec::new(), cells, None, false, None), Instant::now())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capping_cells_bounds_a_page_and_reports_the_whole_length() {
|
||||
let wide = "x".repeat(1_000_000);
|
||||
let mut r = rows(vec![vec![Some("short".into()), Some(wide.clone()), None], vec![Some(wide), None, None]]);
|
||||
r.cap_cells(100);
|
||||
let size: usize = r.rows.iter().flatten().flatten().map(String::len).sum();
|
||||
assert_eq!(size, 5 + 100 + 100);
|
||||
assert_eq!(
|
||||
r.truncated,
|
||||
[
|
||||
TruncatedCell { row: 0, column: 1, length: 1_000_000, hash: fnv1a_utf16(&"x".repeat(1_000_000)) },
|
||||
TruncatedCell { row: 1, column: 0, length: 1_000_000, hash: fnv1a_utf16(&"x".repeat(1_000_000)) }
|
||||
]
|
||||
);
|
||||
assert_eq!(r.rows[0][0].as_deref(), Some("short"));
|
||||
assert_eq!(r.rows[0][2], None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_cell_is_hashed_by_its_utf16_units() {
|
||||
// Fixed values: the client (`cutCells.ts`) computes the same hash to recognise a value it reads again.
|
||||
assert_eq!(fnv1a_utf16(""), 2_166_136_261);
|
||||
assert_eq!(fnv1a_utf16("a"), 3_826_002_220);
|
||||
assert_eq!(fnv1a_utf16("a😀b"), 2_412_414_209);
|
||||
assert_eq!(fnv1a_utf16("日本語日本語"), 2_778_669_755);
|
||||
assert_ne!(fnv1a_utf16(&"x".repeat(100)), fnv1a_utf16(&format!("{}y", "x".repeat(99))));
|
||||
let mut r = rows(vec![vec![Some("a😀b".into())]]);
|
||||
r.cap_cells(2);
|
||||
assert_eq!(r.truncated[0].hash, 2_412_414_209);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capping_cells_keeps_values_at_or_under_the_limit_whole() {
|
||||
let mut r = rows(vec![vec![Some("abcd".into()), Some("😀😀".into()), Some("ééé".into())]]);
|
||||
// 4 units, 4 units (two pairs), 3 units in 6 bytes.
|
||||
r.cap_cells(4);
|
||||
assert!(r.truncated.is_empty());
|
||||
assert_eq!(r.rows[0][1].as_deref(), Some("😀😀"));
|
||||
r.cap_cells(3);
|
||||
assert_eq!(
|
||||
r.truncated,
|
||||
[
|
||||
TruncatedCell { row: 0, column: 0, length: 4, hash: fnv1a_utf16("abcd") },
|
||||
TruncatedCell { row: 0, column: 1, length: 4, hash: fnv1a_utf16("😀😀") }
|
||||
]
|
||||
);
|
||||
assert_eq!(r.rows[0][2].as_deref(), Some("ééé"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capping_cells_never_splits_a_character_or_a_surrogate_pair() {
|
||||
// "a😀b": units a=1, 😀=2, b=1. A cut inside the pair falls back to before it.
|
||||
let mut r = rows(vec![vec![Some("a😀b".into()), Some("日本語日本語".into())]]);
|
||||
r.cap_cells(2);
|
||||
assert_eq!(r.rows[0][0].as_deref(), Some("a"));
|
||||
assert_eq!(r.rows[0][1].as_deref(), Some("日本"));
|
||||
assert_eq!(r.truncated[0].length, 4);
|
||||
assert_eq!(r.truncated[1].length, 6);
|
||||
// What is kept is a prefix of the whole value, measured in UTF-16 units.
|
||||
for (cut, whole) in [(&r.rows[0][0], "a😀b"), (&r.rows[0][1], "日本語日本語")] {
|
||||
assert!(whole.starts_with(cut.as_deref().unwrap()));
|
||||
assert!(cut.as_deref().unwrap().encode_utf16().count() <= 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefer_retries_without_tls_only_after_a_failed_handshake() {
|
||||
use std::io;
|
||||
|
||||
@@ -1,474 +0,0 @@
|
||||
//! Result paging that reads on from where the previous page stopped.
|
||||
//!
|
||||
//! A statement has no way to start at row N: its server sends the rows before it, and a
|
||||
//! page that re-runs the query reads and drops all of them. The page after another one
|
||||
//! continues the same stream instead, so paging forward costs one page per click.
|
||||
//!
|
||||
//! A cursor keeps its statement's stream, and so its connection, open, which holds
|
||||
//! server resources (locks, a snapshot) for as long as it lives. That is bounded:
|
||||
//! one cursor per target, a few overall, each closed after [`IDLE`] without a page, when
|
||||
//! its tab is closed or its target disconnects, and before a statement that is not a
|
||||
//! query runs on its target. A page that finds no cursor at its position (jumping
|
||||
//! to another page, going back, a closed cursor) starts a new one.
|
||||
|
||||
use super::{Cells, Fetched, Held, Pool, Reader, drain, looks_like_query, statement_columns};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use parking_lot::Mutex;
|
||||
use sqlx::{Executor, SqlSafeStr};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
/// How long a cursor waits for its next page.
|
||||
const IDLE: Duration = Duration::from_secs(30);
|
||||
/// Cursors kept at once, over all targets (each holds a connection).
|
||||
const MAX_CURSORS: usize = 4;
|
||||
|
||||
/// What a cursor reads the pages of: one statement of one target, in a schema context.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct Key {
|
||||
target: String,
|
||||
statement: String,
|
||||
schema: Option<String>,
|
||||
}
|
||||
|
||||
impl Key {
|
||||
pub(crate) fn new(target: &str, statement: &str, schema: Option<&str>) -> Self {
|
||||
Self {
|
||||
target: target.to_owned(),
|
||||
statement: statement.to_owned(),
|
||||
schema: schema.filter(|s| !s.is_empty()).map(str::to_owned),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A request for the next rows of a cursor's statement.
|
||||
struct Read {
|
||||
skip: usize,
|
||||
max: usize,
|
||||
cancel: CancellationToken,
|
||||
reply: oneshot::Sender<IdeResult<Fetched>>,
|
||||
}
|
||||
|
||||
/// A live cursor: where its stream stands, and the channel to the task that owns it.
|
||||
struct Slot {
|
||||
id: u64,
|
||||
key: Key,
|
||||
/// The number of rows read from the start of the statement (skipped or returned).
|
||||
next: usize,
|
||||
/// A page is being read from it: it stays registered meanwhile, so a release finds it.
|
||||
busy: bool,
|
||||
reads: mpsc::Sender<Read>,
|
||||
}
|
||||
|
||||
/// Reads `max` rows after the first `skip` of a cursor's stream through `reads`; `None` when the cursor is gone.
|
||||
async fn read(
|
||||
reads: &mpsc::Sender<Read>,
|
||||
skip: usize,
|
||||
max: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> Option<IdeResult<Fetched>> {
|
||||
let (reply, answer) = oneshot::channel();
|
||||
reads.send(Read { skip, max, cancel: cancel.clone(), reply }).await.ok()?;
|
||||
answer.await.ok()
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Registry {
|
||||
/// Oldest first.
|
||||
slots: Vec<Slot>,
|
||||
issued: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Cursors {
|
||||
registry: Mutex<Registry>,
|
||||
}
|
||||
|
||||
impl Cursors {
|
||||
/// The page at `skip` read from the cursor of `key` that stands there; `None` when
|
||||
/// there is none (the caller starts one) or it failed (a lost connection: the caller
|
||||
/// runs the statement again and reports whatever that returns).
|
||||
pub(crate) async fn resume(
|
||||
&self,
|
||||
key: &Key,
|
||||
skip: usize,
|
||||
max: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> Option<IdeResult<Fetched>> {
|
||||
let (id, reads) = {
|
||||
let mut registry = self.registry.lock();
|
||||
let slot = registry
|
||||
.slots
|
||||
.iter_mut()
|
||||
.find(|s| s.key == *key && s.next == skip && !s.busy && !s.reads.is_closed())?;
|
||||
slot.busy = true;
|
||||
(slot.id, slot.reads.clone())
|
||||
};
|
||||
match read(&reads, 0, max, cancel).await {
|
||||
Some(Ok(fetched)) => {
|
||||
self.finish(id, &fetched);
|
||||
Some(Ok(fetched))
|
||||
}
|
||||
Some(Err(e)) if e.kind == ErrorKind::Cancelled => {
|
||||
self.close(id);
|
||||
Some(Err(e))
|
||||
}
|
||||
_ => {
|
||||
self.close(id);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the statement of `key` on `held`, returns the page at `skip` and keeps the
|
||||
/// statement's stream for the page after it. `held` is taken out of `pool` (its
|
||||
/// context applied); `pool` stops the statement on the server when `cancel` fires.
|
||||
pub(crate) async fn start(
|
||||
&self,
|
||||
held: Held,
|
||||
pool: Arc<Pool>,
|
||||
key: Key,
|
||||
skip: usize,
|
||||
max: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Fetched> {
|
||||
let (reads, requests) = mpsc::channel(1);
|
||||
tokio::spawn(serve(held, pool, key.statement.clone(), requests));
|
||||
let id = self.register(key, skip, reads.clone());
|
||||
let fetched = match read(&reads, skip, max, cancel).await {
|
||||
Some(Ok(fetched)) => fetched,
|
||||
other => {
|
||||
self.close(id);
|
||||
return other.unwrap_or_else(|| Err(IdeError::internal("the statement stopped before it answered")));
|
||||
}
|
||||
};
|
||||
self.finish(id, &fetched);
|
||||
Ok(fetched)
|
||||
}
|
||||
|
||||
/// Registers a cursor that is reading its first page. A target keeps one cursor (its
|
||||
/// connection pool is small), and all together are bounded.
|
||||
fn register(&self, key: Key, next: usize, reads: mpsc::Sender<Read>) -> u64 {
|
||||
let mut registry = self.registry.lock();
|
||||
registry.issued += 1;
|
||||
let id = registry.issued;
|
||||
registry.slots.retain(|s| s.key.target != key.target && !s.reads.is_closed());
|
||||
registry.slots.push(Slot { id, key, next, busy: true, reads });
|
||||
if registry.slots.len() > MAX_CURSORS {
|
||||
registry.slots.remove(0);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// Ready for the page after `fetched`, which cursor `id` just read, when more rows are waiting in its
|
||||
/// stream; closed otherwise. A cursor released meanwhile is gone from the registry: the caller's
|
||||
/// handle on its channel is the last, so the statement stops.
|
||||
fn finish(&self, id: u64, fetched: &Fetched) {
|
||||
let mut registry = self.registry.lock();
|
||||
let Some(at) = registry.slots.iter().position(|s| s.id == id) else { return };
|
||||
if fetched.3 {
|
||||
let slot = &mut registry.slots[at];
|
||||
slot.next += fetched.1.len();
|
||||
slot.busy = false;
|
||||
} else {
|
||||
registry.slots.remove(at);
|
||||
}
|
||||
}
|
||||
|
||||
fn close(&self, id: u64) {
|
||||
self.registry.lock().slots.retain(|s| s.id != id);
|
||||
}
|
||||
|
||||
/// Closes the cursor of one statement of `target` (its result tab was closed), also when it is reading a page.
|
||||
pub(crate) fn release(&self, key: &Key) {
|
||||
self.registry.lock().slots.retain(|s| s.key != *key);
|
||||
}
|
||||
|
||||
/// Closes the cursors of `target`: it disconnects, or a statement that changes
|
||||
/// data or schema is about to run there.
|
||||
pub(crate) fn release_target(&self, target: &str) {
|
||||
self.registry.lock().slots.retain(|s| s.key.target != target);
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns `held` and the stream of `sql` on it, answering reads until the stream ends,
|
||||
/// nobody asks for [`IDLE`], or it is released (its channel closes).
|
||||
async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Receiver<Read>) {
|
||||
let Some(first) = reads.recv().await else { return held.discard().await };
|
||||
// `$id`: the query naming the server process, `$kill`: how another connection stops it.
|
||||
// Evaluates to whether the connection can go back to its pool (the stream was read to
|
||||
// its end); otherwise it is closed rather than left to be drained.
|
||||
macro_rules! serve {
|
||||
($conn:expr, $id:expr, $kill:expr) => {{
|
||||
let backend = match $id {
|
||||
Some(q) => backend_id!(&mut **$conn, q),
|
||||
None => None,
|
||||
};
|
||||
let mut stream = sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).fetch_many(&mut **$conn);
|
||||
let mut reader = Reader::default();
|
||||
let mut request = Some(first);
|
||||
let mut last = None;
|
||||
let mut reusable = false;
|
||||
while let Some(Read { skip, max, cancel, reply }) = request.take() {
|
||||
let read = tokio::select! {
|
||||
r = drain(&mut stream, &mut reader, skip, max, Cells::Display, |done| done.rows_affected()) => r,
|
||||
() = cancel.cancelled() => Err(IdeError::cancelled()),
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
if let Some(b) = backend {
|
||||
let _ = pool.rows(&$kill(b), 1).await;
|
||||
}
|
||||
let _ = reply.send(Err(IdeError::cancelled()));
|
||||
break;
|
||||
}
|
||||
match read {
|
||||
Ok(fetched) if fetched.3 => {
|
||||
if reply.send(Ok(fetched)).is_err() {
|
||||
break;
|
||||
}
|
||||
request = tokio::time::timeout(IDLE, reads.recv()).await.unwrap_or(None);
|
||||
}
|
||||
Ok(fetched) => {
|
||||
last = Some((reply, fetched));
|
||||
reusable = true;
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = reply.send(Err(e));
|
||||
reusable = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(stream);
|
||||
if let Some((reply, mut fetched)) = last {
|
||||
if fetched.0.is_empty() && looks_like_query(&sql) {
|
||||
fetched.0 = (&mut **$conn)
|
||||
.prepare(sqlx::AssertSqlSafe(sql.clone()).into_sql_str())
|
||||
.await
|
||||
.map(|s| statement_columns(&s))
|
||||
.unwrap_or_default();
|
||||
}
|
||||
let _ = reply.send(Ok(fetched));
|
||||
}
|
||||
reusable
|
||||
}};
|
||||
}
|
||||
let reusable = match &mut held {
|
||||
Held::Sqlite(c) => serve!(c, None::<&str>, |_: String| String::new()),
|
||||
Held::Postgres(c) => {
|
||||
serve!(&mut ***c, Some("SELECT pg_backend_pid()"), |b: String| format!("SELECT pg_cancel_backend({b})"))
|
||||
}
|
||||
Held::Mysql(c) => serve!(&mut ***c, Some("SELECT CONNECTION_ID()"), |b: String| format!("KILL QUERY {b}")),
|
||||
_ => unreachable!("only the sqlx drivers keep cursors"),
|
||||
};
|
||||
if !reusable {
|
||||
held.discard().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::ROWS_PULLED;
|
||||
use crate::{DataSource, DbDriver, DbManager};
|
||||
use ide_core::{CancellationToken, error::ErrorKind};
|
||||
|
||||
const PAGE: usize = 100;
|
||||
const ROWS: usize = 1000;
|
||||
|
||||
/// A SQLite data source `s1` with a table `t` of `ROWS` rows (`id` 1..=ROWS).
|
||||
async fn manager() -> (tempfile::TempDir, DbManager) {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().to_path_buf();
|
||||
std::fs::File::create(root.join("app.db")).unwrap();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
db.save_sources(vec![DataSource {
|
||||
id: "s1".into(),
|
||||
name: "app".into(),
|
||||
driver: DbDriver::Sqlite,
|
||||
file: Some("app.db".into()),
|
||||
..Default::default()
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
db.execute("s1", "CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)", 0, &cancel).await.unwrap();
|
||||
db.execute(
|
||||
"s1",
|
||||
&format!(
|
||||
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < {ROWS}) \
|
||||
INSERT INTO t SELECT i, 'row ' || i FROM n"
|
||||
),
|
||||
0,
|
||||
&cancel,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
(tmp, db)
|
||||
}
|
||||
|
||||
const QUERY: &str = "SELECT id, name FROM t ORDER BY id";
|
||||
|
||||
/// The ids of page `page` of `QUERY`, and whether more rows follow.
|
||||
async fn page(db: &DbManager, statement: &str, page: usize) -> (Vec<i64>, bool) {
|
||||
let r = db.execute_from("s1", statement, page * PAGE, PAGE, &CancellationToken::new(), None).await.unwrap();
|
||||
(r.rows.iter().map(|row| row[0].as_deref().unwrap().parse().unwrap()).collect(), r.has_more)
|
||||
}
|
||||
|
||||
fn ids(page: usize) -> Vec<i64> {
|
||||
((page * PAGE + 1) as i64..=((page + 1) * PAGE) as i64).collect()
|
||||
}
|
||||
|
||||
fn pulled() -> u64 {
|
||||
ROWS_PULLED.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn paging_forward_reads_each_row_once() {
|
||||
let (_tmp, db) = manager().await;
|
||||
let before = pulled();
|
||||
for p in 0..ROWS / PAGE {
|
||||
let (rows, has_more) = page(&db, QUERY, p).await;
|
||||
assert_eq!(rows, ids(p), "page {p}");
|
||||
assert_eq!(has_more, p + 1 < ROWS / PAGE, "page {p} has_more");
|
||||
}
|
||||
// Running the query again for every page reads 1+2+…+10 pages (5500 rows); one pass reads ~1000.
|
||||
assert!(pulled() - before < 2 * ROWS as u64, "read {} rows", pulled() - before);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn jumping_and_going_back_return_the_right_pages() {
|
||||
let (_tmp, db) = manager().await;
|
||||
for p in [5, 6, 2, 3, 9, 0, 1, 7, 7, 8] {
|
||||
assert_eq!(page(&db, QUERY, p).await.0, ids(p), "page {p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reading_a_row_leaves_the_cursor_of_the_pages_alone() {
|
||||
let (_tmp, db) = manager().await;
|
||||
page(&db, QUERY, 1).await;
|
||||
let row = db.read_row("s1", QUERY, 350, &CancellationToken::new(), None).await.unwrap();
|
||||
assert_eq!(row.rows, [[Some("351".to_owned()), Some("row 351".to_owned())]]);
|
||||
assert_eq!(db.cursors.registry.lock().slots.len(), 1);
|
||||
// The next page still continues the cursor: it reads one page, not 200 rows again.
|
||||
let before = pulled();
|
||||
assert_eq!(page(&db, QUERY, 2).await.0, ids(2));
|
||||
assert!(pulled() - before <= PAGE as u64 + 1, "read {} rows", pulled() - before);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pages_past_the_end_are_empty() {
|
||||
let (_tmp, db) = manager().await;
|
||||
page(&db, QUERY, 8).await;
|
||||
let r = db.execute_from("s1", QUERY, 2 * ROWS, PAGE, &CancellationToken::new(), None).await.unwrap();
|
||||
assert!(r.rows.is_empty() && !r.has_more);
|
||||
// The columns of an empty page still come from the statement.
|
||||
assert_eq!(r.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "name"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn another_statement_does_not_continue_a_cursor() {
|
||||
let (_tmp, db) = manager().await;
|
||||
page(&db, QUERY, 1).await;
|
||||
let other = "SELECT id, name FROM t ORDER BY id DESC";
|
||||
let r = db.execute_from("s1", other, 2 * PAGE, PAGE, &CancellationToken::new(), None).await.unwrap();
|
||||
let first: i64 = r.rows[0][0].as_deref().unwrap().parse().unwrap();
|
||||
assert_eq!(first, (ROWS - 2 * PAGE) as i64);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_statement_that_changes_data_closes_the_cursor() {
|
||||
let (_tmp, db) = manager().await;
|
||||
page(&db, QUERY, 1).await;
|
||||
assert_eq!(db.cursors.registry.lock().slots.len(), 1);
|
||||
db.execute("s1", "DELETE FROM t WHERE id = 150", 0, &CancellationToken::new()).await.unwrap();
|
||||
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
|
||||
// The next page shows the change: row 150 is gone, so page 2 starts at 202.
|
||||
assert_eq!(page(&db, QUERY, 2).await.0[0], 202);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn releasing_and_abandoning_cursors_gives_their_connections_back() {
|
||||
let (_tmp, db) = manager().await;
|
||||
// The pool has 4 connections: a leak would starve `execute` after a few rounds.
|
||||
for _ in 0..8 {
|
||||
page(&db, QUERY, 1).await;
|
||||
db.release_result("s1", QUERY, None);
|
||||
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
|
||||
assert_eq!(page(&db, "SELECT count(*) FROM t", 0).await.0, [ROWS as i64]);
|
||||
}
|
||||
// Finishing a result also frees its connection.
|
||||
for _ in 0..8 {
|
||||
for p in 1..ROWS / PAGE {
|
||||
page(&db, QUERY, p).await;
|
||||
}
|
||||
}
|
||||
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_cancelled_page_closes_its_cursor() {
|
||||
let (_tmp, db) = manager().await;
|
||||
page(&db, QUERY, 1).await;
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
let e = db.execute_from("s1", QUERY, 2 * PAGE, PAGE, &cancel, None).await.unwrap_err();
|
||||
assert_eq!(e.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
|
||||
assert_eq!(page(&db, QUERY, 2).await.0, ids(2));
|
||||
}
|
||||
|
||||
/// A closed result tab releases its cursor even when a page is being read from it: the
|
||||
/// cursor is not put back afterwards and its statement stops.
|
||||
#[tokio::test]
|
||||
async fn releasing_a_cursor_in_the_middle_of_a_page_read_closes_it() {
|
||||
use super::{Cursors, Key, Read};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{Notify, mpsc};
|
||||
|
||||
let cursors = Arc::new(Cursors::default());
|
||||
let key = Key::new("s1", QUERY, None);
|
||||
let (reads, mut requests) = mpsc::channel::<Read>(1);
|
||||
cursors.register(key.clone(), 0, reads.clone());
|
||||
let page = || (Vec::new(), vec![vec![Some("1".to_owned())]], None, true, None);
|
||||
cursors.finish(1, &page());
|
||||
drop(reads);
|
||||
|
||||
let in_read = Arc::new(Notify::new());
|
||||
let (release, announced) = (Arc::new(Notify::new()), in_read.clone());
|
||||
let server = tokio::spawn({
|
||||
let release = release.clone();
|
||||
async move {
|
||||
let read = requests.recv().await.unwrap();
|
||||
announced.notify_one();
|
||||
release.notified().await;
|
||||
let _ = read.reply.send(Ok(page()));
|
||||
// The channel closes once nobody holds a handle on it.
|
||||
requests.recv().await.is_none()
|
||||
}
|
||||
});
|
||||
let resumed = tokio::spawn({
|
||||
let (cursors, key) = (cursors.clone(), key.clone());
|
||||
async move { cursors.resume(&key, 1, 1, &CancellationToken::new()).await.is_some() }
|
||||
});
|
||||
in_read.notified().await;
|
||||
cursors.release(&key);
|
||||
release.notify_one();
|
||||
assert!(resumed.await.unwrap(), "the page that was being read is still returned");
|
||||
assert!(cursors.registry.lock().slots.is_empty(), "the released cursor is not put back");
|
||||
assert!(server.await.unwrap(), "the statement's task sees its channel close");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_target_keeps_one_cursor_and_all_are_bounded() {
|
||||
let (_tmp, db) = manager().await;
|
||||
page(&db, QUERY, 1).await;
|
||||
page(&db, "SELECT id, name FROM t WHERE id > 0 ORDER BY id", 1).await;
|
||||
assert_eq!(db.cursors.registry.lock().slots.len(), 1);
|
||||
// The first statement's cursor is gone: its next page is read again, and still right.
|
||||
assert_eq!(page(&db, QUERY, 2).await.0, ids(2));
|
||||
}
|
||||
}
|
||||
@@ -606,7 +606,6 @@ fn decode(data: &[u8], sql: &str, elapsed_ms: f64) -> IdeResult<QueryResult> {
|
||||
affected: (affected >= 0).then_some(affected as f64),
|
||||
elapsed_ms,
|
||||
execution_ms: elapsed_ms,
|
||||
truncated: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ mod watch;
|
||||
pub use watch::SourcesWatch;
|
||||
|
||||
pub use catalog::{CatalogDatabase, CatalogSchema, SourceCatalog};
|
||||
pub use conn::{Held, Pool, QueryResult, ResultColumn, TruncatedCell};
|
||||
pub use conn::{Held, Pool, QueryResult, ResultColumn};
|
||||
pub use history::HistoryEntry;
|
||||
pub use plan::{PlanNode, PlanProperty};
|
||||
pub use source::{
|
||||
@@ -273,8 +273,6 @@ pub struct DbManager {
|
||||
/// Manual-commit data sources, each with the connection of its open
|
||||
/// transaction (taken by the first statement after a commit / rollback).
|
||||
sessions: Mutex<HashMap<String, Session>>,
|
||||
/// Result pages read on from where the previous page stopped, not by running the statement again.
|
||||
cursors: conn::Cursors,
|
||||
/// The data sources as last read from disk, for [`DbManager::reconcile_sources`]
|
||||
/// (`None` until [`DbManager::watch_sources`]).
|
||||
on_disk: Mutex<Option<Vec<DataSource>>>,
|
||||
@@ -434,7 +432,6 @@ impl DbManager {
|
||||
session_passwords: Mutex::default(),
|
||||
on_disk: Mutex::default(),
|
||||
sessions: Mutex::default(),
|
||||
cursors: conn::Cursors::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -978,7 +975,6 @@ impl DbManager {
|
||||
if let Some(s) = session {
|
||||
end_session(&s).await;
|
||||
}
|
||||
self.cursors.release_target(id);
|
||||
let pool = self.pools.lock().remove(id);
|
||||
if let Some(p) = pool {
|
||||
p.close().await;
|
||||
@@ -1576,25 +1572,6 @@ impl DbManager {
|
||||
r
|
||||
}
|
||||
|
||||
/// Row number `row` (from 0) of the result of `statement`, whole: what a page shows cut
|
||||
/// short. It leaves the cursor of the result's pages where it stands, and is not recorded
|
||||
/// in the history (the statement already was).
|
||||
pub async fn read_row(
|
||||
&self,
|
||||
id: &str,
|
||||
statement: &str,
|
||||
row: usize,
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<QueryResult> {
|
||||
self.run_paged(id, statement, row, 1, cancel, schema, false).await
|
||||
}
|
||||
|
||||
/// Closes the cursor that reads the pages of `statement` on `id` (its result tab was closed).
|
||||
pub fn release_result(&self, id: &str, statement: &str, schema: Option<&str>) {
|
||||
self.cursors.release(&conn::CursorKey::new(id, statement, schema));
|
||||
}
|
||||
|
||||
fn remember_statement(&self, id: &str, statement: &str) {
|
||||
let time = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
@@ -1666,44 +1643,12 @@ impl DbManager {
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<QueryResult> {
|
||||
self.run_paged(id, statement, skip, max_rows, cancel, schema, true).await
|
||||
}
|
||||
|
||||
/// `paging`: whether the page may continue a cursor of `statement` (see `conn::cursor`).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn run_paged(
|
||||
&self,
|
||||
id: &str,
|
||||
statement: &str,
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
paging: bool,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let pool = self.pool(id).await?;
|
||||
if let Pool::Jdbc(p) = &*pool {
|
||||
return p.query_in_schema(statement, skip, max_rows, cancel, schema).await;
|
||||
}
|
||||
let session = self.sessions.lock().get(id).cloned();
|
||||
if !conn::cursor_statement(statement) {
|
||||
// A cursor's open statement could keep this one waiting (a lock), and would show data from before it.
|
||||
self.cursors.release_target(id);
|
||||
}
|
||||
if paging && session.is_none() && skip > 0 && pool.keeps_cursors() && conn::cursor_statement(statement) {
|
||||
let key = conn::CursorKey::new(id, statement, schema);
|
||||
let started = std::time::Instant::now();
|
||||
let page = match self.cursors.resume(&key, skip, max_rows, cancel).await {
|
||||
Some(page) => page,
|
||||
None => {
|
||||
let mut held = Held::acquire(&pool).await?;
|
||||
held.apply_context(schema).await?;
|
||||
self.cursors.start(held, pool.clone(), key, skip, max_rows, cancel).await
|
||||
}
|
||||
};
|
||||
return page.map(|fetched| conn::query_result(statement, fetched, started));
|
||||
}
|
||||
let Some(session) = session else {
|
||||
if schema.is_none() {
|
||||
return pool.execute_from(statement, skip, max_rows, cancel).await;
|
||||
|
||||
@@ -283,7 +283,6 @@ mod tests {
|
||||
has_more: false,
|
||||
elapsed_ms: 0.0,
|
||||
execution_ms: 0.0,
|
||||
truncated: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -892,7 +892,6 @@ impl SnowflakePool {
|
||||
has_more,
|
||||
elapsed_ms: started.elapsed().as_secs_f64() * 1000.0,
|
||||
execution_ms,
|
||||
truncated: Vec::new(),
|
||||
})))
|
||||
}
|
||||
|
||||
|
||||
@@ -298,27 +298,3 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
let query = "WITH RECURSIVE n(id) AS (SELECT 1 UNION ALL SELECT id + 1 FROM n WHERE id < 1000) \
|
||||
SELECT id, REPEAT('x', 10) AS pad FROM n ORDER BY id";
|
||||
// Forward, back, and jumping: every page holds its own rows whichever cursor served it.
|
||||
for page in [0, 1, 2, 3, 1, 7, 8, 9, 4, 0] {
|
||||
let r = db.execute_from("m", query, page * 100, 100, &c, None).await?;
|
||||
let ids: Vec<_> = r.rows.iter().map(|row| row[0].clone().unwrap()).collect();
|
||||
let want: Vec<_> = (page * 100 + 1..=page * 100 + 100).map(|n| n.to_string()).collect();
|
||||
assert_eq!(ids, want, "page {page}");
|
||||
assert_eq!(r.has_more, page < 9, "page {page}");
|
||||
}
|
||||
// A pool of 4 connections: cursors that were left open must not exhaust it.
|
||||
for _ in 0..8 {
|
||||
db.execute_from("m", query, 100, 100, &c, None).await?;
|
||||
db.release_result("m", query, None);
|
||||
assert_eq!(db.execute("m", "SELECT 1", 1, &c).await?.rows[0][0].as_deref(), Some("1"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -342,59 +342,3 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> {
|
||||
db.execute("p", "DROP DATABASE oi_restore", 1, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
let query = "SELECT g AS id, repeat('x', 10) AS pad FROM generate_series(1, 1000) g ORDER BY g";
|
||||
// Forward, back, and jumping: every page holds its own rows whichever cursor served it.
|
||||
for page in [0, 1, 2, 3, 1, 7, 8, 9, 4, 0] {
|
||||
let r = db.execute_from("p", query, page * 100, 100, &c, None).await?;
|
||||
let ids: Vec<_> = r.rows.iter().map(|row| row[0].clone().unwrap()).collect();
|
||||
let want: Vec<_> = (page * 100 + 1..=page * 100 + 100).map(|n| n.to_string()).collect();
|
||||
assert_eq!(ids, want, "page {page}");
|
||||
assert_eq!(r.has_more, page < 9, "page {page}");
|
||||
}
|
||||
// A pool of 4 connections: cursors that were left open must not exhaust it.
|
||||
for _ in 0..8 {
|
||||
db.execute_from("p", query, 100, 100, &c, None).await?;
|
||||
db.release_result("p", query, None);
|
||||
assert_eq!(db.execute("p", "SELECT 1", 1, &c).await?.rows[0][0].as_deref(), Some("1"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_a_later_page_stops_its_statement_on_the_server() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let marker = "oi_cursor_cancel_marker";
|
||||
let slow = format!("SELECT g, pg_sleep(0.05) AS {marker} FROM generate_series(1, 100000) g");
|
||||
let cancel = CancellationToken::new();
|
||||
let stop = cancel.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
stop.cancel();
|
||||
});
|
||||
let started = std::time::Instant::now();
|
||||
let e = db.execute_from("p", &slow, 5, 10, &cancel, None).await.unwrap_err();
|
||||
assert_eq!(e.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5));
|
||||
let c = CancellationToken::new();
|
||||
let active = format!(
|
||||
"SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND query LIKE '%{marker}%' \
|
||||
AND query NOT LIKE '%pg_stat_activity%'"
|
||||
);
|
||||
let mut running = 1;
|
||||
for _ in 0..20 {
|
||||
running = db.execute("p", &active, 1, &c).await?.rows[0][0].as_deref().unwrap().parse().unwrap();
|
||||
if running == 0 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
assert_eq!(running, 0, "the cancelled statement still runs on the server");
|
||||
Ok(())
|
||||
}
|
||||
@@ -557,53 +557,6 @@ fn map_layers(layers: Vec<ApiLayer>, now: i64) -> Vec<DockerImageLayer> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Per-volume disk usage (`GET /system/df?type=volume`).
|
||||
pub(crate) fn volume_sizes(ep: &DockerEndpoint, timeout: Duration) -> Option<IdeResult<BTreeMap<String, String>>> {
|
||||
let addr = address(ep)?;
|
||||
Some((|| {
|
||||
let body = check(request(&addr, "GET", "/system/df?type=volume", timeout)?)?;
|
||||
map_volume_sizes(&body)
|
||||
})())
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct ApiDiskUsage {
|
||||
volumes: Option<Vec<ApiVolumeUsage>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct ApiVolumeUsage {
|
||||
name: String,
|
||||
usage_data: Option<ApiVolumeUsageData>,
|
||||
}
|
||||
|
||||
const fn unknown_volume_size() -> i64 {
|
||||
-1
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct ApiVolumeUsageData {
|
||||
#[serde(default = "unknown_volume_size")]
|
||||
size: i64,
|
||||
}
|
||||
|
||||
fn map_volume_sizes(body: &str) -> IdeResult<BTreeMap<String, String>> {
|
||||
let parsed = serde_json::from_str::<ApiDiskUsage>(body)
|
||||
.map_err(|e| IdeError::internal(format!("the Docker daemon's disk usage is not JSON: {e}")))?;
|
||||
Ok(parsed
|
||||
.volumes
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|v| {
|
||||
let size = v.usage_data?.size;
|
||||
(!v.name.is_empty() && size >= 0).then(|| (v.name, human_size(size)))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn unix_now() -> i64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
|
||||
}
|
||||
@@ -1205,15 +1158,6 @@ mod tests {
|
||||
(top.titles, top.processes),
|
||||
(vec!["PID".to_owned(), "CMD".to_owned()], vec![vec!["1".to_owned(), "sh".to_owned()]])
|
||||
);
|
||||
let sizes = map_volume_sizes(
|
||||
r#"{"Volumes":[{"Name":"shop_pgdata","UsageData":{"RefCount":1,"Size":145442}},{"Name":"empty","UsageData":{"RefCount":0,"Size":0}},{"Name":"remote","UsageData":{"RefCount":1,"Size":-1}},{"Name":"missing","UsageData":null}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(sizes.get("shop_pgdata").map(String::as_str), Some("145.442kB"));
|
||||
assert_eq!(sizes.get("empty").map(String::as_str), Some("0B"));
|
||||
assert!(!sizes.contains_key("remote"));
|
||||
assert!(!sizes.contains_key("missing"));
|
||||
assert!(map_volume_sizes(r#"{"Volumes":null}"#).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -315,17 +315,6 @@ pub fn container_stats(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerContain
|
||||
parse_container_stats(&out).ok_or_else(|| IdeError::not_found("no container stats returned"))
|
||||
}
|
||||
|
||||
/// Per-volume disk usage (`docker system df -v --format '{{json .Volumes}}'`).
|
||||
pub fn volume_sizes(ep: &DockerEndpoint) -> IdeResult<std::collections::BTreeMap<String, String>> {
|
||||
if docker_executable().is_none()
|
||||
&& let Some(sizes) = engine::volume_sizes(ep, QUICK)
|
||||
{
|
||||
return sizes;
|
||||
}
|
||||
let out = run(ep, &["system", "df", "-v", "--format", "{{json .Volumes}}"], QUICK)?;
|
||||
Ok(parse_volume_sizes(&out))
|
||||
}
|
||||
|
||||
/// How long log lines collect before they are handed on together.
|
||||
const LOG_BATCH: Duration = Duration::from_millis(30);
|
||||
|
||||
|
||||
@@ -473,33 +473,6 @@ pub fn parse_container_stats(text: &str) -> Option<DockerContainerStats> {
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct RawVolumeUsage {
|
||||
name: String,
|
||||
size: String,
|
||||
}
|
||||
|
||||
/// `docker system df -v --format '{{json .Volumes}}'` volume name → human size.
|
||||
pub fn parse_volume_sizes(text: &str) -> BTreeMap<String, String> {
|
||||
let trimmed = text.trim();
|
||||
let items: Vec<RawVolumeUsage> = if trimmed.is_empty() || trimmed == "null" {
|
||||
Vec::new()
|
||||
} else if let Ok(parsed) = serde_json::from_str::<Option<Vec<RawVolumeUsage>>>(trimmed) {
|
||||
parsed.unwrap_or_default()
|
||||
} else {
|
||||
lines::<RawVolumeUsage>(text).collect()
|
||||
};
|
||||
items
|
||||
.into_iter()
|
||||
.filter(|v| {
|
||||
let size = v.size.trim();
|
||||
!v.name.is_empty() && !size.is_empty() && !size.eq_ignore_ascii_case("n/a")
|
||||
})
|
||||
.map(|v| (v.name, v.size.trim().to_owned()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct RawVersion {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use ide_docker::{
|
||||
PS_FORMAT, parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images,
|
||||
parse_networks, parse_volume_sizes, parse_volumes,
|
||||
parse_networks, parse_volumes,
|
||||
};
|
||||
|
||||
const PS: &str = include_str!("fixtures/ps.jsonl");
|
||||
@@ -113,12 +113,4 @@ fn image_history_top_and_stats() {
|
||||
assert_eq!(stats.net_io, "12kB / 8kB");
|
||||
assert_eq!(stats.block_io, "1.2MB / 0B");
|
||||
assert_eq!(stats.pids, "14");
|
||||
|
||||
let df_volumes = r#"[{"Availability":"N/A","Driver":"local","Links":"4","Mountpoint":"/var/lib/docker/volumes/selfhost_runner-persist/_data","Name":"selfhost_runner-persist","Scope":"local","Size":"145.4kB"},{"Name":"unused_anon","Size":"0B"},{"Name":"remote_nfs","Size":"N/A"}]"#;
|
||||
let volume_sizes = parse_volume_sizes(df_volumes);
|
||||
assert_eq!(volume_sizes.get("selfhost_runner-persist").map(String::as_str), Some("145.4kB"));
|
||||
assert_eq!(volume_sizes.get("unused_anon").map(String::as_str), Some("0B"));
|
||||
assert!(!volume_sizes.contains_key("remote_nfs"));
|
||||
assert!(parse_volume_sizes("null\n").is_empty());
|
||||
assert!(parse_volume_sizes("").is_empty());
|
||||
}
|
||||
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "plugin.toml";
|
||||
/// The plugin API (engine) version this host implements.
|
||||
pub const ENGINE_VERSION: &str = "1.16.0";
|
||||
pub const ENGINE_VERSION: &str = "1.15.0";
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
pub const LEGACY_API: &str = "0.1";
|
||||
/// Marketplace categories, in the order they are shown.
|
||||
|
||||
@@ -514,7 +514,6 @@ fn cmd_keygen(args: &[String]) -> Result<(), String> {
|
||||
let mut seed = [0u8; 32];
|
||||
getrandom::fill(&mut seed).map_err(|e| format!("random: {e}"))?;
|
||||
let key = PublisherKey::from_seed(seed);
|
||||
create_parent(Path::new(file))?;
|
||||
std::fs::write(file, key.seed_base64()).map_err(|e| format!("{file}: {e}"))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
@@ -578,8 +577,7 @@ fn cmd_pack(args: &[String]) -> Result<(), String> {
|
||||
let out = a.value("out").map(PathBuf::from).unwrap_or_else(|| {
|
||||
PathBuf::from(format!("{}-{}.{}", manifest.id, manifest.version, package::PACKAGE_EXTENSION))
|
||||
});
|
||||
create_parent(&out)?;
|
||||
package::pack(&dir, &files, &out, signature.as_ref()).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
package::pack(&dir, &files, &out, signature.as_ref())?;
|
||||
let size = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);
|
||||
let signed = signature.as_ref().map_or("unsigned".to_owned(), |s| format!("signed by {}", s.publisher));
|
||||
println!("-> {} ({}, {signed})", out.display(), human_size(size));
|
||||
@@ -766,17 +764,8 @@ fn cmd_merge(args: &[String]) -> Result<(), String> {
|
||||
write_index(&index, Path::new(out))
|
||||
}
|
||||
|
||||
/// Creates the directories an output file goes into.
|
||||
fn create_parent(file: &Path) -> Result<(), String> {
|
||||
match file.parent() {
|
||||
Some(parent) => std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display())),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_index(index: &Index, out: &Path) -> Result<(), String> {
|
||||
let json = serde_json::to_string_pretty(index).map_err(|e| e.to_string())?;
|
||||
create_parent(out)?;
|
||||
std::fs::write(out, json).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
println!("-> {} ({} plugins)", out.display(), index.plugins.len());
|
||||
Ok(())
|
||||
@@ -867,48 +856,6 @@ mod tests {
|
||||
cmd_pack(&args).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_files_go_into_missing_directories() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let t = tmp.path();
|
||||
let key = t.join("config/openidea/acme.key");
|
||||
cmd_keygen(&strings(&[key.to_str().unwrap()])).unwrap();
|
||||
assert!(read_key(key.to_str().unwrap()).is_ok());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(std::fs::metadata(&key).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
let key = key.to_string_lossy().into_owned();
|
||||
// `signed_theme` creates `out` itself, so pack into a directory it doesn't know about.
|
||||
signed_theme(t, "acme.night", "acme", &key, &t.join("staging"));
|
||||
let package = t.join("dist/v1/acme.night.oiplugin");
|
||||
let src = t.join("src/acme.night-0.1.0");
|
||||
cmd_pack(&strings(&[
|
||||
src.to_str().unwrap(),
|
||||
"--key",
|
||||
&key,
|
||||
"--publisher",
|
||||
"acme",
|
||||
"--out",
|
||||
package.to_str().unwrap(),
|
||||
]))
|
||||
.unwrap();
|
||||
assert!(package.is_file());
|
||||
let index = t.join("site/market/index.json");
|
||||
cmd_index(&strings(&[
|
||||
t.join("dist/v1").to_str().unwrap(),
|
||||
"--publisher",
|
||||
"acme",
|
||||
"--key",
|
||||
&key,
|
||||
"--out",
|
||||
index.to_str().unwrap(),
|
||||
]))
|
||||
.unwrap();
|
||||
assert!(index.is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_release_keeps_the_versions_older_ides_need() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
+19
-135
@@ -384,12 +384,9 @@ pub async fn db_execute(
|
||||
#[default] skip: u32,
|
||||
max_rows: u32,
|
||||
schema: Option<String>,
|
||||
// Cells longer than this many UTF-16 units come back cut (`truncated` lists them); none: whole.
|
||||
#[default] cell_limit: Option<u32>,
|
||||
) -> IdeResult<Vec<StatementOutcome>> {
|
||||
let mut outcomes = Vec::new();
|
||||
let limits = Limits { skip, max_rows, cell_limit };
|
||||
execute_statements(host, window, request, &id, statements, limits, schema.as_deref(), |event| {
|
||||
execute_statements(host, window, request, &id, statements, skip, max_rows, schema.as_deref(), |event| {
|
||||
if let ExecutionEvent::Completed { outcome, .. } = event {
|
||||
outcomes.push(outcome);
|
||||
}
|
||||
@@ -399,38 +396,6 @@ pub async fn db_execute(
|
||||
Ok(outcomes)
|
||||
}
|
||||
|
||||
/// Row `row` (from 0) of the result of `statement`, whole: what a page of a run with a
|
||||
/// `cell_limit` shows cut short.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_result_row(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
id: String,
|
||||
statement: SqlStatement,
|
||||
row: u32,
|
||||
schema: Option<String>,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let db = host.project(window)?.db.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = db.read_row(&id, &statement.text, row as usize, &cancel, schema.as_deref()).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Closes what the pages of a result keep open on the server (its result tab was closed).
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_release_result(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
statement: String,
|
||||
schema: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
host.project(window)?.db.release_result(&id, &statement, schema.as_deref());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_execute_stream(
|
||||
@@ -441,11 +406,9 @@ pub async fn db_execute_stream(
|
||||
statements: Vec<SqlStatement>,
|
||||
max_rows: u32,
|
||||
schema: Option<String>,
|
||||
#[default] cell_limit: Option<u32>,
|
||||
on_progress: Channel<ExecutionEvent>,
|
||||
) -> IdeResult<()> {
|
||||
let limits = Limits { skip: 0, max_rows, cell_limit };
|
||||
let result = execute_statements(host, window, request, &id, statements, limits, schema.as_deref(), |event| {
|
||||
let result = execute_statements(host, window, request, &id, statements, 0, max_rows, schema.as_deref(), |event| {
|
||||
on_progress.send(event)
|
||||
})
|
||||
.await;
|
||||
@@ -453,14 +416,6 @@ pub async fn db_execute_stream(
|
||||
on_progress.send(ExecutionEvent::Done { error: result.err() })
|
||||
}
|
||||
|
||||
/// What a run of statements returns of each result.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Limits {
|
||||
skip: u32,
|
||||
max_rows: u32,
|
||||
cell_limit: Option<u32>,
|
||||
}
|
||||
|
||||
/// Runs in order on one request and stops on cancellation or the first error.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn execute_statements(
|
||||
@@ -469,7 +424,8 @@ async fn execute_statements(
|
||||
request: RequestId,
|
||||
id: &str,
|
||||
statements: Vec<SqlStatement>,
|
||||
Limits { skip, max_rows, cell_limit }: Limits,
|
||||
skip: u32,
|
||||
max_rows: u32,
|
||||
schema: Option<&str>,
|
||||
mut emit: impl FnMut(ExecutionEvent) -> IdeResult<()>,
|
||||
) -> IdeResult<()> {
|
||||
@@ -485,12 +441,7 @@ async fn execute_statements(
|
||||
.execute_from(id, &statement.text, skip as usize, max_rows.max(1) as usize, &cancel, schema)
|
||||
.await
|
||||
{
|
||||
Ok(mut result) => {
|
||||
if let Some(limit) = cell_limit {
|
||||
result.cap_cells(limit as usize);
|
||||
}
|
||||
StatementOutcome { statement, result: Some(result), error: None }
|
||||
}
|
||||
Ok(result) => StatementOutcome { statement, result: Some(result), error: None },
|
||||
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => return Err(e),
|
||||
// The UI may retry a login failure only before any statement has completed.
|
||||
Err(e) if e.kind == ide_core::error::ErrorKind::PermissionDenied && index == 0 => return Err(e),
|
||||
@@ -669,8 +620,6 @@ ide_command::domain!(
|
||||
db_save_jdbc_driver,
|
||||
db_remove_jdbc_driver,
|
||||
db_object_ddl,
|
||||
db_release_result,
|
||||
db_result_row,
|
||||
db_remove_history,
|
||||
db_retain_catalog,
|
||||
db_save_source_visibility,
|
||||
@@ -698,8 +647,9 @@ mod tests {
|
||||
use crate::HostConfig;
|
||||
use ide_db::DbDriver;
|
||||
|
||||
/// A trusted project with an empty SQLite data source `test`.
|
||||
async fn host_with_sqlite(temp: &tempfile::TempDir) -> Host {
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_reporting_error_stops_the_batch_and_releases_the_request() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
@@ -707,44 +657,28 @@ mod tests {
|
||||
let window = "main";
|
||||
host.open_project(window, &root).unwrap();
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
let id = "test";
|
||||
let file = root.join("test.sqlite");
|
||||
std::fs::File::create(&file).unwrap();
|
||||
db_save_sources(
|
||||
&host,
|
||||
window,
|
||||
vec![DataSource { id: "test".into(), name: "test".into(), file: Some(file.into()), ..Default::default() }],
|
||||
vec![DataSource { id: id.into(), name: id.into(), file: Some(file.into()), ..Default::default() }],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
host
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_reporting_error_stops_the_batch_and_releases_the_request() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_with_sqlite(&temp).await;
|
||||
let (window, id) = ("main", "test");
|
||||
let statements =
|
||||
ide_db::split::split("CREATE TABLE items (n INTEGER); INSERT INTO items VALUES (1);", DbDriver::Sqlite);
|
||||
let request = RequestId(1);
|
||||
let error = execute_statements(
|
||||
&host,
|
||||
window,
|
||||
request,
|
||||
id,
|
||||
statements,
|
||||
Limits { skip: 0, max_rows: 10, cell_limit: None },
|
||||
None,
|
||||
|event| match event {
|
||||
ExecutionEvent::Started { index: 0 } => Ok(()),
|
||||
ExecutionEvent::Completed { index: 0, outcome } => {
|
||||
assert!(outcome.error.is_none(), "{:?}", outcome.error);
|
||||
Err(IdeError::internal("cannot report result"))
|
||||
}
|
||||
_ => panic!("the failed callback must stop execution"),
|
||||
},
|
||||
)
|
||||
let error = execute_statements(&host, window, request, id, statements, 0, 10, None, |event| match event {
|
||||
ExecutionEvent::Started { index: 0 } => Ok(()),
|
||||
ExecutionEvent::Completed { index: 0, outcome } => {
|
||||
assert!(outcome.error.is_none(), "{:?}", outcome.error);
|
||||
Err(IdeError::internal("cannot report result"))
|
||||
}
|
||||
_ => panic!("the failed callback must stop execution"),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.message, "cannot report result");
|
||||
@@ -757,57 +691,7 @@ mod tests {
|
||||
"SELECT 99 AS n UNION ALL SELECT count(*) FROM items ORDER BY n DESC",
|
||||
DbDriver::Sqlite,
|
||||
);
|
||||
let outcomes = db_execute(&host, window, RequestId(2), id.into(), query, 1, 10, None, None).await.unwrap();
|
||||
let outcomes = db_execute(&host, window, RequestId(2), id.into(), query, 1, 10, None).await.unwrap();
|
||||
assert_eq!(outcomes[0].result.as_ref().unwrap().rows, vec![vec![Some("0".into())]]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_page_with_a_cell_limit_carries_prefixes_and_each_whole_value_is_read_on_demand() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_with_sqlite(&temp).await;
|
||||
let (window, id) = ("main", "test");
|
||||
let wide = "😀é".repeat(50_000);
|
||||
let setup = ide_db::split::split(
|
||||
&format!(
|
||||
"CREATE TABLE docs (n INTEGER, body TEXT); INSERT INTO docs VALUES (1, 'tiny'), (2, '{wide}'), (3, '{wide}');"
|
||||
),
|
||||
DbDriver::Sqlite,
|
||||
);
|
||||
db_execute(&host, window, RequestId(1), id.into(), setup, 0, 10, None, None).await.unwrap();
|
||||
|
||||
let query = || ide_db::split::split("SELECT n, body FROM docs ORDER BY n", DbDriver::Sqlite);
|
||||
let capped = db_execute(&host, window, RequestId(2), id.into(), query(), 0, 10, None, Some(100)).await.unwrap();
|
||||
let page = capped[0].result.as_ref().unwrap();
|
||||
// The page no longer carries more than the limit of each cell.
|
||||
let size: usize = page.rows.iter().flatten().flatten().map(String::len).sum();
|
||||
assert!(size < 1_000, "{size} bytes");
|
||||
assert_eq!(page.rows[0][1].as_deref(), Some("tiny"));
|
||||
let whole = 150_000;
|
||||
// What the client checks a value it reads again against: FNV-1a over its UTF-16 units.
|
||||
let hash =
|
||||
wide.encode_utf16().fold(0x811c_9dc5_u32, |hash, unit| (hash ^ u32::from(unit)).wrapping_mul(0x0100_0193));
|
||||
assert_eq!(
|
||||
page.truncated,
|
||||
[
|
||||
ide_db::TruncatedCell { row: 1, column: 1, length: whole, hash },
|
||||
ide_db::TruncatedCell { row: 2, column: 1, length: whole, hash }
|
||||
]
|
||||
);
|
||||
|
||||
// The row of a cut cell, read alone and without a limit, is the whole value.
|
||||
for row in [1, 2] {
|
||||
let statement = query().remove(0);
|
||||
let one = db_result_row(&host, window, RequestId(3), id.into(), statement, row, None).await.unwrap();
|
||||
assert!(one.truncated.is_empty());
|
||||
let full = one.rows[0][1].clone().unwrap();
|
||||
assert_eq!(full.encode_utf16().count(), whole as usize);
|
||||
assert!(full.starts_with(page.rows[row as usize][1].as_deref().unwrap()));
|
||||
}
|
||||
|
||||
// Without a limit nothing is cut or listed.
|
||||
let all = db_execute(&host, window, RequestId(4), id.into(), query(), 0, 10, None, None).await.unwrap();
|
||||
let all = all[0].result.as_ref().unwrap();
|
||||
assert!(all.truncated.is_empty());
|
||||
assert_eq!(all.rows[2][1].as_deref(), Some(wide.as_str()));
|
||||
}
|
||||
}
|
||||
@@ -70,121 +70,27 @@ pub async fn lsp_completion(
|
||||
pos: Pos,
|
||||
trigger: Option<String>,
|
||||
) -> IdeResult<CompletionList> {
|
||||
let project = host.project(window)?;
|
||||
// Typing on in a word whose list only some plugins marked incomplete: ask those plugins
|
||||
// again and keep the rest (the language server's list, the other plugins' items).
|
||||
let word = project.documents.snapshot(doc).ok().and_then(|snap| CompletionWord::at(&snap.text, pos));
|
||||
let resumed = match (&word, trigger.is_none()) {
|
||||
(Some(word), true) => project
|
||||
.completion_session
|
||||
.lock()
|
||||
.as_ref()
|
||||
.filter(|s| s.resumes(doc, word))
|
||||
.map(|s| (s.kept.clone(), s.incomplete.clone())),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((kept, only)) = resumed {
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Completion) else {
|
||||
*project.completion_session.lock() = None;
|
||||
return Ok(CompletionList { is_incomplete: false, items: kept });
|
||||
};
|
||||
let asked = only.clone();
|
||||
let answer = plugin_call(move || plugins.provide_completion_for_editor(&d, pos, None, Some(&asked)))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let mut items = kept;
|
||||
items.extend(answer.items.into_iter().map(|(_, item)| plugin_completion(item)));
|
||||
let mut session = project.completion_session.lock();
|
||||
if let Some(s) = session.as_mut().filter(|s| s.incomplete == only) {
|
||||
s.incomplete = answer.incomplete.clone();
|
||||
}
|
||||
return Ok(CompletionList { is_incomplete: !answer.incomplete.is_empty(), items });
|
||||
}
|
||||
*project.completion_session.lock() = None;
|
||||
|
||||
let lsp = project.lsp.clone();
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let (target, cancel) = begin_position_request(host, window, request, doc, pos).await?;
|
||||
let result = lsp.completion(target, pos, trigger.clone(), cancel).await;
|
||||
host.end_request(request);
|
||||
// Plugin providers (`[[contributes.providers]]`) add theirs.
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Completion) else { return result };
|
||||
let answer = plugin_call(move || plugins.provide_completion_for_editor(&d, pos, trigger.as_deref(), None))
|
||||
let (covered, items) = plugin_call(move || plugins.provide_completion_for_editor(&d, pos, trigger.as_deref()))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
if answer.items.is_empty() && answer.incomplete.is_empty() {
|
||||
return if answer.covered {
|
||||
if items.is_empty() {
|
||||
return if covered {
|
||||
Ok(result.unwrap_or(CompletionList { is_incomplete: true, items: Vec::new() }))
|
||||
} else {
|
||||
result
|
||||
};
|
||||
}
|
||||
let mut list = result.unwrap_or(CompletionList { is_incomplete: false, items: Vec::new() });
|
||||
let server_complete = !list.is_incomplete;
|
||||
let mut fresh = Vec::new();
|
||||
for (id, item) in answer.items {
|
||||
let item = plugin_completion(item);
|
||||
if answer.incomplete.contains(&id) { fresh.push(item) } else { list.items.push(item) }
|
||||
}
|
||||
if !answer.incomplete.is_empty() {
|
||||
// Only a complete server list can be kept; else typing on asks everyone, as before.
|
||||
if let (true, Some(word)) = (server_complete, word) {
|
||||
*project.completion_session.lock() =
|
||||
Some(CompletionSession { doc, word, kept: list.items.clone(), incomplete: answer.incomplete });
|
||||
}
|
||||
list.is_incomplete = true;
|
||||
}
|
||||
list.items.extend(fresh);
|
||||
list.items.extend(items.into_iter().map(|(_, item)| plugin_completion(item)));
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
/// The word completion is asked in: its line and the line's text before the word.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct CompletionWord {
|
||||
line: u32,
|
||||
before: String,
|
||||
}
|
||||
|
||||
impl CompletionWord {
|
||||
/// The identifier ending at `pos` in `text` (possibly empty, right after a `.`).
|
||||
fn at(text: &str, pos: Pos) -> Option<Self> {
|
||||
let line = text.split('\n').nth(pos.line as usize)?.trim_end_matches('\r');
|
||||
let mut col = 0u32;
|
||||
let mut end = line.len();
|
||||
for (i, c) in line.char_indices() {
|
||||
if col >= pos.col {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
col += c.len_utf16() as u32;
|
||||
}
|
||||
if col < pos.col {
|
||||
return None;
|
||||
}
|
||||
let head = &line[..end];
|
||||
let word_len: usize =
|
||||
head.chars().rev().take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '$').map(char::len_utf8).sum();
|
||||
let before = &head[..head.len() - word_len];
|
||||
Some(Self { line: pos.line, before: before.to_owned() })
|
||||
}
|
||||
}
|
||||
|
||||
/// A completion whose list some plugins marked incomplete (API 1.16): while the user types on in
|
||||
/// the same word, only those plugins are asked again.
|
||||
pub(crate) struct CompletionSession {
|
||||
doc: DocId,
|
||||
word: CompletionWord,
|
||||
/// The language server's list (complete) and the other plugins' items.
|
||||
kept: Vec<CompletionItem>,
|
||||
/// The plugins asked again.
|
||||
incomplete: std::collections::BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl CompletionSession {
|
||||
fn resumes(&self, doc: DocId, word: &CompletionWord) -> bool {
|
||||
self.doc == doc && &self.word == word && !self.incomplete.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// The plugin host and the document, when some plugin provides `kind`.
|
||||
pub(crate) fn plugin_providers(
|
||||
host: &Host,
|
||||
@@ -2318,25 +2224,6 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn a_completion_word_is_its_line_and_what_precedes_it() {
|
||||
use super::*;
|
||||
let word = |text: &str, line: u32, col: u32| CompletionWord::at(text, Pos::new(line, col));
|
||||
let before = |text: &str, line: u32, col: u32| word(text, line, col).map(|w| w.before);
|
||||
assert_eq!(before("Book.findByTitle", 0, 16).as_deref(), Some("Book."));
|
||||
// Typing on in the word, or deleting back into it, is the same word.
|
||||
assert_eq!(word("Book.findByTitleA", 0, 17), word("Book.findBy", 0, 11));
|
||||
assert_eq!(word("Book.findBy", 0, 5), word("Book.findBy", 0, 11));
|
||||
// Another line, or a change before the word, is another one.
|
||||
assert_ne!(word("a\nBook.find", 1, 9), word("Book.find\na", 0, 9));
|
||||
assert_ne!(word("Book.find", 0, 9), word("Look.find", 0, 9));
|
||||
// Columns count UTF-16 units; CRLF line ends don't count.
|
||||
assert_eq!(before("😀 x.ab", 0, 7).as_deref(), Some("😀 x."));
|
||||
assert_eq!(before("x.ab\r\nnext", 0, 4).as_deref(), Some("x."));
|
||||
assert_eq!(word("short", 0, 9), None);
|
||||
assert_eq!(word("short", 3, 0), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn python_optimize_imports_without_a_server_runs_ruff_on_the_unsaved_text() {
|
||||
|
||||
@@ -265,21 +265,9 @@ use ide_plugin::{
|
||||
ActorError, CallError, CodeAction, CompletionItem, InlineSuggestion, LineMarker, Location, Pending, PluginHover,
|
||||
PluginInlayHint, ProviderDocument, Runtime, SemanticToken,
|
||||
};
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Weak;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// What the plugins answered for completion in the editor.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct EditorCompletion {
|
||||
/// Some plugin completes in the document, so an empty answer still asks again on typing.
|
||||
pub covered: bool,
|
||||
/// Items with the id of the plugin that gave them.
|
||||
pub items: Vec<(String, CompletionItem)>,
|
||||
/// Plugins that marked their items incomplete (API 1.16 `completion-list-provider`).
|
||||
pub incomplete: BTreeSet<String>,
|
||||
}
|
||||
|
||||
/// How long a superseded inline completion may take to return after its
|
||||
/// request was cancelled before it is interrupted.
|
||||
const CANCEL_GRACE: Duration = Duration::from_millis(250);
|
||||
@@ -344,21 +332,13 @@ impl PluginHost {
|
||||
doc: &ProviderDocument,
|
||||
owner: Option<&str>,
|
||||
f: impl FnOnce(&mut Runtime, Duration) -> Result<R, CallError> + Clone + Send + 'static,
|
||||
) -> Vec<(Arc<LoadedPlugin>, R)> {
|
||||
self.document_calls_where(kind, doc, |id| owner.is_none_or(|o| o == id), f)
|
||||
}
|
||||
/// [`Self::document_calls`] for the plugins whose id `keep` accepts.
|
||||
pub(super) fn document_calls_where<R: Send + 'static>(
|
||||
&self,
|
||||
kind: ProviderKind,
|
||||
doc: &ProviderDocument,
|
||||
keep: impl Fn(&str) -> bool,
|
||||
f: impl FnOnce(&mut Runtime, Duration) -> Result<R, CallError> + Clone + Send + 'static,
|
||||
) -> Vec<(Arc<LoadedPlugin>, R)> {
|
||||
let plugins = self
|
||||
.provider_plugins(kind, &doc.language)
|
||||
.into_iter()
|
||||
.filter(|p| p.dev_root.as_ref().is_none_or(|r| doc.path.starts_with(r)) && keep(p.id()))
|
||||
.filter(|p| {
|
||||
p.dev_root.as_ref().is_none_or(|r| doc.path.starts_with(r)) && owner.is_none_or(|id| p.id() == id)
|
||||
})
|
||||
.collect();
|
||||
self.edit_calls_plugins(plugins, f)
|
||||
}
|
||||
@@ -433,48 +413,41 @@ impl PluginHost {
|
||||
at: ide_core::Pos,
|
||||
trigger: Option<&str>,
|
||||
) -> Vec<(String, CompletionItem)> {
|
||||
self.provide_completion_for_editor(doc, at, trigger, None).items
|
||||
self.provide_completion_for_editor(doc, at, trigger).1
|
||||
}
|
||||
|
||||
/// Completion from the plugins for the editor; with `only`, from those plugins alone (the ones
|
||||
/// whose list was incomplete, asked again while the user types on).
|
||||
pub(crate) fn provide_completion_for_editor(
|
||||
&self,
|
||||
doc: &ProviderDocument,
|
||||
at: ide_core::Pos,
|
||||
trigger: Option<&str>,
|
||||
only: Option<&BTreeSet<String>>,
|
||||
) -> EditorCompletion {
|
||||
) -> (bool, Vec<(String, CompletionItem)>) {
|
||||
// An injection-capable outer document (e.g. SQL embedded in text) may complete at other
|
||||
// positions even when `at` is outside an injection, so avoid marking document-wide backoff.
|
||||
let mut covered = self.has_document_providers(ProviderKind::Injections, doc);
|
||||
let mut incomplete = BTreeSet::new();
|
||||
let mut items = Vec::new();
|
||||
for (doc, bounds) in self.feature_documents(doc, Some(at)) {
|
||||
if self.has_document_providers(ProviderKind::Completion, &doc) {
|
||||
covered = true;
|
||||
}
|
||||
let (d, t) = (Arc::new(doc.clone()), trigger.map(str::to_owned));
|
||||
let answers = self.document_calls_where(
|
||||
ProviderKind::Completion,
|
||||
&doc,
|
||||
|id| only.is_none_or(|ids| ids.contains(id)),
|
||||
move |rt, timeout| rt.provide_completion_list(&d, at, t.as_deref(), timeout),
|
||||
);
|
||||
for (p, (list, more)) in answers {
|
||||
if more {
|
||||
incomplete.insert(p.id().to_owned());
|
||||
let items = self
|
||||
.feature_documents(doc, Some(at))
|
||||
.into_iter()
|
||||
.flat_map(|(doc, bounds)| {
|
||||
if self.has_document_providers(ProviderKind::Completion, &doc) {
|
||||
covered = true;
|
||||
}
|
||||
items.extend(list.into_iter().filter_map(|mut i| {
|
||||
let (d, t) = (Arc::new(doc.clone()), trigger.map(str::to_owned));
|
||||
self.document_calls(ProviderKind::Completion, &doc, move |rt, timeout| {
|
||||
rt.provide_completion(&d, at, t.as_deref(), timeout)
|
||||
})
|
||||
.into_iter()
|
||||
.flat_map(|(p, items)| items.into_iter().map(move |i| (p.id().to_owned(), i)))
|
||||
.filter_map(move |(p, mut i)| {
|
||||
if i.replace.is_some_and(|r| !bounds.contains(r)) {
|
||||
return None;
|
||||
}
|
||||
i.additional_edits.retain(|e| bounds.contains(e.range));
|
||||
Some((p.id().to_owned(), i))
|
||||
}));
|
||||
}
|
||||
}
|
||||
EditorCompletion { covered, items, incomplete }
|
||||
Some((p, i))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
(covered, items)
|
||||
}
|
||||
|
||||
pub fn provide_code_actions(
|
||||
|
||||
@@ -55,8 +55,6 @@ pub struct Project {
|
||||
pub(crate) java_launches: crate::ops::java::cache::Sessions,
|
||||
/// Reasons this window was already told why Kotlin is debugged with kotlin-debug-adapter.
|
||||
pub(crate) kotlin_debug_notices: Mutex<HashSet<&'static str>>,
|
||||
/// The completion only some plugins asked to complete again ([`crate::ops::lsp::lsp_completion`]).
|
||||
pub(crate) completion_session: Mutex<Option<crate::ops::lsp::CompletionSession>>,
|
||||
/// Database tool window: data sources and their connections.
|
||||
pub db: Arc<ide_db::DbManager>,
|
||||
/// HTTP Client responses (IDEA's `.idea/httpRequests`), in the app data dir.
|
||||
@@ -664,7 +662,6 @@ impl Host {
|
||||
cache_dir: self.local_data_dir.join("cache").join(&project_key),
|
||||
java_launches: Default::default(),
|
||||
kotlin_debug_notices: Mutex::default(),
|
||||
completion_session: Mutex::default(),
|
||||
db,
|
||||
http_history,
|
||||
agents,
|
||||
@@ -913,7 +910,6 @@ impl Host {
|
||||
cache_dir: self.local_data_dir.join("cache").join(&project_key),
|
||||
java_launches: Default::default(),
|
||||
kotlin_debug_notices: Mutex::default(),
|
||||
completion_session: Mutex::default(),
|
||||
db,
|
||||
http_history,
|
||||
agents,
|
||||
|
||||
@@ -28,9 +28,7 @@ use std::pin::Pin;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
/// 3: binary arguments (`IpcBytes`) are base64 strings, not arrays of numbers.
|
||||
/// 4: a running tool's output arrives as `AgentEvent::ToolOutput` appends; a client that
|
||||
/// doesn't know the event would show stale output.
|
||||
pub const PROTOCOL_VERSION: u32 = 4;
|
||||
pub const PROTOCOL_VERSION: u32 = 3;
|
||||
pub const SESSION_REPLACED: &str = "session_replaced";
|
||||
pub const SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(90);
|
||||
|
||||
|
||||
@@ -128,9 +128,7 @@ struct Smoke {
|
||||
}
|
||||
|
||||
fn fixture_dir(name: &str) -> PathBuf {
|
||||
let manifest_dir =
|
||||
std::env::var_os("CARGO_MANIFEST_DIR").map_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")), PathBuf::from);
|
||||
manifest_dir.join("../../fixtures").join(name)
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures").join(name)
|
||||
}
|
||||
|
||||
fn copy_dir(from: &Path, to: &Path) {
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
//! API 1.16 `completion-list-provider`: a plugin marks its completion incomplete, and typing on
|
||||
//! in the same word asks that plugin again while the language server's list is kept.
|
||||
mod common;
|
||||
|
||||
use ide_core::{ChangeSet, Pos, RequestId, TextChange};
|
||||
use ide_host::plugins::{Consent, HostWorkspace, PluginHost, set_editor_providers};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use ide_jsonrpc::{Handler, Peer};
|
||||
use ide_plugin::{Limits, ProviderDocument};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Value, json};
|
||||
use std::{path::Path, sync::Arc, time::Duration};
|
||||
|
||||
fn fixture() -> std::path::PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/completion-list")
|
||||
}
|
||||
|
||||
fn plugins(base: &Path) -> Arc<PluginHost> {
|
||||
let p = Arc::new(
|
||||
PluginHost::new(
|
||||
base.join("plugins"),
|
||||
Arc::new(|_: Option<&str>, _| {}),
|
||||
Limits { edit_soft: Duration::from_secs(3), edit_hard: Duration::from_secs(5), ..Default::default() },
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
p.install_from_dir(&fixture(), &Consent::all()).unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_export_replaces_providers_completion_and_carries_the_flag() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let p = plugins(tmp.path());
|
||||
let doc = |text: &str| ProviderDocument {
|
||||
path: tmp.path().join("a.txt"),
|
||||
language: "text".into(),
|
||||
version: 1,
|
||||
text: text.into(),
|
||||
};
|
||||
// `completion` ("legacy") is not called once `completion-list-provider` is exported.
|
||||
let items = p.provide_completion(&doc("Book.findByTitleAnd"), Pos::new(0, 19), None);
|
||||
let labels: Vec<_> = items.iter().map(|(_, i)| i.label.as_str()).collect();
|
||||
assert_eq!(labels, ["findByTitleAndTitle", "findByTitleAndAuthor"]);
|
||||
}
|
||||
|
||||
/// A language server for plain text that counts its completion requests.
|
||||
#[derive(Default)]
|
||||
struct Server {
|
||||
completions: Mutex<usize>,
|
||||
}
|
||||
|
||||
impl Handler for Server {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
fn on_request(&self, method: &str, _: Value) -> Result<Value, (i64, String)> {
|
||||
Ok(match method {
|
||||
"initialize" => {
|
||||
json!({"capabilities": {"textDocumentSync": {"openClose": true, "change": 1}, "completionProvider": {}}})
|
||||
}
|
||||
"textDocument/completion" => {
|
||||
*self.completions.lock() += 1;
|
||||
json!({"isIncomplete": false, "items": [{"label": "server-item"}]})
|
||||
}
|
||||
_ => Value::Null,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn typing_on_asks_only_the_plugins_that_marked_their_list_incomplete() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let host =
|
||||
Arc::new(Host::new(HostConfig { local_data_dir: tmp.path().join("local"), ..common::host_config(tmp.path()) }));
|
||||
host.open_project("main", &root).unwrap();
|
||||
// Language servers start only in trusted projects.
|
||||
ops::project::project_trust_set(&host, root.clone(), true, false).await.unwrap();
|
||||
let p = plugins(tmp.path());
|
||||
p.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host)))));
|
||||
set_editor_providers(Some(&p));
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = Arc::new(Server::default());
|
||||
let peers = Arc::new(Mutex::new(Vec::<Peer>::new()));
|
||||
let (accepted, state) = (peers.clone(), server.clone());
|
||||
tokio::spawn(async move {
|
||||
while let Ok((stream, _)) = listener.accept().await {
|
||||
let (r, w) = stream.into_split();
|
||||
accepted.lock().push(Peer::connect(r, w, state.clone()));
|
||||
}
|
||||
});
|
||||
let cfg: ide_language::LanguageServerConfig =
|
||||
toml::from_str(&format!("name='text-server'\ncommand='no-process-required'\nconnect='127.0.0.1:{port}'"))
|
||||
.unwrap();
|
||||
let project = host.project("main").unwrap();
|
||||
project.lsp.set_servers_hook(Box::new(move |_, _| vec![cfg.clone()]));
|
||||
|
||||
let path = root.join("finders.txt");
|
||||
std::fs::write(&path, "Book.findByTitleAnd").unwrap();
|
||||
let doc = ops::doc::doc_open(&host, "main", path).await.unwrap();
|
||||
let labels = |list: &ide_lsp::types::CompletionList| list.items.iter().map(|i| i.label.clone()).collect::<Vec<_>>();
|
||||
|
||||
let first = ops::lsp::lsp_completion(&host, "main", RequestId(1), doc.id, Pos::new(0, 19), None).await.unwrap();
|
||||
assert!(first.is_incomplete);
|
||||
assert_eq!(labels(&first), ["server-item", "findByTitleAndTitle", "findByTitleAndAuthor"]);
|
||||
assert_eq!(*server.completions.lock(), 1);
|
||||
|
||||
// Typing on in the same word: the plugin answers for the new text, the server isn't asked again.
|
||||
let insert = |from, text: &str| ChangeSet { changes: vec![TextChange { from, to: from, insert: text.into() }] };
|
||||
let version = ops::doc::doc_edit(&host, "main", doc.id, doc.version, insert(19, "A")).await.unwrap();
|
||||
let next = ops::lsp::lsp_completion(&host, "main", RequestId(2), doc.id, Pos::new(0, 20), None).await.unwrap();
|
||||
assert!(next.is_incomplete);
|
||||
assert_eq!(labels(&next), ["server-item", "findByTitleAndATitle", "findByTitleAndAAuthor"]);
|
||||
assert_eq!(*server.completions.lock(), 1);
|
||||
|
||||
// Another word starts another completion: everyone is asked.
|
||||
ops::doc::doc_edit(&host, "main", doc.id, version, insert(20, " x.y")).await.unwrap();
|
||||
let other = ops::lsp::lsp_completion(&host, "main", RequestId(3), doc.id, Pos::new(0, 24), None).await.unwrap();
|
||||
assert_eq!(labels(&other), ["server-item", "yTitle", "yAuthor"]);
|
||||
assert_eq!(*server.completions.lock(), 2);
|
||||
|
||||
set_editor_providers(None);
|
||||
}
|
||||
@@ -53,9 +53,7 @@ fn copy_dir(from: &Path, to: &Path) {
|
||||
async fn open(fixture: &str) -> Opened {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join(fixture);
|
||||
let manifest_dir =
|
||||
std::env::var_os("CARGO_MANIFEST_DIR").map_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")), PathBuf::from);
|
||||
copy_dir(&manifest_dir.join("../../fixtures").join(fixture), &root);
|
||||
copy_dir(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures").join(fixture), &root);
|
||||
let app = tmp.path().join("app");
|
||||
let host = Arc::new(Host::new(common::host_config(&app)));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
|
||||
@@ -432,14 +432,6 @@ async fn patches_read_and_write_the_requested_repository() {
|
||||
})
|
||||
.collect::<String>();
|
||||
let root = Some(roots[0].clone());
|
||||
// Automatic mappings wait for indexing; the new folders and exclude rule may start a rescan.
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
for _ in 0..500 {
|
||||
if !project.index.status().indexing {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
let preview = vcs::vcs_patch_preview(&host, "main", root.clone(), patch.clone(), None, None).await.unwrap();
|
||||
assert!(preview.files.iter().all(|file| file.applies && !file.missing_base));
|
||||
assert_eq!(preview.automatic_mappings.len(), 1);
|
||||
|
||||
+12
-20
@@ -5,10 +5,8 @@
|
||||
//! { "$shared": { "version": "v1" }, "dev": { "host": "localhost:8080" } }
|
||||
//! ```
|
||||
//!
|
||||
//! Lookup order for `{{name}}` with an environment selected: the private
|
||||
//! environment, the public environment, private `$shared`, public `$shared`, then
|
||||
//! file variables (`@name = …`), as in the JetBrains HTTP Client. Without one, file
|
||||
//! variables come before `$shared`.
|
||||
//! Lookup order for `{{name}}`: file variables (`@name = …`), the private
|
||||
//! environment, the public environment, private `$shared`, public `$shared`.
|
||||
//! Dynamic variables: `$uuid` / `$random.uuid`, `$timestamp`, `$isoTimestamp`,
|
||||
//! `$randomInt` / `$random.integer`.
|
||||
|
||||
@@ -269,19 +267,17 @@ fn iso8601(secs: u64) -> String {
|
||||
pub struct Resolver<'a> {
|
||||
pub file_vars: &'a [(String, String)],
|
||||
pub env: HashMap<String, String>,
|
||||
/// An environment is selected: its values override file variables.
|
||||
pub env_first: bool,
|
||||
}
|
||||
|
||||
impl Resolver<'_> {
|
||||
fn lookup(&self, name: &str, depth: u32, missing: &mut BTreeSet<String>) -> Option<String> {
|
||||
let file = || self.file_vars.iter().rev().find(|(k, _)| k == name).map(|(_, v)| v);
|
||||
let env = || self.env.get(name);
|
||||
let found = if self.env_first { env().or_else(file) } else { file().or_else(env) };
|
||||
match found {
|
||||
Some(v) => Some(if depth < 8 { self.substitute_inner(v, depth + 1, missing) } else { v.clone() }),
|
||||
None => dynamic(name),
|
||||
if let Some((_, v)) = self.file_vars.iter().rev().find(|(k, _)| k == name) {
|
||||
return Some(if depth < 8 { self.substitute_inner(v, depth + 1, missing) } else { v.clone() });
|
||||
}
|
||||
if let Some(v) = self.env.get(name) {
|
||||
return Some(if depth < 8 { self.substitute_inner(v, depth + 1, missing) } else { v.clone() });
|
||||
}
|
||||
dynamic(name)
|
||||
}
|
||||
|
||||
fn substitute_inner(&self, text: &str, depth: u32, missing: &mut BTreeSet<String>) -> String {
|
||||
@@ -350,7 +346,7 @@ mod tests {
|
||||
let envs = Environments::from_json(&json, "").unwrap();
|
||||
let vars = envs.variables(Some("dev"));
|
||||
assert_eq!(vars["value"], token);
|
||||
let resolver = Resolver { file_vars: &[], env: vars, env_first: true };
|
||||
let resolver = Resolver { file_vars: &[], env: vars };
|
||||
let mut missing = BTreeSet::new();
|
||||
assert_eq!(resolver.substitute("{\"value\":{{value}}}", &mut missing), format!(r#"{{"value":{token}}}"#));
|
||||
assert!(missing.is_empty());
|
||||
@@ -453,15 +449,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn substitutes_file_env_and_dynamic_variables() {
|
||||
let file_vars =
|
||||
vec![("host".to_owned(), "localhost".to_owned()), ("base".to_owned(), "https://{{host}}".to_owned())];
|
||||
let file_vars = vec![("base".to_owned(), "https://{{host}}".to_owned())];
|
||||
let env = HashMap::from([("host".to_owned(), "example.com".to_owned())]);
|
||||
let r = Resolver { file_vars: &file_vars, env: env.clone(), env_first: true };
|
||||
let r = Resolver { file_vars: &file_vars, env };
|
||||
let mut missing = BTreeSet::new();
|
||||
// The environment's `host` overrides the file's, also inside a file variable.
|
||||
assert_eq!(r.substitute("{{ base }}/a?x={{nope}}", &mut missing), "https://example.com/a?x={{nope}}");
|
||||
let file_first = Resolver { file_vars: &file_vars, env, env_first: false };
|
||||
assert_eq!(file_first.substitute("{{base}}", &mut BTreeSet::new()), "https://localhost");
|
||||
assert_eq!(missing.into_iter().collect::<Vec<_>>(), vec!["nope"]);
|
||||
let mut missing = BTreeSet::new();
|
||||
let id = r.substitute("{{$uuid}}", &mut missing);
|
||||
@@ -473,7 +465,7 @@ mod tests {
|
||||
#[test]
|
||||
fn self_reference_terminates() {
|
||||
let file_vars = vec![("a".to_owned(), "{{a}}".to_owned())];
|
||||
let r = Resolver { file_vars: &file_vars, env: HashMap::new(), env_first: true };
|
||||
let r = Resolver { file_vars: &file_vars, env: HashMap::new() };
|
||||
let mut missing = BTreeSet::new();
|
||||
assert_eq!(r.substitute("{{a}}", &mut missing), "{{a}}");
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ pub fn prepare(
|
||||
env: Option<&str>,
|
||||
base_dir: Option<&Path>,
|
||||
) -> IdeResult<PreparedRequest> {
|
||||
let resolver = Resolver { file_vars, env: envs.variables(env), env_first: env.is_some() };
|
||||
let resolver = Resolver { file_vars, env: envs.variables(env) };
|
||||
let mut missing = BTreeSet::new();
|
||||
let url = resolver.substitute(&raw.block.url, &mut missing);
|
||||
let headers: Vec<(String, String)> =
|
||||
@@ -290,18 +290,6 @@ mod tests {
|
||||
assert_eq!(p.body.as_deref(), Some("{\"id\": \"{{id}}\"}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_environment_overrides_file_variables() {
|
||||
let f = parse("@host = localhost:8080\n@path = {{host}}/v1\nGET http://{{path}}/x?env={{name}}\n");
|
||||
let envs =
|
||||
Environments::from_json(r#"{"$shared":{"host":"shared","name":"none"},"dev":{"host":"dev.test"}}"#, "")
|
||||
.unwrap();
|
||||
let url = |env| prepare(&f.requests[0], &f.variables, &envs, env, None).unwrap().url;
|
||||
assert_eq!(url(Some("dev")), "http://dev.test/v1/x?env=none");
|
||||
// No environment: the file's value wins over `$shared`.
|
||||
assert_eq!(url(None), "http://localhost:8080/v1/x?env=none");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_unresolved_variables() {
|
||||
let f = parse("GET https://{{host}}/x\n");
|
||||
|
||||
@@ -28,7 +28,6 @@ const BUILTIN: &[(&str, &str)] = &[
|
||||
("elixir", include_str!("../../../languages/elixir.toml")),
|
||||
("erb", include_str!("../../../languages/erb.toml")),
|
||||
("erlang", include_str!("../../../languages/erlang.toml")),
|
||||
("freemarker", include_str!("../../../languages/freemarker.toml")),
|
||||
("fsharp", include_str!("../../../languages/fsharp.toml")),
|
||||
("gitattributes", include_str!("../../../languages/gitattributes.toml")),
|
||||
("gdscript", include_str!("../../../languages/gdscript.toml")),
|
||||
@@ -647,7 +646,6 @@ mod tests {
|
||||
"Thymeleaf",
|
||||
"ERB",
|
||||
"JSP",
|
||||
"FreeMarker",
|
||||
"Astro",
|
||||
"GoMod",
|
||||
];
|
||||
@@ -1235,8 +1233,6 @@ mod tests {
|
||||
("a.rb", "ruby"),
|
||||
("Gemfile", "ruby"),
|
||||
("show.html.erb", "erb"),
|
||||
("index.ftl", "freemarker"),
|
||||
("page.ftlh", "freemarker"),
|
||||
("index.php", "php"),
|
||||
("init.lua", "lua"),
|
||||
("main.dart", "dart"),
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
use crate::LspManager;
|
||||
use crate::server::{Running, Server};
|
||||
use ide_core::error::{ErrorData, ErrorKind};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::event::LspRefreshKind;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -520,30 +520,6 @@ fn not_imported(e: &IdeError) -> bool {
|
||||
|| m.contains("cannot find")
|
||||
}
|
||||
|
||||
const BUILD_FILES: [&str; 5] =
|
||||
["pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts"];
|
||||
|
||||
/// Errors on the build files of `module` and the builds enclosing it, nearest first, as
|
||||
/// `path: message` (relative to `root`). When m2e or Buildship can't configure a module (a build
|
||||
/// plugin or parent that doesn't resolve), it stays out of the Java model and these say why.
|
||||
fn build_file_errors(diagnostics: &[(PathBuf, lsp_types::Diagnostic)], root: &Path, module: &Path) -> Vec<String> {
|
||||
let mut errors: Vec<_> = diagnostics
|
||||
.iter()
|
||||
.filter(|(path, d)| {
|
||||
d.severity == Some(lsp_types::DiagnosticSeverity::ERROR)
|
||||
&& path.file_name().and_then(|n| n.to_str()).is_some_and(|n| BUILD_FILES.contains(&n))
|
||||
&& path.parent().is_some_and(|dir| module.starts_with(dir))
|
||||
})
|
||||
.map(|(path, d)| {
|
||||
let message = d.message.lines().next().unwrap_or_default().trim().trim_end_matches(':');
|
||||
(path.components().count(), format!("{}: {message}", path.strip_prefix(root).unwrap_or(path).display()))
|
||||
})
|
||||
.collect();
|
||||
errors.sort_by_key(|(depth, _)| std::cmp::Reverse(*depth));
|
||||
let mut seen = HashSet::new();
|
||||
errors.into_iter().map(|(_, e)| e).filter(|e| seen.insert(e.clone())).collect()
|
||||
}
|
||||
|
||||
/// The java-debug bundle is not loaded into jdtls.
|
||||
fn missing_bundle(e: &IdeError) -> bool {
|
||||
let m = e.message.to_ascii_lowercase();
|
||||
@@ -868,10 +844,6 @@ impl LspManager {
|
||||
loop {
|
||||
match self.jdtls_command_cancellable(path, command, arguments.clone(), cancel).await {
|
||||
Err(e) if not_imported(&e) && Instant::now() < deadline => {
|
||||
// An import that failed on the build file won't finish by waiting.
|
||||
if let Some(unconfigured) = self.unconfigured_module(path, cancel).await? {
|
||||
return Err(unconfigured);
|
||||
}
|
||||
tracing::debug!("{command}: {e}; waiting for the project import");
|
||||
cancellable_wait(cancel, tokio::time::sleep(Duration::from_millis(1500))).await?;
|
||||
}
|
||||
@@ -880,17 +852,6 @@ impl LspManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why jdtls has no Java project for the module at `path`, when its build files say so.
|
||||
async fn unconfigured_module(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<Option<IdeError>> {
|
||||
let (server, _) = self.jdtls(path, cancel).await?;
|
||||
let problems = build_file_errors(&server.diagnostics_snapshot(), &self.project_root, path);
|
||||
Ok((!problems.is_empty()).then(|| IdeError {
|
||||
kind: ErrorKind::InvalidInput,
|
||||
message: format!("{SERVER}: {} is not a Java project: {}", path.display(), problems.join("; ")),
|
||||
data: Some(ErrorData::JavaBuildProblems { problems }),
|
||||
}))
|
||||
}
|
||||
|
||||
fn running_java_projects<'a>(&self, files: &'a [PathBuf]) -> Vec<(Running, Vec<&'a Path>)> {
|
||||
let java = LanguageId::new("java");
|
||||
let mut targets = HashMap::new();
|
||||
@@ -1043,21 +1004,12 @@ impl LspManager {
|
||||
};
|
||||
let cp = match self.java_classpath(module, test, cancel).await {
|
||||
Ok(cp) => Some(cp),
|
||||
Err(e)
|
||||
if e.kind == ErrorKind::Cancelled
|
||||
|| matches!(e.data, Some(ErrorData::JavaBuildProblems { .. })) =>
|
||||
{
|
||||
return Err(e);
|
||||
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
|
||||
Err(e) if matches!(build, Some(JavaBuildStatus::WithErrors | JavaBuildStatus::Failed)) => {
|
||||
tracing::debug!("java.project.getClasspaths: {e}; retaining all compile errors");
|
||||
None
|
||||
}
|
||||
Err(e) => match self.unconfigured_module(module, cancel).await? {
|
||||
// The build "fails" on the build file's errors alone, with no compile errors to show.
|
||||
Some(unconfigured) => return Err(unconfigured),
|
||||
None if matches!(build, Some(JavaBuildStatus::WithErrors | JavaBuildStatus::Failed)) => {
|
||||
tracing::debug!("java.project.getClasspaths: {e}; retaining all compile errors");
|
||||
None
|
||||
}
|
||||
None => return Err(e),
|
||||
},
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let java_home = match self.java_vm_location(module, cancel).await {
|
||||
Ok(home) => home,
|
||||
@@ -1321,36 +1273,6 @@ mod tests {
|
||||
language.language_servers.into_iter().next().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_without_java_configuration_reports_its_build_file_errors() {
|
||||
let at = |path: &str, severity, message: &str| {
|
||||
let d = lsp_types::Diagnostic { severity: Some(severity), message: message.into(), ..Default::default() };
|
||||
(PathBuf::from(path), d)
|
||||
};
|
||||
use lsp_types::DiagnosticSeverity as S;
|
||||
let diagnostics = [
|
||||
at("/w/pom.xml", S::ERROR, "Non-resolvable import POM"),
|
||||
at(
|
||||
"/w/app-server/pom.xml",
|
||||
S::ERROR,
|
||||
"Could not calculate build plan: Plugin x:y:9.9.9 could not be resolved:\nFailure to find…",
|
||||
),
|
||||
at("/w/app-server/pom.xml", S::WARNING, "Overriding managed version"),
|
||||
at("/w/app-server/src/main/java/Main.java", S::ERROR, "Main cannot be resolved"),
|
||||
at("/w/app-system/pom.xml", S::ERROR, "Another module's error"),
|
||||
at("/w/app-server/build.gradle", S::ERROR, "Could not run phased build action"),
|
||||
];
|
||||
assert_eq!(
|
||||
build_file_errors(&diagnostics, Path::new("/w"), Path::new("/w/app-server")),
|
||||
[
|
||||
"app-server/pom.xml: Could not calculate build plan: Plugin x:y:9.9.9 could not be resolved",
|
||||
"app-server/build.gradle: Could not run phased build action",
|
||||
"pom.xml: Non-resolvable import POM",
|
||||
]
|
||||
);
|
||||
assert!(build_file_errors(&diagnostics, Path::new("/w"), Path::new("/w/app-module")).len() == 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unresolvable_build_plugin_is_explained() {
|
||||
let diagnostic = |severity, message: &str| lsp_types::Diagnostic {
|
||||
|
||||
@@ -16,7 +16,6 @@ use crate::types::{
|
||||
FieldValue, ServiceLog, ServiceLogToggle, ServicePane, ServiceTab, TableSort, View, ViewBody, ViewButton,
|
||||
ViewEvent, ViewField, ViewListItem, ViewTable, ViewTreeItem, Viewport,
|
||||
};
|
||||
use crate::wit_host::completion_list_bindings::exports::openidea::plugin::completion_list_provider as wit_cl;
|
||||
use crate::wit_host::hover_actions_bindings::exports::openidea::plugin::hover_actions as wit_hia;
|
||||
use crate::wit_host::injections_bindings::exports::openidea::plugin::injections as wit_inj;
|
||||
use crate::wit_host::language_features_bindings::exports::openidea::plugin::language_features as wit_lf;
|
||||
@@ -59,7 +58,7 @@ use views_bindings::exports::openidea::plugin::view_provider as wit_view;
|
||||
use views_bindings::openidea::plugin::view_types as wit_vt;
|
||||
|
||||
/// The API version of the world above, `major.minor` of [`host_api`].
|
||||
pub const API_VERSION: &str = "1.16";
|
||||
pub const API_VERSION: &str = "1.15";
|
||||
const EPOCH_TICK: Duration = Duration::from_millis(10);
|
||||
pub(crate) const MAX_TEXT: usize = 1 << 20;
|
||||
/// The most text, and the most PNG bytes, `ui.read-clipboard` returns.
|
||||
@@ -893,7 +892,6 @@ struct Exports {
|
||||
endpoints: Option<wit_endpoints::Guest>,
|
||||
search: Option<wit_search::Guest>,
|
||||
hover_actions: Option<wit_hia::Guest>,
|
||||
completion_list: Option<wit_cl::Guest>,
|
||||
run_configurations: Option<wit_configs::Guest>,
|
||||
launch_configurations: Option<wit_launch::Guest>,
|
||||
test_results: Option<wit_tests::Guest>,
|
||||
@@ -1046,7 +1044,6 @@ impl Runtime {
|
||||
let endpoint_indices = wit_endpoints::GuestIndices::new(&pre).ok();
|
||||
let search_indices = wit_search::GuestIndices::new(&pre).ok();
|
||||
let hover_actions_indices = wit_hia::GuestIndices::new(&pre).ok();
|
||||
let completion_list_indices = wit_cl::GuestIndices::new(&pre).ok();
|
||||
let configs_indices = wit_configs::GuestIndices::new(&pre).ok();
|
||||
let launch_indices = wit_launch::GuestIndices::new(&pre).ok();
|
||||
let tests_indices = wit_tests::GuestIndices::new(&pre).ok();
|
||||
@@ -1114,8 +1111,6 @@ impl Runtime {
|
||||
let search = search_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
|
||||
let hover_actions =
|
||||
hover_actions_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
|
||||
let completion_list =
|
||||
completion_list_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
|
||||
let endpoints = match endpoint_indices {
|
||||
Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?),
|
||||
None => None,
|
||||
@@ -1140,7 +1135,6 @@ impl Runtime {
|
||||
endpoints,
|
||||
search,
|
||||
hover_actions,
|
||||
completion_list,
|
||||
run_configurations,
|
||||
launch_configurations,
|
||||
test_results,
|
||||
@@ -1406,57 +1400,29 @@ impl Runtime {
|
||||
trigger: Option<&str>,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<CompletionItem>, CallError> {
|
||||
Ok(self.provide_completion_list(doc, at, trigger, timeout)?.0)
|
||||
}
|
||||
|
||||
/// Completion items and whether the plugin marked them incomplete: from the
|
||||
/// `completion-list-provider` export (API 1.16) when the plugin has it, else
|
||||
/// from `providers.completion`, which is never incomplete.
|
||||
pub fn provide_completion_list(
|
||||
&mut self,
|
||||
doc: &ProviderDocument,
|
||||
at: ide_core::Pos,
|
||||
trigger: Option<&str>,
|
||||
timeout: Duration,
|
||||
) -> Result<(Vec<CompletionItem>, bool), CallError> {
|
||||
macro_rules! item {
|
||||
($i:expr) => {{
|
||||
let i = $i;
|
||||
CompletionItem {
|
||||
label: clip(i.label, MAX_TITLE),
|
||||
detail: i.detail.map(|d| clip(d, MAX_TITLE)),
|
||||
kind: i.kind.map(|k| clip(k, 32)),
|
||||
insert_text: clip(i.insert_text, 64 << 10),
|
||||
snippet: i.snippet,
|
||||
replace: i.replace.map(range_from_wit),
|
||||
sort_text: i.sort_text.map(|t| clip(t, 64)),
|
||||
filter_text: i.filter_text.map(|t| clip(t, MAX_TITLE)),
|
||||
documentation: i.documentation.map(|d| clip(d, 16 << 10)),
|
||||
additional_edits: i
|
||||
.additional_edits
|
||||
.into_iter()
|
||||
.take(MAX_ADDITIONAL_EDITS)
|
||||
.map(edit_from_wit)
|
||||
.collect(),
|
||||
}
|
||||
}};
|
||||
}
|
||||
if self.exports.completion_list.is_some() {
|
||||
let d = wit_cl::Document {
|
||||
path: to_ipc(&doc.path),
|
||||
language: doc.language.clone(),
|
||||
version: doc.version,
|
||||
text: doc.text.clone(),
|
||||
};
|
||||
let list = self.call(Invocation::default(), timeout, |exports, store| {
|
||||
exports.completion_list.as_ref().expect("checked").call_completion(store, &d, pos_to_wit(at), trigger)
|
||||
})?;
|
||||
let items = list.items.into_iter().take(MAX_PROVIDER_ITEMS).map(|i| item!(i)).collect();
|
||||
return Ok((items, list.incomplete));
|
||||
}
|
||||
let d = doc_to_wit(doc);
|
||||
let items = self.provider_call(timeout, |p, s| p.call_completion(s, &d, pos_to_wit(at), trigger))?;
|
||||
Ok((items.into_iter().take(MAX_PROVIDER_ITEMS).map(|i| item!(i)).collect(), false))
|
||||
Ok(items
|
||||
.into_iter()
|
||||
.take(MAX_PROVIDER_ITEMS)
|
||||
.map(|i| CompletionItem {
|
||||
label: clip(i.label, MAX_TITLE),
|
||||
detail: i.detail.map(|d| clip(d, MAX_TITLE)),
|
||||
kind: i.kind.map(|k| clip(k, 32)),
|
||||
insert_text: clip(i.insert_text, 64 << 10),
|
||||
snippet: i.snippet,
|
||||
replace: i.replace.map(range_from_wit),
|
||||
sort_text: i.sort_text.map(|t| clip(t, 64)),
|
||||
filter_text: i.filter_text.map(|t| clip(t, MAX_TITLE)),
|
||||
documentation: i.documentation.map(|d| clip(d, 16 << 10)),
|
||||
additional_edits: i
|
||||
.additional_edits
|
||||
.into_iter()
|
||||
.take(MAX_ADDITIONAL_EDITS)
|
||||
.map(edit_from_wit)
|
||||
.collect(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn provide_inline_completion(
|
||||
|
||||
@@ -112,46 +112,6 @@ pub(crate) mod hover_actions_bindings {
|
||||
});
|
||||
}
|
||||
|
||||
/// The optional `completion-list-provider` export (API 1.16), bound on its own when present.
|
||||
pub(crate) mod completion_list_bindings {
|
||||
wasmtime::component::bindgen!({
|
||||
world: "plugin-completion-list",
|
||||
path: "../../wit",
|
||||
imports: { default: trappable },
|
||||
with: {
|
||||
"openidea:plugin/types": super::bindings::openidea::plugin::types,
|
||||
"openidea:plugin/log": super::bindings::openidea::plugin::log,
|
||||
"openidea:plugin/ui": super::bindings::openidea::plugin::ui,
|
||||
"openidea:plugin/storage": super::bindings::openidea::plugin::storage,
|
||||
"openidea:plugin/workspace": super::bindings::openidea::plugin::workspace,
|
||||
"openidea:plugin/editor": super::bindings::openidea::plugin::editor,
|
||||
"openidea:plugin/decorations": super::bindings::openidea::plugin::decorations,
|
||||
"openidea:plugin/invocation": super::bindings::openidea::plugin::invocation,
|
||||
"openidea:plugin/vcs": super::bindings::openidea::plugin::vcs,
|
||||
"openidea:plugin/build": super::bindings::openidea::plugin::build,
|
||||
"openidea:plugin/commit": super::bindings::openidea::plugin::commit,
|
||||
"openidea:plugin/events": super::bindings::openidea::plugin::events,
|
||||
"openidea:plugin/tasks": super::bindings::openidea::plugin::tasks,
|
||||
"openidea:plugin/diagnostics": super::bindings::openidea::plugin::diagnostics,
|
||||
"openidea:plugin/net": super::bindings::openidea::plugin::net,
|
||||
"openidea:plugin/secrets": super::bindings::openidea::plugin::secrets,
|
||||
"openidea:plugin/run": super::bindings::openidea::plugin::run,
|
||||
"openidea:plugin/process": super::bindings::openidea::plugin::process,
|
||||
"openidea:plugin/output": super::bindings::openidea::plugin::output,
|
||||
"openidea:plugin/auth": super::bindings::openidea::plugin::auth,
|
||||
"openidea:plugin/command-runner": super::bindings::openidea::plugin::command_runner,
|
||||
"openidea:plugin/language-servers": super::bindings::openidea::plugin::language_servers,
|
||||
"openidea:plugin/ipc": super::bindings::openidea::plugin::ipc,
|
||||
"openidea:plugin/fs": super::bindings::openidea::plugin::fs,
|
||||
"openidea:plugin/views": super::bindings::openidea::plugin::views,
|
||||
"openidea:plugin/settings": super::bindings::openidea::plugin::settings,
|
||||
"openidea:plugin/database": super::bindings::openidea::plugin::database,
|
||||
"openidea:plugin/mcp": super::bindings::openidea::plugin::mcp,
|
||||
"openidea:plugin/extensions": super::bindings::openidea::plugin::extensions,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/// The optional `providers` export.
|
||||
pub(crate) mod providers_bindings {
|
||||
wasmtime::component::bindgen!({
|
||||
|
||||
@@ -34,7 +34,6 @@ fn components() -> Vec<PathBuf> {
|
||||
repo().join("crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm"),
|
||||
@@ -94,7 +93,7 @@ fn the_sdk_carries_the_hosts_wit() {
|
||||
|
||||
#[test]
|
||||
fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
let host = v("1.16.0");
|
||||
let host = v("1.15.0");
|
||||
for ok in [
|
||||
"1.0.0",
|
||||
"1.3.0",
|
||||
@@ -110,16 +109,15 @@ fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
"1.13.0",
|
||||
"1.14.0",
|
||||
"1.15.0",
|
||||
"1.16.0",
|
||||
"1.0.0-rc.1",
|
||||
] {
|
||||
assert_eq!(check_api(&v(ok), &host), Ok(()), "{ok}");
|
||||
}
|
||||
let newer = check_api(&v("1.17.0"), &host).unwrap_err();
|
||||
assert!(newer.contains("1.17") && newer.contains("update OpenIDEA"), "{newer}");
|
||||
let newer = check_api(&v("1.16.0"), &host).unwrap_err();
|
||||
assert!(newer.contains("1.16") && newer.contains("update OpenIDEA"), "{newer}");
|
||||
assert!(check_api(&v("2.0.0"), &host).unwrap_err().contains("update OpenIDEA"));
|
||||
let older = check_api(&v("0.2.0"), &host).unwrap_err();
|
||||
assert!(older.contains("rebuild it with the 1.16 SDK"), "{older}");
|
||||
assert!(older.contains("rebuild it with the 1.15 SDK"), "{older}");
|
||||
// 0.x: every minor is its own API.
|
||||
assert_eq!(check_api(&v("0.2.0"), &v("0.2.5")), Ok(()));
|
||||
assert!(check_api(&v("0.1.0"), &v("0.2.0")).is_err());
|
||||
@@ -164,23 +162,6 @@ fn the_hover_actions_component_exports_the_optional_hover_actions_world() {
|
||||
assert!(!old_exports.iter().any(|name| name.starts_with("openidea:plugin/hover-actions")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_completion_list_component_exports_the_optional_completion_list_world() {
|
||||
let engine = PluginEngine::new().unwrap();
|
||||
let exports_of = |path: &str| -> Vec<String> {
|
||||
let component = engine.compile(&repo().join(path)).unwrap();
|
||||
component.component_type().exports(engine.engine()).map(|(name, _)| name.to_owned()).collect()
|
||||
};
|
||||
let exports = exports_of("crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm");
|
||||
let list = format!("openidea:plugin/completion-list-provider@{API_VERSION}.0");
|
||||
assert!(exports.iter().any(|name| name.starts_with(&list)), "{exports:?}");
|
||||
// Next to `providers`, which still serves the other kinds and older hosts.
|
||||
assert!(exports.iter().any(|name| name.starts_with("openidea:plugin/providers@")), "{exports:?}");
|
||||
// A plugin that does not export the optional world stays valid.
|
||||
let old = exports_of("plugins/official/test-runner/dist/plugin.wasm");
|
||||
assert!(!old.iter().any(|name| name.starts_with("openidea:plugin/completion-list-provider")));
|
||||
}
|
||||
|
||||
// --- a later host, simulated -------------------------------------------------------------
|
||||
|
||||
struct Data {
|
||||
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
99d9091eed1143ad5df01e28631fba47f9a30f0ed99f078718a08183b85fa234
|
||||
ef1aeca63e064ddd9c43126347fd69b39597230afe29c023effeecffb5dab627
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
8dde828b674a2728c944bbc39ddbdce930e0ca9ddc94b2c464ab7677f70dc89b
|
||||
b5df63f7d04ab303ccf1c077187df063753a639670254c4bd64ced055e3bf806
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
93acad4b3620ee2a154871558c9f34a80f1b17e5592cd678295d48f08e20ba9d
|
||||
52dfaac64cd496de1685d8412e4073e609a8cb4ab6e1776346aac8c18793550a
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
99387003011b3d6147413b6ec626fbfd298f119dde0496000dad5ba57a9a76dd
|
||||
0a30717897bc970afff38a916353510db23c90123b2dccc0d2b722e734dd83b3
|
||||
-336
@@ -1,336 +0,0 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.105"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "id-arena"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||
|
||||
[[package]]
|
||||
name = "leb128fmt"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
|
||||
[[package]]
|
||||
name = "macro-string"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "openidea-plugin"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openidea-test-completion-list"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"openidea-plugin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prettyplease"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-encoder"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a"
|
||||
dependencies = [
|
||||
"leb128fmt",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-metadata"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"indexmap",
|
||||
"wasm-encoder",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmparser"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"hashbrown",
|
||||
"indexmap",
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"wit-bindgen-rust-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-core"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"heck",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-rust"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"heck",
|
||||
"indexmap",
|
||||
"prettyplease",
|
||||
"syn",
|
||||
"wasm-metadata",
|
||||
"wit-bindgen-core",
|
||||
"wit-component",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-rust-macro"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"macro-string",
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"wit-bindgen-core",
|
||||
"wit-bindgen-rust",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-component"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags",
|
||||
"indexmap",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"wasm-encoder",
|
||||
"wasm-metadata",
|
||||
"wasmparser",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-parser"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"hashbrown",
|
||||
"id-arena",
|
||||
"indexmap",
|
||||
"log",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"unicode-ident",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
@@ -1,20 +0,0 @@
|
||||
[package]
|
||||
name = "openidea-test-completion-list"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
openidea-plugin = { path = "../../../../../sdk/rust/openidea-plugin" }
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
strip = true
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
Binary file not shown.
@@ -1 +0,0 @@
|
||||
7b503b76300faca4c4ccfbb167c1823a32e4b4e5ef431eb8b7a6684b3908df11
|
||||
@@ -1,9 +0,0 @@
|
||||
id = "test.completion-list"
|
||||
name = "Completion list fixture"
|
||||
version = "0.1.0"
|
||||
engines.openidea = "^1.16"
|
||||
wasm = "dist/plugin.wasm"
|
||||
|
||||
[[contributes.providers]]
|
||||
kinds = ["completion"]
|
||||
languages = ["plaintext", "text"]
|
||||
@@ -1,38 +0,0 @@
|
||||
//! API 1.16 fixture for the optional `completion-list-provider` export: GORM-style
|
||||
//! dynamic finders, built from what has been typed after the `.`, so the list is
|
||||
//! marked incomplete.
|
||||
use openidea_plugin::providers::{CompletionItem, CompletionKind, CompletionList, Document, Providers};
|
||||
use openidea_plugin::{Error, Invocation, Plugin, Position, register_plugin};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Fixture;
|
||||
|
||||
impl Plugin for Fixture {
|
||||
fn run_command(&mut self, id: &str, _: &Invocation, _: Option<&str>) -> Result<Option<String>, Error> {
|
||||
Err(Error::NotFound(id.into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Providers for Fixture {
|
||||
/// Not called once `completion_list` is exported.
|
||||
fn completion(&mut self, _: &Document, _: Position, _: Option<&str>) -> Vec<CompletionItem> {
|
||||
vec![CompletionItem::new("legacy", CompletionKind::Text)]
|
||||
}
|
||||
|
||||
fn completion_list(&mut self, doc: &Document, at: Position, _: Option<&str>) -> CompletionList {
|
||||
let line = doc.text.lines().nth(at.line as usize).unwrap_or_default();
|
||||
// ASCII test documents: the UTF-16 column is the byte offset.
|
||||
let head = &line[..(at.character as usize).min(line.len())];
|
||||
let Some(dot) = head.rfind('.') else {
|
||||
return vec![CompletionItem::new("findBy", CompletionKind::Method)].into();
|
||||
};
|
||||
let typed = &head[dot + 1..];
|
||||
let items = ["Title", "Author"]
|
||||
.iter()
|
||||
.map(|p| CompletionItem::new(&format!("{typed}{p}"), CompletionKind::Method))
|
||||
.collect();
|
||||
CompletionList { items, incomplete: true }
|
||||
}
|
||||
}
|
||||
|
||||
register_plugin!(Fixture, providers, completion_list);
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
30c5b5b2aa567d108f46b8c798d37df706d653e108769ed69664bd9c3efca52d
|
||||
d41ca70e38b228af31d69302d0513db52311423f44ad5ef86e47e0f8a409a822
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
bca40b2cec9cfb634110c8ba5147b9d4dcd40a7f7b5bbf4a88d64265138efec5
|
||||
e6ab772482157eae8b9bd558baf62f288899b335851e760bb4f2703dbbc52ede
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
85e9bf858fe2ecd9b09bba20ac8a735c067f2eaedfe927f47d623e33e073a314
|
||||
3c45e59462de19c2ebba63072d2600e8340fdb9aeafc1e0f736facb79d8f3bb9
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
b4a38e2025018bcf3f48f0625ece5615229b1802b5fb142980c620760df94be9
|
||||
fb64178b6cfa96e3b4c7ec03a6cf892467442c322f59d8441bc796e515607ad7
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
f13472dd0130fcf1dc7201f9e8995ada6c2383134d5880f089e74bfe0b202a63
|
||||
2fc18a5627776ab512afdb183ea8ea9aaf77b19496837c0f7b7287d03dc453d9
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
e5668537d9c46cb32e2249a1a24dc43de1255acb1494199d80f9697ff5b8c62e
|
||||
72d2ed671223b984982fc7740e3ea2febfadee0e37ab9490f21cd120abbd6316
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
fcb3aa33e97d9d9540cfe14f2eadabef13ab2040804ba95fb6e29fe92c672960
|
||||
49f428f9e258c0cc72ff6d4f85c573a1875d55a7d1cce9dc8246c950f08c2f5f
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
fe81b9a91dafeeede9ea7673259713d210490d6971b16a1ca09e6e5b5ceed3cd
|
||||
f6d1c7a6734996c0edd23e9e14e4487da5610712d2566b0b389c9d5c0273a71d
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
0758dbb11a1ee942871b0256041028ffb9e1877ddbfbbb2f2a3f09c9dad6ff0c
|
||||
1fcfcd161b3c719d24691ccd10c0eca329b47a6dd0195a77289d10eed8de0de9
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
cc8950002092eb18e6307582219041fdb8bcec6969cf646a17f0dea44370b007
|
||||
b1b8cc4314d9d884da30e16628e79f4c1b844fa8ab39ec1d043de22492004570
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
6f3f22b7dd80eb9e9f4ea92a46321d1b9dba1790bd084c84023a16e89bc18c14
|
||||
be0d5c276c63a310aef3ab1bf72f66ceb61cf064d24284c88883287936c27fd9
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
447cbf1cfabbe3689f280e558d541b0e09c898e873b83c05ae405206b2b73b61
|
||||
a8f4e08bb96467d97e9466ac27ddfd3464ea6fc522a9cb46da0a7addf95bc049
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
3e076f7a5aa0abaa087627cab70fcce9a4042d2285539cce748eaa468cf9e4ad
|
||||
b5b4f2baaf59dc69b631209f1bbe681bae2ccf7007cd809c6d039c00f347c77d
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
bd4573d14459fd540159879d3e081a35c6ff2f48c859efb9e47355b6cc5b0ec5
|
||||
9befc1bcec69b69862b7089fd6c0b1ca0afeadbcc426ad9ea65985dfa0a2da8c
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
6ea6a4e38f44d5588e19ed06c6f255f2d6fb095af052884357c454204c24ba77
|
||||
a1ab5823612e4857fd549e1f4b5733dd7705e4ed9476b30fcf88866f8596f5f8
|
||||
Binary file not shown.
+1
-1
@@ -1 +1 @@
|
||||
31cb0f0ac27a49c6c3243e1d8ff4c4a1b7b9e582f8a89f89e3c61f0b795f0761
|
||||
5f9e8ee5a69354ac954cd8445be90838424ae5d6cf0e3624c40848d94032f474
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
3be98f89396cd9f9b49bf268f3e9b5ffc6be9c59dccea795ae99dc229c1bf8ee
|
||||
a2ff5dd95aca671f24963f9a5fccd47b413d51e9823676d2e233bdc1ec9d5494
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
7671d19deaf46f685c90ccb295eadcfd2634e680cf8e742e537adcac51671e22
|
||||
cb26e176fcd652076e6042ce28741f06aecaad62db8252f753c197f5c77f273b
|
||||
+3
-3
@@ -5,9 +5,9 @@ wit_bindgen::generate!({
|
||||
inline: "
|
||||
package fixture:misbehave;
|
||||
world misbehave {
|
||||
include openidea:plugin/plugin-syntax@1.16.0;
|
||||
export openidea:plugin/providers@1.16.0;
|
||||
export openidea:plugin/file-actions@1.16.0;
|
||||
include openidea:plugin/plugin-syntax@1.15.0;
|
||||
export openidea:plugin/providers@1.15.0;
|
||||
export openidea:plugin/file-actions@1.15.0;
|
||||
}
|
||||
",
|
||||
path: "../../../../../wit",
|
||||
|
||||
Loaded 100 of 463 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user