diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 566b5f9..32cc8c0 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -43,11 +43,11 @@ jobs: echo "IDEA_263_BUILD=$build" >> "$GITHUB_ENV" echo "IDEA_263_SHA256=$digest" >> "$GITHUB_ENV" - - name: Set up Java 17 + - name: Set up Java 21 uses: actions/setup-java@v5 with: distribution: temurin - java-version: "17" + java-version: "21" cache: gradle - name: Restore the cached 2026.3 verification IDE @@ -120,11 +120,16 @@ jobs: ./gradlew test --tests "org.zoocode.jetbrains.terminal.RawOutputTtyConnectorTest" --tests "org.zoocode.jetbrains.util.JcefSupportTest" + --tests "org.zoocode.jetbrains.util.ExecutablePathTest" + --tests "org.zoocode.jetbrains.ipc.proxy.LazyPromiseTest" --tests "org.zoocode.jetbrains.descriptor.PluginDescriptorTest" --tests "org.zoocode.jetbrains.terminal.TerminalPtyBuilderTest" --tests "org.zoocode.jetbrains.terminal.ShellIntegrationOutputStateTest" --tests "org.zoocode.jetbrains.terminal.TerminalShellReadinessTest" --tests "org.zoocode.jetbrains.editor.EditorFocusIntentTest" + --tests "org.zoocode.jetbrains.editor.WorkspaceEditTest" + --tests "org.zoocode.jetbrains.editor.EditorOpenQueueTest" + --tests "org.zoocode.jetbrains.editor.EditorRoutingContractTest" --tests "org.zoocode.jetbrains.terminal.TerminalWidgetVisibilityTest" --tests "org.zoocode.jetbrains.ui.WebViewMountPlanTest" --tests "org.zoocode.jetbrains.util.FocusRequestEpochTest" @@ -143,14 +148,42 @@ jobs: shell: bash run: ./gradlew verifyPackagedBytecode --no-configuration-cache + - name: Record the plugin artifact checksum + working-directory: jetbrains_plugin + run: sha256sum build/distributions/*.zip > build/plugin-sha256.txt + + - name: Verify plugin compatibility with the minimum IDEA 2026.1.5.1 + working-directory: jetbrains_plugin + run: > + ./gradlew verifyPlugin smoke263Dispatch + -PsmokeVerifiedIde=true + -PverifierReportsDir=build/reports/pluginVerifier/261 + --no-configuration-cache + + - name: Verify plugin compatibility with WebStorm 2026.2.1 + working-directory: jetbrains_plugin + run: > + ./gradlew verifyPlugin smoke263Dispatch + -PsmokeVerifiedIde=true + -PverifierType=WS + -PverifierVersion=2026.2.1 + -PverifierReportsDir=build/reports/pluginVerifier/262 + --no-configuration-cache + - name: Verify plugin compatibility with the exact IDEA 2026.3 build working-directory: jetbrains_plugin shell: bash run: > - ./gradlew runPluginVerifier + ./gradlew verifyPlugin smoke263Dispatch + -PsmokeVerifiedIde=true -PverifierLocalIde="build/ideaIC-${IDEA_263_BUILD}" + -PverifierReportsDir=build/reports/pluginVerifier/263 --no-configuration-cache + - name: Confirm verification used the recorded artifact + working-directory: jetbrains_plugin + run: sha256sum --check build/plugin-sha256.txt + - name: Smoke check the 2026.3 createTtyConnector dispatch working-directory: jetbrains_plugin shell: bash @@ -159,6 +192,16 @@ jobs: -PsmokeLocalIde="build/ideaIC-${IDEA_263_BUILD}" --no-configuration-cache + - name: Store compatibility reports and artifact identity + if: always() + uses: actions/upload-artifact@v4 + with: + name: plugin-verifier-${{ github.sha }} + path: | + jetbrains_plugin/build/reports/pluginVerifier/** + jetbrains_plugin/build/plugin-sha256.txt + if-no-files-found: warn + windows-verify: name: Windows terminal tests and PowerShell 5.1 smoke runs-on: windows-latest @@ -181,17 +224,17 @@ jobs: Checkout: $env:GITHUB_WORKSPACE Tested commit: $(git rev-parse HEAD) OS: windows-latest - JDK: temurin 17 + JDK: temurin 21 Run: $env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/actions/runs/$env:GITHUB_RUN_ID "@ Write-Output $identity Set-Content -Path windows-run-identity.txt -Value $identity - - name: Set up Java 17 + - name: Set up Java 21 uses: actions/setup-java@v5 with: distribution: temurin - java-version: "17" + java-version: "21" cache: gradle # The same build-only fixtures the Linux job creates: the Gradle build @@ -228,6 +271,10 @@ jobs: '--tests org.zoocode.jetbrains.terminal.ShellIntegrationOutputStateTest' '--tests org.zoocode.jetbrains.terminal.TerminalShellReadinessTest' '--tests org.zoocode.jetbrains.terminal.WindowsConPtyProcessTest' + '--tests org.zoocode.jetbrains.editor.WorkspaceEditTest' + '--tests org.zoocode.jetbrains.editor.EditorOpenQueueTest' + '--tests org.zoocode.jetbrains.editor.EditorRoutingContractTest' + '--tests org.zoocode.jetbrains.util.ExecutablePathTest' '--no-configuration-cache' ) cmd /c "gradlew.bat $($taskList -join ' ') 2>&1" | Tee-Object -FilePath ..\windows-test-log.txt @@ -263,7 +310,7 @@ jobs: if: always() uses: actions/upload-artifact@v4 with: - name: windows-pr-results-${{ github.sha }}-windows-latest-jdk17 + name: windows-pr-results-${{ github.sha }}-windows-latest-jdk21 path: | jetbrains_plugin/build/test-results/test/*.xml jetbrains_plugin/build/reports/tests/test/** diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7fbe4f0..44e6f30 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -157,11 +157,11 @@ jobs: fi echo "IDEA_263_SHA256=$digest" >> "$GITHUB_ENV" - - name: Set up Java 17 + - name: Set up Java 21 uses: actions/setup-java@v5 with: distribution: temurin - java-version: "17" + java-version: "21" cache: gradle - name: Set up Node.js @@ -223,10 +223,9 @@ jobs: -PpluginVersion="$VERSION" --no-configuration-cache - # gradle-intellij 1.x resolves verification targets from release feeds only, so the - # 2026.3 EAP build is fetched from the IntelliJ snapshots repository, checked - # against the pinned SHA-256, cached, and handed to runPluginVerifier through - # -PverifierLocalIde. The build number lives in jetbrains_plugin/gradle.properties. + # The upper-bound verification SDK is downloaded once, checksum-checked, + # cached, and supplied through -PverifierLocalIde. Compilation still uses + # the minimum SDK configured in jetbrains_plugin/gradle.properties. - name: Restore the cached 2026.3 verification IDE id: idea263-cache uses: actions/cache@v4 @@ -253,6 +252,36 @@ jobs: } unzip -q "$ide_zip" -d "$ide_dir" + - name: Record the plugin artifact checksum + working-directory: jetbrains_plugin + run: sha256sum build/distributions/*.zip > build/plugin-sha256.txt + + - name: Verify plugin compatibility with the minimum IDEA 2026.1.5.1 + working-directory: jetbrains_plugin + env: + VERSION: ${{ needs.prepare.outputs.version }} + run: > + ./gradlew verifyPlugin smoke263Dispatch + -PsmokeVerifiedIde=true + -PdebugMode=release + -PvscodePlugin=zoo-code + -PpluginVersion="$VERSION" + -PverifierReportsDir=build/reports/pluginVerifier/261 + --no-configuration-cache + + - name: Verify plugin compatibility with WebStorm 2026.2.1 + working-directory: jetbrains_plugin + run: > + ./gradlew verifyPlugin smoke263Dispatch + -PsmokeVerifiedIde=true + -PdebugMode=release + -PvscodePlugin=zoo-code + -PpluginVersion="${{ needs.prepare.outputs.version }}" + -PverifierType=WS + -PverifierVersion=2026.2.1 + -PverifierReportsDir=build/reports/pluginVerifier/262 + --no-configuration-cache + - name: Verify plugin compatibility with IDEA 2026.3 working-directory: jetbrains_plugin env: @@ -260,13 +289,18 @@ jobs: shell: bash run: | verifier_build="$(sed -n 's/^idea263Build=//p' gradle.properties)" - ./gradlew runPluginVerifier \ + ./gradlew verifyPlugin \ -PdebugMode=release \ -PvscodePlugin=zoo-code \ -PpluginVersion="$VERSION" \ -PverifierLocalIde="build/ideaIC-${verifier_build}" \ + -PverifierReportsDir=build/reports/pluginVerifier/263 \ --no-configuration-cache + - name: Confirm verification used the recorded artifact + working-directory: jetbrains_plugin + run: sha256sum --check build/plugin-sha256.txt + # The verifier cannot see a silently non-overriding createTtyConnector # signature; this step proves the dispatch binds on the exact downloaded build. - name: Smoke check the 2026.3 createTtyConnector dispatch @@ -283,6 +317,16 @@ jobs: -PsmokeLocalIde="build/ideaIC-${verifier_build}" \ --no-configuration-cache + - name: Store compatibility reports and artifact identity + if: always() + uses: actions/upload-artifact@v4 + with: + name: release-plugin-verifier-${{ github.sha }} + path: | + jetbrains_plugin/build/reports/pluginVerifier/** + jetbrains_plugin/build/plugin-sha256.txt + if-no-files-found: warn + - name: Publish to JetBrains Marketplace if: needs.prepare.outputs.marketplace-published != 'true' env: diff --git a/.github/workflows/windows-chat-focus.yml b/.github/workflows/windows-chat-focus.yml index adea37d..7d3136e 100644 --- a/.github/workflows/windows-chat-focus.yml +++ b/.github/workflows/windows-chat-focus.yml @@ -52,7 +52,7 @@ jobs: - uses: actions/setup-java@v5 with: distribution: temurin - java-version: "17" + java-version: "21" cache: gradle - uses: actions/setup-node@v6 with: @@ -90,8 +90,8 @@ jobs: fail-fast: false matrix: include: - - ide: "2025.3" - sha256: "6f7234b57444371c3af02ab31a15f76dd1d6e5e32eaabc96722777a9addcd023" + - ide: "2026.1.5.1" + sha256: "997dcdaddde05e31d3428e4385fd178f720dfa6dbaebc4203b2ba27c0fca3153" - ide: "2026.2.1" sha256: "8aa16db629952300ab74d2d5e095150d1a534593e65bbbbd795b859759c00cbc" defaults: diff --git a/.gitignore b/.gitignore index b441d87..7e64709 100644 --- a/.gitignore +++ b/.gitignore @@ -63,3 +63,7 @@ plans/ # Generated test reports test-results/ + +# IntelliJ Platform Gradle plugin local artifacts and sandbox +jetbrains_plugin/.intellijPlatform/ +jetbrains_plugin/.kotlin/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..8a1a9b5 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,19 @@ +# Repository working rules + +## Complete the requested scope + +- Treat the linked issue's acceptance criteria and the user's reported findings as the task scope. Account for every item before describing the issue as resolved. +- Do not substitute documentation of limitations, a successful build, passing UI tests, or a Plugin Verifier `Compatible` verdict for the requested API migration. +- If only part of the work is complete, report it as partial. Identify the remaining symbols, evidence, and concrete next steps. Do not close the issue or use closing PR keywords until its acceptance criteria are met. +- Preserve regression coverage tied to specific reported issues, including the product under test. A baseline change does not justify silently replacing WebStorm coverage with IDEA coverage. Flag any supported-range conflict explicitly. +- Investigate practical compatibility implementations and version-specific builds before concluding that the oldest supported SDK prevents a fix. Do not silently raise the minimum IDE or Java version. + +## IntelliJ API and publication checks + +- Published plugin code must not reference IntelliJ APIs annotated `ApiStatus.Internal` or `IntellijInternalApi`. Do not hide such dependencies through reflection, suppression, verifier exclusions, or copied implementation code that still depends on internal APIs. +- For migrations, consult current JetBrains documentation and source, then confirm API availability, annotations, and JVM signatures in the actual supported SDKs. Upstream master alone does not establish release compatibility. +- Prioritize internal and scheduled-for-removal usages. Preserve the existing chat typing/focus behavior when replacing editor-opening APIs; switching back to synchronous opening requires regression evidence. +- Release verification must fail on internal API usages. If the gate is missing, implement it as part of publication-related API work. Report scheduled-for-removal, deprecated, and experimental findings separately; do not describe a report containing findings as clean. +- Verify the exact distributable ZIP against the declared supported IDE range, including the reported failing target when available. Record plugin version, artifact SHA-256, IDE builds, verifier version, and results. Clearly distinguish saved reports from new runs. +- Run behavior checks appropriate to the migration, including native typing/file/diff/terminal regressions for focus-sensitive changes. Honor explicit environment approval requirements for opt-in live suites. +- If no suitable public API exists, prepare a concrete upstream replacement request and track the unresolved release constraint. Do not send it externally without user authorization. Documentation alone does not complete the migration. diff --git a/BUILD.md b/BUILD.md index b665ff2..aa6a1b1 100644 --- a/BUILD.md +++ b/BUILD.md @@ -2,6 +2,17 @@ This directory contains the build and maintenance scripts for the Zoo Code JetBrains project. These scripts follow open source conventions and provide a unified interface for project operations. +## Supported build environment + +This release line targets IntelliJ Platform **261.27258.136 through 263.*** +(2026.1.5.1 through the 2026.3 branch) and requires **JDK 21**. Use the committed +Gradle 9.2.1 wrapper. Older IDEs must use an earlier Zoo Code release. + +The default SDK is pinned in `jetbrains_plugin/gradle.properties`. For a local +unpacked copy of the same SDK, pass `-PplatformLocalIde=/path/to/idea`. +Run `./gradlew verifyPlugin -PverifierLocalIde=/path/to/idea` from +`jetbrains_plugin` to check the distributable; internal API findings fail the task. + ## Quick Start ### Linux/macOS diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c61d6c0..72cb89e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -39,7 +39,7 @@ Before you begin, ensure you have the following installed: - **npm**: Version 8.0.0 or later (comes with Node.js) - **Git**: Any recent version - **JDK**: Version 17 or later (for JetBrains plugin development) -- **JetBrains IDE**: IntelliJ IDEA 2023.1+ (for testing) +- **JetBrains IDE**: IntelliJ IDEA 2026.1.5.1+ within the supported platform range (for testing) ### Optional Tools @@ -100,7 +100,7 @@ cd jetbrains_plugin 1. Open the project root directory in IntelliJ IDEA 2. Import the Gradle project from `jetbrains_plugin/` -3. Configure JDK 17+ in Project Settings +3. Configure JDK 21 in Project Settings 4. Install recommended plugins: - Kotlin - Gradle diff --git a/README.md b/README.md index d13bf4e..47757f9 100644 --- a/README.md +++ b/README.md @@ -70,16 +70,16 @@ Zoo Code supports JetBrains IDEs based on the IntelliJ Platform, including: - GoLand - DataGrip - Rider -- Android Studio **2026.1.4 or newer** (currently available as a preview) +- Android Studio builds meeting the platform range below, with JCEF -The plugin targets IntelliJ Platform build **233** (JetBrains 2023.3) or newer. Android Studio requires version **2026.1.4 or newer** because that release includes the JCEF support required by Zoo Code. At present, Android Studio 2026.1.4 is available through the preview channel. +The plugin targets IntelliJ Platform build **261.27258.136** (JetBrains 2026.1.5.1) through **263.***. Android Studio must also meet this platform build range and include JCEF; older Android Studio builds cannot install this release. ## Requirements ### Using the plugin -- A supported JetBrains IDE based on IntelliJ Platform build 233 or newer -- Android Studio 2026.1.4 or newer when using Android Studio; install a preview build until this version reaches the stable channel +- A supported JetBrains IDE based on IntelliJ Platform build 261.27258.136 through 263.* +- Android Studio must use IntelliJ Platform build 261.27258.136 through 263.* and include JCEF - A JCEF-enabled IDE runtime, which Zoo Code requires to render its interface Where JCEF support comes from depends on the IDE version. From IntelliJ Platform 2026.2 (build 262), JCEF ships as a separate bundled plugin. If that plugin is missing or disabled, Zoo Code shows a warning notification and the Zoo Code tool window cannot render. Enable the bundled JCEF plugin under **Settings → Plugins → Installed** and restart the IDE. On IDEs older than 2026.2, JCEF comes from the IDE runtime; see [Known Issues](docs/KNOWN_ISSUES.md). @@ -89,7 +89,7 @@ On first launch the plugin automatically downloads a pinned, platform-specific N ### Building from source - Node.js 20.6.0 or newer and npm -- JDK 17 or newer +- JDK 21 - Git - Bash - `curl` or `wget` diff --git a/README_zh.md b/README_zh.md index 7a7a235..a06cd66 100644 --- a/README_zh.md +++ b/README_zh.md @@ -41,7 +41,7 @@ Zoo Code JetBrains 目前支持以下 JetBrains IDE 系列: - **Rider** - .NET 开发 - **Android Studio** - Android 开发 -> **注意**:为了获得最佳兼容性,需要 JetBrains IDE 版本 2023.1 或更高版本。 +> **注意**:为了获得最佳兼容性,需要 IntelliJ Platform 261.27258.136 至 263.*(2026.1.5.1 起)。 ## 🏗️ 架构 @@ -114,9 +114,9 @@ graph TB #### 前置条件 - Node.js 18.0+ -- JetBrains IDE 2023.1+ +- JetBrains IDE:IntelliJ Platform 261.27258.136 至 263.*(2026.1.5.1) - Git -- JDK 17+ +- JDK 21 #### 构建步骤 @@ -176,7 +176,7 @@ Zoo Code JetBrains/ ### 技术栈 - **扩展宿主**:Node.js 18+、TypeScript 5.0+ -- **JetBrains 插件**:Kotlin 1.8+、IntelliJ Platform 2023.1+ +- **JetBrains 插件**:Kotlin 2.2、IntelliJ Platform 261.27258.136 至 263.* - **通信**:基于 Unix Domain Sockets/Named Pipes 的 RPC - **构建工具**:npm/pnpm、Gradle、Shell 脚本 diff --git a/docs/KNOWN_ISSUES.md b/docs/KNOWN_ISSUES.md index cd6eb8f..32a84ab 100644 --- a/docs/KNOWN_ISSUES.md +++ b/docs/KNOWN_ISSUES.md @@ -4,7 +4,50 @@ This document records the known issues, limitations, and solutions for the Zoo C The 3.96.0 Marketplace API warnings and JCEF compatibility work are tracked in [issue #16](https://github.com/Zoo-Code-Org/Zoo-Code-Jetbrains/issues/16). -Release verification and the internal/experimental editor API migration remain open. +The additional reupload warnings are tracked in +[issue #18](https://github.com/Zoo-Code-Org/Zoo-Code-Jetbrains/issues/18). + +### API migration and supported versions + +The current branch targets IntelliJ Platform **261.27258.136 through +263.*** (2026.1.5.1 through the 2026.3 branch), with Java 21. Older IDEs must use +an earlier plugin release. The maintainer approved raising the minimum on 2026-11-12 to remove the +internal editor-opening dependency without maintaining separate release lines. +The [compatibility decision](validation/editor-api-migration.md#supported-baseline-decision) +records the released 233 API and version-specific build options considered. + +Normal-file opens and preserving diff opens now use public `NavigationRequest` +and `NavigationService` APIs with an explicit focus request. A negative offset +preserves the caret and permits virtual diff files. The platform handles +suspending editor loading internally; the plugin does not reference +`FileEditorOpenOptions` or the internal `FileEditorManagerEx.openFile` overload. +There is no reflective internal API fallback. Deliberate diff opens retain the +diff helper path. + +The build uses IntelliJ Platform Gradle Plugin 2.x and Java/Kotlin 21 toolchains. +PR and release verification fail on internal API usages as well as binary +compatibility problems. The supported range is bounded to `263.*` pending verification of later IDE branches. + +The proxy settings and terminal customizer migrations in #18 remain separate +unfinished work. Raising the baseline makes their modern replacements available; +it does not itself eliminate those deprecations. The old process-based terminal +runner overrides were removed in favor of the startup-options connector hook. + +See JetBrains' [public navigation API](https://github.com/JetBrains/intellij-community/blob/idea/261.27258.136/platform/platform-api/src/com/intellij/platform/ide/navigation/NavigationService.kt), +[internal API migration guidance](https://plugins.jetbrains.com/docs/intellij/api-internal.html), +and [multi-version guidance](https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html#targeting-multiple-ide-versions). + +Historical verification on 2026-11-09 used the previous 2023.3-based ZIP with +Plugin Verifier 1.410 against IC-233.11799.241 and IC-263.5701.42. Both reported +compatible; the latter still reported 3 internal, 9 scheduled-for-removal, and +4 deprecated usages. Those reports do not validate the current migration. +Current validation and archived historical records are recorded in +[the editor API migration report](validation/editor-api-migration.md). +The final candidate reports zero internal usages on 2026.1.5.1, WebStorm +2026.2.1 and the pinned 2026.3 build. Native IDEA typing/file/diff fixtures passed +at both support boundaries. The local WebStorm desktop run is blocked by license +activation; its issue-specific CI regression remains in place. Other API warnings +and the extension-provider fixture failures are still open. ## 1. JCEF Related Issues diff --git a/docs/validation/editor-api-migration-evidence.tar.gz b/docs/validation/editor-api-migration-evidence.tar.gz new file mode 100644 index 0000000..4a0e473 Binary files /dev/null and b/docs/validation/editor-api-migration-evidence.tar.gz differ diff --git a/docs/validation/editor-api-migration-results.json b/docs/validation/editor-api-migration-results.json new file mode 100644 index 0000000..a88c69e --- /dev/null +++ b/docs/validation/editor-api-migration-results.json @@ -0,0 +1,137 @@ +{ + "date_utc": "2026-11-12", + "scope": "follow-up candidate; commit-bound verification pending signing", + "base_commit": "32fb571f693f36d71b8585179e37cea132033476", + "production_source_manifest_sha256": "c672706f693e03007abefb5a169fb4fd0ff74cde56c476ad86809699d031ad9a", + "plugin_version": "3.96.0", + "artifact": "jetbrains_plugin/build/distributions/ZooCode-3.96.0.zip", + "sha256": "d4516add5b27bbbea5e60540d1725328b24b1f17e83e4b9828a23a9e26e5475a", + "minimum_ide": "2026.1.5.1", + "since_build": "261.27258.136", + "until_build": "263.*", + "bytecode_java_version": 21, + "maintainer_approved_baseline_change": "2026-11-12 review conversation", + "verifier_version": "1.410", + "verifier_java": "Temurin 21.0.12", + "failing_marketplace_target": "IntelliJ IDEA 2026.1.5.1; 2026-11-09 09:56; verifier 1.410", + "original_uploaded_zip_sha256": null, + "jvm_tests": { + "tests": 137, + "failures": 0, + "errors": 0, + "skipped": 0 + }, + "jvm_suites": [ + "org.zoocode.jetbrains.editor.EditorOpenQueueTest", + "org.zoocode.jetbrains.terminal.RawOutputTtyConnectorTest", + "org.zoocode.jetbrains.util.JcefSupportTest", + "org.zoocode.jetbrains.webview.InstanceRetirementTrackerTest", + "org.zoocode.jetbrains.descriptor.PluginDescriptorTest", + "org.zoocode.jetbrains.terminal.TerminalPtyBuilderTest", + "org.zoocode.jetbrains.ui.WebViewMountPlanTest", + "org.zoocode.jetbrains.editor.EditorFocusIntentTest", + "org.zoocode.jetbrains.terminal.TerminalShellReadinessTest", + "org.zoocode.jetbrains.util.FocusRequestEpochTest", + "org.zoocode.jetbrains.editor.EditorRoutingContractTest", + "org.zoocode.jetbrains.terminal.ShellIntegrationOutputStateTest", + "org.zoocode.jetbrains.ipc.proxy.LazyPromiseTest", + "org.zoocode.jetbrains.editor.WorkspaceEditTest", + "org.zoocode.jetbrains.util.TerminalCreationFocusGuardTest", + "org.zoocode.jetbrains.util.ExecutablePathTest", + "org.zoocode.jetbrains.util.ManualFocusGuardTest", + "org.zoocode.jetbrains.terminal.TerminalWidgetVisibilityTest" + ], + "mutation_checks": { + "bulk-fspath": "rejected by one regression test; restored source tests/build pass", + "timeout-error": "rejected by one regression test; restored source tests/build pass" + }, + "verifier_results": [ + { + "ide_build": "IU-261.27258.136", + "compatible": true, + "internal": 0, + "scheduled_for_removal": 7, + "deprecated": 7, + "experimental": 6, + "report": "verifier/IU-261.27258.136", + "dispatch_output_smoke": "PASS" + }, + { + "ide_build": "WS-262.9437.145", + "compatible": true, + "internal": 0, + "scheduled_for_removal": 7, + "deprecated": 7, + "experimental": 6, + "report": "verifier/WS-262.9437.145", + "dispatch_output_smoke": "PASS" + }, + { + "ide_build": "IC-263.7307.112", + "compatible": true, + "internal": 0, + "scheduled_for_removal": 7, + "deprecated": 8, + "experimental": 6, + "report": "verifier/IC-263.7307.112", + "dispatch_output_smoke": "PASS" + } + ], + "native_fixture_runs": [ + { + "ide_build": "IU-261.27258.136", + "java_version": "25.0.4.1", + "status": "PASS", + "deliberate_file_focus_and_typing": "true", + "deliberate_diff_focus": "true", + "preserving_files": "12", + "preserving_diffs": "12", + "both_turns_typing": "true", + "both_turns_focus": "true", + "evidence": "native/261/evidence.json" + }, + { + "ide_build": "IU-263.7307.112", + "java_version": "25.0.4.1", + "status": "PASS", + "deliberate_file_focus_and_typing": "true", + "deliberate_diff_focus": "true", + "preserving_files": "12", + "preserving_diffs": "12", + "both_turns_typing": "true", + "both_turns_focus": "true", + "evidence": "native/263/evidence.json" + } + ], + "windows_hosted": "not rerun; existing fixture and protected WebStorm live jobs retained", + "live_provider": "not run; protected environment approval still applies", + "webstorm_native_local": "no fresh run; previous attempt blocked by license activation; retained CI coverage", + "remote_sdk_resolution": "Gradle dependency graph resolves com.jetbrains.intellij.idea:idea:2026.1.5.1; full remote build pending CI", + "embedded_extension_version": "3.84.0 (existing local cached payload)", + "artifact_scope": "Local release-mode package; final publication payload must be independently rebuilt and verified in CI", + "platform_payload": "Existing prepared payload; missing platform.zip reconstructed locally", + "other_checks": { + "local_http_fixture_tests": "18 passed", + "actionlint": "PASS", + "script_integration_dry_run": "PASS", + "packaged_bytecode_scanner_and_self_test": "PASS", + "git_diff_check": "PASS" + }, + "evidence_archive": "editor-api-migration-evidence.tar.gz", + "evidence_paths": "All report, native, JVM and source-manifest paths are relative to the archive root.", + "source_commit": null, + "commit_checkpoint": "PENDING: configured GPG signing requires an unavailable passphrase", + "prior_mutation_checks": "historical/d6a4436e/mutation-*.log", + "ultimate_dependency_check": { + "required_dependencies": [ + "com.intellij.modules.platform", + "org.jetbrains.plugins.terminal" + ], + "unused_java_build_dependency_removed": true, + "evidence": "product-dependencies.json", + "cross_product_checks": [ + "WS-262.9437.145", + "IC-263.7307.112" + ] + } +} diff --git a/docs/validation/editor-api-migration.md b/docs/validation/editor-api-migration.md new file mode 100644 index 0000000..f324d58 --- /dev/null +++ b/docs/validation/editor-api-migration.md @@ -0,0 +1,127 @@ +# Editor API migration validation + +Validated on **2026-11-12**, from staged production sources based on `32fb571`. +**Commit-bound verification remains pending**: Git signing requires a passphrase +unavailable in this session; no unsigned override or commit was made. +The maintainer approved **261.27258.136–263.* / Java 21** as the supported range. +The three reported internal editor API usages are removed. Issue #18 remains +partial: proxy/customizer migrations and other API warnings remain open. + +## Supported baseline decision + +The minimum moves explicitly from **2023.3 / Java 17** to **2026.1.5.1 / Java 21**. +This is an approved compatibility tradeoff, not a claim that older builds are +technically impossible. Released 233 binaries and source establish: + +- The current request-based navigation descriptor is absent; the direct + `Navigatable` overloads are internal. +- The public data-context overload ultimately uses synchronous + `OpenFileDescriptor.navigate` on EDT. No typing-preserving prototype is claimed. +- Public synchronous file opening exists, but reintroducing it requires fresh + typing regression evidence because lost chat keys motivated the async path. +- A separate Java 17 build with legacy terminal hooks is technically feasible, + but needs its own editor implementation, descriptor, verifier and native tests. + It has not been implemented or tested. One modern build was chosen instead. + +Sources: JetBrains' [multiple-version guidance](https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html#targeting-multiple-ide-versions), +[dependency helpers](https://plugins.jetbrains.com/docs/intellij/tools-intellij-platform-gradle-plugin-dependencies-extension.html), +and [released 233 navigation implementation](https://github.com/JetBrains/intellij-community/blob/idea/233.11799.241/platform/lang-impl/src/com/intellij/platform/ide/navigation/impl/IdeNavigationService.kt). +Exact SDK signatures, annotations and binary hashes are retained in the archive. + +## Artifact and results + +Plugin **3.96.0**: `jetbrains_plugin/build/distributions/ZooCode-3.96.0.zip`. + +SHA-256: `d4516add5b27bbbea5e60540d1725328b24b1f17e83e4b9828a23a9e26e5475a`. +Rebuilding after restoring the source mutations retained this exact hash. +Verifier **1.410**, on Temurin **21.0.12**, checked the same ZIP on all targets: + +| Target | Verdict | Internal | Scheduled for removal | Deprecated | Experimental | Terminal dispatch/output | +| --- | --- | ---: | ---: | ---: | ---: | --- | +| IU-261.27258.136 / IDEA 2026.1.5.1 | Compatible | 0 | 7 | 7 | 6 | PASS | +| WS-262.9437.145 / WebStorm 2026.2.1 | Compatible | 0 | 7 | 7 | 6 | PASS | +| IC-263.7307.112 / pinned 2026.3 SDK | Compatible | 0 | 7 | 8 | 6 | PASS | + +These reports contain warnings. The broad verifier gate rejects internal usages, +compatibility problems and invalid plugins; the targeted bytecode scanner alone +is not evidence of zero internal usages. + +- **137 PR-selected JVM tests passed**, zero skips/failures/errors, including + focus guards, Linux PTY forwarding and shell state. This is not the full suite: + platform-fixture `ExtensionDecouplingTest` and Windows ConPTY were not selected. +- **18 local HTTP fixture/relay tests passed**, along with the packaged-bytecode + scanner/self-test, actionlint, integration dry-run and whitespace checks. +- Native IDEA **261 and 263 passed** on bundled JBR **25.0.4.1**: deliberate + file focus and a typed character, deliberate diff focus, all 12 preserving + file/diff sequences, and exact typing/focus through both streamed chat turns. +- Reverting all four bulk file-operation `fsPath` conversions or changing the + distinct navigation-deadline error back to cancellation independently failed + regression tests. Sources were restored and rebuilt to the same ZIP hash. + Earlier queue/open/refresh mutation results remain in the historical evidence. + +## Review changes + +| Findings | Resolution | +| --- | --- | +| 1–3 | Approved baseline decision above; corrected PR scope; WebStorm coverage retained. | +| 4–5 | Native deliberate-focus checks added. Deliberate diff close/show operations now use the shared queue and suspending EDT context. | +| 6, 9 | Terminal dispatch/output proved against 261, 262 and 263 binaries. Both PR/publication workflows verify WebStorm 262 and support both PTY jar layouts. | +| 7–8 | One artifact identity and compressed, auditable evidence; historical candidates are archived separately. | +| 10–11 | Compiled production-routing tests bind file/diff opens to the queue and both File conversions to fsPath; three actual mutations were rejected. URI tests cover drive, UNC, Unix and escaped characters. | +| 12–13 | Non-strict normalization comment corrected. URI identity and Java filesystem conversion remain distinct; pre-existing VFS path uses are unchanged. | +| 14 | Active navigation has a 120-second cooperative deadline. Its expiry raises EditorNavigationTimeoutException; caller cancellation and nested operation timeouts retain cancellation semantics. Blocking IDE code cannot be forcibly interrupted. | +| 15 | Identity/dirty-state tests deserialize production WorkspaceEdit data. File creation/deletion/rename tests cover nullable endpoints, normalization, options and metadata. | +| 16–17 | Stale comments/counts corrected. Unified IDEA dependency replaces legacy IC for 261; the dependency graph resolves `com.jetbrains.intellij.idea:idea:2026.1.5.1`. Full remote-SDK build remains a CI check. | + +The desktop overlap is stress coverage; unit tests establish deterministic queue +ordering and compiled routing tests establish that production calls use it. + +## Evidence and limits + +[Machine-readable results](editor-api-migration-results.json) record the artifact, +source fingerprint, target builds, counts and evidence paths. The +[evidence archive](editor-api-migration-evidence.tar.gz) retains raw verifier +reports, JVM XML, mutation logs, SDK metadata, native predicates and historical +candidate records. To inspect it without repopulating the repository: + +```sh +mkdir -p /tmp/zoo-api-evidence +tar -xzf docs/validation/editor-api-migration-evidence.tar.gz -C /tmp/zoo-api-evidence +``` + +The local package embeds the cached **3.84.0** extension payload and local +extension-host build, with JVM plugin descriptor **3.96.0**. The missing platform +archive was reconstructed from the existing prepared payload. Publication CI must +assemble and verify its own exact ZIP; these results cannot validate a differently +packaged artifact. + +Hosted Windows/native WebStorm and protected live-provider checks were not rerun. +Their coverage and approval requirements remain intact. Earlier local WebStorm +activation was blocked by licensing. Fixture conversations do not run model-driven +terminal commands; JVM PTY/dispatch tests are separate evidence, and the protected +live job remains the end-to-end terminal check. + +Initial disk-exhausted runs and the initial wrong-PTY-layout smoke were not +counted as passes. Their context and the subsequent fresh results are archived. +The maintainer identified the failing Marketplace check as IDEA **2026.1.5.1**, +**2026-11-09 09:56** (timezone unspecified), Verifier **1.410**, with 3 internal +and 12 removal usages. The original full report/uploaded ZIP hash remain missing. +No publication or issue closure was performed. + +## Follow-up spot-check + +- All four bulk create/delete/rename File conversions now use `fsPath`; a + compiled production-routing test covers them, and reverting them fails it. + The host tests were Linux runs; Windows behavior still needs hosted CI. +- Deadline expiry is a distinct error, while a regression preserves nested + timeout cancellation. The timeout-as-cancellation mutation was rejected. +- `IU` selects the unified IDEA artifact. The unused Java build dependency was + removed; the packaged descriptor requires only platform and terminal modules + (JCEF stays optional). Fresh WebStorm and IC verifier results establish no + missing binary/API dependency on Ultimate for this ZIP. +- GitHub's live PR title/body already state the 261 / Java 21 baseline. The + stale-description finding did not match the live PR when checked. The + existing migration PR retains its associated Windows regression fixes. +- The commit/rebuild checkpoint remains open until signing is resolved. The + current artifact has complete fresh test/verifier/native evidence, but is + explicitly not represented as verification of a new commit. diff --git a/jetbrains_plugin/build.gradle.kts b/jetbrains_plugin/build.gradle.kts index ceef30f..be7155d 100644 --- a/jetbrains_plugin/build.gradle.kts +++ b/jetbrains_plugin/build.gradle.kts @@ -4,15 +4,21 @@ // SPDX-License-Identifier: APACHE2.0 // SPDX-License-Identifier: Apache-2.0 -import org.jetbrains.intellij.tasks.RunPluginVerifierTask +import org.jetbrains.intellij.platform.gradle.tasks.VerifyPluginTask +import org.jetbrains.intellij.platform.gradle.IntelliJPlatformType +import org.jetbrains.intellij.platform.gradle.TestFrameworkType +import org.gradle.process.ExecOperations +import javax.inject.Inject +import org.jetbrains.kotlin.gradle.dsl.JvmTarget +import org.jetbrains.kotlin.gradle.dsl.KotlinVersion // Convenient for reading variables from gradle.properties fun properties(key: String) = providers.gradleProperty(key) plugins { id("java") - id("org.jetbrains.kotlin.jvm") version "1.8.10" - id("org.jetbrains.intellij") version "1.13.3" + id("org.jetbrains.kotlin.jvm") version "2.3.20" + id("org.jetbrains.intellij.platform") version "2.20.0" id("org.jlleitschuh.gradle.ktlint") version "11.6.1" id("io.gitlab.arturbosch.detekt") version "1.23.4" } @@ -22,17 +28,17 @@ apply(from = "genPlatform.gradle") // Use Java/Kotlin toolchains instead of per-task source/target java { toolchain { - languageVersion.set(JavaLanguageVersion.of(17)) + languageVersion.set(JavaLanguageVersion.of(21)) } } kotlin { - jvmToolchain(17) + jvmToolchain(21) } // Toolchain launcher used by verification tasks that start a plain JVM. val verificationJavaLauncher = javaToolchains.launcherFor { - languageVersion.set(JavaLanguageVersion.of(17)) + languageVersion.set(JavaLanguageVersion.of(21)) } // ------------------------------------------------------------ @@ -136,7 +142,7 @@ fun Sync.prepareSandbox() { // Set duplicate strategy to include files, with later sources taking precedence duplicatesStrategy = DuplicatesStrategy.INCLUDE - val sandboxDir = intellij.pluginName.get() + val sandboxDir = "ZooCode" // Themes val themesDir = "${project.projectDir.absolutePath}/src/main/resources/themes/" @@ -246,9 +252,24 @@ version = properties("pluginVersion").get() repositories { mavenCentral() + intellijPlatform { defaultRepositories() } } dependencies { + intellijPlatform { + val localIde = providers.gradleProperty("platformLocalIde").orNull + if (localIde != null) local(file(localIde).absolutePath) + else create { + val code = properties("platformType").get() + type.set(if (code == "IU") IntelliJPlatformType.IntellijIdea + else IntelliJPlatformType.entries.single { it.code == code }) + version = properties("platformVersion").get() + useInstaller = false + } + bundledPlugin("org.jetbrains.plugins.terminal") + testFramework(TestFrameworkType.Platform) + pluginVerifier("1.410") + } implementation("com.squareup.okhttp3:okhttp:4.10.0") implementation("com.google.code.gson:gson:2.10.1") implementation("org.apache.commons:commons-compress:1.27.1") @@ -256,22 +277,53 @@ dependencies { detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.4") } -// Configure Gradle IntelliJ Plugin -// Read more: https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html -intellij { - pluginName.set("ZooCode") - version.set(properties("platformVersion")) - type.set(properties("platformType")) - - plugins.set( - listOf( - "com.intellij.java", - // Add JCEF support - "org.jetbrains.plugins.terminal" - ) - ) +// The IDE supplies Kotlin; do not package older transitive runtimes from OkHttp/Okio. +configurations.implementation { + exclude(group = "org.jetbrains.kotlin") +} + +// A single modern release line; older IDEs must use an earlier plugin release. +intellijPlatform { + projectName.set("ZooCode") + // The plugin contributes no settings Configurable to index. + buildSearchableOptions.set(false) + pluginConfiguration { + version.set(properties("pluginVersion")) + ideaVersion { + sinceBuild.set(properties("pluginSinceBuild")) + untilBuild.set(properties("pluginUntilBuild")) + } + } + pluginVerification { + failureLevel.set(listOf( + VerifyPluginTask.FailureLevel.COMPATIBILITY_PROBLEMS, + VerifyPluginTask.FailureLevel.INVALID_PLUGIN, + VerifyPluginTask.FailureLevel.INTERNAL_API_USAGES, + )) + verificationReportsDirectory.set(layout.dir( + providers.gradleProperty("verifierReportsDir").map { file(it) } + .orElse(layout.buildDirectory.dir("reports/pluginVerifier").map { it.asFile }) + )) + ides { + val localIde = providers.gradleProperty("verifierLocalIde").orNull + // The dependency helper otherwise resolves relative paths from the + // Gradle daemon's working directory, not this project directory. + if (localIde != null) local(file(localIde).absolutePath) + else create { + val code = providers.gradleProperty("verifierType").orElse(properties("platformType")).get() + type.set(if (code == "IU") IntelliJPlatformType.IntellijIdea + else IntelliJPlatformType.entries.single { it.code == code }) + version = providers.gradleProperty("verifierVersion").orElse(properties("platformVersion")).get() + useInstaller = false + } + } + } } +// Gradle 9 removed Project.exec; use the supported injected process service. +abstract class ProcessServices @Inject constructor(val execOperations: ExecOperations) +val processServices = objects.newInstance() + tasks { // Create task for generating configuration files @@ -304,68 +356,22 @@ tasks { // Set the JVM compatibility versions withType { dependsOn("generateConfigProperties") - kotlinOptions { - jvmTarget = "17" - } - } - - patchPluginXml { - version.set(properties("pluginVersion")) - sinceBuild.set(properties("pluginSinceBuild")) - untilBuild.set("") - } - - // One binary must keep 233 support and stay compatible with the 2026.3 terminal - // changes. Verify against the newest supported platform; failures are limited to - // hard compatibility problems so deprecated-API notices do not hide them. - // - // The gradle-intellij 1.x task resolves ideVersions from release feeds only, and - // IC-263.5701.42 (idea263Build property) is an EAP build that no feed lists. CI - // (release.yml) downloads the exact build and passes it as - // -PverifierLocalIde=. Local runs have two clear paths: - // ./gradlew runPluginVerifier -PverifierLocalIde= - // ./gradlew runPluginVerifier -PverifierIdeVersion=IC- - runPluginVerifier { - // Verifier releases: https://repo1.maven.org/maven2/org/jetbrains/intellij/plugins/verifier-cli/ - verifierVersion.set("1.410") - val idea263Build = providers.gradleProperty("idea263Build").orElse("263.5701.42") - val explicitVersions = providers.gradleProperty("verifierIdeVersion").orNull - ideVersions.set(listOf(explicitVersions ?: "IC-${idea263Build.get()}")) - failureLevel.set( - listOf( - RunPluginVerifierTask.FailureLevel.COMPATIBILITY_PROBLEMS, - RunPluginVerifierTask.FailureLevel.INVALID_PLUGIN - ) - ) - val localIde = providers.gradleProperty("verifierLocalIde").orNull - if (localIde != null) { - ideVersions.set(emptyList()) - localPaths.set(listOf(file(localIde))) - } else if (explicitVersions == null) { - doFirst { - throw GradleException( - "runPluginVerifier needs an IDE target. IC-${idea263Build.get()} is an EAP build that " + - "gradle-intellij cannot resolve from release feeds. Download " + - "ideaIC-${idea263Build.get()}-EAP-SNAPSHOT.zip, unpack it, and pass " + - "-PverifierLocalIde= (this is what release.yml does for CI), " + - "or verify a release feed build with -PverifierIdeVersion=IC-.", - ) - } + compilerOptions { + jvmTarget.set(JvmTarget.JVM_21) + languageVersion.set(KotlinVersion.KOTLIN_2_2) + apiVersion.set(KotlinVersion.KOTLIN_2_2) } } - // Regression gate: a packaged method reference to LocalTerminalDirectRunner - // .createProcess(ShellStartupOptions) breaks the same binary on IntelliJ 2026.3, - // where that method returns java.lang.Process instead of PtyProcess, so a 2023.3 - // call site does not resolve. The 2023.3 path and the 2026.3 path both start the - // process through TerminalInstance.startTerminalProcess. + // Regression gate: reject legacy terminal process calls and internal PTY APIs. + // The runner starts our process through TerminalInstance.startTerminalProcess. // // The packaged plugin jar inside the sandbox: instrumentation may rename it with // an "instrumented-" prefix, and patchPluginXml writes the release descriptor into // exactly this copy. fun packagedPluginJar(): File { - val archiveName = jar.get().archiveFileName.get() - val libDir = File(File(prepareSandbox.get().destinationDir, intellij.pluginName.get()), "lib") + val archiveName = project.tasks.named("composedJar", org.jetbrains.intellij.platform.gradle.tasks.ComposedJarTask::class.java).get().archiveFileName.get() + val libDir = File(File(prepareSandbox.get().destinationDir, "ZooCode"), "lib") val candidates = libDir.listFiles { file -> file.name.endsWith(archiveName) } ?: throw GradleException("Sandbox lib directory not found: $libDir") return candidates.firstOrNull { it.name.startsWith("instrumented-") } @@ -375,7 +381,7 @@ tasks { // The scan delegates to smoke/Smoke263DispatchCheck.java --scan-jar so the banned // reference list and the constant-pool parsing live in one place. The checker is - // linked against the 233 platform jars already on the compile classpath; this task + // linked against the target platform jars already on the compile classpath; this task // never needs the 2026.3 IDE. The scan target is the instrumented jar in the // sandbox, the exact bytes that the Plugin Verifier checks and that the published // zip packages. The task first runs the checker --self-test, which feeds it @@ -392,7 +398,7 @@ tasks { outputs.file(layout.buildDirectory.file("verification/packaged-bytecode.ok")) dependsOn(prepareSandbox) doLast { - project.exec { + processServices.execOperations.exec { commandLine( verificationJavaLauncher.get().executablePath.asFile.absolutePath, "-cp", @@ -402,7 +408,7 @@ tasks { ) } val pluginJar = packagedPluginJar() - project.exec { + processServices.execOperations.exec { commandLine( verificationJavaLauncher.get().executablePath.asFile.absolutePath, "-cp", @@ -428,25 +434,31 @@ tasks { // build's jediterm and pty4j. register("smoke263Dispatch") { group = "verification" - description = "Prove the 2026.3 createTtyConnector dispatch against an unpacked ideaIC 263.5701.42" + description = "Prove createTtyConnector dispatch and output forwarding against the selected verification IDE" val checker = layout.projectDirectory.file("smoke/Smoke263DispatchCheck.java") - val idea263Build = providers.gradleProperty("idea263Build").orElse("263.5701.42") - val ideDir = providers.gradleProperty("smokeLocalIde") + val idea263Build = providers.gradleProperty("idea263Build").orElse("263.7307.112") + val verificationIde = providers.provider { verifyPlugin.get().ides.singleFile.absolutePath } + val ideDir = (if (providers.gradleProperty("smokeVerifiedIde").orNull == "true") { + dependsOn(verifyPlugin) + verificationIde + } else providers.gradleProperty("smokeLocalIde")) .orElse(layout.buildDirectory.dir(idea263Build.map { "ideaIC-$it" }).map { it.asFile.absolutePath }) // The checker reads the first jar as bytes and loads the other five. Track only // this jar set so unrelated files in the unpacked IDE cannot invalidate the task. - val ideJarPaths = listOf( + val ideJarPaths = ideDir.map { directory -> listOf( "plugins/terminal/lib/terminal.jar", - "lib/intellij.libraries.pty4j.jar", + if (File(directory, "lib/intellij.libraries.pty4j.jar").isFile) + "lib/intellij.libraries.pty4j.jar" + else "plugins/pty4j-plugin/lib/modules/intellij.libraries.pty4j.jar", "lib/intellij.libraries.jediterm.core.jar", "lib/intellij.libraries.jediterm.ui.jar", "lib/util-8.jar", "lib/util_rt.jar", - ) + ) } inputs.files(prepareSandbox.map { it.destinationDir }) inputs.file(checker) - inputs.files(ideDir.map { ideDirectory -> ideJarPaths.map { File(ideDirectory, it) } }) - inputs.property("idea263Build", idea263Build) + inputs.files(ideDir.zip(ideJarPaths) { directory, paths -> paths.map { File(directory, it) } }) + inputs.property("selectedIde", ideDir) outputs.file(layout.buildDirectory.file("verification/smoke263-dispatch.ok")) dependsOn(prepareSandbox) doLast { @@ -456,10 +468,10 @@ tasks { "ideaIC-${idea263Build.get()}-EAP-SNAPSHOT.zip there or pass " + "-PsmokeLocalIde=." } - val ideJars = ideJarPaths.map { ideDirectory.resolve(it) } + val ideJars = ideJarPaths.get().map { ideDirectory.resolve(it) } ideJars.forEach { check(it.isFile) { - "Expected 2026.3 IDE jar missing: $it. The ideaIC layout changed and the " + + "Expected verification IDE jar missing: $it. The IDE layout changed and the " + "smoke checker needs updated jar locations." } } @@ -471,7 +483,7 @@ tasks { val terminalJar = ideJars.first() val pluginJar = packagedPluginJar() val classpath = ideJars.drop(1) + pluginJar - project.exec { + processServices.execOperations.exec { commandLine( verificationJavaLauncher.get().executablePath.asFile.absolutePath, "-cp", @@ -482,7 +494,7 @@ tasks { ) } val smokeMarker = layout.buildDirectory.file("verification/smoke263-dispatch.ok").get().asFile - smokeMarker.writeText("${idea263Build.get()} ${pluginJar.absolutePath}") + smokeMarker.writeText("${ideDirectory.absolutePath} ${pluginJar.absolutePath}") } } diff --git a/jetbrains_plugin/gradle.properties b/jetbrains_plugin/gradle.properties index 34c4e75..a1b0ac2 100644 --- a/jetbrains_plugin/gradle.properties +++ b/jetbrains_plugin/gradle.properties @@ -2,19 +2,30 @@ pluginGroup=org.zoocode.jetbrains pluginVersion=3.96.0 +# Baseline change from 233 / Java 17 approved by the maintainer on 2026-11-12. # Platform basic information -platformVersion=2023.3 -platformType=IC -pluginSinceBuild=233 +platformVersion=2026.1.5.1 +# Unified IDEA artifact code; plugin requirements remain platform and terminal only. +platformType=IU +pluginSinceBuild=261.27258.136 +pluginUntilBuild=263.* -# The 2026.3 EAP build used by runPluginVerifier and smoke263Dispatch. The +# The pinned 2026.3 build used by verifyPlugin and smoke263Dispatch. The # GitHub Actions workflows download the archive once, check it against the # pinned digest below, and cache the unpacked IDE. -idea263Build=263.5701.42 +idea263Build=263.7307.112 # SHA-256 of the ideaIC--EAP-SNAPSHOT.zip archive. release.yml and # pr.yml both read this value, so it is pinned in one place. -idea263Sha256=e8c679ef071297714151d1f182e5e729e8d1afee216c06ece47fad89a6316846 +idea263Sha256=de9832127205a037c5f28d3a1d846c904dc00811772def92bca076f7691d9566 # Other project configurations can be added here vscodeVersion=1.100.0 + +# Use the Kotlin runtime bundled with the target IDE. +kotlin.stdlib.default.dependency=false + +# Bound worker count and give the modern SDK compiler enough heap on CI. +org.gradle.jvmargs=-Xmx1536m -XX:MaxMetaspaceSize=768m +kotlin.daemon.jvmargs=-Xmx2048m +org.gradle.workers.max=4 diff --git a/jetbrains_plugin/gradle/wrapper/gradle-wrapper.properties b/jetbrains_plugin/gradle/wrapper/gradle-wrapper.properties index db9a6b8..ac57dd1 100644 --- a/jetbrains_plugin/gradle/wrapper/gradle-wrapper.properties +++ b/jetbrains_plugin/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/jetbrains_plugin/scripts/ui-harness/HarnessDriver.java b/jetbrains_plugin/scripts/ui-harness/HarnessDriver.java index 831aa4c..f03eb2e 100644 --- a/jetbrains_plugin/scripts/ui-harness/HarnessDriver.java +++ b/jetbrains_plugin/scripts/ui-harness/HarnessDriver.java @@ -351,6 +351,7 @@ private void runRealConversation(Project project) throws Exception { if (!Boolean.TRUE.equals(ready)) throw new IllegalStateException("Chat remained hidden during indexing"); snap = realSnapshot(webview,title); screenshot("p-configured"); + if (diffStress) checkDeliberateEditorFocus(project); // Establish native focus before typing anything. A freshly mounted OSR // surface may paint after its DOM is ready. Setup clicks are bounded; // no clicks or focus repairs occur inside either draft typing loop. @@ -542,6 +543,59 @@ private void typeText(String text) throws Exception { log("typed text of length " + text.length()); } + // Deliberate opens must transfer native focus; chat typing is checked again + // after the normal setup click below. Preserving opens run during both turns. + private void checkDeliberateEditorFocus(Project project) throws Exception { + Path dir = Paths.get(project.getBasePath(), ".focus-diffs"); + java.util.Map right = java.util.Map.of("scheme", "file", "path", + dir.resolve("after-0.java").toString().replace('\\', '/')); + java.util.Map left = java.util.Map.of("scheme", "file", "path", + dir.resolve("before-0.java").toString().replace('\\', '/')); + Class textClass = zooClass("org.zoocode.jetbrains.actors.MainThreadTextEditors"); + Object textEditors = textClass.getConstructor(Project.class).newInstance(project); + Method show = java.util.Arrays.stream(textClass.getMethods()) + .filter(m -> m.getName().equals("tryShowTextDocument")).findFirst().orElseThrow(); + invokeSuspend(textEditors, show, right, java.util.Map.of("preserveFocus", false)); + awaitSelectedEditorFocus(project); + final String[] before = {null}; + runOnEdt(() -> before[0] = com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project) + .getSelectedTextEditor().getDocument().getText()); + typeText("q"); + Object typed = poll(10000, () -> { + final boolean[] exact = {false}; + runOnEdt(() -> { + String after = com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project) + .getSelectedTextEditor().getDocument().getText(); + exact[0] = after.equals("q" + before[0]); + }); + return exact[0]; + }); + if (!Boolean.TRUE.equals(typed)) throw new IllegalStateException("Deliberate file open lost native typing"); + record("P_deliberateFileFocusAndTyping", true); + Class commandClass = zooClass("org.zoocode.jetbrains.editor.OpenEditorAPICommands"); + Object command = commandClass.getConstructor(Project.class).newInstance(project); + Method diff = java.util.Arrays.stream(commandClass.getMethods()) + .filter(m -> m.getName().equals("workbench_diff")).findFirst().orElseThrow(); + invokeSuspend(command, diff, left, right, "Deliberate focus regression", java.util.Map.of("preserveFocus", false)); + awaitSelectedEditorFocus(project); + record("P_deliberateDiffFocus", true); + } + + private void awaitSelectedEditorFocus(Project project) throws Exception { + Object focused = poll(10000, () -> { + final boolean[] owned = {false}; + runOnEdt(() -> { + Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); + for (com.intellij.openapi.fileEditor.FileEditor editor : + com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project).getSelectedEditors()) { + owned[0] |= owner != null && javax.swing.SwingUtilities.isDescendingFrom(owner, editor.getComponent()); + } + }); + return owned[0]; + }); + if (!Boolean.TRUE.equals(focused)) throw new IllegalStateException("Deliberate open did not focus its editor"); + } + // Exercise showTextDocument followed by diff, as used by live apply_diff. // Both production calls run against fresh files while native keys go // to the real chat. Reflection keeps Kotlin/IDE classes in their own loaders. @@ -566,8 +620,18 @@ private void openPreservingEditors(Project project, int index) throws Exception if (!opened) throw new IllegalStateException("Production call did not open file " + index); }); log("preserving file completed: " + index); + // Match the live extension: showing the edited file can overlap opening its diff. + // Both production calls must complete without NavigationService cancelling either. + java.util.concurrent.Future fileOpen = AppExecutorUtil.getAppExecutorService().submit(() -> { + try { + invokeSuspend(textEditors, show, rightUri, java.util.Map.of("preserveFocus",true)); + } catch (Exception e) { + throw new java.util.concurrent.CompletionException(e); + } + }); invokeSuspend(command, method, leftUri, rightUri, "Input preservation " + index, java.util.Map.of("preserveFocus",true)); + fileOpen.get(30, java.util.concurrent.TimeUnit.SECONDS); runOnEdt(() -> { boolean opened = false; for (com.intellij.openapi.vfs.VirtualFile file : com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project).getOpenFiles()) { diff --git a/jetbrains_plugin/scripts/ui-harness/README.md b/jetbrains_plugin/scripts/ui-harness/README.md index 7185243..0134c4c 100644 --- a/jetbrains_plugin/scripts/ui-harness/README.md +++ b/jetbrains_plugin/scripts/ui-harness/README.md @@ -38,7 +38,7 @@ operations and needs the provider setup documented below. Gradle tests alone do not exercise the bundled extension in a running IDE. The Windows CI workflow pins extension 3.96.0 and builds the checkout; -it has no input for an existing release ZIP. Its IDEA matrix is 2025.3 and +it has no input for an existing release ZIP. Its IDEA matrix is 2026.1.5.1 and 2026.2.1, so those jobs do not establish compatibility with IDEA 2023.3.8. Record the exact ZIP, IDE version, and evidence directory when comparing builds. @@ -303,3 +303,13 @@ loop. Exact draft and focus assertions are unchanged. The external Linux agreement helper only targets named IDE agreement windows and stops when the in-IDE driver starts. It no longer clicks arbitrary windows by size during a conversation. + +## Editor API review regression + +With `HARNESS_DIFF_STRESS=true`, the fixture first verifies that deliberate +file opens transfer native focus and receive a typed character, and deliberate +diff opens transfer focus. It then returns to chat through the normal setup +click and runs the preserving file/diff sequence during streamed native typing. +The overlap in the desktop fixture is stress coverage; deterministic ordering +is asserted by `EditorOpenQueueTest`, and `EditorRoutingContractTest` checks +the compiled production call sites actually enter that queue. diff --git a/jetbrains_plugin/scripts/ui-harness/test_streaming_fixture.py b/jetbrains_plugin/scripts/ui-harness/test_streaming_fixture.py index 54afcec..7989837 100644 --- a/jetbrains_plugin/scripts/ui-harness/test_streaming_fixture.py +++ b/jetbrains_plugin/scripts/ui-harness/test_streaming_fixture.py @@ -2,8 +2,8 @@ import json import tempfile import threading -import time import unittest +from unittest.mock import patch from pathlib import Path from streaming_fixture import make_server @@ -34,16 +34,34 @@ def test_two_incremental_streams_finish_with_native_completion(self): request = {'stream': True, 'messages': [], 'tools': [ {'type': 'function', 'function': {'name': 'attempt_completion'}}]} for turn in (1, 2): - started = time.monotonic() - response = self.post(request) - self.assertEqual(200, response.status) - self.assertEqual('text/event-stream', response.getheader('Content-Type')) - # Read a line before the server's delayed stream completes. - first = json.loads(response.readline().decode()[6:]) - self.assertEqual('assistant', first['choices'][0]['delta']['role']) - events = [json.loads(line[6:]) for line in response.read().decode().splitlines() - if line.startswith('data: {')] - self.assertGreaterEqual(time.monotonic() - started, 0.09) + paused = threading.Event() + release = threading.Event() + + def pause_stream(_interval): + paused.set() + if not release.wait(5): + raise TimeoutError('Test did not release the fixture stream') + + # Hold the server after its first content chunk. Receiving both the + # role and content before release proves incremental delivery without + # depending on sleep durations or the host's clock resolution. + with patch('streaming_fixture.time.sleep', side_effect=pause_stream): + try: + response = self.post(request) + self.assertEqual(200, response.status) + self.assertEqual('text/event-stream', response.getheader('Content-Type')) + first = json.loads(response.readline().decode()[6:]) + self.assertEqual('assistant', first['choices'][0]['delta']['role']) + self.assertEqual(b'\n', response.readline()) + update = json.loads(response.readline().decode()[6:]) + self.assertEqual(f'History update 1 for turn {turn}. ', + update['choices'][0]['delta']['content']) + self.assertTrue(paused.wait(5), 'Server did not pause during the stream') + finally: + # Also unblock the request handler if any assertion fails. + release.set() + events = [update] + [json.loads(line[6:]) for line in response.read().decode().splitlines() + if line.startswith('data: {')] updates = [e for e in events if e['choices'][0]['delta'].get('content')] self.assertEqual(3, len(updates)) tool = events[-2]['choices'][0]['delta']['tool_calls'][0] diff --git a/jetbrains_plugin/smoke/Smoke263DispatchCheck.java b/jetbrains_plugin/smoke/Smoke263DispatchCheck.java index e03ff41..765ac97 100644 --- a/jetbrains_plugin/smoke/Smoke263DispatchCheck.java +++ b/jetbrains_plugin/smoke/Smoke263DispatchCheck.java @@ -17,8 +17,8 @@ import java.util.jar.JarOutputStream; /** - * Headless proof for the 2026.3 terminal compatibility, run by the - * smoke263Dispatch Gradle task against an unpacked ideaIC 263.5701.42. + * Headless proof for terminal compatibility across the declared range, run by the + * smoke263Dispatch Gradle task against each selected verification IDE. * It checks the facts that the Plugin Verifier cannot see: *
    *
  • the platform entry point createTtyConnector(ShellStartupOptions) exists @@ -57,7 +57,8 @@ public class Smoke263DispatchCheck { private static final List BANNED_REF_PREFIXES = List.of( REMOVED_CREATE_PROCESS_PREFIX, "com/intellij/execution/process/LocalPtyOptions#", - "com/intellij/execution/process/LocalPtyOptions$Companion#"); + "com/intellij/execution/process/LocalPtyOptions$Companion#", + "com/intellij/openapi/fileEditor/impl/FileEditorOpenOptions#"); private static final String MULTIBYTE = "naive — 你好, τξζ, 🚀 smoke"; private static final int ACC_PUBLIC = 0x0001; @@ -69,13 +70,13 @@ public class Smoke263DispatchCheck { public static void main(String[] args) throws Exception { if (args.length == 1 && "--self-test".equals(args[0])) { selfTestBannedRefScanner(); - System.out.println("[smoke-263] self-test OK: scanner rejects the banned LocalPtyOptions references and passes clean jars"); + System.out.println("[smoke-263] self-test OK: scanner rejects internal PTY/editor references and passes clean jars"); return; } if (args.length == 2 && "--scan-jar".equals(args[0])) { checkNoBannedRefs(Paths.get(args[1])); System.out.println("[smoke-263] scan OK: no packaged reference to " - + REMOVED_CREATE_PROCESS_PREFIX + "* or LocalPtyOptions*"); + + REMOVED_CREATE_PROCESS_PREFIX + "*, LocalPtyOptions*, or FileEditorOpenOptions"); return; } Path pluginJar = Paths.get(args[0]); @@ -91,7 +92,7 @@ public static void main(String[] args) throws Exception { checkNoBannedRefs(pluginJar); checkConnectorForwards(); - System.out.println("[smoke-263] OK: dispatch binds and output forwarding works against the 2026.3 IDE jars"); + System.out.println("[smoke-263] OK: dispatch binds and output forwarding works against the selected IDE jars"); } private static void checkPlatformEntryPoint(Path terminalJar) throws Exception { @@ -109,21 +110,6 @@ private static void checkPlatformEntryPoint(Path terminalJar) throws Exception { } checkOverridable(RUNNER_CLASS, entryPoint); - // The compatibility premise: the 2023.3 signature returns PtyProcess and the - // 2026.3 signature returns java.lang.Process. Both facts must hold, otherwise - // this smoke check no longer describes the platforms it claims to compare. - if (runner.findMethod("createProcess", - "(Lorg/jetbrains/plugins/terminal/ShellStartupOptions;)Ljava/lang/Process;") == null) { - throw new AssertionError( - RUNNER_CLASS + " no longer declares createProcess(ShellStartupOptions) returning " - + "java.lang.Process; the premise of the compatibility patch changed"); - } - if (runner.findMethod("createProcess", - "(Lorg/jetbrains/plugins/terminal/ShellStartupOptions;)Lcom/pty4j/PtyProcess;") != null) { - throw new AssertionError( - "createProcess(ShellStartupOptions) still returns PtyProcess on this IDE; " - + "the premise of the compatibility patch changed"); - } System.out.println("[smoke-263] platform entry point: createTtyConnector" + DISPATCH_DESCRIPTOR + " on " + RUNNER_CLASS + " is public, non-static and non-final"); } @@ -217,9 +203,9 @@ private static void checkNoBannedRefs(Path pluginJar) throws Exception { throw new AssertionError( "Packaged bytecode references banned platform API. LocalTerminalDirectRunner" + ".createProcess does not resolve on IntelliJ 2026.3 (it returns " - + "java.lang.Process there), and LocalPtyOptions is internal API:\n" + + "java.lang.Process there); LocalPtyOptions and FileEditorOpenOptions are internal API:\n" + String.join("\n", violations) - + "\nStart the process through TerminalInstance.startTerminalProcess instead."); + + "\nUse the public editor request API and the plugin's PTY startup implementation."); } } @@ -239,6 +225,7 @@ private static void selfTestBannedRefScanner() throws Exception { "selftest/BannedRefs.class", syntheticClass("selftest/BannedRefs", new String[][]{ {"com/intellij/execution/process/LocalPtyOptions", "shouldUseWinConPty", "()Z"}, {"com/intellij/execution/process/LocalPtyOptions$Companion", "shouldUseWinConPty", "()Z"}, + {"com/intellij/openapi/fileEditor/impl/FileEditorOpenOptions", "withRequestFocus", "(Z)Lcom/intellij/openapi/fileEditor/impl/FileEditorOpenOptions;"}, }))); AssertionError failure = null; try { @@ -250,9 +237,10 @@ private static void selfTestBannedRefScanner() throws Exception { throw new AssertionError("self-test: scanner missed the LocalPtyOptions reference"); } if (!failure.getMessage().contains("LocalPtyOptions#") - || !failure.getMessage().contains("LocalPtyOptions$Companion")) { + || !failure.getMessage().contains("LocalPtyOptions$Companion") + || !failure.getMessage().contains("FileEditorOpenOptions#")) { throw new AssertionError( - "self-test: scanner report does not name both banned owners:\n" + failure.getMessage(), + "self-test: scanner report does not name every banned owner:\n" + failure.getMessage(), failure); } @@ -261,6 +249,7 @@ private static void selfTestBannedRefScanner() throws Exception { "selftest/CleanRefs.class", syntheticClass("selftest/CleanRefs", new String[][]{ {"com/pty4j/PtyProcess", "getWinSize", "()Lcom/pty4j/WinSize;"}, {"com/intellij/execution/process/LocalPtyOptionsTest", "notInternal", "()V"}, + {"com/intellij/platform/ide/navigation/NavigationOptions", "requestFocus", "(Z)Lcom/intellij/platform/ide/navigation/NavigationOptions;"}, }))); checkNoBannedRefs(clean); } finally { diff --git a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/actors/MainThreadBulkEditsShape.kt b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/actors/MainThreadBulkEditsShape.kt index 1f32d8f..fa60752 100644 --- a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/actors/MainThreadBulkEditsShape.kt +++ b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/actors/MainThreadBulkEditsShape.kt @@ -57,8 +57,8 @@ class MainThreadBulkEdits(val project: Project) : MainThreadBulkEditsShape { // Process file edits - using background thread to avoid EDT violations cto.files.forEach { fileEdit -> if (fileEdit.oldResource != null && fileEdit.newResource != null) { - val oldResource = File(fileEdit.oldResource.path) - val newResource = File(fileEdit.newResource.path) + val oldResource = File(fileEdit.oldResource.fsPath) + val newResource = File(fileEdit.newResource.fsPath) try { Files.move(oldResource.toPath(), newResource.toPath()) // Move VFS refresh operations to background thread @@ -72,7 +72,7 @@ class MainThreadBulkEdits(val project: Project) : MainThreadBulkEditsShape { allSuccess = false } } else if (fileEdit.oldResource != null) { - val oldResource = File(fileEdit.oldResource.path) + val oldResource = File(fileEdit.oldResource.fsPath) try { oldResource.delete() // Move VFS refresh operations to background thread @@ -86,7 +86,7 @@ class MainThreadBulkEdits(val project: Project) : MainThreadBulkEditsShape { allSuccess = false } } else if (fileEdit.newResource != null) { - val newResource = File(fileEdit.newResource.path) + val newResource = File(fileEdit.newResource.fsPath) try { val parentDir = newResource.parentFile if (!parentDir.exists()) { diff --git a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/actors/MainThreadDocumentsShape.kt b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/actors/MainThreadDocumentsShape.kt index b1a42e9..616152b 100644 --- a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/actors/MainThreadDocumentsShape.kt +++ b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/actors/MainThreadDocumentsShape.kt @@ -98,7 +98,7 @@ class MainThreadDocuments(var project: Project) : MainThreadDocumentsShape { val uri = createURI(map) logger.info("tryOpenDocument : ${uri.path}") - val file = File(uri.path) + val file = File(uri.fsPath) val vfs = LocalFileSystem.getInstance() if (!file.exists()) { file.parentFile.mkdirs() diff --git a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionIdentifier.kt b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionIdentifier.kt index 5f7523b..e5baef4 100644 --- a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionIdentifier.kt +++ b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionIdentifier.kt @@ -12,7 +12,7 @@ class ExtensionIdentifier(val value: String) { /** * Stores lowercase value for comparison and indexing */ - val _lower: String = value.toLowerCase() + val _lower: String = value.lowercase() companion object { /** @@ -50,7 +50,7 @@ class ExtensionIdentifier(val value: String) { if (b == null) { return false } - return a._lower == b.toLowerCase() + return a._lower == b.lowercase() } /** @@ -69,7 +69,7 @@ class ExtensionIdentifier(val value: String) { if (b == null) { return false } - return a.toLowerCase() == b._lower + return a.lowercase() == b._lower } /** @@ -87,7 +87,7 @@ class ExtensionIdentifier(val value: String) { * @return Key for indexing */ fun toKey(id: String): String { - return id.toLowerCase() + return id.lowercase() } } diff --git a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionProcessManager.kt b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionProcessManager.kt index 0e6218a..3677304 100644 --- a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionProcessManager.kt +++ b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionProcessManager.kt @@ -4,7 +4,7 @@ package org.zoocode.jetbrains.core -import com.intellij.execution.configurations.PathEnvironmentVariableUtil +import org.zoocode.jetbrains.util.findExecutableOnPath import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.SystemInfo @@ -125,7 +125,7 @@ class ExtensionProcessManager : Disposable { // Build complete PATH envVars["PATH"] = buildEnhancedPath(envVars, nodePath) - LOG.info("Enhanced PATH for ${SystemInfo.getOsNameAndVersion()}: ${envVars["PATH"]}") + LOG.info("Enhanced PATH for ${System.getProperty("os.name")} ${System.getProperty("os.version")}: ${envVars["PATH"]}") // Add key environment variables if (isUds) { @@ -384,9 +384,12 @@ class ExtensionProcessManager : Disposable { * Find executable in system path */ private fun findExecutableInPath(name: String): String? { - val nodePath = PathEnvironmentVariableUtil.findExecutableInPathOnAnyOS("node")?.absolutePath - LOG.info("System Node path: $nodePath") - return nodePath + val executablePath = findExecutableOnPath( + name, EnvironmentUtil.getValue("PATH"), SystemInfo.isWindows, + EnvironmentUtil.getValue("PATHEXT") + )?.absolutePath + LOG.info("System executable path for $name: $executablePath") + return executablePath } /** diff --git a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionSocketServer.kt b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionSocketServer.kt index 33ca660..eb13722 100644 --- a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionSocketServer.kt +++ b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionSocketServer.kt @@ -125,7 +125,7 @@ class ExtensionSocketServer() : ISocketServer { private fun acceptConnections() { val server = serverSocket ?: return - logger.info("Socket server started, waiting for connections..., tid: ${Thread.currentThread().id}") + logger.info("Socket server started, waiting for connections..., thread: ${Thread.currentThread().name}") while (isRunning && !Thread.currentThread().isInterrupted) { try { diff --git a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionUnixDomainSocketServer.kt b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionUnixDomainSocketServer.kt index 278d320..933dabc 100644 --- a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionUnixDomainSocketServer.kt +++ b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/core/ExtensionUnixDomainSocketServer.kt @@ -108,7 +108,7 @@ class ExtensionUnixDomainSocketServer : ISocketServer { // Listen and accept UDS client connections private fun acceptUdsConnections() { val server = udsServerChannel ?: return - logger.info("[UDS] Waiting for connections..., tid: ${Thread.currentThread().id}") + logger.info("[UDS] Waiting for connections..., thread: ${Thread.currentThread().name}") while (isRunning && !Thread.currentThread().isInterrupted) { try { val clientChannel = server.accept() // Block and wait for new connection diff --git a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/editor/EditorAndDocManager.kt b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/editor/EditorAndDocManager.kt index 87b3ace..8a0eb79 100644 --- a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/editor/EditorAndDocManager.kt +++ b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/editor/EditorAndDocManager.kt @@ -10,13 +10,14 @@ import com.intellij.diff.chains.DiffRequestChain import com.intellij.diff.chains.SimpleDiffRequestChain import com.intellij.diff.contents.DiffContent import com.intellij.diff.contents.FileDocumentContentImpl +import com.intellij.diff.editor.DiffVirtualFileBase import com.intellij.diff.editor.ChainDiffVirtualFile import com.intellij.diff.editor.DiffEditorTabFilesManager -import com.intellij.diff.editor.DiffRequestProcessorEditor import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service +import com.intellij.openapi.components.serviceAsync import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diff.DiffBundle import com.intellij.openapi.editor.Editor @@ -24,8 +25,11 @@ import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.FileEditorManagerListener -import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx -import com.intellij.openapi.fileEditor.impl.FileEditorOpenOptions +import com.intellij.openapi.application.EDT +import com.intellij.openapi.application.readAction +import com.intellij.platform.backend.navigation.NavigationRequest +import com.intellij.platform.ide.navigation.NavigationOptions +import com.intellij.platform.ide.navigation.NavigationService import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.LocalFileSystem @@ -54,6 +58,7 @@ class EditorAndDocManager(val project: Project) : Disposable { private var job: Job? = null private val editorStateService:EditorStateService = EditorStateService(project) + private val editorOpenQueue = EditorOpenQueue() init { ideaEditorListener = object : FileEditorManagerListener { @@ -210,35 +215,44 @@ class EditorAndDocManager(val project: Project) : Disposable { } - private suspend fun openFilePreservingFocus(file: VirtualFile): Array { + private suspend fun openFileAsync(file: VirtualFile, requestFocus: Boolean = false): Array = editorOpenQueue.open { if (project.isDisposed) throw CancellationException("Project disposed before editor open") - // Synchronous editor loading pumps a restricted event loop that can - // discard chat keys, even when no focus transfer is requested. - // Invoke the JVM no-arg constructor: Kotlin's default-argument constructor - // changes signature between supported IDE builds. - val openOptions = FileEditorOpenOptions::class.java.getConstructor() - .newInstance().withRequestFocus(false) - val editors = FileEditorManagerEx.getInstanceEx(project) - .openFile(file, openOptions).allEditors.toTypedArray() - // Suspension can outlive the project; do not create handles or tabs afterward. - if (project.isDisposed) throw CancellationException("Project disposed during editor open") - return editors + // NavigationService is public on the minimum SDK and opens files through + // the platform's suspending editor path. A negative offset leaves the caret + // unchanged and also supports the virtual files used for diff tabs. + withContext(Dispatchers.Default) { + // Avoid blocking service initialization after a suspending read action. + // The platform must initialize the service in an active coroutine context. + val navigationService = project.serviceAsync() + val request = readAction { + NavigationRequest.sourceNavigationRequest(project, file, -1) + } ?: throw CancellationException("File unavailable before editor open") + navigationService.navigate( + request, + NavigationOptions.defaultOptions().requestFocus(requestFocus), + null, + ) + // Suspension can outlive the project; do not create handles or tabs afterward. + withContext(Dispatchers.EDT) { + if (project.isDisposed) throw CancellationException("Project disposed during editor open") + FileEditorManager.getInstance(project).getEditors(file) + } + } } /** * Opens a file editor for the document. * * [preserveFocus] carries the display intent from the extension host. The - * [FileEditorManager.openFile] boolean requests editor focus, so a - * preserving open must pass its inverse and must never pass preservation - * itself. + * public opening request takes the inverse as its requestFocus flag. + * Both preserving and deliberate normal-file opens suspend until the + * editor composite is published. * * @param documentUri URI of the document to open * @param preserveFocus true keeps the current focus owner; absent defaults to false * @param options Editor formatting configuration, separate from display intent */ suspend fun openEditor(documentUri: URI, preserveFocus: Boolean = false, options: ResolvedTextEditorConfiguration = ResolvedTextEditorConfiguration()): EditorHolder { - val fileEditorManager = FileEditorManager.getInstance(project) val path = documentUri.path var ideaEditor : Array? = null @@ -246,15 +260,7 @@ class EditorAndDocManager(val project: Project) : Disposable { val file = vfs.findFileByPath(path) file?.let { if (!project.isDisposed) { - if (preserveFocus) { - ideaEditor = openFilePreservingFocus(it) - } else { - ApplicationManager.getApplication().invokeAndWait { - if (!project.isDisposed) { - ideaEditor = fileEditorManager.openFile(it, editorFocusRequest(preserveFocus)) - } - } - } + ideaEditor = openFileAsync(it, editorFocusRequest(preserveFocus)) } } val eh = getEditorHandleByUri(documentUri,false) @@ -300,18 +306,16 @@ class EditorAndDocManager(val project: Project) : Disposable { val diffFile = ChainDiffVirtualFile(requestChain, DiffBundle.message("label.default.diff.editor.tab.name", *arrayOfNulls(0))) when (diffOpenPlan(preserveFocus)) { DiffOpenPlan.PRESERVE_VIA_FILE_EDITOR -> { - ideaEditor = openFilePreservingFocus(diffFile) + ideaEditor = openFileAsync(diffFile) } DiffOpenPlan.DELIBERATE_VIA_DIFF_HELPER -> { - ApplicationManager.getApplication().invokeAndWait { - if (project.isDisposed) return@invokeAndWait - LocalFileSystem.getInstance().findFileByPath(documentUri.path) - ?.let { - ApplicationManager.getApplication().runReadAction { FileEditorManager.getInstance(project).closeFile(it) } - } - - val diffEditorTabFilesManager = DiffEditorTabFilesManager.getInstance(project) - ideaEditor = diffEditorTabFilesManager.showDiffFile(diffFile, true) + editorOpenQueue.open { + withContext(Dispatchers.EDT) { + if (project.isDisposed) throw CancellationException("Project disposed before diff open") + LocalFileSystem.getInstance().findFileByPath(documentUri.path) + ?.let { FileEditorManager.getInstance(project).closeFile(it) } + ideaEditor = DiffEditorTabFilesManager.getInstance(project).showDiffFile(diffFile, true) + } } } } @@ -450,17 +454,12 @@ class EditorAndDocManager(val project: Project) : Disposable { } }else{ ApplicationManager.getApplication().invokeAndWait { - FileEditorManager.getInstance(project).allEditors.forEach { - if(it is DiffRequestProcessorEditor && handler.diff){ - val differ = it - differ.processor.activeRequest?.let { req -> - for (filesToRefresh in req.filesToRefresh) { - if(filesToRefresh.path == handler.document.uri.path){ - differ.dispose() - } - } - } - } + if (handler.diff && !project.isDisposed) { + val manager = FileEditorManager.getInstance(project) + manager.allEditors.filter { editor -> + editor.file is DiffVirtualFileBase && + editor.filesToRefresh.any { it.path == handler.document.uri.path } + }.map { it.file }.distinct().forEach(manager::closeFile) } } diff --git a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/editor/EditorHolder.kt b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/editor/EditorHolder.kt index 68a914e..b31b959 100644 --- a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/editor/EditorHolder.kt +++ b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/editor/EditorHolder.kt @@ -191,7 +191,7 @@ class EditorHolder( } CoroutineScope(Dispatchers.IO).launch { delay(1000) - val file = File(document.uri.path).parentFile + val file = File(document.uri.fsPath).parentFile if(file.exists()){ LocalFileSystem.getInstance().refreshIoFiles(listOf(file)) } diff --git a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/editor/EditorOpenQueue.kt b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/editor/EditorOpenQueue.kt new file mode 100644 index 0000000..c84ac1f --- /dev/null +++ b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/editor/EditorOpenQueue.kt @@ -0,0 +1,24 @@ +package org.zoocode.jetbrains.editor + +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withTimeoutOrNull + +internal class EditorNavigationTimeoutException(timeoutMillis: Long) : + IllegalStateException("Editor navigation did not complete within $timeoutMillis ms") + +/** Keep this project's file and diff opens from superseding one another in NavigationService. */ +internal class EditorOpenQueue(private val navigationTimeoutMillis: Long = 120_000) { + private val mutex = Mutex() + private data class Completed(val value: T) + + // Bound the active navigation, not the time spent waiting for earlier opens. + // Cancellation unwinds navigation before the next caller acquires the mutex. + suspend fun open(action: suspend () -> T): T = mutex.withLock { + // Only our deadline becomes an error. Parent cancellation and nested + // operation timeouts retain their original cancellation semantics. + val completed = withTimeoutOrNull(navigationTimeoutMillis) { Completed(action()) } + ?: throw EditorNavigationTimeoutException(navigationTimeoutMillis) + completed.value + } +} diff --git a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/editor/WorkspaceEdit.kt b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/editor/WorkspaceEdit.kt index 6749fc4..f56025f 100644 --- a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/editor/WorkspaceEdit.kt +++ b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/editor/WorkspaceEdit.kt @@ -50,9 +50,16 @@ class WorkspaceEdit{ for(element in array){ val edit = element.asJsonObject if(edit.has("textEdit")){ - rst.texts.add(Gson().fromJson(edit, TextEdit::class.java)) + val textEdit = Gson().fromJson(edit, TextEdit::class.java) + // Gson bypasses URI construction. Match open/save RPC normalization, + // especially Windows drive paths, so edits use the same document holder. + rst.texts.add(textEdit.copy(resource = URI.from(textEdit.resource))) }else if(edit.has("fileEdit")){ - rst.files.add(Gson().fromJson(edit, FileEdit::class.java)) + val fileEdit = Gson().fromJson(edit, FileEdit::class.java) + rst.files.add(fileEdit.copy( + oldResource = fileEdit.oldResource?.let { URI.from(it) }, + newResource = fileEdit.newResource?.let { URI.from(it) }, + )) } } return rst diff --git a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/terminal/RawOutputTtyConnector.kt b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/terminal/RawOutputTtyConnector.kt index 68cd8c4..2614497 100644 --- a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/terminal/RawOutputTtyConnector.kt +++ b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/terminal/RawOutputTtyConnector.kt @@ -29,20 +29,16 @@ fun interface TerminalRawDataCallback { * * The class extends jediterm ProcessTtyConnector. Its * (java.lang.Process, java.nio.charset.Charset) constructor has the exact same - * descriptor in IntelliJ Platform builds 233 (lib/lib-client.jar) and 263 - * (lib/intellij.libraries.jediterm.core.jar), so one compiled super call - * resolves on both. ready, isConnected, waitFor, both write overloads, and - * getProcess are inherited unchanged. The platform - * com.intellij.terminal.pty.PtyProcessTtyConnector cannot be the superclass: - * on 233 its constructor takes com.pty4j.PtyProcess and on 2026.3 it takes - * java.lang.Process, so no single compiled super call resolves on both. The + * descriptor across the supported 261–263 SDKs + * (lib/intellij.libraries.jediterm.core.jar). ready, isConnected, waitFor, + * both write overloads, and getProcess are inherited unchanged. The * session teardown handles any TtyConnector: it only asks * LocalTerminalTtyConnector for closeSafely and falls back to plain close * otherwise (TerminalUtilKt.closeAndWaitFor). * * Overrides keep the behavior the platform connectors provide: * - read forwards each decoded chunk to [callback] before returning it. - * - resize skips a dead process, matching PtyProcessTtyConnector on both builds. + * - resize skips a dead process, matching PtyProcessTtyConnector across the supported SDKs. * - close sends SIGHUP first on Unix and destroys after one second; on Windows * ConPTY it writes the ETX interrupt byte to the process stdin before * destroy; every other process is destroyed immediately. super.close is not diff --git a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/terminal/TerminalInstance.kt b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/terminal/TerminalInstance.kt index 8d15a7b..124437f 100644 --- a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/terminal/TerminalInstance.kt +++ b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/terminal/TerminalInstance.kt @@ -237,49 +237,13 @@ class TerminalInstance( } /** - * Create custom runner. - * - * IntelliJ 2023.3 runs the session through [createProcess] returning PtyProcess - * and then through [createTtyConnector] with a PtyProcess argument. On 2026.3 - * (build 263.5701.42) that createProcess signature is gone: the method now returns - * java.lang.Process, and the session enters through createTtyConnector with a - * ShellStartupOptions argument. The second method is declared without `override` - * because it does not exist in 2023.3; at runtime its exact descriptor overrides - * the 2026.3 method and shadows the LocalTerminalDirectRunner implementation. No - * method calls super.createProcess or super.createTtyConnector, because the 2023.3 - * descriptors do not resolve on 2026.3. + * Start our local PTY through the supported startup-options connector hook. + * The 261–263 dispatch smoke checks bind this hook; process-based overrides are + * unnecessary. WSL, dev-container and RemDev terminal support is not claimed. */ private fun createCustomRunner(): LocalTerminalDirectRunner { return object : LocalTerminalDirectRunner(project) { - override fun createProcess(options: ShellStartupOptions): PtyProcess { - logger.info("🔧 Custom createProcess method called...") - - return startTerminalProcess(options) - } - - override fun createTtyConnector(process: PtyProcess): TtyConnector { - logger.info("🔧 Custom createTtyConnector(PtyProcess) method called...") - return createRawOutputConnector(process) - } - - /** - * The 2026.3 session entry point. On build 263 the platform - * dispatches createTtyConnector with ShellStartupOptions, because - * createProcess no longer exists there with the 2023.3 signature. - * The method is compiled without `override`, because 2023.3 - * declares no such method; at runtime the identical descriptor - * overrides the platform method. - * - * Support boundary: this bridge is local-only. It starts a - * PtyProcess on the local machine. WSL-internal terminals, - * dev-container terminals, and RemDev sessions are not supported. - * The 2026.3 WSL-internal and dev-container sessions carry - * non-local EEL descriptors, and this bridge implements none. The - * RemDev frontend receives the inherited platform guard and never - * reaches this runner. No EEL support is claimed. - */ - fun createTtyConnector(startupOptions: ShellStartupOptions): TtyConnector { - logger.info("🔧 Custom createTtyConnector(ShellStartupOptions) method called...") + override fun createTtyConnector(startupOptions: ShellStartupOptions): TtyConnector { val process = startTerminalProcess(startupOptions) return createRawOutputConnector(process) } @@ -335,7 +299,7 @@ class TerminalInstance( * * UTF-8 matches the platform connector on every supported build: * LocalTerminalDirectRunner assigns myDefaultCharset = StandardCharsets.UTF_8 - * and passes it to PtyProcessTtyConnector (intellij-community branch 233) and + * and passes it to PtyProcessTtyConnector (platform implementation) and * to LocalTerminalTtyConnector (2026.3), so the raw bytes decode the same way * the stock terminal would. */ diff --git a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/util/ExecutablePath.kt b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/util/ExecutablePath.kt new file mode 100644 index 0000000..1d63323 --- /dev/null +++ b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/util/ExecutablePath.kt @@ -0,0 +1,29 @@ +package org.zoocode.jetbrains.util + +import java.io.File + +/** PATH lookup shared by Java 17 and newer runtimes; never searches the current directory. */ +internal fun findExecutableOnPath( + name: String, + path: String?, + windows: Boolean, + pathExt: String? = null +): File? { + if (path == null || name.isBlank() || name.any { it == '/' || it == '\\' }) return null + val extensions = if (windows) { + pathExt?.split(';')?.filter { it.startsWith('.') && it.length > 1 } + ?.takeIf { it.isNotEmpty() } ?: listOf(".COM", ".EXE", ".BAT", ".CMD") + } else emptyList() + val names = if (windows && extensions.none { name.endsWith(it, ignoreCase = true) }) { + extensions.map { name + it } + } else listOf(name) + for (entry in path.split(if (windows) ';' else ':')) { + val directory = File(entry.removeSurrounding("\"")) + if (!directory.isAbsolute || !directory.isDirectory) continue + for (candidate in names) { + val file = File(directory, candidate) + if (file.isFile && file.canExecute()) return file + } + } + return null +} diff --git a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/util/TerminalCreationFocusGuard.kt b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/util/TerminalCreationFocusGuard.kt index a21bbb4..23407a7 100644 --- a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/util/TerminalCreationFocusGuard.kt +++ b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/util/TerminalCreationFocusGuard.kt @@ -4,7 +4,6 @@ package org.zoocode.jetbrains.util import com.intellij.openapi.project.Project -import com.intellij.openapi.wm.IdeFocusManager import com.intellij.openapi.wm.ToolWindowManager import java.awt.AWTEvent import java.awt.Component @@ -100,11 +99,9 @@ private object SwingTerminalCreationFocusEnvironment : TerminalCreationFocusEnvi return AutoCloseable { timer.stop() } } override fun afterCreation(project: Project, action: () -> Unit) { - // Inline focus settling runs before newTab's queued activation. - ToolWindowManager.getInstance(project).invokeLater { - if (project.isDisposed) action() - else IdeFocusManager.getInstance(project).doWhenFocusSettlesDown { action() } - } + // Tool-window scheduling already defers until activation. The deprecated + // focus-settling callback ran inline on the EDT, adding no further wait. + ToolWindowManager.getInstance(project).invokeLater { action() } } override fun isShowing(component: Component): Boolean = component.isShowing override fun requestFocus(component: Component) { component.requestFocusInWindow() } diff --git a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/util/URIUtil.kt b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/util/URIUtil.kt index f5ac9a7..c515ebb 100644 --- a/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/util/URIUtil.kt +++ b/jetbrains_plugin/src/main/kotlin/org/zoocode/jetbrains/util/URIUtil.kt @@ -93,7 +93,9 @@ class URI private constructor( } } - return URI("file", authority, normalizedPath, EMPTY, EMPTY) + // Use the non-strict normalizing constructor, as parse/from do. + // IDE file events must identify the same document as open/edit/save RPCs. + return URI("file", authority, normalizedPath, EMPTY, EMPTY, strict = false) } /** @@ -626,4 +628,4 @@ private fun encodeURIComponentMinimal(path: String, isPath: Boolean = false, isA } return result ?: path -} \ No newline at end of file +} diff --git a/jetbrains_plugin/src/main/resources/META-INF/plugin.xml b/jetbrains_plugin/src/main/resources/META-INF/plugin.xml index 45e4402..7ee5e6a 100644 --- a/jetbrains_plugin/src/main/resources/META-INF/plugin.xml +++ b/jetbrains_plugin/src/main/resources/META-INF/plugin.xml @@ -58,14 +58,14 @@ SPDX-License-Identifier: Apache-2.0
  • GoLand
  • DataGrip
  • Rider
  • -
  • Android Studio 2026.1.4 or newer (currently available as a preview)
  • +
  • Android Studio builds within the supported IntelliJ Platform range, with JCEF
-

The plugin targets IntelliJ Platform build 233 (JetBrains 2023.3) or newer. Android Studio requires version 2026.1.4 or newer because that release includes the JCEF support required by Zoo Code. At present, Android Studio 2026.1.4 is available through the preview channel.

+

The plugin targets IntelliJ Platform build 261.27258.136 (JetBrains 2026.1.5.1) through 263.*. Android Studio must meet the same platform build range and include JCEF.

Requirements

    -
  • A supported JetBrains IDE based on IntelliJ Platform build 233 or newer
  • -
  • Android Studio 2026.1.4 or newer when using Android Studio; install a preview build until this version reaches the stable channel
  • +
  • A supported JetBrains IDE based on IntelliJ Platform build 261.27258.136 through 263.*
  • +
  • Android Studio must use IntelliJ Platform build 261.27258.136 through 263.* and include JCEF
  • A JCEF-enabled IDE runtime, which Zoo Code requires to render its interface
  • Node.js 20.6.0 or newer available on your PATH
diff --git a/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/descriptor/PluginDescriptorTest.kt b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/descriptor/PluginDescriptorTest.kt index 5b3e1a0..9d11190 100644 --- a/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/descriptor/PluginDescriptorTest.kt +++ b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/descriptor/PluginDescriptorTest.kt @@ -71,6 +71,11 @@ class PluginDescriptorTest { val ids = dependsNodes().map { it.first } assertTrue("descriptor must depend on the platform module", ids.contains("com.intellij.modules.platform")) assertTrue("descriptor must depend on the terminal plugin", ids.contains("org.jetbrains.plugins.terminal")) + assertEquals( + "requirements must stay available outside Ultimate", + setOf("com.intellij.modules.platform", "org.jetbrains.plugins.terminal"), + dependsNodes().filter { it.second["optional"] != "true" }.map { it.first }.toSet() + ) dependsNodes().forEach { (id, attributes) -> if (id != "com.intellij.modules.jcef") { assertFalse("required dependency $id must not be optional", attributes["optional"] == "true") diff --git a/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/editor/EditorFocusIntentTest.kt b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/editor/EditorFocusIntentTest.kt index a0d7318..9c250f3 100644 --- a/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/editor/EditorFocusIntentTest.kt +++ b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/editor/EditorFocusIntentTest.kt @@ -12,7 +12,7 @@ import org.junit.Test /** * Covers the display-intent decoding shared by tryShowTextDocument and * workbench_diff, the inverse platform focus mapping, and the diff routing - * decision. Preserving file and diff opens share the suspending platform API. + * decision. Preserving file and diff opens share the public suspending platform API. * The real open behavior is exercised live by the UI harness, which needs a * real IDE. */ diff --git a/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/editor/EditorOpenQueueTest.kt b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/editor/EditorOpenQueueTest.kt new file mode 100644 index 0000000..f58f78f --- /dev/null +++ b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/editor/EditorOpenQueueTest.kt @@ -0,0 +1,93 @@ +package org.zoocode.jetbrains.editor + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import org.junit.Assert.* +import org.junit.Test + +class EditorOpenQueueTest { + @Test(timeout = 5000) + fun `file open waits for diff navigation to finish`() = runBlocking { + val queue = EditorOpenQueue() + val releaseDiff = CompletableDeferred() + val events = mutableListOf() + val diff = async(start = CoroutineStart.UNDISPATCHED) { + queue.open { + events.add("diff started") + releaseDiff.await() + events.add("diff completed") + } + } + val file = async(start = CoroutineStart.UNDISPATCHED) { + queue.open { events.add("file opened") } + } + assertEquals(listOf("diff started"), events) + assertFalse(file.isCompleted) + releaseDiff.complete(Unit) + diff.await() + file.await() + assertEquals(listOf("diff started", "diff completed", "file opened"), events) + } + + @Test(timeout = 5000) + fun `cancelling a waiting open does not cancel the active navigation`() = runBlocking { + val queue = EditorOpenQueue() + val release = CompletableDeferred() + val active = async(start = CoroutineStart.UNDISPATCHED) { + queue.open { release.await(); "opened" } + } + val waiting = launch(start = CoroutineStart.UNDISPATCHED) { + queue.open { fail("Cancelled waiter must never navigate") } + } + waiting.cancelAndJoin() + assertTrue(active.isActive) + release.complete(Unit) + assertEquals("opened", active.await()) + assertEquals("next", queue.open { "next" }) + } + + @Test(timeout = 5000) + fun `cancelling active navigation releases the next open`() = runBlocking { + val queue = EditorOpenQueue() + val active = launch(start = CoroutineStart.UNDISPATCHED) { + queue.open { awaitCancellation() } + } + val next = async(start = CoroutineStart.UNDISPATCHED) { queue.open { "opened" } } + assertFalse(next.isCompleted) + active.cancelAndJoin() + assertEquals("opened", next.await()) + } + @Test(timeout = 5000) + fun `timed out navigation releases the queue`() = runBlocking { + val queue = EditorOpenQueue(navigationTimeoutMillis = 50) + val started = CompletableDeferred() + val active = async(start = CoroutineStart.UNDISPATCHED) { + try { + queue.open { started.complete(Unit); awaitCancellation() } + false + } catch (_: EditorNavigationTimeoutException) { + true + } + } + started.await() + val next = async(start = CoroutineStart.UNDISPATCHED) { queue.open { "opened" } } + assertTrue(active.await()) + assertEquals("opened", next.await()) + } + + @Test(timeout = 5000) + fun `nested timeout remains cancellation rather than a queue deadline error`() = runBlocking { + val queue = EditorOpenQueue(navigationTimeoutMillis = 2000) + try { + queue.open { kotlinx.coroutines.withTimeout(25) { awaitCancellation() } } + fail("Nested timeout must propagate") + } catch (_: kotlinx.coroutines.TimeoutCancellationException) { + assertEquals("opened", queue.open { "opened" }) + } + } +} diff --git a/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/editor/EditorRoutingContractTest.kt b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/editor/EditorRoutingContractTest.kt new file mode 100644 index 0000000..243b435 --- /dev/null +++ b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/editor/EditorRoutingContractTest.kt @@ -0,0 +1,74 @@ +package org.zoocode.jetbrains.editor + +import org.jetbrains.org.objectweb.asm.ClassReader +import org.jetbrains.org.objectweb.asm.ClassVisitor +import org.jetbrains.org.objectweb.asm.MethodVisitor +import org.jetbrains.org.objectweb.asm.Opcodes +import org.junit.Assert.assertTrue +import org.junit.Assert.assertEquals +import org.junit.Test + +/** Static integration checks complement queue behavior tests without starting an IDE. + * Read compiled production methods so deleting a call-site wrapper fails the test. + */ +class EditorRoutingContractTest { + private data class Call(val callerClass: String, val caller: String, val owner: String, val method: String) + + private fun calls(root: String): List { + val calls = mutableListOf() + val visited = mutableSetOf() + fun read(name: String) { + if (!visited.add(name)) return + val visitedClass = name + val nested = mutableListOf() + val bytes = javaClass.classLoader.getResourceAsStream("$name.class")!!.use { it.readBytes() } + ClassReader(bytes).accept(object : ClassVisitor(Opcodes.ASM9) { + override fun visitInnerClass(name: String, outerName: String?, innerName: String?, access: Int) { + if (name.startsWith(root + "$")) nested.add(name) + } + override fun visitMethod(access: Int, name: String, descriptor: String, signature: String?, exceptions: Array?): MethodVisitor { + return object : MethodVisitor(Opcodes.ASM9) { + override fun visitMethodInsn(opcode: Int, owner: String, method: String, descriptor: String, isInterface: Boolean) { + calls.add(Call(visitedClass, name, owner, method)) + } + } + } + }, ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES) + nested.forEach { read(it) } + } + read(root) + return calls + } + + @Test + fun `production file and deliberate diff opens enter the same queue`() { + val calls = calls("org/zoocode/jetbrains/editor/EditorAndDocManager") + for (method in listOf("openFileAsync", "openDiffEditor")) { + assertTrue("$method must enter EditorOpenQueue", calls.any { + it.callerClass == "org/zoocode/jetbrains/editor/EditorAndDocManager" && + it.caller == method && it.owner == "org/zoocode/jetbrains/editor/EditorOpenQueue" && it.method == "open" + }) + } + } + + @Test + fun `document creation and post edit refresh use filesystem paths`() { + for (root in listOf("org/zoocode/jetbrains/actors/MainThreadDocuments", "org/zoocode/jetbrains/editor/EditorHolder")) { + assertTrue("$root must convert URI to fsPath for java File", calls(root).any { + val expectedCaller = if (root.endsWith("MainThreadDocuments")) + it.callerClass == root && it.caller == "tryOpenDocument" + else it.callerClass.startsWith(root + "\$applyEdit\$") + expectedCaller && it.owner == "org/zoocode/jetbrains/util/URI" && it.method == "getFsPath" + }) + } + } + + @Test + fun `bulk file create delete and both rename endpoints use filesystem paths`() { + val calls = calls("org/zoocode/jetbrains/actors/MainThreadBulkEdits") + assertEquals("All four file-operation conversions must use fsPath", 4, calls.count { + it.caller == "tryApplyWorkspaceEdit" && + it.owner == "org/zoocode/jetbrains/util/URI" && it.method == "getFsPath" + }) + } +} diff --git a/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/editor/WorkspaceEditTest.kt b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/editor/WorkspaceEditTest.kt new file mode 100644 index 0000000..b1bbdbc --- /dev/null +++ b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/editor/WorkspaceEditTest.kt @@ -0,0 +1,103 @@ +package org.zoocode.jetbrains.editor + +import com.google.gson.Gson +import org.junit.Assert.assertEquals +import org.junit.Test +import org.zoocode.jetbrains.util.URI + +class WorkspaceEditTest { + @Test + fun `IDE file events and RPC edits share one document identity`() { + val ideResource = URI.file("C:/workspace/Main.java") + val rpcResource = WorkspaceEdit.from("""{"edits":[{"resource":{"scheme":"file","path":"C:/workspace/Main.java"},"textEdit":{"range":{"startLineNumber":1,"startColumn":1,"endLineNumber":1,"endColumn":10},"text":"solheim_e2e"}}]}""").texts.single().resource + val documents = hashMapOf(ideResource to false) + documents[rpcResource] = true + assertEquals("An edit must update the original document rather than add a second one", 1, documents.size) + assertEquals(true, documents[ideResource]) + assertEquals(rpcResource, ideResource) + assertEquals(rpcResource.toString(), ideResource.toString()) + } + + @Test + fun `editing an IDE document sends a dirty change rather than a second document`() { + val ideResource = URI.file("C:/workspace/Main.java") + val rpcResource = WorkspaceEdit.from("""{"edits":[{"resource":{"scheme":"file","path":"C:/workspace/Main.java"},"textEdit":{"range":{"startLineNumber":1,"startColumn":1,"endLineNumber":1,"endColumn":10},"text":"solheim_e2e"}}]}""").texts.single().resource + val original = ModelAddedData(ideResource, 1, listOf("throwaway"), "\n", "java", false, "utf8") + val previous = DocumentsAndEditorsState(documents = hashMapOf(ideResource to original)) + val current = DocumentsAndEditorsState(documents = hashMapOf(ideResource to original)) + current.documents[rpcResource] = original.copy(uri = rpcResource, versionId = 2, + lines = listOf("solheim_e2e"), isDirty = true) + val delta = current.delta(previous) + assertEquals(true, delta.itemsDelta?.addedDocuments.isNullOrEmpty()) + assertEquals(1, delta.documentDeltas.size) + assertEquals(true, delta.documentDeltas[ideResource]?.isDirty) + assertEquals("solheim_e2e", delta.documentDeltas[ideResource]?.changes?.single()?.text) + } + + @Test + fun `Windows workspace edits share the open and save document path`() { + assertDocumentIdentity("C:/Users/runner/workspace/src/Main.java", "/C:/Users/runner/workspace/src/Main.java") + } + + @Test + fun `canonical Windows Unix and UNC paths retain document identity`() { + assertDocumentIdentity("/C:/workspace/Main.java", "/C:/workspace/Main.java") + assertDocumentIdentity("/workspace/Main.java", "/workspace/Main.java") + assertDocumentIdentity("/share/Main.java", "/share/Main.java", "server") + } + + @Test + fun `file edits normalize both rename resources and preserve options`() { + fun resource(path: String) = mapOf("scheme" to "file", "path" to path) + val edits = listOf( + mapOf("fileEdit" to true, "newResource" to resource("C:/workspace/new.txt")), + mapOf("fileEdit" to true, "oldResource" to resource("C:/workspace/old.txt")), + mapOf("fileEdit" to true, "oldResource" to resource("C:/workspace/old.txt"), + "newResource" to resource("C:/workspace/new.txt"), + "options" to mapOf("overwrite" to true, "copy" to true, "contents" to "aGVsbG8="), + "metadata" to mapOf("isRefactoring" to true)) + ) + val result = WorkspaceEdit.from(Gson().toJson(mapOf("edits" to edits))) + assertEquals(0, result.texts.size) + assertEquals(3, result.files.size) + assertEquals(null, result.files[0].oldResource) + assertEquals(URI.file("C:/workspace/new.txt"), result.files[0].newResource) + assertEquals(URI.file("C:/workspace/old.txt"), result.files[1].oldResource) + assertEquals(null, result.files[1].newResource) + val rename = result.files[2] + assertEquals(URI.file("C:/workspace/old.txt"), rename.oldResource) + assertEquals(URI.file("C:/workspace/new.txt"), rename.newResource) + assertEquals(true, rename.options?.overwrite) + assertEquals(true, rename.options?.copy) + assertEquals("aGVsbG8=", rename.options?.contents) + assertEquals(true, rename.metadata?.isRefactoring) + } + + @Test + fun `filesystem paths decode drive UNC and escaped characters`() { + val windows = System.getProperty("os.name").lowercase().contains("windows") + fun separators(path: String) = if (windows) path.replace('/', '\\') else path + assertEquals(separators("c:/workspace/a b.txt"), URI.parse("file:///C:/workspace/a%20b.txt").fsPath) + assertEquals(separators("//server/share/a b.txt"), URI.parse("file://server/share/a%20b.txt").fsPath) + assertEquals(separators("/workspace/a b.txt"), URI.parse("file:///workspace/a%20b.txt").fsPath) + } + + private fun assertDocumentIdentity(editPath: String, savePath: String, authority: String = "") { + val components = mapOf("scheme" to "file", "authority" to authority, + "path" to editPath, "query" to "", "fragment" to "") + val dto = Gson().toJson(mapOf("edits" to listOf(mapOf( + "resource" to components, + "textEdit" to mapOf("range" to mapOf("startLineNumber" to 1, "startColumn" to 1, + "endLineNumber" to 1, "endColumn" to 10), "text" to "solheim_e2e"), + "metadata" to mapOf("isRefactoring" to false) + )))) + val edit = WorkspaceEdit.from(dto).texts.single() + val savedResource = createURI(components + ("path" to savePath)) + // Document holders are looked up by path; a mismatch makes save miss the edited holder. + assertEquals(savedResource.path, edit.resource.path) + assertEquals(savedResource.authority, edit.resource.authority) + assertEquals("solheim_e2e", edit.textEdit.text) + assertEquals(10, edit.textEdit.range.endColumn) + assertEquals(false, edit.metadata?.isRefactoring) + } +} diff --git a/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/ipc/proxy/LazyPromiseTest.kt b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/ipc/proxy/LazyPromiseTest.kt index 2b866ee..11f527d 100644 --- a/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/ipc/proxy/LazyPromiseTest.kt +++ b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/ipc/proxy/LazyPromiseTest.kt @@ -84,7 +84,10 @@ class LazyPromiseTest { promise.await() fail("Expected remote failure") } catch (actual: IllegalStateException) { - assertSame(error, actual) + // The IDE's coroutine runtime can recover the asynchronous stack by + // copying the exception and retaining the original as its cause. + assertTrue(actual === error || actual.cause === error) + assertEquals("remote failure", actual.message) } } diff --git a/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/terminal/TerminalPtyBuilderTest.kt b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/terminal/TerminalPtyBuilderTest.kt index b4f1c46..b7b49dc 100644 --- a/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/terminal/TerminalPtyBuilderTest.kt +++ b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/terminal/TerminalPtyBuilderTest.kt @@ -45,7 +45,12 @@ class TerminalPtyBuilderTest { val commandField = PtyProcessBuilder::class.java.getDeclaredField("myCommand") commandField.isAccessible = true - assertArrayEquals(arrayOf("/bin/sh", "-i"), commandField.get(builder) as Array<*>) + val command = commandField.get(builder) + val arguments = if (command is Array<*>) command else { + // Newer pty4j stores a public Command value instead of String[]. + command.javaClass.getMethod("toArray").invoke(command) as Array<*> + } + assertArrayEquals(arrayOf("/bin/sh", "-i"), arguments) val environmentField = PtyProcessBuilder::class.java.getDeclaredField("myEnvironment") environmentField.isAccessible = true diff --git a/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/util/ExecutablePathTest.kt b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/util/ExecutablePathTest.kt new file mode 100644 index 0000000..fd3503e --- /dev/null +++ b/jetbrains_plugin/src/test/kotlin/org/zoocode/jetbrains/util/ExecutablePathTest.kt @@ -0,0 +1,112 @@ +package org.zoocode.jetbrains.util + +import org.junit.Assert.* +import org.junit.Assume.assumeFalse +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +class ExecutablePathTest { + @get:Rule val temporary = TemporaryFolder(File(".").absoluteFile) + + private fun executable(directory: File, name: String): File = File(directory, name).apply { + writeText("test executable") + check(setExecutable(true)) + } + + @Test fun `first executable in PATH wins and the requested name is used`() { + assumeFalse(File.separatorChar == '\\') + val first = temporary.newFolder("first") + val second = temporary.newFolder("second") + val expected = executable(first, "custom-node") + executable(second, "custom-node") + assertEquals(expected, findExecutableOnPath("custom-node", "$first:$second", false)) + } + + @Test fun `missing files directories and non executable files are skipped`() { + assumeFalse(File.separatorChar == '\\') + val first = temporary.newFolder("first") + File(first, "node").writeText("not executable") + val second = temporary.newFolder("second") + val expected = executable(second, "node") + assertEquals(expected, findExecutableOnPath("node", "$first:$second", false)) + assertNull(findExecutableOnPath("missing", "$first:$second", false)) + assertNull(findExecutableOnPath("second", temporary.root.path, false)) + } + + @Test fun `Windows lookup honors PATHEXT order quoted directories and explicit suffixes`() { + val directory = temporary.newFolder("with spaces") + val cmd = executable(directory, "node.CMD") + val exe = executable(directory, "node.EXE") + assertEquals(cmd, findExecutableOnPath("node", "\"$directory\"", true, ".CMD;.EXE")) + assertEquals(exe, findExecutableOnPath("node.EXE", directory.path, true, ".CMD;.EXE")) + assertEquals(exe, findExecutableOnPath("node", directory.path, true)) + } + + @Test fun `relative PATH entries cannot select an existing executable`() { + val directory = temporary.newFolder("relative-path") + val expected = executable(directory, "node.EXE") + val relative = File(".").canonicalFile.toPath() + .relativize(directory.canonicalFile.toPath()).toString() + assertFalse(File(relative).isAbsolute) + assertTrue(File(relative).isDirectory) + assertEquals(expected, findExecutableOnPath("node.EXE", directory.path, true, ".EXE")) + assertNull(findExecutableOnPath("node.EXE", relative, true, ".EXE")) + } + + @Test fun `slash in executable name cannot escape the PATH directory`() { + val root = temporary.newFolder("traversal") + val sub = File(root, "sub").apply { mkdir() } + val expected = executable(root, "node.EXE") + assertEquals(expected, findExecutableOnPath("node.EXE", root.path, true, ".EXE")) + assertNull(findExecutableOnPath("../node.EXE", sub.path, true, ".EXE")) + } + + @Test fun `backslash in executable name cannot select an existing file`() { + val directory = temporary.newFolder("backslash") + // Backslash is a directory separator on Windows and a literal filename on Unix. + val target = File(directory, "dir\\node.EXE") + target.parentFile.mkdirs() + executable(target.parentFile, target.name) + assertTrue(target.isFile && target.canExecute()) + assertNull(findExecutableOnPath("dir\\node.EXE", directory.path, true, ".EXE")) + } + + @Test fun `Windows PATH uses semicolons and skips missing directories`() { + val missing = File(temporary.root, "missing") + val directory = temporary.newFolder("second") + val expected = executable(directory, "node.EXE") + assertEquals(expected, findExecutableOnPath("node", "$missing;$directory", true, ".EXE")) + } + + @Test fun `Windows malformed PATHEXT falls back or ignores entries without a dot`() { + val directory = temporary.newFolder("extensions") + val expected = executable(directory, "node.CMD") + executable(directory, "nodeEXE") + for (extensions in listOf(null, "", ";;", "EXE;.CMD")) { + assertEquals(extensions, expected, findExecutableOnPath("node", directory.path, true, extensions)) + } + } + + @Test fun `Windows default extensions keep their precedence`() { + val directory = temporary.newFolder("defaults") + val candidates = listOf(".COM", ".EXE", ".BAT", ".CMD") + .map { executable(directory, "node$it") } + for (expected in candidates) { + assertEquals(expected, findExecutableOnPath("node", directory.path, true)) + assertTrue(expected.delete()) + } + } + + @Test fun `Windows explicit extension matching ignores case`() { + val directory = temporary.newFolder("case") + val expected = executable(directory, "node.exe") + assertEquals(expected, findExecutableOnPath("node.exe", directory.path, true, ".EXE")) + } + + @Test fun `absent PATH and blank names are rejected`() { + assertNull(findExecutableOnPath("node", null, false)) + assertNull(findExecutableOnPath("", temporary.root.path, true)) + } +} diff --git a/scripts/inspect-editor-sdk.py b/scripts/inspect-editor-sdk.py new file mode 100644 index 0000000..7730612 --- /dev/null +++ b/scripts/inspect-editor-sdk.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +"""Record SDK signatures/annotations without loading IDE bytecode. +Usage: inspect-editor-sdk.py OUTPUT_DIR SDK_DIR [SDK_DIR ...] +Requires javap on PATH. Records generated bytecode metadata, not SDK source. +""" +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import zipfile + +CLASSES = [ + 'com/intellij/openapi/fileEditor/FileEditorManager', + 'com/intellij/openapi/fileEditor/ex/FileEditorManagerEx', + 'com/intellij/platform/backend/navigation/NavigationRequest', + 'com/intellij/platform/ide/navigation/NavigationService', + 'org/jetbrains/plugins/terminal/LocalTerminalDirectRunner', +] + + +def inspect(output, sdk): + info = json.loads((sdk / 'product-info.json').read_text()) + build = f"{info['productCode']}-{info['buildNumber']}" + target = output / build + target.mkdir(parents=True, exist_ok=True) + remaining, records = set(CLASSES), [] + jars = sorted(list((sdk / 'lib').glob('*.jar')) + + list((sdk / 'plugins/terminal/lib').glob('*.jar'))) + for jar in jars: + with zipfile.ZipFile(jar) as archive: + found = remaining.intersection(n[:-6] for n in archive.namelist() if n.endswith('.class')) + for name in sorted(found): + verbose = subprocess.check_output(['javap', '-v', '-p', '-classpath', str(jar), name.replace('/', '.')], text=True) + body = verbose[verbose.index('\n{') + 2:] + lines, keep = [], True + for line in body.splitlines(): + if line.startswith(' ') and not line.startswith(' '): + keep = True + if line.strip() in ('Code:', 'kotlin.Metadata('): + keep = False + if keep: + lines.append(line) + (target / (name.rsplit('/', 1)[-1] + '.txt')).write_text('\n'.join(lines) + '\n') + records.append({'class': name, 'jar': str(jar.relative_to(sdk)), + 'class_sha256': hashlib.sha256(archive.read(name + '.class')).hexdigest(), + 'jar_sha256': hashlib.sha256(jar.read_bytes()).hexdigest()}) + remaining.remove(name) + (target / 'sdk.json').write_text(json.dumps({'product': info['productCode'], 'build': info['buildNumber'], 'classes': records, 'missing': sorted(remaining)}, indent=2) + '\n') + if remaining: + raise SystemExit(f'{build}: missing {remaining}') + + +if __name__ == '__main__': + for sdk in sys.argv[2:]: + inspect(Path(sys.argv[1]), Path(sdk))