Skip to content

[FIX] Rebuild notebook from unified rows + resolved text areas - #30

Merged
Avni2000 merged 4 commits into
mainfrom
27-fix-duplicate-cells-after-matching
Feb 4, 2026
Merged

Avni2000 merged 4 commits into
mainfrom
27-fix-duplicate-cells-after-matching

Conversation

@Avni2000

@Avni2000 Avni2000 commented Feb 4, 2026 •

Copy link
Copy Markdown
Owner

Closes #27

Rebuilds notebook as {Unified Rows} U {Resolved Text Areas}

Summary by CodeRabbit

  • New Features

    • UI can submit full per-row resolutions (including choose/base/current/both/delete and edited content) as the source of truth for merges.
  • Refactor

    • Conflict resolution rebuilt to consume row-based resolutions, merge content/metadata, handle deletions, and preserve legacy auto-resolve flows.
    • Prompts user to renumber execution counts after resolving.
  • Chores

    • Minor test script path fix.

@coderabbitai

coderabbitai Bot commented Feb 4, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

This change introduces a UI-provided resolvedRows source of truth that is carried from the Web UI through message handling into the backend resolver; resolver.ts gains applySemanticResolutionsFromRows to build the final notebook from per-row resolutions while preserving the legacy path when resolvedRows is absent.

Changes

Cohort / File(s) Summary
Backend Resolution Logic
src/resolver.ts
Added applySemanticResolutionsFromRows to construct the resolved notebook from UI-provided resolvedRows. applySemanticResolutions now delegates to the rows-based path when present; per-row choices (base/current/incoming/both/delete), resolved content handling, metadata selection, and execution-count renumber prompt are implemented. Legacy flow remains for absence of resolvedRows.
Web UI Types & Messages
src/web/webTypes.ts, src/web/client/types.ts
Added exported ResolvedRow interface and extended resolution message types (UnifiedResolution / ResolutionMessage) to include resolvedRows?: ResolvedRow[] as part of the resolve payload.
Web UI Message Flow
src/web/WebConflictPanel.ts, src/web/client/App.tsx, src/web/client/ConflictResolver.tsx
Propagates resolvedRows through the message pipeline: imports/uses ResolvedRow types, extends _handleMessage shapes, passes resolvedRows into semantic-resolution payloads, and changes ConflictResolver.onResolve signature to accept resolvedRows. ConflictResolver builds resolvedRows from UI rows and choices.
Test Utilities
test/simulate_merge_uu.sh
Fixed project root resolution path used in the test script (one-level correction).

Sequence Diagram

sequenceDiagram
    participant User as User
    participant UI as ConflictResolver (Web UI)
    participant App as App.tsx
    participant Panel as WebConflictPanel
    participant Resolver as resolver.ts

    User->>UI: Drag/drop and edit rows (choose resolutions)
    UI->>UI: Build `resolvedRows` array (per-row choice + resolvedContent)
    UI->>App: onResolve(resolutions, markAsResolved, resolvedRows)
    App->>Panel: sendMessage({ kind: 'resolve', resolvedRows, ... })
    Panel->>Resolver: applySemanticResolutions(unifiedResolution with resolvedRows)
    Resolver->>Resolver: if resolvedRows present?
    alt rows-based path
        Resolver->>Resolver: applySemanticResolutionsFromRows(resolvedRows) -> build NotebookCells, handle deletes, metadata, merging
    else legacy path
        Resolver->>Resolver: applySemanticResolutionsLegacy(cellMappings...)
    end
    Resolver->>Resolver: prompt for execution-count renumbering
    Resolver->>Resolver: saveResolvedNotebook
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~28 minutes

Possibly related PRs

Poem

🐰
Hopping through rows, I patch each line,
UI whispers truth, then the resolver aligns.
Cells stitched together, conflicts undone,
Legacy paths sleep while the new one runs.
A little hop — resolved, and fun!

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: rebuilding the notebook from unified rows and resolved text areas to fix the duplicate cells issue.
Linked Issues check ✅ Passed The PR implements notebook reconstruction from unified rows and resolved text area data to address duplicate cells after matching, directly fulfilling issue #27's core requirement.
Out of Scope Changes check ✅ Passed All changes are directly scoped to supporting the new resolvedRows-based notebook reconstruction flow and maintaining backward compatibility; the test path fix is a minor supporting change.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 27-fix-duplicate-cells-after-matching

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

