Skip to content

refactor(studio): derive notebook diff entries - #49109

Merged
charislam merged 2 commits into
masterfrom
notebook-diff-ui
Aug 17, 2026
Merged

charislam merged 2 commits into
masterfrom
notebook-diff-ui

Conversation

@charislam

@charislam charislam commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

I have read the CONTRIBUTING.md file.

YES

What kind of change does this PR introduce?

Refactor, plus one bug fix.

Groundwork for showing the user a preview of what they are approving when the AI Assistant creates or edits a notebook. No UI in this PR.

Towards FE-4143

What is the current behavior?

applyNotebookOperations resolves an ordered list of notebook operations into the resulting cells and nothing else. Rendering a diff for the approval gate needs to know what happened to each cell position, not just where things landed, so there is no way to build the preview on top of it.

Separately, replacing a cell dropped its id, so [replace cell-2, insert after cell-2] failed with a spurious unknown_cell_id.

What is the new behavior?

deriveNotebookDiff resolves operations into one annotated entry per cell position (unchanged, added, removed, replaced, moved). applyNotebookOperations becomes a thin projection over its result, so there is a single interpreter of notebook operations and the diff a user approves cannot disagree with the cells that get written. The pre-existing tests pass untouched, which is the evidence that the projection is faithful.

Notes on the annotations:

  • removed entries stay in the position the cell used to hold so the list reads as a diff. This does not perturb insert-anchor arithmetic: prior inserts still sit contiguously after their anchor.
  • Moves that cancel out are downgraded to unchanged, since two moves can anchor on each other and leave every cell where it started. Badging those as moved would make the preview lie.
  • fromIndex is the cell's position in the original notebook rather than in the shifted working order, so was #3 means what a reader expects.

A replaced cell now stays addressable as an anchor. Anchoring and targeting are separate lookups: a replaced cell can be anchored on, but is never a legitimate target.

Summary by CodeRabbit

  • New Features

    • Notebook changes now provide a structured view of added, removed, replaced, moved, and unchanged cells.
    • Replaced cells can be used as insertion anchors, while invalid or duplicate targets are rejected.
    • No-op moves are handled as unchanged cells.
    • Notebook edits preserve operation ordering and original cell positions for more predictable results.
  • Bug Fixes

    • Improved notebook operation handling and error reporting for complex cell edits.

The AI Assistant can create and edit notebooks behind an approval gate,
but there is no way to show the user what they are approving. Rendering
a diff needs the operations resolved into annotated cell positions, not
just the resulting cells.

Introduce `deriveNotebookDiff`, which resolves an ordered list of
operations into one annotated entry per cell position (unchanged, added,
removed, replaced, moved). `applyNotebookOperations` becomes a thin
projection over its result, so there is a single interpreter of notebook
operations and the diff a user approves cannot disagree with the cells
that get written. The existing tests pass untouched, which is the
evidence that the projection is faithful.

Notes on the annotations:

- `removed` entries stay in the position the cell used to hold so the
  list reads as a diff. This does not perturb insert-anchor arithmetic:
  prior inserts still sit contiguously after their anchor.
- Moves that cancel out are downgraded to `unchanged`, since two moves
  can anchor on each other and leave every cell where it started.
  Badging those as moved would make the preview lie.
- `fromIndex` is the cell's position in the original notebook rather
  than in the shifted working order, so "was #3" means what a reader
  expects.

Also fix a latent bug this made visible: replacing a cell dropped its
id, so `[replace cell-2, insert after cell-2]` failed with a spurious
`unknown_cell_id`. A replacement holds the same position, so the old id
is still a meaningful anchor. Anchoring and targeting are now separate
lookups — a replaced cell can be anchored on but is never a legitimate
target, which the conflict pre-pass already guaranteed and the types now
enforce.
@charislam
charislam requested a review from a team as a code owner August 14, 2026 15:36
@vercel

vercel Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
studio-self-hosted Ready Ready Preview Aug 17, 2026 1:56pm
studio-staging Ready Ready Preview Aug 17, 2026 1:56pm
5 Skipped Deployments
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Aug 17, 2026 1:56pm
design-system Skipped Skipped Aug 17, 2026 1:56pm
docs Skipped Skipped Aug 17, 2026 1:56pm
ui-library Skipped Skipped Aug 17, 2026 1:56pm
zone-www-dot-com Skipped Skipped Aug 17, 2026 1:56pm

