Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 30e72ffa57 chore: v0.1.51 2026-11-24 20:37:10 +08:00
Deng Liu dd164c0909 ci: route Linux CI and Language smoke jobs to self-hosted runners (#5539)
While SELFHOSTED_RUNNERS is true, trusted Linux jobs in ci.yml and language-smoke.yml run on the openidea-selfhosted runners and fall back to ubuntu-latest otherwise. The runner image moves to Ubuntu 24.04, E2E installs Chromium on the runner, and the smoke tests resolve fixtures from the runtime CARGO_MANIFEST_DIR.
2026-11-24 20:29:25 +08:00
Deng Liu 7419eb85c8 feat(services): show Docker volume disk usage across dashboards (#5545)
Add a docker_volume_sizes command (docker system df -v, Engine API fallback) and show each volume's disk usage in the Volume, Compose project and Container dashboards, refreshed every 30 seconds while the Services tool window is visible.
2026-11-24 19:58:10 +08:00
l0ng-ai 64a168a2d1 fix(agents): title a task from the prompt's text outside code fences (#5631)
A prompt that opened with a pasted fenced block was titled from the first line inside the block until the generated title arrived. A line outside the fences now wins; a prompt that is one fenced block is still titled from inside it.
2026-11-24 19:57:03 +08:00
l0ng-ai 77c531b9ca fix(python): keep inheritance inspections on classes an unsaved edit moved (#5629)
The inheritance inspections matched the open document's classes to the inheritance graph by exact position, and the graph is re-indexed only on save, so a line typed above a class hid the warnings of every class below until the file was saved. The document's classes now pair with the graph's in order while they read the same names, and by position otherwise; same-document methods and members come from the live document.
2026-11-24 19:55:22 +08:00
Deng Liu d411ace29b perf(vcs): cache unchanged ref queries (#5548)
Reuse the ref-decoration snapshot for log refs and cache branch lists, invalidated by ref storage, HEAD, repository config, shallow state and trust-mode changes.
2026-11-24 19:55:16 +08:00
l0ng-ai 4074d079b1 feat(agents): reorder the task menu and polish selection and images (#5621)
* feat(agents): reorder the task menu and polish selection and images

- Task menu: Pin, Rename, Mark as Unread/Read; Fork, Group; Archive (⇧⌘E
  in the task list), Archive All Below, Delete. Terminal and Open in New
  Window leave the menu. Hovering a task row shows Pin and Archive beside
  its age.
- Reply text: no stripe under the unselected start of a line when a
  selection runs on past it; inline code keeps its side insets inside the
  selection. A double or triple click no longer selects into the next
  message.
- Images: tool-read images show as same-height thumbnails; the remove
  button on attached images stays opaque on hover.

* fix(agents): keep Jump to Latest opaque on hover

* fix(agents): keep task row hover buttons from selecting or opening the task
2026-11-24 18:34:22 +08:00
l0ng-ai 2d0120f092 fix(editor): key navigation bar segments by position (#5616)
A path deeper than four folders collapses its middle into an ellipsis whose tooltip is the whole relative path, the same as the last folder's, so React warned about two children with the same key. Segments are now keyed by their position as well.
2026-11-24 17:53:35 +08:00
faysou df470f93c6 test(e2e): keep project focus checks from switching editor tabs (#5604)
With preview tabs enabled, selecting a file in the Project view also opens it, so the External Tools test disables preview tabs to keep the Project selection and the active editor on different files. The task-input shortcut test focuses a directory so the task editor stays visible.
2026-11-24 17:51:02 +08:00
faysou 764b6717e0 fix(python): skip Hatch discovery without a desktop bridge (#5608)
Opening Add Python Interpreter in a plain browser started a Hatch discovery request whose cancellation called the desktop command without a bridge, an unhandled rejection. Browser mode now returns an empty result with a no-op cancel.
2026-11-24 17:50:48 +08:00
l0ng-ai 7aa6adb0ef Revert "fix(agents): extend the chat scrollbar to the composer (#5583)"
This reverts commit c0f7ec93d3.
2026-11-24 17:22:50 +08:00
l0ng-ai 7ebdf04e2f ci: split E2E into four shards (#5591)
Two E2E shards of ~512 tests each hit the 30-minute job timeout; four shards keep each within it.
2026-11-24 16:13:51 +08:00
l0ng-ai c0f7ec93d3 fix(agents): extend the chat scrollbar to the composer (#5583) 2026-11-24 15:38:10 +08:00
l0ng-ai cc9089db11 test: make four tests pass on Windows (#5580)
Windows CI on main failed four tests the earlier clippy error had hidden:
- pipenv naming hashed a Unix path, which Windows joins with a backslash;
  the Windows expectation now uses a Windows path.
- the VIRTUAL_ENV assertion joined "member/.override" as one component.
- the diagnostics coalescing tests slept 30 ms for a 16 ms flush, too short
  for Windows timers; they wait for the flush with a deadline.
- the patch preview test read automatic mappings while new folders could
  still be re-indexing (automatic mappings pause then); it waits for indexing.
2026-11-24 15:36:45 +08:00
l0ng-ai 62095b904e fix(agents): keep selection highlights within reply text (#5574) 2026-11-24 15:36:40 +08:00
l0ng-ai 96c5e94975 fix(agents): open new tasks with less background work (#5573) 2026-11-24 15:36:35 +08:00
LU XIANGRUIтаLU XIANGRUI 97e9657fd3 feat(editor): highlight JPQL, SQL and SpEL in Spring annotation strings (#5565)
- Java parses the string values of Spring Data JPA @Query (JPQL, or SQL with
  nativeQuery = true), @Value / @ConditionalOnExpression (SpEL #{...} and
  property placeholders ${...}), and the SpEL attributes of @PreAuthorize,
  @PostAuthorize, @PreFilter, @PostFilter, @Cacheable, @CachePut, @CacheEvict
- annotations are matched by their imported or qualified class, so other
  annotations named Query stay plain strings
- escape sequences stay outside the embedded text and keep the string colours

Co-authored-by: LU XIANGRUI <[email protected]>
2026-11-24 14:57:35 +08:00
LU XIANGRUIтаLU XIANGRUI 1205ffecd2 fix(editor): leave Java statement labels uncoloured, as IntelliJ does (#5564)
Co-authored-by: LU XIANGRUI <[email protected]>
2026-11-24 14:54:09 +08:00
Deng Liu 51766249f9 fix(services): keep Docker Compose dashboard actions pinned on scroll (#5534) 2026-11-24 14:47:11 +08:00
l0ng-ai ff55bcdf9a fix(vcs): keep Git Log file selection in place (#5563) 2026-11-24 13:52:30 +08:00
l0ng-ai fd6d1d5d0e ci(smoke): build the smoke binaries once for every language (#5395)
Each language job compiled the language_smoke / project_smoke tests and
openidea-server itself, about 4-5 minutes of the same work nine times. A
build job now compiles them once and hands them on as an artifact; the
language jobs only install their tools and run the binaries.
2026-11-24 13:25:13 +08:00
l0ng-ai 9ad5bad82e fix(vcs): refresh status after git commands run outside the IDE in subfolder projects, worktrees and submodules (#5555)
The project file watcher only reports Git metadata in the .git folders it
sees: the project root's and nested repositories'. When the project is a
subfolder of its repository, a linked worktree, a mapped repository
elsewhere, or a submodule (.git/modules/<name>), a commit, checkout or
reset in a terminal wrote nothing the watcher reported, so file statuses
stayed stale until something else triggered a refresh.

Watch HEAD, index, packed-refs and refs/** of those git directories, follow
repository changes, and emit VcsChanged for them (ignoring the IDE's own
index writes).
2026-11-24 13:25:08 +08:00
l0ng-ai fec50f3925 fix(agents): show a sent message before recording the turn checkout (#5536)
The user's message was only added to the conversation after the pre-turn checkout was recorded, which can take seconds in a large repository, so pressing Enter appeared to do nothing and the view did not scroll to the new message.
2026-11-24 12:15:56 +08:00
l0ng-ai 8b3d9adcfe fix(agents): keep the new-task composer height when typing the first character (#5535)
The home composer's taller minimum height overrode the composer rule by selector, so stylesheet load order could reset it to the single-line height once CodeMirror re-rendered. The home view now sets a --composer-min-height variable that the composer rule reads.
2026-11-24 12:15:49 +08:00
l0ng-ai 457174a442 feat(workbench): keep rarely used tool windows off the stripe by default (#5531)
Bookmarks and TODO are listed under the stripe's "…" until first opened. The Database
window is on the stripe by default only while the project has data sources. Of the
Flutter DevTools windows only Flutter Inspector has a stripe button; Deep Links,
DevTools and DevTools Extensions wait under "…". A user's own stripe choice still wins.
2026-11-24 12:15:23 +08:00
Deng Liuтаdengliu de868f1677 feat(remote): persist remote backend, terminals, runs, agents, and workbench state across window close (#4385)
Closing a remote window (SSH, WSL, Dev Containers) used to end openidea-server --stdio and tear down terminals, runs (running their stop commands), indexing and agent turns. openidea-server --attach now connects through a detached per-project daemon (private 0700 run dir, owner check, flock) that keeps them alive across disconnects; reopening reattaches terminals with bounded scrollback and OSC state, runs and agent turns, and restores remote editor tabs, tool windows and plugin views. The close dialog offers Keep Backend Running / Stop Backend; Stop Remote Backend shuts the daemon down on demand. A disconnected backend with no live work exits after an idle timeout (3 hours by default; presets, custom or Never in Settings › Tools › Remote Development, host override wins). The socket is keyed by project, so a new build replaces an idle backend of another build and reports a busy one; a window taken over by another shows that instead of a dropped connection. Clean documents are released on disconnect while dirty buffers keep the backend alive.

Also: a plugin-owned PTY keeps its exit hook across reattach (reattach only rebinds the forwarding sink), and a recent project clicked again while it is still opening joins that attempt instead of connecting twice (a double click made the second attach take over and fail the first).

Co-authored-by: dengliu <[email protected]>
2026-11-24 11:42:00 +08:00
192 змінених файлів з 7463 додано та 959 видалено

No files matched your search

+70 -28
Переглянути файл
@@ -28,7 +28,9 @@ jobs:
# shared runners to others. Pushes, the merge queue and manual runs always run everything.
changes:
name: Changes
runs-on: ubuntu-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: ${{ 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: 5
permissions:
pull-requests: read
@@ -108,10 +110,10 @@ jobs:
strategy:
fail-fast: false
matrix:
os: [macos-latest, ubuntu-22.04, windows-latest]
os: [macos-latest, ubuntu-latest, 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-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 }}
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 }}
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
@@ -144,8 +146,8 @@ jobs:
- name: Linux deps
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf
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[@]}"; }
# tauri-build checks that frontendDist exists.
- run: pnpm install --frozen-lockfile && mkdir -p dist
shell: bash
@@ -155,6 +157,13 @@ jobs:
# Test fixtures write LF files; keep Git from converting them on checkout.
- 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'
run: |
docker pull busybox:latest
cargo nextest run -p ide-host --test remote_daemon --run-ignored only \
-E 'test(=compose_service_survives_disconnect_and_is_removed_on_stop)'
# nextest skips doctests; ide-command's are its compile-fail tests.
- if: runner.os == 'Linux'
run: cargo test --doc -p ide-command
@@ -169,7 +178,7 @@ jobs:
name: Rust checks
needs: [changes, rust]
if: always()
runs-on: ubuntu-latest
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: 5
steps:
- env:
@@ -186,16 +195,27 @@ jobs:
needs: changes
if: needs.changes.outputs.server == 'true'
timeout-minutes: 40
runs-on: ubuntu-22.04
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' }}
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 }
- run: sudo apt-get update && sudo apt-get install -y musl-tools
- 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: cargo build --locked -p ide-host --bin openidea-server --target x86_64-unknown-linux-musl
- run: target/x86_64-unknown-linux-musl/debug/openidea-server --version
- run: '"${CARGO_TARGET_DIR:-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.
@@ -204,18 +224,31 @@ jobs:
needs: changes
if: needs.changes.outputs.plugins == 'true'
timeout-minutes: 30
runs-on: ubuntu-22.04
env:
CARGO_TARGET_DIR: ${{ github.workspace }}/target-plugins
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' }}
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: |
@@ -232,7 +265,7 @@ jobs:
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with: { node-version: 22 }
with: { node-version: 22, package-manager-cache: false }
# Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test.
- name: Web pages typecheck and test
shell: bash
@@ -256,7 +289,7 @@ jobs:
needs: changes
if: needs.changes.outputs.deny == 'true'
timeout-minutes: 15
runs-on: ubuntu-latest
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' }}
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
@@ -268,13 +301,19 @@ jobs:
needs: changes
if: needs.changes.outputs.frontend == 'true'
timeout-minutes: 30
runs-on: ubuntu-22.04
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' }}
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: pnpm }
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- run: pnpm install --frozen-lockfile
- run: pnpm typecheck
- run: pnpm lint
@@ -289,38 +328,41 @@ jobs:
needs: changes
if: needs.changes.outputs.catalog == 'true'
timeout-minutes: 15
runs-on: ubuntu-latest
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' }}
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm }
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- run: pnpm install --frozen-lockfile
- run: pnpm vitest run src/platform/locales/textCatalog.test.ts
e2e:
name: E2E (${{ matrix.shard }}/2)
name: E2E (${{ matrix.shard }}/4)
needs: changes
if: needs.changes.outputs.e2e == 'true'
timeout-minutes: 30
runs-on: ubuntu-24.04
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' }}
strategy:
fail-fast: false
matrix:
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
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm }
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- run: pnpm install --frozen-lockfile
- run: pnpm e2e --shard=${{ matrix.shard }}/2
env:
HOME: /root
- run: pnpm exec playwright install --with-deps chromium
- run: pnpm e2e --shard=${{ matrix.shard }}/4
- uses: actions/upload-artifact@v6
if: failure()
with:
+96 -23
Переглянути файл
@@ -57,6 +57,9 @@ 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).
@@ -72,7 +75,9 @@ jobs:
# run none; anything else runs them all. Pushes and manual runs always run them all.
changes:
name: Changes
runs-on: ubuntu-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: ${{ 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: 5
permissions:
pull-requests: read
@@ -132,41 +137,105 @@ jobs:
done < files.txt
echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT"
smoke:
name: Language smoke (${{ matrix.language }})
# Builds the smoke test binaries and openidea-server once for every language below.
build:
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' }}
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: 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
cargo test --locked -p ide-host --test language_smoke --test project_smoke --no-run --message-format=json \
| 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/
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.
tar -cf smoke-bin.tar smoke-bin
- uses: actions/upload-artifact@v6
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
smoke:
name: Language smoke (${{ matrix.language }})
needs: [changes, build]
strategy:
fail-fast: false
matrix:
language: ${{ fromJSON(needs.changes.outputs.languages) }}
# 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' }}
# 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' }}
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@v4
- uses: actions/checkout@v5
# 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
with: { components: "rust-analyzer, rustfmt" }
# One build cache for every language; main saves it.
- uses: Swatinem/rust-cache@v2
with:
shared-key: language-smoke
save-if: ${{ github.ref == 'refs/heads/main' && matrix.language == 'rust' }}
- uses: actions/download-artifact@v6
with: { name: smoke-bin }
- run: |
tar -xf smoke-bin.tar && rm smoke-bin.tar
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
- uses: pnpm/action-setup@v4
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v4
with: { node-version: 22, cache: pnpm }
- uses: actions/setup-node@v5
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- if: matrix.language == 'typescript'
run: npm install --global "@vtsls/language-server@$VTSLS" "typescript@$TYPESCRIPT"
# The smoke builds the c-app fixture and debugs it with GDB's own DAP interpreter.
# The smoke checks C/C++ with clangd and debugs c-app with GDB's own DAP interpreter (GDB 14+).
- if: matrix.language == 'c' || matrix.language == 'cpp'
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y gdb
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
- if: matrix.language == 'python'
uses: actions/setup-python@v5
@@ -185,6 +254,7 @@ 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"
@@ -209,17 +279,20 @@ jobs:
- if: matrix.language == 'php'
run: npm install --global "intelephense@$INTELEPHENSE"
- run: cargo test --locked -p ide-host --test language_smoke --no-run
- run: cargo test --locked -p ide-host --test language_smoke -- --ignored --exact ${{ matrix.language }}
# The binaries from the build job, run from the crate directory as `cargo test` does.
- working-directory: crates/ide-host
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
- if: matrix.language == 'java'
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
working-directory: crates/ide-host
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
- if: matrix.language == 'kotlin'
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact gradle_sync
working-directory: crates/ide-host
run: ../../smoke-bin/project_smoke --ignored --exact gradle_sync
- if: matrix.language == 'python'
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact python_venv
working-directory: crates/ide-host
run: ../../smoke-bin/project_smoke --ignored --exact python_venv
- run: pnpm install --frozen-lockfile
- run: cargo build --locked -p ide-host --bin openidea-server
- run: pnpm smoke smoke/run.test.ts -t "^${{ matrix.language }}$"
- run: pnpm smoke smoke/debug.test.ts -t "^${{ matrix.language }}$"
# The IDE installs the debugger from GitHub releases: authenticated, against rate limits.
Створено
+48 -48
Переглянути файл
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4172,7 +4172,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4184,7 +4184,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"serde",
@@ -4194,7 +4194,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"blake3",
"chardetng",
@@ -4212,7 +4212,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4226,7 +4226,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4237,7 +4237,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4248,7 +4248,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"dunce",
@@ -4266,7 +4266,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-run",
@@ -4279,7 +4279,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4308,7 +4308,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4345,7 +4345,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"serde",
@@ -4358,7 +4358,7 @@ dependencies = [
[[package]]
name = "ide-drag-out"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4372,7 +4372,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4392,7 +4392,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-android",
"ide-core",
@@ -4403,7 +4403,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4415,7 +4415,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4428,7 +4428,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"criterion",
"ide-core",
@@ -4447,7 +4447,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4522,7 +4522,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"hyper-util",
"ide-core",
@@ -4541,7 +4541,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"blake3",
"criterion",
@@ -4564,7 +4564,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4576,7 +4576,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4592,7 +4592,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"libc",
"tempfile",
@@ -4601,7 +4601,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"futures",
"serde",
@@ -4612,7 +4612,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"blake3",
"criterion",
@@ -4671,7 +4671,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"criterion",
"dunce",
@@ -4700,7 +4700,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"bytes",
"dunce",
@@ -4719,7 +4719,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-vfs",
@@ -4740,7 +4740,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"blake3",
"dunce",
@@ -4762,7 +4762,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4776,7 +4776,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"dunce",
"futures",
@@ -4796,7 +4796,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"dunce",
"encoding_rs",
@@ -4820,7 +4820,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-tools",
@@ -4836,7 +4836,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4862,7 +4862,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"criterion",
"encoding_rs",
@@ -4883,7 +4883,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"parking_lot",
@@ -4896,7 +4896,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4921,7 +4921,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-language",
@@ -4934,7 +4934,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-language",
@@ -4949,7 +4949,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"libc",
@@ -4963,7 +4963,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"criterion",
"ide-core",
@@ -4976,7 +4976,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"flate2",
"hex",
@@ -4997,7 +4997,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"blake3",
"dunce",
@@ -5019,7 +5019,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"chardetng",
"dunce",
@@ -5046,7 +5046,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5062,7 +5062,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"blake3",
"dunce",
@@ -6691,7 +6691,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"blake3",
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.50"
version = "0.1.51"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+36 -8
Переглянути файл
@@ -661,6 +661,15 @@ impl AgentManager {
self.shared.sinks.write().remove(subscriber);
}
pub fn has_live_work(&self) -> bool {
self.tasks.read().values().any(|task| {
let state = task.state.lock();
state.busy
|| !state.background_tasks.is_empty()
|| matches!(state.task.status, AgentStatus::Starting | AgentStatus::Running | AgentStatus::NeedsInput)
})
}
/// Sets the callback used to read the active command execution security policy.
pub fn set_security_hook(&self, hook: SecurityHook) {
*self.shared.security.write() = Some(hook);
@@ -2514,6 +2523,8 @@ impl Task {
/// the user stops one. The caller set `busy`.
async fn run(self: Arc<Self>, mut prompt: AgentPrompt) {
loop {
// The message shows before the checkout is recorded, which can take a while in a large repository.
self.show_prompt(&prompt);
self.checkout_before_turn().await;
let result = self.turn(&prompt).await;
self.cancel_pending.store(false, Ordering::Release);
@@ -2827,11 +2838,8 @@ impl Task {
Ok(())
}
/// Sends one prompt, starting the agent first if needed; returns the stop reason.
async fn turn(self: &Arc<Self>, prompt: &AgentPrompt) -> Result<String, Failure> {
self.turns.fetch_add(1, Ordering::AcqRel);
self.turn_started.store(false, Ordering::Release);
self.state.lock().task.resets_ms = None;
/// Adds the user's message to the conversation and shows the task starting.
fn show_prompt(self: &Arc<Self>, prompt: &AgentPrompt) {
let attachments = prompt
.files
.iter()
@@ -2849,6 +2857,13 @@ impl Task {
// Launching the agent can take a while (`npx` fetches its adapter on first use).
let starting = self.live.lock().as_ref().is_none_or(|l| l.peer.is_closed());
self.set_status(if starting { AgentStatus::Starting } else { AgentStatus::Running }, None);
}
/// Sends one prompt, starting the agent first if needed; returns the stop reason.
async fn turn(self: &Arc<Self>, prompt: &AgentPrompt) -> Result<String, Failure> {
self.turns.fetch_add(1, Ordering::AcqRel);
self.turn_started.store(false, Ordering::Release);
self.state.lock().task.resets_ms = None;
let mut live = self.ensure_session().await.map_err(Failure::from)?;
// Stopped while the agent started: the prompt is never sent.
if self.cancel_pending.load(Ordering::Acquire) {
@@ -4230,11 +4245,24 @@ fn file_uri(path: &Path) -> String {
out
}
/// 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.
/// 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.
fn title_of(prompt: &AgentPrompt) -> String {
let is_fence = |l: &str| l.starts_with("```") || l.starts_with("~~~");
let line = prompt.text.lines().map(str::trim).find(|l| !l.is_empty() && !is_fence(l));
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 = match line {
Some(l) => l.to_owned(),
None => prompt.files.first().map(|f| file_name(&f.0)).unwrap_or_else(|| "Image".into()),
+3
Переглянути файл
@@ -1736,6 +1736,9 @@ 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());
}
+3 -2
Переглянути файл
@@ -40,10 +40,11 @@ pub enum IdeEvent {
McpBackgroundProjectsChanged,
/// A window entered or left full screen, itself or as a member of a full-screen window group.
WindowFullscreenChanged,
/// This remote window's connection to its host ended on its own (network loss, the host or
/// its server went away); the window's project is unreachable until it reconnects.
/// This remote window's connection ended or another window took over the session.
RemoteConnectionLost {
host: String,
#[serde(default)]
taken_over: bool,
},
ProjectTrustChanged {
root: crate::IpcPath,
+14
Переглянути файл
@@ -4,6 +4,20 @@
use serde::{Deserialize, Serialize};
use specta::Type;
/// Tools › Remote Development. This is a user setting on the remote host.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct RemoteDevelopmentSettings {
/// Zero disables idle shutdown. Positive values from older configurations keep their meaning.
pub idle_timeout_minutes: u16,
}
impl Default for RemoteDevelopmentSettings {
fn default() -> Self {
Self { idle_timeout_minutes: 180 }
}
}
/// How an SSH connection authenticates.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+2
Переглянути файл
@@ -60,6 +60,7 @@ pub struct Settings {
pub spelling: SpellingSettings,
/// Tools › SSH Configurations.
pub ssh: SshSettings,
pub remote_development: RemoteDevelopmentSettings,
/// Build, Execution, Deployment › Deployment.
pub deployment: DeploymentSettings,
/// Build, Execution, Deployment › Run Targets.
@@ -578,6 +579,7 @@ impl Default for Settings {
inspections: InspectionSettings::default(),
spelling: SpellingSettings::default(),
ssh: SshSettings::default(),
remote_development: RemoteDevelopmentSettings::default(),
deployment: DeploymentSettings::default(),
run_targets: Vec::new(),
cmake: CMakeSettings::default(),
+56
Переглянути файл
@@ -557,6 +557,53 @@ 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)
}
@@ -1158,6 +1205,15 @@ 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]
+11
Переглянути файл
@@ -315,6 +315,17 @@ 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);
+27
Переглянути файл
@@ -473,6 +473,33 @@ 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 {
+9 -1
Переглянути файл
@@ -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_volumes,
parse_networks, parse_volume_sizes, parse_volumes,
};
const PS: &str = include_str!("fixtures/ps.jsonl");
@@ -113,4 +113,12 @@ 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());
}
+138 -39
Переглянути файл
@@ -1,5 +1,6 @@
//! `openidea-server --stdio`: the IDE backend for remote development, serving
//! one desktop client over stdin / stdout (started by the client over SSH).
//! `openidea-server`: the IDE backend for remote development, either serving one
//! desktop client over stdin / stdout (`--stdio`) or running as a persistent
//! per-project daemon (`--attach <project>`).
use ide_host::catalogue::TrustClass;
use ide_host::plugins::remote::{RemotePluginLanguages, SYNC_COMMAND};
@@ -10,6 +11,12 @@ use ide_language::LanguageRegistry;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
enum Mode {
Stdio,
#[cfg(unix)]
Daemon(PathBuf, ide_host::daemon::BuildId),
}
fn main() {
let raw_args: Vec<String> = std::env::args().collect();
if let Some(project) = ide_mcp::stdio_request(&raw_args) {
@@ -35,18 +42,48 @@ fn main() {
};
std::process::exit(code);
}
if !args.iter().any(|a| a == "--stdio") {
eprintln!(
"usage: openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <port> | --version"
);
std::process::exit(2);
let base = server_home();
#[cfg(unix)]
if args.first().is_some_and(|a| a == "--attach") {
let Some(project_path) = args.get(1).filter(|p| !p.is_empty()) else {
eprintln!("usage: openidea-server --attach <project-path>");
std::process::exit(2);
};
let home = dirs::home_dir().unwrap_or_default();
let code =
match ide_host::daemon::attach(&base, &home, project_path, std::io::stdin(), std::io::stdout().lock()) {
Ok(()) => 0,
Err(e) => {
eprintln!("{e}");
1
}
};
std::process::exit(code);
}
let mode = match args.as_slice() {
#[cfg(unix)]
[flag, sock, build] if flag == "--daemon" => {
let Ok(build) = build.as_bytes().try_into() else {
eprintln!("invalid daemon build identifier");
std::process::exit(2);
};
Mode::Daemon(PathBuf::from(sock), build)
}
#[cfg(not(unix))]
[flag, _] if flag == "--attach" => Mode::Stdio,
_ if args.iter().any(|a| a == "--stdio") => Mode::Stdio,
_ => {
eprintln!(
"usage: openidea-server --stdio | --attach <project-path> | --mcp-stdio [--project <path>] | --connect <host> <port> | --version"
);
std::process::exit(2);
}
};
// stdout carries the protocol: logs go to stderr.
tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_env_filter(tracing_subscriber::EnvFilter::try_from_env("OPENIDEA_LOG").unwrap_or_else(|_| "info".into()))
.init();
let base = server_home();
// An SSH exec channel gets a minimal environment: take the login shell's, read
// afresh on every start, plus the IDE-managed tools. Before any other thread starts.
ide_host::shell_env::inherit_login_shell_env("openidea-server");
@@ -55,7 +92,7 @@ fn main() {
ide_dap::adapter::set_tools_root(ide_tools::tools_dir(&data_dir));
ide_sdk::java::add_jdk_root(&ide_tools::jdk::jdks_dir(&data_dir));
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("tokio runtime");
let code = runtime.block_on(run(base));
let code = runtime.block_on(run(base, mode));
std::process::exit(code);
}
@@ -64,7 +101,7 @@ fn server_home() -> PathBuf {
std::env::var_os("OPENIDEA_SERVER_HOME").map(PathBuf::from).unwrap_or_else(|| home.join(".openidea"))
}
async fn run(base: PathBuf) -> i32 {
async fn run(base: PathBuf, mode: Mode) -> i32 {
let (config_dir, data_dir) = (base.join("config"), base.join("data"));
for dir in [&config_dir, &data_dir] {
if let Err(e) = std::fs::create_dir_all(dir) {
@@ -82,40 +119,103 @@ async fn run(base: PathBuf) -> i32 {
// The desktop's plugin languages (`plugin_sync_languages`); programs pinned on this machine.
let plugin_languages = RemotePluginLanguages::new(Some(&data_dir));
languages.attach_plugins(plugin_languages.store().clone());
let peer = Arc::new(OnceLock::new());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
// A stable path for `--mcp-stdio` client configurations across server upgrades.
match mode {
Mode::Stdio => {
let peer = Arc::new(OnceLock::new());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
start_mcp(&host, &base);
let plugins = start_plugins(&plugins_data, &host, peer.clone());
inherit_trust(&host);
tracing::info!("openidea-server {} ready", env!("CARGO_PKG_VERSION"));
let dispatcher = build_dispatcher(&plugins, plugin_languages);
rpc::serve(host.clone(), dispatcher, peer, tokio::io::stdin(), tokio::io::stdout()).await;
shutdown_all(&host, plugins.as_ref()).await;
0
}
#[cfg(unix)]
Mode::Daemon(socket, build) => {
let peer = Arc::new(rpc::PeerSlot::default());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
start_mcp(&host, &base);
let plugins = start_plugins(&plugins_data, &host, peer.clone());
inherit_trust(&host);
tracing::info!("openidea-server {} daemon ready at {}", env!("CARGO_PKG_VERSION"), socket.display());
let dispatcher = build_dispatcher(&plugins, plugin_languages);
let result = ide_host::daemon::serve(
&socket,
build,
host.clone(),
dispatcher,
peer,
shutdown_all(&host, plugins.as_ref()),
)
.await;
match result {
Ok(()) => 0,
Err(e) => {
eprintln!("daemon error: {e}");
1
}
}
}
}
}
fn start_mcp(host: &Arc<Host>, base: &std::path::Path) {
host.mcp.set_stdio_link(base.join("bin").join("openidea-server"));
host.mcp_background.serve_none();
host.mcp.apply(&host);
// The desktop's code plugins run here, next to the project (`plugin_sync_packages`).
let plugins = match RemotePlugins::start(&plugins_data, &host, peer.clone()) {
host.mcp.apply(host);
}
fn start_plugins<P: rpc::PeerHandle>(
plugins_data: &std::path::Path,
host: &Arc<Host>,
peer: Arc<P>,
) -> Option<Arc<RemotePlugins>> {
match RemotePlugins::start(plugins_data, host, peer) {
Ok(p) => Some(p),
Err(e) => {
tracing::warn!("plugins are unavailable: {e}");
None
}
};
}
}
fn inherit_trust(host: &Host) {
if let Some(root) = std::env::var_os(ide_host::trust::TRUSTED_ROOT_ENV)
&& let Err(e) = host.trust.inherit(std::path::Path::new(&root))
{
tracing::warn!("cannot trust {}: {e}", root.to_string_lossy());
}
tracing::info!("openidea-server {} ready", env!("CARGO_PKG_VERSION"));
}
fn build_dispatcher(plugins: &Option<Arc<RemotePlugins>>, plugin_languages: Arc<RemotePluginLanguages>) -> Dispatcher {
let mut dispatcher = Dispatcher::standard();
if let Some(plugins) = &plugins {
if let Some(plugins) = plugins {
plugins.register(&mut dispatcher);
}
dispatcher.add(SYNC_COMMAND, TrustClass::Trusted, move |c| {
@@ -126,14 +226,13 @@ async fn run(base: PathBuf) -> i32 {
Ok(report)
}
});
rpc::serve(host.clone(), dispatcher, peer, tokio::io::stdin(), tokio::io::stdout()).await;
host.mcp.stop(&host);
if let Some(plugins) = &plugins {
dispatcher
}
async fn shutdown_all(host: &Host, plugins: Option<&Arc<RemotePlugins>>) {
host.mcp.stop(host);
if let Some(plugins) = plugins {
plugins.host().shutdown();
}
// `process::exit` skips destructors: nothing started for the client may outlive it.
if tokio::time::timeout(std::time::Duration::from_secs(10), host.shutdown()).await.is_err() {
tracing::warn!("language servers did not shut down in time");
}
0
host.shutdown().await;
}
+482
Переглянути файл
@@ -0,0 +1,482 @@
//! Persistent per-project `openidea-server` daemon over a local Unix domain socket.
//!
//! * `openidea-server --attach <project_path>` connects to the daemon for `<project_path>`
//! (spawning it detached in a new session if none is listening) and bridges its own
//! stdin / stdout to the Unix socket. Closing the desktop window ends the SSH / WSL /
//! `docker exec` attach relay while the daemon — and its index, language servers,
//! terminals, runs and agent sessions — keeps running.
//! * `openidea-server --daemon <socket_path> <build>` is the process `--attach` starts.
use crate::Host;
use crate::rpc::{self, Dispatcher, PeerSlot, RemoteIdlePolicy};
use ide_core::CancellationToken;
use rustix::fs::{FlockOperation, flock};
use std::fs::{File, OpenOptions};
use std::future::{Future, pending};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::net::Shutdown;
use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt};
use std::os::unix::net::UnixStream;
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Arc, mpsc};
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::signal::unix::{SignalKind, signal};
/// Keep socket paths well below macOS (104) and Linux (108) `sun_path` limits.
const MAX_SUN_PATH: usize = 96;
const STARTUP_TIMEOUT: Duration = Duration::from_secs(15);
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(3);
const EOF_DRAIN: Duration = Duration::from_secs(2);
const EMPTY_IDLE_EXIT: Duration = Duration::from_secs(30);
const IDLE_ENV: &str = "OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS";
pub type BuildId = [u8; 16];
const ATTACHED: u8 = b'A';
const RETIRING: u8 = b'R';
const BUSY: u8 = b'B';
pub struct DaemonPaths {
pub key: String,
pub socket: PathBuf,
pub lock: PathBuf,
pub log: PathBuf,
}
/// Resolves `raw_path` (`~`, `~/…`, symlinks) the same way `open_project` does so
/// `~/repo` and `/home/user/repo` attach to the same daemon.
pub fn normalize_project_path(raw_path: &str, home: &Path) -> PathBuf {
let trimmed = raw_path.trim();
let expanded = if trimmed.is_empty() || trimmed == "~" {
home.to_path_buf()
} else if let Some(rest) = trimmed.strip_prefix("~/") {
home.join(rest)
} else {
PathBuf::from(trimmed)
};
let canonical = dunce::canonicalize(&expanded).unwrap_or(expanded);
let text = canonical.to_string_lossy();
if text.len() > 1 && text.ends_with('/') { PathBuf::from(text.trim_end_matches('/')) } else { canonical }
}
/// Deterministic socket, lock and log paths for a project and server home, across builds.
pub fn paths_for(base: &Path, home: &Path, raw_project_path: &str) -> io::Result<DaemonPaths> {
let project = normalize_project_path(raw_project_path, home);
std::fs::create_dir_all(base)?;
let base_canon = dunce::canonicalize(base).unwrap_or_else(|_| base.to_path_buf());
let mut hasher = blake3::Hasher::new();
hasher.update(project.as_os_str().as_encoded_bytes());
hasher.update(&[0]);
hasher.update(base_canon.as_os_str().as_encoded_bytes());
let key = hasher.finalize().to_hex()[..16].to_owned();
let sock_name = format!("s-{key}.sock");
let lock_name = format!("s-{key}.lock");
let preferred_dir = base.join("run");
let run_dir = if preferred_dir.join(&sock_name).as_os_str().len() <= MAX_SUN_PATH {
ensure_private_dir(&preferred_dir)?;
preferred_dir
} else {
let uid = rustix::process::geteuid().as_raw();
let fallback = PathBuf::from(format!("/tmp/openidea-{uid}"));
ensure_private_dir(&fallback)?;
fallback
};
let log_dir = base.join("logs");
std::fs::create_dir_all(&log_dir)?;
Ok(DaemonPaths {
socket: run_dir.join(sock_name),
lock: run_dir.join(lock_name),
log: log_dir.join(format!("server-{key}.log")),
key,
})
}
fn ensure_private_dir(dir: &Path) -> io::Result<()> {
if !dir.exists() {
let mut builder = std::fs::DirBuilder::new();
builder.recursive(true).mode(0o700);
builder.create(dir)?;
}
let meta = std::fs::symlink_metadata(dir)?;
if meta.file_type().is_symlink() || !meta.is_dir() {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{} is not a private directory", dir.display()),
));
}
let uid = rustix::process::geteuid().as_raw();
if meta.uid() != uid {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{} is owned by uid {}, expected {uid}", dir.display(), meta.uid()),
));
}
if meta.mode() & 0o077 != 0 {
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
}
Ok(())
}
/// Connects to the daemon for `project_path` (spawning it if needed) and bridges
/// `input` / `output` to its Unix socket.
pub fn attach(
base: &Path,
home: &Path,
project_path: &str,
input: impl Read + Send + 'static,
output: impl Write,
) -> Result<(), String> {
let exe = std::env::current_exe().map_err(|e| format!("cannot locate openidea-server: {e}"))?;
let paths = paths_for(base, home, project_path).map_err(|e| format!("cannot prepare runtime dir: {e}"))?;
let mut hasher = blake3::Hasher::new();
hasher
.update_reader(File::open(&exe).map_err(|e| format!("cannot open openidea-server: {e}"))?)
.map_err(|e| format!("cannot identify openidea-server build: {e}"))?;
let hex = hasher.finalize().to_hex();
let build = &hex.as_str()[..16];
let stream = connect_or_spawn(&exe, &paths, build)?;
bridge(stream, input, output).map_err(|e| format!("daemon relay failed: {e}"))
}
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result<UnixStream, String> {
let lock_file = OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.mode(0o600)
.open(&paths.lock)
.map_err(|e| format!("cannot open {}: {e}", paths.lock.display()))?;
flock(&lock_file, FlockOperation::LockExclusive)
.map_err(|e| format!("cannot lock {}: {e}", paths.lock.display()))?;
if let Some(stream) = existing_daemon(paths, build)? {
return Ok(stream);
}
match std::fs::remove_file(&paths.socket) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(format!("cannot remove stale socket {}: {e}", paths.socket.display())),
}
let mut log_file = OpenOptions::new()
.create(true)
.append(true)
.read(true)
.mode(0o600)
.open(&paths.log)
.map_err(|e| format!("cannot open {}: {e}", paths.log.display()))?;
let log_offset = log_file.metadata().map(|m| m.len()).unwrap_or(0);
let stderr_file = log_file.try_clone().map_err(|e| format!("cannot clone log handle: {e}"))?;
let mut cmd = Command::new(exe);
cmd.arg("--daemon")
.arg(&paths.socket)
.arg(build)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(stderr_file));
// SAFETY: `setsid` is an async-signal-safe POSIX call that detaches the daemon into
// a new session without a controlling terminal, outliving the SSH / WSL / docker exec call.
unsafe {
cmd.pre_exec(|| {
let _ = rustix::process::setsid();
Ok(())
});
}
let mut child = cmd.spawn().map_err(|e| format!("cannot spawn openidea-server daemon: {e}"))?;
let deadline = Instant::now() + STARTUP_TIMEOUT;
loop {
if let Some(stream) = existing_daemon(paths, build)? {
return Ok(stream);
}
if let Ok(Some(status)) = child.try_wait() {
let tail = read_log_tail(&mut log_file, log_offset);
let detail = if tail.is_empty() { format!("exited with {status}") } else { tail };
return Err(format!("openidea-server daemon failed to start: {detail}"));
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
let tail = read_log_tail(&mut log_file, log_offset);
let detail = if tail.is_empty() { "timed out waiting for socket".to_owned() } else { tail };
return Err(format!("openidea-server daemon did not start: {detail}"));
}
std::thread::sleep(Duration::from_millis(15));
}
}
fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream>, String> {
let exchange = |mut stream: UnixStream| -> io::Result<Option<UnixStream>> {
stream.set_read_timeout(Some(HANDSHAKE_TIMEOUT))?;
stream.set_write_timeout(Some(HANDSHAKE_TIMEOUT))?;
stream.write_all(build.as_bytes())?;
let mut reply = [0];
stream.read_exact(&mut reply)?;
match reply[0] {
ATTACHED => {
stream.set_read_timeout(None)?;
stream.set_write_timeout(None)?;
Ok(Some(stream))
}
RETIRING => {
// This stream stays open until project cleanup and socket removal finish.
stream.set_read_timeout(Some(rpc::SHUTDOWN_TIMEOUT))?;
if stream.read(&mut reply)? == 0 {
Ok(None)
} else {
Err(io::Error::other("unexpected response from stopping daemon"))
}
}
BUSY => Err(io::Error::other(
"Another build of OpenIDEA still has this project open, is running tasks, or has unsaved changes. \
Reconnect with that build, then stop the remote backend before upgrading.",
)),
_ => Err(io::Error::other("unrecognized remote backend response")),
}
};
let stream = match UnixStream::connect(&paths.socket) {
Ok(stream) => stream,
Err(e) if matches!(e.kind(), io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused) => return Ok(None),
Err(e) => return Err(format!("cannot connect to remote backend at {}: {e}", paths.socket.display())),
};
exchange(stream).map_err(|e| format!("cannot attach to {}: {e}", paths.socket.display()))
}
fn read_log_tail(file: &mut File, offset: u64) -> String {
if file.seek(SeekFrom::Start(offset)).is_err() {
return String::new();
}
let mut text = String::new();
let _ = file.read_to_string(&mut text);
text.trim().to_owned()
}
/// Copies `input` to `stream` and `stream` to `output`, returning promptly when either
/// side closes.
pub fn bridge(
mut from_daemon: UnixStream,
mut input: impl Read + Send + 'static,
mut output: impl Write,
) -> io::Result<()> {
from_daemon.set_read_timeout(Some(Duration::from_millis(100)))?;
let mut to_daemon = from_daemon.try_clone()?;
let (eof_tx, eof_rx) = mpsc::channel();
std::thread::spawn(move || {
let mut buf = [0u8; 16 * 1024];
loop {
match input.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
if to_daemon.write_all(&buf[..n]).is_err() {
break;
}
}
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
Err(_) => break,
}
}
let _ = to_daemon.shutdown(Shutdown::Write);
let _ = eof_tx.send(Instant::now());
});
let mut buf = [0u8; 16 * 1024];
let mut input_closed: Option<Instant> = None;
loop {
if let Ok(at) = eof_rx.try_recv() {
input_closed = Some(at);
}
if input_closed.is_some_and(|at| at.elapsed() >= EOF_DRAIN) {
break;
}
match from_daemon.read(&mut buf) {
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => continue,
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
Ok(0) | Err(_) => break,
Ok(n) => {
if output.write_all(&buf[..n]).and_then(|()| output.flush()).is_err() {
break;
}
}
}
}
let _ = from_daemon.shutdown(Shutdown::Both);
Ok(())
}
/// The socket remains bound until cleanup finishes, so an attach can't start a
/// replacement while the previous backend is still stopping its processes.
pub async fn serve(
socket_path: &Path,
build: BuildId,
host: Arc<Host>,
dispatcher: Dispatcher,
slot: Arc<PeerSlot>,
cleanup: impl Future<Output = ()>,
) -> io::Result<()> {
let start = || {
if let Some(parent) = socket_path.parent() {
ensure_private_dir(parent)?;
}
let terminate = signal(SignalKind::terminate())?;
let listener = tokio::net::UnixListener::bind(socket_path)?;
if let Err(e) = std::fs::set_permissions(socket_path, std::fs::Permissions::from_mode(0o600)) {
let _ = std::fs::remove_file(socket_path);
return Err(e);
}
Ok((listener, terminate))
};
let (listener, mut terminate) = match start() {
Ok(started) => started,
Err(e) => {
cleanup.await;
return Err(e);
}
};
let shutdown = CancellationToken::new();
let idle_policy = RemoteIdlePolicy { override_seconds: idle_override() };
let mut check = tokio::time::interval(Duration::from_secs(idle_policy.override_seconds.unwrap_or(5).min(5)));
let mut idle = None;
let mut retiring = None;
let mut active: Option<ide_jsonrpc::Peer> = None;
let result = loop {
tokio::select! {
_ = shutdown.cancelled() => break Ok(()),
_ = terminate.recv() => break Ok(()),
_ = async {
match &active {
Some(peer) => { peer.closed().await; }
None => pending().await,
}
} => {
active = None;
slot.remove();
host.client_disconnected();
idle = None;
}
accepted = listener.accept() => {
let mut stream = match accepted {
Ok((stream, _)) => stream,
Err(e) => break Err(e),
};
let mut requested_build = [0; 16];
if !matches!(
tokio::time::timeout(HANDSHAKE_TIMEOUT, stream.read_exact(&mut requested_build)).await,
Ok(Ok(_))
) {
continue;
}
if active.as_ref().is_some_and(ide_jsonrpc::Peer::is_closed) {
active = None;
slot.remove();
host.client_disconnected();
idle = None;
}
if shutdown.is_cancelled() {
break Ok(());
}
if requested_build != build {
let busy = active.is_some() || has_live_work(&host);
if busy {
let _ = stream.write_u8(BUSY).await;
} else if stream.write_u8(RETIRING).await.is_ok() {
retiring = Some(stream);
break Ok(());
}
continue;
}
if stream.write_u8(ATTACHED).await.is_err() {
continue;
}
if let Some(old) = slot.remove() {
// Await an acknowledgement before tearing down the old transport.
let _ = tokio::time::timeout(
Duration::from_millis(750),
old.request::<_, ()>(rpc::SESSION_REPLACED, (), None),
).await;
old.kill();
host.client_disconnected();
}
let (reader, writer) = stream.into_split();
active = Some(rpc::connect_persistent(
host.clone(), dispatcher.clone(), slot.clone(), shutdown.clone(), idle_policy, reader, writer,
));
idle = None;
}
_ = check.tick() => {
if active.is_some() || has_live_work(&host) {
idle = None;
} else {
if idle.is_none() {
let since = Instant::now();
let timeout = match disconnected_timeout(&host, idle_policy).await {
Ok(timeout) => timeout,
Err(e) => break Err(e),
};
idle = Some((since, timeout));
}
if let Some((since, Some(timeout))) = idle && since.elapsed() >= timeout {
tracing::info!("idle openidea-server daemon exiting");
break Ok(());
}
}
}
}
};
shutdown.cancel();
slot.remove();
if let Some(peer) = &active {
let _ = tokio::time::timeout(HANDSHAKE_TIMEOUT, peer.flush()).await;
host.client_disconnected();
}
cleanup.await;
if let Err(e) = std::fs::remove_file(socket_path) {
tracing::warn!("cannot remove remote backend socket {}: {e}", socket_path.display());
}
if let Some(active) = active {
active.kill();
}
drop(retiring);
result
}
fn idle_override() -> Option<u64> {
if let Some(value) = std::env::var_os(IDLE_ENV) {
if let Some(seconds) = value.to_str().and_then(|s| s.parse::<u64>().ok()).filter(|&n| n > 0) {
return Some(seconds);
}
tracing::warn!("{IDLE_ENV} must be a positive number of seconds; using the host setting");
}
None
}
async fn disconnected_timeout(host: &Arc<Host>, policy: RemoteIdlePolicy) -> io::Result<Option<Duration>> {
let override_timeout = policy.override_seconds.map(Duration::from_secs);
if host.projects().is_empty() {
return Ok(Some(override_timeout.unwrap_or(EMPTY_IDLE_EXIT).min(EMPTY_IDLE_EXIT)));
}
if let Some(timeout) = override_timeout {
return Ok(Some(timeout));
}
let minutes = crate::ops::project::remote_idle_timeout_minutes(host).await.map_err(io::Error::other)?;
Ok((minutes != 0).then(|| Duration::from_secs(u64::from(minutes) * 60)))
}
/// Keeps a disconnected daemon alive: expiring would end this work, or lose the unsaved
/// edits a dropped connection left behind.
fn has_live_work(host: &Host) -> bool {
!host.terminals.list().is_empty()
|| host.processes.has_live_runs()
|| !host.debugger.sessions(None).is_empty()
|| host
.projects()
.iter()
.any(|project| project.agents.has_live_work() || project.documents.has_unsaved_changes())
}
+40 -9
Переглянути файл
@@ -5,6 +5,8 @@
pub mod agent_secrets;
pub mod catalogue;
#[cfg(unix)]
pub mod daemon;
pub mod data_dirs;
pub mod diagnostics_store;
mod direnv;
@@ -526,6 +528,25 @@ impl Host {
}
}
/// Cleans up per-connection client state when a remote window disconnects from a
/// persistent daemon, leaving the project, index, language servers, terminals,
/// runs and agent sessions running.
pub fn client_disconnected(&self) {
let windows: Vec<String> = self.projects.read().keys().cloned().collect();
for window in &windows {
self.mcp_reports.forget_window(window);
self.mcp_requests.forget_window(window);
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
self.cancel_request(request);
}
}
self.terminals.detach_output();
self.processes.detach_output();
for project in self.projects() {
project.documents.release_client_refs();
}
}
/// Stops what this host started: heap snapshots, notebook kernels, language servers, agents,
/// runs and terminals.
/// For a process that exits without dropping the host (the remote server).
@@ -533,7 +554,6 @@ impl Host {
// A capture's dump may hold secrets from the debuggee's memory: delete it before exiting.
ops::heap::shutdown(self).await;
self.environment.shutdown();
self.processes.kill_all();
self.terminals.kill_all();
let projects: Vec<_> = self.projects.write().drain().map(|(_, p)| p).collect();
for project in &projects {
@@ -553,22 +573,33 @@ impl Host {
project.notebooks.stop_admission();
project.agents.shutdown();
}
let stop_processes = async {
for project in &projects {
self.debugger.stop_under(&project.root).await;
}
self.processes.shutdown().await;
};
// Kernel cleanup owns its interrupt/termination/reaping deadlines. An
// outer LSP timeout must never abort it before owned children are reaped.
for project in &projects {
if let Some(bridge) = &project.kotlin_bridge {
bridge.shutdown().await;
let stop_kernels = async {
for project in &projects {
if let Some(bridge) = &project.kotlin_bridge {
bridge.shutdown().await;
}
project.notebooks.shutdown().await;
}
project.notebooks.shutdown().await;
}
};
let stop_language_servers = async {
for project in &projects {
project.lsp.shutdown_all().await;
}
};
if tokio::time::timeout(std::time::Duration::from_secs(10), stop_language_servers).await.is_err() {
tracing::warn!("language servers did not shut down in time");
}
let stop_lsp = async {
if tokio::time::timeout(std::time::Duration::from_secs(10), stop_language_servers).await.is_err() {
tracing::warn!("language servers did not shut down in time");
}
};
tokio::join!(stop_processes, stop_kernels, stop_lsp);
}
// ---- cancellable requests: the UI allocates ids, `cancel_request` cancels ----
+10
Переглянути файл
@@ -87,6 +87,15 @@ pub fn settings_get_global(host: &Host) -> Settings {
host.with_proxy_password(host.global_settings.effective())
}
/// Read the same host-wide value for the close dialog and the idle timer: another project's
/// daemon may have edited the file since this host loaded its settings.
#[command(trust = always)]
pub async fn remote_idle_timeout_minutes(host: &Arc<Host>) -> IdeResult<u16> {
let h = host.clone();
host.blocking(move || Ok(h.global_settings.layer(SettingsScope::Global).remote_development.idle_timeout_minutes))
.await
}
/// The removed built-in theme id a settings file of this window still names, if any:
/// `settings_get` reports the built-in that stands in for it, so the notice about
/// a theme that moved to a plugin can address the installs it concerns.
@@ -481,6 +490,7 @@ ide_command::domain!(
project_trust_status,
project_workspace_member_set,
project_workspace_members,
remote_idle_timeout_minutes,
settings_get,
settings_get_global,
settings_removed_theme,
+15 -1
Переглянути файл
@@ -3,7 +3,7 @@ use crate::Host;
use ide_command::command;
use ide_core::remote_settings::RunTargetKind;
use ide_core::{IdeError, IdeResult, RunId};
use ide_run::{OutputChunk, RunConfig, RunInfo, StartOptions};
use ide_run::{OutputChunk, RunAttach, RunConfig, RunInfo, StartOptions};
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
@@ -644,6 +644,19 @@ pub fn run_list(host: &Host) -> Vec<RunInfo> {
runs
}
/// Reattaches to a running process `id` on this host, returning its buffered output
/// and configuration while streaming subsequent chunks to `on_output`.
#[command(trust = always)]
pub async fn run_attach(host: &Host, window: &str, id: RunId, on_output: Channel<OutputChunk>) -> IdeResult<RunAttach> {
host.processes.reattach(
id,
host.window_sink(window),
Box::new(move |chunk| {
let _ = on_output.send(chunk);
}),
)
}
pub mod commands;
pub(crate) mod container;
pub use commands::*;
@@ -816,6 +829,7 @@ mod ownership_tests {
ide_command::domain!(
run:
run_apply_settings,
run_attach,
run_close_stdin,
run_configs,
run_list,
+34 -1
Переглянути файл
@@ -2,7 +2,7 @@ use super::{Channel, Emit};
use crate::Host;
use ide_command::command;
use ide_core::{IdeResult, IpcBytes, TerminalId};
use ide_terminal::{TerminalInfo, TerminalOptions};
use ide_terminal::{TerminalAttach, TerminalInfo, TerminalOptions, TerminalSessionInfo};
mod images;
@@ -53,6 +53,7 @@ pub async fn term_spawn(
Box::new(move |chunk| {
let _ = on_output.send(chunk);
}),
None,
)?;
if let Some(line) = activation {
let _ = host.terminals.write(info.id, &format!(" {line}\r"));
@@ -160,6 +161,36 @@ pub fn term_kill(host: &Host, id: TerminalId) -> IdeResult<()> {
host.terminals.kill(id)
}
/// Live terminal sessions of this window, for reattaching after a reconnect.
#[command(trust = always)]
pub async fn term_list(host: &Host, window: &str) -> Vec<TerminalSessionInfo> {
host.terminals.list_key(host.owner_window(window))
}
/// Reattaches to an existing terminal session `id`, returning its buffered output
/// and streaming subsequent chunks to `on_output`.
#[command(trust = always)]
pub async fn term_attach(
host: &Host,
window: &str,
id: TerminalId,
cols: u16,
rows: u16,
on_output: Channel<String>,
) -> IdeResult<TerminalAttach> {
let key = host.owner_window(window);
host.terminals.reattach(
id,
key,
cols,
rows,
host.window_sink(window),
Box::new(move |chunk| {
let _ = on_output.send(chunk);
}),
)
}
/// Whether the session is running a command (closing its tab asks first). A
/// `tcgetpgrp` or one process snapshot: async only to stay off the main thread.
#[command(trust = always)]
@@ -202,10 +233,12 @@ mod tests {
ide_command::domain!(
term:
term_attach,
term_available_shells,
term_default_shell,
term_is_busy,
term_kill,
term_list,
term_resize,
term_spawn,
term_store_image,
+10 -10
Переглянути файл
@@ -20,17 +20,16 @@
use super::{Consent, HostWorkspace, PluginEvent, PluginHost, PluginSource, SecretStore};
use crate::catalogue::TrustClass;
use crate::rpc::Dispatcher;
use crate::rpc::{Dispatcher, PeerHandle};
use base64::Engine as _;
use ide_core::{IdeError, IdeResult};
use ide_extension::{MANIFEST_FILE, ledger};
use ide_jsonrpc::Peer;
use ide_plugin::Limits;
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, OnceLock, Weak};
use std::sync::{Arc, Weak};
use std::time::Duration;
/// The server command the desktop calls with its packages.
@@ -246,13 +245,13 @@ pub struct RemotePlugins {
/// Secrets from the desktop's keychain, asked for when used.
struct ClientSecrets {
peer: Arc<OnceLock<Peer>>,
peer: Arc<dyn PeerHandle>,
runtime: tokio::runtime::Handle,
}
impl SecretStore for ClientSecrets {
fn get(&self, plugin: &str, name: &str) -> Option<String> {
let peer = self.peer.get()?.clone();
let peer = self.peer.current()?;
let request = SecretRequest { plugin: plugin.to_owned(), name: name.to_owned() };
let ask = async move {
tokio::time::timeout(SECRET_TIMEOUT, peer.request::<_, Option<String>>(SECRET_REQUEST, request, None)).await
@@ -275,7 +274,7 @@ impl SecretStore for ClientSecrets {
}
fn set(&self, plugin: &str, name: &str, value: Option<&str>) -> Result<(), String> {
let peer = self.peer.get().ok_or("desktop disconnected")?.clone();
let peer = self.peer.current().ok_or("desktop disconnected")?;
let request = SecretWrite { plugin: plugin.into(), name: name.into(), value: value.map(str::to_owned) };
let ask = async {
tokio::time::timeout(SECRET_TIMEOUT, peer.request::<_, Result<(), String>>(SECRET_WRITE, request, None))
@@ -293,11 +292,12 @@ impl SecretStore for ClientSecrets {
impl RemotePlugins {
/// Creates the host over `<data_dir>/remote-plugins`, loads what earlier
/// sessions installed and starts event delivery and supervision.
pub fn start(data_dir: &Path, projects: &Arc<crate::Host>, peer: Arc<OnceLock<Peer>>) -> IdeResult<Arc<Self>> {
pub fn start<P: PeerHandle>(data_dir: &Path, projects: &Arc<crate::Host>, peer: Arc<P>) -> IdeResult<Arc<Self>> {
let peer: Arc<dyn PeerHandle> = peer;
let sink_peer = peer.clone();
let sink = move |client: Option<&str>, event: PluginEvent| {
if forwarded(&event)
&& let Some(p) = sink_peer.get()
&& let Some(p) = sink_peer.current()
{
let _ = p.notify(EVENT_NOTIFICATION, PluginEventMessage { window: client.map(str::to_owned), event });
}
@@ -486,7 +486,7 @@ fn safe_relative(path: &str) -> IdeResult<PathBuf> {
}
struct ClientLoopbacks {
peer: Arc<OnceLock<Peer>>,
peer: Arc<dyn PeerHandle>,
runtime: tokio::runtime::Handle,
}
impl ClientLoopbacks {
@@ -496,7 +496,7 @@ impl ClientLoopbacks {
operation: AuthOperation,
cancel: Option<ide_core::CancellationToken>,
) -> Result<serde_json::Value, ide_plugin::HostError> {
let peer = self.peer.get().ok_or(ide_plugin::HostError::Cancelled)?.clone();
let peer = self.peer.current().ok_or(ide_plugin::HostError::Cancelled)?;
let timeout = match &operation {
AuthOperation::Wait { timeout_ms, .. } => Duration::from_millis(u64::from(*timeout_ms)) + SECRET_TIMEOUT,
_ => SECRET_TIMEOUT,
+3 -12
Переглянути файл
@@ -16,7 +16,6 @@ use ide_extension::{Package, check_relative};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
/// Most files under one web root.
const MAX_FILES: usize = 4096;
@@ -169,7 +168,7 @@ impl PluginHost {
plugin_id: &str,
window: &str,
output: crate::ops::Emit<String>,
completion: Option<Arc<dyn Fn(Option<i32>) + Send + Sync>>,
completion: Option<ide_terminal::TerminalExitHook>,
options: impl FnOnce() -> IdeResult<ide_terminal::TerminalOptions>,
) -> IdeResult<ide_terminal::TerminalInfo> {
let _guard = self.lifecycle.lock();
@@ -184,20 +183,12 @@ impl PluginHost {
return Err(IdeError::invalid("a plugin may own at most 8 PTYs"));
}
let cwd = options.cwd.0.clone();
let previous = host.window_sink(window);
let sink: Arc<dyn ide_core::EventSink> = Arc::new(move |event: ide_core::IdeEvent| {
if let ide_core::IdeEvent::TerminalExited { code, .. } = &event
&& let Some(completion) = &completion
{
completion(*code);
}
previous.emit(event);
});
let info = host.terminals.spawn_program(
options,
host.owner_window(window).to_owned(),
sink,
host.window_sink(window),
Box::new(move |data| output(data)),
completion,
)?;
if !self
.shared
+115 -4
Переглянути файл
@@ -76,6 +76,8 @@ pub struct Project {
/// watchers for (a virtualenv elsewhere, a path dependency).
lsp_watchers: Mutex<Vec<(PathBuf, Watcher)>>,
pub(crate) _scratch_watcher: Option<Watcher>,
/// Git metadata of repositories whose git directory lies outside the project folder.
pub(crate) git_metadata: Option<Arc<ide_vcs::MetadataWatch>>,
/// Picks up data sources edited on disk outside the Database tool window.
_db_sources_watch: Option<ide_db::SourcesWatch>,
/// A LightEdit window's loose files ([`Host::open_light`]): global settings only,
@@ -106,6 +108,14 @@ impl Host {
&& current.root == root
&& !current.light
{
let status = current.index.status();
if status.indexing {
current.sink.emit(IdeEvent::IndexState {
indexing: true,
files: status.files,
symbols: status.symbols,
});
}
return Ok(current);
}
// A window takes the root over from the MCP server's background project, whose
@@ -377,6 +387,10 @@ impl Host {
for repo in repos.read().all() {
repo.set_execution_allowed(trusted.load(Ordering::Acquire));
}
let git_metadata = git_metadata_watch(&root, &sink);
if let Some(watch) = &git_metadata {
watch.set_repos(repos.read().all(), &root);
}
// Shared handle: `unwatched_reason` is a live query on the watcher,
// filled after `start` returns so the on-change callback can reach it.
let watcher_weak = Arc::new(std::sync::OnceLock::<std::sync::Weak<Watcher>>::new());
@@ -390,6 +404,7 @@ impl Host {
let kotlin_bridge = kotlin_bridge.clone();
let phpstan = phpstan.clone();
let repos = repos.clone();
let git_metadata = git_metadata.clone();
let settings = settings.clone();
let index = index.clone();
let documents = documents.clone();
@@ -513,6 +528,7 @@ impl Host {
scan_repositories(
&root,
&repos,
git_metadata.as_deref(),
&settings,
&sink,
&build_cache,
@@ -603,11 +619,11 @@ impl Host {
mark("watcher");
{
let (root, repos, settings, sink) = (root.clone(), repos.clone(), settings.clone(), sink.clone());
let build_cache = build_cache.clone();
let (build_cache, git_metadata) = (build_cache.clone(), git_metadata.clone());
let trusted = trusted.load(Ordering::Acquire);
std::thread::Builder::new()
.name("openidea-vcs-roots".into())
.spawn(move || scan_repositories(&root, &repos, &settings, &sink, &build_cache, trusted))?;
std::thread::Builder::new().name("openidea-vcs-roots".into()).spawn(move || {
scan_repositories(&root, &repos, git_metadata.as_deref(), &settings, &sink, &build_cache, trusted)
})?;
}
mark("git");
tracing::info!("opened {} in window {window} in {} ms {laps:?}", root.display(), started.elapsed().as_millis());
@@ -656,6 +672,7 @@ impl Host {
content_watchers: Mutex::new(content_watchers),
lsp_watchers: Mutex::new(Vec::new()),
_scratch_watcher: scratch_watcher,
git_metadata,
_db_sources_watch: db_sources_watch,
files_events_active,
light: false,
@@ -903,6 +920,7 @@ impl Host {
content_watchers: Mutex::new(Vec::new()),
lsp_watchers: Mutex::new(Vec::new()),
_scratch_watcher: None,
git_metadata: None,
_db_sources_watch: None,
files_events_active: Arc::new(AtomicBool::new(false)),
light: true,
@@ -1006,6 +1024,7 @@ fn light_watcher(
fn scan_repositories(
root: &Path,
repos: &RwLock<Repos>,
git_metadata: Option<&ide_vcs::MetadataWatch>,
settings: &SettingsStore,
sink: &SharedSink,
build_cache: &Path,
@@ -1014,6 +1033,9 @@ fn scan_repositories(
match discover_repositories(root, settings, build_cache, trusted) {
Ok(found) => {
if found.roots() != repos.read().roots() {
if let Some(watch) = git_metadata {
watch.set_repos(found.all(), root);
}
*repos.write() = found;
sink.emit(IdeEvent::VcsChanged { root: root.to_path_buf().into() });
}
@@ -1067,6 +1089,7 @@ impl Project {
scan_repositories(
&self.root,
&self.repos,
self.git_metadata.as_deref(),
&self.settings,
&self.sink,
&self.build_cache_dir(),
@@ -2321,6 +2344,20 @@ mod maven_linkage_tests {
}
}
/// Commits, checkouts and resets made outside the IDE in a git directory the project
/// watcher doesn't see (the project is a subfolder of its repository, or a linked worktree).
fn git_metadata_watch(root: &Path, sink: &SharedSink) -> Option<Arc<ide_vcs::MetadataWatch>> {
let (root, sink) = (root.to_path_buf(), sink.clone());
ide_vcs::MetadataWatch::new(move |paths| {
if paths.iter().any(|p| vcs_path_changed(p)) {
sink.emit(IdeEvent::VcsChanged { root: root.clone().into() });
}
})
.map(Arc::new)
.map_err(|e| tracing::warn!("{}", e.message))
.ok()
}
fn vcs_path_changed(path: &Path) -> bool {
!path.ends_with(".git/index") || !ide_vcs::is_own_index_write(path)
}
@@ -2605,3 +2642,77 @@ mod content_roots_tests {
assert_eq!(members[&root], ["/dist", "/target"]);
}
}
#[cfg(test)]
mod external_git_metadata_tests {
use crate::{Host, HostConfig};
use ide_core::{IdeEvent, SharedSink};
use parking_lot::Mutex;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
fn git(dir: &Path, args: &[&str]) {
let out = std::process::Command::new("git")
.current_dir(dir)
.args(["-c", "[email protected]", "-c", "user.name=t", "-c", "commit.gpgsign=false"])
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
}
/// A commit made in a terminal refreshes the project's VCS state when the project folder
/// is the repository root, a subfolder of it, or a linked worktree, and for a submodule.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn external_commits_refresh_vcs_wherever_the_git_dir_lives() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let main = base.join("main");
std::fs::create_dir_all(main.join("sub")).unwrap();
git(&main, &["init", "-q", "-b", "main"]);
git(&main, &["commit", "-q", "--allow-empty", "-m", "init"]);
git(&main, &["worktree", "add", "-q", "-b", "topic", base.join("wt").to_str().unwrap()]);
let lib = base.join("lib");
std::fs::create_dir(&lib).unwrap();
git(&lib, &["init", "-q", "-b", "main"]);
git(&lib, &["commit", "-q", "--allow-empty", "-m", "init"]);
let sup = base.join("super");
std::fs::create_dir(&sup).unwrap();
git(&sup, &["init", "-q", "-b", "main"]);
git(&sup, &["-c", "protocol.file.allow=always", "submodule", "add", "-q", lib.to_str().unwrap(), "lib"]);
git(&sup, &["commit", "-q", "-m", "submodule"]);
let seen = Arc::new(Mutex::new(0usize));
let counted = seen.clone();
let sink: SharedSink = Arc::new(move |e: IdeEvent| {
if matches!(e, IdeEvent::VcsChanged { .. }) {
*counted.lock() += 1;
}
});
let host = Host::new(HostConfig {
sink_for: Box::new(move |_| sink.clone()),
local_data_dir: base.join("local"),
..HostConfig::for_test(&base)
});
let cases = [
(main.clone(), main.clone()),
(main.join("sub"), main.join("sub")),
(base.join("wt"), base.join("wt")),
(sup.clone(), sup.join("lib")),
];
for (project, repo) in cases {
host.open_project("main", &project).unwrap();
std::thread::sleep(Duration::from_millis(1500));
*seen.lock() = 0;
std::fs::write(repo.join("a.txt"), repo.to_string_lossy().as_bytes()).unwrap();
git(&repo, &["add", "a.txt"]);
git(&repo, &["commit", "-q", "-m", "change"]);
let deadline = Instant::now() + Duration::from_secs(10);
while *seen.lock() == 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(50));
}
assert!(*seen.lock() > 0, "no VcsChanged for a commit in {}", repo.display());
host.close_project("main");
}
}
}
+135 -16
Переглянути файл
@@ -29,6 +29,15 @@ use std::sync::{Arc, OnceLock};
/// 3: binary arguments (`IpcBytes`) are base64 strings, not arrays of numbers.
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);
/// Advertised only by a persistent backend with an editable idle timeout.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct RemoteIdlePolicy {
pub override_seconds: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -38,6 +47,8 @@ pub struct ServerInfo {
pub os: String,
pub arch: String,
pub home: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub idle_policy: Option<RemoteIdlePolicy>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -60,12 +71,71 @@ pub struct ChannelMessage {
pub data: Value,
}
/// Holds the active client [`Peer`]: once for `--stdio` ([`OnceLock<Peer>`]) or
/// rebound across client reconnects for a persistent daemon ([`PeerSlot`]).
pub trait PeerHandle: Send + Sync + 'static {
fn current(&self) -> Option<Peer>;
fn install(&self, peer: Peer) -> (u64, Option<Peer>);
fn clear(&self, generation: u64) -> bool;
}
impl PeerHandle for OnceLock<Peer> {
fn current(&self) -> Option<Peer> {
self.get().cloned()
}
fn install(&self, peer: Peer) -> (u64, Option<Peer>) {
let _ = self.set(peer);
(1, None)
}
fn clear(&self, _: u64) -> bool {
true
}
}
/// Rebindable client connection slot for a persistent `openidea-server` daemon.
#[derive(Default)]
pub struct PeerSlot {
inner: parking_lot::RwLock<Option<(u64, Peer)>>,
seq: std::sync::atomic::AtomicU64,
}
impl PeerSlot {
#[cfg(unix)]
pub(crate) fn remove(&self) -> Option<Peer> {
self.inner.write().take().map(|(_, p)| p)
}
}
impl PeerHandle for PeerSlot {
fn current(&self) -> Option<Peer> {
self.inner.read().as_ref().map(|(_, p)| p.clone())
}
fn install(&self, peer: Peer) -> (u64, Option<Peer>) {
let id = self.seq.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
let previous = self.inner.write().replace((id, peer)).map(|(_, p)| p);
(id, previous)
}
fn clear(&self, generation: u64) -> bool {
let mut guard = self.inner.write();
if guard.as_ref().is_some_and(|(id, _)| *id == generation) {
*guard = None;
true
} else {
false
}
}
}
/// One `invoke`: its arguments and a way to stream values back.
pub struct Call {
pub host: Arc<Host>,
pub window: String,
pub args: Value,
peer: Arc<OnceLock<Peer>>,
peer: Arc<dyn PeerHandle>,
}
impl Call {
@@ -91,7 +161,7 @@ impl Call {
.ok_or_else(|| IdeError::invalid(format!("argument {name}: expected a channel")))?;
let peer = self.peer.clone();
Ok(Arc::new(move |data: T| {
let Some(peer) = peer.get() else { return };
let Some(peer) = peer.current() else { return };
match serde_json::to_value(&data) {
Ok(data) => {
let _ = peer.notify("channel", ChannelMessage { id, data });
@@ -151,23 +221,56 @@ impl Dispatcher {
/// Serves `host` over `reader` / `writer` until the client disconnects.
/// `peer` must be the one whose events `host` sends ([`event_sink`]).
pub async fn serve<R, W>(host: Arc<Host>, dispatcher: Dispatcher, peer: Arc<OnceLock<Peer>>, reader: R, writer: W)
pub async fn serve<R, W, P>(host: Arc<Host>, dispatcher: Dispatcher, peer: Arc<P>, reader: R, writer: W)
where
R: tokio::io::AsyncRead + Unpin + Send + 'static,
W: tokio::io::AsyncWrite + Unpin + Send + 'static,
P: PeerHandle,
{
let slot: Arc<dyn PeerHandle> = peer;
let handler = Arc::new(ServerHandler { host: host.clone(), dispatcher, peer: slot.clone(), daemon: None });
let p = Peer::connect(reader, writer, handler);
let (generation, previous) = slot.install(p.clone());
if let Some(old) = previous {
old.kill();
}
p.closed().await;
if slot.clear(generation) {
// Reports belong to the disconnected desktop, even while the host shuts down.
for window in host.projects.read().keys() {
host.mcp_reports.forget_window(window);
}
}
}
/// The daemon owns the peer and handles replacement and disconnect serially.
#[cfg(unix)]
pub(crate) fn connect_persistent<R, W>(
host: Arc<Host>,
dispatcher: Dispatcher,
peer: Arc<PeerSlot>,
shutdown: ide_core::CancellationToken,
idle_policy: RemoteIdlePolicy,
reader: R,
writer: W,
) -> Peer
where
R: tokio::io::AsyncRead + Unpin + Send + 'static,
W: tokio::io::AsyncWrite + Unpin + Send + 'static,
{
let handler = Arc::new(ServerHandler { host: host.clone(), dispatcher, peer: peer.clone() });
// Streaming ids belong to the calling connection, not the next window to attach.
let connection = Arc::new(OnceLock::new());
let handler =
Arc::new(ServerHandler { host, dispatcher, peer: connection.clone(), daemon: Some((shutdown, idle_policy)) });
let p = Peer::connect(reader, writer, handler);
let _ = peer.set(p.clone());
p.closed().await;
// Reports belong to the disconnected desktop, even while the host shuts down.
for window in host.projects.read().keys() {
host.mcp_reports.forget_window(window);
}
let _ = connection.set(p.clone());
let (_, previous) = peer.install(p.clone());
debug_assert!(previous.is_none());
p
}
/// Sends a window's events to the client as `event` notifications.
pub fn event_sink(peer: Arc<OnceLock<Peer>>, window: Option<String>) -> ide_core::SharedSink {
pub fn event_sink<P: PeerHandle>(peer: Arc<P>, window: Option<String>) -> ide_core::SharedSink {
Arc::new(PeerSink { peer, window })
}
@@ -218,13 +321,13 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
}
struct PeerSink {
peer: Arc<OnceLock<Peer>>,
peer: Arc<dyn PeerHandle>,
window: Option<String>,
}
impl ide_core::EventSink for PeerSink {
fn emit(&self, event: IdeEvent) {
if let Some(peer) = self.peer.get() {
if let Some(peer) = self.peer.current() {
let _ = peer.notify("event", EventMessage { window: self.window.clone(), event });
}
}
@@ -233,16 +336,18 @@ impl ide_core::EventSink for PeerSink {
struct ServerHandler {
host: Arc<Host>,
dispatcher: Dispatcher,
peer: Arc<OnceLock<Peer>>,
peer: Arc<dyn PeerHandle>,
daemon: Option<(ide_core::CancellationToken, RemoteIdlePolicy)>,
}
pub fn server_info() -> ServerInfo {
fn server_info(idle_policy: Option<RemoteIdlePolicy>) -> ServerInfo {
ServerInfo {
version: env!("CARGO_PKG_VERSION").into(),
protocol: PROTOCOL_VERSION,
os: std::env::consts::OS.into(),
arch: std::env::consts::ARCH.into(),
home: dirs::home_dir().map(|h| h.to_string_lossy().into_owned()).unwrap_or_default(),
idle_policy,
}
}
@@ -250,10 +355,16 @@ impl Handler for ServerHandler {
fn on_notification(&self, _method: &str, _params: Value) {}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
if self.daemon.as_ref().is_some_and(|(shutdown, _)| shutdown.is_cancelled()) {
return Err((codes::INTERNAL_ERROR, "remote backend is stopping".into()));
}
let internal = |e: serde_json::Error| (codes::INTERNAL_ERROR, e.to_string());
match method {
"initialize" => serde_json::to_value(server_info()).map_err(internal),
"initialize" => {
serde_json::to_value(server_info(self.daemon.as_ref().map(|(_, policy)| *policy))).map_err(internal)
}
"commands" => serde_json::to_value(self.dispatcher.commands()).map_err(internal),
"shutdown" => Ok(Value::Null),
"invoke" => {
let call: Invoke =
serde_json::from_value(params).map_err(|e| (codes::INVALID_PARAMS, e.to_string()))?;
@@ -268,6 +379,14 @@ impl Handler for ServerHandler {
_ => Err((codes::METHOD_NOT_FOUND, format!("unknown method {method}"))),
}
}
fn after_response(&self, method: &str) {
if method == "shutdown"
&& let Some((shutdown, _)) = &self.daemon
{
shutdown.cancel();
}
}
}
/// An `IdeError` as a JSON-RPC error: the JSON of the error is the message.
+3 -1
Переглянути файл
@@ -128,7 +128,9 @@ struct Smoke {
}
fn fixture_dir(name: &str) -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures").join(name)
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)
}
fn copy_dir(from: &Path, to: &Path) {
+3 -1
Переглянути файл
@@ -53,7 +53,9 @@ 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);
copy_dir(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures").join(fixture), &root);
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);
let app = tmp.path().join("app");
let host = Arc::new(Host::new(common::host_config(&app)));
host.trust.decide(&root, true, false).unwrap();
+877
Переглянути файл
@@ -0,0 +1,877 @@
//! End-to-end tests of persistent `openidea-server --attach <project>`:
//! closing a client relay keeps the daemon, project index, terminals, runs
//! (including `stopCommand` configs such as `docker compose`) and dirty buffers
//! running until a client sends `"shutdown"` or the backend has been idle long enough.
#![cfg(unix)]
use ide_host::rpc::{self, ChannelMessage, EventMessage, Invoke, ServerInfo};
use ide_jsonrpc::{Handler, Peer};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::Duration;
const SERVER: &str = env!("CARGO_BIN_EXE_openidea-server");
const IDLE_TIMEOUT: &str = "OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS";
#[derive(Default)]
struct Client {
channels: Mutex<Vec<ChannelMessage>>,
events: Mutex<Vec<EventMessage>>,
taken_over: AtomicBool,
}
impl Handler for Client {
fn on_notification(&self, method: &str, params: Value) {
match method {
"channel" => self.channels.lock().push(serde_json::from_value(params).unwrap()),
"event" => self.events.lock().push(serde_json::from_value(params).unwrap()),
_ => {}
}
}
fn on_request(&self, method: &str, _: Value) -> Result<Value, (i64, String)> {
if method == rpc::SESSION_REPLACED {
self.taken_over.store(true, Ordering::Release);
return Ok(Value::Null);
}
Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, method.to_owned()))
}
}
async fn invoke(peer: &Peer, cmd: &str, args: Value) -> Result<Value, ide_core::IdeError> {
let call = Invoke { window: "main".into(), cmd: cmd.into(), args };
tokio::time::timeout(Duration::from_secs(15), peer.request::<_, Value>("invoke", call, None))
.await
.unwrap_or_else(|_| panic!("timed out calling {cmd}"))
.map_err(rpc::error_from_reply)
}
async fn until(what: &str, mut done: impl FnMut() -> bool) {
for _ in 0..600 {
if done() {
return;
}
tokio::time::sleep(Duration::from_millis(15)).await;
}
panic!("timed out waiting for {what}");
}
struct DaemonGuard(PathBuf);
fn test_build() -> &'static [u8] {
static BUILD: OnceLock<String> = OnceLock::new();
BUILD
.get_or_init(|| {
let mut hasher = blake3::Hasher::new();
hasher.update_reader(std::fs::File::open(SERVER).unwrap()).unwrap();
hasher.finalize().to_hex()[..16].to_owned()
})
.as_bytes()
}
impl Drop for DaemonGuard {
fn drop(&mut self) {
use std::io::{Read, Write};
if let Ok(mut stream) = std::os::unix::net::UnixStream::connect(&self.0) {
let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
let mut reply = [0];
if stream.write_all(test_build()).and_then(|_| stream.read_exact(&mut reply)).is_ok() && reply == *b"A" {
let request = r#"{"jsonrpc":"2.0","id":1,"method":"shutdown"}"#;
let _ = write!(stream, "Content-Length: {}\r\n\r\n{request}", request.len());
let _ = std::io::copy(&mut stream, &mut std::io::sink());
}
}
}
}
fn server_env(home: &Path, server_home: &Path, idle_seconds: u64) -> [(String, String); 4] {
[
("HOME".to_owned(), home.to_string_lossy().into_owned()),
("OPENIDEA_SERVER_HOME".to_owned(), server_home.to_string_lossy().into_owned()),
("OPENIDEA_SKIP_SHELL_ENV".to_owned(), "1".into()),
(IDLE_TIMEOUT.into(), idle_seconds.to_string()),
]
}
fn attach_client(home: &Path, server_home: &Path, attach_arg: &str, idle_seconds: u64) -> (Peer, Arc<Client>) {
let client = Arc::new(Client::default());
let args = vec!["--attach".to_owned(), attach_arg.to_owned()];
let env = server_env(home, server_home, idle_seconds);
let peer = Peer::spawn(SERVER, &args, home, &env, client.clone(), Box::new(|line| eprintln!("{line}"))).unwrap();
(peer, client)
}
async fn ssh_server(home: &Path, server_home: &Path, project: &Path) -> Arc<ide_ssh::Session> {
use ide_core::remote_settings::{SshAuth, SshConfiguration};
use ide_ssh::{SshFiles, SshManager};
let project = project.to_owned();
let env = server_env(home, server_home, 10_800);
let port = ide_ssh::testing::sshd_with_process(home.join("sftp"), move |command| {
let path = if command == "openidea-test-attach" {
project.to_str().unwrap()
} else if command == "openidea-test-reattach" {
"~/demo"
} else {
return None;
};
let mut cmd = tokio::process::Command::new(SERVER);
cmd.args(["--attach", path]).envs(env.iter().cloned());
Some(cmd)
})
.await;
let ssh = SshManager::with_files(
home.join("secrets.json"),
SshFiles { known_hosts: home.join("known_hosts"), config: None },
);
ssh.set_configs(vec![SshConfiguration {
id: "local-test".into(),
host: "127.0.0.1".into(),
port: Some(port),
user: "dev".into(),
auth: SshAuth::Password,
save_secret: true,
..Default::default()
}]);
ssh.set_secret("local-test", Some("secret".into()), true);
assert!(ssh.session("local-test").await.is_err(), "unknown host key first");
ssh.trust_host("local-test").await.unwrap();
ssh.session("local-test").await.unwrap()
}
async fn ssh_attach(ssh: &ide_ssh::Session, command: &str) -> (Peer, Arc<Client>) {
let stream = ssh.exec_stream(command).await.unwrap();
let (reader, writer) = tokio::io::split(stream);
let client = Arc::new(Client::default());
(Peer::connect(reader, writer, client.clone()), client)
}
async fn initialize(peer: &Peer) -> ServerInfo {
tokio::time::timeout(
Duration::from_secs(15),
peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None),
)
.await
.expect("initialize timed out")
.unwrap()
}
async fn shutdown(peer: &Peer) {
tokio::time::timeout(Duration::from_secs(15), async {
peer.request::<_, ()>("shutdown", Value::Null, None).await.unwrap();
peer.closed().await;
})
.await
.expect("backend did not shut down");
}
async fn assert_indexed(peer: &Peer, name: &str) {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
let syms =
invoke(peer, "find_symbols", json!({ "query": name, "filter": "all", "limit": 10 })).await.unwrap();
if syms.as_array().is_some_and(|a| a.iter().any(|sym| sym["name"] == name)) {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
})
.await
.unwrap_or_else(|_| panic!("symbol {name} was not indexed"));
}
fn pid_alive(pid: u32) -> bool {
let Ok(pid) = i32::try_from(pid) else { return false };
if pid <= 0 {
return false;
}
// Check `kill(pid, 0)` and exclude zombies on macOS/Linux via `ps`.
let out = std::process::Command::new("ps").args(["-o", "stat=", "-p", &pid.to_string()]).output();
match out {
Ok(o) if o.status.success() => {
let stat = String::from_utf8_lossy(&o.stdout);
let s = stat.trim();
!s.is_empty() && !s.starts_with('Z')
}
_ => false,
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn ssh_disconnect_keeps_terminals_runs_index_and_dirty_docs_until_shutdown() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let project = home.join("demo");
let subdir = project.join("sub");
std::fs::create_dir_all(&subdir).unwrap();
let subdir = dunce::canonicalize(subdir).unwrap();
std::fs::write(project.join("app.py"), "def greet():\n return 42\n").unwrap();
let server_home = tmp.path().join("s");
let guard = DaemonGuard(ide_host::daemon::paths_for(&server_home, &home, "~/demo").unwrap().socket);
let ssh = ssh_server(&home, &server_home, &project).await;
// --- Session 1: open project, start a TUI terminal (`watch date`) and a compose-like run ---
let (peer1, client1) = ssh_attach(&ssh, "openidea-test-attach").await;
let info1 = initialize(&peer1).await;
assert_eq!(info1.protocol, rpc::PROTOCOL_VERSION);
assert_eq!(info1.idle_policy.unwrap().override_seconds, Some(10_800));
let opened = invoke(&peer1, "open_project", json!({ "path": project })).await.unwrap();
assert_eq!(opened["name"], "demo");
invoke(&peer1, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap();
assert_indexed(&peer1, "greet").await;
// Spawn a long-running terminal emitting OSC 7 cwd, OSC 2 title (`watch date`), OSC 133;C and periodic ticks.
let term_script = format!(
"printf '\\033]7;file://localhost{}\\007\\033]2;watch date\\007\\033]133;C\\007'; \
i=0; while true; do i=$((i+1)); echo \"tick-$i\"; sleep 0.05; done",
subdir.display()
);
let term = invoke(
&peer1,
"term_spawn",
json!({
"options": {
"cwd": project,
"shell": "/bin/sh",
"args": ["-c", term_script],
"env": {},
"cols": 80,
"rows": 24,
"shellIntegration": false
},
"onOutput": { "$channel": 101 }
}),
)
.await
.unwrap();
let term_id = term["id"].as_u64().unwrap();
let term_pid = term["pid"].as_u64().unwrap() as u32;
until("initial terminal tick", || {
client1.channels.lock().iter().any(|c| c.id == 101 && c.data.as_str().is_some_and(|s| s.contains("tick-")))
})
.await;
// Start a Docker-Compose-style run with a `stopCommand` that writes `down.marker` ONLY when stopped.
let down_marker = project.join("down.marker");
let run_config = json!({
"id": "docker:compose:up",
"name": "docker compose up",
"kind": "docker-compose",
"command": "/bin/sh",
"args": ["-c", "n=0; while true; do n=$((n+1)); echo \"compose-$n\"; sleep 0.05; done"],
"cwd": project,
"env": {},
"detected": false,
"isTest": false,
"debugAdapter": null,
"stopCommand": format!("touch '{}'", down_marker.display()),
});
let run = invoke(
&peer1,
"run_start",
json!({
"config": run_config,
"onOutput": { "$channel": 102 },
"request": 1
}),
)
.await
.unwrap();
let run_id = run["id"].as_u64().unwrap();
let run_pid = run["pid"].as_u64().unwrap() as u32;
until("initial compose output", || {
client1
.channels
.lock()
.iter()
.any(|c| c.id == 102 && c.data["text"].as_str().is_some_and(|s| s.contains("compose-")))
})
.await;
// Leave an unsaved edit in `app.py` to simulate an unexpected disconnect, plus a clean file `clean.txt`.
std::fs::write(project.join("clean.txt"), "before\n").unwrap();
let _clean_doc = invoke(&peer1, "doc_open", json!({ "path": project.join("clean.txt") })).await.unwrap();
let dirty_doc = invoke(&peer1, "doc_open", json!({ "path": project.join("app.py") })).await.unwrap();
invoke(
&peer1,
"doc_edit",
json!({
"doc": dirty_doc["id"],
"baseVersion": dirty_doc["version"],
"changes": { "changes": [{ "from": 0, "to": 0, "insert": "# unsaved\n" }] }
}),
)
.await
.unwrap();
// --- Close window / disconnect client #1 ---
peer1.kill();
peer1.closed().await;
// Let both background processes produce output while NO client is connected, and update `clean.txt` on disk.
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(pid_alive(term_pid), "terminal PTY process must keep running after window close");
assert!(pid_alive(run_pid), "docker-compose run process must keep running after window close");
assert!(!down_marker.exists(), "closing the remote window must NOT run docker compose down");
std::fs::write(project.join("clean.txt"), "updated-while-closed\n").unwrap();
std::fs::write(project.join("added.py"), "def indexed_while_disconnected():\n pass\n").unwrap();
// --- Session 2: reopen via `~/demo` (tests `~` canonicalization attaching to the SAME daemon) ---
let (peer2, client2) = ssh_attach(&ssh, "openidea-test-reattach").await;
initialize(&peer2).await;
let reopened = invoke(&peer2, "open_project", json!({ "path": project })).await.unwrap();
assert_eq!(reopened["trusted"], true);
assert_indexed(&peer2, "indexed_while_disconnected").await;
// 1. Terminal list & reattach restores `watch date` title, cwd, buffered ticks and live output!
let terms = invoke(&peer2, "term_list", json!({})).await.unwrap();
let listed = terms.as_array().unwrap();
assert_eq!(listed.len(), 1, "{listed:?}");
assert_eq!(listed[0]["id"], term_id);
assert_eq!(listed[0]["appTitle"], "watch date");
assert_eq!(listed[0]["commandRunning"], true);
assert_eq!(listed[0]["cwd"], subdir.to_string_lossy().as_ref());
let attached_term = invoke(
&peer2,
"term_attach",
json!({ "id": term_id, "cols": 100, "rows": 30, "onOutput": { "$channel": 201 } }),
)
.await
.unwrap();
assert!(attached_term["buffered"].as_str().unwrap().contains("tick-"));
until("live terminal ticks on client 2", || {
client2.channels.lock().iter().any(|c| c.id == 201 && c.data.as_str().is_some_and(|s| s.contains("tick-")))
})
.await;
// 2. Run list & reattach restores the running `docker compose up` session and streams live output!
let runs = invoke(&peer2, "run_list", json!({})).await.unwrap();
assert!(runs.as_array().unwrap().iter().any(|r| r["id"] == run_id && r["running"] == true));
let attached_run =
invoke(&peer2, "run_attach", json!({ "id": run_id, "onOutput": { "$channel": 202 } })).await.unwrap();
assert_eq!(attached_run["config"]["id"], "docker:compose:up");
assert!(
attached_run["buffered"]
.as_array()
.unwrap()
.iter()
.any(|c| c["text"].as_str().is_some_and(|s| s.contains("compose-")))
);
until("live compose output on client 2", || {
client2
.channels
.lock()
.iter()
.any(|c| c.id == 202 && c.data["text"].as_str().is_some_and(|s| s.contains("compose-")))
})
.await;
// 3. Clean documents reload external disk changes; dirty documents retain unsaved edits without ref leaks!
let clean_reopened = invoke(&peer2, "doc_open", json!({ "path": project.join("clean.txt") })).await.unwrap();
assert_eq!(clean_reopened["text"], "updated-while-closed\n");
let dirty_reopened = invoke(&peer2, "doc_open", json!({ "path": project.join("app.py") })).await.unwrap();
assert!(dirty_reopened["text"].as_str().unwrap().starts_with("# unsaved\n"));
assert_eq!(dirty_reopened["dirty"], true);
// 4. Explicit `"shutdown"` (Stop Remote Backend) stops the daemon and cleans up processes.
shutdown(&peer2).await;
until("terminal and run processes terminated on explicit backend shutdown", || {
!pid_alive(term_pid) && !pid_alive(run_pid)
})
.await;
assert!(down_marker.exists(), "stopping the backend runs the configured stop command");
assert!(!guard.0.exists(), "the shutdown connection stays open until daemon cleanup finishes");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn ongoing_agent_session_continues_running_while_remote_window_is_closed() {
agent_roundtrip(false).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn stopping_the_backend_terminates_an_agent_mid_turn() {
agent_roundtrip(true).await;
}
async fn agent_roundtrip(stop_during_turn: bool) {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let project = home.join("agent-demo");
std::fs::create_dir_all(&project).unwrap();
let server_home = tmp.path().join("s");
let guard = DaemonGuard(ide_host::daemon::paths_for(&server_home, &home, "~/agent-demo").unwrap().socket);
let agents_dir = server_home.join("config/agents");
std::fs::create_dir_all(&agents_dir).unwrap();
let agent_script = home.join("mock-acp-agent.py");
std::fs::write(
&agent_script,
r#"#!/usr/bin/env python3
import json, os, sys, time
from pathlib import Path
def send(obj):
sys.stdout.write(json.dumps(obj) + "\n")
sys.stdout.flush()
while True:
raw = sys.stdin.readline()
if not raw:
break
raw = raw.strip()
if not raw:
continue
msg = json.loads(raw)
method = msg.get("method")
mid = msg.get("id")
if method == "initialize":
send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": 2, "capabilities": {}, "info": {"name": "mock", "version": "1.0"}}})
elif method == "session/new":
send({"jsonrpc": "2.0", "id": mid, "result": {"sessionId": "sess-1", "configOptions": []}})
elif method == "session/prompt":
send({"jsonrpc": "2.0", "id": mid, "result": {"messageId": "u1"}})
send({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "sess-1", "update": {"sessionUpdate": "state_update", "state": "running"}}})
send({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "sess-1", "update": {"sessionUpdate": "agent_message_chunk", "messageId": "a1", "content": {"type": "text", "text": "part-1 "}}}})
Path("agent.pid").write_text(str(os.getpid()))
while not Path("agent.release").exists():
time.sleep(0.03)
send({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "sess-1", "update": {"sessionUpdate": "agent_message_chunk", "messageId": "a1", "content": {"type": "text", "text": "finished-while-window-closed"}}}})
send({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "sess-1", "update": {"sessionUpdate": "state_update", "state": "idle", "stopReason": "end_turn"}}})
Path("agent.finished").touch()
"#,
)
.unwrap();
std::fs::set_permissions(&agent_script, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::write(
agents_dir.join("mock-agent.toml"),
format!("name = \"Mock Agent\"\ncommand = \"{}\"\nargs = []\n", agent_script.display()),
)
.unwrap();
// Client 1 opens the project, starts the agent task, then disconnects mid-turn.
let (peer1, _) = attach_client(&home, &server_home, "~/agent-demo", 1);
initialize(&peer1).await;
invoke(&peer1, "open_project", json!({ "path": project })).await.unwrap();
invoke(&peer1, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap();
invoke(&peer1, "agent_subscribe", json!({ "subscriber": "main", "onEvent": { "$channel": 301 } })).await.unwrap();
let created = invoke(
&peer1,
"agent_create",
json!({
"request": {
"provider": "mock-agent",
"prompt": { "text": "run background task", "files": [], "images": [] },
"isolation": "local",
"baseBranch": null,
"config": [],
"projectRoot": project,
"mcpOverrides": {}
}
}),
)
.await
.unwrap();
let task_id = created["id"].as_str().unwrap().to_owned();
let pid_path = project.join("agent.pid");
let read_pid = || std::fs::read_to_string(&pid_path).ok().and_then(|text| text.parse::<u32>().ok());
until("agent prompt started", || read_pid().is_some()).await;
let agent_pid = read_pid().unwrap();
peer1.kill();
peer1.exited().await;
// The turn alone keeps the daemon running past its idle deadline.
tokio::time::sleep(Duration::from_millis(2300)).await;
assert!(guard.0.exists(), "the daemon expired during an agent turn");
assert!(pid_alive(agent_pid));
if !stop_during_turn {
std::fs::write(project.join("agent.release"), "").unwrap();
until("agent completed with the window closed", || project.join("agent.finished").exists()).await;
}
let (peer2, _) = attach_client(&home, &server_home, "~/agent-demo", 1);
initialize(&peer2).await;
invoke(&peer2, "open_project", json!({ "path": project })).await.unwrap();
if stop_during_turn {
shutdown(&peer2).await;
until("agent process stopped", || !pid_alive(agent_pid)).await;
assert!(!project.join("agent.finished").exists());
assert!(!guard.0.exists());
return;
}
for _ in 0..200 {
let tasks = invoke(&peer2, "agent_subscribe", json!({ "subscriber": "main", "onEvent": { "$channel": 401 } }))
.await
.unwrap();
let task = tasks.as_array().unwrap().iter().find(|t| t["id"] == task_id).expect("persisted agent task");
if task["status"] == "ready" {
break;
}
assert_ne!(task["status"], "failed", "{task:?}");
tokio::time::sleep(Duration::from_millis(20)).await;
}
let tasks = invoke(&peer2, "agent_subscribe", json!({ "subscriber": "main", "onEvent": { "$channel": 401 } }))
.await
.unwrap();
let task = tasks.as_array().unwrap().iter().find(|t| t["id"] == task_id).expect("persisted agent task");
assert_eq!(task["status"], "ready", "{task:?}");
let entries = invoke(&peer2, "agent_entries", json!({ "task": task_id, "subagent": null })).await.unwrap();
let texts: Vec<&str> = entries
.as_array()
.unwrap()
.iter()
.filter(|e| e["type"] == "agent")
.filter_map(|e| e["text"].as_str())
.collect();
assert!(
texts.iter().any(|t| t.contains("part-1 finished-while-window-closed")),
"expected full agent output across window close, got: {entries:?}"
);
shutdown(&peer2).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_idle_open_project_expires_but_an_attached_view_does_not() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let base = tmp.path().join("s");
let project = home.join("demo");
std::fs::create_dir_all(&project).unwrap();
std::fs::write(project.join("hello.py"), "def kept_during_index():\n pass\n").unwrap();
let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
let (peer, _) = attach_client(&home, &base, "~/demo", 1);
initialize(&peer).await;
invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
assert_indexed(&peer, "kept_during_index").await;
invoke(
&peer,
"settings_set",
json!({ "scope": "global", "key": "remoteDevelopment.idleTimeoutMinutes", "value": "0" }),
)
.await
.unwrap();
tokio::time::sleep(Duration::from_millis(2300)).await;
assert!(!invoke(&peer, "project_current", json!({})).await.unwrap().is_null());
peer.kill();
peer.exited().await;
until("a disconnected, opened project expires", || !guard.0.exists()).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn unsaved_edits_of_a_dropped_connection_keep_an_idle_daemon() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let base = tmp.path().join("s");
let project = home.join("demo");
std::fs::create_dir_all(&project).unwrap();
std::fs::write(project.join("app.py"), "print(1)\n").unwrap();
let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
let (peer, _) = attach_client(&home, &base, "~/demo", 1);
initialize(&peer).await;
invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
let doc = invoke(&peer, "doc_open", json!({ "path": project.join("app.py") })).await.unwrap();
invoke(
&peer,
"doc_edit",
json!({
"doc": doc["id"],
"baseVersion": doc["version"],
"changes": { "changes": [{ "from": 0, "to": 0, "insert": "# unsaved\n" }] }
}),
)
.await
.unwrap();
peer.kill();
peer.exited().await;
tokio::time::sleep(Duration::from_millis(2300)).await;
assert!(guard.0.exists(), "an idle daemon expired with unsaved edits");
let (again, _) = attach_client(&home, &base, "~/demo", 1);
initialize(&again).await;
let reopened = invoke(&again, "doc_open", json!({ "path": project.join("app.py") })).await.unwrap();
assert!(reopened["text"].as_str().unwrap().starts_with("# unsaved\n"));
shutdown(&again).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn applying_the_host_timeout_expires_the_running_daemon_without_a_restart() {
saved_idle_policy(false).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn never_keeps_the_same_idle_daemon_until_explicit_shutdown() {
saved_idle_policy(true).await;
}
async fn saved_idle_policy(never: bool) {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let base = tmp.path().join("s");
let project = home.join("demo");
std::fs::create_dir_all(&project).unwrap();
let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
let mut daemon = tokio::process::Command::new(SERVER)
.arg("--daemon")
.arg(&guard.0)
.arg(std::str::from_utf8(test_build()).unwrap())
.envs(server_env(&home, &base, 1))
.env_remove(IDLE_TIMEOUT)
.kill_on_drop(true)
.spawn()
.unwrap();
until("daemon bound its socket", || guard.0.exists()).await;
let (peer, _) = attach_client(&home, &base, "~/demo", 1);
assert_eq!(initialize(&peer).await.idle_policy.unwrap().override_seconds, None);
invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
let set = |scope: &str, value: &str| {
invoke(
&peer,
"settings_set",
json!({ "scope": scope, "key": "remoteDevelopment.idleTimeoutMinutes", "value": value }),
)
};
let global = invoke(&peer, "settings_get_global", json!({})).await.unwrap();
assert_eq!(global["remoteDevelopment"]["idleTimeoutMinutes"], 180);
assert!(set("global", "-1").await.is_err());
assert!(set("project", "1").await.is_err());
let updated = set("global", "1").await.unwrap();
assert_eq!(updated["remoteDevelopment"]["idleTimeoutMinutes"], 1);
assert!(std::fs::read_to_string(base.join("config/settings.toml")).unwrap().contains("idleTimeoutMinutes = 1"));
if never {
// A different project's daemon can change the host preference after this window connected.
let other = ide_workspace::SettingsStore::load(&base.join("config"), None);
other.set(ide_workspace::SettingsScope::Global, "remoteDevelopment.idleTimeoutMinutes", json!(0)).unwrap();
assert_eq!(invoke(&peer, "remote_idle_timeout_minutes", json!({})).await.unwrap(), 0);
}
let disconnect = std::time::Instant::now();
peer.kill();
peer.exited().await;
if never {
assert!(
tokio::time::timeout(Duration::from_secs(72), daemon.wait()).await.is_err(),
"Never expired at the previous one-minute timeout"
);
let (resumed, _) = attach_client(&home, &base, "~/demo", 1);
assert!(!invoke(&resumed, "project_current", json!({})).await.unwrap().is_null());
shutdown(&resumed).await;
}
let status =
tokio::time::timeout(Duration::from_secs(80), daemon.wait()).await.expect("saved timeout not used").unwrap();
assert!(status.success());
assert!(disconnect.elapsed() >= Duration::from_secs(60), "daemon stopped before the configured minute");
assert!(!guard.0.exists());
}
async fn looping_terminal(peer: &Peer, project: &Path) -> Value {
invoke(
peer,
"term_spawn",
json!({
"options": {
"cwd": project, "shell": "/bin/sh", "args": ["-c", "exec sleep 300"],
"env": {}, "cols": 80, "rows": 24, "shellIntegration": false
},
"onOutput": { "$channel": 1 }
}),
)
.await
.unwrap()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_takeover_notifies_the_first_window_and_keeps_its_terminal() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let base = tmp.path().join("s");
let project = home.join("demo");
std::fs::create_dir_all(&project).unwrap();
let _guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
let (first, original) = attach_client(&home, &base, "~/demo", 1);
initialize(&first).await;
invoke(&first, "open_project", json!({ "path": project })).await.unwrap();
invoke(&first, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap();
let term = looping_terminal(&first, &project).await;
let (second, _) = attach_client(&home, &base, "~/demo", 1);
initialize(&second).await;
tokio::time::timeout(Duration::from_secs(5), first.closed()).await.expect("first window was not disconnected");
assert!(original.taken_over.load(Ordering::Acquire), "the first window saw an unexplained EOF");
assert_eq!(invoke(&second, "term_list", json!({})).await.unwrap()[0]["id"], term["id"]);
second.kill();
second.exited().await;
tokio::time::sleep(Duration::from_millis(2300)).await;
let (third, _) = attach_client(&home, &base, "~/demo", 1);
initialize(&third).await;
assert_eq!(invoke(&third, "term_list", json!({})).await.unwrap()[0]["id"], term["id"]);
shutdown(&third).await;
until("terminal child stopped", || !pid_alive(term["pid"].as_u64().unwrap() as u32)).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::UnixStream;
const OLD_BUILD: &str = "0123456789abcdef";
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let base = tmp.path().join("s");
let project = home.join("demo");
std::fs::create_dir_all(&project).unwrap();
let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
let mut previous_build = tokio::process::Command::new(SERVER)
.arg("--daemon")
.arg(&guard.0)
.arg(OLD_BUILD)
.envs(server_env(&home, &base, 10_800))
.kill_on_drop(true)
.spawn()
.unwrap();
until("old backend socket", || guard.0.exists()).await;
let old_open = || async {
let mut stream = UnixStream::connect(&guard.0).await.unwrap();
stream.write_all(OLD_BUILD.as_bytes()).await.unwrap();
assert_eq!(stream.read_u8().await.unwrap(), b'A');
let (reader, writer) = stream.into_split();
Peer::connect(reader, writer, Arc::new(Client::default()))
};
let old = old_open().await;
initialize(&old).await;
invoke(&old, "open_project", json!({ "path": project })).await.unwrap();
invoke(&old, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap();
let term = looping_terminal(&old, &project).await;
old.kill();
old.closed().await;
let rejected = tokio::time::timeout(
Duration::from_secs(15),
tokio::process::Command::new(SERVER)
.args(["--attach", "~/demo"])
.envs(server_env(&home, &base, 10_800))
.kill_on_drop(true)
.output(),
)
.await
.unwrap()
.unwrap();
assert!(!rejected.status.success());
assert!(String::from_utf8_lossy(&rejected.stderr).contains("Another build of OpenIDEA"), "{rejected:?}");
assert!(previous_build.try_wait().unwrap().is_none(), "the live backend was replaced");
let resumed = old_open().await;
assert_eq!(invoke(&resumed, "term_list", json!({})).await.unwrap()[0]["id"], term["id"]);
invoke(&resumed, "term_kill", json!({ "id": term["id"] })).await.unwrap();
resumed.kill();
resumed.closed().await;
let (new, _) = attach_client(&home, &base, "~/demo", 10_800);
initialize(&new).await;
let old_exit = tokio::time::timeout(Duration::from_secs(5), previous_build.wait()).await.unwrap().unwrap();
assert!(old_exit.success(), "handoff did not shut down the old daemon cleanly");
assert!(invoke(&new, "project_current", json!({})).await.unwrap().is_null());
shutdown(&new).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "requires a Docker context with Docker Compose and the busybox image"]
async fn compose_service_survives_disconnect_and_is_removed_on_stop() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let base = tmp.path().join("s");
let project = home.join("demo");
std::fs::create_dir_all(&project).unwrap();
std::fs::write(
project.join("compose.yml"),
"services:\n worker:\n image: busybox:latest\n command: ['sleep', '300']\n stop_grace_period: 1s\n",
)
.unwrap();
let suffix = tmp.path().file_name().unwrap().to_str().unwrap().trim_start_matches('.').to_ascii_lowercase();
let name = format!("openidea-compose-{suffix}");
let docker = ide_docker::docker_executable().expect("Docker is not installed");
// The test server has its own HOME; keep Docker Desktop's CLI plugins and context accessible.
let docker_config = std::env::var_os("DOCKER_CONFIG")
.map(PathBuf::from)
.unwrap_or_else(|| dirs::home_dir().expect("home").join(".docker"));
struct ComposeCleanup<'a>(&'a Path, &'a Path, &'a str);
impl Drop for ComposeCleanup<'_> {
fn drop(&mut self) {
let _ = std::process::Command::new(self.0)
.current_dir(self.1)
.args(["compose", "-p", self.2, "down", "--timeout", "1"])
.output();
}
}
let _compose = ComposeCleanup(&docker, &project, &name);
let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
let compose_ids = |all| {
let mut cmd = tokio::process::Command::new(&docker);
cmd.current_dir(&project).args(["compose", "-p", &name, "ps", "-q"]);
if all {
cmd.arg("-a");
}
async move {
let out = cmd.output().await.unwrap();
assert!(out.status.success(), "docker compose ps: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8(out.stdout).unwrap().trim().to_owned()
}
};
let (first, client) = attach_client(&home, &base, "~/demo", 1);
initialize(&first).await;
invoke(&first, "open_project", json!({ "path": project })).await.unwrap();
invoke(&first, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap();
let run = invoke(
&first,
"run_start",
json!({
"config": {
"id": "docker:compose:worker", "name": "Compose worker", "kind": "docker-compose",
"command": docker, "args": ["compose", "-p", name, "up", "--pull", "never"], "cwd": project,
"env": { "DOCKER_CONFIG": docker_config }, "detected": false, "isTest": false,
"stopCommand": format!("{} compose -p {name} down", ide_ssh::shell::quote(docker.to_str().unwrap())),
},
"onOutput": { "$channel": 1 }, "request": 1,
}),
)
.await
.unwrap();
let container = tokio::time::timeout(Duration::from_secs(20), async {
loop {
let id = compose_ids(false).await;
if !id.is_empty() {
break id;
}
tokio::time::sleep(Duration::from_millis(150)).await;
}
})
.await
.unwrap_or_else(|_| panic!("the compose service did not start: {:?}", client.channels.lock()));
first.kill();
first.exited().await;
tokio::time::sleep(Duration::from_millis(2300)).await;
assert_eq!(compose_ids(false).await, container, "close without stop interrupted the compose service");
let (second, _) = attach_client(&home, &base, "~/demo", 1);
initialize(&second).await;
let runs = invoke(&second, "run_list", json!({})).await.unwrap();
assert!(runs.as_array().unwrap().iter().any(|r| r["id"] == run["id"] && r["running"] == true));
shutdown(&second).await;
assert!(!guard.0.exists());
assert!(compose_ids(true).await.is_empty(), "the stop command did not remove the compose service");
}
+24 -9
Переглянути файл
@@ -720,6 +720,14 @@ async fn api14_stage3_remote_terminal_pins_and_exit_events_stay_on_the_execution
.await
.unwrap();
assert_eq!(run.await.unwrap(), operation);
let attached = invoke(
&peer,
"term_attach",
json!({"id": terminal["id"], "cols": 80, "rows": 24, "onOutput": {"$channel": 41}}),
)
.await
.unwrap();
assert_eq!(attached["session"]["id"], terminal["id"]);
invoke(
&peer,
"plugin_run_command",
@@ -729,16 +737,23 @@ async fn api14_stage3_remote_terminal_pins_and_exit_events_stay_on_the_execution
.unwrap();
until("PTY exit", 5, || client.events.lock().iter().any(|m| matches!(m.event, IdeEvent::TerminalExited { .. })))
.await;
plugins.host().flush_events_at(std::time::Instant::now() + Duration::from_secs(3));
plugins.host().wait_events(Duration::from_secs(5));
let received = invoke(
&peer,
"plugin_run_command",
json!({"pluginId": "execution", "commandId": "events", "arg": null, "editor": null}),
)
let received = tokio::time::timeout(Duration::from_secs(5), async {
loop {
let received = invoke(
&peer,
"plugin_run_command",
json!({"pluginId": "execution", "commandId": "events", "arg": null, "editor": null}),
)
.await
.unwrap();
if let Some(events) = received.as_str() {
break serde_json::from_str::<Value>(events).unwrap();
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
})
.await
.unwrap();
let received: Value = serde_json::from_str(received.as_str().unwrap()).unwrap();
.expect("plugin terminal completion after reattach");
assert_eq!(received.as_array().unwrap().len(), 1);
assert_eq!(received[0]["kind"], "terminal-exited");
let data: Value = serde_json::from_str(received[0]["data"].as_str().unwrap()).unwrap();
+1
Переглянути файл
@@ -30,6 +30,7 @@ async fn storage_requires_a_registered_terminal() {
"main".into(),
Arc::new(NullSink),
Box::new(|_| {}),
None,
)
.unwrap();
for mime in ["image/png", "audio/mpeg", "video/mp4"] {
+8
Переглянути файл
@@ -432,6 +432,14 @@ 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);
+37 -4
Переглянути файл
@@ -250,8 +250,13 @@ impl Handler for NoopHandler {
type Pending = HashMap<i64, oneshot::Sender<Result<Value, RpcError>>>;
enum Outgoing {
Message(Vec<u8>),
Flush(oneshot::Sender<()>),
}
struct Inner {
out: mpsc::UnboundedSender<Vec<u8>>,
out: mpsc::UnboundedSender<Outgoing>,
pending: Mutex<Pending>,
next_id: AtomicI64,
/// Set once the transport is gone; new requests fail fast.
@@ -275,7 +280,7 @@ impl Inner {
}
let body = serde_json::to_vec(value).map_err(|e| RpcError::Protocol(e.to_string()))?;
tracing::trace!(target: "ide_jsonrpc::wire", "--> {}", String::from_utf8_lossy(&body));
self.out.send(body).map_err(|_| RpcError::Closed)
self.out.send(Outgoing::Message(body)).map_err(|_| RpcError::Closed)
}
/// Fails every in-flight request and refuses new ones.
@@ -479,6 +484,20 @@ impl Peer {
Self::start(reader, writer, handler, true, None, Framing::ContentLength, None)
}
/// Like [`Peer::connect`], with diagnostics from a launcher sharing the stdout stream.
pub fn connect_with_output<R, W>(
reader: R,
writer: W,
handler: Arc<dyn Handler>,
on_output: impl Fn(String) + Send + Sync + 'static,
) -> Self
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
Self::start(reader, writer, handler, true, None, Framing::ContentLength, Some(Arc::new(on_output)))
}
/// [`connect`](Self::connect) with the given wire framing.
pub fn connect_framed<R, W>(reader: R, writer: W, handler: Arc<dyn Handler>, framing: Framing) -> Self
where
@@ -520,7 +539,7 @@ impl Peer {
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
let (out_tx, mut out_rx) = mpsc::unbounded_channel::<Vec<u8>>();
let (out_tx, mut out_rx) = mpsc::unbounded_channel();
let (closed, _) = watch::channel(None);
let inner = Arc::new(Inner {
out: out_tx,
@@ -547,7 +566,14 @@ impl Peer {
body = out_rx.recv() => body,
_ = kill.cancelled() => None,
};
let Some(body) = body else { break };
let body = match body {
Some(Outgoing::Message(body)) => body,
Some(Outgoing::Flush(done)) => {
let _ = done.send(());
continue;
}
None => break,
};
if let Err(e) = framing.write(&mut writer, &body).await {
tracing::debug!("jsonrpc write failed: {e}");
if let Some(inner) = weak.upgrade() {
@@ -706,6 +732,13 @@ impl Peer {
self.inner.send_value(&msg)
}
/// Waits until previously queued messages have been written.
pub async fn flush(&self) -> Result<(), RpcError> {
let (tx, rx) = oneshot::channel();
self.inner.out.send(Outgoing::Flush(tx)).map_err(|_| RpcError::Closed)?;
rx.await.map_err(|_| RpcError::Closed)
}
/// Resolves when the connection closes (process exit or EOF), with the exit code if known.
pub async fn closed(&self) -> Option<i32> {
let mut rx = self.inner.closed.subscribe();
+9
Переглянути файл
@@ -242,6 +242,15 @@ pub struct RunInfo {
pub pty: bool,
}
/// Snapshot and live output binding returned when reattaching to a running process.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct RunAttach {
pub info: RunInfo,
pub config: RunConfig,
pub buffered: Vec<OutputChunk>,
}
pub use external::{EXTERNAL_PREFIX, ExternalDetection, set_external_detection};
/// Detects configs from package.json scripts, Cargo.toml targets, build.gradle(.kts),
+134 -26
Переглянути файл
@@ -2,11 +2,11 @@
//! for "Emulate terminal in output console"), stream output, stdin, stop.
use crate::utf8::OutputDecoder;
use crate::{OutputChunk, RunConfig, RunInfo};
use crate::{OutputChunk, RunAttach, RunConfig, RunInfo};
use ide_core::{IdeError, IdeEvent, IdeResult, RunId, SharedSink};
use parking_lot::Mutex;
use portable_pty::{CommandBuilder, MasterPty, PtySize, native_pty_system};
use std::collections::BTreeMap;
use std::collections::{BTreeMap, VecDeque};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};
@@ -32,11 +32,43 @@ const STOP_GRACE: Duration = Duration::from_secs(3);
const STOP_COMMAND_TIMEOUT: Duration = Duration::from_secs(60);
/// Finished runs kept for [`ProcessManager::list`].
const MAX_FINISHED: usize = 20;
/// Bounded console scrollback retained per run for reattaching across window reconnects.
const MAX_BUFFERED_OUTPUT: usize = 256 * 1024;
/// PTY size until the console reports its own.
const DEFAULT_PTY: (u16, u16) = (120, 30);
type OutputFn = Arc<dyn Fn(OutputChunk) + Send + Sync>;
struct RunOutputState {
buffered: VecDeque<OutputChunk>,
buffered_bytes: usize,
on_output: OutputFn,
}
impl RunOutputState {
fn new(on_output: OutputFn) -> Self {
Self { buffered: VecDeque::new(), buffered_bytes: 0, on_output }
}
fn emit(&mut self, chunk: OutputChunk) {
let len = chunk_len(&chunk);
self.buffered_bytes += len;
self.buffered.push_back(chunk.clone());
while self.buffered_bytes > MAX_BUFFERED_OUTPUT && self.buffered.len() > 1 {
if let Some(removed) = self.buffered.pop_front() {
self.buffered_bytes = self.buffered_bytes.saturating_sub(chunk_len(&removed));
}
}
(self.on_output)(chunk);
}
}
fn chunk_len(chunk: &OutputChunk) -> usize {
match chunk {
OutputChunk::Stdout { text } | OutputChunk::Stderr { text } | OutputChunk::System { text } => text.len(),
}
}
/// Environment of a launched process: the inherited one (unless cleared) plus `vars`.
#[derive(Clone, Debug, Default)]
struct LaunchEnv {
@@ -54,6 +86,7 @@ struct StopCommand {
struct Entry {
project_root: PathBuf,
id: RunId,
config: RunConfig,
config_id: String,
name: String,
pid: Mutex<Option<u32>>,
@@ -67,13 +100,18 @@ struct Entry {
#[cfg(windows)]
job: Option<ide_core::process::Job>,
stop: Option<StopCommand>,
output: OutputFn,
output: Mutex<RunOutputState>,
sink: Mutex<SharedSink>,
exited: AtomicBool,
code: Mutex<Option<i32>>,
stopping: AtomicBool,
}
impl Entry {
fn emit_output(&self, chunk: OutputChunk) {
self.output.lock().emit(chunk);
}
fn info(&self) -> RunInfo {
RunInfo {
id: self.id,
@@ -479,6 +517,7 @@ impl ProcessManager {
let entry = Arc::new(Entry {
project_root: root.to_path_buf(),
id,
config: config.clone(),
config_id: config.id.clone(),
name: config.name.clone(),
pid: Mutex::new(Some(child.id())),
@@ -487,14 +526,15 @@ impl ProcessManager {
#[cfg(windows)]
job,
stop,
output: on_output.clone(),
output: Mutex::new(RunOutputState::new(on_output)),
sink: Mutex::new(sink),
exited: AtomicBool::new(false),
code: Mutex::new(None),
stopping: AtomicBool::new(false),
});
self.register(entry.clone());
on_output(OutputChunk::System { text: format!("{}\n", inv.display) });
entry.emit_output(OutputChunk::System { text: format!("{}\n", inv.display) });
let (tx, rx) = output_queue();
let stdout = child.stdout.take();
@@ -521,7 +561,7 @@ impl ProcessManager {
)?;
}
let decoder = || OutputDecoder::for_pipes(options.encoding.as_deref());
spawn_pump(rx, on_output.clone(), entry.clone(), sink, [decoder(), decoder()], notice)?;
spawn_pump(rx, entry.clone(), [decoder(), decoder()], notice)?;
Ok(())
})();
if let Err(e) = result {
@@ -626,6 +666,7 @@ impl ProcessManager {
let entry = Arc::new(Entry {
project_root: root.to_path_buf(),
id,
config: config.clone(),
config_id: config.id.clone(),
name: config.name.clone(),
pid: Mutex::new(child.process_id()),
@@ -635,13 +676,14 @@ impl ProcessManager {
#[cfg(windows)]
job: child.process_id().and_then(ide_core::process::Job::for_pid),
stop,
output: on_output.clone(),
output: Mutex::new(RunOutputState::new(on_output)),
sink: Mutex::new(sink),
exited: AtomicBool::new(false),
code: Mutex::new(None),
stopping: AtomicBool::new(false),
});
self.register(entry.clone());
on_output(OutputChunk::System { text: format!("{}\n", inv.display) });
entry.emit_output(OutputChunk::System { text: format!("{}\n", inv.display) });
let (tx, rx) = output_queue();
let result = spawn_reader(
@@ -654,7 +696,7 @@ impl ProcessManager {
)
.and_then(|_| {
let decoder = || OutputDecoder::for_label(options.encoding.as_deref());
spawn_pump(rx, on_output, entry.clone(), sink, [decoder(), decoder()], None)
spawn_pump(rx, entry.clone(), [decoder(), decoder()], None)
});
if let Err(e) = result {
let _ = child.kill();
@@ -763,7 +805,7 @@ impl ProcessManager {
!group_alive(pid, &entry)
};
if let Some(stop) = &entry.stop {
run_stop_command(stop, &entry.output);
run_stop_command(stop, &entry);
if exits_within(grace) {
return;
}
@@ -800,6 +842,40 @@ impl ProcessManager {
live.map(|e| e.info()).collect()
}
pub fn has_live_runs(&self) -> bool {
self.runs.lock().values().any(|entry| {
!entry.exited.load(Ordering::Acquire) || entry.pid.lock().is_some_and(|pid| group_alive(pid, entry))
})
}
/// Rebinds `id`'s output stream to `on_output`, returning its buffered console chunks
/// and configuration without dropping or duplicating output.
pub fn reattach(
&self,
id: RunId,
sink: SharedSink,
on_output: Box<dyn Fn(OutputChunk) + Send + Sync>,
) -> IdeResult<RunAttach> {
let entry = self.entry(id)?;
*entry.sink.lock() = sink;
let buffered = {
let mut out = entry.output.lock();
let chunks: Vec<OutputChunk> = out.buffered.iter().cloned().collect();
out.on_output = Arc::from(on_output);
chunks
};
Ok(RunAttach { info: entry.info(), config: entry.config.clone(), buffered })
}
/// Drops live client output callbacks when a remote window disconnects, keeping
/// running processes and their console ring buffers alive.
pub fn detach_output(&self) {
let entries: Vec<Arc<Entry>> = self.runs.lock().values().cloned().collect();
for entry in entries {
entry.output.lock().on_output = Arc::new(|_| {});
}
}
/// Kills every running process tree at once (shutting down).
pub fn kill_project(&self, root: &Path) {
for entry in self.runs.lock().values().filter(|e| e.project_root == root) {
@@ -821,6 +897,34 @@ impl ProcessManager {
}
}
}
/// Honor external service stop actions (for example `docker compose down`) before
/// forcing run processes to exit.
pub async fn shutdown(&self) {
let entries: Vec<_> = self.runs.lock().values().cloned().collect();
let mut stops = tokio::task::JoinSet::new();
for entry in entries {
let Some(pid) = *entry.pid.lock() else { continue };
if entry.exited.load(Ordering::Acquire) && !group_alive(pid, &entry) {
continue;
}
stops.spawn_blocking(move || {
if !entry.stopping.swap(true, Ordering::AcqRel)
&& let Some(stop) = &entry.stop
{
run_stop_command(stop, &entry);
}
if group_alive(pid, &entry) {
kill_tree(&entry, pid, true);
}
});
}
while let Some(result) = stops.join_next().await {
if let Err(e) = result {
tracing::warn!("could not stop a run during shutdown: {e}");
}
}
}
}
impl Drop for ProcessManager {
@@ -865,7 +969,7 @@ fn run_followup(
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0000_0200 | ide_core::process::CREATE_NO_WINDOW);
}
(entry.output)(OutputChunk::System { text: format!("{}\n", inv.display) });
entry.emit_output(OutputChunk::System { text: format!("{}\n", inv.display) });
let mut child = cmd.spawn()?;
// The follow-up run continues the same launch: it joins the run's job, so a Stop
// reaches its tree too.
@@ -997,11 +1101,12 @@ fn apply_env(cmd: &mut Command, env: &LaunchEnv) {
/// Runs `stop.line` through the platform shell and waits for it (bounded), echoing it
/// and any error output to the console.
fn run_stop_command(stop: &StopCommand, output: &OutputFn) {
output(OutputChunk::System { text: format!("{}\n", stop.line) });
fn run_stop_command(stop: &StopCommand, entry: &Entry) {
entry.emit_output(OutputChunk::System { text: format!("{}\n", stop.line) });
let inv = shell_invocation(&stop.line, cfg!(windows), std::env::var("COMSPEC").ok());
let mut cmd = Command::new(&inv.program);
ide_core::process::prepare(&mut cmd);
ide_core::process::own_group(&mut cmd);
if inv.raw_args {
add_raw_args(&mut cmd, &inv.args);
} else {
@@ -1012,16 +1117,18 @@ fn run_stop_command(stop: &StopCommand, output: &OutputFn) {
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(e) => {
output(OutputChunk::Stderr { text: format!("Cannot run the stop command: {e}\n") });
entry.emit_output(OutputChunk::Stderr { text: format!("Cannot run the stop command: {e}\n") });
return;
}
};
let stderr = child.stderr.take().map(|mut pipe| {
let (send, receive) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
String::from_utf8_lossy(&buf).into_owned()
})
let _ = send.send(String::from_utf8_lossy(&buf).into_owned());
});
receive
});
let deadline = Instant::now() + STOP_COMMAND_TIMEOUT;
let status = loop {
@@ -1029,15 +1136,17 @@ fn run_stop_command(stop: &StopCommand, output: &OutputFn) {
Ok(Some(status)) => break Some(status),
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
_ => {
let _ = child.kill();
ide_core::process::kill_tree(&mut child);
let _ = child.wait();
break None;
}
}
};
let err = stderr.and_then(|h| h.join().ok()).unwrap_or_default();
if !status.is_some_and(|s| s.success()) && !err.trim().is_empty() {
output(OutputChunk::Stderr { text: format!("{}\n", err.trim_end()) });
if !status.is_some_and(|s| s.success()) {
let err = stderr.and_then(|r| r.recv_timeout(Duration::from_millis(100)).ok()).unwrap_or_default();
let detail = status.map_or_else(|| "timed out".to_string(), |s| s.to_string());
tracing::warn!("run stop command failed: {detail}");
entry.emit_output(OutputChunk::Stderr { text: format!("Stop command failed ({detail})\n{err}") });
}
}
@@ -1193,9 +1302,7 @@ fn emit(
/// `decoders` decode stdout and stderr.
fn spawn_pump(
rx: mpsc::Receiver<Msg>,
on_output: OutputFn,
entry: Arc<Entry>,
sink: SharedSink,
decoders: [OutputDecoder; 2],
notice: Option<String>,
) -> std::io::Result<()> {
@@ -1216,7 +1323,7 @@ fn spawn_pump(
let flush = |pending: &mut String, stream: Stream, started: &mut Option<Instant>| {
if !pending.is_empty() {
on_output(chunk(stream, std::mem::take(pending)));
entry.emit_output(chunk(stream, std::mem::take(pending)));
}
*started = None;
};
@@ -1296,12 +1403,12 @@ fn spawn_pump(
rest.push_str(&filter.finish());
}
if !rest.is_empty() {
on_output(chunk(stream, rest));
entry.emit_output(chunk(stream, rest));
}
}
let (code, message) = describe_exit(status);
on_output(OutputChunk::System { text: format!("\n{message}\n") });
entry.emit_output(OutputChunk::System { text: format!("\n{message}\n") });
entry.stdin.lock().take();
if let Some(pty) = &entry.pty {
pty.lock().take();
@@ -1333,7 +1440,8 @@ fn spawn_pump(
*entry.code.lock() = code;
entry.exited.store(true, Ordering::Release);
tracing::debug!(id = %entry.id, ?code, "run exited");
sink.emit(IdeEvent::RunExited { run: entry.id, code });
let target_sink = entry.sink.lock().clone();
target_sink.emit(IdeEvent::RunExited { run: entry.id, code });
})?;
Ok(())
}
+3
Переглянути файл
@@ -1605,7 +1605,10 @@ mod pipenv_tests {
#[test]
fn environments_are_named_as_pipenv_names_them() {
// `sanitize(folder)[:42] + "-" + urlsafe_b64encode(sha256(Pipfile path).digest()[:6])`, from pipenv.
#[cfg(unix)]
assert_eq!(pipenv_env_name(Path::new("/home/me/My Shop (2)")), "My_Shop__2_-6rNTtAUD");
#[cfg(windows)]
assert_eq!(pipenv_env_name(Path::new(r"C:\Users\me\My Shop (2)")), "My_Shop__2_-ED1rXUDC");
}
#[test]
+1 -1
Переглянути файл
@@ -597,7 +597,7 @@ fn saved_python_configs_keep_their_explicit_interpreter() {
config.cwd = Some(Path::new("member").into());
apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
assert_eq!(config.command, command);
assert_eq!(config.env["VIRTUAL_ENV"], root.join("member/.override").to_string_lossy());
assert_eq!(config.env["VIRTUAL_ENV"], root.join("member").join(".override").to_string_lossy());
let saved = without_derived(&config, root, &settings);
assert_eq!(saved.command, command);
}
+60 -4
Переглянути файл
@@ -1,5 +1,5 @@
//! An in-process SSH server for tests (feature `testing`): password `dev` /
//! `secret`, commands answered by a closure, SFTP served from a local
//! `secret`, commands answered by a closure or an explicitly allowed process, SFTP served from a local
//! folder (remote `/x` is `<root>/x`), and a shell that echoes its input
//! (`exit` ends it with status 0). `direct-tcpip` channels are forwarded to local TCP
//! ports, and refused when nothing listens there.
@@ -10,15 +10,34 @@ use russh_sftp::protocol::{Attrs, Data, File, FileAttributes, Handle, Name, Open
use std::collections::HashMap;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener;
use tokio::process::Command;
use tokio::sync::Mutex;
/// Reply of a command: (stdout, exit status).
pub type ExecFn = Arc<dyn Fn(&str) -> (String, u32) + Send + Sync>;
type SpawnFn = Arc<dyn Fn(&str) -> Option<Command> + Send + Sync>;
#[derive(Clone)]
enum Exec {
Reply(ExecFn),
Process(SpawnFn),
}
/// Starts the server; returns its port. `root` backs SFTP.
pub async fn sshd(root: PathBuf, exec: ExecFn) -> u16 {
start(root, Exec::Reply(exec)).await
}
/// Serves stdio of an explicitly chosen command over an SSH exec channel.
pub async fn sshd_with_process(root: PathBuf, exec: impl Fn(&str) -> Option<Command> + Send + Sync + 'static) -> u16 {
start(root, Exec::Process(Arc::new(exec))).await
}
async fn start(root: PathBuf, exec: Exec) -> u16 {
let config = Arc::new(server::Config {
keys: vec![russh::keys::decode_secret_key(include_str!("../tests/fixtures/ssh/host"), None).expect("host key")],
auth_rejection_time: std::time::Duration::from_millis(10),
@@ -37,7 +56,7 @@ pub async fn sshd(root: PathBuf, exec: ExecFn) -> u16 {
#[derive(Clone)]
struct Sshd {
root: PathBuf,
exec: ExecFn,
exec: Exec,
}
impl server::Server for Sshd {
@@ -49,7 +68,7 @@ impl server::Server for Sshd {
struct Conn {
root: PathBuf,
exec: ExecFn,
exec: Exec,
channels: Arc<Mutex<HashMap<ChannelId, Channel<Msg>>>>,
shells: std::collections::HashSet<ChannelId>,
}
@@ -99,7 +118,44 @@ impl server::Handler for Conn {
data: &[u8],
session: &mut Session,
) -> Result<(), Self::Error> {
let (out, code) = (self.exec)(&String::from_utf8_lossy(data));
let command = String::from_utf8_lossy(data);
let Exec::Reply(exec) = &self.exec else {
let Exec::Process(spawn) = &self.exec else { unreachable!() };
let Some(ch) = self.channels.lock().await.remove(&channel) else {
session.channel_failure(channel)?;
return Ok(());
};
let Some(mut cmd) = spawn(&command) else {
session.channel_failure(channel)?;
return Ok(());
};
let mut child = cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).kill_on_drop(true).spawn()?;
let mut input = child.stdin.take().expect("piped stdin");
let mut output = child.stdout.take().expect("piped stdout");
session.channel_success(channel)?;
tokio::spawn(async move {
let (mut reader, mut writer) = tokio::io::split(ch.into_stream());
let feed = async {
let _ = tokio::io::copy(&mut reader, &mut input).await;
drop(input);
};
let drain = async {
let _ = tokio::io::copy(&mut output, &mut writer).await;
let _ = writer.shutdown().await;
};
tokio::pin!(drain);
// EOF from the SSH client closes the child stdin; EOF from the child completes the channel.
tokio::select! {
_ = &mut drain => {}
_ = feed => {
let _ = tokio::time::timeout(std::time::Duration::from_secs(5), &mut drain).await;
}
}
let _ = tokio::time::timeout(std::time::Duration::from_secs(5), child.wait()).await;
});
return Ok(());
};
let (out, code) = exec(&command);
session.channel_success(channel)?;
session.data(channel, out.into_bytes())?;
session.exit_status_request(channel, code)?;
+203 -25
Переглянути файл
@@ -2,6 +2,7 @@
//! such as an SSH shell. Rendering is xterm.js.
mod integration;
mod scrollback;
use ide_core::utf8::Utf8Decoder;
use ide_core::{IdeError, IdeEvent, IdeResult, SharedSink, TerminalId};
@@ -130,6 +131,26 @@ pub struct TerminalInfo {
pub pid: Option<u32>,
}
/// Live terminal session state for reattaching across window reconnects.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct TerminalSessionInfo {
pub id: TerminalId,
pub title: String,
pub pid: Option<u32>,
pub cwd: String,
pub app_title: Option<String>,
pub command_running: bool,
}
/// Snapshot and live binding returned when reattaching to an existing session.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct TerminalAttach {
pub session: TerminalSessionInfo,
pub buffered: String,
}
/// A terminal whose shell runs elsewhere (an SSH channel). Its output and exit
/// arrive through the [`TerminalFeed`] paired with it by [`feed`].
pub trait TerminalChannel: Send + Sync {
@@ -207,11 +228,18 @@ enum Io {
},
}
struct OutputState {
scrollback: scrollback::Scrollback,
on_output: Box<dyn Fn(String) + Send>,
}
struct Session {
/// The window that opened it: closing that window's project closes its terminals.
key: String,
info: TerminalInfo,
io: Io,
output: Arc<Mutex<OutputState>>,
sink: Arc<Mutex<SharedSink>>,
exited: Arc<AtomicBool>,
started: Instant,
/// The first input was logged (startup diagnostics, see `spawn`).
@@ -230,6 +258,9 @@ enum Msg {
Exited(Option<i32>),
}
/// Runs when a PTY exits, before the exit event is forwarded to the current sink.
pub type TerminalExitHook = Arc<dyn Fn(Option<i32>) + Send + Sync>;
impl TerminalManager {
pub fn new() -> Self {
Self::default()
@@ -237,15 +268,16 @@ impl TerminalManager {
/// Starts a shell; output goes to `on_output` from a reader thread, batched
/// (~4ms) to limit IPC chatter and always split on UTF-8 boundaries.
/// Emits `IdeEvent::TerminalExited` to `sink` (the starter's) only.
/// Calls `on_exit` if supplied and emits `IdeEvent::TerminalExited` to the current sink.
pub fn spawn(
&self,
options: TerminalOptions,
key: String,
sink: SharedSink,
on_output: Box<dyn Fn(String) + Send>,
on_exit: Option<TerminalExitHook>,
) -> IdeResult<TerminalInfo> {
self.spawn_impl(options, key, sink, on_output, false)
self.spawn_impl(options, key, sink, on_output, on_exit, false)
}
/// Runs an approved absolute executable with exact arguments and cwd.
@@ -256,6 +288,7 @@ impl TerminalManager {
key: String,
sink: SharedSink,
on_output: Box<dyn Fn(String) + Send>,
on_exit: Option<TerminalExitHook>,
) -> IdeResult<TerminalInfo> {
if !options.shell.as_deref().is_some_and(|p| Path::new(p).is_absolute())
|| !options.cwd.is_absolute()
@@ -263,7 +296,7 @@ impl TerminalManager {
{
return Err(IdeError::invalid("a program PTY requires an absolute executable and an existing cwd"));
}
self.spawn_impl(options, key, sink, on_output, true)
self.spawn_impl(options, key, sink, on_output, on_exit, true)
}
fn spawn_impl(
@@ -272,6 +305,7 @@ impl TerminalManager {
key: String,
sink: SharedSink,
on_output: Box<dyn Fn(String) + Send>,
on_exit: Option<TerminalExitHook>,
exact: bool,
) -> IdeResult<TerminalInfo> {
let size = pty_size(options.cols, options.rows);
@@ -351,10 +385,17 @@ impl TerminalManager {
let _ = child.kill();
let _ = child.wait();
})?;
let output = Arc::new(Mutex::new(OutputState {
scrollback: scrollback::Scrollback::new(cwd.to_string_lossy().into_owned()),
on_output,
}));
let sink = Arc::new(Mutex::new(sink));
let session = Arc::new(Session {
key,
info: info.clone(),
io: Io::Pty { writer, master: Mutex::new(pair.master), killer: Mutex::new(child.clone_killer()) },
output: output.clone(),
sink: sink.clone(),
exited: exited.clone(),
started: Instant::now(),
input_logged: AtomicBool::new(false),
@@ -363,7 +404,7 @@ impl TerminalManager {
let (tx, rx) = mpsc::channel::<Msg>();
let budget = ByteBudget::default();
let out = OutputSender { tx: tx.clone(), budget: budget.clone() };
let out = OutputSender { tx, budget: budget.clone() };
let spawned = spawn_reader(
id,
reader,
@@ -375,15 +416,16 @@ impl TerminalManager {
.and_then(|_| {
spawn_pump(
id,
OutputReceiver { rx, budget },
on_output,
OutputReceiver { rx, budget: budget.clone() },
output,
exited,
self.sessions.clone(),
sink,
Instant::now(),
on_exit,
)
});
if let Err(e) = spawned {
budget.close();
if let Some(s) = self.sessions.lock().remove(&id) {
terminate(&s);
}
@@ -411,18 +453,23 @@ impl TerminalManager {
let id = TerminalId::next();
let info = TerminalInfo { id, title, pid: None };
let exited = Arc::new(AtomicBool::new(false));
let output =
Arc::new(Mutex::new(OutputState { scrollback: scrollback::Scrollback::new(String::new()), on_output }));
let sink = Arc::new(Mutex::new(sink));
let session = Arc::new(Session {
key,
info: info.clone(),
io: Io::Channel { channel, size: Mutex::new(size) },
output: output.clone(),
sink: sink.clone(),
exited: exited.clone(),
started: Instant::now(),
input_logged: AtomicBool::new(false),
});
self.sessions.lock().insert(id, session);
let output = feed.into_parts();
let budget = output.budget.clone();
if let Err(e) = spawn_pump(id, output, on_output, exited, self.sessions.clone(), sink, Instant::now()) {
let receiver = feed.into_parts();
let budget = receiver.budget.clone();
if let Err(e) = spawn_pump(id, receiver, output, exited, self.sessions.clone(), sink, None) {
budget.close();
if let Some(s) = self.sessions.lock().remove(&id) {
terminate(&s);
@@ -500,6 +547,85 @@ impl TerminalManager {
out
}
/// Live sessions belonging to `key`, with their current working directory,
/// running-program title and busy state.
pub fn list_key(&self, key: &str) -> Vec<TerminalSessionInfo> {
let sessions: Vec<Arc<Session>> = self
.sessions
.lock()
.values()
.filter(|s| s.key == key && !s.exited.load(Ordering::Acquire))
.cloned()
.collect();
let mut out: Vec<TerminalSessionInfo> = sessions.iter().map(|s| session_info(s)).collect();
out.sort_by_key(|i| i.id);
out
}
/// Rebinds `id`'s output stream to `on_output`, returning its buffered scrollback
/// and current state without dropping or duplicating bytes between them.
pub fn reattach(
&self,
id: TerminalId,
key: &str,
cols: u16,
rows: u16,
sink: SharedSink,
on_output: Box<dyn Fn(String) + Send>,
) -> IdeResult<TerminalAttach> {
let session = self.session(id)?;
if session.key != key || session.exited.load(Ordering::Acquire) {
return Err(not_found(id));
}
*session.sink.lock() = sink;
let (buffered, cwd, app_title, osc_running, alt_screen) = {
let mut out = session.output.lock();
let buffered = out.scrollback.snapshot();
let cwd = out.scrollback.cwd.clone();
let app_title = out.scrollback.app_title.clone();
let osc_running = out.scrollback.command_running;
let alt_screen = out.scrollback.is_alt_screen();
out.on_output = on_output;
(buffered, cwd, app_title, osc_running, alt_screen)
};
if cols > 0 && rows > 0 {
let _ = self.resize(id, cols, rows);
}
#[cfg(unix)]
if alt_screen
&& let Io::Pty { master, .. } = &session.io
&& let Some(fg) = master.lock().process_group_leader().filter(|&fg| fg > 0)
{
// Full-screen TUIs (`watch`, `vim`, `htop`) repaint on SIGWINCH even when cols×rows matched.
unsafe {
libc::kill(-fg, libc::SIGWINCH);
}
}
#[cfg(not(unix))]
let _ = alt_screen;
let busy = session.info.pid.is_some_and(|pid| foreground_busy(&session, pid));
Ok(TerminalAttach {
session: TerminalSessionInfo {
id: session.info.id,
title: session.info.title.clone(),
pid: session.info.pid,
cwd,
app_title,
command_running: osc_running || busy,
},
buffered,
})
}
/// Drops live client output callbacks when a remote window disconnects, while
/// keeping the PTYs and their scrollback buffers running.
pub fn detach_output(&self) {
let sessions: Vec<Arc<Session>> = self.sessions.lock().values().cloned().collect();
for s in sessions {
s.output.lock().on_output = Box::new(|_| {});
}
}
/// Current PTY size of a session (for diagnostics and tests).
pub fn size(&self, id: TerminalId) -> IdeResult<(u16, u16)> {
let session = self.session(id)?;
@@ -711,25 +837,44 @@ fn spawn_waiter(
Ok(())
}
fn session_info(session: &Session) -> TerminalSessionInfo {
let (cwd, app_title, osc_running) = {
let out = session.output.lock();
(out.scrollback.cwd.clone(), out.scrollback.app_title.clone(), out.scrollback.command_running)
};
let busy = session.info.pid.is_some_and(|pid| foreground_busy(session, pid));
TerminalSessionInfo {
id: session.info.id,
title: session.info.title.clone(),
pid: session.info.pid,
cwd,
app_title,
command_running: osc_running || busy,
}
}
fn spawn_pump(
id: TerminalId,
output: OutputReceiver,
on_output: Box<dyn Fn(String) + Send>,
receiver: OutputReceiver,
output: Arc<Mutex<OutputState>>,
exited: Arc<AtomicBool>,
sessions: Sessions,
sink: SharedSink,
started: Instant,
sink: Arc<Mutex<SharedSink>>,
on_exit: Option<TerminalExitHook>,
) -> std::io::Result<()> {
let started = Instant::now();
std::thread::Builder::new().name(format!("openidea-term-pump-{}", id.0)).spawn(move || {
let first_output = std::cell::Cell::new(true);
let on_output = move |text: String| {
let emit_output = |text: String| {
if first_output.replace(false) {
// ConPTY asks for the cursor position (`ESC[6n`) and waits for the answer.
let cursor_query = text.contains("\x1b[6n");
let ms = started.elapsed().as_millis();
tracing::info!(%id, ms, bytes = text.len(), cursor_query, "terminal first output");
}
on_output(text)
let mut out = output.lock();
out.scrollback.push(&text);
(out.on_output)(text);
};
let mut decoder = Utf8Decoder::new();
let mut pending = String::new();
@@ -739,7 +884,7 @@ fn spawn_pump(
let flush = |pending: &mut String, batch_started: &mut Option<Instant>| {
if !pending.is_empty() {
on_output(std::mem::take(pending));
emit_output(std::mem::take(pending));
}
*batch_started = None;
};
@@ -753,10 +898,10 @@ fn spawn_pump(
(Some(a), None) | (None, Some(a)) => a,
(None, None) => Duration::from_secs(3600),
};
match output.rx.recv_timeout(wait) {
match receiver.rx.recv_timeout(wait) {
Ok(Msg::Data(bytes)) => {
// The pump owns these bytes now; wake any producer waiting on the cap.
output.budget.release(bytes.len());
receiver.budget.release(bytes.len());
decoder.decode_into(&bytes, &mut pending);
if !pending.is_empty() && batch_started.is_none() {
batch_started = Some(Instant::now());
@@ -783,11 +928,15 @@ fn spawn_pump(
pending.push_str(&decoder.finish());
flush(&mut pending, &mut batch_started);
exited.store(true, Ordering::Release);
output.budget.close();
receiver.budget.close();
sessions.lock().remove(&id);
let code = exit.flatten();
tracing::debug!(%id, ?code, "terminal exited");
sink.emit(IdeEvent::TerminalExited { terminal: id, code });
let target_sink = sink.lock().clone();
if let Some(on_exit) = on_exit {
on_exit(code);
}
target_sink.emit(IdeEvent::TerminalExited { terminal: id, code });
})?;
Ok(())
}
@@ -1126,6 +1275,7 @@ mod tests {
Box::new(move |s| {
let _ = tx.send(s);
}),
None,
)
.expect("spawn");
(info, rx)
@@ -1192,14 +1342,14 @@ mod tests {
let h = harness();
let mut options = sh("exit 0");
options.shell = None;
assert!(h.manager.spawn_program(options, "test".into(), h.sink.clone(), Box::new(|_| {})).is_err());
assert!(h.manager.spawn_program(options, "test".into(), h.sink.clone(), Box::new(|_| {}), None).is_err());
let mut options = sh("exit 0");
options.shell = Some("sh".into());
assert!(h.manager.spawn_program(options, "test".into(), h.sink.clone(), Box::new(|_| {})).is_err());
assert!(h.manager.spawn_program(options, "test".into(), h.sink.clone(), Box::new(|_| {}), None).is_err());
let mut options = sh("exit 0");
options.cwd = std::env::temp_dir().join(format!("openidea-missing-{}", std::process::id())).into();
assert!(!options.cwd.exists());
assert!(h.manager.spawn_program(options, "test".into(), h.sink.clone(), Box::new(|_| {})).is_err());
assert!(h.manager.spawn_program(options, "test".into(), h.sink.clone(), Box::new(|_| {}), None).is_err());
assert!(h.manager.list().is_empty());
}
@@ -1329,7 +1479,7 @@ mod tests {
let h = harness();
let (other_sink, other_events) = channel_sink();
let (mine, _rx) = spawn_collect(&h, sh("exit 1"));
let theirs = h.manager.spawn(sh("exit 2"), "other".into(), other_sink, Box::new(|_| {})).expect("spawn");
let theirs = h.manager.spawn(sh("exit 2"), "other".into(), other_sink, Box::new(|_| {}), None).expect("spawn");
match h.events.recv_timeout(Duration::from_secs(10)).expect("exit event") {
IdeEvent::TerminalExited { terminal, code } => assert_eq!((terminal, code), (mine.id, Some(1))),
e => panic!("unexpected {e:?}"),
@@ -1342,6 +1492,34 @@ mod tests {
assert!(h.events.try_recv().is_err() && other_events.try_recv().is_err(), "no cross delivery");
}
#[test]
fn reattach_keeps_the_program_exit_hook_and_rebinds_the_event_sink() {
let h = harness();
let (completion, completed) = mpsc::channel();
let info = h
.manager
.spawn_program(
sh("read _; exit 7"),
"test".into(),
h.sink.clone(),
Box::new(|_| {}),
Some(Arc::new(move |code| {
let _ = completion.send(code);
})),
)
.unwrap();
let (sink, events) = channel_sink();
h.manager.reattach(info.id, "test", 80, 24, sink, Box::new(|_| {})).unwrap();
h.manager.write(info.id, "\n").unwrap();
match events.recv_timeout(Duration::from_secs(10)).expect("exit event after reattach") {
IdeEvent::TerminalExited { terminal, code } => assert_eq!((terminal, code), (info.id, Some(7))),
e => panic!("unexpected {e:?}"),
}
assert_eq!(completed.try_recv(), Ok(Some(7)));
assert!(h.events.try_recv().is_err(), "exit delivered to the old sink");
}
#[test]
fn wsl_folder_gets_the_distro_shell_unless_one_is_chosen() {
let mut o = sh("true");
+297
Переглянути файл
@@ -0,0 +1,297 @@
//! Bounded UTF-8 scrollback and OSC state tracker so a reattached terminal
//! restores recent output, alternate-screen state, working directory, title
//! and command-running state without gaps.
/// Maximum scrollback retained per live PTY session (256 KiB).
const MAX_SCROLLBACK_BYTES: usize = 256 * 1024;
/// Maximum incomplete OSC sequence buffered across chunks.
const MAX_OSC_TAIL: usize = 2048;
/// PowerShell / OpenIDEA clear-scrollback OSC marker.
const CLEAR_MARKER: &str = "\x1b]133;OpenIDEA;ClearScrollback\x07";
const CLEAR_CSI: &str = "\x1b[3J";
const ALT_ON: [&str; 3] = ["\x1b[?1049h", "\x1b[?1047h", "\x1b[?47h"];
const ALT_OFF: [&str; 3] = ["\x1b[?1049l", "\x1b[?1047l", "\x1b[?47l"];
pub(crate) struct Scrollback {
buf: String,
/// Whether text evicted before `buf` left the terminal on the alternate screen.
evicted_alt_screen: bool,
/// Whether the current terminal state (evicted + `buf`) is on the alternate screen.
alt_screen: bool,
osc_tail: String,
pub cwd: String,
pub app_title: Option<String>,
pub command_running: bool,
}
impl Scrollback {
pub fn new(initial_cwd: String) -> Self {
Self {
buf: String::new(),
evicted_alt_screen: false,
alt_screen: false,
osc_tail: String::new(),
cwd: initial_cwd,
app_title: None,
command_running: false,
}
}
pub fn is_alt_screen(&self) -> bool {
self.alt_screen
}
pub fn push(&mut self, chunk: &str) {
if chunk.is_empty() {
return;
}
self.scan_osc(chunk);
self.alt_screen = scan_alt_screen(self.alt_screen, chunk);
// Honour explicit scrollback clears so `clear` / Cmd+K doesn't replay cleared history.
let mut slice = chunk;
if let Some(idx) = last_clear_end(slice) {
self.buf.clear();
self.evicted_alt_screen = false;
slice = &slice[idx..];
} else if !self.buf.is_empty() {
// Handle a clear marker split across the boundary between `self.buf` and `chunk`.
let tail_start = floor_char_boundary(&self.buf, self.buf.len().saturating_sub(CLEAR_MARKER.len()));
let combined = format!("{}{}", &self.buf[tail_start..], slice);
if let Some(idx) = last_clear_end(&combined) {
let tail_len = self.buf.len() - tail_start;
self.buf.clear();
self.evicted_alt_screen = false;
if idx > tail_len {
slice = &slice[idx - tail_len..];
} else {
slice = "";
}
}
}
self.buf.push_str(slice);
if self.buf.len() > MAX_SCROLLBACK_BYTES {
let mut cut = self.buf.len() - MAX_SCROLLBACK_BYTES;
while cut < self.buf.len() && !self.buf.is_char_boundary(cut) {
cut += 1;
}
// Avoid slicing inside a short CSI/ESC sequence near `cut`.
cut = avoid_mid_escape(&self.buf, cut);
if cut > 0 {
self.evicted_alt_screen = scan_alt_screen(self.evicted_alt_screen, &self.buf[..cut]);
self.buf.drain(..cut);
}
}
}
/// Buffered output to replay into a freshly attached xterm.js instance.
pub fn snapshot(&self) -> String {
if self.evicted_alt_screen {
let mut out = String::with_capacity("\x1b[?1049h".len() + self.buf.len());
out.push_str("\x1b[?1049h");
out.push_str(&self.buf);
out
} else {
self.buf.clone()
}
}
fn scan_osc(&mut self, chunk: &str) {
if self.osc_tail.is_empty() && !chunk.contains("\x1b]") {
return;
}
let mut combined = std::mem::take(&mut self.osc_tail);
combined.push_str(chunk);
let bytes = combined.as_bytes();
let mut i = 0;
while i < bytes.len() {
let Some(rel) = find_osc_start(&bytes[i..]) else {
// Keep a trailinglone ESC in case `]` arrives in the next chunk.
if bytes.last() == Some(&0x1b) {
self.osc_tail.push('\x1b');
}
return;
};
let start = i + rel;
let body_start = start + 2;
if let Some((body_end, next_i)) = find_osc_end(bytes, body_start) {
if let Ok(body) = std::str::from_utf8(&bytes[body_start..body_end]) {
self.apply_osc(body);
}
i = next_i;
} else {
let rem = &combined[start..];
if rem.len() <= MAX_OSC_TAIL {
self.osc_tail.push_str(rem);
}
return;
}
}
}
fn apply_osc(&mut self, body: &str) {
if let Some(title) = body.strip_prefix("0;").or_else(|| body.strip_prefix("2;")) {
let trimmed = title.trim();
self.app_title = (!trimmed.is_empty()).then(|| trimmed.to_owned());
} else if let Some(url) = body.strip_prefix("7;") {
if let Some(path) = parse_file_url_path(url) {
self.cwd = path;
}
} else if let Some(rest) = body.strip_prefix("133;") {
if rest == "C" {
self.command_running = true;
} else if rest == "D" || rest.starts_with("D;") {
self.command_running = false;
}
}
}
}
fn floor_char_boundary(s: &str, mut index: usize) -> usize {
if index >= s.len() {
return s.len();
}
while index > 0 && !s.is_char_boundary(index) {
index -= 1;
}
index
}
fn last_clear_end(s: &str) -> Option<usize> {
let a = s.rfind(CLEAR_MARKER).map(|i| i + CLEAR_MARKER.len());
let b = s.rfind(CLEAR_CSI).map(|i| i + CLEAR_CSI.len());
match (a, b) {
(Some(x), Some(y)) => Some(x.max(y)),
(x, y) => x.or(y),
}
}
fn scan_alt_screen(mut current: bool, text: &str) -> bool {
if !text.contains("\x1b[?") {
return current;
}
let bytes = text.as_bytes();
let mut i = 0;
while i + 4 < bytes.len() {
if bytes[i] == 0x1b && bytes[i + 1] == b'[' && bytes[i + 2] == b'?' {
let tail = &text[i..];
if ALT_ON.iter().any(|p| tail.starts_with(p)) {
current = true;
} else if ALT_OFF.iter().any(|p| tail.starts_with(p)) {
current = false;
}
}
i += 1;
}
current
}
fn avoid_mid_escape(s: &str, cut: usize) -> usize {
let lookback = floor_char_boundary(s, cut.saturating_sub(16));
let Some(esc_rel) = s[lookback..cut].rfind('\x1b') else {
return cut;
};
let esc = lookback + esc_rel;
// Check whether the escape sequence already ended before `cut`.
let bytes = &s.as_bytes()[esc + 1..cut];
if bytes.first() == Some(&b'[') {
if bytes[1..].iter().any(|&b| (0x40..=0x7e).contains(&b)) {
return cut;
}
// Advance to end of CSI sequence (bounded to 32 bytes).
let max = (cut + 32).min(s.len());
for idx in cut..max {
let b = s.as_bytes()[idx];
if (0x40..=0x7e).contains(&b) {
return idx + 1;
}
}
}
cut
}
fn find_osc_start(bytes: &[u8]) -> Option<usize> {
bytes.windows(2).position(|w| w == b"\x1b]")
}
fn find_osc_end(bytes: &[u8], mut i: usize) -> Option<(usize, usize)> {
while i < bytes.len() {
if bytes[i] == 0x07 {
return Some((i, i + 1));
}
if bytes[i] == 0x1b && bytes.get(i + 1) == Some(&b'\\') {
return Some((i, i + 2));
}
i += 1;
}
None
}
fn parse_file_url_path(url: &str) -> Option<String> {
let rest = url.trim().strip_prefix("file://")?;
let slash = rest.find('/')?;
let raw_path = &rest[slash..];
let decoded = percent_decode(raw_path)?;
(!decoded.is_empty()).then_some(decoded)
}
fn percent_decode(input: &str) -> Option<String> {
let bytes = input.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
let hi = (bytes[i + 1] as char).to_digit(16)?;
let lo = (bytes[i + 2] as char).to_digit(16)?;
out.push(((hi << 4) | lo) as u8);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tracks_osc_cwd_title_and_command_across_split_chunks() {
let mut sb = Scrollback::new("/initial".into());
sb.push("\x1b]7;file://host/home/coder/my%20");
sb.push("repo\x07\x1b]2;watch date\x1b\\\x1b]133;C\x07tick 1\r\n");
assert_eq!(sb.cwd, "/home/coder/my repo");
assert_eq!(sb.app_title.as_deref(), Some("watch date"));
assert!(sb.command_running);
sb.push("\x1b]133;D;0\x07");
assert!(!sb.command_running);
}
#[test]
fn preserves_alt_screen_prefix_when_initial_enter_scrolls_off() {
let mut sb = Scrollback::new("/".into());
sb.push("\x1b[?1049hframe-0\r\n");
assert!(sb.is_alt_screen());
let filler = "x".repeat(MAX_SCROLLBACK_BYTES + 1024);
sb.push(&filler);
let snap = sb.snapshot();
assert!(snap.starts_with("\x1b[?1049h"));
assert!(sb.is_alt_screen());
sb.push("\x1b[?1049lprompt$ ");
assert!(!sb.is_alt_screen());
}
#[test]
fn clear_scrollback_drops_prior_history() {
let mut sb = Scrollback::new("/".into());
sb.push("old line 1\r\nold line 2\r\n");
sb.push("\x1b[2J\x1b[3Jfresh prompt$ ");
assert_eq!(sb.snapshot(), "fresh prompt$ ");
}
}
+13 -5
Переглянути файл
@@ -933,6 +933,8 @@ mod ignore;
mod index_writes;
mod log_index;
mod manage;
mod metadata_watch;
pub use metadata_watch::MetadataWatch;
mod ops;
mod patch;
mod preserve;
@@ -1326,10 +1328,15 @@ impl Repo {
/// Reference names and peeled commit ids, including tags and detached HEAD.
pub fn log_refs(&self) -> IdeResult<std::collections::BTreeMap<String, String>> {
let repo = self.gix()?;
Ok(history::decorations(&repo)?
.into_iter()
.flat_map(|(id, names)| names.into_iter().map(move |name| (name, id.to_string())))
.collect())
let (decorations, _) = self.ref_decorations(&repo)?;
let mut refs = std::collections::BTreeMap::new();
for (id, names) in decorations.iter() {
let id = id.to_string();
for name in names {
refs.insert(name.clone(), id.clone());
}
}
Ok(refs)
}
pub fn log_users(&self) -> IdeResult<Vec<String>> {
let _scope = self.execution_scope();
@@ -1486,7 +1493,8 @@ impl Repo {
/// Local and remote branches; the current branch first, then most recent first.
pub fn branches(&self) -> IdeResult<Vec<Branch>> {
let _scope = self.execution_scope();
refs::branches(self)
let repo = self.gix()?;
self.cached_branches(&repo)
}
/// Stash entries, newest (`stash@{0}`) first.
pub fn stashes(&self) -> IdeResult<Vec<Stash>> {
+224
Переглянути файл
@@ -0,0 +1,224 @@
use crate::Repo;
use ide_core::{IdeError, IdeResult};
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};
const QUIET: Duration = Duration::from_millis(100);
const MAX_WAIT: Duration = Duration::from_secs(1);
/// Watches the Git metadata (`HEAD`, `index`, `packed-refs`, `refs/**`) of repositories whose
/// git directories lie outside the project's own file watcher: a project opened in a
/// subfolder of its repository, a linked worktree, a mapped repository elsewhere. Commits,
/// checkouts and resets run in a terminal then reach the IDE like those below the project.
pub struct MetadataWatch {
watcher: Mutex<RecommendedWatcher>,
/// Watched directory → whether only its top-level metadata files count (`false`: a
/// recursively watched `refs` directory, where every non-lock file counts).
dirs: Arc<Mutex<BTreeMap<PathBuf, bool>>>,
}
impl MetadataWatch {
/// `changed` receives the metadata files that changed, coalesced over short bursts.
pub fn new(changed: impl Fn(Vec<PathBuf>) + Send + 'static) -> IdeResult<Self> {
let dirs = Arc::new(Mutex::new(BTreeMap::<PathBuf, bool>::new()));
let (tx, rx) = mpsc::channel::<PathBuf>();
let watched = dirs.clone();
let watcher = notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
let Ok(event) = event else { return };
if event.kind.is_access() {
return;
}
let dirs = watched.lock().unwrap_or_else(|e| e.into_inner());
for path in event.paths.iter().filter(|p| is_metadata(&dirs, p)) {
let _ = tx.send(path.clone());
}
})
.map_err(|e| IdeError::internal(format!("Git metadata watcher: {e}")))?;
std::thread::Builder::new()
.name("openidea-git-metadata".into())
.spawn(move || {
while let Ok(first) = rx.recv() {
let deadline = Instant::now() + MAX_WAIT;
let mut paths = BTreeSet::from([first]);
while Instant::now() < deadline
&& let Ok(path) = rx.recv_timeout(QUIET)
{
paths.insert(path);
}
changed(paths.into_iter().collect());
}
})
.map_err(|e| IdeError::internal(format!("Git metadata watcher: {e}")))?;
Ok(Self { watcher: Mutex::new(watcher), dirs })
}
/// Watches the metadata of `repos` that the project watcher of `covered` doesn't report:
/// git directories outside it, and submodule git directories (`.git/modules/…`) inside it.
pub fn set_repos(&self, repos: &[Arc<Repo>], covered: &Path) {
let covered = dunce::canonicalize(covered).unwrap_or_else(|_| covered.to_path_buf());
let mut wanted = BTreeMap::new();
for repo in repos {
let Ok([git_dir, common_dir]) = repo.metadata_dirs() else { continue };
for (dir, top_level) in [(git_dir, true), (common_dir.clone(), true), (common_dir.join("refs"), false)] {
if let Ok(dir) = dunce::canonicalize(&dir)
&& !watched_by_project(&covered, &dir)
{
wanted.insert(dir, top_level);
}
}
}
let mut watcher = self.watcher.lock().unwrap_or_else(|e| e.into_inner());
let mut dirs = self.dirs.lock().unwrap_or_else(|e| e.into_inner());
for dir in dirs.keys().filter(|d| !wanted.contains_key(*d)) {
let _ = watcher.unwatch(dir);
}
wanted.retain(|dir, top_level| {
if dirs.contains_key(dir) {
return true;
}
let mode = if *top_level { RecursiveMode::NonRecursive } else { RecursiveMode::Recursive };
watcher.watch(dir, mode).map_err(|e| tracing::debug!("Git metadata watcher {}: {e}", dir.display())).is_ok()
});
*dirs = wanted;
}
pub fn watched_dirs(&self) -> Vec<PathBuf> {
self.dirs.lock().unwrap_or_else(|e| e.into_inner()).keys().cloned().collect()
}
}
fn watched_by_project(root: &Path, dir: &Path) -> bool {
dir.strip_prefix(root)
.is_ok_and(|rel| !rel.components().skip_while(|c| c.as_os_str() != ".git").any(|c| c.as_os_str() == "modules"))
}
fn is_metadata(dirs: &BTreeMap<PathBuf, bool>, path: &Path) -> bool {
if path.file_name().is_some_and(|n| n.to_string_lossy().ends_with(".lock")) {
return false;
}
dirs.iter().any(|(dir, top_level)| match path.strip_prefix(dir) {
Ok(rest) if *top_level => rest.to_str().is_some_and(|r| matches!(r, "HEAD" | "index" | "packed-refs")),
Ok(rest) => !rest.as_os_str().is_empty(),
Err(_) => false,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn git(dir: &Path, args: &[&str]) {
let out = std::process::Command::new("git")
.current_dir(dir)
.args(["-c", "[email protected]", "-c", "user.name=t", "-c", "commit.gpgsign=false"])
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
}
fn wait_for(seen: &Mutex<Vec<PathBuf>>, pred: impl Fn(&[PathBuf]) -> bool) -> bool {
let deadline = Instant::now() + Duration::from_secs(10);
while Instant::now() < deadline {
if pred(&seen.lock().unwrap()) {
return true;
}
std::thread::sleep(Duration::from_millis(50));
}
false
}
#[test]
fn metadata_files_count_and_locks_and_objects_do_not() {
let dirs = BTreeMap::from([(PathBuf::from("/r/.git"), true), (PathBuf::from("/r/.git/refs"), false)]);
for (path, expected) in [
("/r/.git/HEAD", true),
("/r/.git/index", true),
("/r/.git/packed-refs", true),
("/r/.git/refs/heads/main", true),
("/r/.git/refs/heads/feature/x", true),
("/r/.git/index.lock", false),
("/r/.git/refs/heads/main.lock", false),
("/r/.git/objects/aa/bb", false),
("/r/.git/logs/HEAD", false),
("/r/.git/COMMIT_EDITMSG", false),
("/r/src/HEAD", false),
] {
assert_eq!(is_metadata(&dirs, Path::new(path)), expected, "{path}");
}
}
/// The project folder is a subfolder of its repository, or a linked worktree: a commit made
/// in a terminal writes only outside it, and still surfaces.
#[test]
fn external_commits_surface_for_projects_outside_their_git_dir() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let main = base.join("main");
std::fs::create_dir_all(main.join("sub")).unwrap();
git(&main, &["init", "-q", "-b", "main"]);
git(&main, &["commit", "-q", "--allow-empty", "-m", "init"]);
git(&main, &["worktree", "add", "-q", "-b", "topic", base.join("wt").to_str().unwrap()]);
for project in [main.join("sub"), base.join("wt")] {
let repo = Arc::new(Repo::discover(&project).unwrap().unwrap());
let seen = Arc::new(Mutex::new(Vec::new()));
let watch = {
let seen = seen.clone();
MetadataWatch::new(move |paths| seen.lock().unwrap().extend(paths)).unwrap()
};
watch.set_repos(std::slice::from_ref(&repo), &project);
assert!(!watch.watched_dirs().is_empty(), "{}", project.display());
std::thread::sleep(Duration::from_millis(300));
std::fs::write(project.join("a.txt"), project.to_string_lossy().as_bytes()).unwrap();
git(&project, &["add", "a.txt"]);
git(&project, &["commit", "-q", "-m", "change"]);
assert!(
wait_for(&seen, |p| p.iter().any(|p| p.starts_with(repo.metadata_dirs().unwrap()[1].join("refs")))),
"{}: {:?}",
project.display(),
seen.lock().unwrap()
);
assert!(
wait_for(&seen, |p| p.iter().any(|p| p.ends_with("index"))),
"{}: {:?}",
project.display(),
seen.lock().unwrap()
);
}
}
#[test]
fn the_project_watcher_reports_its_git_dirs_but_not_submodule_ones() {
let root = Path::new("/p");
for (dir, expected) in [
("/p/.git", true),
("/p/.git/refs", true),
("/p/.git/worktrees/wt", true),
("/p/nested/.git", true),
("/p/.git/modules/lib", false),
("/p/.git/modules/lib/refs", false),
("/p/.git/modules/a/modules/b", false),
("/elsewhere/.git", false),
] {
assert_eq!(watched_by_project(root, Path::new(dir)), expected, "{dir}");
}
}
#[test]
fn metadata_below_the_covered_folder_is_left_to_the_project_watcher() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
git(&root, &["init", "-q"]);
let repo = Arc::new(Repo::discover(&root).unwrap().unwrap());
let watch = MetadataWatch::new(|_| {}).unwrap();
watch.set_repos(std::slice::from_ref(&repo), &root);
assert!(watch.watched_dirs().is_empty());
watch.set_repos(std::slice::from_ref(&repo), &root.join("elsewhere"));
assert_eq!(watch.watched_dirs().len(), 2, "{:?}", watch.watched_dirs());
watch.set_repos(&[], &root);
assert!(watch.watched_dirs().is_empty());
}
}
+154 -6
Переглянути файл
@@ -4,9 +4,11 @@
//! even for a one-row page. A page now stats `HEAD`, `packed-refs` and the directories under
//! `refs/` instead: git replaces a loose ref by renaming a lock file over it, which changes
//! the modification time of the ref's directory, and rewrites `packed-refs` the same way.
//! Branch lists reuse the same snapshot because their ref walk and ahead/behind work are
//! otherwise repeated for every VCS view refresh.
use crate::Repo;
use crate::repo::absolute;
use crate::{Branch, Repo};
use gix::ObjectId;
use ide_core::IdeResult;
use std::collections::HashMap;
@@ -24,6 +26,7 @@ pub(crate) type Decorations = Arc<HashMap<ObjectId, Vec<String>>>;
#[derive(Default)]
pub(crate) struct RefDecorations {
snapshot: Option<Snapshot>,
branches: Option<BranchSnapshot>,
/// Changes when the decorations do, so cached views of them can be keyed by it.
generation: u64,
}
@@ -34,11 +37,37 @@ struct Snapshot {
reusable: bool,
}
struct BranchSnapshot {
branches: Vec<Branch>,
generation: u64,
/// The exact ref stamp also catches a checkout of another branch at the same commit.
references: Vec<(PathBuf, Stat)>,
trusted: bool,
configuration: Vec<(PathBuf, Stat)>,
reusable: bool,
}
fn stat(path: &Path) -> Stat {
let metadata = std::fs::metadata(path).ok()?;
Some((metadata.modified().ok()?, metadata.len()))
}
fn reusable(stamp: &[(PathBuf, Stat)], taken: SystemTime) -> bool {
stamp.iter().all(|(_, stat)| stat.is_none_or(|(modified, _)| modified + RACY_WINDOW <= taken))
}
fn configuration_stamp(git_dir: &Path, common_dir: &Path) -> Vec<(PathBuf, Stat)> {
[
common_dir.join("config"),
git_dir.join("config.worktree"),
common_dir.join("config.worktree"),
common_dir.join("shallow"),
]
.into_iter()
.map(|path| (path.clone(), stat(&path)))
.collect()
}
/// `HEAD`, `packed-refs` and every directory under `refs/`.
fn stamp(git_dir: &Path, common_dir: &Path) -> Vec<(PathBuf, Stat)> {
let mut paths = vec![git_dir.join("HEAD"), common_dir.join("packed-refs")];
@@ -64,7 +93,7 @@ impl RefDecorations {
let taken = SystemTime::now();
let stamp = stamp(git_dir, common_dir);
let map = crate::history::decorations(repo)?;
let reusable = stamp.iter().all(|(_, stat)| stat.is_none_or(|(modified, _)| modified + RACY_WINDOW <= taken));
let reusable = reusable(&stamp, taken);
let unchanged = self.snapshot.as_ref().is_some_and(|old| *old.map == map);
let map = match &self.snapshot {
Some(old) if unchanged => old.map.clone(),
@@ -76,6 +105,45 @@ impl RefDecorations {
self.snapshot = Some(Snapshot { map: map.clone(), stamp, reusable });
Ok((map, self.generation))
}
fn branches(
&mut self,
repo: &gix::Repository,
git_dir: &Path,
common_dir: &Path,
trusted: bool,
) -> IdeResult<Vec<Branch>> {
let (_, generation) = self.get(repo, git_dir, common_dir)?;
let references = self
.snapshot
.as_ref()
.ok_or_else(|| ide_core::IdeError::internal("reference cache did not populate a snapshot"))?
.stamp
.clone();
let taken = SystemTime::now();
let configuration = configuration_stamp(git_dir, common_dir);
if let Some(snapshot) = &self.branches
&& snapshot.reusable
&& snapshot.generation == generation
&& snapshot.references == references
&& snapshot.trusted == trusted
&& snapshot.configuration == configuration
{
return Ok(snapshot.branches.clone());
}
let branches = crate::refs::branches(repo)?;
let reusable =
self.snapshot.as_ref().is_some_and(|snapshot| snapshot.reusable) && reusable(&configuration, taken);
self.branches = Some(BranchSnapshot {
branches: branches.clone(),
generation,
references,
trusted,
configuration,
reusable,
});
Ok(branches)
}
}
impl Repo {
@@ -84,6 +152,17 @@ impl Repo {
let common_dir = absolute(repo.common_dir())?;
self.ref_decorations.lock().unwrap_or_else(|p| p.into_inner()).get(repo, &self.git_dir, &common_dir)
}
pub(crate) fn cached_branches(&self, repo: &gix::Repository) -> IdeResult<Vec<Branch>> {
let common_dir = absolute(repo.common_dir())?;
let trusted = self.execution_allowed.load(std::sync::atomic::Ordering::Acquire);
self.ref_decorations.lock().unwrap_or_else(|p| p.into_inner()).branches(
repo,
&self.git_dir,
&common_dir,
trusted,
)
}
}
#[cfg(test)]
@@ -112,11 +191,18 @@ mod tests {
git(dir, &["rev-parse", "HEAD"])
}
/// Sets the modification time of `HEAD`, `packed-refs` and every directory under `refs/`.
/// Sets the modification time of every metadata path used by the ref and branch caches.
fn set_ref_times(repo: &Repo, time: SystemTime) {
let git = repo.git_dir.clone();
let mut paths = vec![git.join("HEAD"), git.join("packed-refs")];
let mut pending = vec![git.join("refs")];
let [git, common] = repo.metadata_dirs().unwrap();
let mut paths = vec![
git.join("HEAD"),
common.join("packed-refs"),
common.join("config"),
git.join("config.worktree"),
common.join("config.worktree"),
common.join("shallow"),
];
let mut pending = vec![common.join("refs")];
while let Some(dir) = pending.pop() {
pending.extend(std::fs::read_dir(&dir).unwrap().flatten().filter(|e| e.path().is_dir()).map(|e| e.path()));
paths.push(dir);
@@ -175,6 +261,68 @@ mod tests {
assert_eq!(decorations_scans(), after_first, "a warm page listed the refs again");
}
#[test]
fn warm_log_refs_do_not_list_the_refs() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
commit(dir, "first");
for i in 0..20 {
git(dir, &["branch", &format!("b{i}")]);
}
let repo = Repo::discover(dir).unwrap().unwrap();
settle(&repo);
let after_first = decorations_scans();
for _ in 0..5 {
assert!(repo.log_refs().unwrap().contains_key("main"));
}
assert_eq!(decorations_scans(), after_first, "warm log refs listed the refs again");
}
#[test]
fn warm_branch_lists_reuse_the_ref_walk() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let first = commit(dir, "first");
git(dir, &["remote", "add", "origin", "."]);
git(dir, &["update-ref", "refs/remotes/origin/main", &first]);
let repo = Repo::discover(dir).unwrap().unwrap();
repo.set_execution_allowed(true);
set_ref_times(&repo, SystemTime::now() - Duration::from_secs(3600));
let scans = crate::refs::branch_scans();
assert!(repo.branches().unwrap().iter().any(|branch| branch.name == "origin/main"));
let after_first = crate::refs::branch_scans();
assert!(after_first > scans);
for _ in 0..5 {
repo.branches().unwrap();
}
assert_eq!(crate::refs::branch_scans(), after_first, "warm branch list walked the refs again");
git(dir, &["branch", "side"]);
assert!(repo.branches().unwrap().iter().any(|branch| branch.name == "side"));
assert!(crate::refs::branch_scans() > after_first, "branch creation did not invalidate the cache");
git(dir, &["checkout", "-q", "side"]);
let at_side = repo.branches().unwrap();
assert!(at_side.iter().any(|branch| branch.name == "side" && branch.current));
assert!(!at_side.iter().any(|branch| branch.name == "main" && branch.current));
let scans = crate::refs::branch_scans();
git(dir, &["config", "branch.main.remote", "origin"]);
git(dir, &["config", "branch.main.merge", "refs/heads/main"]);
let main = repo.branches().unwrap().into_iter().find(|branch| branch.name == "main").unwrap();
assert_eq!(main.upstream.as_deref(), Some("origin/main"));
assert!(crate::refs::branch_scans() > scans, "config change did not invalidate the cache");
repo.set_execution_allowed(false);
let restricted = repo.branches().unwrap().into_iter().find(|branch| branch.name == "main").unwrap();
assert_eq!(restricted.upstream, None);
repo.set_execution_allowed(true);
let trusted = repo.branches().unwrap().into_iter().find(|branch| branch.name == "main").unwrap();
assert_eq!(trusted.upstream.as_deref(), Some("origin/main"));
}
#[test]
fn fresh_ref_timestamps_are_not_trusted() {
let tmp = tempfile::tempdir().unwrap();
+17 -8
Переглянути файл
@@ -137,8 +137,17 @@ fn commit_time_ms(repo: &gix::Repository, id: gix::ObjectId) -> f64 {
repo.find_commit(id).ok().and_then(|c| c.time().ok()).map(|t| t.seconds as f64 * 1000.0).unwrap_or(0.0)
}
pub(crate) fn branches(r: &Repo) -> IdeResult<Vec<Branch>> {
let repo = r.gix()?;
#[cfg(test)]
thread_local!(static BRANCH_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) });
#[cfg(test)]
pub(crate) fn branch_scans() -> usize {
BRANCH_SCANS.get()
}
pub(crate) fn branches(repo: &gix::Repository) -> IdeResult<Vec<Branch>> {
#[cfg(test)]
BRANCH_SCANS.set(BRANCH_SCANS.get() + 1);
let head_name = repo.head_name().map_err(gx)?;
let platform = repo.references().map_err(gx)?;
let remotes = repo.remote_names();
@@ -161,20 +170,20 @@ pub(crate) fn branches(r: &Repo) -> IdeResult<Vec<Branch>> {
ahead: 0,
behind: 0,
outgoing: None,
last_commit_ms: commit_time_ms(&repo, id),
last_commit_ms: commit_time_ms(repo, id),
commit: id.to_string(),
};
let mut counted_upstream = None;
if let Some((up, up_id)) = upstream_of(&repo, full.as_ref()) {
if let Some((up, up_id)) = upstream_of(repo, full.as_ref()) {
branch.upstream = Some(up);
branch.tracked_tip = configured_upstream(&repo, full.as_ref())
branch.tracked_tip = configured_upstream(repo, full.as_ref())
.map(|tracking| TrackedTip { tracking, commit: up_id.to_string() });
let (a, b) = ahead_behind(&repo, id, up_id)?;
let (a, b) = ahead_behind(repo, id, up_id)?;
branch.ahead = a;
branch.behind = b;
counted_upstream = Some((up_id, a));
}
branch.outgoing = crate::push_preview::outgoing_commits(&repo, &remotes, full.as_ref(), id, counted_upstream);
branch.outgoing = crate::push_preview::outgoing_commits(repo, &remotes, full.as_ref(), id, counted_upstream);
out.push(branch);
}
for reference in platform.remote_branches().map_err(gx)? {
@@ -194,7 +203,7 @@ pub(crate) fn branches(r: &Repo) -> IdeResult<Vec<Branch>> {
ahead: 0,
behind: 0,
outgoing: None,
last_commit_ms: commit_time_ms(&repo, id),
last_commit_ms: commit_time_ms(repo, id),
commit: id.to_string(),
});
}
+42
Переглянути файл
@@ -668,6 +668,44 @@ impl Documents {
}
}
/// Releases client-held document references when a remote window disconnects:
/// clean documents close so external changes on disk are picked up cleanly on
/// reopen, while dirty buffers remain registered (`refs = 0`) so reconnecting
/// after a dropped connection keeps unsaved edits without leaking refcounts.
pub fn release_client_refs(&self) {
let _operation = self.operations.lock();
let mut to_close = Vec::new();
{
let mut reg = self.registry.lock();
let ids: Vec<DocId> = reg.docs.keys().copied().collect();
for id in ids {
let dirty = reg.docs.get(&id).is_some_and(|e| e.slot.lock().dirty);
if dirty {
if let Some(entry) = reg.docs.get_mut(&id) {
entry.refs = 0;
}
} else if let Some(entry) = reg.docs.remove(&id) {
for k in &entry.keys {
if reg.by_key.get(k) == Some(&id) {
reg.by_key.remove(k);
}
}
to_close.push((id, entry.slot));
}
}
}
let observers = self.observers();
for (doc, slot) in to_close {
let mut st = slot.lock();
st.closed = true;
if st.observed {
for o in &observers {
o.closed(doc, &st.path);
}
}
}
}
fn set_dirty(&self, doc: DocId, st: &mut DocState, dirty: bool) {
if st.dirty != dirty {
st.dirty = dirty;
@@ -941,6 +979,10 @@ impl Documents {
})
}
pub fn has_unsaved_changes(&self) -> bool {
self.registry.lock().docs.values().any(|entry| entry.slot.lock().dirty)
}
/// Saves every dirty document; reports the first failure after trying all.
pub fn save_all(&self) -> IdeResult<()> {
let ids: Vec<DocId> = self.registry.lock().docs.keys().copied().collect();
+3 -2
Переглянути файл
@@ -66,8 +66,9 @@ pub enum SettingsScope {
/// Settings a project's own file can't hold: the IDE's MCP server, imported color schemes, and
/// what agents may do without asking (commands run without asking, the modes new tasks start in,
/// whether new tasks ask for approvals).
const USER_ONLY: [&[&str]; 6] = [
const USER_ONLY: &[&[&str]] = &[
&["mcpServer"],
&["remoteDevelopment"],
&["editor", "customSchemes"],
&["agentSecurity", "allowedCommands"],
&["agents", "defaults"],
@@ -91,7 +92,7 @@ fn user_only_setting(key: &str, value: &Json) -> Option<String> {
/// Applies a project layer's limits before it merges onto `below`: [`USER_ONLY`] settings are
/// dropped, and its blocked agent commands add to the ones below instead of replacing them.
fn restrict_project_layer(below: &Json, layer: &mut Json) {
for path in USER_ONLY {
for &path in USER_ONLY {
let (last, parents) = path.split_last().expect("non-empty path");
if let Some(table) = parents.iter().try_fold(&mut *layer, |v, seg| v.get_mut(seg)).and_then(Json::as_object_mut)
{
+4 -2
Переглянути файл
@@ -28,6 +28,7 @@ flowchart LR
| Piece | Where |
| --------------------------------- | ----------------------------------------------------------------------------- |
| Server binary | `crates/ide-host/src/bin/server.rs` (`openidea-server`) |
| Persistent daemon and attach | `crates/ide-host/src/daemon.rs` (`openidea-server --attach` / `--daemon`) |
| Protocol and dispatcher | `crates/ide-host/src/rpc.rs` |
| Client: connect, install, forward | `src-tauri/src/remote_dev.rs` |
| WSL and dev container transports | `src-tauri/src/remote_wsl.rs`, `src-tauri/src/remote_container.rs` |
@@ -38,10 +39,11 @@ flowchart LR
## The server
```text
openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <port> | --version
openidea-server --stdio | --attach <project-path> | --mcp-stdio [--project <path>] | --connect <host> <port> | --version
```
- `--stdio` serves one desktop client over stdin/stdout. stdout carries the protocol, so logs go to stderr (filter with `OPENIDEA_LOG`).
- `--attach <project-path>` bridges stdin/stdout to a detached daemon on a `0600` Unix socket in a `0700` directory. The socket key is stable across builds. The relay checks the daemon's build before attaching; a different build can replace it only when no window, live workload, or unsaved document remains. Idle or explicit shutdown keeps the socket bound until cleanup is complete.
- `--stdio` serves a single desktop client directly over stdin/stdout and exits on EOF. stdout carries the protocol, so logs go to stderr (filter with `OPENIDEA_LOG`).
- Its state lives under `OPENIDEA_SERVER_HOME` (default `~/.openidea`), in `config/` and `data/`. Language definitions can be added in `config/languages/`.
- An SSH exec channel gets a minimal environment, so on every start the server takes the login shell's environment and adds the IDE-managed tools directory to `PATH`.
- `--version` prints the app version and the protocol version.
+2 -2
Переглянути файл
@@ -80,12 +80,12 @@ See [Unit and E2E tests](/en/contribute/testing/unit-e2e) for details.
`.github/workflows/ci.yml` first classifies the changed files, so a docs-only or frontend-only PR skips the jobs it can't affect:
- **Rust** on macOS, Ubuntu 22.04 and Windows: `cargo fmt --check` (Linux), clippy with `-D warnings`, `cargo nextest run --workspace`, and a check that `src/bindings.ts` is up to date.
- **Rust** on macOS, Ubuntu and Windows: `cargo fmt --check` (Linux), clippy with `-D warnings`, `cargo nextest run --workspace`, and a check that `src/bindings.ts` is up to date.
- **Remote server**: a static Linux (musl) build of `openidea-server`.
- **Plugins**: format, clippy (host and `wasm32-wasip2`) and tests of the SDK, the official plugins and the test fixtures; plugin web pages typechecked and tested; `plugins/build.sh --check`.
- **Cargo deny**: `cargo deny check` (licences, advisories, sources).
- **Frontend**: typecheck, lint, format check, knip, tests, build.
- **E2E**: `pnpm e2e` in the Playwright container.
- **E2E**: `pnpm e2e` in Chromium.
`.github/workflows/language-smoke.yml` runs the [language smoke tests](/en/contribute/testing/smoke) when crates, `languages/`, `fixtures/`, the run/debugger features, `src/platform/` or `smoke/` change.
+33 -6
Переглянути файл
@@ -9,9 +9,27 @@ language servers, terminals, runs, debugging, build tools and Git. The desktop w
commands to it.
You don't start it yourself. When you open a remote project ([SSH](/en/guide/remote/ssh),
[Containers](/en/guide/remote/containers)), the desktop app installs the server on the host if needed, starts it as
`openidea-server --stdio` over the SSH connection (or `wsl.exe` / `docker exec`) and talks to it over stdin and
stdout. The server serves one desktop window and exits when that window disconnects.
[Containers](/en/guide/remote/containers)), the desktop app installs the server on the host if needed, runs
`openidea-server --attach <project>` over the SSH connection (or `wsl.exe` / `docker exec`) to attach to a persistent
per-project daemon over a private Unix socket, and talks to it over stdin and stdout.
## Closing or stopping a remote backend
- **Keep Backend Running** (the default when closing a remote window) disconnects the window without interrupting
terminal sessions, runs, indexing or agent turns. Reopen the same project to reattach. A network drop also leaves
the backend running.
- **Stop Backend** on close, or **File › Stop Remote Backend**, shuts down the IDE backend and its workloads.
Active Run configurations with a stop command, such as `docker compose down`, run that command first. Stopping the
IDE backend in a dev container does not stop the dev container itself.
- By default, a backend stops after **3 hours** with no connected window, live terminal, run, debug session, or agent
work. In a connected window, open **Settings › Tools › Remote Development › Stop backend when idle**. Pick a
preset, choose **Custom…** to enter minutes, hours, or days, or choose **Never** to keep an idle project running.
**Apply** saves the choice for your user on that host. It takes effect the next time a backend becomes idle, without a restart.
**Never** does not prevent **Stop Backend**, and backends that never opened a project still clean themselves up.
- The close dialog shows what **Keep Backend Running** means for this host. A positive
`OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS` set at server startup takes precedence, even over **Never**;
Settings shows that value read-only. Reconnecting resets the idle timer. Save
your edits before leaving a project idle: unsaved buffers retained after a network drop are kept only in memory.
## Supported hosts
@@ -35,8 +53,10 @@ On every connection the desktop app checks whether the host already has the serv
desktop's local data directory under `server/<version>/<os>-<arch>/`.
3. It uploads the binary to the host and removes older builds of the same version.
The desktop and the server always run the same version. After you update OpenIDEA, the next connection installs the
new server next to the old one.
After you update OpenIDEA, the next connection replaces the old backend for that project if it has no connected
window, live work, or unsaved documents. Otherwise OpenIDEA asks you to finish or save your work using the previous
build and stop that backend before upgrading. Two windows on the same build can use the same project in turn; the
previous window shows that another window took over and does not reconnect automatically.
## Files on the host
@@ -45,6 +65,12 @@ new server next to the old one.
| `~/.openidea/server/<version>/<build>/openidea-server` | The installed server binaries, one folder per version and build. |
| `~/.openidea/config/` | The host's settings, including custom language definitions in `languages/`. |
| `~/.openidea/data/` | Tools OpenIDEA installs on the host (language servers, debuggers, JDKs), caches and indexes. |
| `~/.openidea/logs/server-<key>.log` | Backend log for each project (under `OPENIDEA_SERVER_HOME` if set). |
To stop all of your backends by hand, open a shell on the remote host, WSL distribution, or dev container and list
your processes with `ps -u "$(id -un)" -o pid=,args=`. Review the rows for `openidea-server --daemon`, then run
`kill -TERM <pid>` for each of those daemon PIDs. Save any open work first: this shuts down those backends even if
a window is still connected. It does not stop unrelated processes.
To free space, delete old version folders under `~/.openidea/server/`. After deleting `~/.openidea/data/`, OpenIDEA
installs its tools again when they are needed.
@@ -95,7 +121,8 @@ The flags are meant for the desktop app, but `--version` is handy for checking a
| Flag | Meaning |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `--version` | Print the server version and protocol version, then exit. |
| `--stdio` | Serve one desktop client over stdin / stdout. Logs go to stderr. |
| `--attach <project>` | Start or attach to the persistent per-project daemon and bridge stdin / stdout to its Unix socket. |
| `--stdio` | Serve a single desktop client directly over stdin / stdout and exit on EOF. Logs go to stderr. |
| `--mcp-stdio [--project <dir>]` | Relay stdio MCP traffic to the running `openidea-server` MCP server on this host. |
| `--connect <host> <port>` | Relay one TCP connection to `<host>:<port>` over stdin / stdout. Used for port forwarding into dev containers. |
+2 -1
Переглянути файл
@@ -96,7 +96,8 @@ After the project opens you are asked whether to trust it, as for a local folder
- Your keymap, appearance, editor font and colour scheme stay on the desktop. Project and tool settings live on the
host.
- Your code plugins are synced to the server and run next to the project.
- **File › Disconnect from Remote Host** closes the project and ends the connection.
- **Keep Backend Running** when closing a remote window, or **File › Disconnect from Remote Host**, leaves the remote IDE backend and its workloads running. Reopen the project to reattach.
- **Stop Backend** when closing the window, or **File › Stop Remote Backend**, shuts down the backend and its workloads. See [Stopping a remote backend](/en/guide/remote/server#closing-or-stopping-a-remote-backend) for idle timeout and manual cleanup.
### Forward ports
+3 -3
Переглянути файл
@@ -69,10 +69,10 @@ Long operations (pull, prune, Compose) show progress at the top with a **Cancel*
Selecting an item shows tabs in the detail pane:
- **Compose project**: **Dashboard** (project overview, services with live resource usage, named volumes created by the project).
- **Container**: **Dashboard** (overview, live resource usage, port bindings that open in the browser, mounts, networks, environment variables, labels), **Log** (last 1,000 lines, following while the container runs, with **Timestamps**), **Processes** (`docker top`) and **Inspect** (the raw JSON).
- **Compose project**: **Dashboard** (project overview, services with live resource usage, named volumes created by the project with live disk usage).
- **Container**: **Dashboard** (overview, live resource usage, port bindings that open in the browser, mounts with live volume disk usage, networks, environment variables, labels), **Log** (last 1,000 lines, following while the container runs, with **Timestamps**), **Processes** (`docker top`) and **Inspect** (the raw JSON).
- **Image**: **Dashboard** (tags, containers using it, environment, labels), **Layers** and **Inspect**.
- **Volume** and **network**: **Dashboard** and **Inspect**.
- **Volume** and **network**: **Dashboard** (including live volume disk usage) and **Inspect**.
**Open Log in Editor** opens the log in an editor tab with **Timestamps**, **Soft-wrap**, **Find in Logs** and **Clear**.
+1 -1
Переглянути файл
@@ -27,7 +27,7 @@ When a session's process exits, the terminal prints the exit code; press `Enter`
### Across restarts
OpenIDEA remembers each project's terminal tabs: their directory, custom names, the shell used and the split layout (up to 32 tabs). After a restart each tab starts a **new** session in its directory. Scrollback and running commands are not restored.
OpenIDEA remembers each project's terminal tabs: their directory, custom names, the shell used and the split layout (up to 32 tabs). For local projects, a restart starts a **new** session in each tab's directory without restoring scrollback or running commands. In a remote project, closing and reopening the window reattaches to the running PTY sessions on `openidea-server` along with their recent scrollback and active commands.
## Keys in the terminal
+13 -11
Переглянути файл
@@ -25,23 +25,25 @@ flowchart LR
S1 --> H["ide-host: Host<br/>项目、LSP、索引、git、<br/>终端、运行、调试器、插件"]
```
| 部分 | 位置 |
| ------------------------- | ------------------------------------------------------------------------- |
| 服务端二进制 | `crates/ide-host/src/bin/server.rs`(`openidea-server`) |
| 协议与 dispatcher | `crates/ide-host/src/rpc.rs` |
| 客户端:连接、安装、转发 | `src-tauri/src/remote_dev.rs` |
| WSL 与 dev container 传输 | `src-tauri/src/remote_wsl.rs`、`src-tauri/src/remote_container.rs` |
| 容器内的端口中继 | `crates/ide-host/src/relay.rs`(`openidea-server --connect`) |
| 前端路由 | `src/platform/remote.ts`,由 `src/platform/tauriCore.ts` 挂到 `invoke` 上 |
| UI(文件 › 远程开发…) | `src/features/remote-dev/` |
| 部分 | 位置 |
| ------------------------- | -------------------------------------------------------------------------- |
| 服务端二进制 | `crates/ide-host/src/bin/server.rs`(`openidea-server`) |
| 持久化守护进程与连接桥接 | `crates/ide-host/src/daemon.rs`(`openidea-server --attach` / `--daemon`) |
| 协议与 dispatcher | `crates/ide-host/src/rpc.rs` |
| 客户端:连接、安装、转发 | `src-tauri/src/remote_dev.rs` |
| WSL 与 dev container 传输 | `src-tauri/src/remote_wsl.rs`、`src-tauri/src/remote_container.rs` |
| 容器内的端口中继 | `crates/ide-host/src/relay.rs`(`openidea-server --connect`) |
| 前端路由 | `src/platform/remote.ts`,由 `src/platform/tauriCore.ts` 挂到 `invoke` 上 |
| UI(文件 › 远程开发…) | `src/features/remote-dev/` |
## 服务端
```text
openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <port> | --version
openidea-server --stdio | --attach <project-path> | --mcp-stdio [--project <path>] | --connect <host> <port> | --version
```
- `--stdio` 通过 stdin/stdout 为一个桌面客户端提供服务。stdout 承载协议,所以日志写到 stderr(用 `OPENIDEA_LOG` 过滤)。
- `--attach <project-path>` 将 stdin/stdout 桥接到独立守护进程,套接字权限为 `0600`,目录权限为 `0700`。套接字键不随构建变化;连接前会核对构建,只有在没有连接的窗口、活动任务或未保存的文档时才替换旧后端。空闲退出或主动关闭时会保留套接字,直到清理完成。
- `--stdio` 直接通过 stdin/stdout 为单个桌面客户端提供服务并在断开时退出。stdout 承载协议,所以日志写到 stderr(用 `OPENIDEA_LOG` 过滤)。
- 状态保存在 `OPENIDEA_SERVER_HOME`(默认 `~/.openidea`)下的 `config/` 和 `data/` 中。可以在 `config/languages/` 里追加语言定义。
- SSH exec channel 只给最小的环境变量,所以服务端每次启动都会读取登录 shell 的环境,并把 IDE 托管的工具目录加入 `PATH`。
- `--version` 打印应用版本和协议版本。
+2 -2
Переглянути файл
@@ -76,12 +76,12 @@ description: "issue 如何分流、PR 需要包含什么、验证说明如何检
`.github/workflows/ci.yml` 先按改动的文件分类,只改文档或只改前端的 PR 会跳过与之无关的任务:
- **Rust**:在 macOS、Ubuntu 22.04、Windows 上运行 `cargo fmt --check`(仅 Linux)、带 `-D warnings` 的 clippy、`cargo nextest run --workspace`,并检查 `src/bindings.ts` 是否最新。
- **Rust**:在 macOS、Ubuntu、Windows 上运行 `cargo fmt --check`(仅 Linux)、带 `-D warnings` 的 clippy、`cargo nextest run --workspace`,并检查 `src/bindings.ts` 是否最新。
- **Remote server**:`openidea-server` 的静态 Linux(musl)构建。
- **Plugins**:SDK、官方插件和测试夹具的格式、clippy(宿主与 `wasm32-wasip2`)和测试;插件 Web 页面的类型检查与测试;`plugins/build.sh --check`。
- **Cargo deny**:`cargo deny check`(许可证、安全公告、依赖来源)。
- **Frontend**:类型检查、lint、格式检查、knip、测试、构建。
- **E2E**:在 Playwright 容器里运行 `pnpm e2e`。
- **E2E**:在 Chromium 中运行 `pnpm e2e`。
当 crates、`languages/`、`fixtures/`、运行/调试功能、`src/platform/` 或 `smoke/` 有改动时,`.github/workflows/language-smoke.yml` 会运行[语言冒烟测试](/zh/contribute/testing/smoke)。
+23 -4
Переглянути файл
@@ -7,8 +7,19 @@ description: "运行在远程主机上的 IDE 后端:桌面端如何安装和
承担桌面端在本地时要做的工作:文件系统、索引、语言服务器、终端、运行、调试、构建工具和 Git。桌面窗口只负责显示界面,并把命令发给它。
你不需要手动启动它。打开远程项目时([SSH](/zh/guide/remote/ssh)、[容器](/zh/guide/remote/containers)),桌面端会按需在主机上安装服务端,
通过 SSH 连接(或 `wsl.exe` / `docker exec`)以 `openidea-server --stdio` 启动,并经由标准输入输出与它通信。一个服务端进程只服务一个桌面窗口,
窗口断开后即退出。
通过 SSH 连接(或 `wsl.exe` / `docker exec`)运行 `openidea-server --attach <project>`,连接到按项目隔离的后台守护进程(经由私有 Unix 套接字),
并经由标准输入输出与它通信。
## 关闭窗口或停止远程后端
- 关闭窗口时默认选择**保持后端运行**。窗口断开连接,但终端、运行配置、索引和智能体任务不受影响。重新打开同一项目即可接回。网络中断也不会停止后端。
- 关闭时选择**停止后端**,或使用**文件 › 停止远程后端**,会关闭 IDE 后端及其任务。正在运行且配置了停止命令的运行配置会先执行该命令,例如 `docker compose down`。
停止开发容器里的 IDE 后端不会关闭开发容器本身。
- 默认情况下,没有窗口连接,且没有活动的终端、运行配置、调试会话或智能体任务时,后端闲置**三小时**后自动退出。
在已连接的窗口中,打开**设置 › 工具 › 远程开发 › 空闲时停止后端**。选择预设时长、通过**自定义…**输入分钟、小时或天数,或选择**从不**让空闲项目保持运行。
点击**应用**后,设置保存在远程主机的用户设置中;后端下次进入空闲时即生效,无需重启。选择**从不**后仍可手动**停止后端**;从未打开项目的后端仍会自动退出。
- 关闭窗口的对话框会说明在当前主机上**保持后端运行**的效果。启动环境中的 `OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS` 如为正整数秒数,会优先于所有用户选择(包括**从不**),并在设置页以只读形式显示。重新连接会重置计时。
请在项目闲置前保存修改:网络中断后,未保存的文档仅保留在后端内存里。
## 支持的主机
@@ -30,7 +41,9 @@ description: "运行在远程主机上的 IDE 后端:桌面端如何安装和
校验 SHA-256 后缓存到本机本地数据目录的 `server/<version>/<os>-<arch>/` 下。
3. 把二进制上传到主机,并删除同一版本的旧构建。
桌面端和服务端始终是同一版本。升级 OpenIDEA 后,下一次连接会在旧版本旁边安装新的服务端。
升级 OpenIDEA 后,若旧后端没有窗口连接、活动任务或未保存的文档,下一次连接会替换该项目的旧后端。
否则,OpenIDEA 会提示你用旧版本结束任务或保存文档,再停止旧后端并升级。同一版本的两个窗口可以轮流连接同一项目;
原窗口会提示会话已被另一个窗口接管,不会自动重新连接。
## 主机上的文件
@@ -39,6 +52,11 @@ description: "运行在远程主机上的 IDE 后端:桌面端如何安装和
| `~/.openidea/server/<version>/<build>/openidea-server` | 已安装的服务端,每个版本、每个构建一个文件夹。 |
| `~/.openidea/config/` | 主机端的设置,包括 `languages/` 中的自定义语言定义。 |
| `~/.openidea/data/` | OpenIDEA 在主机上安装的工具(语言服务器、调试器、JDK)、缓存和索引。 |
| `~/.openidea/logs/server-<key>.log` | 各项目的后端日志(如设置了 `OPENIDEA_SERVER_HOME`,则在其下)。 |
若要手动停止自己的所有后端,请在远程主机、WSL 发行版或开发容器中打开 shell,运行 `ps -u "$(id -un)" -o pid=,args=`。
确认属于 `openidea-server --daemon` 的 PID,再对每个 PID 运行 `kill -TERM <pid>`。请先保存工作:
即使窗口仍然连接,此操作也会关闭这些后端,不会停止无关进程。
想释放空间,可以删除 `~/.openidea/server/` 下的旧版本文件夹。删除 `~/.openidea/data/` 后,OpenIDEA 会在需要时重新安装工具。
@@ -82,7 +100,8 @@ cargo build --release -p ide-host --bin openidea-server
| 参数 | 含义 |
| ------------------------------- | -------------------------------------------------------------------------------- |
| `--version` | 输出服务端版本和协议版本后退出。 |
| `--stdio` | 通过标准输入输出服务一个桌面客户端,日志写到 stderr。 |
| `--attach <project>` | 启动或连接到该项目的持久化后台守护进程,并将标准输入输出桥接到其 Unix 套接字。 |
| `--stdio` | 直接通过标准输入输出服务单个桌面客户端并在断开时退出,日志写到 stderr。 |
| `--mcp-stdio [--project <dir>]` | 将标准输入输出上的 MCP 消息转发给当前主机正在运行的 `openidea-server` MCP 服务。 |
| `--connect <host> <port>` | 通过标准输入输出中转一个到 `<host>:<port>` 的 TCP 连接,用于开发容器的端口转发。 |
+2 -1
Переглянути файл
@@ -74,7 +74,8 @@ SSH 代理使用 `IdentityAgent` 指定的那个,未指定时使用登录 shel
- OpenIDEA 安装的语言服务器、调试器等工具都装在远程主机的 `~/.openidea/data` 下。
- 快捷键、外观、编辑器字体和配色方案保留在本机;项目和工具相关的设置保存在主机上。
- 你的代码插件会同步到服务端,在项目所在的机器上运行。
- **文件 › 断开与远程主机的连接**会关闭项目并断开连接。
- 关闭窗口时选择**保持后端运行**,或使用**文件 › 断开与远程主机的连接**,会保留远程 IDE 后端及其任务。重新打开项目即可接回。
- 关闭窗口时选择**停止后端**,或使用**文件 › 停止远程后端**,会关闭后端及其任务。有关空闲超时和手动清理,请参阅[关闭窗口或停止远程后端](/zh/guide/remote/server#关闭窗口或停止远程后端)。
### 端口转发
+3 -3
Переглянути файл
@@ -69,10 +69,10 @@ OpenIDEA 通过 `docker` 命令行操作 Docker,所以只要能提供可用的
选中某项后,详情区会显示以下标签页:
- **Compose 项目**:**仪表盘**(项目概览、各服务的实时资源使用情况、该项目创建的命名卷)。
- **容器**:**仪表盘**(概览、实时资源使用情况、可在浏览器中打开的端口绑定、挂载、网络、环境变量、标签)、**日志**(最近 1,000 行,容器运行时持续跟随,可切换 **时间戳**)、**进程**(`docker top`)和 **检查**(原始 JSON)。
- **Compose 项目**:**仪表盘**(项目概览、各服务的实时资源使用情况、该项目创建的命名卷及其实时磁盘占用)。
- **容器**:**仪表盘**(概览、实时资源使用情况、可在浏览器中打开的端口绑定、挂载及数据卷实时磁盘占用、网络、环境变量、标签)、**日志**(最近 1,000 行,容器运行时持续跟随,可切换 **时间戳**)、**进程**(`docker top`)和 **检查**(原始 JSON)。
- **镜像**:**仪表盘**(标签、使用它的容器、环境变量、标签)、**镜像层** 和 **检查**。
- **卷** 和 **网络**:**仪表盘** 和 **检查**。
- **卷** 和 **网络**:**仪表盘**(含数据卷实时磁盘占用)和 **检查**。
**在编辑器中打开日志** 会在编辑器标签页中打开日志,提供 **时间戳**、**软换行**、**在日志中查找** 和 **清除**。
+1 -1
Переглянути файл
@@ -27,7 +27,7 @@ description: "使用内置终端:标签页、拆分、Shell、链接、查找
### 重启 IDE 之后
OpenIDEA 会按项目记住终端标签页:各自的目录、自定义名称、使用的 Shell 以及拆分布局(最多 32 个标签页)。重启后每个标签页都会在原目录**重新**启动一个会话,不会恢复滚动缓冲区和正在运行的命令。
OpenIDEA 会按项目记住终端标签页:各自的目录、自定义名称、使用的 Shell 以及拆分布局(最多 32 个标签页)。对于本地项目,重启后每个标签页都会在原目录**重新**启动一个会话,不会恢复滚动缓冲区和正在运行的命令;对于远程项目,关闭并重新打开窗口会重新连接到 `openidea-server` 上仍在运行的终端会话,并恢复最近的终端输出与正在执行的命令。
## 终端中的按键
+2 -1
Переглянути файл
@@ -335,7 +335,8 @@ for (const placement of ["editor", "toolWindow"] as const) {
await seedTasks(page, placement);
const box = messageBox(page);
await box.fill(draft);
await page.getByRole("treeitem", { name: "README.md", exact: true }).click();
await page.getByRole("treeitem", { name: "src", exact: true }).click();
await expect(box).toBeVisible();
await expect(box).not.toBeFocused();
await page.keyboard.press("Meta+L");
await expect(box).toBeFocused();
+8 -1
Переглянути файл
@@ -11,7 +11,12 @@ test("External Tools take $FilePath$ from the Project view selection, else the e
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const tool = { id: "echo", name: "Echo File Path", program: "echo", arguments: "$FilePath$ $FileName$" };
useProject.setState({ settings: { externalTools: [{ ...tool, openConsole: false, synchronizeAfter: false }] } });
useProject.setState({
settings: {
editor: { tabs: { previewTab: false } },
externalTools: [{ ...tool, openConsole: false, synchronizeAfter: false }],
},
});
let id = 0;
window.__ipc.handlers.run_start = ({ config }) => {
id++;
@@ -40,10 +45,12 @@ test("External Tools take $FilePath$ from the Project view selection, else the e
(await ipcCalls(page, "run_start")).map((c) => (c as { config: { args: string[] } }).config.args);
await page.getByRole("treeitem", { name: "build.gradle.kts", exact: true }).click();
await expect(page.getByRole("tab", { name: "README.md", exact: true })).toHaveAttribute("aria-selected", "true");
await runTool();
await expect.poll(startedArgs).toEqual([["/dev/acme-api/build.gradle.kts", "build.gradle.kts"]]);
await editor.click();
await expect(editor).toBeFocused();
await runTool();
await expect.poll(startedArgs).toEqual([
["/dev/acme-api/build.gradle.kts", "build.gradle.kts"],
+7 -2
Переглянути файл
@@ -34,6 +34,7 @@ export interface IpcStub {
send(channel: unknown, message: unknown): void;
/** Emits an `IdeEvent` the way the backend does. */
emit(event: { type: string } & Record<string, unknown>): void;
dispatch(event: string, payload: unknown): void;
}
declare global {
@@ -71,8 +72,12 @@ export async function stubDesktop(page: Page) {
callbacks.get(id)?.({ index, message });
},
emit(event) {
for (const l of listeners)
if (l.event === "ide://event") callbacks.get(l.handler)?.({ event: l.event, id: 0, payload: event });
ipc.dispatch("ide://event", event);
},
dispatch(event, payload) {
for (const l of listeners) {
if (l.event === event) callbacks.get(l.handler)?.({ event, id: 0, payload });
}
},
};
window.__ipc = ipc;
+47
Переглянути файл
@@ -430,6 +430,53 @@ test("Git Log puts affected changes on the changed-files toolbar and groups prev
await expect(notes).toBeVisible();
});
test("Git Log file selection stays in place and opens a diff on activation", async ({ workbench: page }) => {
await page.clock.install();
await page.evaluate(() => {
window.__ipc.handlers.vcs_commit_files = () =>
Array.from({ length: 30 }, (_, index) => ({
path: `src/change-${String(index).padStart(2, "0")}.ts`,
kind: "modified",
oldPath: null,
}));
});
await page.getByRole("listbox", { name: "Commits" }).getByRole("option").first().click();
const tree = page.getByRole("tree", { name: "Changed files" });
const first = tree.getByRole("treeitem", { name: "change-10.ts" });
const second = tree.getByRole("treeitem", { name: "change-11.ts" });
const firstDiff = page.getByRole("tab", { name: /^change-10\.ts/ });
const secondDiff = page.getByRole("tab", { name: /^change-11\.ts/ });
await tree.evaluate((el) => (el.scrollTop = 24 * 11));
await expect(first).toBeInViewport({ ratio: 1 });
await expect(second).toBeInViewport({ ratio: 1 });
const scrollTop = () => tree.evaluate((el) => el.scrollTop);
const initialScroll = await scrollTop();
await first.click();
await page.clock.runFor(150);
await expect(first).toHaveAttribute("aria-selected", "true");
await expect(firstDiff).toHaveCount(0);
expect(await scrollTop()).toBe(initialScroll);
await first.dblclick();
await expect(firstDiff).toHaveAttribute("aria-selected", "true");
expect(await scrollTop()).toBe(initialScroll);
await second.click();
await expect(secondDiff).toHaveAttribute("aria-selected", "true");
await expect(firstDiff).toHaveCount(0);
await expect(second).toHaveAttribute("aria-selected", "true");
expect(await scrollTop()).toBe(initialScroll);
await secondDiff.dblclick(); // Keep the preview tab open.
await first.click();
await page.clock.runFor(150);
await expect(firstDiff).toHaveCount(0);
await expect(secondDiff).toHaveAttribute("aria-selected", "true");
await tree.press("Enter");
await expect(firstDiff).toHaveAttribute("aria-selected", "true");
});
test("Not Cherry-Picked Commits dims other rows while keeping unpicked commits readable", async ({
workbench: page,
}) => {
+298
Переглянути файл
@@ -0,0 +1,298 @@
import type { Page } from "@playwright/test";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
const CLOSE = "tauri://close-requested";
const DESTROY = "plugin:window|destroy";
const CANCEL_CLOSE = "window_group_cancel_close";
const STOP = "remote_stop_backend";
interface CloseOptions {
windows?: number;
quitting?: boolean;
dirty?: boolean;
fail?: boolean;
idleMinutes?: number | null;
overrideSeconds?: number | null;
}
async function requestClose(
page: Page,
{
windows = 2,
quitting = false,
dirty = false,
fail = false,
idleMinutes = 180,
overrideSeconds = null,
}: CloseOptions = {},
) {
await stubDesktop(page);
await page.evaluate(
async ({ windows, quitting, dirty, fail, idleMinutes, overrideSeconds }) => {
const closes = "/src/features/app/closeGuard.ts";
const remote = "/src/platform/remote.ts";
const project = "/src/platform/project.ts";
const { installCloseGuard } = await import(/* @vite-ignore */ closes);
const { enableRemote } = await import(/* @vite-ignore */ remote);
const { useProject } = await import(/* @vite-ignore */ project);
enableRemote({
target: { kind: "ssh", config: "devbox" },
root: useProject.getState().project.root,
host: "devbox",
os: "linux",
commands: ["doc_close", "remote_idle_timeout_minutes"],
idlePolicy: { overrideSeconds },
});
window.__ipc.handlers.window_close_context = () => ({ windows, quitting });
window.__ipc.handlers.close_project = () => null;
window.__ipc.handlers.remote_invoke = ({ cmd }) => {
if (cmd === "remote_idle_timeout_minutes") {
if (idleMinutes === null) throw { kind: "unavailable", message: "offline", detail: null };
return JSON.stringify(idleMinutes);
}
return JSON.stringify(null);
};
window.__ipc.handlers.window_group_cancel_close = () => null;
window.__ipc.handlers.app_cancel_quit = () => null;
window.__ipc.handlers.remote_stop_backend = () => {
if (fail) throw { kind: "unavailable", message: "Backend did not respond", detail: null };
return null;
};
installCloseGuard();
if (dirty) window.__ipc.emit({ type: "docDirty", doc: 100, dirty: true });
},
{ windows, quitting, dirty, fail, idleMinutes, overrideSeconds },
);
await expect.poll(async () => (await ipcCalls(page, "plugin:event|listen")).map((e) => e.event)).toContain(CLOSE);
await page.evaluate((event) => window.__ipc.dispatch(event, null), CLOSE);
return page.getByRole("dialog", { name: "Close Remote Development Window" });
}
for (const windows of [1, 2]) {
for (const stop of [false, true]) {
test(`${stop ? "stops" : "keeps"} the backend on close (${windows === 1 ? "last" : "other"} window)`, async ({
workbench: page,
}) => {
await openFromTree(page, "README.md");
const dialog = await requestClose(page, { windows });
await expect(dialog.getByRole("status")).toHaveText("If kept running, the backend stops after 3 hours idle.");
const keep = dialog.getByRole("button", { name: "Keep Backend Running" });
await expect(keep).toBeFocused();
await (stop ? dialog.getByRole("button", { name: "Stop Backend" }) : keep).click();
const close = windows === 1 ? "close_project" : DESTROY;
await expect.poll(() => ipcCalls(page, close)).toHaveLength(1);
const actions = await page.evaluate(
({ stop, close }) => window.__ipc.calls.map((c) => c.cmd).filter((cmd) => cmd === stop || cmd === close),
{ stop: STOP, close },
);
expect(actions).toEqual(stop ? [STOP, close] : [close]);
if (windows === 1) await expect(page.getByRole("tree", { name: "Project" })).toHaveCount(0);
});
}
}
test("Escape leaves the remote project, backend and window open", async ({ workbench: page }) => {
const dialog = await requestClose(page, { idleMinutes: 0 });
await expect(dialog.getByRole("status")).toHaveText("Idle shutdown is off on devbox.");
await page.keyboard.press("Escape");
await expect.poll(() => ipcCalls(page, CANCEL_CLOSE)).toHaveLength(1);
await expect(page.getByRole("tree", { name: "Project" })).toBeVisible();
expect(await ipcCalls(page, STOP)).toHaveLength(0);
expect(await ipcCalls(page, DESTROY)).toHaveLength(0);
});
test("cancelling unsaved changes after choosing Stop Backend also cancels quit", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
const dialog = await requestClose(page, {
windows: 1,
quitting: true,
dirty: true,
idleMinutes: 0,
overrideSeconds: 90,
});
await expect(dialog.getByRole("status")).toHaveText("If kept running, the backend stops after 90 seconds idle.");
expect((await ipcCalls(page, "remote_invoke")).filter((c) => c.cmd === "remote_idle_timeout_minutes")).toHaveLength(
0,
);
await dialog.getByRole("button", { name: "Stop Backend" }).click();
const unsaved = page.getByRole("dialog", { name: /unsaved changes/i });
await unsaved.getByRole("button", { name: "Cancel" }).click();
await expect.poll(() => ipcCalls(page, "app_cancel_quit")).toHaveLength(1);
expect(await ipcCalls(page, STOP)).toHaveLength(0);
expect(await ipcCalls(page, DESTROY)).toHaveLength(0);
});
test("reports a shutdown failure and does not close the window", async ({ workbench: page }) => {
const dialog = await requestClose(page, { fail: true });
await dialog.getByRole("button", { name: "Stop Backend" }).click();
await expect(page.getByText("Could not stop the remote backend")).toBeVisible();
await expect.poll(() => ipcCalls(page, CANCEL_CLOSE)).toHaveLength(1);
expect(await ipcCalls(page, DESTROY)).toHaveLength(0);
});
test("can disconnect even if the host cannot report its current idle timeout", async ({ workbench: page }) => {
const dialog = await requestClose(page, { idleMinutes: null });
await expect(dialog.getByRole("status")).toHaveText("The host’s idle timeout is unavailable.");
await dialog.getByRole("button", { name: "Keep Backend Running" }).click();
await expect.poll(() => ipcCalls(page, DESTROY)).toHaveLength(1);
});
test("Don't Save discards remote edits even when keeping the backend alive", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
const dialog = await requestClose(page, { dirty: true });
await dialog.getByRole("button", { name: "Keep Backend Running" }).click();
await page
.getByRole("dialog", { name: /unsaved changes/i })
.getByRole("button", { name: /don.t save/i })
.click();
await expect.poll(() => ipcCalls(page, DESTROY)).toHaveLength(1);
expect((await ipcCalls(page, "remote_invoke")).filter((c) => c.cmd === "doc_close")).toEqual([
expect.objectContaining({ args: '{"doc":100}' }),
]);
expect(await ipcCalls(page, STOP)).toHaveLength(0);
});
async function enablePolicy(page: Page, overrideSeconds: number | null, initialMinutes = 180) {
await stubDesktop(page);
await page.evaluate(
async ({ overrideSeconds, initialMinutes }) => {
const remote = "/src/platform/remote.ts";
const project = "/src/platform/project.ts";
const { enableRemote } = await import(/* @vite-ignore */ remote);
const { useProject } = await import(/* @vite-ignore */ project);
const settings = { remoteDevelopment: { idleTimeoutMinutes: initialMinutes } };
window.__ipc.handlers.settings_get_global = () => ({});
window.__ipc.handlers.remote_invoke = ({ cmd, args }) => {
if (cmd === "settings_set") {
const change = JSON.parse(String(args));
if (change.scope !== "global" || change.key !== "remoteDevelopment.idleTimeoutMinutes")
throw new Error("Unexpected settings write");
settings.remoteDevelopment.idleTimeoutMinutes = JSON.parse(change.value);
}
return JSON.stringify(settings);
};
enableRemote({
target: { kind: "ssh", config: "devbox" },
root: useProject.getState().project.root,
host: "devbox",
os: "linux",
commands: ["settings_get", "settings_get_global", "settings_set"],
idlePolicy: { overrideSeconds },
});
// The Settings window reconciles its global snapshot with the connected host after first paint.
const staging = "/src/features/settings/model/staging.ts";
const schema = "/src/features/settings/model/schema.ts";
(await import(/* @vite-ignore */ staging)).rebaseSettings(
(await import(/* @vite-ignore */ schema)).validateSettings(settings),
);
},
{ overrideSeconds, initialMinutes },
);
}
for (const override of [null, 90]) {
test(`remote idle timeout ${override ? "shows the host override read-only" : "is searchable and saves only on Apply"}`, async ({
workbench: page,
}) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await dialog.getByRole("textbox", { name: "Search settings" }).fill("Idle timeout");
await dialog.getByRole("treeitem", { name: "Remote Development", exact: true }).click();
const picker = dialog.getByRole("button", { name: "Stop backend when idle", exact: true });
await expect(picker).toBeDisabled();
await enablePolicy(page, override);
const apply = dialog.getByRole("button", { name: "Apply", exact: true });
if (override) {
await expect(dialog.getByText("90 seconds", { exact: true })).toBeVisible();
await expect(dialog.getByText("Set by OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS on devbox.")).toBeVisible();
await expect(picker).toHaveCount(0);
await expect(apply).toBeDisabled();
} else {
await expect(picker).toHaveText("After 3 hours (default)");
await picker.click();
const options = page.getByRole("listbox").getByRole("option");
expect(await options.allTextContents()).toEqual([
"After 30 minutes",
"After 1 hour",
"After 3 hours (default)",
"After 8 hours",
"After 1 day",
"Custom…",
"Never",
]);
await page.getByRole("option", { name: "After 1 day", exact: true }).click();
await apply.click();
await expect(apply).toBeDisabled();
await picker.click();
await page.getByRole("option", { name: "Never", exact: true }).click();
await expect(
dialog.getByText("Idle shutdown is off on devbox. You can still stop the backend manually."),
).toBeVisible();
await expect(dialog.getByRole("textbox", { name: "Custom duration" })).toHaveCount(0);
await apply.click();
await expect(apply).toBeDisabled();
const writes = (await ipcCalls(page, "remote_invoke")).filter((c) => c.cmd === "settings_set");
expect(writes.map((c) => JSON.parse(String(c.args)))).toEqual(
["1440", "0"].map((value) => ({ scope: "global", key: "remoteDevelopment.idleTimeoutMinutes", value })),
);
expect(await ipcCalls(page, "settings_set")).toHaveLength(0);
}
});
}
test("custom idle time preserves 90 minutes across units and accepts only whole-minute durations", async ({
workbench: page,
}) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await dialog.getByRole("textbox", { name: "Search settings" }).fill("Idle timeout");
await dialog.getByRole("treeitem", { name: "Remote Development", exact: true }).click();
await enablePolicy(page, null, 90);
const amount = dialog.getByRole("textbox", { name: "Custom duration" });
const unit = dialog.getByRole("button", { name: "Duration unit" });
const apply = dialog.getByRole("button", { name: "Apply", exact: true });
await expect(amount).toHaveValue("90");
await unit.click();
await page.getByRole("option", { name: "Hours", exact: true }).click();
await expect(amount).toHaveValue("1.5");
await expect(apply).toBeDisabled();
await unit.click();
await page.getByRole("option", { name: "Days", exact: true }).click();
await expect(amount).toHaveValue("0.0625");
await expect(apply).toBeDisabled();
for (const invalid of ["0", "0.001", "46"]) {
await amount.fill(invalid);
await expect(amount).toHaveAttribute("aria-invalid", "true");
await expect(apply).toBeDisabled();
}
await amount.fill("1.5");
await apply.click();
await expect(apply).toBeDisabled();
const writes = (await ipcCalls(page, "remote_invoke")).filter((c) => c.cmd === "settings_set");
expect(writes.map((c) => JSON.parse(String(c.args)).value)).toEqual(["2160"]);
const picker = dialog.getByRole("button", { name: "Stop backend when idle" });
await picker.click();
await page.getByRole("option", { name: "After 3 hours (default)", exact: true }).click();
await expect(amount).toHaveCount(0);
await picker.click();
await page.getByRole("option", { name: "Custom…", exact: true }).click();
await expect(amount).toHaveValue("3");
});
test("a same-build takeover notifies the old window and leaves reconnect to the user", async ({ workbench: page }) => {
await enablePolicy(page, null);
await page.clock.install();
await page.evaluate(() => window.__ipc.emit({ type: "remoteConnectionLost", host: "devbox", takenOver: true }));
await expect(page.getByText("Another window took over this remote session", { exact: true })).toBeVisible();
await expect(page.getByText(/This window will not reconnect automatically/)).toBeVisible();
await page.getByRole("button", { name: "Reconnect", exact: true }).click();
const prompt = page.getByRole("dialog", { name: "Reconnect to Remote Host" });
await expect(
prompt.getByText("Reconnecting takes over the remote session and disconnects the other window."),
).toBeVisible();
await prompt.getByRole("button", { name: "Cancel" }).click();
await page.clock.fastForward(25_000);
expect(await ipcCalls(page, "remote_connect")).toHaveLength(0);
await expect(page.getByRole("button", { name: "SSH: devbox (disconnected)" })).toBeVisible();
});
+233
Переглянути файл
@@ -679,3 +679,236 @@ test("Docker Compose dashboard shows per-service resource usage and named projec
});
await expect(detail).toContainText("27.40%", { timeout: 5000 });
});
test("Docker Compose dashboard keeps its action row pinned when scrolling", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1200, height: 640 });
await stubDesktop(page);
await page.evaluate(async () => {
const containers = Array.from({ length: 10 }, (_, idx) => {
const n = idx + 1;
return {
id: `runner-${n}`,
name: `selfhost-github-runner-${n}`,
image: "myoung34/github-runner:latest",
command: "./bin/Runner.Listener run",
state: "running",
status: "Up 24 hours",
ports: "",
createdAt: "2026-11-22T20:00:00Z",
composeProject: "selfhost",
composeService: `github-runner-${n}`,
composeWorkingDir: "/work/selfhost",
composeFiles: ["/work/selfhost/docker-compose.yml"],
mounts: [],
networks: ["selfhost_default"],
};
});
const snapshot = {
availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: "desktop-linux" },
executable: "/usr/bin/docker",
containers,
images: [],
volumes: [],
networks: [],
errors: [],
};
window.__ipc.handlers.docker_settings = () => ({
connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }],
registries: [],
});
window.__ipc.handlers.docker_snapshot = () => snapshot;
window.__ipc.handlers.docker_events = () => new Promise(() => {});
window.__ipc.handlers.docker_inspect = () => "[]";
window.__ipc.handlers.docker_container_stats = () => ({
cpuPerc: "0.04%",
memUsage: "99.85MiB / 114.3GiB",
memPerc: "0.09%",
netIo: "1.1MB / 3.75MB",
blockIo: "0B / 213kB",
pids: "15",
});
const storeMod = "/src/features/services/store.ts";
const treeMod = "/src/features/services/tree.ts";
const { useServices } = await import(/* @vite-ignore */ storeMod);
const { useServicesTree } = await import(/* @vite-ignore */ treeMod);
useServices.setState({
settings: { connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
conns: { default: { snapshot, loading: false, error: null } },
});
useServicesTree.setState({
expanded: new Set(["docker:default"]),
selectedKey: "docker:default:compose:selfhost",
selectedKeys: new Set(["docker:default:compose:selfhost"]),
});
});
await page.keyboard.press("Meta+8");
const services = page.getByRole("region", { name: "Services", exact: true });
const detail = services.locator("[data-panel][id=services-detail]");
const startBtn = detail.getByRole("button", { name: "Start", exact: true });
const stopBtn = detail.getByRole("button", { name: "Stop", exact: true });
const restartBtn = detail.getByRole("button", { name: "Restart", exact: true });
const downBtn = detail.getByRole("button", { name: "Compose Down", exact: true });
await expect(downBtn).toBeVisible();
const beforeStart = (await startBtn.boundingBox())!;
const beforeDown = (await downBtn.boundingBox())!;
const beforeBanner = (await detail.getByText("Compose project 'selfhost'").boundingBox())!;
const scrollState = await detail.evaluate((panel) => {
const scrollers = Array.from(panel.querySelectorAll<HTMLElement>("*")).filter((el) => {
const cs = getComputedStyle(el);
return (cs.overflowY === "auto" || cs.overflowY === "scroll") && el.scrollHeight - el.clientHeight > 2;
});
scrollers[0]!.scrollTop = 160;
return {
scrollerCount: scrollers.length,
scrollTop: scrollers[0]!.scrollTop,
scrollerTop: scrollers[0]!.getBoundingClientRect().top,
};
});
expect(scrollState.scrollerCount).toBe(1);
expect(scrollState.scrollTop).toBeGreaterThan(100);
// The scroll container starts strictly below the pinned action row.
expect(scrollState.scrollerTop).toBeGreaterThanOrEqual(beforeDown.y + beforeDown.height);
await expect(startBtn).toBeVisible();
await expect(stopBtn).toBeVisible();
await expect(restartBtn).toBeVisible();
await expect(downBtn).toBeVisible();
const afterStart = (await startBtn.boundingBox())!;
const afterDown = (await downBtn.boundingBox())!;
const afterBanner = (await detail.getByText("Compose project 'selfhost'").boundingBox())!;
expect(afterStart.y).toBe(beforeStart.y);
expect(afterDown.y).toBe(beforeDown.y);
expect(afterBanner.y).toBeLessThan(beforeBanner.y - 100);
});
test("Docker volume, Compose, and container dashboards show volume disk usage", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
(window as unknown as { __volSize: string }).__volSize = "145.4kB";
const inspectJson = JSON.stringify([
{
Created: "2026-11-23T02:37:25Z",
State: { Status: "running", Pid: 2048, StartedAt: "2026-11-23T02:37:26Z" },
HostConfig: { RestartPolicy: { Name: "unless-stopped", MaximumRetryCount: 0 } },
Config: { Entrypoint: [], Cmd: ["./bin/Runner.Listener", "run"], Env: [], Labels: {} },
Mounts: [
{
Type: "volume",
Name: "selfhost_runner-persist",
Source: "/var/lib/docker/volumes/selfhost_runner-persist/_data",
Destination: "/persist",
Mode: "rw",
RW: true,
},
],
NetworkSettings: { Ports: {}, Networks: {} },
},
]);
const snapshot = {
availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: "desktop-linux" },
executable: "/usr/bin/docker",
containers: [
{
id: "runner-1",
name: "selfhost-github-runner-1",
image: "myoung34/github-runner:latest",
command: "./bin/Runner.Listener run",
state: "running",
status: "Up 24 hours",
ports: "",
createdAt: "2026-11-23T02:37:25Z",
composeProject: "selfhost",
composeService: "github-runner-1",
composeWorkingDir: "/work/selfhost",
composeFiles: ["/work/selfhost/docker-compose.yml"],
mounts: ["selfhost_runner-persist"],
networks: ["selfhost_default"],
},
],
images: [],
volumes: [
{
name: "selfhost_runner-persist",
driver: "local",
mountpoint: "/var/lib/docker/volumes/selfhost_runner-persist/_data",
composeProject: "selfhost",
scope: "local",
labels: {
"com.docker.compose.project": "selfhost",
"com.docker.compose.volume": "runner-persist",
},
},
],
networks: [
{ id: "net-1", name: "selfhost_default", driver: "bridge", scope: "local", composeProject: "selfhost" },
],
errors: [],
};
window.__ipc.handlers.docker_settings = () => ({
connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }],
registries: [],
});
window.__ipc.handlers.docker_snapshot = () => snapshot;
window.__ipc.handlers.docker_events = () => new Promise(() => {});
window.__ipc.handlers.docker_inspect = () => inspectJson;
window.__ipc.handlers.docker_container_stats = () => ({
cpuPerc: "0.02%",
memUsage: "96MiB / 114GiB",
memPerc: "0.08%",
netIo: "1.1MB / 3.8MB",
blockIo: "512kB / 201kB",
pids: "16",
});
window.__ipc.handlers.docker_volume_sizes = () => ({
"selfhost_runner-persist": (window as unknown as { __volSize: string }).__volSize,
});
const storeMod = "/src/features/services/store.ts";
const treeMod = "/src/features/services/tree.ts";
const { useServices } = await import(/* @vite-ignore */ storeMod);
const { useServicesTree } = await import(/* @vite-ignore */ treeMod);
useServices.setState({
settings: { connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
conns: { default: { snapshot, loading: false, error: null } },
detailTab: "dashboard",
});
useServicesTree.setState({
expanded: new Set(["docker:default"]),
selectedKey: "docker:default:compose:selfhost",
selectedKeys: new Set(["docker:default:compose:selfhost"]),
});
});
await page.keyboard.press("Meta+8");
const services = page.getByRole("region", { name: "Services", exact: true });
const detail = services.locator("[data-panel][id=services-detail]");
// 1. Compose dashboard shows volume disk usage on the chip and the banner.
const volumeChip = detail.getByRole("button", { name: /selfhost_runner-persist/ });
await expect(volumeChip).toContainText("runner-persist · local · 145.4kB");
await expect(detail).toContainText("Disk usage: 145.4kB");
// 2. Opening the volume samples again; the dashboard shows the current size.
await page.evaluate(() => {
(window as unknown as { __volSize: string }).__volSize = "210.8kB";
});
await volumeChip.click();
await expect(detail.getByText("Volume Overview")).toBeVisible();
await expect(detail).toContainText("210.8kB");
// 3. The container dashboard shows the size beside the volume mount.
await page.evaluate(() => {
(window as unknown as { __volSize: string }).__volSize = "380.2kB";
});
await detail.getByRole("button", { name: /selfhost-github-runner-1/ }).click();
await expect(detail.getByText("Volume & Bind Mounts")).toBeVisible();
await expect(detail).toContainText("380.2kB");
});
+3 -1
Переглянути файл
@@ -5,8 +5,10 @@ test("keeps the file count visible beside a long directory in the TODO pane", as
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const todoModule = "/src/features/todo/store.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { useTodos } = await import(/* @vite-ignore */ todoModule);
const { showToolWindow } = await import(/* @vite-ignore */ layoutModule);
const directory = "src/features/checkout/shared/services/with-a-long-directory-name/for-order-processing";
const path = `${useProject.getState().project.root}/${directory}/orders.ts`;
useTodos.setState({
@@ -14,9 +16,9 @@ test("keeps the file count visible beside a long directory in the TODO pane", as
error: null,
scanned: new Map([[path, [{ path, line: 8, col: 3, keyword: "TODO", text: "TODO: validate orders" }]]]),
});
showToolWindow("todo", true);
});
await page.getByRole("button", { name: "TODO" }).click();
const pane = page.locator('[data-toolwindow="todo"]');
const toolbar = pane.getByRole("toolbar", { name: "TODO actions" });
await expect(toolbar).toHaveAttribute("aria-orientation", "vertical");
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.50",
"version": "0.1.51",
"license": "Apache-2.0",
"type": "module",
"scripts": {
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@
Runs _N_ persistent, isolated GitHub Actions runners via Docker Compose on a single Docker named volume (`runner-persist`) without requiring repository admin Personal Access Tokens.
In `.github/workflows/ci.yml`, the Linux leg of `Rust (${{ matrix.os }})` routes to `["self-hosted", "openidea-selfhosted"]` on trusted events (`push`, `merge_group`, `workflow_dispatch`, and same-repo pull requests) while the `SELFHOSTED_RUNNERS` repository variable is `true`. Fork pull requests, and every run while the variable is unset, use GitHub-hosted runners.
In `.github/workflows/ci.yml` and `.github/workflows/language-smoke.yml`, every Linux job routes to `["self-hosted", "openidea-selfhosted"]` on trusted events (`push`, `merge_group`, `workflow_dispatch`, and same-repo pull requests) while the `SELFHOSTED_RUNNERS` repository variable is `true`. Fork pull requests, and every run while the variable is unset, fall back to `ubuntu-latest`. Workflows triggered on `pull_request_target` with write-scoped `GITHUB_TOKEN` permissions (`pr-check.yml`, `cancel-on-close.yml`) stay on `ubuntu-latest`.
> **Availability requirement:** GitHub Actions `runs-on` cannot fall back to GitHub-hosted runners when no matching self-hosted runner is online; jobs stay queued until one connects. Set `SELFHOSTED_RUNNERS=true` (**Settings → Secrets and variables → Actions → Variables**) only once the runners are up, and delete it before taking the host down.
+1 -1
Переглянути файл
@@ -3,7 +3,7 @@
services:
github-runner:
image: myoung34/github-runner:2.338.2-ubuntu-jammy@sha256:9944eb7fe15cff8f31ce6389a1cd39f5fb32627f56bdfa8a21fb27e56e99fa1a
image: myoung34/github-runner:2.338.2-ubuntu-noble@sha256:23e3a4a1da30de5b462ad0ae13d901288e803a688075c3b9b5bb79b7148c07fa
restart: unless-stopped
deploy:
replicas: ${RUNNER_COUNT:-4}
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// The commit being prepared in the window the current command or event came
/// from (the Commit tool window, or the Commit dialog while it is open): the
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Plugin-owned project data sources. Requires database.sources and project trust.
/// Runs on the Database subsystem's host, including on remote project servers.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Editor and project-tree decorations (API 1.4). Requires project.read. An editor set
/// follows its file: the file's own project, or the nearest one when it is outside them all.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// What the pane beside the Services tree shows for a plugin's node.
interface detail-types {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Optional export (world `plugin-diagnostics`): problems in the current,
/// possibly unsaved document, for the languages declared with the
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
interface endpoints-provider {
+6 -2
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Workbench events, delivered in batches to `event-handler.handle`.
interface events {
@@ -35,9 +35,13 @@ interface events {
/// API 1.5 also delivers `extensions-changed` (JSON array of the extension
/// points this plugin declares whose contributions changed) through `other`,
/// to the declaring plugin only and without a capability.
/// API 1.15 also delivers `caret-moved` (JSON {path, line, col, settled},
/// 0-based UTF-16 positions, when the caret moves in the focused editor;
/// `settled` is true for the final position once the caret rests, so costly
/// work waits for it; it requires `events`) through `other`.
/// Kinds: `file-opened`, `file-saved`, `document-changed` (versioned UTF-16
/// replacements from explicit path subscriptions), `websocket-ready`
/// (a host-owned connection has messages to drain), `files-changed` (batched disk changes
/// (a host-owned connection has messages to drain), `caret-moved`, `files-changed` (batched disk changes
/// as `other`, with created/modified/removed path lists in JSON), `editor-focused` (the focused editor
/// changed), `vcs-changed` (a repository's state changed: commit,
/// checkout, fetch…), `action-performed` (an IDE action ran) and
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
interface lifecycle {
use types.{context, error};
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// What other plugins contributed to the extension points this plugin declares
/// (`[[extension-points]]` in `plugin.toml`; the contributors list this plugin
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Optional export (world `plugin-file-actions`): quick fixes and
/// refactorings that create, rename or delete files, next to the text edits
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Files outside the open projects: the configuration of the program a
/// plugin integrates with, a tool installed elsewhere, a licence file.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Writes to the IDE log, tagged with the plugin id.
interface log {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Optional export (world `plugin-hover-actions`): clickable actions rendered
/// at the left edge of a line and revealed while the pointer is in the leftmost
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Optional export (world `plugin-hover`): Markdown added to the hover of
/// documents of the languages declared with the `hover` provider kind,
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Cross-file associations a plugin publishes for the files it declares under
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Embedded languages. The host routes plugin providers and configured language
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
/// the languages declared with the `inlay-hints` provider kind, including
+20 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Problems in files, shown in the editor and the Problems view.
interface diagnostics {
@@ -138,6 +138,14 @@ interface process {
stderr: string,
}
/// Options for running a program with configurable capture or streaming (API 1.15).
record process-options {
/// Maximum bytes captured per stream before returning an error (up to 128 MiB; default 16 MiB).
max-output-bytes: option<u32>,
/// In-flight buffer size per stream for streaming backpressure (default 256 KiB, max 4 MiB).
buffer-bytes: option<u32>,
}
/// What to run (API 1.3). `env` only adds variables: an existing name in
/// the prepared child environment (including the login-shell PATH) is an
/// error naming that key; nothing is replaced or removed. Names compare
@@ -194,6 +202,17 @@ interface process {
/// handle to it without waiting (API 1.3). Closing the invoking window
/// also ends its processes.
start: func(cmd: command, cwd: option<borrow<project>>) -> result<child, error>;
/// Runs `cmd` with configurable capture limits (API 1.15).
/// Both stdout and stderr are captured losslessly up to `options.max-output-bytes`.
/// Exceeding the limit on either stream returns an explicit error naming that stream.
run-captured: func(cmd: command, cwd: option<borrow<project>>, stdin: option<string>, options: option<process-options>) -> result<output, error>;
/// Starts `cmd` with backpressure-driven lossless streaming (API 1.15).
/// If the unread buffer reaches `buffer-bytes`, the reader pauses and the child blocks
/// on its pipe, preventing head truncation. If total output exceeds `max-output-bytes`,
/// polling returns an explicit error.
start-stream: func(cmd: command, cwd: option<borrow<project>>, options: option<process-options>) -> result<child, error>;
}
/// Local sockets on the project machine, including the server for remote projects.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Additional language features, called only for declared API 1.4 provider kinds.
/// Editor calls have a 50 ms soft / 500 ms hard budget; formatting has 5 seconds.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Discovery of the IDE's built-in MCP server; never exposes its URL or token.
interface mcp {
+1 -1
Переглянути файл
@@ -8,7 +8,7 @@
/// `fs` and `workspace`, and everything else goes through the imports below,
/// gated by the capabilities granted in `plugin.toml` (a missing one returns
/// `error::denied`).
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
world plugin {
import log;
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Editor features a plugin provides for the languages it declares under
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Project-scoped targets owned by the registering plugin (API 1.4).
interface run-targets {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Launches this plugin's configurations in the invoking window's Run tool window.
interface run {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// On-demand results for `[[contributes.searchCategories]]`. Optional, API 1.13.
interface search-provider {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Optional export (world `plugin-semantic-tokens`): semantic colouring of
/// documents of the languages declared with the `semantic-tokens` provider
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
/// as in the editor and LSP.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
/// Declarative views: tool windows declared
/// under `[[contributes.views]]` and custom editors under
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]4.0;
package openidea:[email protected]5.0;
interface workspace {
use types.{error, location};
+13
Переглянути файл
@@ -130,6 +130,18 @@ pub async fn docker_container_stats(
blocking(move || ide_docker::container_stats(&endpoint, &id)).await
}
/// Disk usage per volume name (`docker system df -v`).
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub async fn docker_volume_sizes(
state: State<'_, AppState>,
endpoint: DockerEndpoint,
) -> IdeResult<std::collections::BTreeMap<String, String>> {
let endpoint = resolve(&state, endpoint).await?;
blocking(move || ide_docker::volume_sizes(&endpoint)).await
}
/// Streams a container's log lines, in batches, until it stops or the request is cancelled.
#[desktop_command(trust = trusted)]
#[tauri::command]
@@ -308,4 +320,5 @@ ide_command::desktop_domain!(
docker_set_registry_password,
docker_settings,
docker_snapshot,
docker_volume_sizes,
);
+1 -8
Переглянути файл
@@ -252,17 +252,10 @@ pub fn window_take_settings_init(
let owner = AppState::owner_window(window.label());
let launch = windows.take_launch(window.label());
let (remote, project) = if let Some(c) = state.remote_dev.get(owner) {
let session = crate::remote_dev::RemoteSession {
target: c.target.clone(),
root: c.root.clone(),
host: c.host.clone(),
os: c.os.clone(),
commands: c.commands.clone(),
};
// Leave `project` empty on remote sessions: the Settings page tree renders immediately
// from local client settings, and `projectCurrent()` fills in project-scoped settings
// right after first paint without keeping a shadow cache in sync.
(Some(session), None)
(Some(c.snapshot()), None)
} else {
let project = state.project(owner).ok().filter(|p| !p.light).map(|p| ide_host::ops::project::info(&p));
(None, project)
+10 -4
Переглянути файл
@@ -228,6 +228,14 @@ mod tests {
(coalescing_sink(Arc::new(move |event| saved.lock().push(event)), tokio::runtime::Handle::current()), events)
}
/// Waits for the coalescing window to flush `n` events (a fixed sleep is too short on slow CI timers).
async fn wait_for_events(events: &Mutex<Vec<IdeEvent>>, n: usize) {
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while events.lock().len() < n && std::time::Instant::now() < deadline {
tokio::time::sleep(Duration::from_millis(5)).await;
}
}
fn diagnostics(path: &str, source: &str, message: &str) -> IdeEvent {
IdeEvent::Diagnostics {
path: IpcPath::from(path),
@@ -316,9 +324,7 @@ mod tests {
sink.emit(diagnostics("/p/b.rs", "rust-analyzer", "other"));
assert!(events.lock().is_empty());
tokio::task::yield_now().await;
tokio::time::sleep(Duration::from_millis(30)).await;
tokio::task::yield_now().await;
wait_for_events(&events, 3).await;
{
let saved_events = events.lock();
@@ -381,7 +387,7 @@ mod tests {
}
assert_eq!(events.lock().len(), MAX_PENDING_DIAGNOSTICS);
tokio::time::sleep(Duration::from_millis(30)).await;
wait_for_events(&events, MAX_PENDING_DIAGNOSTICS + 1).await;
assert_eq!(events.lock().len(), MAX_PENDING_DIAGNOSTICS + 1);
}
+1
Переглянути файл
@@ -249,6 +249,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("remote.connect", "Remote Development…"),
act("remote.reopenInContainer", "Reopen in Container"),
act("remote.disconnect", "Disconnect from Remote Host"),
act("remote.stopBackend", "Stop Remote Backend"),
act("remote.reloadEnvironment", "Reload Environment"),
SEP,
act("file.save", "Save All"),
+62 -11
Переглянути файл
@@ -172,7 +172,7 @@ fn server_args(up: &Up, bin: &str) -> Vec<String> {
] {
args.extend(["-e".to_owned(), var]);
}
args.extend([up.container.clone(), bin.to_owned(), "--stdio".to_owned()]);
args.extend([up.container.clone(), bin.to_owned(), "--attach".to_owned(), up.folder.clone()]);
args
}
@@ -253,7 +253,8 @@ mod tests {
"OPENIDEA_LIFECYCLE_DONE=1",
ID,
"/home/vscode/.openidea/server/1/ab/openidea-server",
"--stdio",
"--attach",
"/workspaces/my app",
]
);
}
@@ -332,10 +333,12 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
#[tokio::test]
#[ignore = "requires Docker, the Dev Containers CLI, OPENIDEA_DOCKER_TEST_DIR and OPENIDEA_SERVER_BIN"]
async fn opens_a_real_dev_container() {
use serde_json::{Value, json};
let base = PathBuf::from(std::env::var("OPENIDEA_DOCKER_TEST_DIR").expect("OPENIDEA_DOCKER_TEST_DIR"));
let server = PathBuf::from(std::env::var("OPENIDEA_SERVER_BIN").expect("OPENIDEA_SERVER_BIN"));
let root = base.join("devcontainer");
let _ = std::fs::remove_dir_all(&root);
let workspace = tempfile::Builder::new().prefix("openidea-devcontainer-").tempdir_in(base).unwrap();
let root = workspace.path();
std::fs::create_dir_all(root.join(".devcontainer")).unwrap();
std::fs::write(
root.join(".devcontainer/devcontainer.json"),
@@ -350,10 +353,19 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
std::fs::write(root.join("main.py"), "print('hello')\n").unwrap();
let docker = ide_docker::docker_executable().expect("docker");
let tail = Tail::default();
let up = up(Path::new("devcontainer"), &docker, &root, "", &tail)
let up = up(Path::new("devcontainer"), &docker, root, "", &tail)
.await
.unwrap_or_else(|e| panic!("{e:?}; the CLI said: {}", tail.text()));
assert_eq!(up.folder, "/workspaces/devcontainer");
struct RemoveContainer<'a>(&'a Path, &'a str);
impl Drop for RemoveContainer<'_> {
fn drop(&mut self) {
if let Err(e) = std::process::Command::new(self.0).args(["rm", "-f", self.1]).status() {
eprintln!("could not remove dev container {}: {e}", self.1);
}
}
}
let _container = RemoveContainer(&docker, &up.container);
assert_eq!(up.folder, format!("/workspaces/{}", root.file_name().unwrap().to_string_lossy()));
assert_eq!(up.user, "root");
let found = probe(&docker, &up, "0.0.0-test").await.unwrap();
assert_eq!(platform_os(&found.uname), "linux");
@@ -374,7 +386,7 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
.request("invoke", invoke("open_project", serde_json::json!({ "path": up.folder })), None)
.await
.unwrap_or_else(|e| panic!("{e:?}; the server said: {}", tail.text()));
assert_eq!(project["root"], "/workspaces/devcontainer");
assert_eq!(project["root"], up.folder);
assert_eq!(project["trusted"], true, "the trust of the local folder is inherited");
let files: serde_json::Value = peer
.request("invoke", invoke("fs_read_dir", serde_json::json!({ "path": up.folder })), None)
@@ -410,10 +422,49 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
}
assert_eq!(reply, "from the container\n");
drop(tunnel);
drop(peer);
let removed = std::process::Command::new(&docker).args(["rm", "-f", &up.container]).output().unwrap();
assert!(removed.status.success());
std::fs::remove_dir_all(&root).unwrap();
let term: Value = peer
.request(
"invoke",
invoke(
"term_spawn",
json!({
"options": {
"cwd": up.folder, "shell": "/bin/sh", "args": ["-c", "exec sleep 300"],
"env": {}, "cols": 80, "rows": 24, "shellIntegration": false
},
"onOutput": { "$channel": 1 }
}),
),
None,
)
.await
.unwrap();
let pid = term["pid"].as_u64().unwrap();
peer.kill();
peer.exited().await;
let live = || docker_sh(&docker, &up.container, &format!("kill -0 {pid} 2>/dev/null && printf live"));
assert_eq!(live(), "live", "the terminal must outlive the window in a dev container");
let peer = spawn(&docker, &up, &bin, Arc::new(Silent), &Tail::default()).unwrap();
tokio::time::timeout(Duration::from_secs(30), async {
let project: Value = peer.request("invoke", invoke("project_current", json!({})), None).await.unwrap();
assert_eq!(project["root"], up.folder);
let terms: Value = peer.request("invoke", invoke("term_list", json!({})), None).await.unwrap();
assert_eq!(terms[0]["id"], term["id"]);
peer.request::<_, ()>("shutdown", Value::Null, None).await.unwrap();
peer.closed().await;
})
.await
.expect("dev container backend did not reattach and stop");
assert_eq!(docker_sh(&docker, &up.container, "printf running"), "running", "stopping the IDE keeps Docker up");
for _ in 0..50 {
if live().is_empty() {
return;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
panic!("terminal process {pid} outlived backend shutdown");
}
fn platform_os(uname: &str) -> String {
+131 -24
Переглянути файл
@@ -8,7 +8,7 @@ use crate::state::AppState;
use ide_command::desktop_command;
use ide_core::{EventSink, IdeError, IdeResult};
use ide_host::catalogue::TrustClass;
use ide_host::rpc::{ChannelMessage, EventMessage, Invoke, ServerInfo};
use ide_host::rpc::{ChannelMessage, EventMessage, Invoke, RemoteIdlePolicy, ServerInfo};
use ide_jsonrpc::{Handler, Peer};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
@@ -16,6 +16,8 @@ use serde_json::Value;
use specta::Type;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use tauri::ipc::Channel;
use tauri::{AppHandle, Manager, State, Window};
@@ -55,12 +57,20 @@ pub(crate) const SERVER_DIR: &str = ".openidea/server";
/// File name of the server binary on every host.
pub(crate) const SERVER_BIN: &str = "openidea-server";
/// Canonical window key sent to the per-project `openidea-server` daemon, so
/// reopening the project in another desktop window (`main` vs `project-1`)
/// rebinds to the same open project and live terminal sessions on the server.
const SERVER_WINDOW: &str = "main";
/// Printed before a probe's answer: shell start-up files and `wsl.exe` may print first.
pub(crate) const PROBE_MARK: &str = "__OPENIDEA_PROBE__";
/// One remote window's connection.
pub struct Connection {
peer: Peer,
stopping: AtomicBool,
taken_over: Arc<AtomicBool>,
idle_policy: Option<RemoteIdlePolicy>,
pub target: RemoteTarget,
pub root: String,
pub host: String,
@@ -118,6 +128,18 @@ pub struct Connections {
}
impl Connection {
pub(crate) fn snapshot(&self) -> RemoteSession {
RemoteSession {
target: self.target.clone(),
root: self.root.clone(),
host: self.host.clone(),
os: self.os.clone(),
commands: self.commands.clone(),
idle_policy: self.idle_policy,
taken_over: self.taken_over.load(Ordering::Acquire),
}
}
/// Commands of a remote window that run on this machine follow this machine's decision about the
/// remote project, never the server's: the server only answers for what runs there. A remote
/// window always has a project, so only `Always` runs before it is trusted.
@@ -336,6 +358,8 @@ pub struct RemoteProject {
pub host: String,
pub server_version: String,
pub os: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub idle_policy: Option<RemoteIdlePolicy>,
/// Commands routed to the server (the rest run locally).
pub commands: Vec<String>,
pub project: ide_host::ops::project::ProjectInfo,
@@ -346,6 +370,7 @@ struct ClientHandler {
window: String,
channels: Channels,
connection: Arc<std::sync::OnceLock<std::sync::Weak<Connection>>>,
taken_over: Arc<AtomicBool>,
}
impl Handler for ClientHandler {
@@ -394,6 +419,10 @@ impl Handler for ClientHandler {
AUTH_REQUEST, AuthRequest, SECRET_REQUEST, SECRET_WRITE, SecretRequest, SecretWrite,
};
match method {
ide_host::rpc::SESSION_REPLACED => {
self.taken_over.store(true, Ordering::Release);
Ok(Value::Null)
}
// A remote plugin's request header needs a secret from this machine's keychain.
SECRET_REQUEST => {
let r: SecretRequest =
@@ -640,11 +669,13 @@ pub async fn remote_connect(
let attempt = state.remote_dev.begin(&label);
let channels: Channels = Arc::default();
let connection_slot: Arc<std::sync::OnceLock<std::sync::Weak<Connection>>> = Arc::default();
let taken_over = Arc::new(AtomicBool::new(false));
let handler = Arc::new(ClientHandler {
app: window.app_handle().clone(),
window: label.clone(),
channels: channels.clone(),
connection: connection_slot.clone(),
taken_over: taken_over.clone(),
});
let tail = crate::remote_wsl::Tail::default();
let mut exec = None;
@@ -654,17 +685,29 @@ pub async fn remote_connect(
let session = state.ssh.session(id).await?;
let bin = ensure_server(&state, &session, progress.clone()).await?;
progress(RemoteStage::Starting, None);
let attach_arg = if path.trim().is_empty() { "~" } else { path.trim() };
let stream = session
.exec_stream(&format!("{} --stdio", ide_ssh::shell::tilde_quote(&bin)))
.exec_stream(&format!(
"{} --attach {} 2>&1",
ide_ssh::shell::tilde_quote(&bin),
ide_ssh::shell::quote(attach_arg),
))
.await
.map_err(|e| IdeError::unavailable(format!("cannot start openidea-server: {e}")))?;
let (reader, writer) = tokio::io::split(stream);
(Peer::connect(reader, writer, handler), Some(session), config.label(), config.label())
let output = tail.clone();
(
Peer::connect_with_output(reader, writer, handler, move |line| output.push(line)),
Some(session),
config.label(),
config.label(),
)
}
RemoteTarget::Wsl { distro } => {
let bin = crate::remote_wsl::ensure_server(&state, distro, progress.clone()).await?;
progress(RemoteStage::Starting, None);
let peer = crate::remote_wsl::spawn(distro, &bin, handler, &tail)?;
let attach_arg = if path.trim().is_empty() { "~" } else { path.trim() };
let peer = crate::remote_wsl::spawn(distro, &bin, attach_arg, handler, &tail)?;
(peer, None, distro.clone(), format!("WSL: {distro}"))
}
RemoteTarget::DevContainer { folder, config } => {
@@ -711,7 +754,8 @@ pub async fn remote_connect(
path.trim().to_owned()
};
progress(RemoteStage::Opening, None);
let call = Invoke { window: label.clone(), cmd: "open_project".into(), args: serde_json::json!({ "path": root }) };
let call =
Invoke { window: SERVER_WINDOW.into(), cmd: "open_project".into(), args: serde_json::json!({ "path": root }) };
let project: ide_host::ops::project::ProjectInfo =
peer.request("invoke", call, None).await.map_err(ide_host::rpc::error_from_reply)?;
// As the server resolved it (symlinks, a trailing `/`): the frontend compares it with the project's.
@@ -722,6 +766,9 @@ pub async fn remote_connect(
let _ = window.set_title(&format!("{} [{title_tag}]", project.display_name));
let connection = Arc::new(Connection {
peer,
stopping: AtomicBool::new(false),
taken_over: taken_over.clone(),
idle_policy: info.idle_policy,
target: target.clone(),
root: root.clone(),
host: host.clone(),
@@ -754,16 +801,22 @@ pub async fn remote_connect(
let app = window.app_handle().clone();
tauri::async_runtime::spawn(async move {
peer.closed().await;
auth_plugins.forget_remote_loopbacks(&auth_window);
let current = app.state::<AppState>().remote_dev.get(&auth_window);
if current.is_none() {
auth_plugins.forget_remote_loopbacks(&auth_window);
}
let Some(connection) = weak.upgrade() else { return };
connection.forwards.lock().clear();
// Still the window's connection: not a disconnect or a replacement, so the window learns
// its project is unreachable instead of failing every command with "connection closed".
let current = app.state::<AppState>().remote_dev.get(&auth_window);
if current.is_some_and(|c| Arc::ptr_eq(&c, &connection)) {
tracing::warn!("{}: the connection to openidea-server was lost", connection.host);
TauriSink { app, window: Some(auth_window) }
.emit(ide_core::IdeEvent::RemoteConnectionLost { host: connection.host.clone() });
auth_plugins.forget_remote_loopbacks(&auth_window);
if !connection.stopping.load(Ordering::Acquire) || taken_over.load(Ordering::Acquire) {
let taken_over = taken_over.load(Ordering::Acquire);
tracing::info!(host = connection.host, taken_over, "remote backend disconnected");
TauriSink { app, window: Some(auth_window) }
.emit(ide_core::IdeEvent::RemoteConnectionLost { host: connection.host.clone(), taken_over });
}
}
});
let plugins = state.plugins.clone();
@@ -774,16 +827,25 @@ pub async fn remote_connect(
if let Err(error) = crate::window_groups::persist(window.app_handle()).await {
tracing::warn!(%error, "cannot save window session after opening remote project");
}
Ok(RemoteProject { target, root, host, server_version: info.version, os: info.os, commands, project })
Ok(RemoteProject {
target,
root,
host,
server_version: info.version,
os: info.os,
idle_policy: info.idle_policy,
commands,
project,
})
}
/// Sends the desktop's plugin languages, with the programs granted to them, to
/// the window's server: `Workspace` contributions take effect where the project
/// is. A server without the command answers an error, which is logged.
pub async fn sync_plugin_languages(plugins: &ide_host::plugins::PluginHost, c: &Connection, window: &str) {
pub async fn sync_plugin_languages(plugins: &ide_host::plugins::PluginHost, c: &Connection, _window: &str) {
use ide_host::plugins::remote::{SYNC_COMMAND, SyncReport};
let call = Invoke {
window: window.to_owned(),
window: SERVER_WINDOW.to_owned(),
cmd: SYNC_COMMAND.into(),
args: serde_json::json!({ "languages": plugins.remote_languages() }),
};
@@ -803,12 +865,12 @@ pub async fn sync_plugin_languages(plugins: &ide_host::plugins::PluginHost, c: &
/// Sends the desktop's live code plugins to the window's server, which runs
/// them next to the project: digests and grants first,
/// then the files of the packages the server lacks, one per request.
pub async fn sync_plugin_packages(plugins: &Arc<ide_host::plugins::PluginHost>, c: &Connection, window: &str) {
pub async fn sync_plugin_packages(plugins: &Arc<ide_host::plugins::PluginHost>, c: &Connection, _window: &str) {
use ide_host::plugins::remote_host::{PackageSyncReport, SYNC_PACKAGES};
let host = plugins.clone();
let Ok(packages) = tauri::async_runtime::spawn_blocking(move || host.remote_packages()).await else { return };
let sync = |files: serde_json::Value| Invoke {
window: window.to_owned(),
window: SERVER_WINDOW.to_owned(),
cmd: SYNC_PACKAGES.into(),
args: serde_json::json!({ "packages": packages, "files": files }),
};
@@ -854,6 +916,10 @@ pub struct RemoteSession {
/// `linux`, `macos` or `windows`: the OS the project's commands run on.
pub os: String,
pub commands: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub idle_policy: Option<RemoteIdlePolicy>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub taken_over: bool,
}
/// The remote session of this window (a settings window: its parent's), if any.
@@ -862,13 +928,7 @@ pub struct RemoteSession {
#[specta::specta]
pub fn remote_current(window: Window, state: State<'_, AppState>) -> Option<RemoteSession> {
let c = state.remote_dev.get(AppState::owner_window(window.label()))?;
Some(RemoteSession {
target: c.target.clone(),
root: c.root.clone(),
host: c.host.clone(),
os: c.os.clone(),
commands: c.commands.clone(),
})
Some(c.snapshot())
}
/// This machine's trust decision for the window's remote project (see [`Connection::authorize`]).
@@ -891,7 +951,16 @@ pub fn remote_trust_status(window: Window, state: State<'_, AppState>) -> IdeRes
#[specta::specta]
pub fn remote_trust_set(window: Window, state: State<'_, AppState>, trusted: bool) -> IdeResult<()> {
let c = connection(&window, &state)?;
state.host.trust.decide_remote(&c.location(), trusted)
state.host.trust.decide_remote(&c.location(), trusted)?;
if trusted {
let plugins = state.plugins.clone();
let label = AppState::owner_window(window.label()).to_owned();
tauri::async_runtime::spawn(async move {
sync_plugin_languages(&plugins, &c, &label).await;
sync_plugin_packages(&plugins, &c, &label).await;
});
}
Ok(())
}
/// A port of the remote host reachable on this machine at `localhost:local_port`.
@@ -1097,6 +1166,40 @@ pub fn remote_disconnect(window: Window, state: State<'_, AppState>) {
state.remote_dev.disconnect(AppState::owner_window(window.label()));
}
/// Stops the persistent `openidea-server` daemon for this window's remote project,
/// terminating its terminals, runs, language servers and agent sessions, then disconnects.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn remote_stop_backend(window: Window, state: State<'_, AppState>) -> IdeResult<()> {
let label = AppState::owner_window(window.label()).to_owned();
let c = connection(&window, &state)?;
if c.stopping.swap(true, Ordering::AcqRel) {
return Err(IdeError::unavailable("The remote backend is already stopping"));
}
let result: IdeResult<()> = async {
tokio::time::timeout(Duration::from_secs(10), c.peer.request::<_, Value>("shutdown", Value::Null, None))
.await
.map_err(|_| IdeError::unavailable("The remote backend did not respond to the shutdown request"))?
.map_err(ide_host::rpc::error_from_reply)?;
tokio::time::timeout(ide_host::rpc::SHUTDOWN_TIMEOUT, c.peer.closed())
.await
.map_err(|_| IdeError::unavailable("Timed out waiting for the remote backend to stop"))?;
Ok(())
}
.await;
if result.is_err() {
c.stopping.store(false, Ordering::Release);
}
result?;
let mut connections = state.remote_dev.windows.lock();
if connections.get(&label).is_some_and(|current| Arc::ptr_eq(current, &c)) {
connections.remove(&label);
state.host.mcp_reports.remove_remote(&label);
}
Ok(())
}
/// Runs a command on the window's remote server; `args` and the result are JSON
/// text. Streaming arguments are `{ "$channel": id }`; their values arrive on
/// `on_channel` tagged with the id.
@@ -1150,7 +1253,7 @@ pub async fn remote_invoke(
None
};
let web_url = cmd == "web_url";
let call = Invoke { window: label, cmd, args };
let call = Invoke { window: SERVER_WINDOW.into(), cmd, args };
let reply = invoke_reply(&c.peer, call, std::time::Duration::from_secs(30)).await;
// These commands finish streaming before their reply. Other commands may retain their channels.
if let Some(id) = finite_channel {
@@ -1406,6 +1509,9 @@ mod tests {
std::mem::forget(Peer::connect(reader, writer, Arc::new(TrustingServer)));
Connection {
peer,
stopping: AtomicBool::new(false),
taken_over: Arc::default(),
idle_policy: None,
target,
root: root.into(),
host: "host".into(),
@@ -1506,6 +1612,7 @@ ide_command::desktop_domain!(
remote_forwarded_ports,
remote_import_local,
remote_invoke,
remote_stop_backend,
remote_stop_forwarding,
remote_trust_set,
remote_trust_status,
Loaded 100 of 192 files, more files were not shown because too many files have changed in this diff. Show more