Compare commits

...
Author SHA1 Message Date
l0ng-ai 31b076dd32 fix(python): keep inheritance inspections on classes an unsaved edit moved
The Python inheritance inspections matched each class of the open document
to the project's inheritance graph by its exact line and column, and the
graph is re-indexed only when a file is saved. A line typed above a class
moved it and every class below off their indexed positions, so their
warnings (abstract method not implemented, redundant override, ...) vanished
until the file was saved. The document's classes now pair with the graph's
in order while they still read the same names, and by position otherwise;
methods and members of classes in the same document come from the live
document.
2026-11-24 19:55:10 +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 XIANGRUIandLU 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 XIANGRUIandLU 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 Liuanddengliu 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
l0ng-ai e27fc0d867 refactor(run): remove the npm tool window
Detected npm scripts are already in the run configuration list and runnable from the
package.json gutter. Remove the separate npm tool window, its package scan and e2e spec.
The editor context menu Run / Debug on a package.json script line stays.
2026-11-24 10:59:41 +08:00
l0ng-ai c50c2ea629 feat(editor): support Helm and Go templates (#5522)
Helm chart manifests and .tpl helpers keep YAML highlighting with Go template actions and are served by helm-ls (installable from Settings › Language Servers, pinned 0.5.4). Standalone .gotmpl / .tmpl / .go.tmpl files are a Go Template language: template actions highlighted, the Go icon, and gopls. Adds a small chart fixture.
2026-11-24 10:50:03 +08:00
l0ng-ai 3e9e86edf1 fix(services): keep a disconnected Docker connection disconnected across restarts (#5519)
Disconnecting a Docker connection in Services was remembered only in memory, so after a restart opening Services dialled every saved connection again (including SSH ones the user had disconnected). The Disconnect intent is now saved per connection; panel startup and the 10 s poll skip it until Connect clears the flag. Older settings keep connecting automatically.
2026-11-24 10:36:20 +08:00
l0ng-ai cb24be4c19 docs(readme): switch the WeChat group QR code to group 4 2026-11-24 10:32:53 +08:00
l0ng-ai 52e3276f93 test(ide-host): compile the code action stub only where its test runs (#5516)
The code action stub carries the cfg(unix) of its only test, fixing Windows clippy on main.
2026-11-24 10:24:30 +08:00
l0ng-ai fcf5406de0 fix(keymap): list Smart Type completion and Rearrange Code in every preset (#5515)
Smart Type completion is in the VS Code preset and Rearrange Code is listed (no default shortcut) in the IntelliJ and VS Code presets, fixing the keymap and Vim :action tests on main.
2026-11-24 10:22:47 +08:00
Deng Liuanddengliu aee72d994e chore(dev): replace dogfood:build/install with dogfood:local and dogfood:all (#5271)
dogfood:local builds and installs the local dogfood app (--build-only skips installation); dogfood:all <remote_name> runs it alongside dogfood:remote in parallel with [local]/[remote] prefixed output, validates the SSH configuration before the local build starts, stops the sibling process tree on failure, and runs the remote restart prompt once after both finish. AGENTS.md, mise tasks and the setup docs use the new names.

Co-authored-by: dengliu <[email protected]>
2026-11-24 08:57:51 +08:00
LU XIANGRUIandwildcatDownstairs 397522e099 feat(editor): show language server colors in the gutter (#5229)
Tailwind color classes (`bg-red-500`, `text-brand-700`, `@apply bg-brand-500` in CSS) and the colors a CSS server knows beyond the built-in literal detector (`hwb()`…) now show swatches in the editor gutter. This was the remaining acceptance criterion of #5154. The editor never asked language servers for `textDocument/documentColor`; it only drew swatches for literals it found itself and for colors that plugins reported.
- Backend (`ide-lsp`): the client advertises `colorProvider`. `document_colors` asks every server that has it and tags each color with its server, then drops the answer if the document version changed in the meantime. `color_presentations` asks that server for `textDocument/colorPresentation`. A presentation without its own `textEdit` replaces the color's range with its label. New commands `lsp_document_colors` / `lsp_color_presentations`; bindings regenerated.
- Frontend (`color-preview`): `lspColors.ts` sits next to the plugin source and shares its swatch and picker flow, now in `providerSwatch.ts`. A server color gets no swatch when the built-in detector already shows a literal at the same range, and two servers reporting the same range (CSS + Tailwind) get one swatch. The gutter follows Settings › Editor › General › Gutter Icons › Color preview, and while that is off the editor sends no requests. Picking a color applies the server's single presentation, or offers a menu when there are several.
- Tailwind only presents arbitrary values (`border-[#16a34a]` → `border-[#2563eb]` / `[rgb(…)]` / `[hsl(…)]`). For palette classes like `bg-red-500` it returns none, as in VS Code. In that case a hint says the color can't be changed with the picker (new string, en + zh).

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 08:45:02 +08:00
189 changed files with 7811 additions and 1408 deletions

No files matched your search

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

+9 -3
View File
@@ -155,6 +155,12 @@ 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
if: runner.os == 'Linux'
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
@@ -300,7 +306,7 @@ jobs:
- 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
@@ -308,7 +314,7 @@ jobs:
strategy:
fail-fast: false
matrix:
shard: [1, 2]
shard: [1, 2, 3, 4]
# Browsers and their system libraries are preinstalled; keep the tag in step with @playwright/test.
container: mcr.microsoft.com/playwright:v1.64.1-noble
steps:
@@ -318,7 +324,7 @@ jobs:
- uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm }
- run: pnpm install --frozen-lockfile
- run: pnpm e2e --shard=${{ matrix.shard }}/2
- run: pnpm e2e --shard=${{ matrix.shard }}/4
env:
HOME: /root
- uses: actions/upload-artifact@v6
+48 -13
View File
@@ -65,6 +65,8 @@ concurrency:
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
# Line tables keep test backtraces readable and the binaries the build job hands on small.
CARGO_PROFILE_DEV_DEBUG: line-tables-only
jobs:
# The languages a pull request can affect: a change to one language's fixture, definition or
@@ -132,10 +134,40 @@ 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 != '[]'
# The tests find the fixtures through the checkout path compiled into them (CARGO_MANIFEST_DIR),
# which is the same on every GitHub-hosted runner.
runs-on: ubuntu-22.04
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
shared-key: language-smoke
save-if: ${{ github.ref == 'refs/heads/main' }}
- 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 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:
@@ -149,11 +181,11 @@ jobs:
- 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
with: { version: 11 }
@@ -209,17 +241,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.
+2 -1
View File
@@ -79,8 +79,9 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
this worktree's running MCP bridges and actual ports.
- `pnpm build` — typecheck + bundle frontend.
- `pnpm dogfood:build` / `pnpm dogfood:install` (or `mise run dogfood:build` / `mise run dogfood:install`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
- `pnpm dogfood:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
+1 -1
View File
@@ -68,7 +68,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
- WeChat group — scan to join:
<img src=".github/assets/wechat-group-3.png" alt="WeChat group QR code" width="200">
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
+1 -1
View File
@@ -68,7 +68,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
- WeChat grubu, katılmak için kodu okut:
<img src=".github/assets/wechat-group-3.png" alt="WeChat grubu QR kodu" width="200">
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
+1 -1
View File
@@ -66,7 +66,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
- 微信群,扫码加入:
<img src=".github/assets/wechat-group-3.png" alt="微信群二维码" width="200">
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
+20 -5
View File
@@ -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) {
+3 -2
View File
@@ -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
View File
@@ -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
View File
@@ -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(),
+28 -2
View File
@@ -143,6 +143,9 @@ pub struct DockerConnection {
pub id: String,
pub name: String,
pub endpoint: DockerEndpoint,
/// Whether the user explicitly disconnected this connection in Services.
#[serde(default)]
pub disconnected: bool,
}
/// A registry to log in to (Docker Hub, GHCR, a private one). The password is stored separately.
@@ -414,6 +417,7 @@ mod tests {
id: "c1".into(),
name: "Build box".into(),
endpoint: DockerEndpoint::Tcp { host: "build:2376".into(), tls_cert_dir: None },
disconnected: true,
}],
registries: vec![DockerRegistry {
id: "r1".into(),
@@ -435,12 +439,34 @@ mod tests {
assert!(load_settings(dir).connections.is_empty());
}
#[test]
fn connection_intent_defaults_to_connected_and_round_trips() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
std::fs::write(
dir.join(SETTINGS_FILE),
r#"{"connections":[{"id":"box","name":"Box","endpoint":{"kind":"ssh","config":"build"}}]}"#,
)
.unwrap();
let mut settings = load_settings(dir);
assert!(!settings.connections[0].disconnected);
for disconnected in [true, false] {
settings.connections[0].disconnected = disconnected;
save_settings(dir, &settings).unwrap();
assert_eq!(load_settings(dir), settings);
}
}
#[test]
fn load_drops_the_injected_default_connection() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
let injected =
|| DockerConnection { id: "default".into(), name: "Docker".into(), endpoint: DockerEndpoint::Default };
let injected = || DockerConnection {
id: "default".into(),
name: "Docker".into(),
endpoint: DockerEndpoint::Default,
disconnected: false,
};
let registry =
DockerRegistry { id: "r1".into(), name: "GHCR".into(), address: "ghcr.io".into(), username: "me".into() };
// Saved untouched by an older version (e.g. along with a registry): dropped on load.
+138 -39
View File
@@ -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
View File
@@ -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
View File
@@ -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 ----
+20
View File
@@ -1834,6 +1834,23 @@ pub async fn lsp_document_links(host: &Host, window: &str, doc: DocId) -> IdeRes
Ok(out)
}
/// Colors in a document from its language servers (Tailwind classes, CSS values…).
#[command(trust = trusted)]
pub async fn lsp_document_colors(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<DocumentColor>> {
host.project(window)?.lsp.document_colors(doc).await
}
/// How the server that reported `color` writes it with new components.
#[command(trust = trusted)]
pub async fn lsp_color_presentations(
host: &Host,
window: &str,
doc: DocId,
color: DocumentColor,
) -> IdeResult<Vec<ColorPresentation>> {
host.project(window)?.lsp.color_presentations(doc, color).await
}
#[command(trust = trusted)]
pub async fn lsp_call_hierarchy(
host: &Host,
@@ -2302,6 +2319,7 @@ mod tests {
assert_eq!(result.unwrap_err().kind, ErrorKind::Cancelled);
}
#[cfg(unix)]
fn action_stub() -> CodeAction {
CodeAction {
title: String::new(),
@@ -3046,7 +3064,9 @@ ide_command::domain!(
lsp_code_action_query,
lsp_code_actions,
lsp_code_lens,
lsp_color_presentations,
lsp_completion,
lsp_document_colors,
lsp_document_highlights,
lsp_document_links,
lsp_exception_class_at,
+10
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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.
+877
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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();
+3
View File
@@ -121,6 +121,9 @@ pub struct FrameworkFiles {
pub extensions: Vec<String>,
/// Matched like language servers' `root-markers`, e.g. `manage.py`.
pub root_markers: Vec<String>,
/// Require the marker directly beside `folder`.
#[serde(default)]
pub root_marker_in_parent: bool,
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize, Type)]
+62 -18
View File
@@ -33,6 +33,7 @@ const BUILTIN: &[(&str, &str)] = &[
("gdscript", include_str!("../../../languages/gdscript.toml")),
("gdshader", include_str!("../../../languages/gdshader.toml")),
("go", include_str!("../../../languages/go.toml")),
("gotmpl", include_str!("../../../languages/gotmpl.toml")),
("gherkin", include_str!("../../../languages/gherkin.toml")),
("gomod", include_str!("../../../languages/gomod.toml")),
("gowork", include_str!("../../../languages/gowork.toml")),
@@ -406,7 +407,14 @@ impl LanguageRegistry {
if let Some((_, i)) = t.name_globs.iter().find(|(p, _)| wildcard_match(p, file_name)) {
return languages[*i].id.clone();
}
if let Some(l) = languages.iter().find(|l| l.framework_files.iter().any(|f| is_framework_file(f, path))) {
let framework_language = |root_marker_in_parent| {
languages.iter().find(|l| {
l.framework_files
.iter()
.any(|f| f.root_marker_in_parent == root_marker_in_parent && is_framework_file(f, path))
})
};
if let Some(l) = framework_language(true).or_else(|| framework_language(false)) {
return l.id.clone();
}
let lower = file_name.to_ascii_lowercase();
@@ -429,17 +437,21 @@ impl LanguageRegistry {
}
}
/// `path` is one of `files`: its extension is listed, and the nearest folder above it named
/// `files.folder` has a root marker in a directory above that folder.
/// `path` has a listed extension and lies under a matching folder with a root marker.
fn is_framework_file(files: &crate::FrameworkFiles, path: &Path) -> bool {
let Some(ext) = path.extension().and_then(|e| e.to_str()) else { return false };
if !files.extensions.iter().any(|e| e.eq_ignore_ascii_case(ext)) {
return false;
}
path.ancestors()
.skip(1)
.find(|dir| dir.file_name().is_some_and(|name| name == files.folder.as_str()))
.is_some_and(|folder| crate::marked_root(None, folder, &files.root_markers).is_some())
let mut folders =
path.ancestors().skip(1).filter(|dir| dir.file_name().is_some_and(|name| name == files.folder.as_str()));
if files.root_marker_in_parent {
folders
.filter_map(Path::parent)
.any(|parent| crate::marked_root(Some(parent), parent, &files.root_markers).is_some())
} else {
folders.next().is_some_and(|folder| crate::marked_root(None, folder, &files.root_markers).is_some())
}
}
/// `*` matches any (possibly empty) run of characters, `?` exactly one; everything else is literal.
@@ -486,6 +498,7 @@ mod tests {
"CQL",
"CSS",
"Go",
"Go Template",
"HTML",
"Java",
"JavaScript",
@@ -997,21 +1010,52 @@ mod tests {
std::fs::create_dir_all(root.join("charts/podinfo/templates/tests")).unwrap();
std::fs::create_dir_all(root.join("k8s/templates")).unwrap();
std::fs::write(root.join("charts/podinfo/Chart.yaml"), "apiVersion: v2\nname: podinfo\n").unwrap();
assert_eq!(detect("charts/podinfo/Chart.yaml"), "yaml");
assert_eq!(detect("charts/podinfo/values.yaml"), "yaml");
assert_eq!(detect("charts/podinfo/templates/deployment.yaml"), "helm-template");
assert_eq!(detect("charts/podinfo/templates/tests/connection.yml"), "helm-template");
assert_eq!(detect("charts/podinfo/templates/_helpers.tpl"), "helm-template");
assert_eq!(detect("charts/podinfo/templates/NOTES.txt"), "helm-template");
// No `Chart.yaml` / `Chart.yml` above this `templates` folder.
assert_eq!(detect("k8s/templates/deployment.yaml"), "yaml");
assert_eq!(detect("common.gotmpl"), "helm-template");
// Outside a chart, `.tpl` belongs to other template engines (Smarty, Terraform).
assert_ne!(detect("site/index.tpl"), "helm-template");
std::fs::write(root.join("manage.py"), "").unwrap();
for file in [
"deployment.yaml",
"tests/connection.yml",
"_helpers.tpl",
"NOTES.txt",
"dashboard.json",
"config.yaml.gotmpl",
"config.yaml.go.tmpl",
"tests/templates/check.YAML",
] {
let path = format!("charts/podinfo/templates/{file}");
assert_eq!(detect(&path), "helm-template", "{path}");
}
for (path, language) in [
("charts/podinfo/Chart.yaml", "yaml"),
("charts/podinfo/values.yaml", "yaml"),
("charts/podinfo/docs/templates/deployment.yaml", "yaml"),
("charts/podinfo/docs/templates/_helpers.tpl", "plaintext"),
("charts/podinfo/docs/templates/sample.tmpl", "gotmpl"),
("charts/podinfo/docs/templates/notes.txt", "django-html"),
("k8s/templates/deployment.yaml", "yaml"),
("site/index.tpl", "plaintext"),
] {
assert_eq!(detect(path), language, "{path}");
}
assert!(reg.is_framework_marker(&root.join("charts/podinfo/Chart.yaml")));
assert!(reg.is_framework_marker(&root.join("charts/podinfo/Chart.yml")));
}
#[test]
fn standalone_go_templates_are_detected_by_extension() {
let reg = reg();
for (path, language) in [
("common.gotmpl", "gotmpl"),
("email.tmpl", "gotmpl"),
("config.go.tmpl", "gotmpl"),
("config.GO.TMPL", "gotmpl"),
("docker-stack.yaml.tmpl", "gotmpl"),
("docker-stack.yaml", "yaml"),
("main.go", "go"),
] {
assert_eq!(reg.detect(Path::new(path), None).as_str(), language, "{path}");
}
}
#[test]
fn the_django_fixture_has_templates_and_a_page() {
let reg = reg();
+1
View File
@@ -122,6 +122,7 @@ pub fn client_capabilities() -> Value {
},
"codeLens": { "dynamicRegistration": false },
"documentLink": { "dynamicRegistration": false, "tooltipSupport": true },
"colorProvider": { "dynamicRegistration": false },
"formatting": { "dynamicRegistration": false },
"rangeFormatting": { "dynamicRegistration": false },
"rename": {
+68
View File
@@ -1036,6 +1036,29 @@ pub fn document_link(conv: &Conv, path: &Path, l: lsp::DocumentLink) -> Option<D
})
}
pub fn document_color(conv: &Conv, path: &Path, server: ServerId, c: lsp::ColorInformation) -> DocumentColor {
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
DocumentColor {
range: conv.range(path, c.range),
red: unit(c.color.red),
green: unit(c.color.green),
blue: unit(c.color.blue),
alpha: unit(c.color.alpha),
server,
}
}
/// Without its own edit, a presentation's label replaces the color.
pub fn color_presentation(conv: &Conv, path: &Path, range: Range, p: lsp::ColorPresentation) -> ColorPresentation {
let main = match p.text_edit {
Some(e) => conv.text_edit(path, e),
None => TextEdit { range, new_text: p.label.clone() },
};
let mut edits = vec![main];
edits.extend(conv.text_edits(path, p.additional_text_edits.unwrap_or_default()));
ColorPresentation { label: p.label, edits }
}
pub fn call_item(conv: &Conv, item: &lsp::CallHierarchyItem, from_ranges: Vec<Range>) -> Option<HierarchyItem> {
let (path, uri) = uri_target(item.uri.as_str());
Some(HierarchyItem {
@@ -1634,6 +1657,51 @@ mod tests {
assert_eq!(h.kind, InlayKind::Other);
}
#[test]
fn document_colors_keep_their_server_and_clamp_components() {
let conv = Conv::utf16();
let info = serde_json::from_value::<lsp::ColorInformation>(json!({
"range": { "start": { "line": 2, "character": 14 }, "end": { "line": 2, "character": 24 } },
"color": { "red": 0.937, "green": 0.267, "blue": 0.267, "alpha": 1.5 },
}))
.unwrap();
let c = document_color(&conv, Path::new("/p/a.html"), ServerId(3), info);
assert_eq!(c.range, Range::new(p(2, 14), p(2, 24)));
assert_eq!((c.red, c.green, c.blue, c.alpha), (0.937, 0.267, 0.267, 1.0));
assert_eq!(c.server, ServerId(3));
}
#[test]
fn color_presentations_replace_the_color_unless_the_server_gives_an_edit() {
let conv = Conv::utf16();
let here = Path::new("/p/a.css");
let color = Range::new(p(0, 7), p(0, 10));
let plain = serde_json::from_value::<lsp::ColorPresentation>(json!({ "label": "#00ff00" })).unwrap();
let plain = color_presentation(&conv, here, color, plain);
assert_eq!(plain.label, "#00ff00");
assert_eq!(plain.edits, vec![TextEdit { range: color, new_text: "#00ff00".into() }]);
let edited = serde_json::from_value::<lsp::ColorPresentation>(json!({
"label": "rgb(0 255 0)",
"textEdit": {
"range": { "start": { "line": 0, "character": 7 }, "end": { "line": 0, "character": 10 } },
"newText": "rgb(0 255 0)",
},
"additionalTextEdits": [{
"range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } },
"newText": "/* x */",
}],
}))
.unwrap();
let edited = color_presentation(&conv, here, color, edited);
assert_eq!(
edited.edits,
vec![
TextEdit { range: color, new_text: "rgb(0 255 0)".into() },
TextEdit { range: Range::new(p(0, 0), p(0, 0)), new_text: "/* x */".into() },
]
);
}
#[cfg(unix)]
#[test]
fn document_links_split_file_targets_and_urls() {
+65
View File
@@ -3401,6 +3401,71 @@ impl LspManager {
out.finish(Vec::new())
}
/// The colors the servers find in the document (`textDocument/documentColor`), each tagged with
/// its server for [`Self::color_presentations`]. An answer for an older version is dropped.
pub async fn document_colors(&self, doc: DocId) -> IdeResult<Vec<DocumentColor>> {
let (snap, targets) = self.doc_targets(doc, "document colors", |c| c.has("colorProvider")).await?;
let requests = targets.iter().map(|t| {
let params = json!({ "textDocument": snap.ident() });
async move {
let colors = self
.call_retrying::<_, Option<Vec<lsp::ColorInformation>>>(
t,
"textDocument/documentColor",
params,
DEFAULT_TIMEOUT,
)
.await;
(t, colors)
}
});
let mut out = Outcome::new();
for (t, r) in join_all(requests).await {
match r {
Ok(colors) => {
let conv = self.conv(t.enc());
let acc = out.value.get_or_insert_with(Vec::new);
acc.extend(
colors
.unwrap_or_default()
.into_iter()
.map(|c| convert::document_color(&conv, &snap.path, t.server.id, c)),
);
}
Err(e) => out.fail(e),
}
}
if self.docs.lock().get(&doc).is_none_or(|d| d.version != snap.version) {
return Err(IdeError::cancelled());
}
out.finish(Vec::new())
}
/// How `color.server` would write `color` at its range (`textDocument/colorPresentation`).
pub async fn color_presentations(&self, doc: DocId, color: DocumentColor) -> IdeResult<Vec<ColorPresentation>> {
let snap = self.snapshot(doc)?;
let Some(server) = snap.servers.iter().find(|s| s.id == color.server) else { return Ok(Vec::new()) };
let Some(t) = self.ready_targets(std::slice::from_ref(server), |c| c.has("colorProvider")).await.pop() else {
return Ok(Vec::new());
};
let params = json!({
"textDocument": snap.ident(),
"color": { "red": color.red, "green": color.green, "blue": color.blue, "alpha": color.alpha },
"range": snap.range(&t, color.range),
});
let list: Option<Vec<lsp::ColorPresentation>> =
self.call(&t, "textDocument/colorPresentation", params, None, DEFAULT_TIMEOUT).await?;
if self.docs.lock().get(&doc).is_none_or(|d| d.version != snap.version) {
return Err(IdeError::cancelled());
}
let conv = self.conv(t.enc());
Ok(list
.unwrap_or_default()
.into_iter()
.map(|p| convert::color_presentation(&conv, &snap.path, color.range, p))
.collect())
}
pub async fn call_hierarchy(
&self,
doc: DocId,
+21
View File
@@ -307,6 +307,27 @@ pub struct DocumentLink {
pub tooltip: Option<String>,
}
/// A color a server found in a document (`textDocument/documentColor`); components are 0–1.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DocumentColor {
pub range: Range,
pub red: f32,
pub green: f32,
pub blue: f32,
pub alpha: f32,
pub server: ServerId,
}
/// One way to write a picked color (`textDocument/colorPresentation`): `edits` replace the
/// color's range (with `label` unless the server gave its own edit), then any extra edits.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ColorPresentation {
pub label: String,
pub edits: Vec<TextEdit>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum HierarchyDirection {
+9
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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$ ");
}
}
+49 -25
View File
@@ -1439,26 +1439,10 @@ impl Tools {
sha256: Some(sha256.into()),
checksum_url: None,
}),
ReleaseSource::GitHub { repo } => match http.get_text(&sources::github_latest_url(repo), cancel) {
Ok(json) => sources::github_pick(&json, assets, self.platform),
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
// Without a token the API allows 60 requests an hour per IP address, often used
// up behind a shared one (403/429); the release's web pages have no such limit.
Err(api) => self.resolve_github_web(http, repo, assets, cancel).map_err(|web| {
if web.kind == ErrorKind::Cancelled {
return web;
}
tracing::warn!("GitHub release lookup for {repo} failed: {api}; web pages: {web}");
IdeError::new(
api.kind,
format!(
"{}\nDownload it from {} and set its Path in Settings › Languages & Frameworks › Language Servers.",
api.message,
sources::github_latest_page(repo)
),
)
}),
},
ReleaseSource::GitHub { repo } => self.resolve_github_release(http, repo, None, assets, cancel),
ReleaseSource::GitHubTag { repo, tag } => {
self.resolve_github_release(http, repo, Some(tag), assets, cancel)
}
ReleaseSource::HashiCorp { product } => {
let json = http.get_text(&sources::hashicorp_latest_url(product), cancel)?;
sources::hashicorp_pick(&json, assets, self.platform)
@@ -1485,17 +1469,53 @@ impl Tools {
}
}
/// [`resolve_release`](Self::resolve_release) for a GitHub release, from its web pages.
fn resolve_github_release(
&self,
http: &Http,
repo: &str,
tag: Option<&str>,
assets: &[platform::AssetRule],
cancel: &CancellationToken,
) -> IdeResult<sources::Download> {
let api_url = tag.map_or_else(|| sources::github_latest_url(repo), |tag| sources::github_tag_url(repo, tag));
match http.get_text(&api_url, cancel) {
Ok(json) => sources::github_pick(&json, assets, self.platform),
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
// Shared IP addresses can run out of unauthenticated API requests (403/429).
Err(api) => self.resolve_github_web(http, repo, tag, assets, cancel).map_err(|web| {
if web.kind == ErrorKind::Cancelled {
return web;
}
let page = tag.map_or_else(|| sources::github_latest_page(repo), |tag| sources::github_tag_page(repo, tag));
tracing::warn!("GitHub release lookup for {repo} failed: {api}; web pages: {web}");
IdeError::new(
api.kind,
format!(
"{}\nDownload it from {page} and set its Path in Settings › Languages & Frameworks › Language Servers.",
api.message
),
)
}),
}
}
/// Resolve a GitHub release from its web pages when the API is unavailable.
fn resolve_github_web(
&self,
http: &Http,
repo: &str,
tag: Option<&str>,
assets: &[platform::AssetRule],
cancel: &CancellationToken,
) -> IdeResult<sources::Download> {
let page = http.effective_url(&sources::github_latest_page(repo), cancel)?;
let tag = sources::github_tag_from_url(&page)
.ok_or_else(|| IdeError::unavailable(format!("{repo} has no published release")))?;
let tag = match tag {
Some(tag) => tag.to_owned(),
None => {
let page = http.effective_url(&sources::github_latest_page(repo), cancel)?;
sources::github_tag_from_url(&page)
.ok_or_else(|| IdeError::unavailable(format!("{repo} has no published release")))?
}
};
let list = http.get_text(&sources::github_assets_page(repo, &tag), cancel)?;
match sources::github_pick_web(repo, &tag, &list, None, assets, self.platform) {
Err(e) if e.kind == ErrorKind::Unavailable => {
@@ -1516,7 +1536,11 @@ impl Tools {
emit: Emit,
) -> IdeResult<()> {
let http = Http::new(&self.system_path)?;
emit(InstallEvent::Line { text: "Resolving the latest release…".into() });
let message = match source {
ReleaseSource::GitHubTag { tag, .. } => format!("Resolving release {tag}…"),
_ => "Resolving the latest release…".into(),
};
emit(InstallEvent::Line { text: message });
let dl = self.resolve_release(&http, source, assets, cancel)?;
emit(InstallEvent::Line { text: format!("Downloading {} ({})", dl.name, dl.url) });
let staging = self.root.join(format!(".staging-{}", spec.name));
+45
View File
@@ -24,6 +24,8 @@ pub enum ReleaseSource {
Fixed { version: &'static str, url: &'static str, sha256: &'static str },
/// Latest GitHub release of `owner/repo`; assets plus links in the release notes.
GitHub { repo: &'static str },
/// Assets from a specific GitHub release tag.
GitHubTag { repo: &'static str, tag: &'static str },
/// `api.releases.hashicorp.com` product.
HashiCorp { product: &'static str },
/// Latest Eclipse JDT LS milestone tarball from download.eclipse.org.
@@ -604,6 +606,27 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/samehelhawary/phoxite",
needs: &[],
},
ToolSpec {
name: "helm-ls",
display: "helm-ls",
kind: LanguageServer,
commands: &["helm_ls"],
method: Method::Release {
source: ReleaseSource::GitHubTag { repo: "mrjosh/helm-ls", tag: "v0.5.4" },
assets: &[
rule(Mac, Arm64, "helm_ls_darwin_arm64"),
rule(Mac, X64, "helm_ls_darwin_amd64"),
rule(Linux, Arm64, "helm_ls_linux_arm64"),
rule(Linux, X64, "helm_ls_linux_amd64"),
rule(Windows, X64, "helm_ls_windows_amd64.exe"),
],
locate: &["helm_ls"],
},
fallback: None,
version: Some(("helm_ls", &["version"])),
homepage: "https://github.com/mrjosh/helm-ls",
needs: &[],
},
ToolSpec {
name: "gopls",
display: "gopls",
@@ -1362,6 +1385,28 @@ mod tests {
}
}
#[test]
fn helm_ls_picks_the_pinned_native_binary() {
use crate::platform::{Platform, select_asset};
let spec = find("helm-ls").unwrap();
assert!(matches!(
spec.method,
Method::Release { source: ReleaseSource::GitHubTag { repo: "mrjosh/helm-ls", tag: "v0.5.4" }, .. }
));
let releases = [
(Mac, Arm64, "helm_ls_darwin_arm64"),
(Mac, X64, "helm_ls_darwin_amd64"),
(Linux, Arm64, "helm_ls_linux_arm64"),
(Linux, X64, "helm_ls_linux_amd64"),
(Windows, X64, "helm_ls_windows_amd64.exe"),
];
let checksums = releases.map(|(_, _, name)| format!("{name}.sha256sum"));
let names: Vec<_> = checksums.iter().map(String::as_str).chain(releases.map(|(_, _, name)| name)).collect();
for (os, arch, name) in releases {
assert_eq!(select_asset(&names, spec.asset_rules(), Platform { os, arch }), Some(name));
}
}
/// The v263 kotlin-server-* release notes: the CLI distribution archives plus
/// the VS Code extension and checksums; each platform must pick its native
/// distribution and the aarch64 archive must never be picked on x64.
+4
View File
@@ -47,6 +47,10 @@ pub fn github_latest_url(repo: &str) -> String {
format!("https://api.github.com/repos/{repo}/releases/latest")
}
pub fn github_tag_url(repo: &str, tag: &str) -> String {
format!("https://api.github.com/repos/{repo}/releases/tags/{tag}")
}
/// The latest release's web page; it redirects to `…/releases/tag/<tag>`. Web pages don't
/// count against the API's rate limit for unauthenticated clients (60 requests an hour).
pub fn github_latest_page(repo: &str) -> String {
+2
View File
@@ -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;
+224
View File
@@ -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());
}
}
+42
View File
@@ -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
View File
@@ -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
View File
@@ -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.
+1 -1
View File
@@ -67,7 +67,7 @@ mise run dev
`setup` runs `pnpm install` in this worktree. `dev` and `dev:app` use the same worktree-aware launchers as the direct commands. No shell activation is needed for `mise run`.
Run `mise tasks` to list all tasks. `mise run build` builds the frontend (not a desktop installer); `mise run dogfood:build` and `mise run dogfood:install` build and locally install a grey-icon dogfood desktop app that shares settings and data with the release app. Only one of the two apps runs at a time, since they share one instance; settings written by the newer dogfood build can make an older release ignore the settings file. The dogfood app never updates itself: run `dogfood:install` again to pick up new changes. `mise run dogfood:remote <remote_name>` builds and stages `openidea-server` on an SSH host configured in **Tools › SSH Configurations** (`--clean` removes the override). `mise run test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target.
Run `mise tasks` to list all tasks. `mise run build` builds the frontend (not a desktop installer); `mise run dogfood:local` builds and locally installs a grey-icon dogfood desktop app (`--build-only` skips installation) that shares settings and data with the release app. Only one of the two apps runs at a time, since they share one instance; settings written by the newer dogfood build can make an older release ignore the settings file. The dogfood app never updates itself: run `dogfood:local` again to pick up new changes. `mise run dogfood:remote <remote_name>` builds and stages `openidea-server` on an SSH host configured in **Tools › SSH Configurations** (`--clean` removes the override), and `mise run dogfood:all <remote_name>` runs `dogfood:local` and `dogfood:remote <remote_name>` in parallel. `mise run test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target.
## Worktrees
+33 -6
View File
@@ -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
View File
@@ -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
+1 -1
View File
@@ -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
View File
@@ -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` 打印应用版本和协议版本。
+1 -1
View File
@@ -67,7 +67,7 @@ mise run dev
`setup` 在当前 worktree 中执行 `pnpm install`。`dev` 和 `dev:app` 都沿用原来的启动脚本,保留 worktree 隔离。使用 `mise run` 不需要在 shell 中激活 mise。
运行 `mise tasks` 可以查看全部任务。`mise run build` 构建前端,不生成桌面安装包;`mise run dogfood:build` 和 `mise run dogfood:install` 用于构建并在本地安装灰色图标的 dogfood 桌面版(与正式版共享设置和数据)。两者共用同一个实例,同一时间只能运行一个;较新的 dogfood 版写入的设置可能让较旧的正式版忽略整个设置文件。dogfood 版不会自动更新,需要更新时重新运行 `dogfood:install`。`mise run dogfood:remote <remote_name>` 在 **工具 › SSH 配置** 中指定的远程主机上构建并部署 `openidea-server`(`--clean` 可移除覆盖)。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。
运行 `mise tasks` 可以查看全部任务。`mise run build` 构建前端,不生成桌面安装包;`mise run dogfood:local` 用于构建并在本地安装灰色图标的 dogfood 桌面版(与正式版共享设置和数据;`--build-only` 仅构建不安装)。两者共用同一个实例,同一时间只能运行一个;较新的 dogfood 版写入的设置可能让较旧的正式版忽略整个设置文件。dogfood 版不会自动更新,需要更新时重新运行 `dogfood:local`。`mise run dogfood:remote <remote_name>` 在 **工具 › SSH 配置** 中指定的远程主机上构建并部署 `openidea-server`(`--clean` 可移除覆盖),`mise run dogfood:all <remote_name>` 则并行执行 `dogfood:local` 与 `dogfood:remote <remote_name>`。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。
## Worktree
+23 -4
View File
@@ -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
View File
@@ -74,7 +74,8 @@ SSH 代理使用 `IdentityAgent` 指定的那个,未指定时使用登录 shel
- OpenIDEA 安装的语言服务器、调试器等工具都装在远程主机的 `~/.openidea/data` 下。
- 快捷键、外观、编辑器字体和配色方案保留在本机;项目和工具相关的设置保存在主机上。
- 你的代码插件会同步到服务端,在项目所在的机器上运行。
- **文件 › 断开与远程主机的连接**会关闭项目并断开连接。
- 关闭窗口时选择**保持后端运行**,或使用**文件 › 断开与远程主机的连接**,会保留远程 IDE 后端及其任务。重新打开项目即可接回。
- 关闭窗口时选择**停止后端**,或使用**文件 › 停止远程后端**,会关闭后端及其任务。有关空闲超时和手动清理,请参阅[关闭窗口或停止远程后端](/zh/guide/remote/server#关闭窗口或停止远程后端)。
### 端口转发
+1 -1
View File
@@ -27,7 +27,7 @@ description: "使用内置终端:标签页、拆分、Shell、链接、查找
### 重启 IDE 之后
OpenIDEA 会按项目记住终端标签页:各自的目录、自定义名称、使用的 Shell 以及拆分布局(最多 32 个标签页)。重启后每个标签页都会在原目录**重新**启动一个会话,不会恢复滚动缓冲区和正在运行的命令。
OpenIDEA 会按项目记住终端标签页:各自的目录、自定义名称、使用的 Shell 以及拆分布局(最多 32 个标签页)。对于本地项目,重启后每个标签页都会在原目录**重新**启动一个会话,不会恢复滚动缓冲区和正在运行的命令;对于远程项目,关闭并重新打开窗口会重新连接到 `openidea-server` 上仍在运行的终端会话,并恢复最近的终端输出与正在执行的命令。
## 终端中的按键
+2 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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,
}) => {
-44
View File
@@ -1,44 +0,0 @@
/** The npm tool window lists package.json scripts without run configurations and runs them. */
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const PKG = JSON.stringify({ name: "acme-api", scripts: { dev: "vite", build: "vite build" } });
/** The root package.json has scripts; there are no run configurations. */
async function stubNpm(page: Page) {
await stubDesktop(page);
await page.evaluate(async (pkg) => {
const h = window.__ipc.handlers;
h.fs_read_text = (args) => (String(args.path).endsWith("/package.json") ? pkg : "");
h.run_configs = () => [];
h.run_start = (args) => {
const config = args.config as { id: string; name: string };
return { id: 8, configId: config.id, name: config.name, pid: 4242, running: true, pty: false };
};
const npmModule = "/src/features/run/npmScripts.ts";
const { loadNpmScripts } = await import(/* @vite-ignore */ npmModule);
await loadNpmScripts();
}, PKG);
}
test("lists scripts without run configurations and runs one on double-click", async ({ workbench: page }) => {
await stubNpm(page);
await page.getByRole("button", { name: "npm", exact: true }).click();
const tree = page.getByRole("tree", { name: "npm scripts" });
await expect(tree).toBeVisible();
await expect(tree.getByRole("treeitem", { name: /^acme-api/ })).toBeVisible();
await expect(tree.getByRole("treeitem", { name: "dev" })).toBeVisible();
await expect(tree.getByRole("treeitem", { name: "build" })).toBeVisible();
await tree.getByRole("treeitem", { name: "dev" }).dblclick();
const [started] = await ipcCalls(page, "run_start");
expect(started).toMatchObject({ config: { args: ["run", "dev"], kind: "npm" } });
});
test("offers Run / Debug in a script's context menu", async ({ workbench: page }) => {
await stubNpm(page);
await page.getByRole("button", { name: "npm", exact: true }).click();
const tree = page.getByRole("tree", { name: "npm scripts" });
await tree.getByRole("treeitem", { name: "build" }).click({ button: "right" });
await expect(page.getByRole("menuitem", { name: /Run '.*run build'/ })).toBeVisible();
await expect(page.getByRole("menuitem", { name: /Debug '.*run build'/ })).toBeVisible();
});
+298
View File
@@ -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();
});
+108
View File
@@ -679,3 +679,111 @@ 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);
});
+3 -1
View File
@@ -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");
+4
View File
@@ -0,0 +1,4 @@
apiVersion: v2
name: hello
description: A sample chart for template editing
version: 0.1.0
@@ -0,0 +1,7 @@
services:
web:
image: {{ printf "nginx:%s" .Tag }}
{{- if .Replicas }}
deploy:
replicas: {{ .Replicas }}
{{- end }}
@@ -0,0 +1,3 @@
{{- define "hello.name" -}}
{{ .Release.Name }}
{{- end -}}
@@ -0,0 +1,6 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: {{ include "hello.name" . }}
data:
message: {{ .Values.message | quote }}
+1
View File
@@ -0,0 +1 @@
message: Hello from Helm
+12
View File
@@ -0,0 +1,12 @@
id = "gotmpl"
name = "Go Template"
extensions = ["gotmpl", "tmpl"]
block-comment = ["{{/*", "*/}}"]
ui-mode = "Go Template"
[[language-servers]]
name = "gopls"
command = "gopls"
initialization-options = { semanticTokens = true, vulncheck = "Imports", hints = { constantValues = true } }
root-markers = ["go.work", "go.mod"]
install-hint = "go install golang.org/x/tools/gopls@latest"
+11 -6
View File
@@ -1,16 +1,21 @@
id = "helm-template"
name = "Helm Template"
# `.tpl` is Smarty, Terraform and other template engines too: only charts claim it (below).
extensions = ["gotmpl"]
line-comment = "#"
block-comment = ["{{/*", "*/}}"]
indent = { tab-size = 2, insert-spaces = true }
ui-mode = "Helm Template"
# Helm charts: YAML, template and notes files in a `templates` folder.
# No YAML formatter or strict YAML language server: Go `{{ … }}` actions are
# not valid YAML until rendered by `helm template`.
# Helm charts: YAML, templates and notes in the chart's `templates` folder.
[[framework-files]]
folder = "templates"
extensions = ["yaml", "yml", "tpl", "txt"]
extensions = ["yaml", "yml", "json", "tpl", "txt", "gotmpl", "tmpl"]
root-markers = ["Chart.yaml", "Chart.yml"]
root-marker-in-parent = true
[[language-servers]]
name = "helm-ls"
command = "helm_ls"
args = ["serve"]
root-markers = ["Chart.yaml"]
require-root-marker = true
install-hint = "https://github.com/mrjosh/helm-ls/releases/tag/v0.5.4"
+7 -8
View File
@@ -20,19 +20,18 @@ run = "pnpm dev:app"
description = "Typecheck, bundle and verify the frontend"
run = "pnpm build"
[tasks."dogfood:build"]
description = "Build a local dogfood desktop app bundle"
run = "pnpm dogfood:build"
[tasks."dogfood:install"]
description = "Build and install the local dogfood desktop app"
depends = ["dogfood:build"]
run = "pnpm dogfood:install --no-build"
[tasks."dogfood:local"]
description = "Build and locally install the dogfood desktop app"
run = "pnpm dogfood:local"
[tasks."dogfood:remote"]
description = "Build and install a local dogfood openidea-server on a configured SSH remote"
run = "pnpm dogfood:remote"
[tasks."dogfood:all"]
description = "Build and install the local dogfood desktop app and remote openidea-server in parallel"
run = "pnpm dogfood:all"
[tasks.test]
description = "Run the frontend and Rust workspace tests"
run = ["pnpm test", "cargo test --workspace"]
+3 -3
View File
@@ -34,9 +34,9 @@
"perf:rust": "node perf/rust.ts",
"eval": "node evals/run.ts",
"release:prepare": "node scripts/release-prepare.ts",
"dogfood:build": "node scripts/dogfood.ts build",
"dogfood:install": "node scripts/dogfood.ts install",
"dogfood:remote": "node scripts/dogfood-remote.ts"
"dogfood:local": "node scripts/dogfood.ts local",
"dogfood:remote": "node scripts/dogfood-remote.ts",
"dogfood:all": "node scripts/dogfood.ts all"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged"
+36 -10
View File
@@ -1058,16 +1058,48 @@ async function handleRunningRemoteServers(
}
}
export async function runDogfoodRemote(root: string, cliArgs: readonly string[]) {
const parsed = parseDogfoodRemoteArgs(cliArgs);
export interface DogfoodRemoteTarget {
remoteConfig: SshRemoteConfig;
remoteContext: RemoteContext;
sshArgs: string[];
version: string;
rustVersion: string;
localDataDir: string;
}
export function resolveDogfoodRemoteTarget(root: string, parsed: DogfoodRemoteArgs): DogfoodRemoteTarget {
const { version, rustVersion } = readWorkspaceMetadata(root);
const { configDir, localDataDir } = resolveAppDirs();
const envOpts = (process.env.DOGFOOD_SSH_OPTS ?? "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
const extraSshOpts = [...envOpts, ...parsed.sshOpts];
const configs = loadSshConfigs(configDir, root);
const remoteConfig = resolveSshConfig(configs, parsed.remoteName!);
const remoteContext: RemoteContext = {
name: remoteConfig.name,
endpoint: formatRemoteEndpoint(remoteConfig),
};
const sshArgs = buildSshArgs(remoteConfig, extraSshOpts);
return { remoteConfig, remoteContext, sshArgs, version, rustVersion, localDataDir };
}
export async function finishDogfoodRemoteRestart(root: string, parsed: DogfoodRemoteArgs) {
if (parsed.restart === "never" || !parsed.remoteName) return;
const { remoteContext, sshArgs, version, localDataDir } = resolveDogfoodRemoteTarget(root, parsed);
const { os, arch } = probeRemote(sshArgs, remoteContext);
const markerPath = join(localDataDir, "server", version, `${os}-${arch}`, DOGFOOD_MARKER_FILE);
if (!existsSync(markerPath)) return;
const buildId = readFileSync(markerPath, "utf8").trim();
if (!buildId) return;
await handleRunningRemoteServers(sshArgs, remoteContext, buildId, parsed.restart);
}
export async function runDogfoodRemote(root: string, cliArgs: readonly string[]) {
const parsed = parseDogfoodRemoteArgs(cliArgs);
const { version } = readWorkspaceMetadata(root);
const { localDataDir } = resolveAppDirs();
if (parsed.clean && !parsed.remoteName) {
const cleaned = cleanLocalDogfoodServers(localDataDir, version);
@@ -1083,13 +1115,7 @@ export async function runDogfoodRemote(root: string, cliArgs: readonly string[])
return;
}
const configs = loadSshConfigs(configDir, root);
const remoteConfig = resolveSshConfig(configs, parsed.remoteName!);
const remoteContext: RemoteContext = {
name: remoteConfig.name,
endpoint: formatRemoteEndpoint(remoteConfig),
};
const sshArgs = buildSshArgs(remoteConfig, extraSshOpts);
const { remoteConfig, remoteContext, sshArgs, rustVersion } = resolveDogfoodRemoteTarget(root, parsed);
const probe = probeRemote(sshArgs, remoteContext);
const { os, arch } = probe;
const platformKey = `${os}-${arch}`;
+76 -8
View File
@@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import {
DEFAULT_DOGFOOD_APP_NAME,
deferRestartArgs,
dogfoodBuildEnv,
dogfoodCliArgs,
dogfoodPaths,
@@ -13,18 +14,85 @@ import {
generateDogfoodIcons,
installDogfood,
parseDogfoodArgs,
runParallelTasks,
} from "./dogfood.ts";
const root = fileURLToPath(new URL("..", import.meta.url));
describe("dogfood build and install", () => {
it("parses build and install arguments, including pnpm separator flags", () => {
expect(parseDogfoodArgs(["build"])).toEqual({ action: "build", skipBuild: false });
expect(parseDogfoodArgs(["install"])).toEqual({ action: "install", skipBuild: false });
expect(parseDogfoodArgs(["install", "--no-build"])).toEqual({ action: "install", skipBuild: true });
expect(parseDogfoodArgs(["install", "--", "--no-build"])).toEqual({ action: "install", skipBuild: true });
expect(() => parseDogfoodArgs([])).toThrow(/Expected 'build' or 'install'/);
expect(() => parseDogfoodArgs(["build", "--no-build"])).toThrow(/Unexpected option/);
describe("dogfood local and all", () => {
it("parses local and all arguments, including pnpm separator flags", () => {
expect(parseDogfoodArgs(["local"])).toEqual({ action: "local", buildOnly: false });
expect(parseDogfoodArgs(["local", "--build-only"])).toEqual({ action: "local", buildOnly: true });
expect(parseDogfoodArgs(["local", "--", "--build-only"])).toEqual({ action: "local", buildOnly: true });
expect(parseDogfoodArgs(["all", "--", "my-remote", "--build-only", "--restart", "--ssh-opt", "Port=2222"])).toEqual(
{
action: "all",
buildOnly: true,
remoteArgs: ["my-remote", "--restart", "--ssh-opt", "Port=2222"],
remote: {
remoteName: "my-remote",
clean: false,
installRust: false,
restart: "always",
sshOpts: ["Port=2222"],
},
},
);
expect(deferRestartArgs(["my-remote", "--restart", "--ssh-opt", "Port=2222"])).toEqual([
"my-remote",
"--ssh-opt",
"Port=2222",
"--no-restart",
]);
expect(() => parseDogfoodArgs([])).toThrow(/Expected 'local' or 'all'/);
expect(() => parseDogfoodArgs(["build"])).toThrow(/Expected 'local' or 'all'/);
expect(() => parseDogfoodArgs(["local", "my-remote"])).toThrow(/Unexpected option/);
expect(() => parseDogfoodArgs(["all"])).toThrow(/Usage: dogfood:all <remote_name>/);
expect(() => parseDogfoodArgs(["all", "my-remote", "--clean"])).toThrow(/dogfood:remote <remote_name> --clean/);
});
it("runs parallel tasks concurrently, prefixes lines, and terminates siblings on failure", async () => {
const out: string[] = [];
const err: string[] = [];
await runParallelTasks(
[
{
label: "local",
command: process.execPath,
args: ["-e", 'process.stdout.write("step 1\\nstep "); setTimeout(() => process.stdout.write("2"), 40);'],
},
{
label: "remote",
command: process.execPath,
args: ["-e", 'process.stderr.write("warn line\\n"); process.stdout.write("done\\n");'],
},
],
{ stdout: (line) => out.push(line), stderr: (line) => err.push(line) },
);
expect(out).toContain("[local] step 1\n");
expect(out).toContain("[local] step 2\n");
expect(out).toContain("[remote] done\n");
expect(err).toEqual(["[remote] warn line\n"]);
const started = Date.now();
await expect(
runParallelTasks(
[
{
label: "local",
command: process.execPath,
args: ["-e", "setTimeout(() => {}, 10_000)"],
},
{
label: "remote",
command: process.execPath,
args: ["-e", "setTimeout(() => process.exit(2), 50)"],
},
],
{ stdout: () => {}, stderr: () => {} },
),
).rejects.toThrow(/\[remote\] exited with status 2/);
expect(Date.now() - started).toBeLessThan(3_000);
});
it("keeps the vanilla app identifier so settings, MCP, Skills and agent sessions are shared, without updates", () => {
+200 -23
View File
@@ -1,4 +1,4 @@
import { spawnSync } from "node:child_process";
import { spawn, spawnSync, type ChildProcess } from "node:child_process";
import { createHash } from "node:crypto";
import {
chmodSync,
@@ -16,16 +16,29 @@ import { createRequire } from "node:module";
import { homedir } from "node:os";
import { dirname, join, relative } from "node:path";
import { fileURLToPath } from "node:url";
import {
finishDogfoodRemoteRestart,
parseDogfoodRemoteArgs,
resolveDogfoodRemoteTarget,
type DogfoodRemoteArgs,
} from "./dogfood-remote.ts";
export const DEFAULT_DOGFOOD_APP_NAME = "openidea_dogfood";
const LSREGISTER_PATH =
"/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";
export interface DogfoodCommand {
action: "build" | "install";
skipBuild: boolean;
}
export type DogfoodCommand =
| {
action: "local";
buildOnly: boolean;
}
| {
action: "all";
buildOnly: boolean;
remoteArgs: string[];
remote: DogfoodRemoteArgs;
};
export interface DogfoodPaths {
bundlePath: string;
@@ -35,18 +48,39 @@ export interface DogfoodPaths {
export function parseDogfoodArgs(args: readonly string[]): DogfoodCommand {
const filtered = args.filter((arg) => arg !== "--");
const action = filtered[0];
if (action !== "build" && action !== "install") {
throw new Error(`Expected 'build' or 'install', got ${action ? `'${action}'` : "no command"}`);
if (action !== "local" && action !== "all") {
throw new Error(`Expected 'local' or 'all', got ${action ? `'${action}'` : "no command"}`);
}
let skipBuild = false;
for (const flag of filtered.slice(1)) {
if (action === "install" && flag === "--no-build") {
skipBuild = true;
let buildOnly = false;
const rest: string[] = [];
for (const arg of filtered.slice(1)) {
if (arg === "--build-only") {
buildOnly = true;
} else if (action === "local") {
throw new Error(`Unexpected option '${arg}' for 'local'`);
} else {
throw new Error(`Unexpected option '${flag}' for '${action}'`);
rest.push(arg);
}
}
return { action, skipBuild };
if (action === "local") {
return { action: "local", buildOnly };
}
if (rest.includes("--clean")) {
throw new Error("Unexpected option '--clean' for 'all'; use 'dogfood:remote <remote_name> --clean' instead");
}
let remote: DogfoodRemoteArgs;
try {
remote = parseDogfoodRemoteArgs(rest);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(
message.startsWith("Usage:")
? "Usage: dogfood:all <remote_name> [--build-only] [--install-rust] [--restart | --no-restart] [--ssh-opt key=value]"
: message,
{ cause: error },
);
}
return { action: "all", buildOnly, remoteArgs: rest, remote };
}
/**
@@ -218,7 +252,7 @@ export function buildDogfood(root: string, appName: string) {
const SHARED_DATA_NOTES = [
"The dogfood app shares its single instance with OpenIDEA: quit one before opening the other.",
"It writes OpenIDEA's settings and data; a setting only newer builds know can make an older OpenIDEA ignore your settings file.",
"It never updates itself: run 'pnpm dogfood:install' again to pick up new changes.",
"It never updates itself: run 'pnpm dogfood:local' again to pick up new changes.",
];
export function installDogfood(
@@ -240,7 +274,7 @@ function installBundle(
installPath: string,
) {
if (!existsSync(bundlePath)) {
throw new Error(`Dogfood build output not found at ${bundlePath}; run 'mise run dogfood:build' first`);
throw new Error(`Dogfood build output not found at ${bundlePath}; run 'mise run dogfood:local --build-only' first`);
}
if (platform === "darwin") {
@@ -297,21 +331,164 @@ function installBundle(
console.log(`Installed ${appName} to ${installPath}`);
}
function main() {
const root = realpathSync(fileURLToPath(new URL("..", import.meta.url)));
const { action, skipBuild } = parseDogfoodArgs(process.argv.slice(2));
const appName = process.env.DOGFOOD_APP_NAME?.trim() || DEFAULT_DOGFOOD_APP_NAME;
if (action === "build" || !skipBuild) {
buildDogfood(root, appName);
export interface ParallelTaskSpec {
label: string;
command: string;
args: string[];
cwd?: string;
env?: NodeJS.ProcessEnv;
}
function stopProcessTree(child: ChildProcess, signal: NodeJS.Signals) {
if (!child.pid) return;
if (process.platform === "win32") {
spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
} else {
try {
process.kill(-child.pid, signal);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
}
}
if (action === "install") {
}
function pipePrefixedLines(
stream: NodeJS.ReadableStream | null,
prefix: string,
writeLine: (line: string) => void,
): Promise<void> {
if (!stream) return Promise.resolve();
return new Promise((resolve) => {
let remainder = "";
stream.setEncoding("utf8");
stream.on("data", (chunk: string) => {
remainder += chunk;
let newline = remainder.indexOf("\n");
while (newline !== -1) {
const line = remainder.slice(0, newline).replace(/\r$/, "");
writeLine(`[${prefix}] ${line}\n`);
remainder = remainder.slice(newline + 1);
newline = remainder.indexOf("\n");
}
});
stream.on("end", () => {
if (remainder.length > 0) {
writeLine(`[${prefix}] ${remainder.replace(/\r$/, "")}\n`);
}
resolve();
});
stream.on("error", () => resolve());
});
}
export async function runParallelTasks(
specs: readonly ParallelTaskSpec[],
writers: {
stdout?: (text: string) => void;
stderr?: (text: string) => void;
} = {},
): Promise<void> {
const writeOut = writers.stdout ?? ((text: string) => process.stdout.write(text));
const writeErr = writers.stderr ?? ((text: string) => process.stderr.write(text));
const children: ChildProcess[] = [];
let firstError: Error | null = null;
let killTimer: ReturnType<typeof setTimeout> | undefined;
const stopAll = (signal: NodeJS.Signals) => {
for (const child of children) stopProcessTree(child, signal);
if (signal === "SIGTERM") {
killTimer ??= setTimeout(() => {
for (const child of children) stopProcessTree(child, "SIGKILL");
}, 5000);
killTimer.unref();
}
};
const onSigint = () => stopAll("SIGTERM");
const onSigterm = () => stopAll("SIGTERM");
process.on("SIGINT", onSigint);
process.on("SIGTERM", onSigterm);
try {
await Promise.all(
specs.map(
(spec) =>
new Promise<void>((resolve) => {
const child = spawn(spec.command, spec.args, {
cwd: spec.cwd,
env: spec.env,
stdio: ["ignore", "pipe", "pipe"],
detached: process.platform !== "win32",
});
children.push(child);
const outDone = pipePrefixedLines(child.stdout, spec.label, writeOut);
const errDone = pipePrefixedLines(child.stderr, spec.label, writeErr);
child.once("error", (err) => {
if (!firstError) {
firstError = new Error(`[${spec.label}] ${err.message}`);
stopAll("SIGTERM");
}
void Promise.all([outDone, errDone]).then(() => resolve());
});
child.once("close", (code, signal) => {
if (code !== 0 && !firstError) {
firstError = new Error(
`[${spec.label}] exited with ${code !== null ? `status ${code}` : `signal ${signal}`}`,
);
stopAll("SIGTERM");
}
void Promise.all([outDone, errDone]).then(() => resolve());
});
}),
),
);
} finally {
if (killTimer) clearTimeout(killTimer);
process.off("SIGINT", onSigint);
process.off("SIGTERM", onSigterm);
}
if (firstError) throw firstError;
}
export function deferRestartArgs(remoteArgs: readonly string[]): string[] {
return [...remoteArgs.filter((arg) => arg !== "--restart" && arg !== "--no-restart"), "--no-restart"];
}
async function runDogfoodAll(root: string, command: Extract<DogfoodCommand, { action: "all" }>) {
// Validate the SSH remote exists in settings.toml before starting the local Cargo build.
resolveDogfoodRemoteTarget(root, command.remote);
const localArgs = [join(root, "scripts", "dogfood.ts"), "local"];
if (command.buildOnly) localArgs.push("--build-only");
const remoteScriptArgs = [join(root, "scripts", "dogfood-remote.ts"), ...deferRestartArgs(command.remoteArgs)];
await runParallelTasks([
{ label: "local", command: process.execPath, args: localArgs, cwd: root, env: process.env },
{ label: "remote", command: process.execPath, args: remoteScriptArgs, cwd: root, env: process.env },
]);
await finishDogfoodRemoteRestart(root, command.remote);
}
async function main() {
const root = realpathSync(fileURLToPath(new URL("..", import.meta.url)));
const parsed = parseDogfoodArgs(process.argv.slice(2));
if (parsed.action === "all") {
await runDogfoodAll(root, parsed);
return;
}
const appName = process.env.DOGFOOD_APP_NAME?.trim() || DEFAULT_DOGFOOD_APP_NAME;
buildDogfood(root, appName);
if (!parsed.buildOnly) {
installDogfood(root, appName);
}
}
if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) {
try {
main();
await main();
} catch (error) {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
+1 -8
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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,
+22 -10
View File
@@ -182,15 +182,27 @@ impl Tail {
}
}
/// Starts `bin --stdio` in `distro` and speaks the protocol over its stdio. The process dies
/// with the connection.
pub(crate) fn spawn(distro: &str, bin: &str, handler: Arc<dyn Handler>, tail: &Tail) -> IdeResult<Peer> {
spawn_with(ide_core::wsl::EXE, distro, bin, handler, tail)
/// Starts `bin --attach <project_path>` in `distro` and speaks the protocol over its stdio.
pub(crate) fn spawn(
distro: &str,
bin: &str,
project_path: &str,
handler: Arc<dyn Handler>,
tail: &Tail,
) -> IdeResult<Peer> {
spawn_with(ide_core::wsl::EXE, distro, bin, project_path, handler, tail)
}
/// [`spawn`] through `launcher` instead of `wsl.exe` (tests put a stand-in there).
fn spawn_with(launcher: &str, distro: &str, bin: &str, handler: Arc<dyn Handler>, tail: &Tail) -> IdeResult<Peer> {
let args: Vec<String> = ["-d", checked(distro)?, "--exec", bin, "--stdio"].map(str::to_owned).into();
fn spawn_with(
launcher: &str,
distro: &str,
bin: &str,
project_path: &str,
handler: Arc<dyn Handler>,
tail: &Tail,
) -> IdeResult<Peer> {
let args: Vec<String> = ["-d", checked(distro)?, "--exec", bin, "--attach", project_path].map(str::to_owned).into();
let tail = tail.clone();
Peer::spawn(launcher, &args, &std::env::temp_dir(), &[], handler, Box::new(move |line| tail.push(line)))
.map_err(|e| IdeError::unavailable(format!("cannot start wsl.exe: {e}")))
@@ -274,12 +286,12 @@ mod tests {
#[tokio::test]
async fn speaks_the_protocol_through_the_launcher_after_its_utf16_notice() {
use std::os::unix::fs::PermissionsExt;
let (distro, bin) = ("Debian-12", "/home/me/server");
let (distro, bin, project) = ("Debian-12", "/home/me/server", "/home/me/proj");
let dir = tempfile::tempdir().unwrap();
let launcher = dir.path().join("fake-wsl");
let script = format!(
r#"#!/bin/sh
[ "$*" = "-d {distro} --exec {bin} --stdio" ] || {{ echo "unexpected arguments: $*" >&2; exit 2; }}
[ "$*" = "-d {distro} --exec {bin} --attach {project}" ] || {{ echo "unexpected arguments: $*" >&2; exit 2; }}
printf '\377\376N\000o\000\r\000\n\000'
while read -r line; do
line=${{line%?}}
@@ -293,7 +305,7 @@ printf 'Content-Length: %s\r\n\r\n%s' "${{#body}}" "$body"
std::fs::write(&launcher, script).unwrap();
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
let tail = Tail::default();
let peer = spawn_with(launcher.to_str().unwrap(), distro, bin, Arc::new(Silent), &tail).unwrap();
let peer = spawn_with(launcher.to_str().unwrap(), distro, bin, project, Arc::new(Silent), &tail).unwrap();
let reply: String = peer.request("ping", serde_json::Value::Null, None).await.unwrap_or_else(|e| {
panic!("{e:?}; launcher said: {}", tail.text());
});
@@ -302,7 +314,7 @@ printf 'Content-Length: %s\r\n\r\n%s' "${{#body}}" "$body"
#[tokio::test]
async fn a_bad_distro_name_never_starts_the_launcher() {
let err = spawn_with("does-not-exist", "-d", "/x", Arc::new(Silent), &Tail::default()).err().unwrap();
let err = spawn_with("does-not-exist", "-d", "/x", "~", Arc::new(Silent), &Tail::default()).err().unwrap();
assert!(err.message.contains("not a valid"), "{}", err.message);
}
}
+7
View File
@@ -348,7 +348,9 @@ lsp_change_signature trusted project_host bin
lsp_code_action_query trusted project_host bindings async
lsp_code_actions trusted project_host bindings async
lsp_code_lens trusted project_host bindings async
lsp_color_presentations trusted project_host bindings async
lsp_completion trusted project_host bindings async
lsp_document_colors trusted project_host bindings async
lsp_document_highlights trusted project_host bindings async
lsp_document_links trusted project_host bindings async
lsp_exception_class_at trusted project_host bindings async
@@ -540,6 +542,7 @@ remote_download_into trusted project_host bin
remote_download_local trusted desktop bindings async
remote_forward_port trusted desktop bindings async
remote_forwarded_ports trusted desktop bindings sync
remote_idle_timeout_minutes always project_host bindings async
remote_import_local trusted desktop bindings async
remote_invoke always desktop bindings async
remote_list always project_host bindings async
@@ -547,6 +550,7 @@ remote_mkdir trusted project_host bin
remote_of always project_host bindings sync
remote_open always project_host bindings async
remote_rename trusted project_host bindings async
remote_stop_backend always desktop bindings async
remote_stop_forwarding trusted desktop bindings async
remote_trust_set always desktop bindings sync
remote_trust_status always desktop bindings sync
@@ -557,6 +561,7 @@ replace_preview trusted project_host bin
run_application_build trusted project_host bindings async
run_application_publish trusted project_host bindings async
run_apply_settings trusted project_host bindings async
run_attach always project_host bindings async
run_close_stdin trusted project_host bindings sync
run_configs trusted project_host bindings async
run_dotnet_resolve trusted project_host bindings async
@@ -647,10 +652,12 @@ syntax_structural_ranges always project_host bin
syntax_support always project_host bindings sync
system_font_families always desktop bindings async
system_probe_hotkeys trusted desktop bindings sync
term_attach always project_host bindings async
term_available_shells always project_host bindings sync
term_default_shell always project_host bindings sync
term_is_busy always project_host bindings async
term_kill always project_host bindings sync
term_list always project_host bindings async
term_resize always project_host bindings sync
term_spawn always project_host bindings async
term_store_image always project_host bindings async
+117 -8
View File
@@ -859,7 +859,11 @@ export const commands = {
lspCodeActionQuery: (request: RequestId, doc: DocId, range: Range, only: string[]) => typedError<CodeActionQuery, IdeError>(__TAURI_INVOKE("lsp_code_action_query", { request, doc, range, only })),
lspCodeActions: (doc: DocId, range: Range, only: string[]) => typedError<CodeAction[], IdeError>(__TAURI_INVOKE("lsp_code_actions", { doc, range, only })),
lspCodeLens: (doc: DocId) => typedError<CodeLens[], IdeError>(__TAURI_INVOKE("lsp_code_lens", { doc })),
/** How the server that reported `color` writes it with new components. */
lspColorPresentations: (doc: DocId, color: DocumentColor) => typedError<ColorPresentation[], IdeError>(__TAURI_INVOKE("lsp_color_presentations", { doc, color })),
lspCompletion: (request: RequestId, doc: DocId, pos: Pos, trigger: string | null) => typedError<CompletionList, IdeError>(__TAURI_INVOKE("lsp_completion", { request, doc, pos, trigger })),
/** Colors in a document from its language servers (Tailwind classes, CSS values…). */
lspDocumentColors: (doc: DocId) => typedError<DocumentColor[], IdeError>(__TAURI_INVOKE("lsp_document_colors", { doc })),
lspDocumentHighlights: (doc: DocId, pos: Pos) => typedError<Highlight[], IdeError>(__TAURI_INVOKE("lsp_document_highlights", { doc, pos })),
/** Links in a document (`href`s, Markdown links, `#include`s…) from its language servers. */
lspDocumentLinks: (doc: DocId) => typedError<DocumentLink[], IdeError>(__TAURI_INVOKE("lsp_document_links", { doc })),
@@ -1452,6 +1456,8 @@ export const commands = {
/** `linux`, `macos` or `windows`: the OS the project's commands run on. */
os: string,
commands: string[],
idlePolicy?: RemoteIdlePolicy | null,
takenOver?: boolean,
} | null>("remote_current"),
remoteDelete: (connection: FsConnection, path: string) => typedError<null, IdeError>(__TAURI_INVOKE("remote_delete", { connection, path })),
remoteDisconnect: () => __TAURI_INVOKE<void>("remote_disconnect"),
@@ -1469,6 +1475,11 @@ export const commands = {
remoteForwardPort: (remotePort: number) => typedError<ForwardedPort, IdeError>(__TAURI_INVOKE("remote_forward_port", { remotePort })),
/** The remote ports this window forwards to this machine. */
remoteForwardedPorts: () => __TAURI_INVOKE<ForwardedPort[]>("remote_forwarded_ports"),
/**
* 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.
*/
remoteIdleTimeoutMinutes: () => typedError<number, IdeError>(__TAURI_INVOKE("remote_idle_timeout_minutes")),
/** A client OS file belongs to this machine even when its destination is remote. */
remoteImportLocal: (from: string, to: string, request: RequestId) => typedError<string[], IdeError>(__TAURI_INVOKE("remote_import_local", { from, to, request })),
/**
@@ -1482,6 +1493,11 @@ export const commands = {
remoteOf: (path: IpcPath) => __TAURI_INVOKE<[FsConnection, string] | null>("remote_of", { path }),
remoteOpen: (connection: FsConnection, path: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("remote_open", { connection, path })),
remoteRename: (connection: FsConnection, from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("remote_rename", { connection, from, to })),
/**
* Stops the persistent `openidea-server` daemon for this window's remote project,
* terminating its terminals, runs, language servers and agent sessions, then disconnects.
*/
remoteStopBackend: () => typedError<null, IdeError>(__TAURI_INVOKE("remote_stop_backend")),
/** Stops forwarding `remote_port` of `host` (`None`: the remote host itself). */
remoteStopForwarding: (remotePort: number, host: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("remote_stop_forwarding", { remotePort, host })),
/** Records the user's trust decision for the window's remote project on this machine. */
@@ -1510,6 +1526,11 @@ export const commands = {
runApplicationPublish: (config: RunConfig_Deserialize, classPaths: string[], mainClass: string) => typedError<null, IdeError>(__TAURI_INVOKE("run_application_publish", { config, classPaths, mainClass })),
/** Kept temporary configurations with the current settings applied. */
runApplySettings: (configs: RunConfig_Deserialize[]) => typedError<RunConfig_Serialize[], IdeError>(__TAURI_INVOKE("run_apply_settings", { configs })),
/**
* Reattaches to a running process `id` on this host, returning its buffered output
* and configuration while streaming subsequent chunks to `on_output`.
*/
runAttach: (id: RunId, onOutput: Channel<OutputChunk>) => typedError<RunAttach_Serialize, IdeError>(__TAURI_INVOKE("run_attach", { id, onOutput })),
runCloseStdin: (id: RunId) => typedError<null, IdeError>(__TAURI_INVOKE("run_close_stdin", { id })),
/** Detected configs followed by user-defined ones (user ids win on conflict). */
runConfigs: () => typedError<RunConfig_Serialize[], IdeError>(__TAURI_INVOKE("run_configs")),
@@ -1849,6 +1870,11 @@ export const commands = {
* already registered to another app. Empty everywhere but Windows.
*/
systemProbeHotkeys: (combos: string[]) => typedError<string[], IdeError>(__TAURI_INVOKE("system_probe_hotkeys", { combos })),
/**
* Reattaches to an existing terminal session `id`, returning its buffered output
* and streaming subsequent chunks to `on_output`.
*/
termAttach: (id: TerminalId, cols: number, rows: number, onOutput: Channel<string>) => typedError<TerminalAttach, IdeError>(__TAURI_INVOKE("term_attach", { id, cols, rows, onOutput })),
/** Installed shells for the Terminal's "New Predefined Session" menu. */
termAvailableShells: () => __TAURI_INVOKE<string[]>("term_available_shells"),
/** Shell used when Settings › Terminal › Shell path is empty. */
@@ -1859,6 +1885,8 @@ export const commands = {
*/
termIsBusy: (id: TerminalId) => typedError<boolean, IdeError>(__TAURI_INVOKE("term_is_busy", { id })),
termKill: (id: TerminalId) => typedError<null, IdeError>(__TAURI_INVOKE("term_kill", { id })),
/** Live terminal sessions of this window, for reattaching after a reconnect. */
termList: () => __TAURI_INVOKE<TerminalSessionInfo[]>("term_list"),
termResize: (id: TerminalId, cols: number, rows: number) => typedError<null, IdeError>(__TAURI_INVOKE("term_resize", { id, cols, rows })),
/**
* Async to stay off the main thread: forking the IDE (its whole address space)
@@ -4231,6 +4259,15 @@ export type ColorInfo = {
alpha: number | null,
};
/**
* One way to write a picked color (`textDocument/colorPresentation`): `edits` replace the
* color's range (with `label` unless the server gave its own edit), then any extra edits.
*/
export type ColorPresentation = {
label: string,
edits: TextEdit[],
};
export type Command = {
title: string,
command: string,
@@ -6019,6 +6056,8 @@ export type DockerConnection = {
id: string,
name: string,
endpoint: DockerEndpoint,
/** Whether the user explicitly disconnected this connection in Services. */
disconnected?: boolean,
};
export type DockerContainer = {
@@ -6183,6 +6222,16 @@ export type DocumentChanged = {
changes: DocumentTextChange[],
};
/** A color a server found in a document (`textDocument/documentColor`); components are 0–1. */
export type DocumentColor = {
range: Range,
red: number | null,
green: number | null,
blue: number | null,
alpha: number | null,
server: ServerId,
};
/** Encoding and BOM currently applied to an open document. */
export type DocumentEncoding = {
encoding: string,
@@ -7942,11 +7991,8 @@ export type IdeEvent =
{ type: "mcpBackgroundProjectsChanged" } |
/** A window entered or left full screen, itself or as a member of a full-screen window group. */
{ type: "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.
*/
{ type: "remoteConnectionLost"; host: string } | { type: "projectTrustChanged"; root: IpcPath; trusted: boolean } |
/** This remote window's connection ended or another window took over the session. */
{ type: "remoteConnectionLost"; host: string; takenOver?: boolean } | { type: "projectTrustChanged"; root: IpcPath; trusted: boolean } |
/**
* The project's direnv environment (`.envrc`) could not be loaded, or a file it is read
* from changed and it can be reloaded.
@@ -11694,6 +11740,12 @@ export type Remote = {
resolvedUrl?: string | null,
};
/** Tools › Remote Development. This is a user setting on the remote host. */
export type RemoteDevelopmentSettings = {
/** Zero disables idle shutdown. Positive values from older configurations keep their meaning. */
idleTimeoutMinutes?: number,
};
/** Manage Remotes edits. */
export type RemoteEdit = { op: "add"; name: string; url: string } | { op: "remove"; name: string } |
/** Renames `name` to `new_name` (when different) and sets its URL. */
@@ -11713,6 +11765,11 @@ export type RemoteEntry = {
permissions: string,
};
/** Advertised only by a persistent backend with an editable idle timeout. */
export type RemoteIdlePolicy = {
overrideSeconds: number | null,
};
/** A project folder on an SSH host, in a WSL distribution or in a dev container. */
export type RemoteLaunch = {
target: RemoteTarget,
@@ -11765,6 +11822,7 @@ export type RemoteProject_Deserialize = {
host: string,
serverVersion: string,
os: string,
idlePolicy?: RemoteIdlePolicy | null,
/** Commands routed to the server (the rest run locally). */
commands: string[],
project: ProjectInfo_Deserialize,
@@ -11777,18 +11835,34 @@ export type RemoteProject_Serialize = {
host: string,
serverVersion: string,
os: string,
idlePolicy?: RemoteIdlePolicy | null,
/** Commands routed to the server (the rest run locally). */
commands: string[],
project: ProjectInfo_Serialize,
};
export type RemoteSession = {
export type RemoteSession = RemoteSession_Serialize | RemoteSession_Deserialize;
export type RemoteSession_Deserialize = {
target: RemoteTarget,
root: string,
host: string,
/** `linux`, `macos` or `windows`: the OS the project's commands run on. */
os: string,
commands: string[],
idlePolicy?: RemoteIdlePolicy | null,
takenOver?: boolean,
};
export type RemoteSession_Serialize = {
target: RemoteTarget,
root: string,
host: string,
/** `linux`, `macos` or `windows`: the OS the project's commands run on. */
os: string,
commands: string[],
idlePolicy?: RemoteIdlePolicy | null,
takenOver?: boolean,
};
export type RemoteSkillBrowseResult = {
@@ -11967,6 +12041,23 @@ export type RubySettings = {
interpreter?: string,
};
/** Snapshot and live output binding returned when reattaching to a running process. */
export type RunAttach = RunAttach_Serialize | RunAttach_Deserialize;
/** Snapshot and live output binding returned when reattaching to a running process. */
export type RunAttach_Deserialize = {
info: RunInfo,
config: RunConfig_Deserialize,
buffered: OutputChunk[],
};
/** Snapshot and live output binding returned when reattaching to a running process. */
export type RunAttach_Serialize = {
info: RunInfo,
config: RunConfig_Serialize,
buffered: OutputChunk[],
};
export type RunConfig = RunConfig_Serialize | RunConfig_Deserialize;
export type RunConfig_Deserialize = {
@@ -12476,7 +12567,7 @@ export type SettingsWindowInit = SettingsWindowInit_Serialize | SettingsWindowIn
export type SettingsWindowInit_Deserialize = {
launch: Launch_Deserialize | null,
remote: RemoteSession | null,
remote: RemoteSession_Deserialize | null,
project: ProjectInfo_Deserialize | null,
globalSettings: Settings_Deserialize,
updates: boolean,
@@ -12484,7 +12575,7 @@ export type SettingsWindowInit_Deserialize = {
export type SettingsWindowInit_Serialize = {
launch: Launch_Serialize | null,
remote: RemoteSession | null,
remote: RemoteSession_Serialize | null,
project: ProjectInfo_Serialize | null,
globalSettings: Settings_Serialize,
updates: boolean,
@@ -12545,6 +12636,7 @@ export type Settings_Deserialize = {
spelling?: SpellingSettings,
/** Tools › SSH Configurations. */
ssh?: SshSettings,
remoteDevelopment?: RemoteDevelopmentSettings,
/** Build, Execution, Deployment › Deployment. */
deployment?: DeploymentSettings,
/** Build, Execution, Deployment › Run Targets. */
@@ -12621,6 +12713,7 @@ export type Settings_Serialize = {
spelling: SpellingSettings,
/** Tools › SSH Configurations. */
ssh: SshSettings,
remoteDevelopment: RemoteDevelopmentSettings,
/** Build, Execution, Deployment › Deployment. */
deployment: DeploymentSettings,
/** Build, Execution, Deployment › Run Targets. */
@@ -13286,6 +13379,12 @@ export type TableSort = {
/** A long-running background task shown in the status bar. */
export type TaskId = number;
/** Snapshot and live binding returned when reattaching to an existing session. */
export type TerminalAttach = {
session: TerminalSessionInfo,
buffered: string,
};
/** TerminalExited data exchanged with the IDE. */
export type TerminalExited = {
id: string,
@@ -13315,6 +13414,16 @@ export type TerminalOptions = {
shellIntegration?: boolean,
};
/** Live terminal session state for reattaching across window reconnects. */
export type TerminalSessionInfo = {
id: TerminalId,
title: string,
pid: number | null,
cwd: string,
appTitle: string | null,
commandRunning: boolean,
};
/** Tools › Terminal. */
export type TerminalSettings = {
/** Empty = project root; relative paths resolve against it. */
+20 -2
View File
@@ -4,8 +4,8 @@ import { completedSyntaxTree } from "@/test/syntax";
import { classHighlighter, highlightTree } from "@lezer/highlight";
import { findLanguageDescription, loadSupport } from "./languages";
async function tokens(source: string) {
const desc = findLanguageDescription("Helm Template", "templates/applications.yaml")!;
async function tokens(source: string, mode = "Helm Template") {
const desc = findLanguageDescription(mode, "")!;
const support = await loadSupport(desc);
const state = EditorState.create({ doc: source, extensions: [support!] });
const result: { text: string; style: string }[] = [];
@@ -52,3 +52,21 @@ describe("Helm Template mode", () => {
expect(out).toContainEqual(expect.objectContaining({ text: "replicas", style: "tok-propertyName" }));
});
});
describe("Go Template mode", () => {
it.each(["common.gotmpl", "message.tmpl", "docker-stack.yaml.go.tmpl"])("loads for %s", (path) => {
expect(findLanguageDescription(null, path)?.name).toBe("Go Template");
});
it("highlights actions and keeps host text plain", async () => {
const out = await tokens(
'services:\n web: {{- if .Image }}{{ printf "nginx:%s" .Image }}{{ end -}}\n{{/* note */}}',
"Go Template",
);
expect(out).toContainEqual({ text: "if", style: "tok-keyword" });
expect(out).toContainEqual({ text: ".Image", style: "tok-propertyName" });
expect(out).toContainEqual({ text: '"nginx:%s"', style: "tok-string" });
expect(out.some(({ text }) => /services|web/.test(text))).toBe(false);
expect(out).toContainEqual({ text: "{{/* note */}}", style: "tok-comment" });
});
});
+53 -44
View File
@@ -1,16 +1,14 @@
// Helm Template editor mode: YAML outside `{{ … }}`, Go `text/template` + Sprig/Helm
// actions and `{{/* … */}}` comments inside. Each region runs on a sub-stream bounded
// at the next delimiter so `{{ … }}` never breaks YAML key/value tokenization.
// Go text/template actions over plain text or Helm YAML. The YAML parser reads up to the
// next template delimiter so the action never breaks YAML key/value tokenization.
import { LanguageSupport, StreamLanguage, StringStream, type StreamParser } from "@codemirror/language";
import { tags } from "@lezer/highlight";
type HelmState<Y> = {
type TemplateState<Y> = {
yaml: Y;
inAction: boolean;
inComment: boolean;
inRawString: boolean;
quote: '"' | "'" | null;
indentUnit: number;
};
const OPEN = /\{\{-?/;
@@ -21,56 +19,60 @@ const COMMENT_CLOSE = /\*\/\s*-?\}\}/;
const KEYWORDS = new Set(["if", "else", "end", "range", "with", "define", "template", "block", "break", "continue"]);
const ATOMS = new Set(["true", "false", "nil"]);
const FUNCTIONS = new Set([
const BUILTINS = new Set([
"and",
"call",
"eq",
"ge",
"gt",
"html",
"index",
"js",
"le",
"len",
"lt",
"ne",
"not",
"or",
"print",
"printf",
"println",
"slice",
"urlquery",
]);
const HELM_FUNCTIONS = new Set([
"b64dec",
"b64enc",
"call",
"coalesce",
"contains",
"default",
"dict",
"empty",
"eq",
"fail",
"first",
"fromJson",
"fromYaml",
"ge",
"get",
"gt",
"has",
"hasKey",
"hasPrefix",
"hasSuffix",
"html",
"include",
"indent",
"index",
"int",
"int64",
"join",
"js",
"keys",
"kindIs",
"kindOf",
"last",
"le",
"len",
"list",
"lookup",
"lower",
"lt",
"merge",
"mustMerge",
"ne",
"nindent",
"not",
"or",
"pluck",
"print",
"printf",
"println",
"quote",
"regexMatch",
"replace",
@@ -78,7 +80,6 @@ const FUNCTIONS = new Set([
"semverCompare",
"set",
"sha256sum",
"slice",
"snakecase",
"squote",
"ternary",
@@ -99,11 +100,10 @@ const FUNCTIONS = new Set([
"typeOf",
"unset",
"upper",
"urlquery",
"values",
]);
function tokenAction<Y>(stream: StringStream, state: HelmState<Y>): string | null {
function tokenAction<Y>(stream: StringStream, state: TemplateState<Y>, helm: boolean): string | null {
if (state.inRawString) {
const end = stream.string.indexOf("`", stream.pos);
if (end < 0) {
@@ -122,14 +122,14 @@ function tokenAction<Y>(stream: StringStream, state: HelmState<Y>): string | nul
if (close?.index === 0) {
stream.pos += close[0].length;
state.inAction = false;
return "helmDelimiter";
return "templateDelimiter";
}
const ch = stream.peek();
if (ch === "`") {
stream.next();
state.inRawString = true;
return tokenAction(stream, state);
return tokenAction(stream, state, helm);
}
if (ch === '"') {
stream.match(/^"(?:[^"\\]|\\.)*"?/);
@@ -158,7 +158,7 @@ function tokenAction<Y>(stream: StringStream, state: HelmState<Y>): string | nul
const word = stream.current();
if (KEYWORDS.has(word)) return "keyword";
if (ATOMS.has(word)) return "bool";
if (FUNCTIONS.has(word)) return "helmFunc";
if (BUILTINS.has(word) || (helm && HELM_FUNCTIONS.has(word))) return "templateFunc";
return "variableName";
}
@@ -166,7 +166,8 @@ function tokenAction<Y>(stream: StringStream, state: HelmState<Y>): string | nul
return null;
}
export function helmParser<Y>(yaml: StreamParser<Y>): StreamParser<HelmState<Y>> {
function templateParser<Y>(yaml?: StreamParser<Y>): StreamParser<TemplateState<Y | undefined>> {
const helm = yaml !== undefined;
const copy = (base: StreamParser<Y>, state: Y): Y =>
base.copyState
? base.copyState(state)
@@ -174,7 +175,11 @@ export function helmParser<Y>(yaml: StreamParser<Y>): StreamParser<HelmState<Y>>
Object.entries(state as object).map(([k, v]) => [k, Array.isArray(v) ? v.slice() : v]),
) as Y);
const withinYaml = (stream: StringStream, end: number, state: HelmState<Y>): string | null => {
const tokenHost = (stream: StringStream, end: number, state: TemplateState<Y | undefined>): string | null => {
if (!yaml || state.yaml === undefined) {
stream.pos = end;
return null;
}
if (state.quote) {
const q = state.quote;
while (stream.pos < end) {
@@ -220,30 +225,30 @@ export function helmParser<Y>(yaml: StreamParser<Y>): StreamParser<HelmState<Y>>
return style;
};
const block = { open: "{{/*", close: "*/}}" };
return {
name: "helm-template",
name: helm ? "helm-template" : "gotmpl",
languageData: {
...yaml.languageData,
commentTokens: { line: "#", block: { open: "{{/*", close: "*/}}" } },
...yaml?.languageData,
commentTokens: helm ? { line: "#", block } : { block },
},
tokenTable: {
...yaml.tokenTable,
...yaml?.tokenTable,
atom: tags.propertyName,
helmDelimiter: tags.special(tags.brace),
helmFunc: tags.function(tags.variableName),
templateDelimiter: tags.special(tags.brace),
templateFunc: tags.function(tags.variableName),
},
startState: (indentUnit) => ({
yaml: yaml.startState!(indentUnit),
yaml: yaml?.startState?.(indentUnit),
inAction: false,
inComment: false,
inRawString: false,
quote: null,
indentUnit,
}),
copyState: (s) => ({ ...s, yaml: copy(yaml, s.yaml) }),
copyState: (s) => ({ ...s, yaml: yaml && s.yaml !== undefined ? copy(yaml, s.yaml) : s.yaml }),
blankLine: (s, unit) => {
s.quote = null;
yaml.blankLine?.(s.yaml, unit);
if (yaml && s.yaml !== undefined) yaml.blankLine?.(s.yaml, unit);
},
token(stream, state) {
if (stream.sol()) state.quote = null;
@@ -261,7 +266,7 @@ export function helmParser<Y>(yaml: StreamParser<Y>): StreamParser<HelmState<Y>>
}
if (state.inAction) {
return tokenAction(stream, state);
return tokenAction(stream, state, helm);
}
const rest = stream.string.slice(stream.pos);
@@ -281,16 +286,20 @@ export function helmParser<Y>(yaml: StreamParser<Y>): StreamParser<HelmState<Y>>
}
stream.pos += open[0].length;
state.inAction = true;
return "helmDelimiter";
return "templateDelimiter";
}
const end = open ? stream.pos + open.index : stream.string.length;
return withinYaml(stream, end, state);
return tokenHost(stream, end, state);
},
};
}
export async function helmTemplate(): Promise<LanguageSupport> {
const { yaml } = await import("@codemirror/legacy-modes/mode/yaml");
return new LanguageSupport(StreamLanguage.define(helmParser(yaml)));
return new LanguageSupport(StreamLanguage.define(templateParser(yaml)));
}
export function goTemplate(): LanguageSupport {
return new LanguageSupport(StreamLanguage.define(templateParser()));
}
+154
View File
@@ -0,0 +1,154 @@
import { beforeAll, describe, expect, it } from "vitest";
import type { LanguageSupport } from "@codemirror/language";
import { highlightTree, tags as t, type Tag } from "@lezer/highlight";
import { findLanguageDescription, loadSupport } from "./languages";
import { openideaHighlightStyle } from "./highlight";
let java: LanguageSupport;
beforeAll(async () => {
java = (await loadSupport(findLanguageDescription("Java", "")!))!;
});
function tokens(doc: string): { text: string; cls: string }[] {
const out: { text: string; cls: string }[] = [];
highlightTree(java.language.parser.parse(doc), openideaHighlightStyle, (from, to, cls) => {
out.push({ text: doc.slice(from, to), cls });
});
return out;
}
const cls = (tag: Tag) => openideaHighlightStyle.style([tag])!;
function expectTokens(doc: string, expected: readonly (readonly [string, Tag])[]) {
const got = tokens(doc);
for (const [text, tag] of expected) expect(got, text).toContainEqual({ text, cls: cls(tag) });
}
/** The literal holding `text` is one string token: nothing is embedded. */
function expectPlainString(doc: string, text: string) {
expect(
tokens(doc).some((tok) => tok.cls === cls(t.string) && tok.text.includes(text)),
text,
).toBe(true);
}
const JPA = "import org.springframework.data.jpa.repository.Query;\n";
const VALUE = "import org.springframework.beans.factory.annotation.Value;\n";
describe("Java annotation string languages", () => {
it("highlights JPQL in Spring Data JPA @Query, also concatenated and as countQuery", () => {
const doc = `${JPA}interface Repo {
@Query(value = "select u from User u " + "where u.email = :email", countQuery = "select count(u) from User u")
User find(String email);
}`;
expectTokens(doc, [
["select", t.keyword],
["from", t.keyword],
["where", t.keyword],
["count", t.keyword],
// The quotes stay the Java string's.
['"', t.string],
]);
expect(tokens(doc).filter((tok) => tok.cls === cls(t.string) && tok.text.includes("select"))).toEqual([]);
// JPQL names entities: `User` is not SQL's `USER` keyword.
expect(tokens(doc).filter((tok) => tok.text === "User" && tok.cls === cls(t.keyword))).toEqual([]);
});
it("highlights native SQL in a text block", () => {
const doc = `${JPA}interface Repo {
@Query(nativeQuery = true, value = """
SELECT * FROM User WHERE id = 1
""")
User find();
}`;
expectTokens(doc, [
["SELECT", t.keyword],
["WHERE", t.keyword],
["1", t.number],
// Native SQL keeps SQL's keywords.
["User", t.keyword],
]);
});
it("resolves the annotation through a package import or its qualified name", () => {
expectTokens('import org.springframework.data.jpa.repository.*;\ninterface R { @Query("select 1") void f(); }', [
["select", t.keyword],
]);
expectTokens('interface R { @org.springframework.data.jpa.repository.Query("select 1") void f(); }', [
["select", t.keyword],
]);
});
it("leaves other annotations named Query as plain strings", () => {
expectPlainString('import com.example.Query;\ninterface R { @Query("select u from User u") void f(); }', "select");
expectPlainString('interface R { @Query("select u from User u") void f(); }', "select");
expectPlainString(
'import org.springframework.data.mongodb.repository.Query;\ninterface R { @Query("{ name: ?0 }") void f(); }',
"name",
);
expectPlainString(
'import org.springframework.data.mongodb.repository.*;\ninterface R { @Query("{ name: ?0 }") void f(); }',
"name",
);
});
it("keeps escape sequences out of the embedded text", () => {
const doc = `${JPA}interface R { @Query("select u from User u where u.name = \\"x\\"") void f(); }`;
const got = tokens(doc);
// The escapes keep the Java string's colour; the escape colouring of the semantic layer marks them.
expect(got).toContainEqual({ text: '\\"', cls: cls(t.string) });
expect(got).toContainEqual({ text: "where", cls: cls(t.keyword) });
// The escaped quotes don't open an SQL quoted identifier: `x` is plain text.
expect(got.filter((tok) => tok.text.includes("x"))).toEqual([]);
});
it("highlights placeholders and SpEL in @Value", () => {
const doc = `${VALUE}class C {
@Value("\${app.timeout:30}") int timeout;
@Value("#{systemProperties['user.region'] ?: 'eu'}") String region;
@Value("prefix-#{@config.name()}") String name;
}`;
expectTokens(doc, [
["${", t.meta],
["app.timeout", t.propertyName],
["30", t.string],
["#{", t.meta],
["}", t.meta],
["systemProperties", t.variableName],
["'user.region'", t.string],
["?:", t.operator],
["prefix-", t.string],
["#{@config", t.meta],
["name", t.function(t.propertyName)],
]);
});
it("highlights the whole value as SpEL in security and cache annotations", () => {
const doc = `import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.cache.annotation.Cacheable;
class C {
@PreAuthorize("hasRole('ADMIN') and #id == authentication.principal.id")
@Cacheable(cacheNames = "users", key = "#id", unless = "#result == null")
User find(long id) { return null; }
}`;
expectTokens(doc, [
["hasRole", t.function(t.variableName)],
["'ADMIN'", t.string],
["and", t.keyword],
["#id", t.standard(t.variableName)],
["principal", t.propertyName],
["#result", t.standard(t.variableName)],
["null", t.null],
]);
// Not a SpEL attribute.
expectPlainString(doc, "users");
});
it("closes #{…} after an inline list", () => {
expectTokens(`${VALUE}class C { @Value("#{ {1, 2}.size() } items") int n; }`, [
["size", t.function(t.propertyName)],
[" items", t.string],
]);
});
});
+261
View File
@@ -0,0 +1,261 @@
/**
* Embedded languages in Java annotation strings, as IntelliJ IDEA Ultimate's Spring support
* injects them: JPQL (SQL with `nativeQuery = true`) in Spring Data JPA's `@Query`, SpEL in `@PreAuthorize`, `@Cacheable(key = …)`
* and the like, and SpEL `#{…}` with property placeholders `${…}` in `@Value` and
* `@ConditionalOnExpression`.
*
* An annotation counts only by its resolved name: written fully qualified, or by a simple name the file
* imports (the class itself or its package with `.*`), so a project's own `@Query` keeps a plain string.
* Escape sequences stay outside the embedded text and keep the Java string's colours.
*/
import { LanguageSupport, LRLanguage, StreamLanguage, type StringStream } from "@codemirror/language";
import { java } from "@codemirror/lang-java";
import {
parseMixed,
type Input,
type NestedParse,
type Parser,
type SyntaxNode,
type SyntaxNodeRef,
} from "@lezer/common";
import { SQLDialect, StandardSQL } from "@codemirror/lang-sql";
type Embedded = "SQL" | "SpEL" | "SpEL template";
const PREPOST = "org.springframework.security.access.prepost.";
const CACHE = "org.springframework.cache.annotation.";
const CACHE_ATTRIBUTES = {
key: "SpEL",
condition: "SpEL",
unless: "SpEL",
} as const;
/** Annotation class → attribute → embedded language. */
const INJECTIONS: Record<string, Record<string, Embedded>> = {
"org.springframework.data.jpa.repository.Query": {
value: "SQL",
countQuery: "SQL",
},
"org.springframework.beans.factory.annotation.Value": {
value: "SpEL template",
},
"org.springframework.boot.autoconfigure.condition.ConditionalOnExpression": {
value: "SpEL template",
},
[`${PREPOST}PreAuthorize`]: { value: "SpEL" },
[`${PREPOST}PostAuthorize`]: { value: "SpEL" },
[`${PREPOST}PreFilter`]: { value: "SpEL" },
[`${PREPOST}PostFilter`]: { value: "SpEL" },
[`${CACHE}Cacheable`]: CACHE_ATTRIBUTES,
[`${CACHE}CachePut`]: CACHE_ATTRIBUTES,
[`${CACHE}CacheEvict`]: CACHE_ATTRIBUTES,
};
const SIMPLE_NAMES = new Set(Object.keys(INJECTIONS).map((name) => name.slice(name.lastIndexOf(".") + 1)));
const text = (node: SyntaxNode, input: Input) => input.read(node.from, node.to).replace(/\s+/g, "");
/** The annotation's class: `name` as written when qualified, else the import that brings it in. */
function annotationClass(annotation: SyntaxNode, input: Input): string | null {
const nameNode = annotation.getChild("Identifier") ?? annotation.getChild("ScopedIdentifier");
if (!nameNode) return null;
const name = text(nameNode, input);
if (name.includes(".")) return name;
if (!SIMPLE_NAMES.has(name)) return null;
let program = annotation;
while (program.parent) program = program.parent;
for (const decl of program.getChildren("ImportDeclaration")) {
if (decl.getChild("static")) continue;
const path = decl.getChild("ScopedIdentifier");
if (!path) continue;
const imported = text(path, input);
if (!decl.getChild("Asterisk")) {
if (imported.endsWith(`.${name}`)) return imported;
} else if (INJECTIONS[`${imported}.${name}`]) return `${imported}.${name}`;
}
return null;
}
/** The string literals of an attribute value: one literal, or several joined with `+`. */
function literals(value: SyntaxNode, out: SyntaxNode[] = []): SyntaxNode[] {
if (value.name === "StringLiteral" || value.name === "TextBlock") out.push(value);
else if (value.name === "BinaryExpression" || value.name === "ParenthesizedExpression")
for (let child = value.firstChild; child; child = child.nextSibling) literals(child, out);
return out;
}
const ESCAPE = /\\(?:u+[0-9a-fA-F]{4}|[0-7]{1,3}|[\s\S])/g;
/** The literal's text between its quotes, without escape sequences. */
function contentRanges(literal: SyntaxNode, input: Input, out: { from: number; to: number }[]) {
const quote = literal.name === "TextBlock" ? 3 : 1;
const from = literal.from + quote;
const raw = input.read(literal.from, literal.to);
const closed = raw.length >= 2 * quote && raw.endsWith(quote === 3 ? '"""' : '"');
const to = closed ? literal.to - quote : literal.to;
let start = from;
// ponytail: an escape splits the embedded text, so `FROM\nUser` reads as `FROMUser`; rare in queries.
for (const m of input.read(from, to).matchAll(ESCAPE)) {
const at = from + m.index;
if (at > start) out.push({ from: start, to: at });
start = at + m[0].length;
}
if (to > start) out.push({ from: start, to });
}
const SPEL_KEYWORDS = /^(?:and|or|not|eq|ne|lt|gt|le|ge|div|mod|instanceof|matches|between|new|T)\b(?![\w$])/;
interface Frame {
kind: "#" | "$";
/** Inside a placeholder, past the `:` before its default value. */
fallback: boolean;
/** Open `{` of inline lists and maps inside a `#{…}`. */
braces: number;
}
interface SpelState {
/** Open `#{` / `${`. Outside them a template string is text and an expression-only string is SpEL. */
stack: Frame[];
/** The last token was `.` or `?.`: a property or method name follows. */
member: boolean;
}
function spelToken(stream: StringStream, state: SpelState, template: boolean): string | null {
if (stream.match(/^[#$]\{/)) {
state.stack.push({
kind: stream.current()[0] as "#" | "$",
fallback: false,
braces: 0,
});
return "meta";
}
const frame = state.stack[state.stack.length - 1];
if (frame && (frame.kind === "$" || !frame.braces) && stream.eat("}")) {
state.stack.pop();
return "meta";
}
if (template && !frame) {
if (!stream.match(/^[^#$]+/)) stream.next();
return "string";
}
if (frame?.kind === "$") {
if (frame.fallback) {
if (!stream.match(/^[^#$}]+/)) stream.next();
return "string";
}
if (stream.eat(":")) {
frame.fallback = true;
return "operator";
}
if (!stream.match(/^[^:#$}]+/)) stream.next();
return "propertyName";
}
if (stream.eatSpace()) return null;
const member = state.member;
state.member = false;
if (stream.eat("'")) {
while (!stream.eol()) if (stream.next() === "'" && !stream.eat("'")) break;
return "string";
}
if (stream.match(/^\d+(?:\.\d+)?(?:[eE][-+]?\d+)?[lLfFdD]?/)) return "number";
if (stream.match(/^#\w+/)) return "variableName.standard";
if (stream.match(/^[@&][\w$]+/)) return "meta";
if (!member && stream.match(/^(?:true|false)\b/)) return "bool";
if (!member && stream.match(/^null\b/)) return "null";
if (!member && stream.match(SPEL_KEYWORDS)) return "keyword";
if (stream.match(/^[A-Za-z_$][\w$]*/)) {
const call = stream.match(/^\s*\(/, false);
if (member) return call ? "propertyName.function" : "propertyName";
return call ? "variableName.function" : "variableName";
}
if (stream.match(/^\??\./)) {
state.member = true;
return "derefOperator";
}
if (stream.match(/^(?:\?:|\.\?|\.\^|\.\$|[!=<>]=?|&&|\|\||[-+*/%^?:])/)) return "operator";
if (frame && stream.match(/^[{}]/)) frame.braces += stream.current() === "{" ? 1 : -1;
else if (!stream.match(/^[()[\]{}]/)) {
if (stream.eat(",")) return "separator";
stream.next();
return null;
}
return "bracket";
}
function spel(template: boolean): Parser {
return StreamLanguage.define<SpelState>({
name: template ? "spel-template" : "spel",
startState: () => ({ stack: [], member: false }),
copyState: (s) => ({
stack: s.stack.map((f) => ({ ...f })),
member: s.member,
}),
token: (stream, state) => spelToken(stream, state, template),
}).parser;
}
/** JPQL / HQL: entity names such as `User` or `Order` are not keywords, unlike in SQL. */
const JPQL_KEYWORDS =
"select from where and or not as join left right inner outer full cross fetch on with distinct order by group " +
"having asc desc nulls first last in like escape between is null empty member of exists all any some case when " +
"then else end new update set delete insert into union intersect except true false count sum avg min max upper " +
"lower trim leading trailing both length locate abs sqrt mod size index key value entry treat type coalesce " +
"nullif concat substring cast extract function current_date current_time current_timestamp object limit offset";
let parsers: Record<Embedded | "JPQL", Parser> | null = null;
/** Whether `@Query(…)` has `nativeQuery = true`. */
function nativeQuery(args: SyntaxNode, input: Input): boolean {
return args
.getChildren("ElementValuePair")
.some((pair) => /^nativeQuery\s*=\s*true$/.test(input.read(pair.from, pair.to)));
}
/** The nested parse for an annotation attribute value (`ElementValuePair`) or a lone value. */
export function javaInjection() {
return (ref: SyntaxNodeRef, input: Input): NestedParse | null => {
// Called for every node on each parse: rule out the rest before materializing the node.
if (ref.name !== "ElementValuePair" && ref.name !== "AnnotationArgumentList") return null;
const node = ref.node;
let attribute: string;
let value: SyntaxNode | null;
let annotation: SyntaxNode | null;
if (node.name === "ElementValuePair") {
const name = node.getChild("Identifier");
attribute = name ? input.read(name.from, name.to) : "";
value = node.lastChild;
annotation = node.parent?.parent ?? null;
} else {
// `@Ann("…")`: the value attribute's shorthand.
attribute = "value";
value = node.firstChild?.nextSibling ?? null;
if (value?.name === "ElementValuePair") return null;
annotation = node.parent;
}
if (!value || annotation?.name !== "Annotation") return null;
const cls = annotationClass(annotation, input);
const language = cls ? INJECTIONS[cls]?.[attribute] : undefined;
if (!language) return null;
const overlay: { from: number; to: number }[] = [];
for (const literal of literals(value)) contentRanges(literal, input, overlay);
if (!overlay.length) return null;
parsers ??= {
SQL: StandardSQL.language.parser,
JPQL: SQLDialect.define({ keywords: JPQL_KEYWORDS, types: "", builtin: "" }).language.parser,
SpEL: spel(false),
"SpEL template": spel(true),
};
// ponytail: the mount is per attribute, so toggling `nativeQuery` restyles the query once it is edited.
const jpql = language === "SQL" && !nativeQuery(annotation.getChild("AnnotationArgumentList")!, input);
return { parser: parsers[jpql ? "JPQL" : language], overlay };
};
}
/** `java()` that also parses the embedded languages of Spring annotation strings. */
export function javaWithInjections(): LanguageSupport {
const base = java();
const language = (base.language as LRLanguage).configure({
wrap: parseMixed(javaInjection()),
});
return new LanguageSupport(language, base.support);
}
+23
View File
@@ -411,6 +411,29 @@ describe("language modes", () => {
}
});
it("leaves Java statement labels uncoloured, unlike JavaScript's", async () => {
const highlighter = tagHighlighter([
{ tag: t.labelName, class: "label" },
{ tag: t.variableName, class: "variable" },
]);
const labels = async (mode: string, path: string, doc: string) => {
const support = await loadSupport(findLanguageDescription(mode, path)!);
const found: string[] = [];
highlightTree(support!.language.parser.parse(doc), highlighter, (from, to, style) =>
found.push(`${doc.slice(from, to)}:${style}`),
);
return found.filter((s) => s.startsWith("outer"));
};
expect(await labels("Java", "/p/A.java", "class A { void f() { outer: for (;;) { break outer; } } }")).toEqual([
"outer:variable",
"outer:variable",
]);
expect(await labels("JavaScript", "/p/a.js", "outer: for (;;) { break outer; }")).toEqual([
"outer:label",
"outer:label",
]);
});
it("recognizes go.mod and go.work files by mode and filename", async () => {
for (const [mode, path] of [
["GoMod", "/project/go.mod"],
+14 -2
View File
@@ -224,6 +224,11 @@ const OWN_MODES = [
load: () => import("./templateLanguages").then((m) => m.javascriptWithTemplates(config, templateLanguage)),
}),
),
// JPQL / SQL in `@Query`, SpEL and property placeholders in Spring annotation strings.
LanguageDescription.of({
name: "Java",
load: () => import("./javaInjections").then((m) => m.javaWithInjections()),
}),
// Only for template literals: `.graphql` files keep the backend's tree-sitter highlighting.
LanguageDescription.of({
name: "GraphQL",
@@ -248,10 +253,15 @@ const OWN_MODES = [
extensions: ["djhtml"],
load: () => import("./django").then((m) => m.django()),
}),
LanguageDescription.of({
name: "Go Template",
alias: ["gotmpl", "tmpl"],
extensions: ["gotmpl", "tmpl"],
load: () => import("./helm").then((m) => m.goTemplate()),
}),
LanguageDescription.of({
name: "Helm Template",
alias: ["helm-template", "gotmpl"],
extensions: ["gotmpl"],
alias: ["helm-template"],
load: () => import("./helm").then((m) => m.helmTemplate()),
}),
LanguageDescription.of({
@@ -490,6 +500,8 @@ const CSS_TAGS: Parameters<typeof styleTags>[0] = {
export const JAVA_TAGS: Parameters<typeof styleTags>[0] = {
"MarkerAnnotation/Identifier Annotation/Identifier MarkerAnnotation Annotation": t.annotation,
this: t.keyword,
// IntelliJ has no Java label colour: `outer:` stays plain text, like `break outer`.
Label: t.variableName,
};
// @lezer/go leaves `default` uncoloured, unlike `case` and `switch`.
+14 -11
View File
@@ -55,7 +55,7 @@ import { hoverActionsAt } from "@/platform/hoverActions";
import { chooseSavePath } from "@/platform/choosePath";
import type { DialogFilter as SaveDialogFilter } from "@/platform/dialog";
import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs";
import { isRemoteWindow } from "@/platform/remote";
import { isRemoteWindow, projectLocation } from "@/platform/remote";
import { auxiliaryWindow } from "@/platform/auxWindow";
import { fileIconName, showContextMenu, type MenuItem } from "@/ui";
import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
@@ -391,7 +391,7 @@ export class EditorController implements SlotHost {
);
tabOptions.activateOnClose = editorPrefs().tabs.activateOnClose as typeof tabOptions.activateOnClose;
let prevSettings = useProject.getState().settings;
let prevRoot = useProject.getState().project?.root ?? null;
let prevScope = projectLocation(useProject.getState().project?.root);
let prevLight = useProject.getState().lightEdit;
this.disposers.push(
useProject.subscribe((s, previous) => {
@@ -401,10 +401,10 @@ export class EditorController implements SlotHost {
.activateOnClose as typeof tabOptions.activateOnClose;
this.manager.applySettings();
}
const root = s.project?.root ?? null;
const scope = projectLocation(s.project?.root);
// Entering or leaving LightEdit replaces the backend's documents too.
if (root !== prevRoot || s.lightEdit !== prevLight || (s.opening && s.project !== previous.project)) {
prevRoot = root;
if (scope !== prevScope || s.lightEdit !== prevLight || (s.opening && s.project !== previous.project)) {
prevScope = scope;
prevLight = s.lightEdit;
this.saveSession();
this.sessionRoot = null;
@@ -417,7 +417,7 @@ export class EditorController implements SlotHost {
const carriedUntitled: Tab[] = [];
let carriedActive: string | null = null;
const cs = useTabs.getState();
for (const pane of root || s.lightEdit ? Object.values(cs.panes) : []) {
for (const pane of scope || s.lightEdit ? Object.values(cs.panes) : []) {
for (const tab of pane.tabs) {
if (isUntitledUri(tab.input.path ?? "")) {
carriedUntitled.push(tab);
@@ -462,7 +462,7 @@ export class EditorController implements SlotHost {
.catch((e) => this.documentError(e))
.then(() => {
if (generation !== this.projectGeneration) return;
if (root) return this.restoreSession(root);
if (scope) return this.restoreSession(scope);
else if (s.lightEdit) return this.restoreSession(LIGHT_EDIT_SESSION);
});
} else if (previous.opening && !s.opening && this.closeCommitted) {
@@ -478,7 +478,7 @@ export class EditorController implements SlotHost {
this.upgradeWrappedImageTabs(wrappers);
}),
);
if (prevRoot) this.projectTransition = this.restoreSession(prevRoot);
if (prevScope) this.projectTransition = this.restoreSession(prevScope);
if (this.manager.backend.onFsChanged)
this.disposers.push(this.manager.backend.onFsChanged((e) => this.onFilesRemoved(e.removed)));
if (this.manager.backend.onDiskConflict)
@@ -671,7 +671,8 @@ export class EditorController implements SlotHost {
private openSessionKey(): string | null {
const s = useProject.getState();
if (s.project?.root) return s.project.root;
const scope = projectLocation(s.project?.root);
if (scope) return scope;
if (s.lightEdit) return LIGHT_EDIT_SESSION;
return null;
}
@@ -2170,8 +2171,10 @@ export class EditorController implements SlotHost {
return this.removeGuarded((s) => closeKey(s, key));
}
activeInput(): EditorInput | null {
return this.activeTabOf()?.input ?? null;
activeInput(options?: { previewOnly?: boolean }): EditorInput | null {
const tab = this.activeTabOf();
if (options?.previewOnly && (!tab?.preview || !editorPrefs().tabs.previewTab)) return null;
return tab?.input ?? null;
}
onActiveInputChange(fn: (input: EditorInput | null) => void): () => void {
+2 -1
View File
@@ -58,7 +58,7 @@ export function activate(): void | (() => void) {
onOpenTabsChange: (fn) => useTabs.subscribe(fn),
openTabs: () => ctrl.openTabs(),
tabInput: (paneId, tabId) => ctrl.tabInput(paneId, tabId),
activeInput: () => ctrl.activeInput(),
activeInput: (options) => ctrl.activeInput(options),
onActiveInputChange: (fn) => ctrl.onActiveInputChange(fn),
closePath: (path) => ctrl.closePath(path),
closeInput: (key) => ctrl.closeInput(key),
@@ -66,6 +66,7 @@ export function activate(): void | (() => void) {
cancelClose: () => ctrl.cancelClose(),
forgetSavedTabs: () => ctrl.forgetSavedTabs(),
keepSavedTabs: () => ctrl.keepSavedTabs(),
flushSession: () => ctrl.saveSession(),
documentHistory: (command) => ctrl.documentHistory(command),
chooseDeclaration: async (targets, name, anchor) =>
openPopup({
+7 -2
View File
@@ -8,6 +8,7 @@
* TabsState with new ids.
*/
import { ipcPath } from "@/platform/paths";
import { parseRemoteLocation } from "@/platform/remote";
import type { EditorInput } from "@/workbench/contributions";
import { initialTabsState, paneIds, type LayoutNode, type Pane, type Tab, type TabsState } from "./tabs";
@@ -198,8 +199,12 @@ export function restoreTabsState(session: EditorSession, fileKey: (path: string)
export function loadSession(root: string): EditorSession | null {
try {
// Sessions saved under the backslash spelling of a Windows root are picked up too.
const raw = localStorage.getItem(STORAGE_PREFIX + root) ?? legacyWindowsSession(root);
const legacyRemote = parseRemoteLocation(root)?.path;
// Sessions saved under the backslash spelling of a Windows root or bare remote path are picked up too.
const raw =
localStorage.getItem(STORAGE_PREFIX + root) ??
(legacyRemote ? localStorage.getItem(STORAGE_PREFIX + legacyRemote) : null) ??
legacyWindowsSession(root);
return raw ? parseSession(JSON.parse(raw)) : null;
} catch {
return null;
+1 -1
View File
@@ -248,7 +248,7 @@ function CrumbNav({
const current = i === segments.length - 1;
const icon = s.nav?.kind === "dir" && !s.nav.root && !current ? undefined : s.icon;
return (
<Fragment key={s.title}>
<Fragment key={`${i}:${s.title}`}>
{i > 0 && <Icon name="chevron-right" size={12} className={styles.statusSep} />}
<BarButton
className={styles.crumbButton}
+15
View File
@@ -292,3 +292,18 @@ it("shows the revision and the file's folders for a file at a Git revision", ()
view.unmount();
useProject.setState({ project: null, settings: null });
});
it("elides the middle of a deep path without a duplicate React key", () => {
useProject.setState({
project: { root: "/p", name: "app", settings: {}, trusted: true, isGit: false },
settings: { appearance: { navigationBar: "top" } } as unknown as Settings,
});
useEditorStatus.setState({ status: { ...caret(0, 0), path: "/p/src/main/java/com/example/orders/Rule.java" } });
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const view = render(<Breadcrumbs className="nav" />);
expect(screen.getByRole("navigation", { name: "Breadcrumbs" }).textContent).toBe("appsrc…exampleordersRule.java");
expect(error).not.toHaveBeenCalled();
error.mockRestore();
view.unmount();
useProject.setState({ project: null, settings: null });
});
+37
View File
@@ -91,6 +91,43 @@
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
}
/* Pin and Archive appear beside the age while the pointer is on the row. */
.rowActions {
display: none;
flex: none;
margin-left: auto;
margin-right: var(--space-2);
gap: var(--space-2);
}
.row:hover .rowActions,
.rowActions:focus-within {
display: flex;
}
.row:hover .age,
.row:has(.rowActions:focus-within) .age {
margin-left: 0;
}
.rowAction {
display: flex;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
padding: 0;
border: none;
background: none;
color: var(--fg-subtle);
--icon-color: currentColor;
cursor: pointer;
}
.rowAction:hover {
color: var(--fg-strong);
}
.rowAction:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: 1px;
border-radius: var(--radius-small);
}
.ready {
color: var(--success);
}
+43 -15
View File
@@ -338,7 +338,7 @@ describe("Agents bulk actions", () => {
select("one");
select("three", { shiftKey: true });
context("two");
fireEvent.click(screen.getByRole("menuitem", { name: "Archive (1)" }));
fireEvent.click(screen.getByRole("menuitem", { name: /^Archive \(1\)/ }));
await waitFor(() => expect(archiveTask).toHaveBeenCalledExactlyOnceWith("two"));
});
@@ -388,24 +388,39 @@ describe("Agents task menu", () => {
expect(menu).not.toContainEqual(expect.objectContaining({ action: "agents.undockTask" }));
// A click opens the task: the menu doesn't repeat it.
expect(menu).not.toContainEqual(expect.objectContaining({ action: "agents.openTask" }));
expect(menu[0]).toMatchObject({ action: "agents.renameTask" });
expect(menu).toContainEqual(expect.objectContaining({ action: "agents.renameTask" }));
});
it("offers Terminal for worktree or off-root tasks and hides it for local-checkout tasks at the project root", () => {
const localMenu = taskMenu([{ ...task("one", "ready", "local"), projectRoot: "/project", cwd: "/project" }]);
expect(localMenu).not.toContainEqual(expect.objectContaining({ action: "terminal.openAt" }));
const worktree = { ...task("two", "ready", "worktree"), cwd: "/worktrees/two" };
const worktreeMenu = taskMenu([worktree]);
expect(worktreeMenu).toContainEqual(
expect.objectContaining({ action: "terminal.openAt", label: "Terminal", arg: "/worktrees/two" }),
it("orders the single-task menu: pin, rename, unread; fork, group; archive, archive below, delete", () => {
const one = useAgents.getState().tasks.get("one")!;
const two = useAgents.getState().tasks.get("two")!;
const menu = taskMenu([{ ...one, capabilities: { fork: true } }], [two]);
const names = menu.map((item) =>
item.kind === "separator" ? "-" : "action" in item ? item.action : (item as { id?: string }).id,
);
expect(names).toEqual([
"agents.pinTasks",
"agents.renameTask",
"agents.markTasksUnread",
"-",
"agents.forkTask",
"move-to-group",
"-",
"agents.archiveTasks",
"archive-below",
"agents.deleteTasks",
]);
expect(menu).not.toContainEqual(expect.objectContaining({ action: "terminal.openAt" }));
expect(menu).not.toContainEqual(expect.objectContaining({ action: "agents.moveToNewWindow" }));
});
const subfolder = { ...task("three", "ready", "local"), projectRoot: "/project", cwd: "/project/packages/api" };
const subfolderMenu = taskMenu([subfolder]);
expect(subfolderMenu).toContainEqual(
expect.objectContaining({ action: "terminal.openAt", label: "Terminal", arg: "/project/packages/api" }),
);
it("marks tasks unread, then offers to mark them read", async () => {
await taskActions.find((action) => action.id === "agents.markTasksUnread")!.run({ ctx: {}, arg: ["one"] });
expect(useAgents.getState().unread.has("one")).toBe(true);
const menu = taskMenu([useAgents.getState().tasks.get("one")!]);
expect(menu).toContainEqual(expect.objectContaining({ action: "agents.markTasksRead", label: "Mark as Read" }));
await taskActions.find((action) => action.id === "agents.markTasksRead")!.run({ ctx: {}, arg: ["one"] });
expect(useAgents.getState().unread.has("one")).toBe(false);
});
});
@@ -466,6 +481,19 @@ describe("Agents pinned and grouped tasks", () => {
expect(treeRows().some((text) => text.includes("Pinned"))).toBe(false);
});
it("pins from the row's hover button without selecting or opening the task", async () => {
setup();
select("one");
vi.mocked(openTask).mockClear();
const pin = within(row("two") as HTMLElement).getByRole("button", { name: "Pin" });
fireEvent.mouseDown(pin, { button: 0 });
fireEvent.click(pin);
fireEvent.doubleClick(pin);
await waitFor(() => expect(useAgents.getState().organize.pinned).toEqual(["two"]));
expect(selectedTasks()).toEqual(["one"]);
expect(openTask).not.toHaveBeenCalled();
});
it("filters every section by the search, archived ones included, and highlights the match", () => {
const tasks = useAgents.getState().tasks;
const rename = (id: string, title: string, status: AgentTask["status"] = "ready") =>
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff. Show more