Repository navigation
Feat/idea plugin - #1031
Feat/idea plugin#1031
Conversation
|
🔍 OpenCodeReview found 109 issue(s) in this PR.
|
| ideaVersion { | ||
| sinceBuild = "251" | ||
| } |
There was a problem hiding this comment.
Missing untilBuild configuration: With IntelliJ Platform Gradle Plugin 2.x, when untilBuild is not explicitly set, it defaults to ${sinceBuild}.*, i.e., 251.*. This means the plugin will only be compatible with IntelliJ IDEA 2025.1.x and will not install on 2025.2 (build 252) or later.
If this is intentional (pinning to a specific version branch), it should be documented with a comment. If broader forward compatibility is desired, untilBuild should be set explicitly (e.g., untilBuild = "252.*" or removed entirely via untilBuild = provider { null } to allow all future versions).
Suggestion:
| ideaVersion { | |
| sinceBuild = "251" | |
| } | |
| ideaVersion { | |
| sinceBuild = "251" | |
| // untilBuild defaults to "251.*" — plugin won't install on IDEA 2025.2+. | |
| // Set explicitly or use `provider { null }` to allow all future versions. | |
| untilBuild = "252.*" | |
| } |
| val npmExecutable: String? = providers.environmentVariable("PATH").orElse("").get() | ||
| .split(File.pathSeparator) | ||
| .asSequence() | ||
| .filter(String::isNotBlank) | ||
| .map { File(it, npmCommand) } | ||
| .firstOrNull { it.canExecute() } | ||
| ?.absolutePath |
There was a problem hiding this comment.
The npm path resolution only scans the PATH environment variable. On macOS, when IntelliJ IDEA is launched from the Finder (not a terminal), the PATH often lacks /opt/homebrew/bin (Apple Silicon) or /usr/local/bin (Intel), which are the default Homebrew Node.js installation paths. Consider adding a fallback that checks well-known system paths before giving up.
For example, append a search through common paths:
val wellKnownPaths = listOf("/usr/local/bin", "/opt/homebrew/bin", "/usr/bin")
val npmExecutable: String? = /* existing PATH search */
?: wellKnownPaths.map { File(it, npmCommand) }.firstOrNull { it.canExecute() }?.absolutePath| inputs.file(frontendDir.file("package.json")) | ||
| outputs.dir(frontendDir.dir("node_modules")) |
There was a problem hiding this comment.
package-lock.json (or package.json-lock) is not declared as a task input. If the lock file changes (e.g., after npm update or a security audit fix) but package.json remains the same, Gradle will consider this task UP-TO-DATE and skip npm install, resulting in stale dependencies. Consider adding the lock file as an input, or use a .orNull approach since it might not exist on first run.
Suggestion:
| inputs.file(frontendDir.file("package.json")) | |
| outputs.dir(frontendDir.dir("node_modules")) | |
| inputs.file(frontendDir.file("package.json")) | |
| frontendDir.file("package-lock.json").asFile.takeIf { it.exists() }?.let { inputs.file(it) } | |
| outputs.dir(frontendDir.dir("node_modules")) |
| if (config.llm.url && config.llm.model && config.llm.authToken) { | ||
| return { | ||
| kind: 'legacy', | ||
| name: 'legacy', | ||
| displayName: 'Legacy LLM 端点', | ||
| model: config.llm.model, | ||
| detail: config.llm.url, | ||
| }; | ||
| } |
There was a problem hiding this comment.
The hardcoded Chinese string 'Legacy LLM 端点' breaks i18n pattern. The codebase has proper i18n support with ext.config.legacyDisplayName key defined for both English ('Legacy LLM Endpoint') and Chinese ('Legacy LLM 端点'). This function should not hardcode language-specific strings. However, since the sole consumer (ConfigView.tsx line 208) already handles i18n by overriding this value for legacy providers, the hardcoded string here has no functional impact but creates confusion and maintenance burden.
Suggestion:
| if (config.llm.url && config.llm.model && config.llm.authToken) { | |
| return { | |
| kind: 'legacy', | |
| name: 'legacy', | |
| displayName: 'Legacy LLM 端点', | |
| model: config.llm.model, | |
| detail: config.llm.url, | |
| }; | |
| } | |
| if (config.llm.url && config.llm.model && config.llm.authToken) { | |
| return { | |
| kind: 'legacy', | |
| name: 'legacy', | |
| displayName: 'legacy', // Consumer handles i18n via 'ext.config.legacyDisplayName' | |
| model: config.llm.model, | |
| detail: config.llm.url, | |
| }; | |
| } |
| export function buildCustomCreateSaveEntries(params: { | ||
| name: string; | ||
| protocol: string; | ||
| url: string; | ||
| model: string; | ||
| models: string; | ||
| apiKey: string; | ||
| authHeader: string; | ||
| }): ConfigEntry[] { |
There was a problem hiding this comment.
buildCustomCreateSaveEntries and buildCustomUpdateSaveEntries share substantial duplicate logic (both construct nearly identical ConfigEntry arrays for custom providers with protocol, url, model, optional models, provider name, optional api_key, optional auth_header). The only difference is that create always includes api_key while update conditionally includes it based on apiKeyChanged. This duplication increases maintenance burden and risk of divergence. Consider extracting a shared helper function or unifying these into a single function with an options parameter.
Suggestion:
| export function buildCustomCreateSaveEntries(params: { | |
| name: string; | |
| protocol: string; | |
| url: string; | |
| model: string; | |
| models: string; | |
| apiKey: string; | |
| authHeader: string; | |
| }): ConfigEntry[] { | |
| export function buildCustomProviderSaveEntries(params: { | |
| name: string; | |
| protocol: string; | |
| url: string; | |
| model: string; | |
| models: string; | |
| apiKey: string; | |
| authHeader: string; | |
| mode: 'create' | 'update'; | |
| apiKeyChanged?: boolean; | |
| }): ConfigEntry[] { | |
| const models = params.models.trim(); | |
| const includeApiKey = params.mode === 'create' || (params.apiKeyChanged && params.apiKey.trim()); | |
| const entries: ConfigEntry[] = [ | |
| { key: `custom_providers.${params.name}.protocol`, value: params.protocol }, | |
| { key: `custom_providers.${params.name}.url`, value: params.url.trim() }, | |
| { key: `custom_providers.${params.name}.model`, value: params.model.trim() }, | |
| ...(includeApiKey ? [{ key: `custom_providers.${params.name}.api_key`, value: params.apiKey.trim() }] : []), | |
| ...(models ? [{ key: `custom_providers.${params.name}.models`, value: models }] : []), | |
| { key: 'provider', value: params.name.trim() }, | |
| ]; | |
| if (params.authHeader.trim()) { | |
| entries.push({ key: `custom_providers.${params.name}.auth_header`, value: params.authHeader.trim() }); | |
| } | |
| return entries; | |
| } |
| useEffect(() => { | ||
| if (mode === ReviewMode.Branch && from && to) onRequestModeFiles(ReviewMode.Branch, from, to); | ||
| }, [mode, from, to]); |
There was a problem hiding this comment.
Missing useEffect dependency (onRequestModeFiles): Both useEffect hooks call onRequestModeFiles but do not include it in their dependency arrays. In App.tsx, requestModeFiles is defined as a regular function inside the component body (not wrapped in useCallback), meaning its reference changes on every render. Omitting it from the dependency array means the effect captures a stale closure — if the parent recreates this function (e.g., due to a store change), the effect may call an outdated version. Either add onRequestModeFiles to the dependency arrays, or wrap it in useCallback in the parent.
| useEffect(() => { | ||
| if (mode === ReviewMode.Commit && commit) onRequestModeFiles(ReviewMode.Commit, undefined, undefined, commit); | ||
| }, [mode, commit]); |
| const willRequest = mode === ReviewMode.Workspace || (mode === ReviewMode.Branch && !!from && !!to) || (mode === ReviewMode.Commit && !!commit); | ||
| const loading = filesLoading && willRequest; | ||
| // 可发起审查的前置条件:按 tab 校验选择已就绪,且有待审查文件、不在加载/审查中。 | ||
| const selectionReady = | ||
| mode === ReviewMode.Workspace || (mode === ReviewMode.Branch && !!from && !!to) || (mode === ReviewMode.Commit && !!commit); |
There was a problem hiding this comment.
Duplicate computation: willRequest and selectionReady compute the exact same boolean expression (mode === ReviewMode.Workspace || (mode === ReviewMode.Branch && !!from && !!to) || (mode === ReviewMode.Commit && !!commit)). One of them should be removed and the other reused — e.g., just use selectionReady directly in the loading calculation: const loading = filesLoading && selectionReady;.
| override val isOpen: Boolean | ||
| get() = dialog?.isShowing == true |
There was a problem hiding this comment.
Reading dialog?.isShowing accesses Swing component hierarchy state, which per Swing's single-thread rule should only be called on the EDT. However, isOpen has no EDT enforcement and could be called from any thread (e.g., from ConfigPanelRouter background threads or other services). This thread-safety violation could cause subtle race conditions or inconsistent reads. Consider either enforcing EDT access or using SwingUtilities.invokeLater to safely read the property.
Suggestion:
| override val isOpen: Boolean | |
| get() = dialog?.isShowing == true | |
| override val isOpen: Boolean | |
| get() { | |
| var result = false | |
| if (ApplicationManager.getApplication().isDispatchThread) { | |
| result = dialog?.isShowing == true | |
| } else { | |
| ApplicationManager.getApplication().invokeAndWait { | |
| result = dialog?.isShowing == true | |
| } | |
| } | |
| return result | |
| } |
| <html lang="${locale.toHtmlLang()}"><head><meta charset="UTF-8"></head> | ||
| <body style="font-family: sans-serif; padding: 16px; line-height: 1.6"> | ||
| <h3>${HostStrings.t(locale, "ext.webview.missingBundleTitle")}</h3> | ||
| <p>${HostStrings.t(locale, "ext.webview.missingBundleBody", "resource" to resource)}</p> |
There was a problem hiding this comment.
The resource parameter is interpolated into the HTML template via HostStrings.t() without HTML entity escaping. While the current callers only pass hardcoded classpath strings (/webview/webview.js, /webview/configPanel.js), this creates a fragile invariant: if a future caller passes a resource path containing <, >, or & (e.g., via a parameterized path), it would break the HTML or create an injection vector inside the <code> tag in missingBundleBody.
Consider adding a lightweight HTML-escape for the resource value before passing it to HostStrings.t(), or document the constraint that resource must be free of HTML special characters.
| content.split("\n").forEachIndexed { index, raw -> | ||
| val n = normalizeLine(raw.removeSuffix("\r")) |
There was a problem hiding this comment.
Bug: \r handling inconsistency between splitAndNormalize and findLinesByExistingCode.
In findLinesByExistingCode, the content side (line 74) strips \r via raw.removeSuffix("\r") before calling normalizeLine. However, splitAndNormalize (used to process the existingCode target on line 68) does NOT strip \r — it only calls normalizeLine, which only trims and strips leading +/-.
If existingCode contains \r\n line endings (common on Windows or when CLI output uses CRLF), the target lines will retain trailing \r after normalizeLine (since trim() does strip it — but wait, actually trim() strips whitespace including \r... let me re-check).
Actually String.trim() in Kotlin does strip \r since it's whitespace. So the removeSuffix("\r") on the content side is redundant with trim() inside normalizeLine. However, this means the removeSuffix("\r") call on line 74 is misleading dead code — it suggests \r needs special handling, but normalizeLine already covers it via trim(). Consider removing the redundant removeSuffix("\r") on line 74 for clarity, or adding a comment explaining it's defensive.
| private fun jumpToFirstMounted() { | ||
| val first = synchronized(lock) { mounts.keys.minOrNull() } ?: return | ||
| if (ApplicationManager.getApplication().isDispatchThread) { | ||
| ApplicationManager.getApplication().executeOnPooledThread { | ||
| if (!project.isDisposed) jumpTo(first) | ||
| } | ||
| } else { | ||
| jumpTo(first) | ||
| } | ||
| } |
There was a problem hiding this comment.
Unnecessary pooled-thread detour in jumpToFirstMounted
When called from EDT (the common case from show()'s invokeLater), this dispatches jumpTo to a pooled thread, which for workspace targets immediately calls invokeLater to return to EDT. This round-trip introduces unnecessary latency and a timing window: if show() is called again before the pooled thread executes, mounts.keys.minOrNull() may refer to a stale or invalid index.
For diff targets, git.openDiff internally uses invokeLater anyway, so the pooled thread adds no value there either. Consider calling jumpTo(first) directly when already on EDT, or using invokeLater with a delay coalescing mechanism.
Suggestion:
| private fun jumpToFirstMounted() { | |
| val first = synchronized(lock) { mounts.keys.minOrNull() } ?: return | |
| if (ApplicationManager.getApplication().isDispatchThread) { | |
| ApplicationManager.getApplication().executeOnPooledThread { | |
| if (!project.isDisposed) jumpTo(first) | |
| } | |
| } else { | |
| jumpTo(first) | |
| } | |
| } | |
| private fun jumpToFirstMounted() { | |
| val first = synchronized(lock) { mounts.keys.minOrNull() } ?: return | |
| if (!project.isDisposed) jumpTo(first) | |
| } |
| handleMessage(msg) | ||
| } catch (e: Exception) { | ||
| thisLogger().warn("[ocr] Config panel message handling failed", e) | ||
| post(ConfigPanelHostToWebview.PanelError(e.message ?: e.javaClass.simpleName)) |
There was a problem hiding this comment.
Raw exception messages may leak internal details to the frontend: When message handling throws, e.message ?: e.javaClass.simpleName is sent as a PanelError to the webview. For CliException, messages are pre-sanitized by extractCliError, which is fine. But for unexpected exceptions (e.g., IOException, SecurityException, or JDK internals), the raw message may contain file paths, internal state, or stack trace snippets. Since PanelError is rendered in the UI, this both exposes implementation details and provides a poor user experience (e.g., "java.nio.file.AccessDeniedException: /home/user/.opencodereview/config.json").
Consider mapping known exception types to user-friendly, localized messages, and falling back to a generic error string for unknown exceptions while logging the full details server-side.
| when (opts.mode) { | ||
| ReviewMode.WORKSPACE -> Unit | ||
| ReviewMode.BRANCH -> { | ||
| opts.from?.takeIf(String::isNotBlank)?.let { addAll(listOf("--from", it)) } | ||
| opts.to?.takeIf(String::isNotBlank)?.let { addAll(listOf("--to", it)) } | ||
| } | ||
| ReviewMode.COMMIT -> opts.commit?.takeIf(String::isNotBlank)?.let { addAll(listOf("--commit", it)) } | ||
| } |
There was a problem hiding this comment.
Inconsistent trimming. customPrompt is trimmed (.trim()) but from, to, and commit are not. This inconsistency could lead to unexpected behavior if users accidentally include leading/trailing whitespace in branch names or commit hashes. Consider applying consistent trimming to all user-provided values.
normalize() only resolves .. and . lexically, not symlinks. A symlink inside the repo pointing outside (e.g. evil_link.txt -> /etc/passwd) passes the startsWith check but refreshAndFindFileByNioFile resolves to the symlink target — reading files outside the repo. Switched normalize() to toRealPath() which resolves all symlinks, so the startsWith check catches symlink escapes.
Consistent with forceFullRepaint which already checks disposed. Prevents restarting stopped timers after dispose().
…ory leak OcrWebview's constructor calls messageBus.connect(this), which adds OcrWebview to the Disposer tree under ROOT_DISPOSABLE (no parent). Neither JcefReviewPanel nor JcefConfigPanelHost registered OcrWebview as their child, so on IDE shutdown Disposer found 11+ leaked instances. Fix: Disposer.register(this, webview) in both JcefReviewPanel and JcefConfigPanelHost. webview.dispose() is idempotent, so the existing manual dispose calls in dispose() methods are safe alongside Disposer.
- Move webview/ and shared/ from vscode/src/ to extensions/frontend/src/ - Split bridge.ts into bridge.vsc.ts and bridge.idea.ts - Shared webpack.config.js with OCR_TARGET env var (NormalModuleReplacementPlugin) - VSC webpack.config.js: only extension host config; webview build delegates to extensions/frontend - IDEA build.gradle.kts: frontendDir points to ../frontend, OCR_TARGET=idea - VSC extension host imports: ../../shared → @shared (tsconfig paths + webpack alias) - ts-loader: transpileOnly=true (type checking via tsc separately) - Delete extensions/idea/frontend/ (no longer needed) - Delete extensions/vscode/src/webview/ and src/shared/ (moved) Both VSC and IDEA builds verified: extension.js, webview.js, configPanel.js all produced successfully.
- idea: update architecture docs, remove stale UPSTREAM.md references - idea: bump version to 0.3.0 - idea: add MessageContractTest for host↔frontend message type drift - vscode: update architecture docs for shared frontend at extensions/frontend/ - vscode: fix test imports (../../../shared → @shared) broken by extraction
…place listing Replace the template default plugin icon with the project brand icon (shield+eye, transparent background, aligned with the VS Code extension); add pluginIcon_dark.svg for dark IDE themes. Expand plugin.xml description with features/prerequisites HTML for the JetBrains Marketplace listing.
Process.destroy()/destroyForcibly() only signal the direct child. The globally-installed ocr CLI is a Node launcher that spawns the Go binary as a grandchild; killing only the launcher orphans the Go process, which gets reparented to the system root and keeps running after cancellation. Snapshot descendants before SIGTERM (handles stay valid after the parent dies, while live enumeration goes blind due to reparenting), then tree-kill from the snapshot after the grace period, parent first so supervisor-like parents cannot respawn children. Applied to all six kill sites: cancel, runRaw stale/finally, install finally, killStaleInstall, and probe timeout. Fallback sites drop the isAlive guard to shrink the check-then-enumerate TOCTOU window, and kill helpers never throw so stream cleanup in finally blocks is always reached. Adds CliServiceTreeKillTest: spawns a fake CLI with a grandchild, cancels, and asserts the grandchild dies (POSIX only).
Configure pluginVerification so ./gradlew verifyPlugin has an IDE to
check against (2.x requires an explicit list); this only wires the
verification task — the packaged zip is byte-identical before/after.
Switch OcrWebview to the JBCefBrowserBase overload of JBCefJSQuery.create:
the JBCefBrowser overload is scheduled for removal and was flagged by
the verifier. Verifier verdict is now clean ("Compatible").
Add missing SPDX headers to shared config files, translate the remaining Chinese comments in extensions/frontend, exempt the webview i18n copy table in english-check, and untrack extensions/.idea.
- bridge.ts facade lets tsc resolve ./bridge, which only webpack's NormalModuleReplacementPlugin could map before (typecheck was broken) - build:webview installs frontend deps first so clean clones build - add frontend-ext and idea-ext workflows; extend vscode-ext paths filter
The idea job runs on the self-hosted host without a container, so ~/.gradle (including the ~1GB IDE distribution) already persists between runs. setup-java's post-job cache save tried to upload a 2.4GB archive and stalled the runner, leaving the job red despite green tests.
Upstream alibaba#1407 extends the license gate to kt/kts/css; the IDEA plugin and the shared frontend predated that requirement. Headers generated with scripts/add-license.sh from upstream/main.
…gate The plugin's comments and zh-cn UI strings are still Chinese. Mirror the extensions/vscode/ precedent with a TEMPORARY allowedPrefixes entry, dropped once the sources are translated. Takes effect together with upstream alibaba#1407, which adds .kt/.kts to scannedExts.
8ad8c12 to
a6c9922
Compare
The frontend-extraction refactor ran npm install inside the vscode extension package and committed the resulting npm lockfile. That package is yarn-managed (yarn.lock, yarn install --frozen-lockfile in CI), so the npm lockfile is redundant and risks drifting out of sync with yarn.lock. Nothing references it.
extensions/vscode is yarn-managed and extensions/frontend is npm-managed; ignore the other manager's lockfile in each so an accidental npm/yarn install cannot sneak a second lockfile into the repo again.
Description
Add IntelliJ IDEA (JetBrains) plugin extension for Open Code Review.
This is a new extension under
extensions/idea/that brings the samecode review workflow available in the VSCode extension to IntelliJ-based
IDEs (IDEA Community/Ultimate, WebStorm, PyCharm, etc.).
The implementation mirrors the VSCode extension architecture:
Type of Change
How Has This Been Tested?
make testpasses locallyManual testing (describe below)
./gradlew compileKotlincompiles with zero errors./gradlew test— 16 unit tests pass./gradlew runIdelaunches the plugin in the IntelliJ sandbox without errorsManually verified: sidebar tool window renders, config panel opens, configuration is persisted, workspace/branch/commit review modes work
Checklist
go fmt,go vet)Related Issues
closes #499