🤖 Fix all issues with AI agents
In `@src/resolver.ts`:
- Around line 320-326: The current matching in applySemanticResolutionsFromRows
uses object reference and source string equality to find autoResolvedNotebook
cells, which is fragile; instead extend the ResolvedRow to carry the original
cell index (e.g., add a property like cellIndex or mapping.currentIndex
preserved through serialization) and change applySemanticResolutionsFromRows to
use that index to pick the corresponding cell from autoResolvedNotebook.cells
(fallback to current heuristics only if index is missing); update any code that
constructs ResolvedRow to populate the index so index-based lookup is reliable
across WebSocket/serialization boundaries.
- Around line 302-305: The code currently treats resolvedContent === '' as an
implicit deletion which conflicts with explicit choice === 'delete'; update the
logic in the resolver where resolvedContent and choice are handled so deletion
only occurs when choice === 'delete' (remove the implicit empty-content
continue), and add validation that if choice !== 'delete' and resolvedContent
=== '' the resolver raises/returns a validation error (or marks the cell
invalid) so empty content isn’t silently dropped; reference the resolvedContent
variable and the choice branch in the function handling cell resolution to
locate and modify the behavior.
🧹 Nitpick comments (4)
test/simulate_merge_uu.sh (1)

35-39: Use ROOT to avoid hardcoded repo paths.

You already compute ROOT from the script’s location; consider using it for the initial cd to make the script portable across different checkout locations.

♻️ Suggested update
-cd ~/source/repos/MergeNB
-
-npm run compile
-
-ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+cd "$ROOT"
+npm run compile
src/web/webTypes.ts (1)

35-53: Consider consolidating the duplicated ResolvedRow type definition.

The ResolvedRow interface is defined identically in both src/web/webTypes.ts (lines 39-53) and src/web/client/types.ts (lines 77-91). This duplication creates a maintenance risk where changes to one definition might not be reflected in the other.

Consider one of these approaches:

  1. Define ResolvedRow only in webTypes.ts and re-export it from client/types.ts
  2. Define it in a shared location and import from both files
♻️ Proposed fix: Re-export from client/types.ts

In src/web/client/types.ts, replace the duplicate definition with:

+// Re-export ResolvedRow from webTypes to avoid duplication
+export type { ResolvedRow } from '../webTypes';
-/**
- * Resolved row from the UI - represents the final state after drag/drop and user edits.
- * This is the source of truth for reconstructing the notebook.
- */
-export interface ResolvedRow {
-    /** Base cell (may be undefined if cell not present in base) */
-    baseCell?: import('../../types').NotebookCell;
-    // ... rest of the interface
-}
src/web/WebConflictPanel.ts (1)

127-134: Consider using the BrowserToExtensionMessage type instead of inline type assertion.

The manual type shape duplicates what's already defined in BrowserToExtensionMessage. Using the imported type would ensure consistency and catch future mismatches.

