Skip to content

Feat/idea plugin - #1031

Merged
lizhengfeng101 merged 36 commits into
alibaba:mainfrom
Airport233:feat/idea-plugin
Sep 18, 2026
Merged

lizhengfeng101 merged 36 commits into
alibaba:mainfrom
Airport233:feat/idea-plugin

Conversation

@Airport233

Copy link
Copy Markdown
Contributor

Description

Add IntelliJ IDEA (JetBrains) plugin extension for Open Code Review.

This is a new extension under extensions/idea/ that brings the same
code review workflow available in the VSCode extension to IntelliJ-based
IDEs (IDEA Community/Ultimate, WebStorm, PyCharm, etc.).

The implementation mirrors the VSCode extension architecture:

  • JCEF-based webview for sidebar and config panel (shared HTML/JS bundle)
  • Same CLI integration (ocr review, config, install)
  • Git integration via command-line git (branch/commit/workspace modes)
  • Comment mounting with RangeHighlighter and inline panels
  • i18n support (en/zh-cn), matching the VSCode extension
  • Theme-aware CSS variables synced from IDEA's LookAndFeel

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Refactoring (no functional changes)
  • Documentation update
  • CI / Build / Tooling

How Has This Been Tested?

  • make test passes locally

  • Manual testing (describe below)

  • ./gradlew compileKotlin compiles with zero errors

  • ./gradlew test — 16 unit tests pass

  • ./gradlew runIde launches the plugin in the IntelliJ sandbox without errors

  • Manually verified: sidebar tool window renders, config panel opens, configuration is persisted, workspace/branch/commit review modes work

Checklist

  • My code follows the project's coding style (go fmt, go vet)
  • I have performed a self-review of my code
  • I have added tests that prove my fix is effective or my feature works
  • New and existing unit tests pass locally with my changes
  • I have updated the documentation accordingly (if applicable)
  • I have signed the CLA

Related Issues

closes #499

@github-actions

github-actions Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

🔍 OpenCodeReview found 109 issue(s) in this PR.

  • ✅ Successfully posted inline: 109 comment(s)

⚠️ 1 warning(s) occurred during review.


⚠️ Warnings:

  • extensions/idea/frontend/src/webview/views/FailedView.tsx (comment_refiled): comment filed against extensions/idea/frontend/src/webview/views/DoneView.tsx describes code in extensions/idea/frontend/src/webview/views/FailedView.tsx; re-filed

Comment on lines +44 to +46
ideaVersion {
sinceBuild = "251"
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · medium
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:

Suggested change
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.*"
}

Comment on lines +69 to +75
val npmExecutable: String? = providers.environmentVariable("PATH").orElse("").get()
.split(File.pathSeparator)
.asSequence()
.filter(String::isNotBlank)
.map { File(it, npmCommand) }
.firstOrNull { it.canExecute() }
?.absolutePath

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
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

Comment on lines +98 to +99
inputs.file(frontendDir.file("package.json"))
outputs.dir(frontendDir.dir("node_modules"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

other · medium
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:

Suggested change
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"))

Comment on lines +67 to +75
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,
};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

low
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:

Suggested change
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,
};
}

Comment on lines +113 to +121
export function buildCustomCreateSaveEntries(params: {
name: string;
protocol: string;
url: string;
model: string;
models: string;
apiKey: string;
authHeader: string;
}): ConfigEntry[] {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

low
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:

Suggested change
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;
}

Comment on lines +46 to +48
useEffect(() => {
if (mode === ReviewMode.Branch && from && to) onRequestModeFiles(ReviewMode.Branch, from, to);
}, [mode, from, to]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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.

Comment on lines +51 to +53
useEffect(() => {
if (mode === ReviewMode.Commit && commit) onRequestModeFiles(ReviewMode.Commit, undefined, undefined, commit);
}, [mode, commit]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
Same missing dependency issue: onRequestModeFiles is also missing from this dependency array. Same root cause and fix as the effect above.

Comment on lines +57 to +61
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
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;.

Comment on lines +36 to +37
override val isOpen: Boolean
get() = dialog?.isShowing == true

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security · low
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.

Comment on lines +73 to +74
content.split("\n").forEachIndexed { index, raw ->
val n = normalizeLine(raw.removeSuffix("\r"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
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.

Comment on lines +184 to +193
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)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · medium
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:

Suggested change
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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security · low
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.

Comment on lines +52 to +59
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)) }
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
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.

Airport233 and others added 16 commits September 18, 2026 15:41
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.
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.

@lizhengfeng101 lizhengfeng101 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

需要idea插件

2 participants