Skip to content

fix(vscode): respect the selected workspace for reviews - #1379

Open
Wanming08 wants to merge 3 commits into
alibaba:mainfrom
Wanming08:fix/vscode-workspace-selection-1350
Open

Wanming08 wants to merge 3 commits into
alibaba:mainfrom
Wanming08:fix/vscode-workspace-selection-1350

Conversation

@Wanming08

@Wanming08 Wanming08 commented Sep 17, 2026 •

Copy link
Copy Markdown

Description

In a multi-root VS Code workspace, reviews always use the first folder. Add a Project button that opens the native workspace-folder picker and use the selected folder's Git repository for changed files, branch/commit metadata, CLI reviews, diff navigation, and inline comments.

Switching projects clears old results and branch/commit selections, reattaches the Git watcher, and ignores stale responses. Selection stays fixed until the review and comment mounting finish. Results remain available if inline comments cannot mount; if the repository disappears, unavailable comment jump links stay disabled. Workspace subdirectories resolve to their Git root, and non-Git folders cannot silently review another repository.

Rebased onto e5d7ce0 after #1031. Shared UI, types, messages, and tests now live under extensions/frontend/; the VS Code host uses the new @shared/ imports. The shared UI shows the Project button only when the host supplies workspace metadata. IDEA does not expose this VS Code-only feature; its message-contract tests explicitly account for the two host-specific messages.

This addresses project selection in #1350. Result copying/exporting remains outside this PR.

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?

  • VS Code npm test -- --runInBand: 103 tests across 12 suites pass.
  • Shared frontend npm test -- --runInBand: 18 tests pass. Total remains 121 after splitting the packages.
  • Frontend npm run typecheck, both OCR_TARGET=vscode npm run build and OCR_TARGET=idea npm run build, and VS Code npm run build:extension: pass.
  • VS Code npm run lint, repository make check, and git diff --check: pass.
  • make test: all 23 Go packages pass on the rebased tree, with race detection enabled.
  • Browser smoke tests using the actual production bundles and mock host bridges verify project selection emits selectWorkspace, the returned project updates the UI, selection is disabled during review, and the IDEA bundle omits the unsupported selector. These tests make no CLI/LLM calls.
  • A source-level parity check verifies IDEA's existing message sets still match the common frontend messages after excluding the two explicitly VS Code-only messages. The Kotlin/JUnit suite was not executed because no Java runtime is available locally.
  • No interactive VS Code Extension Development Host or IntelliJ IDE test was run.

Earlier OCR CLI self-reviews used DeepSeek deepseek-v4-pro. No additional OCR/LLM API review was run for this migration; the validation above was rerun locally. Root-resolution subprocess overhead remains a possible performance follow-up.

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 (TypeScript and Go; Kotlin execution limitation noted above)
  • I have updated the documentation accordingly (if applicable)
  • I have signed the CLA
  • AI/LLM assistance is disclosed below; commits do not attribute authorship to AI, and substantive maintainer replies will come from the contributor.

AI assistance: OpenAI Codex (GPT-6) was used for investigation, implementation, tests, migration, and drafting this description. OpenCodeReview CLI with DeepSeek deepseek-v4-pro was used for the earlier self-reviews. The contributor personally reviewed the submission before it was marked ready for review. Substantive answers to maintainer questions will come from the contributor, with AI limited to translation or wording assistance.

Related Issues

Refs #1350 (project selection only). Adapts to the frontend extraction in #1031.

@Wanming08
Wanming08 marked this pull request as ready for review September 17, 2026 14:04
@github-actions

github-actions Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

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

  • ✅ Successfully posted inline: 8 comment(s)

Comment on lines 60 to 61
const root = await git.getRepositoryRoot();
if (!root) return;

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
Silent early return leaves partially-mutated state. When getRepositoryRoot() returns null, the method returns after already mutating this.git, this.comments, and this.reviewContext (lines 56-58), but before creating any threads or calling emitSync(). This leaves the CommentProvider in an inconsistent state — comments are stored but invisible, and sync listeners are never notified.