♻️ Suggested improvement
+import type { UnifiedConflict, UnifiedResolution, ResolvedRow, BrowserToExtensionMessage } from './webTypes';

 private _handleMessage(message: unknown): void {
     if (this._isDisposed) return;
     
-    const msg = message as { 
-        command?: string; 
-        type?: string; 
-        resolutions?: Array<{ index: number; choice: string; resolvedContent: string }>; 
-        resolvedRows?: ResolvedRow[];
-        semanticChoice?: string; 
-        markAsResolved?: boolean 
-    };
+    const msg = message as BrowserToExtensionMessage & { command?: string };
src/resolver.ts (1)

309-319: Casting to any bypasses type safety.

Lines 317-318 use (cellToUse as any) to set execution_count and outputs. Since NotebookCell already defines these as optional properties for code cells, you can construct the full object conditionally instead.

♻️ Proposed improvement
-                cellToUse = {
-                    cell_type: cellType,
-                    metadata: referenceCell?.metadata ? JSON.parse(JSON.stringify(referenceCell.metadata)) : {},
-                    source: resolvedContent.split(/(?<=\n)/)
-                } as NotebookCell;
-                
-                // Add execution_count and outputs for code cells
-                if (cellType === 'code') {
-                    (cellToUse as any).execution_count = null;
-                    (cellToUse as any).outputs = [];
-                }
+                cellToUse = {
+                    cell_type: cellType,
+                    metadata: referenceCell?.metadata ? JSON.parse(JSON.stringify(referenceCell.metadata)) : {},
+                    source: resolvedContent.split(/(?<=\n)/),
+                    ...(cellType === 'code' ? { execution_count: null, outputs: [] } : {})
+                };

Comment thread src/resolver.ts Outdated
Comment on lines +302 to +305
// Check if deletion (empty content)
if (resolvedContent === '') {
continue; // Skip this cell
}

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

🧩 Analysis chain

🌐 Web query:

Is it valid for a Jupyter notebook cell to have empty source content

💡 Result:

Yes—a cell’s source may be empty, e.g. "" (or [] on disk, since multiline strings may be stored as a list of strings). The notebook format treats source as a “multiline string” (a string or string[]), and an empty string/list is still a valid value. [1] [2]

What’s not valid (per the spec/schema) is omitting the source field entirely—cells are defined to include a source property. [1]

Sources:
[1] Jupyter nbformat “The Notebook file format” (cell structure + multiline string rules) (nbformat.readthedocs.io)
[2] JupyterLab nbformat type MultilineString = string | string[] (jupyterlab.readthedocs.io)

Citations:


🏁 Script executed:

# Find and examine the resolver.ts file around lines 298-310
fd -t f "resolver.ts" | head -5

Repository: Avni2000/MergeNB

Length of output: 111


🏁 Script executed:

# Read the resolver.ts file around lines 298-310 to understand the deletion logic
wc -l src/resolver.ts

Repository: Avni2000/MergeNB

Length of output: 79


🏁 Script executed:

# Read lines 290-315 to get full context of the deletion logic
sed -n '290,315p' src/resolver.ts

Repository: Avni2000/MergeNB

Length of output: 1265


🏁 Script executed:

# Let me look at more context to understand the user interaction flow
# Check lines 270-305 to see the broader context
sed -n '270,310p' src/resolver.ts

Repository: Avni2000/MergeNB

Length of output: 1819


🏁 Script executed:

# Also check if there's a UI component that handles deletion separately
grep -n "delete" src/resolver.ts | head -20

Repository: Avni2000/MergeNB

Length of output: 244


🏁 Script executed:

# Check the UI component to understand how resolvedContent is set and if users can clear it
fd -t f "ConflictResolver.tsx" -o "conflict" | head -5

Repository: Avni2000/MergeNB

Length of output: 195


🏁 Script executed:

# Look for how resolvedContent is managed in the UI
rg -n "resolvedContent" src/ -B 2 -A 2 | head -40

Repository: Avni2000/MergeNB

Length of output: 2559


🏁 Script executed:

# Find the UI component that handles the text area and see if users can clear content
fd -t f "ConflictResolver.tsx"

Repository: Avni2000/MergeNB

Length of output: 95


🏁 Script executed:

# Search for text area handling in the UI
rg -n "textarea\|text area\|resolvedContent" src/web/ -l

Repository: Avni2000/MergeNB

Length of output: 42


🏁 Script executed:

# Examine the ConflictResolver.tsx to understand user interaction
wc -l src/web/client/ConflictResolver.tsx

Repository: Avni2000/MergeNB

Length of output: 99


🏁 Script executed:

# Search for textarea or text input handling in the resolver UI
rg -n "textarea|input|onChange|resolvedContent" src/web/client/ConflictResolver.tsx -A 2 -B 2 | head -60

Repository: Avni2000/MergeNB

Length of output: 2018


🏁 Script executed:

# Find the textarea element in ConflictResolver.tsx
rg -n "textarea|<textarea" src/web/client/ConflictResolver.tsx -B 3 -A 3

Repository: Avni2000/MergeNB

Length of output: 42


🏁 Script executed:

# Look at how the resolved content text editor is rendered
sed -n '200,300p' src/web/client/ConflictResolver.tsx

Repository: Avni2000/MergeNB

Length of output: 4118


🏁 Script executed:

# Look for more context around how the text editor is rendered and if there are any warnings/validations
sed -n '300,400p' src/web/client/ConflictResolver.tsx | head -80

Repository: Avni2000/MergeNB

Length of output: 4435


🏁 Script executed:

# Also check if there's any documentation or comments about the intended behavior
rg -n "empty|clear|delete" src/resolver.ts -B 2 -A 2 | head -40

Repository: Avni2000/MergeNB

Length of output: 2090


Clarify whether empty resolvedContent should trigger cell deletion or if it should be explicitly prevented.

The current logic treats empty resolvedContent as implicit cell deletion (line 302–304), which coexists with the explicit choice: 'delete' path (line 297–299). While Jupyter notebook cells can validly have empty source content per the nbformat specification, the implicit deletion here creates a potential issue: if a user selects "current" and then accidentally clears the text area, the cell will be silently deleted rather than resulting in a validation error.

Consider either:

  1. Removing the empty content check and allowing empty cells to be preserved (valid per Jupyter spec)
  2. Adding validation to prevent empty content for non-delete choices (flag as error)
  3. Making deletion explicit in the UI (dedicated delete button/choice) rather than relying on clearing the text
🤖 Prompt for AI Agents
In `@src/resolver.ts` around lines 302 - 305, The code currently treats
resolvedContent === '' as an implicit deletion which conflicts with explicit
choice === 'delete'; update the logic in the resolver where resolvedContent and
choice are handled so deletion only occurs when choice === 'delete' (remove the
implicit empty-content continue), and add validation that if choice !== 'delete'
and resolvedContent === '' the resolver raises/returns a validation error (or
marks the cell invalid) so empty content isn’t silently dropped; reference the
resolvedContent variable and the choice branch in the function handling cell
resolution to locate and modify the behavior.

Comment thread src/resolver.ts Resolved
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.

[FIX] Duplicate Cells after matching

1 participant