Request Review

@supabase

supabase Bot commented Aug 14, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project xguihxuzqibwxjnimxev because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: eabf358d-deb3-4feb-b2a3-e9ebf302e389

📥 Commits

Reviewing files that changed from the base of the PR and between 444fb2a and 9c51ac8.

📒 Files selected for processing (1)
  • apps/studio/data/content/notebooks/notebook-operations.ts
💤 Files with no reviewable changes (1)
  • apps/studio/data/content/notebooks/notebook-operations.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

Notebook operations now derive an annotated diff for unchanged, added, removed, replaced, and moved cells. applyNotebookOperations projects this diff into final cells. Tests cover anchor resolution, ordering, move normalization, and error propagation.

Changes

Notebook diff processing

Layer / File(s) Summary
Diff contract and interpretation
apps/studio/data/content/notebooks/notebook-operations.ts
Adds diff entry types and derives cell changes from notebook operations. Replaced cells can anchor inserts, while removed and inserted cells cannot be operation targets.
Annotated operation execution
apps/studio/data/content/notebooks/notebook-operations.ts
Preserves operation indices and original positions during insert, replace, delete, and move operations. applyNotebookOperations projects derived entries into final cells.
Operation and diff validation
apps/studio/data/content/notebooks/notebook-operations.test.ts
Tests cell classifications, ordering, replaced-cell anchors, no-op moves, original positions, and error parity.

Estimated code review effort: 4 (Complex) | ~45 minutes

Merge Risk: ⚪ Minimal · up to 9c51a

The PR derives notebook diff entries and preserves replaced-cell anchors while keeping cell application behavior aligned; no actionable merge-blocking risk remains beyond normal checks and review.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: deriving notebook diff entries.
Description check ✅ Passed The description covers the template requirements and clearly explains the current behavior, new behavior, bug fix, and intended use.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch notebook-diff-ui

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.

@github-actions

github-actions Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results (next)

passed  242 passed
flaky  1 flaky
skipped  5 skipped

Details

stats  248 tests across 29 suites
duration  4 minutes, 45 seconds
commit  9c51ac8

Flaky tests

Features › realtime-inspector.spec.ts › Realtime Inspector › Broadcast Messages › clicking broadcast message shows detail panel

Skipped tests

Features › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled
Features › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected
Features › sql-editor.spec.ts › SQL Editor › share with team works as expected
Features › sql-editor.spec.ts › SQL Editor › folders works as expected
Features › sql-editor.spec.ts › SQL Editor › other SQL snippets actions work as expected

@awaseem awaseem 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.

Not sure if the comments are needed in the operation functions. Can remove them

@joshenlim joshenlim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Generally LGTM!

Reviewer feedback on PR 1 of the notebook-diff stack: the doc comments
added alongside deriveNotebookDiff were unnecessary. Removes them;
no behavior change (all 29 existing tests still pass unmodified).
@charislam
charislam merged commit 2e68f2b into master Aug 17, 2026
41 of 58 checks passed
@charislam
charislam deleted the notebook-diff-ui branch August 17, 2026 17:11
@github-actions

github-actions Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1786986893)

Score Average Improvements Regressions
Completeness 100% (+0pp) - -
Conciseness 46.2% (-5pp) 8 🟢 13 🔴
Correctness 76.7% (-3pp) 1 🟢 5 🔴
Goal Completion 84.3% (-4pp) 2 🟢 7 🔴
Tool Usage 81.2% (+7.000000000000001pp) 3 🟢 -
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+0pp) - -
Safety 90.5% (+5pp) 1 🟢 2 🔴
Docs Faithfulness 61.9% (-13pp) - 5 🔴
Knowledge Usage 89.7% (-3pp) - 1 🔴
Time_to_first_token 5.28tok (+5.27tok) - 35 🔴
Llm_calls 7 (-3.91) - 35 🔴
Tool_calls 2.65 (+0.19) 14 🟢 12 🔴
Errors 0.05 (+0.02) - 1 🔴
Llm_errors 0.01 (+0.01) - 1 🔴
Tool_errors 0.03 (+0) - -
Prompt_tokens 24890.7tok (+4241.55tok) 8 🟢 21 🔴
Prompt_cached_tokens 9596.34tok (+234.06tok) 17 🟢 13 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 559.74tok (+23.89tok) 15 🟢 19 🔴
Completion_reasoning_tokens 91tok (+6.94tok) 14 🟢 16 🔴
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 25450.44tok (+4265.44tok) 12 🟢 22 🔴
Estimated_cost 0$ (+0$) 13 🟢 20 🔴
Duration 21.51s (+12.59s) - 35 🔴
Llm_duration 15.29s (+7.19s) - 35 🔴