Although the caller (SidebarProvider.startReview) currently guards against a missing repo root before invoking show, this silent return is fragile: if future refactoring changes the caller's guard or adds new call sites, the inconsistency would surface as a hard-to-debug UI bug.

Consider either throwing an error (so the caller's try/catch logs a warning) or calling emitSync() before returning to ensure listeners see a consistent empty state.

try {
const cwd = await git.getRepositoryRoot();
if (!cwd) {
this.post({ type: 'stateChange', state: 'failed', error: t(resolveLocale(vscode.env.language), 'ext.noRepository') });

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
Minor: Redundant locale resolution. resolveLocale(vscode.env.language) is called inline three times within this method (lines 72, 79, 118). Consider resolving it once at the top of handle() (or caching it as a class field) and reusing the value, consistent with how the ready handler already assigns it to a local variable.

Comment on lines +127 to +145
onDone: (result) => {
completion = (async () => {
try {
if (result.comments.length) {
await this.comments.show(result.comments, {
mode: msg.options.mode,
from: msg.options.from,
to: msg.options.to,
commit: msg.options.commit,
}, git);
}
} catch (e) {
this.post({
type: 'logLine',
line: { level: 'warn', text: `[ocr] Unable to display inline comments: ${e instanceof Error ? e.message : String(e)}` },
});
}
this.post({ type: 'reviewDone', result });
})();

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
Race condition / inconsistency: The onDone, onState, and onLog callbacks do not check git === this.git before posting messages, unlike every other async handler in this method (ready, getGitState, getModeFiles). While the reviewRunning guard currently prevents workspace switching during a review, this is a defense-in-depth concern. If any future code path mutates this.git without checking reviewRunning, stale review results would be posted to the webview and applied to the wrong workspace's comment provider.

Recommend adding a git === this.git guard inside onDone (and ideally onState/onLog) for consistency and safety:

Suggestion:

Suggested change
onDone: (result) => {
completion = (async () => {
try {
if (result.comments.length) {
await this.comments.show(result.comments, {
mode: msg.options.mode,
from: msg.options.from,
to: msg.options.to,
commit: msg.options.commit,
}, git);
}
} catch (e) {
this.post({
type: 'logLine',
line: { level: 'warn', text: `[ocr] Unable to display inline comments: ${e instanceof Error ? e.message : String(e)}` },
});
}
this.post({ type: 'reviewDone', result });
})();
onDone: (result) => {
completion = (async () => {
if (git !== this.git) return;
try {
if (result.comments.length) {
await this.comments.show(result.comments, {
mode: msg.options.mode,
from: msg.options.from,
to: msg.options.to,
commit: msg.options.commit,
}, git);
}
} catch (e) {
this.post({
type: 'logLine',
line: { level: 'warn', text: `[ocr] Unable to display inline comments: ${e instanceof Error ? e.message : String(e)}` },
});
}
this.post({ type: 'reviewDone', result });
})();

Comment on lines +99 to +100
const root = await this.getRepositoryRoot();
const apiRoot = await realpath(repo.rootUri.fsPath).catch(() => null);

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
Symlink resolution asymmetry: apiRoot is resolved through realpath() (which resolves symlinks), but root from getRepositoryRoot() (git rev-parse --show-toplevel) is not. If the workspace path involves symlinks, these two values may differ even for the same repository, causing a valid repo to be incorrectly rejected. Consider applying realpath() to both sides (or neither) for consistent comparison.

Comment on lines +101 to +102
// An ancestor may be discovered before the selected nested repository.
if (!root || !apiRoot || relative(apiRoot, root) !== '') repo = null;

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 comment says "An ancestor may be discovered before the selected nested repository", but the check actually verifies that the API-reported repo root matches the git rev-parse root exactly. If the intent is to detect when VS Code's Git extension selects an ancestor repo instead of the correct nested one, consider adding a more descriptive log message when this mismatch occurs so users can diagnose why their repo is being rejected. Currently it falls through to getState: no repo which doesn't explain the root cause.

const root = await this.getRepositoryRoot();
const apiRoot = await realpath(repo.rootUri.fsPath).catch(() => null);
// An ancestor may be discovered before the selected nested repository.
if (!root || !apiRoot || relative(apiRoot, root) !== '') repo = null;

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
Potential false negative on case-insensitive filesystems (macOS, Windows). path.relative performs string-based comparison, so if apiRoot and root differ only in casing (e.g., /Users/Foo/repo vs /users/foo/repo), relative() will return a non-empty path and the valid repo will be incorrectly rejected.

Consider normalizing both paths to the same case before comparison, or using a direct equality check with case-insensitive comparison on platforms that need it:

const normalize = process.platform === 'win32' || process.platform === 'darwin'
  ? (p: string) => p.toLowerCase()
  : (p: string) => p;
if (!root || !apiRoot || normalize(apiRoot) !== normalize(root)) repo = null;

Alternatively, since you already use realpath for apiRoot, you could also apply realpath to root to ensure both are fully resolved and comparable.

Comment on lines +106 to +108
this.cache.branches = [];
this.cache.currentBranch = '';
this.cache.recentCommits = [];

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
Behavioral regression: The old code returned a fresh empty object with workspaceFiles: [] when no repo was found. Now snapshot() spreads this.cache, which may contain stale workspaceFiles from a prior Workspace-mode call. While consumers currently only read workspaceFiles in Workspace mode, returning stale data violates the contract and could cause subtle bugs if any caller inspects workspaceFiles regardless of mode. Consider also clearing this.cache.workspaceFiles = [] here to match the previous behavior.

Suggestion:

Suggested change
this.cache.branches = [];
this.cache.currentBranch = '';
this.cache.recentCommits = [];
this.cache.branches = [];
this.cache.currentBranch = '';
this.cache.recentCommits = [];
this.cache.workspaceFiles = [];

Comment on lines +64 to +71
case 'workspaceChanged':
return {
...initialState,
config: state.config,
locale: state.locale,
gitState: msg.gitState,
filesLoading: false,
};

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
Minor: Spreading initialState sets filesLoading: true (from initialState), only to immediately override it to false on the next line. While functionally correct, this is slightly misleading to readers. Consider either omitting filesLoading from the override (since you want false, not the initial true) or restructuring for clarity.

Also note that this resets reviewMode to ReviewMode.Workspace (via initialState). If the user was on Branch/Commit mode before switching workspaces, they'll be silently reset to Workspace mode. Make sure this is the intended behavior.

@lizhengfeng101

Copy link
Copy Markdown
Contributor

Heads up — #1031 just landed on main and moved the VS Code webview and shared types into a new extensions/frontend/ package, so please rebase onto the latest main and relocate any changes under extensions/vscode/src/webview/ or extensions/vscode/src/shared/ to extensions/frontend/src/.

@chaojixinren

Copy link
Copy Markdown
Contributor

The multi-root workspace selection addresses a real pain point from #1350, and the test coverage for stale responses and review-time switching looks solid. Two things before this can land:

1. Rebase needed — currently CONFLICTING with main.

2. Path comparison rejects valid repos on case-insensitive filesystems (extensions/vscode/src/extension/services/GitService.ts:100)

apiRoot goes through realpath(), but root from git rev-parse --show-toplevel does not. On macOS/Windows these can differ in casing (/Users/Foo/repo vs /users/foo/repo) or symlink resolution even for the same repository, so relative(apiRoot, root) !== '' incorrectly rejects the selected repo and branch/commit metadata silently disappears.

Before: user selects a nested repo in a multi-root workspace on macOS, sees branches and commits.
After: same setup can show empty branch/commit lists because the case mismatch nulls the repo.

Please apply realpath() to both sides (or normalize casing on darwin/win32) before comparing, and add a regression test with differently-cased paths.

Optional follow-up, not blocking: CommentProvider.show() early-returns when getRepositoryRoot() is null after already mutating this.git/this.comments without calling emitSync(), leaving sync listeners with stale state. Either throw or emit before returning.


AI assistance disclosure: This review was drafted with the help of Hermes Agent (Kimi, developed by Moonshot AI), which analyzed the PR diff, the linked issue #1350, and the existing OCR bot comments via the GitHub API. I personally reviewed the analysis and the final wording before posting; the judgments and requests in this comment are my own.

This branch has not been deployed

No deployments
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.

3 participants