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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 2c6696dd3a fix(json): validate JSON files and map SchemaStore schemas for common config files
vscode-json-language-server validates nothing unless `json.validate.enable`
is set, so even a file's own `$schema` was ignored. Turn validation on and
associate package.json, tsconfig/jsconfig, ESLint, Prettier, Babel, Lerna,
Turborepo, SWC and Composer configuration files with their published schemas,
for both JSON and JSON with Comments.
2026-11-21 23:08:11 +08:00
Deng Liuтаdengliu 09d8e92e2c chore(dev): add an optional mise contributor toolchain (#4948)
Add mise.toml pinning Rust (with rustfmt and clippy), Node.js and pnpm, plus six tasks (setup, dev, dev:app, build, test, check) that call the existing pnpm scripts and Cargo commands, so the worktree-aware launcher is unchanged and contributors can still work without mise. Document the optional workflow in both setup guides and AGENTS.md, and raise the documented Node minimum to 22.22.2, which the locked jsdom requires on the 22.x line.

Closes #4941

Co-authored-by: dengliu <[email protected]>
2026-11-21 22:22:19 +08:00
Mr0Bread 221b6c3098 fix(ci): validate language smoke dependency triggers (#4847)
Language smoke's path filters missed inputs the smoke actually loads (src/workbench, src/ui, src/bindings.ts, editor LSP modules, vite/tsconfig, pnpm-workspace, patches, build-tools) and the crates ide-host pulls in directly (ide-search, ide-streams), so changes there skipped the smoke. Add them to the workflow paths and the Changes step patterns, and add scripts/smoke-paths.ts with a test that derives the smoke's inputs from the frontend import closure and cargo metadata and fails when the workflow misses one. CI's frontend filter now also runs on crate manifest changes, which the test reads.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-21 22:21:17 +08:00
ntbang0901 d154dce4f7 fix(app): restrict base and form targets in the workbench CSP (#4874)
The workbench CSP had no base-uri or form-action, so injected markup could add a <base> element to retarget relative URLs or post a form to any origin. Add base-uri 'self' and form-action 'none'; the workbench never uses <base> and every form handles submit in script. The plugin view CSP already sets form-action 'none'.

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 22:19:42 +08:00
l0ng-ai 83364c5423 chore: v0.1.50 2026-11-21 21:03:57 +08:00
l0ng-ai fa33819afb fix(agents): keep the model name readable in a narrow chat composer (#5015)
In a narrow composer the toolbar's first item was capped at 110px, meant for the New Task agent picker. A chat's composer has no agent picker, so the cap fell on the model control and squeezed the model name to "G…" next to its settings chip while the row had room to spare. The agent picker already shows only its icon and doesn't grow, so the cap is removed.
2026-11-21 20:59:22 +08:00
l0ng-ai 5e6a59eae8 fix(agents): pick the model from the list and set its options from one chip (#5012)
The composer's model controls had three ways into the same settings: a "High" detail next to the model chip with a half divider and no chevron, a "Low ›" entry on model list rows leading to a settings page with a back arrow, and inside it a dropdown for Codex's six effort levels — two steps to change effort. While a model's settings loaded, a "Loading model settings…" text broke the row's alignment.

Now the model chip only picks (and pins) models, and the chip next to it opens every option of the current model — effort, context size, fast mode — in one popup, each a click away: on/off as a switch, up to five values as a segmented control, more listed. A model with a single option closes the popup on a choice. The chip has a chevron like the other composer chips, and a spinner takes its place while settings load. Configuring a model other than the current one from its list row is gone.
2026-11-21 20:46:14 +08:00
l0ng-ai a9971905dc fix(navigation): prioritize existing tests in the test chooser (#5011)
The Test and Test Subject choosers give file names their own space and align directories to the right, keeping the end of long directories visible. When there are several tests, the first match is selected and Create New Test appears below the results, with a divider before it.
2026-11-21 20:38:21 +08:00
l0ng-ai 7e6296f0c6 fix(navigation): separate target names from file locations (#5010)
Navigation target rows show the container next to the symbol at the same text size. File locations align to the right and keep the file name and line visible when a long path has to be shortened. The list scrolls inside the popup when space is limited.
2026-11-21 20:18:55 +08:00
l0ng-ai 31c169c889 fix(editor): give the indentation chooser a code style heading (#5008)
The indentation popup uses a Code Style heading for the active file's language. The current indentation stays checked even when the file uses a custom number of spaces. The heading and choices use the standard menu text size.
2026-11-21 20:05:32 +08:00
l0ng-ai 13103fd5af fix(plugins): update wasmtime to 49.0.7 for the WASI sandbox advisory (#5009)
RUSTSEC-2026-0587: on Windows a drive-prefixed path component let a WASI guest escape its preopened directory. 49.0.7 carries the fix; the rest of the wasmtime crates move with it. Lockfile-only.
2026-11-21 20:03:31 +08:00
l0ng-ai 50340219ac fix(editor): show usages on a declaration a server finds no definition for
Go to Declaration on a declaration's own name shows its usages only when the language server answers the declaration itself. kotlin-language-server answers nothing there, so ⌘B / ⌘-click on `fun lend` reported "Cannot find declaration to go to" while Find Usages listed four. When the server has no definition and the syntax tree puts the caret on a declaration's name, the usages show now, for every language.
2026-11-21 19:58:02 +08:00
l0ng-ai 71000e15f2 fix(editor): open library sources reached by navigation read-only
Go to Declaration into a library could open its source editable: only files under the External Libraries roots were read-only, and many language servers answer with sources they keep elsewhere (java-analyzer's source cache, the TypeScript lib files of the server's own typescript, Intelephense's stubs, the temporary copies kotlin-language-server writes). A file outside the project that code navigation opens (declarations, implementations, usages, hierarchy, documentation and inlay links) now opens read-only with the Library source notice. Files opened outside the project in other ways stay editable.
2026-11-21 19:58:02 +08:00
l0ng-ai 042008f681 fix(run): don't launch Java with a server JDK older than the module's release
Without jdtls, a Java run or debug used the JDK the Java language server reports (java-analyzer's own runtime) before matching the module's Java version, so a module compiled for release 21 started on JDK 17 and failed with UnsupportedClassVersionError. The server's JDK is now used only when it can run the module's release; otherwise the installed JDK matching it is picked.
2026-11-21 19:58:02 +08:00
l0ng-ai 942e6cb237 fix(windows): stop WebView2 browser shortcuts from taking unhandled IDE keys (#5007)
A key the keymap leaves alone reached WebView2's browser accelerators: Ctrl+F in a view without its own find opened the page's Find bar over the whole window, and F3, F12 or Alt+Left ran browser features. Turn the accelerators off for every webview; the page still gets every key.
2026-11-21 19:57:55 +08:00
l0ng-ai 674cdd3925 fix(diff): align headers in the combined changes view (#5006)
The combined changes view gives each file its own inset section, with a bold file name and a muted path. File actions sit before the name so they stay visible when a narrow editor pane truncates the text. Compact Mode reduces the space around file sections and headers.
2026-11-21 19:44:35 +08:00
l0ng-ai 04666f5980 fix(app): open middle-clicked links in the browser (#5005)
A middle click on a link (an agent reply, any rendered content) navigated the IDE window to it: link handlers listen to click, and the middle button fires auxclick, whose default action the webview carried out. A window-wide auxclick handler now cancels it for every link and opens a web link in the default browser, as a left click does; a link into the app itself does nothing.

Fixes #4992
2026-11-21 19:33:15 +08:00
85 змінених файлів з 1975 додано та 626 видалено

No files matched your search

+3 -2
Переглянути файл
@@ -65,8 +65,9 @@ jobs:
plugin_web='^plugins/official/[^/]+/web-src/'
# Paths the frontend checks never read...
backend='^(crates/|src-tauri/|sdk/|wit/|java/|fixtures/|Cargo\.(toml|lock)$|deny\.toml$|rustfmt\.toml$|rust-toolchain(\.toml)?$|\.cargo/)'
# ...except these, which frontend tests and e2e fixtures load.
read_by_web='^(fixtures/(folding|django-app)/|crates/ide-plugin/tests/fixtures/|crates/ide-db/(src|tests/fixtures)/snowflake/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
# ...except these, which frontend tests and e2e fixtures load (the crate manifests:
# scripts/smoke-paths.test.ts, through cargo metadata).
read_by_web='^(fixtures/(folding|django-app)/|(crates/[^/]+/)?Cargo\.toml$|crates/ide-plugin/tests/fixtures/|crates/ide-db/(src|tests/fixtures)/snowflake/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
# What the browser app and its e2e tests are built from.
app='^(src/|e2e/|public/|index\.html$|vite\.config\.ts$|tsconfig\.json$|playwright\.config\.ts$|package\.json$|pnpm-(lock|workspace)\.yaml$|crates/ide-plugin/tests/fixtures/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
# The plugin workspaces: the SDK, the plugins, their interface and the host's fixture plugins.
+28 -3
Переглянути файл
@@ -8,6 +8,9 @@ name: Language smoke
# (Run, Run tests, the test tree, Rerun Failed Tests): smoke/run.test.ts; and debugging its
# entry point with the debugger the IDE installs (breakpoint, frames, variables, evaluate,
# Step Over, Resume): smoke/debug.test.ts.
# The paths below and the Changes step's patterns must cover every file the smoke loads and
# every crate it runs: scripts/smoke-paths.test.ts checks them (`node scripts/smoke-paths.ts
# [file…]` lists what they miss, or the languages a change runs).
on:
push:
branches: [main]
@@ -20,10 +23,30 @@ on:
- "Cargo.lock"
- "src/features/run/**"
- "src/features/debugger/**"
- "src/features/build-tools/**"
- "src/platform/**"
- "src/workbench/**"
- "src/ui/**"
- "src/editor/api.ts"
- "src/editor/core/cm/cornerInset.ts"
- "src/editor/core/cm/iconArea.ts"
- "src/editor/lsp/availability.ts"
- "src/editor/lsp/diagnostics.ts"
- "src/editor/lsp/files.ts"
- "src/editor/lsp/hint.ts"
- "src/editor/lsp/lsp.ts"
- "src/editor/lsp/positions.ts"
- "src/bindings.ts"
- "src/styles/tokens.css"
- "src/test/setup.ts"
- "src-tauri/icons/128x128.png"
- "smoke/**"
- "vite.config.ts"
- "tsconfig.json"
- "package.json"
- "pnpm-lock.yaml"
- "pnpm-workspace.yaml"
- "patches/**"
- ".github/workflows/language-smoke.yml"
- ".github/tool-versions.env"
pull_request:
@@ -70,10 +93,12 @@ jobs:
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt
cat files.txt
# Crates outside what the smoke runs (language servers, debuggers, run configurations,
# SDKs, build tools and the project model): cargo metadata, deps of ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-search|ide-spell|ide-ssh|ide-streams|ide-vcs|ide-web)/'
# SDKs, build tools, the project model, Find Usages candidates, debug stream traces):
# cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger)/|src/platform/|smoke/|package\.json$|pnpm-lock\.yaml$|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
+3 -1
Переглянути файл
@@ -73,7 +73,9 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
## Commands
- `pnpm tauri dev` — run the app with worktree isolation (Node 22.18+).
- Optional: `mise install` provisions the contributor toolchain; `mise tasks` lists the task aliases.
See [Development setup](docs/en/contribute/setup.mdx). The direct commands below still work without mise.
- `pnpm tauri dev` — run the app with worktree isolation. Use Node 22.22.2 or later on the 22.x line.
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
this worktree's running MCP bridges and actual ports.
- `pnpm build` — typecheck + bundle frontend.
Створено
+115 -124
Переглянути файл
@@ -1203,27 +1203,27 @@ dependencies = [
[[package]]
name = "cranelift-assembler-x64"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aecefa88696b62f833cc0c997d19c93246b0268e2aaf23e0e8692e527f6de088"
checksum = "c19fba13ee427c4dd29488ea51127e945bf07fd9d79093f14c9cc57f74acf757"
dependencies = [
"cranelift-assembler-x64-meta",
]
[[package]]
name = "cranelift-assembler-x64-meta"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1391a2546f5edf06a0ff5e9430d73c2713fd536aefec53200dc21846d1467f53"
checksum = "dd88c766346fcc14bbadbd68cb11e9bc1e555e99f7e8f6b1f4c27a73ca659bec"
dependencies = [
"cranelift-srcgen",
]
[[package]]
name = "cranelift-bforest"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9528915fbc2c950702329e08c6d72aaff8ece9b7ecdbd225742825c09a445227"
checksum = "f19d43d75dd963d6b1a653f2e03d4eed4365ca2e598ec57e52c15afdad6c3276"
dependencies = [
"cranelift-entity",
"wasmtime-internal-core",
@@ -1231,9 +1231,9 @@ dependencies = [
[[package]]
name = "cranelift-bitset"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9dd69a6db85c1bcff989809e0e0b3b06506425f32b545c46aeafda5fe7775d6a"
checksum = "45d0b93e50856858c89c61cbe3f6d4b07596da22eb5a03a95b19420e1d08a275"
dependencies = [
"serde",
"serde_derive",
@@ -1242,9 +1242,9 @@ dependencies = [
[[package]]
name = "cranelift-codegen"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24c2db6c26cd96393cf785c4b51b900738963cc7422aa0045416a7641ae2f6cd"
checksum = "efbdff32d3b6b4f33f1ba8a4ac747b97ce569b1d6834c3089c1c0933b94e618c"
dependencies = [
"bumpalo",
"cranelift-assembler-x64",
@@ -1273,9 +1273,9 @@ dependencies = [
[[package]]
name = "cranelift-codegen-meta"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e284270142e7f1dcb73a992a62a8b3716b4062a65a52d8f2732c6ebf6f7f342f"
checksum = "67fd11ff24916a2c1ff852ce4bb664fcf2c2970ed551de44dd5b573321123703"
dependencies = [
"cranelift-assembler-x64-meta",
"cranelift-codegen-shared",
@@ -1286,24 +1286,24 @@ dependencies = [
[[package]]
name = "cranelift-codegen-shared"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6595667b7d505cf85d5bdd014e6f57ad6128183238f8e372319d9384782472f5"
checksum = "ba5d321229c3e00a17d7bb3633529ffdf97a13bcf4962fd2e92f1e0fd39360aa"
[[package]]
name = "cranelift-control"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26ffdbfcd24c3833d730849e6d132af34a400a2b89b44446015c01eecbea21d"
checksum = "71cd63450256d0f80f7a0527e133452f84fa6e1ca73c7db6ca2a9e8cc89d1c18"
dependencies = [
"arbitrary",
]
[[package]]
name = "cranelift-entity"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ffb08ccd8a77fb31cdbbda2afa2333d8f85299b1bc0d1c194259ba66d160d74"
checksum = "18d2f259130db1bbb89500d26944971a9beeb410de91ff14039203f055d7f9f0"
dependencies = [
"cranelift-bitset",
"serde",
@@ -1313,9 +1313,9 @@ dependencies = [
[[package]]
name = "cranelift-frontend"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b447e4f2bb44b1188185a77f478e5a91b7723a40b3b58c3e2d5b26df2ed5a665"
checksum = "cf37a38d982d45fe2c065d55e4de76e596b443b6acceb3ca726c2072c8ba6d7b"
dependencies = [
"cranelift-codegen",
"hashbrown 0.17.1",
@@ -1326,15 +1326,15 @@ dependencies = [
[[package]]
name = "cranelift-isle"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f0989e943f3a9d41989595826bba544df9fda64bcddd4df0c06fb2e26af3cb3"
checksum = "8ce8f84e2d44326879e18016d763457a2cb5d775e4a5822cd7473fc171fca063"
[[package]]
name = "cranelift-native"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fa10df59e776c42dae5b6ba5216ba5321707a2136abd2219e615c54b234fc1b"
checksum = "df64a0392edac7b38fb2965ce8e205e7c5e219e4c531ed3cd1929c782f21853d"
dependencies = [
"cranelift-codegen",
"libc",
@@ -1343,9 +1343,9 @@ dependencies = [
[[package]]
name = "cranelift-srcgen"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36508559c8839a8b6ee091f9deaa9cfe620a82f1abb5e358a0a0c65290583622"
checksum = "3748e3c77c0717359cd4c089e1dc057221eb8598a9c18b0b5afccb5685975abb"
[[package]]
name = "crc"
@@ -2154,7 +2154,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -2386,7 +2386,7 @@ checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
dependencies = [
"io-lifetimes 2.0.4",
"rustix",
"windows-sys 0.59.0",
"windows-sys 0.52.0",
]
[[package]]
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"blake3",
"dunce",
@@ -4171,7 +4171,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4185,7 +4185,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"serde",
@@ -4196,7 +4196,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"blake3",
"chardetng",
@@ -4214,7 +4214,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4228,7 +4228,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4239,7 +4239,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4250,7 +4250,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"dunce",
"encoding_rs",
@@ -4267,7 +4267,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-run",
@@ -4281,7 +4281,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4310,7 +4310,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4348,7 +4348,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"serde",
@@ -4361,7 +4361,7 @@ dependencies = [
[[package]]
name = "ide-drag-out"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4375,7 +4375,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4396,7 +4396,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-android",
"ide-core",
@@ -4407,7 +4407,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4419,7 +4419,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4432,7 +4432,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"criterion",
"ide-core",
@@ -4450,7 +4450,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4525,7 +4525,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"hyper-util",
"ide-core",
@@ -4545,7 +4545,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"blake3",
"criterion",
@@ -4567,7 +4567,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4579,7 +4579,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"encoding_rs",
"futures",
@@ -4596,7 +4596,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"libc",
"tempfile",
@@ -4605,7 +4605,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"futures",
"serde",
@@ -4616,7 +4616,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"blake3",
"criterion",
@@ -4675,7 +4675,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"criterion",
"dunce",
@@ -4704,7 +4704,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"bytes",
"dunce",
@@ -4723,7 +4723,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"futures",
"ide-core",
@@ -4746,7 +4746,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"blake3",
"dunce",
@@ -4769,7 +4769,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4783,7 +4783,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"dunce",
"futures",
@@ -4803,7 +4803,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"dunce",
"encoding_rs",
@@ -4827,7 +4827,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-tools",
@@ -4843,7 +4843,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"dunce",
"flate2",
@@ -4866,7 +4866,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"criterion",
"encoding_rs",
@@ -4887,7 +4887,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"parking_lot",
@@ -4900,7 +4900,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4925,7 +4925,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-language",
@@ -4938,7 +4938,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-language",
@@ -4953,7 +4953,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"libc",
@@ -4967,7 +4967,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"criterion",
"ide-core",
@@ -4980,7 +4980,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"flate2",
"hex",
@@ -5001,7 +5001,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"blake3",
"dunce",
@@ -5022,7 +5022,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"chardetng",
"dunce",
@@ -5049,7 +5049,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5065,7 +5065,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"blake3",
"dunce",
@@ -5227,7 +5227,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
dependencies = [
"io-lifetimes 3.0.1",
"windows-sys 0.60.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -5265,7 +5265,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
dependencies = [
"hermit-abi",
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -6694,7 +6694,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -7424,9 +7424,9 @@ dependencies = [
[[package]]
name = "pulley-interpreter"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "335e459f9c7809af04768799880504d014d07e8e2fc6ae682fe2a105d8ced33f"
checksum = "99ecf828c291348e4066f8e45bf37c35ea6012b07a9201e7911c21f03ad1af3e"
dependencies = [
"cranelift-bitset",
"log",
@@ -7436,9 +7436,9 @@ dependencies = [
[[package]]
name = "pulley-macros"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd492ac929a6ca0357362d9fa0a09e31290feac5914550ccfb539b21f89c4b9e"
checksum = "20e35ece122b2e8bbd7ea9db0709b3d32f20555b73985efc3eaf6afa4ef2ecdf"
dependencies = [
"proc-macro2",
"quote",
@@ -7968,7 +7968,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -8036,7 +8036,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -9783,7 +9783,7 @@ dependencies = [
"getrandom 0.3.4",
"once_cell",
"rustix",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -11117,9 +11117,9 @@ dependencies = [
[[package]]
name = "wasmtime"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f32390bdc8d7cdb6259a1b855178bfed88226b4004b209fd48fb30e0deb01cd3"
checksum = "263d6a66a772efff2c98a1aa367e8e61dae32d2ecf95f85f4776733762322aa7"
dependencies = [
"addr2line",
"async-trait",
@@ -11159,9 +11159,9 @@ dependencies = [
[[package]]
name = "wasmtime-environ"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c10f8ef1c9ee5e0f125c775fe56a4d07b8525db30a96e6358c61d93bd11dee4"
checksum = "5f2f0898bedc77f110dca6f70394780f89af68a8ca19e12559ee73d4187a6fe9"
dependencies = [
"anyhow",
"cpp_demangle",
@@ -11190,9 +11190,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-component-macro"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "620c53182ebd26c9fff5b90dd53cf8ec3103c381403fd32f8d395da31a9e4a46"
checksum = "b140c28283bd2255a4bb8834621f7200bbe7581cbca91d803b5ba4adf9119a5e"
dependencies = [
"anyhow",
"proc-macro2",
@@ -11205,15 +11205,15 @@ dependencies = [
[[package]]
name = "wasmtime-internal-component-util"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "011e31ca343d9ba0ec623153cd94131b6f03973ef1a0ab791161f642e4a16a93"
checksum = "853075a197694ba7f0749e7af78b59e12c0956dff5b16dafbfc49c3b90cdbc93"
[[package]]
name = "wasmtime-internal-core"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab15e50a060b746493e6e95ef3ce4e6e7ebfdd7cc336a7dff0f0277e01b447ef"
checksum = "e6e13ab3aa598d863643ef9ec043d63fde7effca4465270446d5b868936b27a6"
dependencies = [
"hashbrown 0.17.1",
"libm",
@@ -11222,9 +11222,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-cranelift"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc3d27440a83fba26dd2784a997e13d9acb3606a75fb127c324929b52221c5c5"
checksum = "660103cff91df46f9f06568f3889b8b59a6ae0f56756abfcc002a0a69974cc9f"
dependencies = [
"cranelift-codegen",
"cranelift-control",
@@ -11248,9 +11248,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-fiber"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e54b28d0d453ca8932e4504065ae66a78f01fcb22b1a2ee287128d732fa9d6f"
checksum = "c4d0e958516bdf283b83015283774e11c86b66f2f4bd7d2ea52e9799fa59cddb"
dependencies = [
"cc",
"libc",
@@ -11262,9 +11262,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-jit-debug"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9293e75a3048b900f7b7c524702abca16d8a2332f970324eefc519f454cd5d69"
checksum = "ad61b1e661871bb7d11b5543202a05c44ed8682806b438f68ced629a22719463"
dependencies = [
"cc",
"wasmtime-internal-versioned-export-macros",
@@ -11272,9 +11272,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-jit-icache-coherence"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b852e568831b913d410541bb37edc45a5002e472208fbdbaf844ed801dd4255f"
checksum = "52c641b9e1bab449c7316896f01d4a0c426e2a502a5a8098e1af4a0392053e7a"
dependencies = [
"libc",
"wasmtime-internal-core",
@@ -11283,9 +11283,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-unwinder"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1f7349c9834a542275ad757340079e6453fccb429efce581454d23f85af92c0"
checksum = "03303a9abd333edcbd44fee3b1e0905ad156d3bcec311323d061cdff92e7d1f3"
dependencies = [
"cranelift-codegen",
"log",
@@ -11295,9 +11295,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-versioned-export-macros"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30b3e0768a450d9dea3e16b83f2498f0b08db0e32bad695e35564eef017be3f1"
checksum = "8db0c7f417e5ca3ba92d127d17b980529455d01c141be99204e6d309630c42de"
dependencies = [
"proc-macro2",
"quote",
@@ -11306,9 +11306,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-wit-bindgen"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d085c540b95d0ffebf98c266e6f152e1acf96a9f676f224a74307b9d422c15"
checksum = "6292ee4f797f9befb64aa2b3477ec8576501d6302ec21fd2785a8d3f94cf8717"
dependencies = [
"anyhow",
"bitflags 2.13.2",
@@ -11320,9 +11320,9 @@ dependencies = [
[[package]]
name = "wasmtime-wasi"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17f8ce6b9e77539b5f52d440346f876a84c513ec1b07162845282f8652f7f7f9"
checksum = "3175ff29e2992269f51ec372f7757941f11f87b265a614761726960d42ef6e4d"
dependencies = [
"async-trait",
"bitflags 2.13.2",
@@ -11344,9 +11344,9 @@ dependencies = [
[[package]]
name = "wasmtime-wasi-io"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da9f90eb7ce6edbead27dba3a58843398875defa73b8dce4bbc29d0ce3dc9b40"
checksum = "3bb561839e32b61bf0cdd51efe3874fac5de1bd5775a5b7c41bdf70993e367ea"
dependencies = [
"async-trait",
"bytes",
@@ -11620,7 +11620,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -11788,15 +11788,6 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.60.2"
@@ -12069,7 +12060,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
dependencies = [
"bitflags 2.13.2",
"windows-sys 0.59.0",
"windows-sys 0.52.0",
]
[[package]]
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.49"
version = "0.1.50"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+65 -9
Переглянути файл
@@ -301,19 +301,30 @@ fn finish_launch(
// The module/project JDK, else the JDK the Java language server builds the module with, else one
// matching its Java version.
let project_jdk = ide_sdk::apply::module_jdk(root, module, settings);
let from_server = info.java_home.as_deref().map(ide_sdk::java::java_executable).filter(|p| p.is_file());
let java = project_jdk.map(|j| ide_sdk::java::java_executable(&j.home)).or(from_server).or_else(|| {
// The build model's level includes what the module inherits from its parent POMs.
let release = model
// The build model's level includes what the module inherits from its parent POMs.
let release = || {
model
.maven
.as_ref()
.and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module))
.and_then(|p| p.java_version)
.or_else(|| ide_sdk::java::project_java_version(module));
let jdks = ide_sdk::java::installed_jdks();
info.hints.extend(ide_sdk::java::missing_jdk_message(&jdks, release));
ide_sdk::java::pick_jdk(&jdks, release).map(|j| ide_sdk::java::java_executable(&j.home))
});
.or_else(|| ide_sdk::java::project_java_version(module))
};
let java = match project_jdk {
Some(j) => Some(ide_sdk::java::java_executable(&j.home)),
None => {
let release = release();
let server = info.java_home.as_deref().and_then(|home| server_java(home, release));
match server {
Some(java) => Some(java),
None => {
let jdks = ide_sdk::java::installed_jdks();
info.hints.extend(ide_sdk::java::missing_jdk_message(&jdks, release));
ide_sdk::java::pick_jdk(&jdks, release).map(|j| ide_sdk::java::java_executable(&j.home))
}
}
}
};
info.java_exec = Some(java.map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| "java".to_owned()));
let exec = PathBuf::from(info.java_exec.as_deref().unwrap_or("java"));
let shorten = ide_run::java_cmdline::shortening_for(&exec, &info.class_paths, &info.module_paths, cfg!(windows));
@@ -328,6 +339,19 @@ fn finish_launch(
}
}
/// The `java` of the JDK a Java language server reports, when it can run classes compiled for
/// `release`: that JDK is the one the server runs on or defaults to, not necessarily one the
/// module's bytecode loads on. A home whose version is unknown is used only when `release` is too.
fn server_java(home: &Path, release: Option<u32>) -> Option<PathBuf> {
match ide_sdk::java::jdk_at(home) {
Some(jdk) if release.is_none_or(|release| jdk.major >= release) => {
Some(ide_sdk::java::java_executable(&jdk.home))
}
Some(_) => None,
None => Some(ide_sdk::java::java_executable(home)).filter(|java| release.is_none() && java.is_file()),
}
}
/// With Settings › Maven › Delegate IDE build/run actions to Maven, javac's verdict replaces
/// JDT's. Classes JDT wrote for sources with errors look up to date to Maven's incremental
/// compiler, so a launch JDT reports errors for recompiles everything.
@@ -557,6 +581,38 @@ fn drop_processor_recreate_errors(info: &mut JavaLaunchInfo) {
mod tests {
use super::*;
fn fake_jdk(dir: &Path, version: Option<&str>) -> PathBuf {
let bin = dir.join("bin");
std::fs::create_dir_all(&bin).unwrap();
std::fs::write(bin.join(if cfg!(windows) { "java.exe" } else { "java" }), "").unwrap();
if let Some(version) = version {
std::fs::write(dir.join("release"), format!("JAVA_VERSION=\"{version}\"\n")).unwrap();
}
dir.to_path_buf()
}
#[test]
fn a_server_jdk_older_than_the_module_release_is_not_used() {
let tmp = tempfile::tempdir().unwrap();
let jdk17 = fake_jdk(&tmp.path().join("17"), Some("17.0.12"));
let jdk21 = fake_jdk(&tmp.path().join("21"), Some("21.0.4"));
let unknown = fake_jdk(&tmp.path().join("unknown"), None);
// (server JDK, module release, used?)
let cases = [
(&jdk17, Some(21), false),
(&jdk17, Some(17), true),
(&jdk17, Some(11), true),
(&jdk17, None, true),
(&jdk21, Some(21), true),
(&unknown, None, true),
(&unknown, Some(21), false),
];
for (home, release, used) in cases {
assert_eq!(server_java(home, release).is_some(), used, "{} for release {release:?}", home.display());
}
assert!(server_java(&tmp.path().join("missing"), None).is_none());
}
#[test]
fn recognises_a_processor_recreating_its_output() {
assert!(processor_recreated_a_file(
+21 -6
Переглянути файл
@@ -7,12 +7,12 @@ OpenIDEA is a Tauri 2 app: a Rust backend (`crates/`, `src-tauri/`) and a React
## Prerequisites
| Tool | Version | Notes |
| ------------------------- | --------------------- | --------------------------------------------------------------------------------------------------------- |
| Rust | stable, at least 1.96 | `rust-version` in the root `Cargo.toml`. Install `clippy` and `rustfmt` too. |
| Node.js | 22.18 or newer | The repo's scripts (`scripts/*.ts`, `perf/*.ts`) are run directly by Node as TypeScript. CI uses Node 22. |
| pnpm | 11 | The version CI uses. |
| Tauri system dependencies | — | Per OS: see [Tauri prerequisites](https://v2.tauri.app/start/prerequisites/). |
| Tool | Version | Notes |
| ------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------ |
| Rust | stable, at least 1.96 | `rust-version` in the root `Cargo.toml`. Install `clippy` and `rustfmt` too. |
| Node.js | 22.x, at least 22.22.2 | CI uses Node 22. Node runs the TypeScript scripts directly; the locked jsdom requires this patch or newer on 22.x. |
| pnpm | 11 | The version CI uses. |
| Tauri system dependencies | — | Per OS: see [Tauri prerequisites](https://v2.tauri.app/start/prerequisites/). |
On Linux (Ubuntu 22.04, as in CI) the system packages are:
@@ -54,6 +54,21 @@ Other everyday commands:
| `pnpm gen:bindings` | Regenerate `src/bindings.ts` from the Rust command signatures. |
| `pnpm dev` | Vite alone: the UI in a plain browser with in-memory backends (no Rust). |
## Optional: use mise
Instead of installing Rust, Node.js and pnpm separately, [install mise](https://mise.jdx.dev/installing-mise.html). You still need the Tauri system dependencies above. From the cloned worktree, after reviewing `mise.toml`, run:
```sh
mise trust
mise install
mise run setup
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 six tasks. `mise run build` builds the frontend (not a desktop installer). `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
Several worktrees can be developed and run side by side. Create one per task:
+21 -6
Переглянути файл
@@ -7,12 +7,12 @@ OpenIDEA 是一个 Tauri 2 应用:Rust 后端(`crates/`、`src-tauri/`)加
## 前置条件
| 工具 | 版本 | 说明 |
| -------------- | ----------------- | ------------------------------------------------------------------------------------------ |
| Rust | stable,至少 1.96 | 见根目录 `Cargo.toml` 的 `rust-version`。同时安装 `clippy` 和 `rustfmt`。 |
| Node.js | 22.18 及以上 | 仓库脚本(`scripts/*.ts`、`perf/*.ts`)由 Node 直接按 TypeScript 运行。CI 用的是 Node 22。 |
| pnpm | 11 | 与 CI 一致。 |
| Tauri 系统依赖 | — | 各平台要求见 [Tauri prerequisites](https://v2.tauri.app/start/prerequisites/)。 |
| 工具 | 版本 | 说明 |
| -------------- | ------------------ | ------------------------------------------------------------------------------------------- |
| Rust | stable,至少 1.96 | 见根目录 `Cargo.toml` 的 `rust-version`。同时安装 `clippy` 和 `rustfmt`。 |
| Node.js | 22.x,至少 22.22.2 | CI 使用 Node 22。Node 直接运行 TypeScript 脚本;锁定的 jsdom 在 22.x 上至少需要此补丁版本。 |
| pnpm | 11 | 与 CI 一致。 |
| Tauri 系统依赖 | — | 各平台要求见 [Tauri prerequisites](https://v2.tauri.app/start/prerequisites/)。 |
Linux(与 CI 一样以 Ubuntu 22.04 为例)需要的系统包:
@@ -54,6 +54,21 @@ sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librs
| `pnpm gen:bindings` | 根据 Rust 命令签名重新生成 `src/bindings.ts`。 |
| `pnpm dev` | 只起 Vite:在普通浏览器里运行 UI,后端用内存实现(不需要 Rust)。 |
## 可选:使用 mise
如果不想分别安装 Rust、Node.js 和 pnpm,可以[安装 mise](https://mise.jdx.dev/installing-mise.html)。上面列出的 Tauri 系统依赖仍需单独安装。在克隆的 worktree 中查看 `mise.toml`,然后运行:
```sh
mise trust
mise install
mise run setup
mise run dev
```
`setup` 在当前 worktree 中执行 `pnpm install`。`dev` 和 `dev:app` 都沿用原来的启动脚本,保留 worktree 隔离。使用 `mise run` 不需要在 shell 中激活 mise。
运行 `mise tasks` 可以查看全部六个任务。`mise run build` 构建前端,不生成桌面安装包。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。
## Worktree
可以同时开发和运行多个 worktree。每个任务建一个:
+8 -14
Переглянути файл
@@ -285,7 +285,7 @@ async function expectNoSubmission(page: Page) {
}
for (const surface of ["new", "task"] as const) {
test(`${surface}: configure another model from its row, then edit its context from the composer`, async ({
test(`${surface}: switch models from the list, then set effort and context from the settings chip`, async ({
workbench: page,
}) => {
const context = option(
@@ -306,22 +306,16 @@ for (const surface of ["new", "task"] as const) {
await modelButton(page).click();
const row = page.getByRole("option", { name: /^Swift\b/ });
await row.hover();
const configure = row.getByRole("button", { name: "Configure Swift…" });
if (surface === "task") await configure.press("Enter");
else await configure.click();
await expect(modelButton(page)).toHaveText("Atlas");
await expect(page.getByRole("radio", { name: "Gentle" })).toHaveCount(0);
await page.getByRole("radio", { name: "Thorough" }).click();
await expect(row.getByRole("button", { name: /^Configure/ })).toHaveCount(0);
if (surface === "task") await row.press("Enter");
else await row.click();
await expect(modelButton(page)).toHaveText("Swift");
await expect(page.getByRole("radio", { name: "Thorough" })).toBeChecked();
await page.keyboard.press("Escape");
const settings = page.getByRole("button", { name: /^Model settings:/ });
await expect(settings).toHaveText("Thorough · 200K");
await settings.click();
await expect(page.getByRole("button", { name: "Back to models" })).toHaveCount(0);
await page.getByRole("radio", { name: "Thorough" }).click();
await page.getByRole("radio", { name: "1M" }).click();
await expect(settings).toHaveText("Thorough · 1M");
await page.getByRole("button", { name: "Back to models" }).click();
await expect(page.getByRole("listbox", { name: "Model", exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(box(page)).toHaveText("Review the project structure");
await expectNoSubmission(page);
@@ -642,7 +636,7 @@ test("New Task discovers uncached model effort before the first prompt", async (
await expect
.poll(async () => (await ipcCalls(page, "agent_refresh_models")).filter((call) => call.model === "swift"))
.toEqual([{ provider: provider.id, force: false, model: "swift" }]);
await expect(page.getByRole("status").filter({ hasText: "Loading model settings…" })).toBeVisible();
await expect(page.getByRole("status", { name: "Loading model settings…" })).toBeVisible();
await expect(effortLabel(page)).toHaveCount(0);
await page.screenshot({ path: testInfo.outputPath("model-settings-loading.png") });
await page.evaluate(() => document.dispatchEvent(new Event("test:model-settings-ready")));
@@ -671,7 +665,7 @@ test("an existing chat can choose effort for a refreshed model before sending",
await page.getByRole("button", { name: "Refresh models", exact: true }).click();
await swiftModel.click();
const loading = page.getByRole("status").filter({ hasText: "Loading model settings…" });
const loading = page.getByRole("status", { name: "Loading model settings…" });
const send = page.getByRole("button", { name: "Send", exact: true });
await expect(loading).toBeVisible();
await expect(send).toBeDisabled();
+44
Переглянути файл
@@ -46,6 +46,50 @@ test("a narrow diff keeps navigation, settings and the difference count visible"
await expect(toolbar).toContainText("1 of 1 differences");
});
test("combined diff file actions stay visible beside a long name in a narrow pane", async ({ workbench: page }) => {
const longName = "OrderHistoryCustomerNotificationDeliveryPreferencesValidationDefaults.txt";
const directory = "/dev/acme-api/src/main/orders/preferences";
await page.evaluate(
async (paths) => {
const optionsPath = "/src/features/vcs/allInOneDiff.ts";
const inputPath = "/src/features/vcs/diffInput.ts";
const { setAllInOneDiff } = await import(optionsPath);
const { openDiff, withChain } = await import(inputPath);
setAllInOneDiff(true);
await openDiff(
withChain(
paths.map((path) => ({
path,
left: { type: "text", text: "before\n", label: "HEAD" },
right: { type: "worktree" },
})),
0,
),
);
},
[`${directory}/${longName}`, `${directory}/Notes.txt`],
);
await page.setViewportSize({ width: 460, height: 600 });
const file = page.getByRole("region", { name: longName, exact: true });
const header = file.getByRole("button", { name: /^(Collapse|Expand) File$/ }).locator("..");
const open = header.getByRole("button", { name: "Open in Separate Tab", exact: true });
const jump = header.getByRole("button", { name: "Jump to Source", exact: true });
await expect(open).toBeInViewport({ ratio: 1 });
await expect(jump).toBeInViewport({ ratio: 1 });
const label = header.getByText(longName, { exact: true });
await expect(label).toHaveCSS("text-overflow", "ellipsis");
const labelBox = (await label.boundingBox())!;
const jumpBox = (await jump.boundingBox())!;
expect(labelBox.x).toBeGreaterThan(jumpBox.x + jumpBox.width);
await expect(header).toContainText("src/main/orders/preferences");
await header.getByRole("button", { name: "Collapse File", exact: true }).click();
await expect(file.getByRole("button", { name: "Expand File", exact: true })).toBeVisible();
await open.click();
await expect(page.getByRole("tab", { name: new RegExp(longName), selected: true })).toBeVisible();
});
test("maximizes a diff preview tab and restores its previous layout", async ({ workbench: page }) => {
const toolbar = await openChain(page);
const viewer = toolbar.locator("..");
+34
Переглянути файл
@@ -13,6 +13,40 @@ test("opens a file from the project tree and types into it", async ({ workbench:
await expect(editor.locator(".cm-content")).not.toContainText("// typed by e2e");
});
test("indentation shows the language and current width with room for the keyboard choices", async ({
workbench: page,
}) => {
await openFromTree(page, "build.gradle.kts");
await page.evaluate(async () => {
const path = "/src/editor/core/controller.ts";
const { editorController, useEditorStatus } = await import(/* @vite-ignore */ path);
const active = useEditorStatus.getState().status!.path;
editorController().manager.get(active)!.setIndent({ tabSize: 3, insertSpaces: true });
});
const status = page.getByRole("button", { name: "3 spaces", exact: true });
await status.click();
const menu = page.getByRole("menu", { name: "Indentation", exact: true });
const title = page.getByText("Kotlin Code Style", { exact: true });
await expect(title).toBeVisible();
await page.setViewportSize({ width: 500, height: 520 });
await expect(title).toBeInViewport({ ratio: 1 });
await expect(title).toHaveCSS("font-size", "13px");
await expect(title).toHaveCSS("font-weight", "600");
await expect(menu.getByRole("menuitemcheckbox", { name: "3 spaces", checked: true })).toBeInViewport({ ratio: 1 });
await expect(menu.getByRole("menuitem", { name: "Configure Indents…" })).toBeInViewport({ ratio: 1 });
await expect(menu.getByRole("menuitemcheckbox", { name: "2 spaces", checked: false })).toBeFocused();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Enter");
await expect(menu).toBeHidden();
const four = page.getByRole("button", { name: "4 spaces", exact: true });
await expect(four).toBeVisible();
await four.click();
await expect(menu.getByRole("menuitemcheckbox", { name: "4 spaces", checked: true })).toBeVisible();
});
test("Delete edits text after the focused Project tree is remounted", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
const content = editor.locator(".cm-content");
+55
Переглянути файл
@@ -0,0 +1,55 @@
import { expect, test } from "./fixtures";
test("keeps names, containers and keyboard targets visible near the window edge", async ({ workbench: page }) => {
await page.setViewportSize({ width: 460, height: 320 });
await page.evaluate(async () => {
const backendPath = "/src/editor/core/backend.ts";
const navigationPath = "/src/editor/lsp/navigation.ts";
const popupPath = "/src/editor/lsp/popupStore.ts";
const { docBackend } = await import(/* @vite-ignore */ backendPath);
const { locationItems } = await import(/* @vite-ignore */ navigationPath);
const { openPopup } = await import(/* @vite-ignore */ popupPath);
const targets = Array.from({ length: 20 }, (_, i) => {
const path = `/dev/acme-api/src/main/customer/orders/processing/notification/delivery/provider-${i + 1}/Target${i + 1}.txt`;
const name = i === 0 ? "dispatchOrder" : `dispatchOrder${i + 1}`;
docBackend().files.set(path, `${name} target\n`);
return {
path,
name,
kind: "method",
container: "OrderService",
uri: null,
range: {
start: { line: 0, col: 0 },
end: { line: 0, col: name.length },
},
};
});
openPopup({
kind: "list",
anchor: { x: 50, y: 150 },
title: "Choose Declaration (20 found)",
items: await locationItems(targets),
});
});
const popup = page.getByRole("dialog", { name: "Choose Declaration (20 found)" });
const list = popup.getByRole("listbox");
const first = list.getByRole("option", { selected: true });
const name = first.getByText("dispatchOrder", { exact: true });
const container = first.getByText("(OrderService)", { exact: true });
const path = first.getByText(/provider-1\/Target1\.txt:1$/);
await expect(container).toBeInViewport({ ratio: 1 });
await expect(container).toHaveCSS("font-size", await name.evaluate((el) => getComputedStyle(el).fontSize));
const nameBox = (await name.boundingBox())!;
const containerBox = (await container.boundingBox())!;
const pathBox = (await path.locator("..").boundingBox())!;
expect(containerBox.x - nameBox.x - nameBox.width).toBeLessThanOrEqual(4);
expect(pathBox.x).toBeGreaterThan(containerBox.x);
await list.press("End");
await expect(list.getByRole("option", { name: /dispatchOrder20/, selected: true })).toBeInViewport({ ratio: 1 });
await list.press("Enter");
await expect(popup).toBeHidden();
await expect(page.getByRole("tab", { name: "Target20.txt", exact: true, selected: true })).toBeVisible();
});
+53
Переглянути файл
@@ -0,0 +1,53 @@
import { expect, stubDesktop, test } from "./fixtures";
test("selects an existing test first and places the creation action after the results", async ({ workbench: page }) => {
await page.setViewportSize({ width: 500, height: 540 });
await stubDesktop(page);
await page.evaluate(async () => {
const backendPath = "/src/editor/core/backend.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const { docBackend } = await import(/* @vite-ignore */ backendPath);
const { editorService } = await import(/* @vite-ignore */ contributionsPath);
const files = new Map([
["/dev/acme-api/src/Checkout.ts", "export const checkout = 'source';"],
["/dev/acme-api/src/Checkout.js", "export const checkout = 'alternate source';"],
["/dev/acme-api/tests/enterprise/orders/reconciliation/merchant/Checkout.test.ts", "const suite = 'merchant';"],
["/dev/acme-api/tests/enterprise/orders/reconciliation/guest/Checkout.test.ts", "const suite = 'guest';"],
]);
for (const [path, text] of files) docBackend().files.set(path, text);
window.__ipc.handlers.find_files = ({ query }) =>
[...files.keys()].filter((path) => path.endsWith(`/${query}`)).map((path) => ({ path }));
window.__ipc.handlers.fs_probe = () => ({ binary: false, tooLarge: false });
window.__ipc.handlers.project_roots = () => ({ folders: [] });
await editorService().openFile("/dev/acme-api/src/Checkout.ts", { focus: true });
});
const editor = page.locator(".cm-content").last();
await expect(editor).toContainText("source");
await editor.press("Meta+Shift+t");
const tests = page.getByRole("dialog", { name: "Choose Test for Checkout (2 found)" });
const list = tests.getByRole("listbox");
const first = list.getByRole("option", { selected: true });
const create = list.getByRole("option", { name: "Create New Test…", exact: true });
await expect(first).toContainText("Checkout.test.ts");
await expect(first.getByText("Checkout.test.ts", { exact: true })).toBeInViewport({ ratio: 1 });
await expect(first.locator('[title="tests/enterprise/orders/reconciliation/guest"]')).toHaveCSS("font-size", "13px");
await expect(list.getByRole("option").last()).toHaveText("Create New Test…");
await list.press("Enter");
await expect(editor).toContainText("guest");
await editor.press("Meta+Shift+t");
const subjects = page.getByRole("dialog", { name: "Choose Test Subject for Checkout.test (2 found)" });
await expect(subjects.getByRole("option", { selected: true })).toContainText("Checkout.js");
await subjects.getByRole("listbox").press("End");
await subjects.getByRole("listbox").press("Enter");
await expect(editor).toContainText("checkout = 'source'");
await editor.press("Meta+Shift+t");
await list.press("End");
await expect(create).toHaveAttribute("aria-selected", "true");
await list.press("Enter");
const form = page.getByRole("dialog", { name: "New TypeScript File", exact: true });
await expect(form).toBeVisible();
await expect(form.getByRole("option", { name: "Test", exact: true, selected: true })).toBeVisible();
});
+45
Переглянути файл
@@ -13,3 +13,48 @@ command = "vscode-json-language-server"
args = ["--stdio"]
initialization-options = { provideFormatter = true }
install-hint = "npm i -g vscode-langservers-extracted"
# Validation is off in vscode-json-language-server unless enabled. Schemas from SchemaStore for
# common configuration files; a `$schema` in the file itself still wins.
[language-servers.settings.json.validate]
enable = true
[[language-servers.settings.json.schemas]]
fileMatch = ["package.json"]
url = "https://json.schemastore.org/package.json"
[[language-servers.settings.json.schemas]]
fileMatch = ["tsconfig.json", "tsconfig.*.json"]
url = "https://json.schemastore.org/tsconfig.json"
[[language-servers.settings.json.schemas]]
fileMatch = ["jsconfig.json", "jsconfig.*.json"]
url = "https://json.schemastore.org/jsconfig.json"
[[language-servers.settings.json.schemas]]
fileMatch = [".eslintrc", ".eslintrc.json"]
url = "https://json.schemastore.org/eslintrc.json"
[[language-servers.settings.json.schemas]]
fileMatch = [".prettierrc", ".prettierrc.json"]
url = "https://json.schemastore.org/prettierrc.json"
[[language-servers.settings.json.schemas]]
fileMatch = [".babelrc", ".babelrc.json", "babel.config.json"]
url = "https://json.schemastore.org/babelrc.json"
[[language-servers.settings.json.schemas]]
fileMatch = ["lerna.json"]
url = "https://json.schemastore.org/lerna.json"
[[language-servers.settings.json.schemas]]
fileMatch = ["turbo.json"]
url = "https://turbo.build/schema.json"
[[language-servers.settings.json.schemas]]
fileMatch = [".swcrc"]
url = "https://swc.rs/schema.json"
[[language-servers.settings.json.schemas]]
fileMatch = ["composer.json"]
url = "https://getcomposer.org/schema.json"
+45
Переглянути файл
@@ -15,3 +15,48 @@ command = "vscode-json-language-server"
args = ["--stdio"]
initialization-options = { provideFormatter = true }
install-hint = "npm i -g vscode-langservers-extracted"
# Validation is off in vscode-json-language-server unless enabled. Schemas from SchemaStore for
# common configuration files; a `$schema` in the file itself still wins.
[language-servers.settings.json.validate]
enable = true
[[language-servers.settings.json.schemas]]
fileMatch = ["package.json"]
url = "https://json.schemastore.org/package.json"
[[language-servers.settings.json.schemas]]
fileMatch = ["tsconfig.json", "tsconfig.*.json"]
url = "https://json.schemastore.org/tsconfig.json"
[[language-servers.settings.json.schemas]]
fileMatch = ["jsconfig.json", "jsconfig.*.json"]
url = "https://json.schemastore.org/jsconfig.json"
[[language-servers.settings.json.schemas]]
fileMatch = [".eslintrc", ".eslintrc.json"]
url = "https://json.schemastore.org/eslintrc.json"
[[language-servers.settings.json.schemas]]
fileMatch = [".prettierrc", ".prettierrc.json"]
url = "https://json.schemastore.org/prettierrc.json"
[[language-servers.settings.json.schemas]]
fileMatch = [".babelrc", ".babelrc.json", "babel.config.json"]
url = "https://json.schemastore.org/babelrc.json"
[[language-servers.settings.json.schemas]]
fileMatch = ["lerna.json"]
url = "https://json.schemastore.org/lerna.json"
[[language-servers.settings.json.schemas]]
fileMatch = ["turbo.json"]
url = "https://turbo.build/schema.json"
[[language-servers.settings.json.schemas]]
fileMatch = [".swcrc"]
url = "https://swc.rs/schema.json"
[[language-servers.settings.json.schemas]]
fileMatch = ["composer.json"]
url = "https://getcomposer.org/schema.json"
+37
Переглянути файл
@@ -0,0 +1,37 @@
[tools]
node = "22.23.5"
# Use the JS distribution: pnpm's standalone release doesn't cover Intel Macs.
"npm:pnpm" = "11.28.12"
rust = { version = "1.100.0", profile = "minimal", components = ["rustfmt", "clippy"] }
[tasks.setup]
description = "Install frontend dependencies for this worktree"
run = "pnpm install"
[tasks.dev]
description = "Launch the desktop app with worktree isolation"
run = "pnpm tauri dev"
[tasks."dev:app"]
description = "Launch the desktop app with the global Tauri API enabled"
run = "pnpm dev:app"
[tasks.build]
description = "Typecheck, bundle and verify the frontend"
run = "pnpm build"
[tasks.test]
description = "Run the frontend and Rust workspace tests"
run = ["pnpm test", "cargo test --workspace"]
[tasks.check]
description = "Check formatting, lint, types and unused code, then run the tests"
run = [
"pnpm format:check",
"pnpm lint",
"pnpm typecheck",
"pnpm knip",
"cargo fmt --all --check",
"cargo clippy --workspace --all-targets -- -D warnings",
{ task = "test" },
]
+3 -2
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.49",
"version": "0.1.50",
"license": "Apache-2.0",
"type": "module",
"scripts": {
@@ -110,6 +110,7 @@
"tsrs": "^0.20.0-ts7.1.0-beta",
"typescript": "~6.0.3",
"vite": "^8.0.16",
"vitest": "^5.0.5"
"vitest": "^5.0.5",
"yaml": "^2.9.1"
}
}
Створено
+3
Переглянути файл
@@ -211,6 +211,9 @@ importers:
vitest:
specifier: ^5.0.5
version: 5.0.5(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected]))
yaml:
specifier: ^2.9.1
version: 2.9.1
packages:
+195
Переглянути файл
@@ -0,0 +1,195 @@
// @vitest-environment node
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import ts from "typescript";
import { afterEach, describe, expect, it } from "vitest";
import {
describeUnselected,
filterPattern,
importClosure,
readWorkflow,
rustSmokeInputs,
selectedLanguages,
smokeInputs,
unselected,
type Workflow,
} from "./smoke-paths.ts";
const repo = resolve(dirname(fileURLToPath(import.meta.url)), "..");
describe("the Language smoke workflow", () => {
const workflow = readWorkflow(repo);
it("runs every language when a file the frontend smoke loads changes", async () => {
const { files, problems } = await smokeInputs(repo, workflow);
expect(problems).toEqual([]);
expect(describeUnselected(await unselected(workflow, [...files.keys()]), files)).toBe("");
});
it("runs every language when a crate the smoke runs changes", async () => {
const crates = rustSmokeInputs(repo);
expect(describeUnselected(await unselected(workflow, [...crates.keys()]), crates)).toBe("");
});
});
const dirs: string[] = [];
afterEach(() => dirs.splice(0).forEach((dir) => rmSync(dir, { recursive: true, force: true })));
function scratch(files: Record<string, string>): string {
const root = mkdtempSync(join(tmpdir(), "smoke-paths-test-"));
dirs.push(root);
for (const [path, text] of Object.entries(files)) {
mkdirSync(dirname(join(root, path)), { recursive: true });
writeFileSync(join(root, path), text);
}
return root;
}
const options = {
moduleResolution: ts.ModuleResolutionKind.Bundler,
module: ts.ModuleKind.ESNext,
allowImportingTsExtensions: true,
};
describe("importClosure", () => {
it("follows every kind of import to repository files, once each", () => {
const root = scratch({
"smoke/entry.ts": [
'import { a } from "../src/a";',
'import type { T } from "@/types";',
'export * from "../src/reexported";',
'import { invoke } from "pkg/core";',
'import external from "ext";',
'import { readFileSync } from "node:fs";',
'import raw from "../src/data.txt?raw";',
'import styles from "../src/x.module.css";',
'const lazy = () => import("../src/lazy");',
'const icons = import.meta.glob(["../src/icons/*.svg", "!../src/icons/none.svg"]);',
'const worker = new URL("../src/worker.ts", import.meta.url);',
'const folder = new URL("../src", import.meta.url);',
].join("\n"),
"src/a.ts": 'import { b } from "./b";\nexport const a = 1;',
"src/b.ts": 'import { a } from "./a";\nimport "./dir";\nexport const b = a;',
"src/dir/index.ts": "export {};",
"src/types.ts": "export type T = 1;",
"src/core.ts": "export const invoke = 1;",
"src/reexported.ts": "export const r = 1;",
"src/data.txt": "raw",
"src/x.module.css": '@import "./tokens.css";\n@import url("https://example.com/font.css");',
"src/tokens.css": ":root {}",
"src/lazy.ts": "export {};",
"src/icons/a.svg": "<svg/>",
"src/worker.ts": "export {};",
"src/unused.ts": "export {};",
"node_modules/ext/package.json": '{ "name": "ext", "main": "index.js" }',
"node_modules/ext/index.js": "export default 1;",
});
const alias = [
{ find: "@", replacement: join(root, "src") },
{ find: /^pkg\/core$/, replacement: join(root, "src/core.ts") },
];
const { files, problems } = importClosure(root, ["smoke/entry.ts"], alias, options);
expect(problems).toEqual([]);
expect([...files.keys()]).toEqual([
"smoke/entry.ts",
"src/a.ts",
"src/b.ts",
"src/core.ts",
"src/data.txt",
"src/dir/index.ts",
"src/icons/a.svg",
"src/lazy.ts",
"src/reexported.ts",
"src/tokens.css",
"src/types.ts",
"src/worker.ts",
"src/x.module.css",
]);
expect(files.get("src/b.ts")).toBe("imported by src/a.ts");
});
it("reports imports it cannot follow instead of skipping them", () => {
const root = scratch({
"entry.ts": ['import "./missing";', "import(name);", 'import "not-installed";'].join("\n"),
});
expect(importClosure(root, ["entry.ts"], [], options).problems).toEqual([
'entry.ts: cannot resolve "./missing"',
"entry.ts: import() of a computed specifier",
'entry.ts: cannot resolve "not-installed" (not a local file, not an installed package)',
]);
});
});
describe("GitHub path filters", () => {
it("match * within a directory and ** across directories", () => {
expect(filterPattern("src/*.ts").test("src/a.ts")).toBe(true);
expect(filterPattern("src/*.ts").test("src/a/b.ts")).toBe(false);
expect(filterPattern("src/**").test("src/a/b.ts")).toBe(true);
expect(filterPattern("package.json").test("packageXjson")).toBe(false);
});
it("refuse syntax the check does not model", () => {
expect(() => filterPattern("!src/**")).toThrow();
expect(() => filterPattern("src/?.ts")).toThrow();
});
});
describe("the Changes step", () => {
// The shape of language-smoke.yml's step, with a POSIX class JavaScript reads differently.
const step = (arms: string) => `
set -euo pipefail
all="a b"
emit() { tr ' ' '\\n' <<< "$1" | { grep . || true; } | sort -u | jq -Rsc 'split("\\n") | map(select(. != ""))'; }
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then echo "languages=$(emit "$all")" >> "$GITHUB_OUTPUT"; exit 0; fi
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" > files.txt
unused='^src/gen/'
smoke='^src/([[:alpha:]]+\\.ts$|gen/)|^lib/'
langs=""
while read -r f; do
case "$f" in
${arms}
*) if grep -Eq "$smoke" <<< "$f" && ! grep -Eq "$unused" <<< "$f"; then langs="$all"; break; fi ;;
esac
done < files.txt
echo "languages=$(emit "$langs")" >> "$GITHUB_OUTPUT"`;
const workflow = (arms = 'src/only-a.ts) langs+=" a" ;;'): Workflow => ({
on: { pull_request: { paths: ["src/**", "lib/*.ts"] }, push: { paths: ["src/**"] } },
jobs: { changes: { steps: [{ id: "classify", run: step(arms) }] } },
});
it("is run as written, with grep -E", async () => {
expect(await selectedLanguages(workflow(), ["src/app.ts", "src/app2.ts", "src/only-a.ts"])).toEqual(
new Map([
["src/app.ts", ["a", "b"]],
["src/app2.ts", []],
["src/only-a.ts", ["a"]],
]),
);
});
it("decides with the path filters which paths could skip a language", async () => {
const reasons = await unselected(workflow(), [
"src/app.ts",
"src/app2.ts",
"src/gen/x.ts",
"lib/x.ts",
"lib/a/x.ts",
]);
expect(reasons).toEqual(
new Map([
["src/app2.ts", ['not matched by "smoke" in the Changes step']],
["src/gen/x.ts", ['matched by "unused" in the Changes step']],
["lib/x.ts", ["not in on.push.paths"]],
["lib/a/x.ts", ["not in on.pull_request.paths", "not in on.push.paths"]],
]),
);
});
it("fails when a case arm sends a path elsewhere than its patterns say", async () => {
await expect(unselected(workflow("src/app.ts) ;;"), ["src/app.ts"])).rejects.toThrow(
/for src\/app\.ts the Changes step runs no language/,
);
});
});
+512
Переглянути файл
@@ -0,0 +1,512 @@
/**
* What the Language smoke workflow must run for, so that its path selection can be checked
* against it (scripts/smoke-paths.test.ts):
* - the files `pnpm smoke` loads: the import closure of the test files the workflow runs, of the
* Vitest config and of its setup files, resolved as Vite does (its aliases, then TypeScript's
* resolver); the tsconfig files Vite reads to compile them; the dependency manifests;
* - the crates the smoke runs: the workspace dependencies (cargo metadata) of `rustSmoke`.
*
* `node scripts/smoke-paths.ts` lists the inputs a pull request could change without running
* every language; `node scripts/smoke-paths.ts <path>…` the languages a change to each path runs.
*/
import { execFile, execFileSync } from "node:child_process";
import {
existsSync,
globSync,
mkdtempSync,
readFileSync,
realpathSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { builtinModules } from "node:module";
import { availableParallelism, tmpdir } from "node:os";
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { promisify } from "node:util";
import ts from "typescript";
import type { ViteUserConfigExport } from "vitest/config";
import { parse } from "yaml";
const execFileAsync = promisify(execFile);
export const WORKFLOW = ".github/workflows/language-smoke.yml";
/** Inputs that no import reaches: what installs the packages the smoke imports. */
const MANIFESTS = ["package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"];
/**
* Crates the smoke runs, and why; their workspace dependencies run with them. ide-host is the
* exception: it links every crate, and the smoke drives only part of it.
*/
export const rustSmoke: Record<string, string> = {
"ide-host": "openidea-server and the smoke tests (crates/ide-host/tests/language_smoke.rs, project_smoke.rs)",
"ide-lsp": "every code intelligence check of language_smoke.rs",
"ide-dap": "debugging in smoke/debug.test.ts",
"ide-run": "runs and test runs in smoke/run.test.ts",
"ide-sdk": "the SDKs project_smoke.rs detects (jdk, python_venv)",
"ide-tools": "the language servers and debuggers the IDE installs",
"ide-search": "Find Usages candidates (Project::reference_candidates), language_smoke.rs references",
"ide-streams": "debugStreamTrace in smoke/debug.test.ts",
};
export interface Alias {
find: string | RegExp;
replacement: string;
}
export interface Closure {
/** Repository-relative `/`-separated path → what makes it an input (who imports it). */
files: Map<string, string>;
/** Imports that may load repository files but can't be followed. */
problems: string[];
}
const isFile = (path: string) => existsSync(path) && statSync(path).isFile();
const packageName = (spec: string) =>
spec
.split("/")
.slice(0, spec.startsWith("@") ? 2 : 1)
.join("/");
/** Vite's alias rule (@rollup/plugin-alias): the first entry that matches rewrites the specifier. */
function applyAlias(spec: string, alias: Alias[]): string {
const hit = alias.find(({ find }) =>
typeof find === "string" ? spec === find || spec.startsWith(`${find}/`) : find.test(spec),
);
return hit ? spec.replace(hit.find, hit.replacement) : spec;
}
const isImportMeta = (node: ts.Node | undefined, name: string) =>
!!node &&
ts.isPropertyAccessExpression(node) &&
node.name.text === name &&
ts.isMetaProperty(node.expression) &&
node.expression.keywordToken === ts.SyntaxKind.ImportKeyword;
/**
* The repository files `entries` load, transitively: static, type-only and literal dynamic
* imports, re-exports, `import.meta.glob`, `new URL(…, import.meta.url)`, `/// <reference path>`
* and CSS `@import`. Packages and Vite's virtual modules are not repository files; an import that
* might be one but can't be resolved, or is computed at run time, is a problem.
*/
export function importClosure(root: string, entries: string[], alias: Alias[], options: ts.CompilerOptions): Closure {
root = realpathSync(root);
const rel = (file: string) => relative(root, file).split(sep).join("/");
const cache = ts.createModuleResolutionCache(root, (name) => name, options);
const files = new Map<string, string>();
const problems: string[] = [];
const queue: string[] = [];
const add = (file: string, why: string) => {
// Alias targets may name the repository through a symlink (macOS /var → /private/var).
const path = rel(realpathSync(file));
if (path.startsWith("../") || isAbsolute(path)) return problems.push(`${why}: ${file} is outside the repository`);
if (path.split("/").includes("node_modules") || files.has(path)) return;
files.set(path, why);
queue.push(resolve(root, path));
};
const follow = (spec: string, importer: string) => {
const from = `imported by ${rel(importer)}`;
if (/^(virtual:|\0|\/@)/.test(spec) || spec.startsWith("node:") || builtinModules.includes(spec)) return;
const query = spec.indexOf("?");
const path = applyAlias(query < 0 ? spec : spec.slice(0, query), alias);
if (query < 0) {
const hit = ts.resolveModuleName(path, importer, options, ts.sys, cache).resolvedModule;
if (hit) {
add(hit.resolvedFileName, from);
// A declaration file beside the module Vite loads.
if (hit.extension === ts.Extension.Dts) {
const base = hit.resolvedFileName.slice(0, -".d.ts".length);
for (const ext of [".js", ".mjs", ".cjs"]) if (isFile(base + ext)) add(base + ext, from);
}
return;
}
}
// Assets (`./x.css`, `?raw`) and other files TypeScript doesn't resolve as modules.
if (path.startsWith(".") || isAbsolute(path)) {
const file = path.startsWith(".") ? resolve(dirname(importer), path) : isFile(path) ? path : join(root, path);
if (isFile(file)) add(file, from);
else problems.push(`${rel(importer)}: cannot resolve "${spec}"`);
} else if (!existsSync(join(root, "node_modules", packageName(path)))) {
problems.push(`${rel(importer)}: cannot resolve "${spec}" (not a local file, not an installed package)`);
}
};
const globImport = (arg: ts.Expression | undefined, importer: string) => {
const patterns = arg && ts.isArrayLiteralExpression(arg) ? [...arg.elements] : arg ? [arg] : [];
if (!patterns.length || !patterns.every(ts.isStringLiteralLike)) {
return problems.push(`${rel(importer)}: import.meta.glob with computed patterns`);
}
for (const { text } of patterns) {
// Negated patterns only narrow the match.
if (text.startsWith("!")) continue;
const pattern = applyAlias(text, alias);
const cwd = pattern.startsWith("/") && !pattern.startsWith(root) ? root : dirname(importer);
for (const hit of globSync(pattern.startsWith(root) ? pattern : pattern.replace(/^\//, ""), { cwd })) {
const file = resolve(cwd, hit);
if (isFile(file)) add(file, `globbed by ${rel(importer)}`);
}
}
};
const scan = (file: string) => {
const text = readFileSync(file, "utf8");
if (file.endsWith(".css")) {
for (const [, spec] of text.matchAll(/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)) {
if (spec && !/^[a-z]+:\/\//.test(spec)) follow(spec, file);
}
return;
}
if (!/\.[cm]?[jt]sx?$/.test(file)) return;
const tree = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, false);
for (const ref of tree.referencedFiles) {
const target = resolve(dirname(file), ref.fileName);
if (isFile(target)) add(target, `referenced by ${rel(file)}`);
else problems.push(`${rel(file)}: cannot resolve reference "${ref.fileName}"`);
}
const visit = (node: ts.Node): void => {
if (
(ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&
node.moduleSpecifier &&
ts.isStringLiteral(node.moduleSpecifier)
) {
follow(node.moduleSpecifier.text, file);
} else if (
ts.isImportEqualsDeclaration(node) &&
ts.isExternalModuleReference(node.moduleReference) &&
ts.isStringLiteral(node.moduleReference.expression)
) {
follow(node.moduleReference.expression.text, file);
} else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) {
if (ts.isStringLiteral(node.argument.literal)) follow(node.argument.literal.text, file);
} else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
const [arg] = node.arguments;
if (arg && ts.isStringLiteralLike(arg)) follow(arg.text, file);
else problems.push(`${rel(file)}: import() of a computed specifier`);
} else if (ts.isCallExpression(node) && isImportMeta(node.expression, "glob")) {
globImport(node.arguments[0], file);
} else if (
ts.isNewExpression(node) &&
ts.isIdentifier(node.expression) &&
node.expression.text === "URL" &&
isImportMeta(node.arguments?.[1], "url")
) {
// URL resolution: relative to the module even without "./".
const arg = node.arguments?.[0];
const spec = arg && ts.isStringLiteralLike(arg) ? arg.text.replace(/^(?![./])/, "./") : undefined;
if (!spec) problems.push(`${rel(file)}: new URL(…, import.meta.url) of a computed path`);
// A directory (an alias's target, say) is no module: what loads from it is imported on its own.
else if (!existsSync(resolve(dirname(file), spec)) || isFile(resolve(dirname(file), spec))) follow(spec, file);
}
ts.forEachChild(node, visit);
};
visit(tree);
};
for (const entry of entries) {
const file = resolve(root, entry);
if (isFile(file)) add(file, "entry point");
else problems.push(`${entry}: entry point not found`);
}
for (let file = queue.pop(); file; file = queue.pop()) scan(file);
return { files: new Map([...files].sort(([a], [b]) => (a < b ? -1 : 1))), problems };
}
// ---- The workflow ----
interface Step {
id?: string;
run?: string;
}
export interface Workflow {
on: Record<string, { paths?: string[] } | null>;
jobs: Record<string, { steps?: Step[] }>;
}
export function readWorkflow(root: string): Workflow {
return parse(readFileSync(join(root, WORKFLOW), "utf8")) as Workflow;
}
/** A GitHub path filter as a RegExp: `*` is any run of characters but `/`, `**` any run at all. */
export function filterPattern(glob: string): RegExp {
if (/[?+[\]]|^!/.test(glob)) throw new Error(`path filter "${glob}": only * and ** are modelled here`);
const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return new RegExp(
`^${glob
.split("**")
.map((part) => part.split("*").map(escape).join("[^/]*"))
.join(".*")}$`,
);
}
/** The test files the workflow's `pnpm smoke` steps run. */
export function smokeTestFiles(workflow: Workflow): string[] {
const files = new Set<string>();
for (const job of Object.values(workflow.jobs)) {
for (const { run } of job.steps ?? []) {
for (const [, args = ""] of (run ?? "").matchAll(/\bpnpm smoke\b(.*)/g)) {
const named = args.trim().split(/\s+/);
const end = named.findIndex((arg) => arg.startsWith("-"));
const paths = named.slice(0, end < 0 ? undefined : end).filter(Boolean);
if (!paths.length) throw new Error(`${WORKFLOW}: "pnpm smoke${args}" names no test file`);
paths.forEach((path) => files.add(path));
}
}
}
return [...files];
}
function classifyScript(workflow: Workflow): string {
const script = workflow.jobs.changes?.steps?.find((step) => step.id === "classify")?.run;
if (!script) throw new Error(`${WORKFLOW}: no "classify" step in the "changes" job`);
return script;
}
/**
* Runs bash `driver` beside the Changes step (`classify.sh`) and `paths.txt`, as for a pull
* request, then `collect`s from the scratch directory. The driver defines `gh`, which lists the
* pull request's files.
*/
async function runChangesStep<T>(workflow: Workflow, paths: string[], driver: string, collect: (dir: string) => T) {
const dir = mkdtempSync(join(tmpdir(), "smoke-paths-"));
try {
writeFileSync(join(dir, "classify.sh"), classifyScript(workflow));
writeFileSync(join(dir, "paths.txt"), paths.map((path) => `${path}\n`).join(""));
const { stdout } = await execFileAsync("bash", ["--noprofile", "--norc", "-c", driver], {
cwd: dir,
encoding: "utf8",
maxBuffer: 64 << 20,
env: { ...process.env, GITHUB_EVENT_NAME: "pull_request", GITHUB_REPOSITORY: "openidea/openidea", PR: "1" },
});
return { stdout, collected: collect(dir) };
} finally {
rmSync(dir, { recursive: true, force: true });
}
}
/** The Changes step's run, once per path: path → the languages a pull request changing only that path runs. */
export async function selectedLanguages(workflow: Workflow, paths: string[]): Promise<Map<string, string[]>> {
const workers = Math.max(1, Math.min(availableParallelism(), paths.length));
const chunks = Array.from({ length: workers }, (_, i) => paths.filter((_, j) => j % workers === i));
const driver = `
gh() { printf '%s\\n' "$CHANGED"; }
export GITHUB_OUTPUT="$PWD/output"
while IFS= read -r CHANGED; do
: > "$GITHUB_OUTPUT"
( set -eo pipefail; . ./classify.sh ) > /dev/null 2> error
status=$?
printf '%s\\t%s\\t%s\\n' "$CHANGED" "$status" "$(grep '^languages=' "$GITHUB_OUTPUT" | cut -d= -f2-)$(tr '\\n' ' ' < error)"
done < paths.txt`;
const runs = await Promise.all(chunks.map((chunk) => runChangesStep(workflow, chunk, driver, () => undefined)));
const result = new Map<string, string[]>();
for (const line of runs.flatMap(({ stdout }) => stdout.split("\n")).filter(Boolean)) {
const [path = "", status, output = ""] = line.split("\t");
if (status !== "0") throw new Error(`${WORKFLOW}: the Changes step failed for ${path} (exit ${status}): ${output}`);
result.set(path, JSON.parse(output) as string[]);
}
return result;
}
/**
* The Changes step's own `all`, `smoke` and `unused` (set by its bash, never copied here) and the
* paths its `grep -E` matches with each, for every path at once.
*/
async function changesPatterns(workflow: Workflow, paths: string[]) {
const driver = `
gh() { :; }
report() {
printf '%s\\n' "$all" > all
grep -E -- "$smoke" paths.txt > smoke || [ $? -eq 1 ]
grep -E -- "$unused" paths.txt > unused || [ $? -eq 1 ]
}
trap report EXIT
export GITHUB_OUTPUT="$PWD/output"
set -eo pipefail
. ./classify.sh > /dev/null`;
const { collected } = await runChangesStep(workflow, paths, driver, (dir) => {
const lines = (name: string) => readFileSync(join(dir, name), "utf8").split(/\s+/).filter(Boolean);
return { all: lines("all"), smoke: new Set(lines("smoke")), unused: new Set(lines("unused")) };
});
if (!collected.all.length) throw new Error(`${WORKFLOW}: the Changes step's "all" lists no language`);
return collected;
}
/**
* Paths a pull request or push could change without running every language, with why: outside an
* `on.<event>.paths` filter, or not selected for every language by the Changes step.
*
* The step sends a path matching its `smoke` pattern and not its `unused` one, in its last case
* arm, to every language; that decides every path. The step itself also runs for one path per
* directory and outcome, so an earlier arm that takes a directory elsewhere breaks the check.
*/
export async function unselected(workflow: Workflow, paths: string[]): Promise<Map<string, string[]>> {
const reasons = new Map<string, string[]>();
const flag = (path: string, reason: string) => reasons.set(path, [...(reasons.get(path) ?? []), reason]);
for (const event of ["pull_request", "push"]) {
const filters = workflow.on[event]?.paths?.map(filterPattern);
if (!filters) continue;
for (const path of paths) if (!filters.some((filter) => filter.test(path))) flag(path, `not in on.${event}.paths`);
}
const { all, smoke, unused } = await changesPatterns(workflow, paths);
const selects = (path: string) => smoke.has(path) && !unused.has(path);
for (const path of paths) {
if (!smoke.has(path)) flag(path, 'not matched by "smoke" in the Changes step');
else if (unused.has(path)) flag(path, 'matched by "unused" in the Changes step');
}
const sample = new Map<string, string>();
for (const path of paths) {
const key = `${path.slice(0, path.lastIndexOf("/") + 1)}\t${selects(path)}`;
if (!sample.has(key)) sample.set(key, path);
}
for (const [path, languages] of await selectedLanguages(workflow, [...sample.values()])) {
if (all.every((language) => languages.includes(language)) !== selects(path)) {
throw new Error(
`${WORKFLOW}: for ${path} the Changes step runs ${languages.join(" ") || "no language"}, ` +
`not what its "smoke" and "unused" patterns give; update unselected() in scripts/smoke-paths.ts`,
);
}
}
return reasons;
}
// ---- What the smoke depends on ----
/** Every repository file `pnpm smoke` loads or is built from, with why. */
export async function smokeInputs(root: string, workflow: Workflow): Promise<Closure> {
root = realpathSync(root);
const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { scripts?: Record<string, string> };
const configFile = /--config\s+(\S+)/.exec(pkg.scripts?.smoke ?? "")?.[1];
if (!configFile) throw new Error('package.json: the "smoke" script names no --config file');
// Named by the "smoke" script, so only known at run time.
const loaded: { default: ViteUserConfigExport } = await import(pathToFileURL(join(root, configFile)).href);
const config =
typeof loaded.default === "function"
? await loaded.default({ command: "serve", mode: "test" })
: await loaded.default;
const rawAlias = config.resolve?.alias ?? [];
const alias: Alias[] = Array.isArray(rawAlias)
? rawAlias.map(({ find, replacement }) => ({ find, replacement }))
: Object.entries(rawAlias).map(([find, replacement]) => ({ find, replacement }));
const tests = smokeTestFiles(workflow);
const tsconfig = ts.findConfigFile(join(root, dirname(tests[0] ?? ".")), ts.sys.fileExists);
if (!tsconfig) throw new Error(`no tsconfig.json for ${tests[0]}`);
const parsed = ts.getParsedCommandLineOfConfigFile(
tsconfig,
{},
{
...ts.sys,
onUnRecoverableConfigFileDiagnostic: (d) => {
throw new Error(ts.flattenDiagnosticMessageText(d.messageText, "\n"));
},
},
);
const setup = [config.test?.setupFiles ?? []].flat();
const closure = importClosure(root, [...tests, configFile, ...setup], alias, parsed?.options ?? {});
const files = new Map(closure.files);
// Vite compiles each module with the options of its nearest tsconfig.json (and what it extends).
const seen = new Set<string>();
const addConfig = (file: string, why: string) => {
const path = relative(root, file).split(sep).join("/");
if (path.startsWith("../") || seen.has(path)) return;
seen.add(path);
files.set(path, why);
const raw: { extends?: string | string[] } | undefined = ts.readConfigFile(file, ts.sys.readFile).config;
const extended = raw?.extends;
for (const base of [extended ?? []].flat()) {
if (base.startsWith(".")) addConfig(resolve(dirname(file), base), `extended by ${path}`);
}
};
for (const path of closure.files.keys()) {
const config = ts.findConfigFile(join(root, dirname(path)), ts.sys.fileExists);
if (config) addConfig(config, `compiles ${path}`);
}
for (const manifest of MANIFESTS) files.set(manifest, "installs the packages the smoke imports");
const workspace = parse(readFileSync(join(root, "pnpm-workspace.yaml"), "utf8")) as {
patchedDependencies?: Record<string, string>;
};
for (const patch of Object.values(workspace.patchedDependencies ?? {}))
files.set(patch, "patches an installed package");
return { files: new Map([...files].sort(([a], [b]) => (a < b ? -1 : 1))), problems: closure.problems };
}
/** The crates the smoke runs (path of their library root → why), from cargo metadata. */
export function rustSmokeInputs(root: string): Map<string, string> {
const metadata = JSON.parse(
execFileSync("cargo", ["metadata", "--no-deps", "--format-version", "1", "--offline"], {
cwd: root,
encoding: "utf8",
maxBuffer: 64 << 20,
}),
) as {
packages: {
name: string;
manifest_path: string;
dependencies: { name: string; kind: string | null; path?: string }[];
targets: { kind: string[]; src_path: string }[];
}[];
};
const packages = new Map(metadata.packages.map((pkg) => [pkg.name, pkg]));
const why = new Map<string, string>(Object.entries(rustSmoke));
const queue = Object.keys(rustSmoke).filter((name) => name !== "ide-host");
for (let name = queue.pop(); name; name = queue.pop()) {
const pkg = packages.get(name);
if (!pkg) throw new Error(`cargo metadata: no workspace crate ${name}`);
for (const dep of pkg.dependencies) {
if (!dep.path || dep.kind === "dev" || why.has(dep.name)) continue;
why.set(dep.name, `dependency of ${name}`);
queue.push(dep.name);
}
}
const real = realpathSync(root);
const inputs = new Map<string, string>();
for (const [name, reason] of why) {
const pkg = packages.get(name);
if (!pkg) throw new Error(`cargo metadata: no workspace crate ${name}`);
const target = pkg.targets.find((t) => t.kind.includes("lib")) ?? pkg.targets[0];
const path = relative(real, realpathSync(target?.src_path ?? pkg.manifest_path))
.split(sep)
.join("/");
inputs.set(path, `${name}: ${reason}`);
}
return inputs;
}
export function describeUnselected(reasons: Map<string, string[]>, inputs: Map<string, string>): string {
if (!reasons.size) return "";
const lines = [...reasons].map(([path, why]) => ` ${path} (${inputs.get(path)}): ${why.join("; ")}`);
return [
`Language smoke would not run every language for a change to:`,
...lines,
``,
`Add these paths to both on.*.paths and the "smoke" pattern in ${WORKFLOW},`,
`or change the dependency that brings them in.`,
].join("\n");
}
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const workflow = readWorkflow(root);
const asked = process.argv.slice(2);
if (asked.length) {
const filters = workflow.on.pull_request?.paths?.map(filterPattern);
for (const [path, languages] of await selectedLanguages(workflow, asked)) {
const triggered = !filters || filters.some((filter) => filter.test(path));
console.log(`${path}: ${triggered ? languages.join(" ") || "no language" : "not in on.pull_request.paths"}`);
}
} else {
const { files, problems } = await smokeInputs(root, workflow);
const inputs = new Map([...files, ...rustSmokeInputs(root)]);
const report = [...problems, describeUnselected(await unselected(workflow, [...inputs.keys()]), inputs)].filter(
Boolean,
);
console.log(report.join("\n") || `All ${inputs.size} Language smoke inputs run every language.`);
if (report.length) process.exitCode = 1;
}
}
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// The commit being prepared in the window the current command or event came
/// from (the Commit tool window, or the Commit dialog while it is open): the
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Plugin-owned project data sources. Requires database.sources and project trust.
/// Runs on the Database subsystem's host, including on remote project servers.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Editor and project-tree decorations (API 1.4). Requires project.read. An editor set
/// follows its file: the file's own project, or the nearest one when it is outside them all.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// What the pane beside the Services tree shows for a plugin's node.
interface detail-types {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Optional export (world `plugin-diagnostics`): problems in the current,
/// possibly unsaved document, for the languages declared with the
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
interface endpoints-provider {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Workbench events, delivered in batches to `event-handler.handle`.
interface events {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
interface lifecycle {
use types.{context, error};
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// What other plugins contributed to the extension points this plugin declares
/// (`[[extension-points]]` in `plugin.toml`; the contributors list this plugin
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Optional export (world `plugin-file-actions`): quick fixes and
/// refactorings that create, rename or delete files, next to the text edits
+7 -7
Переглянути файл
@@ -1,15 +1,15 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Files outside the open projects: the configuration of the program a
/// plugin integrates with, a tool installed elsewhere, a licence file.
///
/// A plugin's own WASI has no preopened directory. Every path outside its
/// own `plugin-dir` is checked against its `fs.read:<path>` (reading) or
/// `fs.write:<path>`
/// (writing; it doesn't imply reading) grants; without one covering the path a
/// call returns `denied` naming the capability the manifest has to declare. A
/// file inside a project is `workspace.project.read-file` / `write-file`.
/// `path` is absolute, or starts with `~/` for the user's home.
/// own `plugin-dir` and install directory is checked against its
/// `fs.read:<path>` (reading) or `fs.write:<path>` (writing; it doesn't imply
/// reading) grants; without one covering the path a call returns `denied`
/// naming the capability the manifest has to declare. The install directory is
/// read-only. A file inside a project is `workspace.project.read-file` /
/// `write-file`. `path` is absolute, or starts with `~/` for the user's home.
interface fs {
use types.{error};
use workspace.{file-kind, file-stat};
+30 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Writes to the IDE log, tagged with the plugin id.
interface log {
@@ -18,6 +18,27 @@ interface ui {
command: option<string>,
}
/// An action in a status bar item's menu (API 1.14).
record status-menu-action {
/// Up to 256 bytes, one line.
label: string,
/// Secondary text shown after the label, such as a URL (up to 256 bytes).
description: option<string>,
/// The id of a command the plugin declares, run when the entry is chosen.
command: string,
/// Passed to the command as its argument (up to 64 KiB).
argument: option<string>,
}
/// An entry of a status bar item's menu (API 1.14).
variant status-menu-entry {
action(status-menu-action),
/// A line between groups of actions.
separator,
/// A caption above a group (up to 256 bytes, one line).
header(string),
}
record pick-item {
/// Returned when the item is chosen.
key: string,
@@ -90,6 +111,14 @@ interface ui {
set-window-status-item: func(id: string, item: status-item) -> result<_, error>;
/// Removes this window's override, falling back to the global item.
remove-window-status-item: func(id: string) -> result<_, error>;
/// `set-status-item` with a menu (API 1.14): clicking the item opens the
/// menu anchored to it instead of running the item's command, and choosing
/// an action runs its command in that window. At most 64 entries. An empty
/// menu is the same as `set-status-item`. An action naming a command the
/// plugin does not declare fails the call and changes nothing.
set-status-item-menu: func(id: string, item: status-item, menu: list<status-menu-entry>) -> result<_, error>;
/// `set-window-status-item` with a menu, as `set-status-item-menu` (API 1.14).
set-window-status-item-menu: func(id: string, item: status-item, menu: list<status-menu-entry>) -> result<_, error>;
/// Replaces the plugin's console highlight rules (API 1.12); an empty
/// list removes them. Every window applies them to the stdout and stderr
/// lines of its Run and Debug consoles; the plugin never sees the output.
+40
Переглянути файл
@@ -0,0 +1,40 @@
package openidea:[email protected];
/// Optional export (world `plugin-hover-actions`): clickable actions rendered
/// at the left edge of a line and revealed while the pointer is in the leftmost
/// editing-area strip of the action's line range.
interface hover-actions {
use language-features.{document};
/// An action drawn at the left edge of `line`.
record hover-action {
/// The line the button is drawn on; normally the declaration line.
line: u32,
/// First line whose left strip reveals this action, inclusive.
start-line: u32,
/// Last line whose left strip reveals this action, inclusive.
end-line: u32,
/// Optional icon: a registered icon name or a declared manifest SVG path.
icon: option<string>,
/// Text shown when no icon is present, or beside the icon.
label: string,
tooltip: option<string>,
/// This plugin's declared command.
command: string,
argument: option<string>,
}
/// Actions for the visible document, under the editor-provider budget.
hover-actions: func(doc: document) -> list<hover-action>;
}
/// The optional export-only world the SDK merges with `plugin`.
world hover-actions-provider {
export hover-actions;
}
/// The host-side world used to instantiate a component that exports it.
world plugin-hover-actions {
include plugin;
export hover-actions;
}
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Optional export (world `plugin-hover`): Markdown added to the hover of
/// documents of the languages declared with the `hover` provider kind,
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Cross-file associations a plugin publishes for the files it declares under
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Embedded languages. The host routes plugin providers and configured language
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
/// the languages declared with the `inlay-hints` provider kind, including
+9 -5
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Problems in files, shown in the editor and the Problems view.
interface diagnostics {
@@ -150,7 +150,8 @@ interface process {
}
/// What a kept-running program printed since the last call, and its exit
/// code once it ended (`none` while it still runs).
/// code with the last of its output (`none` while it still runs or output
/// is left to read, so the first chunk with a status is the final one).
record chunk {
/// Up to 1 MiB per stream; unpolled output keeps the last 1 MiB.
/// `poll` takes up to `max-bytes`, or one whole character when that
@@ -165,10 +166,13 @@ interface process {
/// (the ninth `start` is `invalid`). They also end with the plugin:
/// stopping, disabling or reclaiming it kills what it started.
resource child {
/// What it printed since the last call, and its status once it ends.
/// What it printed since the last call; the status comes with the
/// chunk that holds the last of its output.
poll: func(max-bytes: u32) -> result<chunk, error>;
/// Waits up to `timeout-ms` for it to end (0 only checks), then
/// reports what it printed since the last call.
/// Waits up to `timeout-ms` for it to end and its output to reach the
/// end (0 only checks), then reports what it printed since the last
/// call. When more is left than one chunk holds, the status comes
/// with a later `poll`.
wait: func(timeout-ms: u32) -> result<chunk, error>;
/// Writes to its stdin; fails once it ended or stdin was closed.
write: func(text: string) -> result<_, error>;
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Additional language features, called only for declared API 1.4 provider kinds.
/// Editor calls have a 50 ms soft / 500 ms hard budget; formatting has 5 seconds.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Discovery of the IDE's built-in MCP server; never exposes its URL or token.
interface mcp {
+1 -1
Переглянути файл
@@ -8,7 +8,7 @@
/// `fs` and `workspace`, and everything else goes through the imports below,
/// gated by the capabilities granted in `plugin.toml` (a missing one returns
/// `error::denied`).
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
world plugin {
import log;
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Editor features a plugin provides for the languages it declares under
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Project-scoped targets owned by the registering plugin (API 1.4).
interface run-targets {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Launches this plugin's configurations in the invoking window's Run tool window.
interface run {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// On-demand results for `[[contributes.searchCategories]]`. Optional, API 1.13.
interface search-provider {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Optional export (world `plugin-semantic-tokens`): semantic colouring of
/// documents of the languages declared with the `semantic-tokens` provider
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
/// as in the editor and LSP.
+4 -3
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
/// Declarative views: tool windows declared
/// under `[[contributes.views]]` and custom editors under
@@ -188,8 +188,9 @@ interface views {
/// Opens `path` (project-relative or absolute, inside the project) in an
/// editor of the window the call came from, the caret at `line` and
/// `column` (0-based; UTF-16 column): a view's links to code.
/// An absolute path inside the plugin's own fs.plugin-dir also works,
/// without project.read or an open project, from a command or event.
/// An absolute path inside the plugin's own fs.plugin-dir or its install
/// directory also works, without project.read or an open project, from a
/// command or event.
open-location: func(path: string, line: u32, column: u32) -> result<_, error>;
}
+4 -3
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:[email protected]3.0;
package openidea:[email protected]4.0;
interface workspace {
use types.{error, location};
@@ -123,8 +123,9 @@ interface editor {
record open-editor { path: string, language: string, dirty: bool, active: bool }
/// Only from commands/events of a window. Requires editor.read.
open-editors: func() -> result<list<open-editor>, error>;
/// Open a project file (project.read) or a file in plugin-dir, selecting a range.
/// Only from commands/events of a window. Paths follow views.open-location.
/// Open a project file (project.read), a file in plugin-dir, or a file in
/// the plugin's install directory, selecting a range. Only from
/// commands/events of a window. Paths follow views.open-location.
open: func(path: string, selection: option<range>) -> result<_, error>;
/// Current version and text of an open project document. Unlike
+4
Переглянути файл
@@ -44,6 +44,8 @@ mod windows;
#[cfg(windows)]
mod windows_error_mode;
#[cfg(windows)]
mod windows_webview_keys;
#[cfg(windows)]
mod windows_webview_recovery;
use parking_lot::Mutex;
@@ -140,6 +142,8 @@ pub fn run() {
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_dialog::init());
#[cfg(windows)]
let app = app.plugin(windows_webview_keys::init());
#[cfg(windows)]
let app = app.plugin(windows_webview_recovery::init());
#[cfg(target_os = "linux")]
let app = app.plugin(linux_window_state::plugin());
+32
Переглянути файл
@@ -0,0 +1,32 @@
//! WebView2's browser accelerator keys. A key the IDE keymap leaves alone otherwise reaches
//! WebView2, which runs its browser feature: Ctrl+F in a view without its own find opens the
//! page's Find bar over the whole window, F3 finds the next match there, Ctrl+P prints, F12 opens
//! DevTools. Turning them off leaves every key to the page; editing keys stay with the webview.
use tauri::{Webview, Wry, plugin};
use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Settings3;
use windows::core::Interface;
pub fn init() -> plugin::TauriPlugin<Wry> {
plugin::Builder::new("webview-keys").on_webview_ready(disable_browser_keys).build()
}
fn disable_browser_keys(webview: Webview) {
let label = webview.label().to_owned();
if let Err(error) = webview.with_webview(move |platform| {
// SAFETY: with_webview runs on the controller's owning STA thread.
let result = unsafe {
platform
.controller()
.CoreWebView2()
.and_then(|core| core.Settings())
.and_then(|settings| settings.cast::<ICoreWebView2Settings3>())
.and_then(|settings| settings.SetAreBrowserAcceleratorKeysEnabled(false))
};
if let Err(error) = result {
tracing::warn!(window = %label, %error, "cannot turn off WebView2 browser keys");
}
}) {
tracing::warn!(window = webview.label(), %error, "cannot access WebView2 controller");
}
}
+2 -2
Переглянути файл
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenIDEA",
"version": "0.1.49",
"version": "0.1.50",
"identifier": "ai.l0ng.openidea",
"build": {
"beforeDevCommand": "pnpm dev",
@@ -26,7 +26,7 @@
}
],
"security": {
"csp": "default-src 'self'; img-src 'self' asset: data: blob: http: https:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src ipc: http://ipc.localhost; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:; frame-src http://127.0.0.1:* openidea-plugin: http://openidea-plugin.localhost; frame-ancestors 'none'"
"csp": "default-src 'self'; img-src 'self' asset: data: blob: http: https:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src ipc: http://ipc.localhost; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:; frame-src http://127.0.0.1:* openidea-plugin: http://openidea-plugin.localhost; frame-ancestors 'none'; base-uri 'self'; form-action 'none'"
}
},
"bundle": {
+30 -4
Переглянути файл
@@ -37,6 +37,7 @@ import { maybeEditorService, type EditorInput } from "@/workbench/contributions"
import { isSameOrInside } from "@/platform/paths";
import { useProject } from "@/platform/project";
import { rootOfPath } from "@/platform/projectRoots";
import { isVirtualUri } from "@/platform/virtualDocs";
import { cornerInset } from "@/editor/core/cm/cornerInset";
export { iconAreaSource, mapLineStart, type IconAreaSource } from "@/editor/core/cm/iconArea";
@@ -788,11 +789,38 @@ export function setLibraryRoots(owner: string, roots: readonly string[]): () =>
}
export function isLibraryPath(path: string): boolean {
if (navigatedLibraryFiles.has(path)) return true;
for (const roots of libraryRoots.values())
for (const r of roots) if (path === r || path.startsWith(r.endsWith("/") ? r : `${r}/`)) return true;
return false;
}
/** Whether `path` lies outside every folder of the open project (or workspace). */
function outsideProject(path: string): boolean {
const project = useProject.getState().project;
if (!project) return false;
const folders = project.workspace ? project.workspace.projects : [project.root];
return !folders.some((root) => isSameOrInside(path, root));
}
/** Files outside the project that code navigation opened: library sources, shown read-only. */
const navigatedLibraryFiles = new Set<string>();
/**
* Opens a code location a language server or the index answered (a declaration, an
* implementation, a documentation link) and selects `selection`. A file outside the project is a
* library source wherever the server keeps it (an SDK, its own cache or bundled stubs, a temporary
* copy), so it opens read-only like the External Libraries' files.
*/
export async function openCodeLocation(
path: string,
selection?: { line: number; col: number },
options: { focus?: boolean } = {},
): Promise<void> {
if (!isVirtualUri(path) && outsideProject(path)) navigatedLibraryFiles.add(path);
await maybeEditorService()?.openFile(path, { selection, focus: options.focus ?? true });
}
/**
* A document outside the project's own code: a server's virtual document (a library class), a
* file under the library roots or in a `node_modules` folder (the library roots list only direct
@@ -806,10 +834,8 @@ export function isLibraryPath(path: string): boolean {
*/
export function isLibrarySource(ctx: Pick<EditorDocContext, "path" | "virtual">): boolean {
if (ctx.virtual || isLibraryPath(ctx.path) || /(^|[\\/])node_modules[\\/]/.test(ctx.path)) return true;
const project = useProject.getState().project;
if (!project) return false;
const folders = project.workspace ? project.workspace.projects : [project.root];
if (!folders.some((root) => isSameOrInside(ctx.path, root))) return true;
if (!useProject.getState().project) return false;
if (outsideProject(ctx.path)) return true;
return rootOfPath(ctx.path)?.kind === "excluded";
}
+56
Переглянути файл
@@ -0,0 +1,56 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const openFile = vi.fn(async () => {});
vi.mock("@/workbench/contributions", async (importOriginal) => ({
...(await importOriginal<typeof import("@/workbench/contributions")>()),
maybeEditorService: () => ({ openFile }),
}));
import { isLibraryPath, isLibrarySource, openCodeLocation } from "./api";
import { useProject } from "@/platform/project";
describe("openCodeLocation", () => {
beforeEach(() => {
openFile.mockClear();
useProject.setState({ project: { root: "/work/app" } as never });
});
// Where language servers keep the library sources they answer with, outside the project.
it.each([
["Java (java-analyzer cache)", "/Users/me/Library/Caches/java-analyzer/sources/src/fe1e/java/util/ArrayList.java"],
["TypeScript (global typescript lib)", "/opt/homebrew/lib/node_modules/typescript/lib/lib.dom.d.ts"],
[
"PHP (Intelephense stubs)",
"/Users/me/Library/Application Support/ide/tools/node_modules/intelephense/lib/stub/standard/standard_2.php",
],
["Kotlin (kotlin-language-server temp copy)", "/private/var/folders/gx/T/kotlinlangserver1146/LocalDate1643.java"],
["Python (interpreter stdlib)", "/Users/me/.pyenv/versions/3.11.5/lib/python3.11/argparse.py"],
])("opens a %s target outside the project as a read-only library source", async (_, path) => {
expect(isLibraryPath(path)).toBe(false);
await openCodeLocation(path, { line: 3, col: 1 });
expect(openFile).toHaveBeenCalledWith(path, { selection: { line: 3, col: 1 }, focus: true });
expect(isLibraryPath(path)).toBe(true);
expect(isLibrarySource({ path, virtual: false })).toBe(true);
});
it("leaves project files and virtual documents editable", async () => {
for (const path of ["/work/app/src/Main.java", "jdt://contents/rt.jar/java.util/ArrayList.class"]) {
await openCodeLocation(path, { line: 0, col: 0 });
expect(isLibraryPath(path)).toBe(false);
}
});
it("does not mark files without an open project", async () => {
useProject.setState({ project: null });
await openCodeLocation("/tmp/elsewhere/notes.txt");
expect(isLibraryPath("/tmp/elsewhere/notes.txt")).toBe(false);
});
it("keeps a workspace's other projects editable", async () => {
useProject.setState({
project: { root: "/work/app", workspace: { projects: ["/work/app", "/work/lib"] } } as never,
});
await openCodeLocation("/work/lib/src/Util.java");
expect(isLibraryPath("/work/lib/src/Util.java")).toBe(false);
});
});
+11 -6
Переглянути файл
@@ -30,6 +30,7 @@ import {
untitledTitle,
} from "@/platform/virtualDocs";
import { editorController, isTextInput, useEditorStatus, useGotoLine, useTabs } from "../controller";
import { languageInfo } from "../cm/languages";
import { useDocMeta, useOutline, type DocMeta } from "../model/document";
import { symbolChain } from "./outline";
import { NavChildrenPopup } from "./NavBarPopup";
@@ -625,13 +626,18 @@ export function IndentStatus() {
const ref = useRef<HTMLButtonElement>(null);
if (!meta) return null;
const { tabSize, insertSpaces } = meta.indent;
const label = insertSpaces ? `${tabSize} spaces` : `Tab (${tabSize})`;
const language = languageInfo(meta.language)?.name;
const title = language ? tx`${language} Code Style` : tx("Code Style");
const spaces = (width: number) => (width === 1 ? tx`${width} space` : tx`${width} spaces`);
const tabs = tx`Tab (${tabSize})`;
const widths = [...new Set(insertSpaces ? [2, 4, 8, tabSize] : [2, 4, 8])].sort((a, b) => a - b);
const label = insertSpaces ? spaces(tabSize) : tabs;
const set = (indent: { tabSize: number; insertSpaces: boolean }) =>
editorController().manager.get(meta.path)?.setIndent(indent);
const choice = (id: string, text: string, indent: { tabSize: number; insertSpaces: boolean }) => ({
id,
label: text,
checked: indent.tabSize === tabSize && indent.insertSpaces === insertSpaces ? true : undefined,
checked: indent.tabSize === tabSize && indent.insertSpaces === insertSpaces,
run: () => set(indent),
});
return (
@@ -650,12 +656,11 @@ export function IndentStatus() {
onClose={() => setOpen(false)}
anchor={ref}
placement="top-end"
title={title}
aria-label="Indentation"
items={[
choice("s2", "2 spaces", { tabSize: 2, insertSpaces: true }),
choice("s4", "4 spaces", { tabSize: 4, insertSpaces: true }),
choice("s8", "8 spaces", { tabSize: 8, insertSpaces: true }),
choice("tab", `Tab (${tabSize})`, { tabSize, insertSpaces: false }),
...widths.map((width) => choice(`s${width}`, spaces(width), { tabSize: width, insertSpaces: true })),
choice("tab", tabs, { tabSize, insertSpaces: false }),
{ kind: "separator" },
{
id: "configure",
+27 -2
Переглянути файл
@@ -131,11 +131,14 @@
.listBody > * {
flex: 1;
}
.centeredList {
.centeredList,
.targetPopup {
min-width: min(360px, 90vw);
}
.centeredList .listMain,
.centeredList .listBody {
.centeredList .listBody,
.targetPopup .listMain,
.targetPopup .listBody {
flex-shrink: 1;
min-height: 0;
}
@@ -212,6 +215,28 @@
font-size: var(--fs-small);
color: var(--fg-subtle);
}
.targetIdentity {
display: flex;
align-items: baseline;
gap: var(--space-1);
min-width: 0;
flex: 1;
}
.targetIdentity .label {
flex: none;
max-width: 100%;
}
.targetContainer,
.targetPath {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
}
.targetPath {
max-width: 44%;
direction: rtl;
}
.shortcut {
flex: none;
font-size: var(--fs-small);
+24 -7
Переглянути файл
@@ -1,4 +1,5 @@
/** React popups for LSP editor features, rendered as a workbench overlay. */
import { openCodeLocation } from "@/editor/api";
import { useEffect, useId, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
import clsx from "clsx";
import {
@@ -22,7 +23,6 @@ import {
T,
} from "@/ui";
import { basename, relativePath, useProject } from "@/platform/project";
import { editorService } from "@/workbench/contributions";
import {
closePopup,
updatePopup,
@@ -122,6 +122,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
const activeRow = rows[activeIndex];
const activeItem = activeRow?.kind === "action" ? activeRow.item : undefined;
const showIcons = !popup.compact || popup.items.some((item) => item.icon || item.symbol);
const hasTargets = popup.items.some((item) => item.target);
// Choosers highlight what the selected row would act on.
useEffect(() => {
@@ -207,6 +208,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
(i.leadingDetail?.length ?? 0) +
(i.preview?.length ?? 0) +
(i.detail?.length ?? 0) +
(i.target ? i.target.path.length + (i.target.container?.length ?? 0) + 3 : 0) +
(i.shortcut?.length ?? 0),
),
);
@@ -257,6 +259,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
aria-label={popup.title}
className={clsx(
styles.listPopup,
hasTargets && styles.targetPopup,
popup.compact && styles.compactListPopup,
hasPreview && styles.withPreview,
previewBelow && styles.previewBelow,
@@ -313,6 +316,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
if (row.kind !== "action") return null;
const { item, match } = row;
const n = popup.numbered && !query ? indexOf(item) + 1 : 0;
const name = <HighlightedText className={styles.label} text={item.label} indices={match} tone="accent" />;
return (
<div
className={clsx(styles.item, item.disabled && styles.disabled, item.emphasis && styles.emphasis)}
@@ -328,13 +332,29 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
)}
{popup.numbered && <span className={styles.mnemonic}>{n > 0 && n <= 9 ? n : ""}</span>}
{showIcons && <ItemIcon item={item} />}
<HighlightedText className={styles.label} text={item.label} indices={match} tone="accent" />
{item.target ? (
<span className={styles.targetIdentity}>
{name}
{item.target.container && (
<span className={styles.targetContainer} title={item.target.container}>
({item.target.container})
</span>
)}
</span>
) : (
name
)}
{item.preview && (
<span className={styles.preview} title={item.preview}>
{item.preview}
</span>
)}
<span className={styles.spacer} />
{!item.target && <span className={styles.spacer} />}
{item.target && (
<span className={styles.targetPath} title={item.target.path}>
<bdi>{item.target.path}</bdi>
</span>
)}
{item.detail && <span className={styles.detail}>{item.detail}</span>}
{item.shortcut && <span className={styles.shortcut}>{item.shortcut}</span>}
{item.submenu?.length ? (
@@ -564,10 +584,7 @@ function DefinitionPopup({ popup }: { popup: Extract<LspPopup, { kind: "definiti
const targetIcon = (path: string) => fileIconName(basename(path), path);
const open = () => {
closePopup();
void editorService().openFile(location.path, {
selection: { line: location.range.start.line, col: location.range.start.col },
focus: true,
});
void openCodeLocation(location.path, { line: location.range.start.line, col: location.range.start.col });
};
const select = (index: number) =>
updatePopup("definition", { index: (index + popup.targets.length) % popup.targets.length });
+4 -9
Переглянути файл
@@ -6,10 +6,11 @@
* F1's documentation instead of a popup while it is open. The hover's
* documentation is the same view with its own history.
*/
import { openCodeLocation } from "@/editor/api";
import { create, createStore, type StoreApi } from "zustand";
import { commands, nextRequestId, type Location } from "@/platform/ipc";
import { hasPrimaryModifier } from "@/platform/keymap";
import { editorService, maybeEditorService, toolWindowService } from "@/workbench/contributions";
import { toolWindowService } from "@/workbench/contributions";
import { closePopup, updatePopup, useLspPopup, type DocEntry } from "./popupStore";
import { isEmptyMarkup, languageForPath, openDocLink, sourceLink, type DocLinkHandler } from "./markdown";
import { resolveGoRef, signatureRef } from "./docLinks/go";
@@ -144,10 +145,7 @@ export async function editDocSource(host: DocHost): Promise<boolean> {
const loc = (await entry?.source?.().catch(() => null)) ?? null;
if (!loc) return false;
closeHost(host);
await editorService().openFile(loc.path, {
selection: { line: loc.range.start.line, col: loc.range.start.col },
focus: true,
});
await openCodeLocation(loc.path, { line: loc.range.start.line, col: loc.range.start.col });
return true;
}
@@ -199,10 +197,7 @@ async function followTo(host: DocHost, target: DocTarget) {
const h = history(host);
if (!entry || !h) {
closeHost(host);
void maybeEditorService()?.openFile(target.path, {
selection: { line: target.line, col: target.col },
focus: true,
});
void openCodeLocation(target.path, { line: target.line, col: target.col });
return;
}
setHistory(host, pushHistory(h, entry));
+2 -6
Переглянути файл
@@ -5,12 +5,11 @@
* offers to disable hints of that kind.
*/
import { StateEffect, StateField, type Extension } from "@codemirror/state";
import { shownAgain } from "@/editor/api";
import { openCodeLocation, shownAgain } from "@/editor/api";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { call, commands, isTauri, type InlayHint } from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { isNavigationGesture, navigationModifierHeld, onNavigationModifier } from "@/platform/navigationModifier";
import { maybeEditorService } from "@/workbench/contributions";
import { showContextMenu, type MenuItem } from "@/ui";
import { useProject } from "@/platform/project";
import { editorPrefs } from "@/platform/editorSettings";
@@ -84,10 +83,7 @@ class InlayWidget extends WidgetType {
if (e.button !== 0 || !isNavigationGesture(e)) return;
e.preventDefault();
e.stopPropagation();
void maybeEditorService()?.openFile(loc.path, {
selection: { line: loc.range.start.line, col: loc.range.start.col },
focus: true,
});
void openCodeLocation(loc.path, { line: loc.range.start.line, col: loc.range.start.col });
});
}
el.appendChild(span);
+2 -5
Переглянути файл
@@ -6,12 +6,12 @@
* The Markdown parser (marked + DOMPurify, ~40 KB gzip) loads on first use and
* is prefetched when the app goes idle; until then markup shows as plain text.
*/
import { openCodeLocation } from "@/editor/api";
import { useMemo, useSyncExternalStore } from "react";
import { LanguageDescription, type Language } from "@codemirror/language";
import { languages } from "@codemirror/language-data";
import { classHighlighter, highlightTree } from "@lezer/highlight";
import type { Markup } from "@/bindings";
import { maybeEditorService } from "@/workbench/contributions";
import { isTauri } from "@/platform/ipc";
import { onOtherShare } from "@/platform/paths";
import { useProject } from "@/platform/project";
@@ -247,10 +247,7 @@ export function sourceLink(href: string): { path: string; line: number; col: num
export function openDocLink(href: string) {
const target = sourceLink(href);
if (target) {
void maybeEditorService()?.openFile(target.path, {
selection: { line: target.line, col: target.col },
focus: true,
});
void openCodeLocation(target.path, { line: target.line, col: target.col });
} else if (/^https?:\/\//.test(href) && isTauri()) {
void import("@tauri-apps/plugin-opener").then((m) => m.openUrl(href)).catch(() => {});
}
+10 -6
Переглянути файл
@@ -51,11 +51,11 @@ import {
whenSynced,
type ContributedDefinition,
type EditorDocContext,
openCodeLocation,
} from "@/editor/api";
import { structure } from "@/editor/structure";
import { executeAction } from "@/platform/actions";
import { basename, relativePath, useProject } from "@/platform/project";
import { editorService } from "@/workbench/contributions";
import { fileIconName } from "@/ui";
import { NO_SERVER, debounce, docOf, isUnavailable, lspDoc, lspRequest, reportLspError } from "./lsp";
import { offsetToPos, rangeContains, rangeToOffsets } from "./positions";
@@ -108,10 +108,7 @@ import {
const highlightsBackoff = featureBackoff();
export async function navigateTo(loc: Location) {
await editorService().openFile(loc.path, {
selection: { line: loc.range.start.line, col: loc.range.start.col },
focus: true,
});
await openCodeLocation(loc.path, { line: loc.range.start.line, col: loc.range.start.col });
}
const NOT_FOUND: Record<GotoKind, string> = {
@@ -210,7 +207,7 @@ export async function locationItems(locs: readonly DeclarationTarget[]): Promise
return rows.map(({ l, where, label, container, indexSymbol }, i) => ({
id: `${i}`,
label: byContainer ? container! : label,
detail: (byContainer ? [where] : [container, where]).filter(Boolean).join(" · "),
target: { container: byContainer ? null : container, path: where },
...(indexSymbol ? { symbol: l.kind! } : { icon: fileIconName(basename(l.path), l.path) }),
location: { path: l.path, line: l.range.start.line },
run: () => navigateTo(l),
@@ -585,6 +582,13 @@ async function gotoResolved(
)
return;
if (superseded()) return;
// ⌘B on a declaration's own name shows its usages also when the server has no definition
// there instead of answering the declaration itself (kotlin-language-server).
if (kind === "definition" && !fromSyntax && (await onDeclarationName(view, offset))) {
if (superseded()) return;
if (!(await executeAction("find.showUsages"))) showHint(view, "No usages found");
return;
}
// The server only resolves what it sees: answer from the project index, which also
// covers attached dependency projects (an unresolved import into them). Never for a
// module path: a segment is not a symbol name.
+22 -23
Переглянути файл
@@ -68,7 +68,7 @@ describe("locationItems", () => {
project("/p");
const item = (await locationItems([target("/p/src/mod.py", "refresh", 3)]))[0]!;
expect(item.label).toBe("refresh");
expect(item.detail).toBe("_StatefulDataset · src/mod.py:4");
expect(item.target).toEqual({ container: "_StatefulDataset", path: "src/mod.py:4" });
// No signature preview line in the row.
expect(item.preview).toBeUndefined();
});
@@ -79,7 +79,7 @@ describe("locationItems", () => {
readManyFileLines.mockResolvedValue(new Map([[path, lines]]));
project("/p");
const item = (await locationItems([target(path, "refresh", 3)]))[0]!;
expect(item.detail).toBe("_StatefulDataset · …/unit_tests/test_data.py:4");
expect(item.target).toEqual({ container: "_StatefulDataset", path: "…/unit_tests/test_data.py:4" });
});
it("does not take the container from a line comment mentioning 'class'", async () => {
@@ -94,8 +94,7 @@ describe("locationItems", () => {
readManyFileLines.mockResolvedValue(new Map([["/p/src/mod.py", lines]]));
project("/p");
const item = (await locationItems([target("/p/src/mod.py", "refresh", 5)]))[0]!;
expect(item.detail).not.toContain("does");
expect(item.detail).toContain("_StatefulDataset");
expect(item.target?.container).toBe("_StatefulDataset");
});
it("does not take the container from a docstring mentioning 'class'", async () => {
@@ -113,9 +112,7 @@ describe("locationItems", () => {
readManyFileLines.mockResolvedValue(new Map([["/p/src/mod.py", lines]]));
project("/p");
const item = (await locationItems([target("/p/src/mod.py", "refresh", 8)]))[0]!;
expect(item.detail).not.toContain("factory");
expect(item.detail).not.toContain("helper");
expect(item.detail).toContain("_StatefulDataset");
expect(item.target?.container).toBe("_StatefulDataset");
});
it("does not open a docstring fence inside a comment", async () => {
@@ -131,7 +128,7 @@ describe("locationItems", () => {
project("/p");
const item = (await locationItems([target("/p/src/mod.py", "refresh", 5)]))[0]!;
// The scan must still reach the class declaration above the comment lines.
expect(item.detail).toContain("_StatefulDataset");
expect(item.target?.container).toBe("_StatefulDataset");
});
it("prefers the index container over the enclosing-type heuristic", async () => {
@@ -155,8 +152,7 @@ describe("locationItems", () => {
project("/p");
const item = (await locationItems([target("/p/src/mod.py", "refresh", 4)]))[0]!;
// The index's answer wins even though the heuristic would answer from the comment.
expect(item.detail).not.toContain("class");
expect(item.detail).toContain("DatasetMixin");
expect(item.target?.container).toBe("DatasetMixin");
});
it("falls back to the enclosing-type heuristic when the index misses", async () => {
@@ -165,7 +161,7 @@ describe("locationItems", () => {
findSymbols.mockResolvedValue([]);
project("/p");
const item = (await locationItems([target("/p/src/mod.py", "refresh", 3)]))[0]!;
expect(item.detail).toContain("_StatefulDataset");
expect(item.target?.container).toBe("_StatefulDataset");
});
it("keeps index symbols' own container detail", async () => {
@@ -184,7 +180,7 @@ describe("locationItems", () => {
])
)[0]!;
expect(item.label).toBe("Configurable");
expect(item.detail).toBe("config · src/mod.py:1");
expect(item.target).toEqual({ container: "config", path: "src/mod.py:1" });
});
it("names same-named targets (a method's implementations) by their containers", async () => {
@@ -197,9 +193,9 @@ describe("locationItems", () => {
);
project("/p");
const items = await locationItems([target("/p/src/a.py", "refresh", 3), target("/p/src/b.py", "refresh", 3)]);
expect(items.map((i) => [i.label, i.detail])).toEqual([
["Cached", "src/a.py:4"],
["Remote", "src/b.py:4"],
expect(items.map((i) => [i.label, i.target])).toEqual([
["Cached", { container: null, path: "src/a.py:4" }],
["Remote", { container: null, path: "src/b.py:4" }],
]);
// A single target, or targets with different names, keep their own names.
expect((await locationItems([target("/p/src/a.py", "refresh", 3)]))[0]!.label).toBe("refresh");
@@ -242,20 +238,20 @@ describe("locationItems", () => {
it("anonymous targets after a closed interface", async () => {
const union = cart[12]!;
const items = await locationItems([at(12, union.indexOf("{")), at(12, union.lastIndexOf("{ kind"))]);
expect(items.map((i) => [i.label, i.detail])).toEqual([
["cart.ts", "src/cart.ts:13"],
["cart.ts", "src/cart.ts:13"],
expect(items.map((i) => [i.label, i.target])).toEqual([
["cart.ts", { container: null, path: "src/cart.ts:13" }],
["cart.ts", { container: null, path: "src/cart.ts:13" }],
]);
});
it("a named target after a closed interface", async () => {
const item = (await locationItems([at(7, cart[7]!.indexOf("CartLine"))]))[0]!;
expect([item.label, item.detail]).toEqual(["CartLine", "src/cart.ts:8"]);
expect([item.label, item.target]).toEqual(["CartLine", { container: null, path: "src/cart.ts:8" }]);
});
it("a member after a closed type, inside its own class", async () => {
const item = (await locationItems([at(17, cart[17]!.indexOf("total"))]))[0]!;
expect([item.label, item.detail]).toEqual(["total", "Cart · src/cart.ts:18"]);
expect([item.label, item.target]).toEqual(["total", { container: "Cart", path: "src/cart.ts:18" }]);
});
it("indentation-delimited bodies: a function after a class, a method after a dict literal", async () => {
@@ -271,12 +267,15 @@ describe("locationItems", () => {
];
readManyFileLines.mockResolvedValue(new Map([["/p/src/mod.py", lines]]));
const items = await locationItems([target("/p/src/mod.py", "load", 3), target("/p/src/mod.py", "main", 6)]);
expect(items.map((i) => i.detail)).toEqual(["Config · src/mod.py:4", "src/mod.py:7"]);
expect(items.map((i) => i.target)).toEqual([
{ container: "Config", path: "src/mod.py:4" },
{ container: null, path: "src/mod.py:7" },
]);
const main = {
...target("/p/src/mod.py", "main", 6),
range: { start: { line: 6, col: 0 }, end: { line: 6, col: 3 } },
};
expect((await locationItems([main]))[0]!.detail).toBe("src/mod.py:7");
expect((await locationItems([main]))[0]!.target).toEqual({ container: null, path: "src/mod.py:7" });
});
it("Go: a method's container is its receiver, declared outside the struct's body", async () => {
@@ -291,7 +290,7 @@ describe("locationItems", () => {
];
readManyFileLines.mockResolvedValue(new Map([["/p/shapes.go", lines]]));
const at = { path: "/p/shapes.go", uri: null, range: { start: { line: 4, col: 17 }, end: { line: 4, col: 21 } } };
expect((await locationItems([at]))[0]!.detail).toBe("Square · shapes.go:5");
expect((await locationItems([at]))[0]!.target).toEqual({ container: "Square", path: "shapes.go:5" });
});
});
+2
Переглянути файл
@@ -18,6 +18,8 @@ export interface ListPopupItem {
section?: { id: string; label?: string };
/** Muted trailing text (file:line, kind…). */
detail?: string;
/** Container beside the symbol name, and the location aligned to the trailing edge. */
target?: { container: string | null; path: string };
/** In its own column before the label (for example, a timestamp). */
leadingDetail?: string;
/** Second line / muted text after the label (code preview). */
+28 -3
Переглянути файл
@@ -417,6 +417,31 @@ describe("navigation wiring", () => {
expect(openFile).not.toHaveBeenCalled();
});
it.each([
["kotlin", "class Library {\n fun lend(isbn: String) = isbn\n}\n", 24, "/p/Library.kt", "function_declaration"],
["java", "class A {\n void lend() {}\n}\n", 17, "/p/A.java", "method_declaration"],
["typescript", "class A {}\nfunction lend() {}\n", 20, "/p/a.ts", "function_declaration"],
])(
"shows usages on a %s declaration whose server answers no definition there",
async (language, text, at, path, declaration) => {
// kotlin-language-server answers nothing on a declaration's own name.
cmd.lspGoto.mockReturnValueOnce(ok([]));
const line = text.slice(0, at).split("\n").length - 1;
const col = at - text.lastIndexOf("\n", at - 1) - 1;
cmd.syntaxNodeAt.mockReturnValueOnce(
ok({
node: node("identifier", r(line, col, col + 4), "name"),
ancestors: [node(declaration, r(line, 0, col + 20))],
}),
);
const view = editor(text, language, at, path);
await gotoTargets(view, "definition");
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
expect(openFile).not.toHaveBeenCalled();
},
);
it("shows usages on a declaration a plugin's index links elsewhere, and follows the link from a call", async () => {
// MyBatis Duo indexes the mapper method's name as a link to its XML statement.
const xml = { path: "/p/UserMapper.xml", range: r(3, 16, 24) };
@@ -586,9 +611,9 @@ describe("navigation wiring", () => {
expect(popup.title).toBe("Choose Declaration of run (2 found, based on syntax)");
expect(popup.pin?.label).toBe("Open in Find Tool Window");
// Same-named candidates read by their containers.
expect(popup.items.map((i) => [i.label, i.symbol, i.detail])).toEqual([
["A", "method", "p/a.ts:4"],
["B", "method", "p/b.ts:4"],
expect(popup.items.map((i) => [i.label, i.symbol, i.target])).toEqual([
["A", "method", { container: null, path: "p/a.ts:4" }],
["B", "method", { container: null, path: "p/b.ts:4" }],
]);
expect(openFile).not.toHaveBeenCalled();
});
+6 -5
Переглянути файл
@@ -56,7 +56,7 @@ describe("Go to Test / Test Subject", () => {
expect(d.open).toHaveBeenCalledWith("/p/src/main/java/a/Foo.java");
});
it("shows a chooser with Create New Test… for several tests, mirrored package first", async () => {
it("shows the mirrored test first and the creation action last", async () => {
const d = deps([
"/p/src/test/java/b/FooTest.java",
"/p/src/test/java/a/FooTests.java",
@@ -64,7 +64,8 @@ describe("Go to Test / Test Subject", () => {
]);
await gotoTestOrSubject("/p/src/main/java/a/Foo.java", "", d);
expect(d.chosen[0]!.title).toBe("Choose Test for Foo (2 found)");
expect(d.chosen[0]!.items.map((i) => i.label)).toEqual(["Create New Test…", "FooTests.java", "FooTest.java"]);
expect(d.chosen[0]!.items.map((i) => i.label)).toEqual(["FooTests.java", "FooTest.java", "Create New Test…"]);
expect(d.chosen[0]!.items.map((i) => i.kind)).toEqual(["target", "target", "create"]);
});
it("offers Create New Test… in the mirrored test package when there is none", async () => {
@@ -104,10 +105,10 @@ describe("Go to Test / Test Subject", () => {
const text = "pub fn lex() {}\n#[cfg(test)]\nmod tests {}\n";
const d = deps(["/p/src/lexer.rs", "/p/tests/lexer.rs"], []);
await gotoTestOrSubject("/p/src/lexer.rs", text, d);
expect(d.chosen[0]!.items.map((i) => i.label)).toEqual(["Create New Test…", "mod tests", "lexer.rs"]);
await d.chosen[0]!.items[1]!.run();
expect(d.open).toHaveBeenCalledWith("/p/src/lexer.rs", text.indexOf("#[cfg"));
expect(d.chosen[0]!.items.map((i) => i.label)).toEqual(["mod tests", "lexer.rs", "Create New Test…"]);
await d.chosen[0]!.items[0]!.run();
expect(d.open).toHaveBeenCalledWith("/p/src/lexer.rs", text.indexOf("#[cfg"));
await d.chosen[0]!.items[2]!.run();
expect(d.createRustTestModule).toHaveBeenCalled();
await gotoTestOrSubject("/p/tests/lexer.rs", "", d);
expect(d.open).toHaveBeenLastCalledWith("/p/src/lexer.rs");
+20 -11
Переглянути файл
@@ -5,6 +5,7 @@
* always, in the chooser) "Create New Test…" creates one from the file templates.
*/
import { basename, dirname } from "@/platform/project";
import { tx } from "@/platform/i18n";
import { isTestFile, rootOfPath } from "@/platform/projectRoots";
import type { RootFolder } from "@/platform/languageSettings";
import {
@@ -17,13 +18,10 @@ import {
testNamesFor,
} from "./testNaming";
export interface ChooserItem {
export type ChooserItem = {
label: string;
detail?: string;
icon?: string;
emphasis?: boolean;
run: () => void | Promise<void>;
}
} & ({ kind: "target"; detail: string } | { kind: "create" });
export interface TestNavDeps {
projectRoot: () => string | null;
@@ -102,6 +100,7 @@ export async function gotoTestOrSubject(path: string, text: string, deps: TestNa
const roots = deps.roots();
const root = deps.projectRoot();
const name = await subjectFileName(path, deps);
const { stem, ext } = splitName(name);
const rank = (paths: string[]) => rankCandidates(path, paths, belowRoot(root, roots));
if (isTestSide(path, roots)) {
@@ -109,13 +108,19 @@ export async function gotoTestOrSubject(path: string, text: string, deps: TestNa
if (subjects.length === 1) return deps.open(subjects[0]!);
if (!subjects.length) return deps.hint("No test subject found");
return deps.choose(
`Choose Test Subject for ${splitName(name).stem} (${subjects.length} found)`,
subjects.map((p) => ({ label: basename(p), detail: relLabel(root, dirname(p)), run: () => deps.open(p) })),
tx`Choose Test Subject for ${stem} (${subjects.length} found)`,
subjects.map((p) => ({
kind: "target",
label: basename(p),
detail: relLabel(root, dirname(p)),
run: () => deps.open(p),
})),
);
}
const tests = rank((await findAll(testNamesFor(name), path, deps)).filter((p) => isTestSide(p, roots)));
const items: ChooserItem[] = tests.map((p) => ({
kind: "target",
label: basename(p),
detail: relLabel(root, dirname(p)),
run: () => deps.open(p),
@@ -123,12 +128,16 @@ export async function gotoTestOrSubject(path: string, text: string, deps: TestNa
// Rust unit tests live in the file's own `#[cfg(test)]` module.
const inFile = path.endsWith(".rs") ? rustTestModuleOffset(text) : null;
if (inFile !== null)
items.unshift({ label: "mod tests", detail: `${name} (#[cfg(test)])`, run: () => deps.open(path, inFile) });
items.unshift({
kind: "target",
label: "mod tests",
detail: `${name} (#[cfg(test)])`,
run: () => deps.open(path, inFile),
});
if (items.length === 1) return void (await items[0]!.run());
const { ext } = splitName(name);
const create: ChooserItem = {
kind: "create",
label: "Create New Test…",
emphasis: true,
run: () =>
path.endsWith(".rs")
? deps.createRustTestModule()
@@ -139,5 +148,5 @@ export async function gotoTestOrSubject(path: string, text: string, deps: TestNa
subject: name,
}),
};
deps.choose(`Choose Test for ${splitName(name).stem} (${items.length} found)`, [create, ...items]);
deps.choose(tx`Choose Test for ${stem} (${items.length} found)`, [...items, create]);
}
+5 -8
Переглянути файл
@@ -5,7 +5,7 @@
*/
import { EditorSelection } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { activeEditor, editorsFor, whenSynced, type EditorDocContext } from "@/editor/api";
import { openCodeLocation, activeEditor, editorsFor, whenSynced, type EditorDocContext } from "@/editor/api";
import { docOf, lspRequest } from "@/editor/lsp/lsp";
import { offsetToPos, posToOffset } from "@/editor/lsp/positions";
import { caretAnchor, openPopup } from "@/editor/lsp/popupStore";
@@ -143,9 +143,9 @@ function testDeps(view: EditorView, ctx: EditorDocContext): TestNavDeps {
items: items.map((it, i) => ({
id: `${i}`,
label: it.label,
detail: it.detail,
emphasis: it.emphasis,
icon: it.emphasis ? "plus" : fileIconName(it.label),
...(it.kind === "create"
? { icon: "plus", section: { id: "create-test" } }
: { icon: fileIconName(it.label), target: { container: null, path: it.detail } }),
run: it.run,
})),
}),
@@ -217,10 +217,7 @@ async function gotoRelated(view: EditorView) {
return;
}
const open = (item: (typeof items)[number]) =>
editorService().openFile(item.path, {
selection: item.line === undefined ? undefined : { line: item.line, col: item.col ?? 0 },
focus: true,
});
openCodeLocation(item.path, item.line === undefined ? undefined : { line: item.line, col: item.col ?? 0 });
if (items.length === 1) {
await open(items[0]!);
return;
+6 -42
Переглянути файл
@@ -121,10 +121,6 @@
.modelControl {
align-items: center;
}
.modelDetail {
box-shadow: inset 1px 0 var(--border);
color: var(--fg-muted);
}
.configPicker > button {
max-width: 100%;
}
@@ -164,6 +160,11 @@
white-space: nowrap;
transition: background var(--dur-fast) var(--ease);
}
.chip.chipLoading,
.chip.chipLoading:hover {
color: var(--fg-muted);
background: none;
}
.chip:hover,
.chip[aria-expanded="true"] {
background: var(--bg-toolbar-hover);
@@ -233,16 +234,6 @@
gap: var(--space-3);
padding: 4px 12px 10px;
}
.modelSettingsHeader {
display: flex;
align-items: center;
gap: var(--space-2);
}
.modelSettingsHeader strong {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.quickRow {
display: flex;
flex-direction: column;
@@ -258,8 +249,7 @@
}
.modelEffortPopup [role="option"]:hover .modelRowConfigure,
.modelEffortPopup [role="option"][aria-selected="true"] .modelRowConfigure,
.modelEffortPopup [role="option"]:focus-within .modelRowConfigure,
.modelEffortPopup [role="option"] .currentRowSettings {
.modelEffortPopup [role="option"]:focus-within .modelRowConfigure {
opacity: 1;
}
.modelRowConfigure {
@@ -274,23 +264,6 @@
color: var(--fg-muted);
cursor: pointer;
}
.modelRowSettings {
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
width: auto;
max-width: 120px;
padding-inline: 4px;
font-size: var(--fs-small);
}
.modelRowSettings span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.modelRowSettings svg {
flex: none;
}
.modelRowConfigure:hover,
.modelRowConfigure:focus-visible {
outline: none;
@@ -419,15 +392,6 @@
text-overflow: ellipsis;
white-space: nowrap;
}
/* The agent picker keeps its icon and truncates its name instead of taking the row. */
.toolbar > :first-child {
flex: 0 1 auto;
min-width: 0;
max-width: 110px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.chipDetail {
display: none;
}
+30 -23
Переглянути файл
@@ -350,7 +350,7 @@ describe("model settings", () => {
expect(onChange).toHaveBeenCalledExactlyOnceWith("reasoning_effort", "xhigh");
});
it("offers more effort levels than fit the segmented control as a dropdown", () => {
it("lists more effort levels than fit the segmented control, one click away", () => {
const onChange = vi.fn();
const config = copilotConfig().map((o) =>
o.category === "thought_level"
@@ -367,9 +367,13 @@ describe("model settings", () => {
fireEvent.click(screen.getByRole("button", { name: "Model settings: Max" }));
const dialog = screen.getByRole("dialog", { name: "Model settings" });
expect(within(dialog).queryByRole("radiogroup", { name: "Effort Level" })).not.toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("button", { name: /Reasoning Effort/ }));
fireEvent.click(screen.getByRole("option", { name: /Extra high/ }));
expect(onChange).toHaveBeenCalledWith("reasoning_effort", "extra-high");
expect(within(dialog).queryByRole("button", { name: /Reasoning Effort/ })).not.toBeInTheDocument();
const levels = within(dialog).getByRole("listbox", { name: "Effort Level" });
expect(within(levels).getByRole("option", { name: /Max/ })).toHaveAttribute("aria-selected", "true");
fireEvent.click(within(levels).getByRole("option", { name: /Extra high/ }));
expect(onChange).toHaveBeenCalledExactlyOnceWith("reasoning_effort", "extra-high");
// The only setting: choosing it is done.
expect(screen.queryByRole("dialog", { name: "Model settings" })).not.toBeInTheDocument();
});
it("tucks Fast into the model popup", () => {
@@ -392,7 +396,7 @@ describe("model settings", () => {
expect(within(dialog).getByRole("switch", { name: "Fast" })).toHaveAttribute("aria-checked", "false");
});
it("opens settings from the selected row without choosing it and returns to a pinnable model list", () => {
it("keeps the model list to models and the settings chip to every model setting", () => {
const onChange = vi.fn();
const cfg = copilotConfig().map((o) =>
o.id === "model"
@@ -417,32 +421,35 @@ describe("model settings", () => {
render(<ConfigPickers config={cfg} onChange={onChange} />);
const model = screen.getByRole("button", { name: "Model" });
expect(model).toHaveTextContent("Claude Sonnet 5.5");
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("medium · 1M");
const settings = screen.getByRole("button", { name: /^Model settings:/ });
expect(settings).toHaveTextContent("medium · 1M");
fireEvent.click(model);
const dialog = screen.getByRole("dialog", { name: "Model" });
expect(within(dialog).queryByText("Balanced")).not.toBeInTheDocument();
expect(within(dialog).getByText("Medium cost")).toBeVisible();
expect(within(dialog).queryByRole("radio")).not.toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("button", { name: "Configure Claude Sonnet 5.5…" }));
expect(onChange).not.toHaveBeenCalled();
const models = screen.getByRole("dialog", { name: "Model" });
expect(within(models).queryByText("Balanced")).not.toBeInTheDocument();
expect(within(models).getByText("Medium cost")).toBeVisible();
expect(within(models).queryByRole("radio")).not.toBeInTheDocument();
expect(within(models).queryByRole("button", { name: /^Configure/ })).not.toBeInTheDocument();
fireEvent.click(within(models).getAllByRole("button", { name: "Pin model" })[0]!);
const listbox = within(models).getByRole("listbox", { name: "Model" });
expect(within(listbox).getByText("Pinned")).toBeVisible();
expect(within(listbox).getByText("Models")).toBeVisible();
fireEvent.click(within(models).getByRole("option", { name: /GPT-6 Sol/ }));
expect(onChange).toHaveBeenCalledExactlyOnceWith("model", "gpt-6-sol");
expect(screen.queryByRole("dialog", { name: "Model" })).not.toBeInTheDocument();
onChange.mockClear();
fireEvent.click(settings);
const dialog = screen.getByRole("dialog", { name: "Model settings" });
expect(within(dialog).queryByRole("button", { name: "Back to models" })).not.toBeInTheDocument();
const effortGroup = within(dialog).getByRole("radiogroup", { name: "Effort Level" });
expect(within(effortGroup).getByRole("radio", { name: "medium" })).toHaveAttribute("aria-checked", "true");
const contextGroup = within(dialog).getByRole("radiogroup", { name: "Context Size" });
expect(within(contextGroup).getByRole("radio", { name: "1M" })).toHaveAttribute("aria-checked", "true");
fireEvent.click(within(contextGroup).getByRole("radio", { name: "200K" }));
expect(onChange).toHaveBeenCalledWith("contextTier", "default");
fireEvent.click(within(dialog).getByRole("button", { name: "Back to models" }));
fireEvent.click(within(dialog).getAllByRole("button", { name: "Pin model" })[0]!);
const listbox = within(dialog).getByRole("listbox", { name: "Model" });
expect(within(listbox).getByText("Pinned")).toBeVisible();
expect(within(listbox).getByText("Models")).toBeVisible();
fireEvent.click(within(dialog).getByRole("option", { name: /GPT-6 Sol/ }));
expect(onChange).toHaveBeenCalledWith("model", "gpt-6-sol");
expect(screen.queryByRole("dialog", { name: "Model" })).not.toBeInTheDocument();
expect(onChange).toHaveBeenCalledExactlyOnceWith("contextTier", "default");
// Several settings: the popup stays for the next one.
expect(screen.getByRole("dialog", { name: "Model settings" })).toBeInTheDocument();
});
it("filters the model list and picks the highlighted model with the keyboard", () => {
+92 -139
Переглянути файл
@@ -7,6 +7,7 @@ import type { AgentConfigOption } from "@/bindings";
import { useTx } from "@/platform/i18n";
import { Icon, IconButton, Popup, Select, T, Toggle } from "@/ui";
import { SelectListbox, type SelectOption } from "@/ui/Select";
import { Spinner } from "@/ui/Spinner";
import { isContextOption, mainOptions, modelConfigOptions, modeIcon } from "./composerModel";
import { togglePinnedModel, useAgents } from "./store";
import styles from "./Composer.module.css";
@@ -76,7 +77,7 @@ function switchValues(option: AgentConfigOption): { on: string; off: string } |
const selected = (option: AgentConfigOption, value: string | null) =>
option.values.find((v) => v.value === value) ?? null;
type ChangeOption = (option: string, value: string, forModel?: string) => void;
type ChangeOption = (option: string, value: string) => void;
interface ModelRefresh {
draft?: boolean;
@@ -86,12 +87,6 @@ interface ModelRefresh {
error: string | null;
onOpen?: () => void;
onRefresh: () => void;
preview?: {
/** Undefined until discovery; an empty array means the agent reported no settings. */
settingsFor: (model: string) => AgentConfigOption[] | undefined;
load: (model: string) => void;
errorFor: (model: string) => string | null | undefined;
};
}
export function ConfigPickers({
@@ -168,11 +163,7 @@ export function ConfigPickers({
) : (
<ConfigPicker option={o} value={valueOf(o)} onChange={onChange} />
)}
{o === model && modelRefresh?.loadingSettings && (
<span className={styles.pickerValue} role="status">
<T>Loading model settings…</T>
</span>
)}
{o === model && !combinedModel && modelRefresh?.loadingSettings && <LoadingSettingsChip />}
</span>
))}
{secondary.length > 0 && (
@@ -261,8 +252,8 @@ function ConfigPicker({
);
}
/** Effort levels that fit the popup's segmented control; more (Codex has six) get a dropdown. */
const SEGMENTED_EFFORT_MAX = 5;
/** Values a setting shows as a segmented control; a longer list (Codex has six effort levels) is listed. */
const SEGMENTED_MAX = 5;
function settingName(option: AgentConfigOption) {
return option.category === "thought_level"
@@ -299,7 +290,8 @@ function ModelPicker({
modelRefresh?: ModelRefresh;
}) {
const tx = useTx();
const [page, setPage] = useState<"models" | { model: string | null } | null>(null);
// The model chip picks a model; the settings chip next to it holds the model's settings.
const [open, setOpen] = useState<"models" | "settings" | null>(null);
const pinnedModels = useAgents((s) => s.pinnedModels);
const anchor = useRef<HTMLSpanElement>(null);
const selectedModel = selected(model, modelValue);
@@ -307,15 +299,12 @@ function ModelPicker({
const modelName = unavailable
? tx`${modelValue} (unavailable)`
: (selectedModel?.name ?? (modelRefresh ? modelValue : null) ?? tx("Default"));
const summary = settingsSummary(settings, tx);
const settingsFor = (id: string | null) =>
id === modelValue ? settings : id ? modelRefresh?.preview?.settingsFor(id) : undefined;
const details = page && page !== "models" && (page.model === modelValue || selected(model, page.model)) ? page : null;
const inspectedModel = details ? selected(model, details.model) : null;
const openModels = () => {
modelRefresh?.onOpen?.();
setPage("models");
const shown = settings.filter((o) => o.values.length > 0);
const summary = settingsSummary(shown, tx);
const toggle = (which: "models" | "settings") => {
if (open === which) return setOpen(null);
if (which === "models") modelRefresh?.onOpen?.();
setOpen(which);
};
return (
@@ -325,46 +314,41 @@ function ModelPicker({
className={styles.chip}
aria-label={tx(model.name)}
aria-haspopup="dialog"
aria-expanded={!!page && !details}
aria-expanded={open === "models"}
title={`${tx(model.name)}: ${modelName}`}
onClick={() => (page && !details ? setPage(null) : openModels())}
onClick={() => toggle("models")}
>
<span className={styles.chipValue}>{modelName}</span>
<Icon name="chevron-down" size={14} className={styles.chipChevron} />
</button>
{summary && !unavailable && (
<button
type="button"
className={clsx(styles.chip, styles.modelDetail)}
aria-label={tx`Model settings: ${summary}`}
title={tx`Configure ${modelName}…`}
aria-haspopup="dialog"
aria-expanded={!!details && details.model === modelValue}
onClick={() => setPage(details && details.model === modelValue ? null : { model: modelValue })}
>
<span className={styles.chipValue}>{summary}</span>
</button>
{!unavailable && modelRefresh?.loadingSettings ? (
<LoadingSettingsChip />
) : (
summary &&
!unavailable && (
<button
type="button"
className={clsx(styles.chip, styles.modelDetail)}
aria-label={tx`Model settings: ${summary}`}
title={tx`Configure ${modelName}…`}
aria-haspopup="dialog"
aria-expanded={open === "settings"}
onClick={() => toggle("settings")}
>
<span className={styles.chipValue}>{summary}</span>
<Icon name="chevron-down" size={14} className={styles.chipChevron} />
</button>
)
)}
<Popup
open={!!page}
open={!!open}
anchor={anchor}
onClose={() => setPage(null)}
aria-label={tx(details ? "Model settings" : "Model")}
onClose={() => setOpen(null)}
aria-label={tx(open === "settings" ? "Model settings" : "Model")}
className={styles.modelEffortPopup}
>
{details ? (
<ModelSettings
key={details.model}
id={details.model}
name={inspectedModel?.name ?? modelName}
settings={settingsFor(details.model)}
modelRefresh={modelRefresh}
onBack={openModels}
onChange={(option, value) => {
if (details.model && details.model !== modelValue) onChange(option, value, details.model);
else onChange(option, value);
}}
/>
{open === "settings" ? (
<ModelSettings settings={shown} onChange={onChange} onDone={() => setOpen(null)} />
) : (
<>
{unavailable && (
@@ -381,16 +365,12 @@ function ModelPicker({
listClassName={styles.modelList}
onChoose={(v) => {
onChange(model.id, v);
setPage(null);
setOpen(null);
}}
renderAction={(opt) => {
const raw = model.values.find((v) => v.value === opt.value);
if (!raw) return null;
const pinned = pinnedModels.includes(raw.value);
const rowSettings = settingsFor(raw.value);
const configurable = rowSettings
? rowSettings.some((o) => o.values.length > 0)
: !!modelRefresh?.preview;
return (
<>
<CostBadge category={raw.costCategory} />
@@ -404,23 +384,6 @@ function ModelPicker({
>
<Icon name="pin" size={12} />
</button>
{configurable && (
<button
type="button"
className={clsx(
styles.modelRowConfigure,
styles.modelRowSettings,
raw.value === modelValue && styles.currentRowSettings,
)}
title={tx`Configure ${opt.label}…`}
aria-label={tx`Configure ${opt.label}…`}
aria-haspopup="dialog"
onClick={() => setPage({ model: raw.value })}
>
{rowSettings && <span>{settingsSummary(rowSettings, tx)}</span>}
<Icon name="chevron-right" size={14} />
</button>
)}
</>
);
}}
@@ -438,82 +401,72 @@ function ModelPicker({
);
}
/**
* The current model's settings (effort, context size, fast mode…), each a click away: an on/off
* setting as a switch, a short list as a segmented control, a longer one listed. A model with
* one setting closes on a choice.
*/
function ModelSettings({
id,
name,
settings,
modelRefresh,
onBack,
onChange,
onDone,
}: {
id: string | null;
name: string;
settings: AgentConfigOption[] | undefined;
modelRefresh?: ModelRefresh;
onBack: () => void;
settings: AgentConfigOption[];
onChange: ChangeOption;
onDone: () => void;
}) {
const tx = useTx();
const attempted = useRef(false);
const lookup = modelRefresh?.preview;
const refreshing = modelRefresh?.refreshing;
useEffect(() => {
if (!id || settings || !lookup || refreshing || attempted.current) return;
attempted.current = true;
lookup.load(id);
}, [id, settings, lookup, refreshing]);
const loading = modelRefresh?.loadingSettings || (!settings && refreshing);
const error = !settings && id && lookup?.errorFor(id);
const only = settings.length === 1;
return (
<div className={styles.quickSettings}>
<div className={styles.modelSettingsHeader}>
<IconButton autoFocus icon="arrow-left" title="Back to models" size="small" onClick={onBack} />
<strong>{name}</strong>
</div>
{loading ? (
<p role="status">
<T>Loading model settings…</T>
</p>
) : error ? (
<p role="alert" className={styles.catalogError}>{tx`Could not refresh models: ${error}`}</p>
) : !settings?.some((o) => o.values.length) ? (
<p role="status">
<T>No settings reported for this model.</T>
</p>
) : (
settings
.filter((o) => o.values.length > 0)
.map((o) => {
const label = tx(settingName(o));
const segmented =
isContextOption(o.id) || (o.category === "thought_level" && o.values.length <= SEGMENTED_EFFORT_MAX);
return (
<div key={o.id} className={styles.quickRow}>
<span className={styles.quickLabel} title={o.description ?? undefined}>
{label}
</span>
{segmented ? (
<SegmentedControl
ariaLabel={label}
options={o.values.map((v) => ({
value: v.value,
label: v.name,
description: v.description ?? undefined,
}))}
value={settingValue(o)!.value}
onChange={(v) => onChange(o.id, v)}
/>
) : (
<ConfigPicker option={o} value={o.current} onChange={onChange} framed />
)}
</div>
);
})
)}
{settings.map((o) => {
const label = tx(settingName(o));
const control = switchValues(o) ? (
<ConfigPicker option={o} value={o.current} onChange={onChange} framed />
) : o.values.length <= SEGMENTED_MAX ? (
<SegmentedControl
ariaLabel={label}
options={o.values.map((v) => ({ value: v.value, label: v.name, description: v.description ?? undefined }))}
value={settingValue(o)!.value}
onChange={(v) => {
onChange(o.id, v);
if (only) onDone();
}}
/>
) : (
<SelectListbox
aria-label={label}
value={settingValue(o)?.value ?? null}
options={o.values.map((v) => ({ value: v.value, label: v.name, detail: v.description ?? undefined }))}
onChoose={(v) => {
onChange(o.id, v);
if (only) onDone();
}}
/>
);
return (
<div key={o.id} className={styles.quickRow}>
<span className={styles.quickLabel} title={o.description ?? undefined}>
{label}
</span>
{control}
</div>
);
})}
</div>
);
}
/** Where the model's settings chip appears once they arrive. */
function LoadingSettingsChip() {
const tx = useTx();
return (
<span className={clsx(styles.chip, styles.chipLoading)} title={tx("Loading model settings…")}>
<Spinner size={12} label={tx("Loading model settings…")} />
</span>
);
}
function ModelRefreshFooter({ refreshing, retryAtMs, error, onRefresh }: ModelRefresh) {
const tx = useTx();
const [now, setNow] = useState(Date.now);
+1 -15
Переглянути файл
@@ -24,7 +24,6 @@ import {
HOME,
NO_COMMANDS,
draftConfig,
draftModelSettings,
refreshProviders,
refreshModels,
setDraftMcpOverrides,
@@ -243,10 +242,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
<ConfigPickers
key={provider?.id}
config={config}
onChange={(option, value, forModel) => {
if (forModel && model) setDraftOption(model.id, forModel);
setDraftOption(option, value);
}}
onChange={setDraftOption}
modelRefresh={
provider?.installed
? {
@@ -259,16 +255,6 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
: null,
error: !requestingModels && currentModelRequest ? (catalog?.error ?? null) : null,
onRefresh: () => void executeAction("agents.refreshModels", null),
preview: {
settingsFor: (id) =>
draftModelSettings(
(catalog ?? provider).thoughtLevels?.[id],
draft.thoughtLevels?.[id],
providerDefaults,
),
load: (id) => void refreshModels(provider.id, false, id),
errorFor: (id) => (requestTarget === id ? catalog?.error : null),
},
}
: undefined
}
+4 -35
Переглянути файл
@@ -511,7 +511,7 @@ it("discovers an uncached model's own settings before its first task and restore
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("option", { name: "small" }));
await waitFor(() => expect(backend.refresh).toHaveBeenLastCalledWith("first", false, "small"));
expect(screen.getByText("Loading model settings…")).toHaveAttribute("role", "status");
expect(screen.getByRole("status", { name: "Loading model settings…" })).toBeVisible();
expect(screen.queryByRole("dialog", { name: "Model" })).not.toBeInTheDocument();
expect(backend.create).not.toHaveBeenCalled();
await act(async () =>
@@ -529,14 +529,14 @@ it("discovers an uncached model's own settings before its first task and restore
),
),
);
expect(screen.queryByText("Loading model settings…")).not.toBeInTheDocument();
expect(screen.queryByRole("status", { name: "Loading model settings…" })).not.toBeInTheDocument();
const settings = screen.getByRole("button", { name: /^Model settings:/ });
expect(settings).toHaveTextContent("medium");
fireEvent.click(settings);
fireEvent.click(screen.getByRole("radio", { name: "max" }));
expect(screen.getByRole("radio", { name: "long_context" })).toBeVisible();
fireEvent.click(screen.getByRole("radio", { name: "long_context" }));
fireEvent.click(screen.getByRole("button", { name: "Back to models" }));
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByTitle("big"));
expect(settings).toHaveTextContent("high");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
@@ -562,41 +562,10 @@ it("does not rediscover a model that explicitly reports no per-model controls",
fireEvent.click(screen.getByTitle(model));
}
expect(backend.refresh).toHaveBeenCalledExactlyOnceWith("first", false, "big");
expect(screen.queryByText("Loading model settings…")).not.toBeInTheDocument();
expect(screen.queryByRole("status", { name: "Loading model settings…" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Reasoning" })).not.toBeInTheDocument();
});
it("inspects uncached settings without switching models or borrowing the current model's levels", async () => {
delete backend.providers[0]!.thoughtLevels!.small;
await connect();
render(<HomeEditor />);
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
const pending = deferred<CatalogReply>();
backend.refresh.mockReturnValueOnce(pending.promise);
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("button", { name: "Configure small…" }));
expect(backend.refresh).toHaveBeenLastCalledWith("first", false, "small");
expect(screen.getByRole("status")).toHaveTextContent("Loading model settings…");
expect(screen.queryByRole("radio")).not.toBeInTheDocument();
await act(async () =>
pending.resolve(
ok(
catalog("first", {
thoughtLevels: {
...catalog().thoughtLevels,
small: [option("effort", "thought_level", ["quick", "thorough"])],
},
}),
),
),
);
expect(screen.getByRole("radio", { name: "quick" })).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Back to models" }));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big");
expect(backend.setConfig).not.toHaveBeenCalled();
expect(backend.create).not.toHaveBeenCalled();
});
it("waits for an unrelated lookup and discovers only the latest selected model", async () => {
backend.providers[0]!.config = [option("model", "model", ["big", "small", "latest"])];
await connect();
+3 -20
Переглянути файл
@@ -162,7 +162,6 @@ export function SessionComposer({
const provider = useAgents((s) => s.providers.find((p) => p.id === task.provider));
const catalog = useAgents((s) => s.modelCatalogs.get(task.provider));
const requestingModels = useAgents((s) => s.modelRequests.has(task.provider));
const requestTarget = useAgents((s) => s.modelRequestTargets.get(task.provider));
const model = task.config.find((o) => o.category === "model");
const catalogModel = (catalog?.config ?? provider?.config)?.find((o) => o.category === "model");
const canRefreshModels =
@@ -230,28 +229,17 @@ export function SessionComposer({
)
.finally(() => setSending(false));
};
const setOption = (id: string, value: string, forModel?: string) => {
const setOption = (id: string, value: string) => {
const pickerModel = pickerConfig.find((o) => o.category === "model");
const changingModel = id === pickerModel?.id;
const loadingModel = !!forModel || (changingModel && !model?.values.some((v) => v.value === value));
const loadingModel = changingModel && !model?.values.some((v) => v.value === value);
const pendingModel = model?.current != null && model.current !== task.model;
const change = loadingModel || (changingModel && configChange.current) || pendingModel ? { loadingModel } : null;
if (change) {
configChange.current = change;
setConfiguring(change);
}
const apply = async () => {
if (forModel && pickerModel) {
await setTaskConfig(task.id, pickerModel.id, forModel);
// A later model choice supersedes both halves of this edit.
const latest = useAgents.getState().tasks.get(task.id);
const selected = latest?.config.find((o) => o.category === "model")?.current ?? latest?.model;
if (configChange.current !== change) return;
if (selected !== forModel) throw new Error(tx("The model changed before its setting could be applied."));
}
await setTaskConfig(task.id, id, value);
};
void apply()
void setTaskConfig(task.id, id, value)
.catch((e: unknown) =>
notifications().notify({
level: "error",
@@ -333,11 +321,6 @@ export function SessionComposer({
error: requestingModels ? null : (catalog?.error ?? null),
onOpen: () => void refreshTaskModels(task.id, false),
onRefresh: () => void executeAction("agents.refreshModels", task.id),
preview: {
settingsFor: (id) => (catalog ?? provider)?.thoughtLevels?.[id],
load: (id) => void refreshTaskModels(task.id, false, id),
errorFor: (id) => (requestTarget === id ? catalog?.error : null),
},
}
: undefined
}
+3 -2
Переглянути файл
@@ -1,8 +1,9 @@
/** "hierarchy" tool window: call hierarchy (⌃⌥H) and type hierarchy (⌃H). */
import { openCodeLocation } from "@/editor/api";
import { useCallback, useMemo, useRef } from "react";
import { create } from "zustand";
import { basename, relativePath, useProject } from "@/platform/project";
import { maybeEditorService, useOccurrenceNavigator } from "@/workbench/contributions";
import { useOccurrenceNavigator } from "@/workbench/contributions";
import {
EmptyState,
IconButton,
@@ -164,7 +165,7 @@ export function HierarchyView() {
};
const show = (n: Node, focus: boolean) => {
const t = targetOf(n);
if (t) void maybeEditorService()?.openFile(t.path, { selection: { line: t.line, col: t.col }, focus });
if (t) void openCodeLocation(t.path, { line: t.line, col: t.col }, { focus });
};
// Every node is an occurrence, as in IDEA's hierarchy views.
+3 -2
Переглянути файл
@@ -2,6 +2,7 @@
* "usages" tool window: Find Usages results grouped by file with line
* previews, one tab per search (pinnable, as the Find tool window's tabs).
*/
import { openCodeLocation } from "@/editor/api";
import { useCallback, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import clsx from "clsx";
import { create } from "zustand";
@@ -11,7 +12,7 @@ import { useEditorPrefs } from "@/platform/editorSettings";
import { BUNDLED_MONO_FAMILY, monoFontFamily } from "@/platform/fonts";
import { shortcutLabel } from "@/platform/keymap";
import { basename, relativeDir, useProject } from "@/platform/project";
import { maybeEditorService, useOccurrenceNavigator } from "@/workbench/contributions";
import { useOccurrenceNavigator } from "@/workbench/contributions";
import {
EmptyState,
Icon,
@@ -143,7 +144,7 @@ export function toggleExcludedUsages(excluded: ReadonlySet<string>, usages: read
}
function openUsage(u: Usage, focus: boolean) {
void maybeEditorService()?.openFile(u.path, { selection: { line: u.line, col: u.col }, focus });
void openCodeLocation(u.path, { line: u.line, col: u.col }, { focus });
}
export function UsagesView() {
+2 -1
Переглянути файл
@@ -1,4 +1,5 @@
/** IPC helpers shared by the code-insight views. */
import { openCodeLocation } from "@/editor/api";
import type { EditorView } from "@codemirror/view";
import { activeEditor, editorsFor, whenSynced } from "@/editor/api";
import { isVirtualUri, virtualDocument } from "@/platform/virtualDocs";
@@ -144,5 +145,5 @@ export async function withDocument<T>(path: string, fn: (doc: number) => Promise
}
export function openLocation(path: string, line: number, col: number): Promise<void> {
return maybeEditorService()?.openFile(path, { selection: { line, col }, focus: true }) ?? Promise.resolve();
return openCodeLocation(path, { line, col });
}
+54 -15
Переглянути файл
@@ -8,24 +8,24 @@
}
.toolbar {
flex: none;
height: var(--h-header);
display: flex;
align-items: center;
gap: var(--space-0-5);
padding: 0 6px;
padding: var(--space-1) 10px;
border-bottom: 1px solid var(--border);
}
.toolbar > * {
flex-shrink: 0;
}
.sep {
flex: none;
width: 1px;
height: 14px;
margin: 0 4px;
margin-inline: var(--space-1);
background: var(--border-strong);
}
.count {
padding: 0 6px;
min-width: 0;
margin-inline: var(--space-1-5);
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
font-size: var(--fs-small);
white-space: nowrap;
@@ -37,9 +37,15 @@
flex: 1;
min-height: 0;
overflow-y: auto;
padding: var(--space-2) var(--space-3);
}
.block {
border-bottom: 1px solid var(--border);
border: 1px solid var(--border);
border-radius: var(--radius-popup-large);
background: var(--bg-editor);
}
.block + .block {
margin-top: 10px;
}
/* The file's header stays at the top while its diff scrolls by. */
.header {
@@ -49,27 +55,47 @@
display: flex;
align-items: center;
gap: var(--space-1);
height: var(--h-header);
padding: 0 6px;
background: var(--bg-elev);
padding: var(--space-3) 10px;
background: var(--bg-editor);
border-bottom: 1px solid var(--border);
border-start-start-radius: inherit;
border-start-end-radius: inherit;
font-size: var(--fs-ui);
}
.name {
.block[data-collapsed] .header {
border-radius: inherit;
border-bottom: 0;
}
.file {
display: flex;
align-items: center;
gap: var(--space-1-5);
min-width: 0;
flex: 1;
}
.file > svg {
flex: none;
font-weight: 500;
white-space: nowrap;
}
.name,
.dir {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.name {
font-weight: 600;
}
.dir {
flex: 1;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.body {
display: flex;
flex-direction: column;
overflow: hidden;
border-end-start-radius: inherit;
border-end-end-radius: inherit;
}
.body[hidden] {
display: none;
@@ -84,3 +110,16 @@
justify-content: center;
color: var(--fg-subtle);
}
:global(:root[data-compact]) .toolbar {
padding-block: 1px;
}
:global(:root[data-compact]) .scroll {
padding: var(--space-1) var(--space-1-5);
}
:global(:root[data-compact]) .header {
padding-block: 7px;
}
:global(:root[data-compact]) .block + .block {
margin-top: var(--space-1);
}
+19 -12
Переглянути файл
@@ -63,7 +63,13 @@ function Block({
const root = useProject((s) => s.project?.root ?? "");
const dir = relativeDir(root, item.path);
return (
<section ref={ref} className={styles.block} data-combined-block={item.path} aria-label={name}>
<section
ref={ref}
className={styles.block}
data-combined-block={item.path}
data-collapsed={collapsed || undefined}
aria-label={name}
>
<div className={styles.header}>
<IconButton
icon={collapsed ? "chevron-right" : "chevron-down"}
@@ -72,16 +78,6 @@ function Block({
aria-expanded={!collapsed}
onClick={onToggle}
/>
<Icon name={fileIconName(name)} size={16} />
<span className={styles.name} style={{ color: KIND_COLOR[kind] }} title={tx(KIND_LABEL[kind])}>
{name}
</span>
{dir && (
<span className={styles.dir} title={item.path}>
{dir}
</span>
)}
<span className={styles.grow} />
<IconButton
icon="diff"
title="Open in Separate Tab"
@@ -97,6 +93,14 @@ function Block({
onClick={() => void editorService().openFile(item.path, { focus: true })}
/>
)}
<span className={styles.sep} aria-hidden="true" />
<div className={styles.file} title={`${item.path}\n${tx(KIND_LABEL[kind])}`}>
<Icon name={fileIconName(name)} size={16} />
<span className={styles.name} style={{ color: KIND_COLOR[kind] }}>
{name}
</span>
{dir && <span className={styles.dir}>{dir}</span>}
</div>
</div>
{/* A collapsed block keeps its loaded diff, hidden: unmounting it would release the
working-tree document and, with autosave off, drop its unsaved edits. */}
@@ -129,7 +133,10 @@ export function CombinedDiffTab({ input }: { input: EditorInput }) {
const scrollTo = (path: string) => {
const el = blocks().find((b) => b.dataset.combinedBlock === path);
const scroller = scrollRef.current;
if (el && scroller) scroller.scrollTop += el.getBoundingClientRect().top - scroller.getBoundingClientRect().top;
if (el && scroller) {
const inset = Number.parseFloat(getComputedStyle(scroller).paddingTop) || 0;
scroller.scrollTop += el.getBoundingClientRect().top - scroller.getBoundingClientRect().top - inset;
}
};
const step = (dir: 1 | -1) => {
const next = items[current() + dir];
+7 -3
Переглянути файл
@@ -1,4 +1,11 @@
{
"Choose Test for {stem} ({count} found)": "Choose Test for {stem} ({count} found)",
"Choose Test Subject for {stem} ({count} found)": "Choose Test Subject for {stem} ({count} found)",
"Code Style": "Code Style",
"{language} Code Style": "{language} Code Style",
"{width} space": "{width} space",
"{width} spaces": "{width} spaces",
"Tab ({tabSize})": "Tab ({tabSize})",
"Timeline": "Timeline",
"At breakpoint": "At breakpoint",
"Replacement preview": "Replacement preview",
@@ -185,9 +192,6 @@
"Effort Level": "Effort Level",
"Model settings": "Model settings",
"Model settings: {summary}": "Model settings: {summary}",
"Back to models": "Back to models",
"No settings reported for this model.": "No settings reported for this model.",
"The model changed before its setting could be applied.": "The model changed before its setting could be applied.",
"Context Size": "Context Size",
"Free": "Free",
"Low cost": "Low cost",
-3
Переглянути файл
@@ -175,9 +175,6 @@
"Effort Level": "Düşünme Düzeyi",
"Model settings": "Model ayarları",
"Model settings: {summary}": "Model ayarları: {summary}",
"Back to models": "Modellere dön",
"No settings reported for this model.": "Bu model için bildirilen ayar bulunmuyor.",
"The model changed before its setting could be applied.": "Ayar uygulanamadan model değişti.",
"Context Size": "Bağlam Boyutu",
"Free": "Ücretsiz",
"Low cost": "Düşük maliyet",
-3
Переглянути файл
@@ -156,9 +156,6 @@
"Effort Level": "思考強度",
"Model settings": "模型設定",
"Model settings: {summary}": "模型設定:{summary}",
"Back to models": "返回模型清單",
"No settings reported for this model.": "此模型未提供可設定的設定。",
"The model changed before its setting could be applied.": "應用設定前,所選模型已發生變化。",
"Context Size": "上下文大小",
"Free": "免費",
"Low cost": "低開銷",
+6 -3
Переглянути файл
@@ -158,9 +158,6 @@
"Effort Level": "思考强度",
"Model settings": "模型设置",
"Model settings: {summary}": "模型设置:{summary}",
"Back to models": "返回模型列表",
"No settings reported for this model.": "此模型未提供可配置的设置。",
"The model changed before its setting could be applied.": "应用设置前,所选模型已发生变化。",
"Context Size": "上下文大小",
"Free": "免费",
"Low cost": "低开销",
@@ -1080,6 +1077,10 @@
"Code Structure": "代码结构",
"Code Folding": "代码折叠",
"Code Style": "代码样式",
"{language} Code Style": "{language} 代码样式",
"{width} space": "{width} 个空格",
"{width} spaces": "{width} 个空格",
"Tab ({tabSize})": "制表符({tabSize})",
"Code breadcrumbs": "代码痕迹导航",
"Collapse": "折叠",
"Collapse All": "全部折叠",
@@ -1231,6 +1232,8 @@
"Create Branch": "创建分支",
"Create New Branch": "创建新分支",
"Create New Test…": "创建新测试…",
"Choose Test for {stem} ({count} found)": "选择 {stem} 的测试(找到 {count} 项)",
"Choose Test Subject for {stem} ({count} found)": "选择 {stem} 的被测代码(找到 {count} 项)",
"Create Patch": "创建补丁",
"Create Patch…": "创建补丁…",
"Create Pull Request": "创建拉取请求",
+30 -1
Переглянути файл
@@ -5,7 +5,7 @@ const openUrl = vi.fn(async (_url: string) => {});
vi.mock("./ipc", () => ({ isTauri: () => true }));
vi.mock("@tauri-apps/plugin-opener", () => ({ openUrl }));
import { openExternalUrl } from "./openUrl";
import { installMiddleClickLinks, openExternalUrl } from "./openUrl";
describe("openExternalUrl", () => {
beforeEach(() => openUrl.mockClear());
@@ -30,3 +30,32 @@ describe("openExternalUrl", () => {
expect(openUrl).not.toHaveBeenCalled();
});
});
describe("middle click on a link", () => {
beforeEach(() => openUrl.mockClear());
const middleClick = (target: Element) => {
const event = new MouseEvent("auxclick", { button: 1, bubbles: true, cancelable: true });
target.dispatchEvent(event);
return event;
};
it("opens a web link in the browser instead of letting the webview navigate (#4992)", async () => {
const off = installMiddleClickLinks();
document.body.innerHTML = '<p><a href="https://example.com/pr/1"><code>#1</code></a><a href="/local">x</a></p>';
const event = middleClick(document.querySelector("code")!);
expect(event.defaultPrevented).toBe(true);
await vi.waitFor(() => expect(openUrl).toHaveBeenCalledWith("https://example.com/pr/1"));
// A link into the app itself is not handed to the browser, nor followed.
expect(middleClick(document.querySelector('a[href="/local"]')!).defaultPrevented).toBe(true);
// Left clicks and other targets are left alone.
const left = new MouseEvent("auxclick", { button: 2, bubbles: true, cancelable: true });
document.querySelector("code")!.dispatchEvent(left);
expect(left.defaultPrevented).toBe(false);
expect(middleClick(document.querySelector("p")!).defaultPrevented).toBe(false);
off();
expect(middleClick(document.querySelector("code")!).defaultPrevented).toBe(false);
expect(openUrl).toHaveBeenCalledTimes(1);
});
});
+18
Переглянути файл
@@ -22,3 +22,21 @@ export async function openExternalUrl(url: string): Promise<void> {
const { openUrl } = await import("@tauri-apps/plugin-opener");
await openUrl(url);
}
/**
* A middle click on a link (`auxclick`) would have the webview open it in a new window or
* navigate this window away from the IDE. A web link opens in the default browser instead,
* as a left click on it does; any other link does nothing.
*/
export function installMiddleClickLinks(target: Document = document): () => void {
const onAuxClick = (e: MouseEvent) => {
if (e.button !== 1 || e.defaultPrevented) return;
const link = (e.target as Element | null)?.closest?.("a[href]");
if (!(link instanceof HTMLAnchorElement)) return;
e.preventDefault();
const url = new URL(link.href, location.href);
if (/^https?:$/.test(url.protocol) && url.origin !== location.origin) void openExternalUrl(url.href);
};
target.addEventListener("auxclick", onAuxClick);
return () => target.removeEventListener("auxclick", onAuxClick);
}
+2
Переглянути файл
@@ -4,6 +4,7 @@ import "./styles/global.css";
import { installRepeatedDoubleClick } from "./platform/doubleClick";
import { installErrorLogging, logError } from "./platform/errorLog";
import { installImeKeyGuard } from "./platform/ime";
import { installMiddleClickLinks } from "./platform/openUrl";
import { call, commands, isTauri } from "./platform/ipc";
import { installPageSwipeTracking } from "./platform/pageSwipe";
import { guessOs } from "./platform/platformInfo";
@@ -49,6 +50,7 @@ export async function installCommonWindowBoot(): Promise<void> {
toggleMaximize: () => call(commands.windowToggleZoom()).catch((e) => console.warn("cannot zoom the window", e)),
});
installPointerFocus();
installMiddleClickLinks();
installImeKeyGuard();
installErrorLogging();
installPageSwipeTracking(window);