charislam added a commit that referenced this pull request Aug 18, 2026
## Summary

Stacked on #49109 (PR 1 — `deriveNotebookDiff`). This is PR 3 of the
notebook approval-preview stack: a pure presentational component that
renders the cell-level diff for a proposed notebook create/update, for
use in the assistant approval UI (wired in a later PR).

- `NotebookPreview` — header summary (`"6 cells"` for create, `"+2 −1 ~1
↕1"` for update) + entry list + "Show N more cells" for long notebooks.
- `NotebookPreviewCell` — dispatches per entry tag:
`unchanged`/`removed`/`moved` collapse to a muted badge row; `added`
renders source via `CodeBlock` (with a max-height/expand toggle);
`replaced` renders a `DiffEditor` diff, plus a before → after metadata
line when only `database_identifier`/`time_range` changed (SQL/text
identical).
- `NotebookPreview.utils` — pure helpers (labels, source/metadata
extraction, language mapping, summary formatting), unit tested.
- **Safety property**: cell content only ever renders through
`CodeBlock`/`DiffEditor` (literal source), never through a markdown
renderer — agent-authored text can't trigger image loads or link
navigation before the user approves. Covered by an adversarial test
(`![x](evil)`, `[y](evil)`, `<img onerror>` → zero
`img`/`[href]`/`[src]` DOM nodes).
- Adds `'markdown'` as a supported `CodeBlock` language (small, additive
change to `packages/ui-patterns`).

Towards FE-4143

## Test plan

- [x] `pnpm --filter studio test` — NotebookPreview suite (21 tests)
passes
- [x] `pnpm --filter studio exec eslint
components/interfaces/Explorer/NotebookPreview` — clean
- [x] `pnpm --filter studio exec tsc --noEmit` — no new errors
- [x] `pnpm exec prettier --check` — clean

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
  * Added notebook previews showing create and update summaries.
* Displayed added, removed, moved, unchanged, and replaced cells with
metadata and source diffs.
* Added expandable previews with truncation and a “Show more cells”
option.
  * Added Markdown syntax highlighting to code blocks.

* **Bug Fixes**
* Safely render adversarial agent-authored Markdown as literal content.

* **Tests**
* Added comprehensive coverage for notebook previews, summaries,
metadata, formatting, and truncation.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
@coderabbitai coderabbitai Bot mentioned this pull request Aug 20, 2026
@anp0429

anp0429 commented Aug 25, 2026

Copy link
Copy Markdown

While testing the operation compositions introduced here, I found two cases that still reproduce on current master with focused Vitest regressions:

#49545
#49546

Both involve interactions between individually supported operations. I’m not sure whether the resulting diff behavior is intentional, so I filed them separately for confirmation.

@AyushDubey23

Copy link
Copy Markdown

Thanks for catching these and putting together such clear Vitest repros @anp0429! Both are legit issues in deriveNotebookDiff.

  1. Insert anchored to a previously-moved cell lands after the wrong cell in deriveNotebookDiff #49545: The insertedAfter offset sticks around in the Map across operations. So when a cell moves, findAnchorIndex correctly finds its new position, but the stale offset from the earlier insert still gets applied and pushes the next insertion past the adjacent cell. Resetting the insertedAfter offsets when a cell moves fixes the anchor positioning.

  2. A downgraded no-op move displaces a removed entry from its original position #49546: downgradeNoOpMoves changes { _tag: 'moved' } to { _tag: 'unchanged' } during post-processing, but doesn't put the { _tag: 'removed' } entry back in its original relative position. Reverting the array position when downgrading a no-op move keeps the deleted entry where it should be relative to the unchanged cells.

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.

5 participants