Skip to content

File Decorator and Status Bar uses subscription to VSCode API - #132

Merged
Avni2000 merged 8 commits into
mainfrom
git-status-run-over-and-over
Feb 22, 2026
Merged

Avni2000 merged 8 commits into
mainfrom
git-status-run-over-and-over

Conversation

@Avni2000

@Avni2000 Avni2000 commented Feb 22, 2026 •

Copy link
Copy Markdown
Owner
  • Replaces infinitely recurring calls to git status --porcelain
  • Creates regression test for this behaviour, ensuring status bar is shown at startup (if conflicts exist at startup) and onGitChange from VSCode

Summary by CodeRabbit

  • New Features

    • Faster, per-root detection of notebook merge conflicts with earlier activation so indicators appear promptly.
    • Centralized decoration provider and a new command to query a file's decoration state (returns presence, badge, tooltip).
    • File-watcher updates decorations and status indicators on notebook create/modify/delete; status bar kept in sync.
  • Tests

    • New regression test validating status bar and file decoration behavior across the conflict lifecycle.

@coderabbitai

coderabbitai Bot commented Feb 22, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds per-root unmerged-file caching and refresh, centralizes notebook (.ipynb) conflict decoration logic with a query command, wires Git repository/file watchers to refresh snapshots and decorations, and adds an end-to-end regression test exercising status bar and decoration state across conflict lifecycles.

Changes

Cohort / File(s) Summary
Extension: decorations, watchers & command
src/extension.ts
Introduces getNotebookConflictDecoration(uri), centralizes file-decoration provisioning, registers merge-nb.getFileDecorationState, moves Git watcher init earlier, wires repository change events to refresh unmerged snapshots/status, and adds a .ipynb file watcher to emit decoration-change events.
Git integration: per-root caching & refresh
src/gitIntegration.ts
Implements per-root TTL cache, per-root snapshots and in-flight fetch coordination, streaming git-status parsing, getUnmergedFilesForRoot / refreshUnmergedFilesSnapshotForRoot, and exports refreshUnmergedFilesSnapshot(workspaceFolderOrPath?) for extension-driven refresh.
Tests: registry & regression test
src/tests/registry.ts, src/tests/statusIndicatorsRegression.test.ts
Adds a regression test entry to TEST_GROUPS and a new regression test that runs git operations to validate status bar and file-decoration indicators through startup conflict, resolution, conflict re-creation, and final resolution.
Manifest / public API
package.json, manifest_file
Exposes new command merge-nb.getFileDecorationState in the extension manifest and reflects new decoration/querying behavior in public commands.

Sequence Diagram(s)

sequenceDiagram
    participant Repo as Repository
    participant Ext as Extension
    participant Git as GitIntegration
    participant Dec as DecorationProvider
    participant Status as StatusBar

    Repo->>Ext: repository attached / state changed
    Ext->>Git: refreshUnmergedFilesSnapshot(workspaceFolder)
    Git->>Git: refreshUnmergedFilesSnapshotForRoot (stream parse, per-root cache)
    Git-->>Ext: unmerged files snapshot
    Ext->>Dec: fireDidChangeFileDecorations(uri?)
    Dec->>Git: getUnmergedFilesForRoot (cache-backed)
    Git-->>Dec: unmerged files info
    Dec-->>Ext: decoration (badge "⚠", tooltip, color)
    Ext->>Status: refresh status bar indicators
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Poem

🐰 I hopped through code with nimble paws,

Badges ⚠ bloom on conflicted jaws.
Snapshots hum and watchers peep,
Decorations wake from sleepy sleep,
Merge mended — I thump and pause.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.54% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main architectural change: replacing polling with event-driven subscriptions to VS Code's API for status bar and file decoration updates.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch git-status-run-over-and-over

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🧹 Nitpick comments (6)
src/gitIntegration.ts (2)

698-714: workspaceFolderOrPath typed as any – consider a union type.

The parameter accepts either a string path, a VS Code WorkspaceFolder-like object, or undefined. A union type would improve call-site safety:

Suggested type
-export async function refreshUnmergedFilesSnapshot(workspaceFolderOrPath?: any): Promise<void> {
+export async function refreshUnmergedFilesSnapshot(
+    workspaceFolderOrPath?: string | { uri: { fsPath: string } }
+): Promise<void> {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/gitIntegration.ts` around lines 698 - 714, The parameter
workspaceFolderOrPath on refreshUnmergedFilesSnapshot is typed as any; change it
to a precise union such as string | WorkspaceFolder | undefined (or your
project's equivalent type) to improve call-site safety, update the function
signature export async function
refreshUnmergedFilesSnapshot(workspaceFolderOrPath: string | WorkspaceFolder |
undefined): Promise<void>, and add the appropriate WorkspaceFolder type import
(e.g., from 'vscode' or your workspace types) so resolveGitRoots(pathHint) still
receives the same pathHint logic without using any.

642-665: In-flight dedup in refreshUnmergedFilesSnapshotForRoot reuses fetches that may not refresh the snapshot.

When an in-flight promise exists (set by getUnmergedFilesForRoot), this function awaits it and then sets the snapshot (line 647). This is correct, but there's a subtle ordering concern: if two refreshUnmergedFilesSnapshotForRoot calls arrive concurrently, the first enters the else branch (line 651) and sets its own fetch promise. The second hits the if (inFlight) branch (line 645), awaits the same promise, and sets the snapshot from that result. Both callers end up writing the same snapshot, which is fine.

However, the finally block (line 662–664) unconditionally deletes the cache key. If a new refresh was enqueued between the fetch start and finally, the new promise gets deleted prematurely. This is a low-probability race since these are single-threaded JS microtasks, but consider guarding the delete:

Guard against deleting a different promise
     unmergedFilesFetchPromisesByRoot.set(cacheKey, fetchPromise);
     try {
         const files = await fetchPromise;
         setSnapshotUnmergedFilesForRoot(gitRoot, files);
         return files;
     } finally {
-        unmergedFilesFetchPromisesByRoot.delete(cacheKey);
+        if (unmergedFilesFetchPromisesByRoot.get(cacheKey) === fetchPromise) {
+            unmergedFilesFetchPromisesByRoot.delete(cacheKey);
+        }
     }

The same pattern applies to getUnmergedFilesForRoot (line 694).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/gitIntegration.ts` around lines 642 - 665, The finally block in
refreshUnmergedFilesSnapshotForRoot can delete a newer in-flight promise
accidentally; modify the cleanup to only remove the cache entry if the stored
promise strictly equals the local fetchPromise (i.e., get the current value from
unmergedFilesFetchPromisesByRoot using the same cacheKey and delete only when it
=== fetchPromise). Apply the same guarded-delete pattern to
getUnmergedFilesForRoot to avoid removing a subsequent promise enqueued after
this fetch started.
src/tests/statusIndicatorsRegression.test.ts (3)

55-60: hasUnmergedConflict is hardcoded to conflict.ipynb.

The function name suggests a general-purpose check, but it only matches lines containing conflict.ipynb. If the fixture file is renamed or a different notebook is used, this will silently pass/fail incorrectly. Consider parameterizing:

Suggested refactor
-function hasUnmergedConflict(statusOutput: string): boolean {
+function hasUnmergedConflict(statusOutput: string, filename: string = 'conflict.ipynb'): boolean {
     return statusOutput
         .split('\n')
         .map((line) => line.trim())
-        .some((line) => line.startsWith('UU ') && line.includes('conflict.ipynb'));
+        .some((line) => line.startsWith('UU ') && line.includes(filename));
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/tests/statusIndicatorsRegression.test.ts` around lines 55 - 60, The
helper hasUnmergedConflict currently only detects a hardcoded filename
"conflict.ipynb"; change it to accept a filename parameter (e.g.,
hasUnmergedConflict(statusOutput: string, filename: string)) or generalize to a
pattern (e.g., detect any ".ipynb" conflict) so it reliably checks for unmerged
conflicts; update callers/tests to pass the expected filename or rely on the new
pattern and ensure the function still trims lines and checks for lines starting
with "UU " before matching the filename/pattern.

139-141: Unexplained sleep(600) — add a comment clarifying what this wait is for.

Is this waiting for the extension to activate, for Git watchers to attach, or for the decoration provider to initialize? A brief comment would help future maintainers understand whether this can be reduced or needs to be increased.

Suggested comment
     const doc = await vscode.workspace.openTextDocument(conflictFile);
     await vscode.window.showTextDocument(doc);
-    await sleep(600);
+    // Allow time for the extension to activate and Git state watchers to initialize.
+    await sleep(600);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/tests/statusIndicatorsRegression.test.ts` around lines 139 - 141, Add an
inline comment immediately above the sleep(600) call in
statusIndicatorsRegression.test.ts (the block where you call
vscode.workspace.openTextDocument and vscode.window.showTextDocument) explaining
specifically what the 600ms wait is for (e.g., "wait for extension activation",
"allow Git file watchers to attach", or "allow decoration provider to
initialize") and whether it is a conservative estimate that can be reduced;
reference the sleep(600) call and the surrounding
openTextDocument/showTextDocument steps so future maintainers know the
dependency and can safely adjust the duration.

148-164: Consider using git reset --merge instead of git merge --abort for better compatibility and clarity.

After git add conflict.ipynb (line 149), the file is staged as part of the merge resolution. While git merge --abort typically succeeds in this scenario, git reset --merge is more explicitly designed to safely handle mixed staged/unstaged states during merges and avoids any version-dependent edge cases. This would make the test more robust.

If changing the command, replace line 154:

git(workspacePath, ['merge', '--abort']);

with:

git(workspacePath, ['reset', '--merge']);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/tests/statusIndicatorsRegression.test.ts` around lines 148 - 164, The
test uses git(workspacePath, ['merge', '--abort']) to abort a recreated merge
but should use git(workspacePath, ['reset', '--merge']) to more safely handle
the mixed staged/unstaged state after git(workspacePath, ['add',
'conflict.ipynb']); update the call in the test (near the merge recreate block
that calls ensureNoUnmergedConflict and waitForIndicatorState) to use
['reset','--merge'] instead of ['merge','--abort'] so the test is more robust
across Git versions.
src/extension.ts (1)

436-461: File watcher + Git state watcher may cause redundant decoration/status-bar refreshes.

Both fileWatcher.onDidChange (line 449) and repository.state.onDidChange (line 205) fire decorationChangeEmitter and updateStatusBar(). When Git operations modify .ipynb files, both triggers fire in quick succession. This is benign because updateStatusBar uses a version counter, and decorationChangeEmitter.fire just schedules a decoration re-query, but it does cause duplicate work. If performance becomes a concern, consider debouncing the file watcher callbacks.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/extension.ts` around lines 436 - 461, File-system file watcher callbacks
(fileWatcher.onDidChange/onDidCreate/onDidDelete) and
repository.state.onDidChange both call decorationChangeEmitter.fire and
updateStatusBar, causing duplicate refreshes; debounce the file-watcher handlers
to coalesce rapid successive events before calling decorationChangeEmitter.fire
and updateStatusBar. Locate the fileWatcher callbacks in extension.ts (the
fileWatcher.onDidChange/onDidCreate/onDidDelete handlers) and wrap their bodies
in a short debounce (e.g., 100–300ms) so multiple rapid events invoke
decorationChangeEmitter.fire and updateStatusBar only once, leaving
repository.state.onDidChange unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/extension.ts`:
- Around line 190-196: The fire-and-forget async IIFE in
refreshRepositoryUnmergedSnapshot can surface an unhandled rejection if
gitIntegration.refreshUnmergedFilesSnapshot throws; wrap the await call in a
try/catch (or attach a .catch to the inner promise) inside the IIFE, log the
error via processLogger or similar and ensure decorationChangeEmitter.fire and
updateStatusBar still run or run in finally as appropriate; reference
refreshRepositoryUnmergedSnapshot, gitIntegration.refreshUnmergedFilesSnapshot,
decorationChangeEmitter.fire and updateStatusBar so you modify the async block
to catch and handle any exceptions.

In `@src/gitIntegration.ts`:
- Around line 609-640: The execAsync call in queryUnmergedFilesForRoot can
exceed Node's default 1MB stdout buffer; update the execAsync invocation in
function queryUnmergedFilesForRoot to include the same maxBuffer used elsewhere
(e.g., maxBuffer: 10 * 1024 * 1024) alongside the existing cwd: gitRoot option
so the promise won't reject on large git status output.

---

Nitpick comments:
In `@src/extension.ts`:
- Around line 436-461: File-system file watcher callbacks
(fileWatcher.onDidChange/onDidCreate/onDidDelete) and
repository.state.onDidChange both call decorationChangeEmitter.fire and
updateStatusBar, causing duplicate refreshes; debounce the file-watcher handlers
to coalesce rapid successive events before calling decorationChangeEmitter.fire
and updateStatusBar. Locate the fileWatcher callbacks in extension.ts (the
fileWatcher.onDidChange/onDidCreate/onDidDelete handlers) and wrap their bodies
in a short debounce (e.g., 100–300ms) so multiple rapid events invoke
decorationChangeEmitter.fire and updateStatusBar only once, leaving
repository.state.onDidChange unchanged.

In `@src/gitIntegration.ts`:
- Around line 698-714: The parameter workspaceFolderOrPath on
refreshUnmergedFilesSnapshot is typed as any; change it to a precise union such
as string | WorkspaceFolder | undefined (or your project's equivalent type) to
improve call-site safety, update the function signature export async function
refreshUnmergedFilesSnapshot(workspaceFolderOrPath: string | WorkspaceFolder |
undefined): Promise<void>, and add the appropriate WorkspaceFolder type import
(e.g., from 'vscode' or your workspace types) so resolveGitRoots(pathHint) still
receives the same pathHint logic without using any.
- Around line 642-665: The finally block in refreshUnmergedFilesSnapshotForRoot
can delete a newer in-flight promise accidentally; modify the cleanup to only
remove the cache entry if the stored promise strictly equals the local
fetchPromise (i.e., get the current value from unmergedFilesFetchPromisesByRoot
using the same cacheKey and delete only when it === fetchPromise). Apply the
same guarded-delete pattern to getUnmergedFilesForRoot to avoid removing a
subsequent promise enqueued after this fetch started.

In `@src/tests/statusIndicatorsRegression.test.ts`:
- Around line 55-60: The helper hasUnmergedConflict currently only detects a
hardcoded filename "conflict.ipynb"; change it to accept a filename parameter
(e.g., hasUnmergedConflict(statusOutput: string, filename: string)) or
generalize to a pattern (e.g., detect any ".ipynb" conflict) so it reliably
checks for unmerged conflicts; update callers/tests to pass the expected
filename or rely on the new pattern and ensure the function still trims lines
and checks for lines starting with "UU " before matching the filename/pattern.
- Around line 139-141: Add an inline comment immediately above the sleep(600)
call in statusIndicatorsRegression.test.ts (the block where you call
vscode.workspace.openTextDocument and vscode.window.showTextDocument) explaining
specifically what the 600ms wait is for (e.g., "wait for extension activation",
"allow Git file watchers to attach", or "allow decoration provider to
initialize") and whether it is a conservative estimate that can be reduced;
reference the sleep(600) call and the surrounding
openTextDocument/showTextDocument steps so future maintainers know the
dependency and can safely adjust the duration.
- Around line 148-164: The test uses git(workspacePath, ['merge', '--abort']) to
abort a recreated merge but should use git(workspacePath, ['reset', '--merge'])
to more safely handle the mixed staged/unstaged state after git(workspacePath,
['add', 'conflict.ipynb']); update the call in the test (near the merge recreate
block that calls ensureNoUnmergedConflict and waitForIndicatorState) to use
['reset','--merge'] instead of ['merge','--abort'] so the test is more robust
across Git versions.

Comment thread src/extension.ts Resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/extension.ts (1)

444-444: Optional: propagate CancellationToken into getNotebookConflictDecoration.

VS Code passes a CancellationToken to provideFileDecoration, but the assigned function ignores it. Since isUnmergedFile reads from an in-memory snapshot this is not a practical concern today, but if the snapshot lookup ever becomes async/IO-bound, ignoring cancellation could cause stale work to pile up.

♻️ Optional refactor
-async function getNotebookConflictDecoration(uri: vscode.Uri): Promise<vscode.FileDecoration | undefined> {
+async function getNotebookConflictDecoration(uri: vscode.Uri, token?: vscode.CancellationToken): Promise<vscode.FileDecoration | undefined> {
 	if (!backgroundConflictMonitoringEnabled || !uri.fsPath.endsWith('.ipynb')) {
 		return undefined;
 	}
+	if (token?.isCancellationRequested) {
+		return undefined;
+	}
 
 	try {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/extension.ts` at line 444, The assigned file-decoration provider
(getNotebookConflictDecoration) currently ignores the CancellationToken passed
by VS Code; update getNotebookConflictDecoration to accept a CancellationToken
parameter and propagate it into any lookup or helper (e.g., isUnmergedFile) so
callers can early-return when token.isCancellationRequested, and update the
provideFileDecoration assignment so the token argument is forwarded; also adjust
types/signatures where getNotebookConflictDecoration and isUnmergedFile are
declared to accept the token.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/extension.ts`:
- Around line 175-177: The silent catch in provideFileDecoration swallows
exceptions from gitIntegration.isUnmergedFile; change the catch to capture the
error (e.g., catch (err)) and call your debug-level logger (for example
processLogger.debug or extensionLogger.debug) with a clear message referencing
provideFileDecoration and the file path (the uri.path or similar) plus the error
details so failures are recorded; do not alter the normal return behavior (still
return undefined on error) but ensure the exception is logged for diagnosis.

---

Duplicate comments:
In `@src/extension.ts`:
- Around line 190-200: The async IIFE inside refreshRepositoryUnmergedSnapshot
correctly wraps await gitIntegration.refreshUnmergedFilesSnapshot(...) in a
try/catch, so no further changes are required: keep the existing try/catch
around the async body in refreshRepositoryUnmergedSnapshot, leave
decorationChangeEmitter.fire(undefined) and the call to updateStatusBar() inside
the try, and keep the catch logging the error (currently console.error) so
unhandled rejections from gitIntegration.refreshUnmergedFilesSnapshot are
caught.

---

Nitpick comments:
In `@src/extension.ts`:
- Line 444: The assigned file-decoration provider
(getNotebookConflictDecoration) currently ignores the CancellationToken passed
by VS Code; update getNotebookConflictDecoration to accept a CancellationToken
parameter and propagate it into any lookup or helper (e.g., isUnmergedFile) so
callers can early-return when token.isCancellationRequested, and update the
provideFileDecoration assignment so the token argument is forwarded; also adjust
types/signatures where getNotebookConflictDecoration and isUnmergedFile are
declared to accept the token.

Comment thread src/extension.ts Resolved

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🧹 Nitpick comments (4)
src/gitIntegration.ts (3)

662-685: In-flight join also writes the snapshot, duplicating the work of the originator.

When an in-flight promise already exists (lines 664–669), setSnapshotUnmergedFilesForRoot is called for the joined result. The originator of that same promise also sets the snapshot at line 680. This is harmless (same data) but redundant. A minor simplification: the joiner could simply return await inFlight without re-setting the snapshot.

Proposed simplification
     const inFlight = unmergedFilesFetchPromisesByRoot.get(cacheKey);
     if (inFlight) {
-        const files = await inFlight;
-        setSnapshotUnmergedFilesForRoot(gitRoot, files);
-        return files;
+        return inFlight;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/gitIntegration.ts` around lines 662 - 685, The join path in
refreshUnmergedFilesSnapshotForRoot redundantly calls
setSnapshotUnmergedFilesForRoot when an in-flight promise exists; change the
in-flight branch to simply await and return the existing promise result (i.e.,
return await inFlight) instead of calling setSnapshotUnmergedFilesForRoot again
so only the original fetch (the fetchPromise path that calls
queryUnmergedFilesForRoot and setCachedUnmergedFilesForRoot) updates the
snapshot; reference unmergedFilesFetchPromisesByRoot, getGitRootCacheKey,
setSnapshotUnmergedFilesForRoot, queryUnmergedFilesForRoot, and
setCachedUnmergedFilesForRoot when locating the code to modify.

627-627: Verbose logging: full git status --porcelain output is logged on every refresh.

Line 627 dumps the entire stdout of git status --porcelain at the default console.log level. In repos with many files this will produce significant log noise on every Git state change event. Consider gating this behind a debug/verbose flag or reducing it to a summary (e.g., line count only).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/gitIntegration.ts` at line 627, In getUnmergedFiles replace the
unconditional console.log of the full stdout with a gated or reduced log: either
call a debug-level logger (e.g., console.debug or existing verbose logger)
instead of console.log when a verbose flag is enabled, or log a summary like the
number of lines/files by computing stdout.split('\n').filter(Boolean).length and
include gitRoot and that count (and only include the full stdout when the
verbose flag is true). Ensure you reference the stdout variable and the
getUnmergedFiles function when making the change.

718-734: any type on the public API parameter.

workspaceFolderOrPath?: any is a loose signature for an exported function. A union type would improve discoverability and type safety for callers.

Proposed typing
-export async function refreshUnmergedFilesSnapshot(workspaceFolderOrPath?: any): Promise<void> {
+export async function refreshUnmergedFilesSnapshot(workspaceFolderOrPath?: string | { uri?: { fsPath?: string } }): Promise<void> {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/gitIntegration.ts` around lines 718 - 734, The exported function
refreshUnmergedFilesSnapshot currently accepts workspaceFolderOrPath?: any;
change this to a precise union type (for example: workspaceFolderOrPath?: string
| { uri: { fsPath: string } } | WorkspaceFolder) so callers get proper
autocompletion and type safety, and update the pathHint extraction accordingly
(keep the existing ternary and optional chaining but typed inputs will eliminate
any); ensure any references to resolveGitRoots or subsequent logic still accept
the narrowed type and adjust imports/types (e.g., WorkspaceFolder) if you
introduce VS Code types.
src/extension.ts (1)

443-468: File watcher + Git state watcher may cause redundant refreshes.

The .ipynb file watcher (lines 453–468) fires decorationChangeEmitter and updateStatusBar() on every file change, while the Git state watchers (lines 211–215) do the same on every repository.state.onDidChange. A single git merge or git add can trigger both paths nearly simultaneously, causing duplicate status-bar refreshes and decoration recomputes.

This is low-severity because updateStatusBar already has a staleness guard (statusBarRefreshVersion), but the decoration provider will still re-query isUnmergedFile redundantly. Not urgent, but worth a future TODO for debouncing or coalescing the fire events.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/extension.ts` around lines 443 - 468, File-system watchers (fileWatcher
handlers) and the Git repository watcher (repository.state.onDidChange) both
call decorationChangeEmitter.fire and updateStatusBar, causing redundant
refreshes; create a single debounced/coalescing refresh helper (e.g.,
scheduleRefresh or debouncedFire) and use it from both the fileWatcher handlers
and the repository.state.onDidChange handler so repeated calls within a short
window coalesce into one call; update usages of decorationChangeEmitter.fire,
updateStatusBar, getNotebookConflictDecoration and isUnmergedFile to rely on the
debounced helper rather than firing directly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/extension.ts`:
- Around line 160-183: getNotebookConflictDecoration currently calls
vscode.window.showErrorMessage and re-throws on every
gitIntegration.isUnmergedFile failure which can spam the user; change this by
introducing a module-level sentinel (e.g., hasShownGitCheckError) used inside
getNotebookConflictDecoration to ensure vscode.window.showErrorMessage is only
called once per activation (or deduplicated), log the full error to console as
before, and do NOT re-throw the error so provideFileDecoration simply returns
undefined on failure; locate these changes around getNotebookConflictDecoration
and the gitIntegration.isUnmergedFile error handling.

In `@src/gitIntegration.ts`:
- Around line 619-660: The git status call in queryUnmergedFilesForRoot uses
GIT_STATUS_MAX_BUFFER_BYTES (currently 1MB) which is too small for large repos;
increase GIT_STATUS_MAX_BUFFER_BYTES to match the 10MB buffer used by the other
git commands (or reuse the same 10*1024*1024 constant used by the git show
calls) so execAsync('git status --porcelain', { cwd: gitRoot, maxBuffer:
GIT_STATUS_MAX_BUFFER_BYTES }) uses a 10MB buffer to avoid spurious maxBuffer
errors.

---

Nitpick comments:
In `@src/extension.ts`:
- Around line 443-468: File-system watchers (fileWatcher handlers) and the Git
repository watcher (repository.state.onDidChange) both call
decorationChangeEmitter.fire and updateStatusBar, causing redundant refreshes;
create a single debounced/coalescing refresh helper (e.g., scheduleRefresh or
debouncedFire) and use it from both the fileWatcher handlers and the
repository.state.onDidChange handler so repeated calls within a short window
coalesce into one call; update usages of decorationChangeEmitter.fire,
updateStatusBar, getNotebookConflictDecoration and isUnmergedFile to rely on the
debounced helper rather than firing directly.

In `@src/gitIntegration.ts`:
- Around line 662-685: The join path in refreshUnmergedFilesSnapshotForRoot
redundantly calls setSnapshotUnmergedFilesForRoot when an in-flight promise
exists; change the in-flight branch to simply await and return the existing
promise result (i.e., return await inFlight) instead of calling
setSnapshotUnmergedFilesForRoot again so only the original fetch (the
fetchPromise path that calls queryUnmergedFilesForRoot and
setCachedUnmergedFilesForRoot) updates the snapshot; reference
unmergedFilesFetchPromisesByRoot, getGitRootCacheKey,
setSnapshotUnmergedFilesForRoot, queryUnmergedFilesForRoot, and
setCachedUnmergedFilesForRoot when locating the code to modify.
- Line 627: In getUnmergedFiles replace the unconditional console.log of the
full stdout with a gated or reduced log: either call a debug-level logger (e.g.,
console.debug or existing verbose logger) instead of console.log when a verbose
flag is enabled, or log a summary like the number of lines/files by computing
stdout.split('\n').filter(Boolean).length and include gitRoot and that count
(and only include the full stdout when the verbose flag is true). Ensure you
reference the stdout variable and the getUnmergedFiles function when making the
change.
- Around line 718-734: The exported function refreshUnmergedFilesSnapshot
currently accepts workspaceFolderOrPath?: any; change this to a precise union
type (for example: workspaceFolderOrPath?: string | { uri: { fsPath: string } }
| WorkspaceFolder) so callers get proper autocompletion and type safety, and
update the pathHint extraction accordingly (keep the existing ternary and
optional chaining but typed inputs will eliminate any); ensure any references to
resolveGitRoots or subsequent logic still accept the narrowed type and adjust
imports/types (e.g., WorkspaceFolder) if you introduce VS Code types.

Comment thread src/extension.ts Resolved

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/gitIntegration.ts (2)

609-668: Consider wrapping onLine invocations in try/catch for robustness.

If a future caller passes an onLine callback that throws, the exception will escape the stdout.on('data', ...) handler as an uncaught error and the wrapping promise will never settle. Today's sole caller (queryUnmergedFilesForRoot) won't throw, but this function appears designed as a reusable utility.

Suggested defensive fix
         stdout.on('data', (chunk: string) => {
             bufferedLine += chunk;
 
             let newlineIndex = bufferedLine.indexOf('\n');
             while (newlineIndex !== -1) {
                 const rawLine = bufferedLine.slice(0, newlineIndex);
                 bufferedLine = bufferedLine.slice(newlineIndex + 1);
                 const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
                 if (line.length > 0) {
-                    onLine(line);
+                    try {
+                        onLine(line);
+                    } catch (err) {
+                        gitStatus.kill();
+                        reject(err);
+                        return;
+                    }
                 }
                 newlineIndex = bufferedLine.indexOf('\n');
             }
         });

Same guard should apply to the trailing-line onLine(trailingLine) call in the close handler (line 655).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/gitIntegration.ts` around lines 609 - 668, In streamGitStatusPorcelain,
guard all calls to the provided onLine callback (inside the stdout 'data'
handler loop and the trailing-line call in the 'close' handler) with try/catch
so thrown exceptions don't escape the event handlers; on catch, reject the
surrounding Promise with the caught error (and optionally kill the spawned git
process) while protecting against double-settling (e.g., track a settled flag)
so the Promise always settles when onLine throws.

728-757: Snapshot has no TTL or invalidation — stale data risk if event subscriptions drop.

Once refreshUnmergedFilesSnapshotForRoot sets the snapshot (line 721), getUnmergedFilesForRoot always returns it (lines 729–732) and never falls through to a fresh fetch. If the VS Code git-change subscription stops firing (extension host restarts, API changes, etc.), the snapshot becomes permanently stale. The TTL cache on lines 734–737 is effectively dead code after the first refresh.

Consider either giving snapshots a generous TTL (e.g. 30 s) or clearing the snapshot map on deactivation / workspace-folder removal so the TTL cache can serve as a fallback.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/gitIntegration.ts` around lines 728 - 757, getUnmergedFilesForRoot
currently returns a persistent snapshot from getSnapshotUnmergedFilesForRoot
(set by refreshUnmergedFilesSnapshotForRoot) which can become permanently stale;
update the logic so snapshots have a TTL or are invalidated on extension
lifecycle events. Specifically: modify getUnmergedFilesForRoot to check snapshot
age (or presence of an expiry) and fall through to the existing TTL cache and
fresh fetch when stale; alternatively, add explicit invalidation hooks that
clear the snapshot (the storage used by
getSnapshotUnmergedFilesForRoot/refreshUnmergedFilesSnapshotForRoot) on
deactivation or workspace-folder removal so the TTL cache
(getCachedUnmergedFilesForRoot/setCachedUnmergedFilesForRoot) can serve as a
fallback. Ensure you reference getUnmergedFilesForRoot,
getSnapshotUnmergedFilesForRoot, refreshUnmergedFilesSnapshotForRoot, and the
cache helpers when implementing the TTL/invalidation.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/gitIntegration.ts`:
- Around line 670-701: The function queryUnmergedFilesForRoot currently swallows
errors and floods logs: instead of catching and silently returning an empty
array, propagate the error so callers can surface it (rethrow the caught error)
or call vscode.window.showErrorMessage when vscode is available; update the
catch block in queryUnmergedFilesForRoot to either throw the error after logging
or call vscode.window.showErrorMessage with a clear message including gitRoot
and the error, and ensure callers handle the thrown error to show UI feedback.
Also remove or gate the per-line console.log statements (those using
streamGitStatusPorcelain and printing status/path) behind a debug flag or delete
them to avoid flooding output for large repos, leaving only summary or error
logs (keep the final summary console.log if desired).

---

Nitpick comments:
In `@src/gitIntegration.ts`:
- Around line 609-668: In streamGitStatusPorcelain, guard all calls to the
provided onLine callback (inside the stdout 'data' handler loop and the
trailing-line call in the 'close' handler) with try/catch so thrown exceptions
don't escape the event handlers; on catch, reject the surrounding Promise with
the caught error (and optionally kill the spawned git process) while protecting
against double-settling (e.g., track a settled flag) so the Promise always
settles when onLine throws.
- Around line 728-757: getUnmergedFilesForRoot currently returns a persistent
snapshot from getSnapshotUnmergedFilesForRoot (set by
refreshUnmergedFilesSnapshotForRoot) which can become permanently stale; update
the logic so snapshots have a TTL or are invalidated on extension lifecycle
events. Specifically: modify getUnmergedFilesForRoot to check snapshot age (or
presence of an expiry) and fall through to the existing TTL cache and fresh
fetch when stale; alternatively, add explicit invalidation hooks that clear the
snapshot (the storage used by
getSnapshotUnmergedFilesForRoot/refreshUnmergedFilesSnapshotForRoot) on
deactivation or workspace-folder removal so the TTL cache
(getCachedUnmergedFilesForRoot/setCachedUnmergedFilesForRoot) can serve as a
fallback. Ensure you reference getUnmergedFilesForRoot,
getSnapshotUnmergedFilesForRoot, refreshUnmergedFilesSnapshotForRoot, and the
cache helpers when implementing the TTL/invalidation.

Comment thread src/gitIntegration.ts
Comment on lines +670 to +701
async function queryUnmergedFilesForRoot(gitRoot: string): Promise<GitFileStatus[]> {
const unmergedFiles: GitFileStatus[] = [];
let lineCount = 0;

try {
await streamGitStatusPorcelain(gitRoot, (line) => {
if (!line.trim()) {
return;
}
lineCount += 1;
const status = line.substring(0, 2);
const filePath = normalizeStatusPath(line.substring(3));
console.log(`[GitIntegration] Line: "${line}" -> status="${status}" path="${filePath}"`);

if (isUnmergedStatus(status)) {
const fullPath = path.join(gitRoot, filePath);
console.log(`[GitIntegration] -> UNMERGED: ${fullPath}`);
unmergedFiles.push({
path: fullPath,
repoPath: filePath,
status,
isUnmerged: true
});
}
});
console.log(`[GitIntegration] getUnmergedFiles: ${lineCount} non-empty lines in ${gitRoot}`);
} catch (error) {
console.error(`[GitIntegration] Error getting unmerged files for ${gitRoot}:`, error);
}

return unmergedFiles;
}

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.

⚠️ Potential issue | 🟡 Minor

Errors are swallowed — consider surfacing them via VS Code.

The PR objective states: "Introduces error surfacing for Git-related failures in VS Code", but queryUnmergedFilesForRoot catches all errors (line 696–698), logs to console.error, and silently returns an empty array. Callers cannot distinguish "no conflicts" from "git failed". Consider either re-throwing (so callers can surface a warning) or showing a vscode.window.showErrorMessage here when vscode is available.

Additionally, the console.log on line 682 fires for every git status --porcelain line. In repos with thousands of changed/untracked files, this will flood the output channel. Consider gating this behind a debug flag or removing it.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/gitIntegration.ts` around lines 670 - 701, The function
queryUnmergedFilesForRoot currently swallows errors and floods logs: instead of
catching and silently returning an empty array, propagate the error so callers
can surface it (rethrow the caught error) or call vscode.window.showErrorMessage
when vscode is available; update the catch block in queryUnmergedFilesForRoot to
either throw the error after logging or call vscode.window.showErrorMessage with
a clear message including gitRoot and the error, and ensure callers handle the
thrown error to show UI feedback. Also remove or gate the per-line console.log
statements (those using streamGitStatusPorcelain and printing status/path)
behind a debug flag or delete them to avoid flooding output for large repos,
leaving only summary or error logs (keep the final summary console.log if
desired).

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (2)
src/extension.ts (2)

36-36: decorationChangeEmitter is never disposed.

The EventEmitter is created at module scope but never pushed to context.subscriptions. Its internal listener list and resources won't be cleaned up on deactivation. Consider adding it to subscriptions inside activate().

Proposed fix

Add this inside activate(), near line 256 where statusBarItem is pushed:

 context.subscriptions.push(statusBarItem);
+context.subscriptions.push(decorationChangeEmitter);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/extension.ts` at line 36, The EventEmitter decorationChangeEmitter
created at module scope isn't disposed; inside activate() add
decorationChangeEmitter to context.subscriptions (just like statusBarItem) so VS
Code will call dispose() on it at deactivation; locate the
decorationChangeEmitter identifier and push it into context.subscriptions within
the activate() function to ensure proper cleanup.

209-219: Debounce repository.state.onDidChange to avoid excessive git subprocess spawning.

repository.state.onDidChange fires on every index, working-tree, and HEAD change — potentially many times per second during staging, rebasing, or merging. Each event currently triggers a git subprocess (via refreshUnmergedFilesSnapshot) plus a full decoration refresh (fire(undefined) re-queries all visible .ipynb files). Given the PR goal of eliminating excessive git status calls, a short debounce here would collapse bursts into a single refresh.

Proposed debounce approach
+	const debounceTimers = new Map<Repository, ReturnType<typeof setTimeout>>();
+
 	const attachRepositoryWatcher = (repository: Repository): void => {
 		if (!repository?.state || watchedRepositories.has(repository)) {
 			return;
 		}
 		watchedRepositories.add(repository);
 		refreshRepositoryUnmergedSnapshot(repository);
 		context.subscriptions.push(
 			repository.state.onDidChange(() => {
-				refreshRepositoryUnmergedSnapshot(repository);
+				const existing = debounceTimers.get(repository);
+				if (existing) { clearTimeout(existing); }
+				debounceTimers.set(repository, setTimeout(() => {
+					debounceTimers.delete(repository);
+					refreshRepositoryUnmergedSnapshot(repository);
+				}, 300));
 			})
 		);
 	};
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/extension.ts` around lines 209 - 219, The repository change handler in
attachRepositoryWatcher triggers refreshRepositoryUnmergedSnapshot on every
repository.state.onDidChange causing many git subprocesses; wrap the onDidChange
callback in a short debounce (e.g., 100-300ms) so rapid bursts collapse to one
call. Update attachRepositoryWatcher to create a debounced function (per
repository) that calls refreshRepositoryUnmergedSnapshot (and downstream
refreshUnmergedFilesSnapshot/fire(undefined) behavior) and register that
debounced function with repository.state.onDidChange, ensuring the debounce
timer is cleared on disposal and that watchedRepositories logic remains
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/extension.ts`:
- Line 36: The EventEmitter decorationChangeEmitter created at module scope
isn't disposed; inside activate() add decorationChangeEmitter to
context.subscriptions (just like statusBarItem) so VS Code will call dispose()
on it at deactivation; locate the decorationChangeEmitter identifier and push it
into context.subscriptions within the activate() function to ensure proper
cleanup.
- Around line 209-219: The repository change handler in attachRepositoryWatcher
triggers refreshRepositoryUnmergedSnapshot on every repository.state.onDidChange
causing many git subprocesses; wrap the onDidChange callback in a short debounce
(e.g., 100-300ms) so rapid bursts collapse to one call. Update
attachRepositoryWatcher to create a debounced function (per repository) that
calls refreshRepositoryUnmergedSnapshot (and downstream
refreshUnmergedFilesSnapshot/fire(undefined) behavior) and register that
debounced function with repository.state.onDidChange, ensuring the debounce
timer is cleared on disposal and that watchedRepositories logic remains
unchanged.

@Avni2000
Avni2000 merged commit 508e2b5 into main Feb 22, 2026
This was referenced Feb 22, 2026
@Avni2000
Avni2000 deleted the git-status-run-over-and-over branch March 1, 2026 01:38
@coderabbitai coderabbitai Bot mentioned this pull request Apr 3, 2026
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.

1 participant