Skip to content

feat: persist CodeEditor's json state across tab switching - #7797

Merged
sid-bruno merged 7 commits into
usebruno:mainfrom
shubh-bruno:poc/codeeditor-state
May 4, 2026
Merged

sid-bruno merged 7 commits into
usebruno:mainfrom
shubh-bruno:poc/codeeditor-state

Conversation

@shubh-bruno

@shubh-bruno shubh-bruno commented Apr 19, 2026 •

Copy link
Copy Markdown
Collaborator

Description

JIRA

Problem

Every tab switch called editor.setValue(newContent), which mutates the
underlying CodeMirror Doc and wipes its attached state — folds expand
back, cursor resets, selection clears, undo history is gone, scroll jumps
to the top.

Solution

Snapshot the editor's view state to localStorage on tab switch / unmount
and re-apply it on the next mount. CodeMirror's getHistory() /
setHistory() are JSON-serializable, which is what makes Cmd-Z survive.

  • Tab switch → snapshot { history, cursor, selection, folds, scrollY }
    under persisted::codeeditor::<tabUid>:<...> → setValue loads the new
    content → re-apply the incoming tab's snapshot via setHistory /
    setCursor / foldCode.
  • Same tab, new content → setValue and invalidate the snapshot.
  • Tab close → closeTabs thunk calls clearCodeEditorPersistedState
    and an unmount-guard prevents the re-write race.

Content lives in Redux; only view state is persisted. Keyed per editor
(item/collection uid + mode + readOnly), with an optional docKey prop
for editors that would otherwise collide (e.g. Pre-Request vs
Post-Response scripts).


Contribution Checklist:

  • I've used AI significantly to create this pull request
  • The pull request only addresses one issue or adds one feature.
  • The pull request does not introduce any breaking changes
  • I have added screenshots or gifs to help explain the change if applicable.
  • I have read the contribution guidelines.
  • Create an issue and link to the pull request.

Note: Keeping the PR small and focused helps make it easier to review and merge. If you have multiple changes you want to make, please consider submitting them as separate pull requests.

Publishing to New Package Managers

Please see here for more information.

Summary by CodeRabbit

  • New Features

    • Editor now persists and restores view state per document/tab, preserving cursor, folds and undo when content matches.
  • Bug Fixes

    • Different editor panes (scripts, tests, response editor) use distinct persistence keys so switching restores the correct view.
    • Same-tab external updates preserve cursor/selection and avoid applying stale snapshots.
  • Stability

    • State is snapshotted on unmount and persistence failures are handled gracefully.

@coderabbitai

coderabbitai Bot commented Apr 19, 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

Persist and restore CodeMirror view state per-document using a computed docKey. CodeEditor snapshots/restores folds, selections, history, cursor, and vertical scroll across mount, update (including tab/document switches), and unmount flows; multiple editor consumers now pass explicit docKeys.

Changes

Cohort / File(s) Summary
CodeEditor core & persistence
packages/bruno-app/src/components/CodeEditor/index.js, packages/bruno-app/src/components/CodeEditor/state-persistence.js
Add state-persistence module with scoped storage keys and safe read/write. CodeEditor now computes docKey, restores persisted state on mount/when switching documents, snapshots outgoing state on doc switch, distinguishes same-doc external props.value updates (preserve cursor, invalidate persisted snapshot), and persists state on unmount. Default export changed to a forwardRef wrapper injecting persistenceScope; removed unused import.
Script editors — docKey propagation
packages/bruno-app/src/components/CollectionSettings/Script/index.js, packages/bruno-app/src/components/FolderSettings/Script/index.js, packages/bruno-app/src/components/RequestPane/Script/index.js
Pre-request and post-response CodeEditor instances now receive distinct, stable docKey values (e.g., ...:pre-request, ...:post-response) to separate view-state. Minor import cleanup in RequestPane.
Tests / Response / Request editors — docKey propagation
packages/bruno-app/src/components/CollectionSettings/Tests/index.js, packages/bruno-app/src/components/FolderSettings/Tests/index.js, packages/bruno-app/src/components/RequestPane/Tests/index.js, packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.js
Provide deterministic docKey props (e.g., "collection-tests", "folder-tests", "tests", "response:editor") so persisted view-state is scoped per item/folder/response. No other behavior changed.
Minor import style
packages/bruno-app/src/hooks/usePersistedState/PersistedScopeProvider.tsx
Non-functional style change to import quoting/semicolon.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant React as "React Component"
    participant CE as "CodeEditor (wrapper)"
    participant SP as "state-persistence"
    participant CM as "CodeMirror"
    participant LS as "localStorage"

    rect rgba(0,150,255,0.5)
    Note over User,CM: Mount or Tab Switch
    User->>React: mount / switch tab
    React->>CE: mount/update (with docKey)
    CE->>SP: readPersistedEditorState(scope, docKey)
    alt persisted state found
        SP-->>CE: state
        CE->>CM: applyEditorState(state, currentContent)
    else no persisted state
        CE->>CM: set initial value
    end
    CE->>CM: refresh overlays / lint
    end

    rect rgba(0,200,100,0.5)
    Note over User,CM: Same-doc external value update
    User->>React: props.value changes (same docKey)
    React->>CE: componentDidUpdate
    CE->>CM: setValue(newValue) (preserve cursor where possible)
    CE->>SP: writePersistedEditorState(scope, docKey, captureEditorState(CM))
    end

    rect rgba(200,100,0,0.5)
    Note over User,LS: Unmount / Tab close
    User->>React: unmount / close tab
    React->>CE: componentWillUnmount
    CE->>SP: captureEditorState(CM) and writePersistedEditorState(scope, docKey, state)
    CE->>CM: detach or swap document
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • helloanoop
  • sid-bruno
  • lohit-bruno
  • bijin-bruno

Poem

✨ A key for every pane, a tiny saving grace,
Folds and cursors find again their place.
Switch and return, the view resumes true—
No lost scroll, no lost line, just pick up where you knew.
🎉

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: implementing state persistence for the CodeEditor across tab switches, which is the primary objective of this PR.
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.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/bruno-app/src/components/CodeEditor/index.js`:
- Line 44: docCache currently holds CodeMirror.Doc objects forever (const
docCache = new Map()), leaking content, markers, and undo history; add an
explicit eviction/invalidation strategy: either implement a bounded LRU or TTL
for entries in docCache, and expose a removal call that your tab/collection
lifecycle can call when a tab is closed (e.g., add a removeDoc(key) or
clearDocsForCollection(collectionId) function and call it from the
tab-close/unmount handler). Ensure eviction cleans up the underlying
CodeMirror.Doc (call its .toTextArea() / .clearHistory() or appropriate dispose
API) before deleting the Map entry so markers/undo stacks are released.
Reference docCache and the tab/collection unmount/close handlers when wiring
this up.
- Around line 337-338: The code is converting null/undefined into the literal
strings "null"/"undefined" when setting this.cachedValue and calling
this.editor.setValue; change both uses to coalesce this.props.value to an empty
string before stringifying (i.e., use this.props.value ?? '' or
this?.props?.value ?? '' as the input to String) so cachedValue and
editor.setValue never receive the text "null" or "undefined" — update the
references to cachedValue and the call to this.editor.setValue accordingly.
- Around line 46-55: getOrCreateDoc mutates a cached Doc (doc.setValue(content))
before checking whether that Doc is attached to another editor, which can
trigger change handlers on the wrong editor; change getOrCreateDoc signature to
accept the current editor instance, and inside getOrCreateDoc check doc.cm (or
doc.cm !== undefined) before calling doc.setValue — if doc.cm is set (attached
elsewhere) create a fresh Doc instead of mutating the cached one and update
docCache accordingly; update all call sites (including the other occurrences
mentioned) to pass the current editor so the defensive attachment check happens
before any mutation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7aa22db5-759e-45e2-b071-1779a4040c92

📥 Commits

Reviewing files that changed from the base of the PR and between c6281d3 and fa3515a.

📒 Files selected for processing (4)
  • packages/bruno-app/src/components/CodeEditor/index.js
  • packages/bruno-app/src/components/CollectionSettings/Script/index.js
  • packages/bruno-app/src/components/FolderSettings/Script/index.js
  • packages/bruno-app/src/components/RequestPane/Script/index.js

@shubh-bruno shubh-bruno changed the title poc: codeeditor shrink state persist poc: persist CodeEditor state across tab switching Apr 28, 2026

@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

♻️ Duplicate comments (1)
packages/bruno-app/src/components/CodeEditor/index.js (1)

261-263: ⚠️ Potential issue | 🟡 Minor

Coalesce before stringifying when calling setValue.

String(this.props.value) || '' at Line 262 and Line 280 can write 'undefined' / 'null' into the editor.

Proposed fix
-        this.cachedValue = String(this?.props?.value ?? '');
-        this.editor.setValue(String(this.props.value) || '');
+        const nextValue = String(this.props.value ?? '');
+        this.cachedValue = nextValue;
+        this.editor.setValue(nextValue);
@@
-        this.cachedValue = String(this?.props?.value ?? '');
-        this.editor.setValue(String(this.props.value) || '');
+        const nextValue = String(this.props.value ?? '');
+        this.cachedValue = nextValue;
+        this.editor.setValue(nextValue);

Also applies to: 279-280

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

In `@packages/bruno-app/src/components/CodeEditor/index.js` around lines 261 -
263, The editor is currently calling String(this.props.value) || '' which can
produce the literal "undefined"/"null" in the editor; change the setValue and
cachedValue assignments to coalesce before stringifying (e.g., use
this.props.value ?? '' or this?.props?.value ?? ''), so update the occurrences
that set this.cachedValue and call this.editor.setValue (both the lines that set
cachedValue and the calls to setValue around the constructor/initialization and
the later update at lines ~279-280) to coalesce first and then convert to
string.
🧹 Nitpick comments (1)
packages/bruno-app/src/components/CodeEditor/state-persistence.js (1)

31-37: Explicit docKey should be normalized to preserve close-tab cleanup.

Line 32 bypasses key normalization, but cleanup at Line 78 assumes ${tabUid}: prefix. This can leave stale persisted entries after tab close when custom keys are used.

Proposed fix
 export const getDocKey = (props) => {
-  if (props.docKey) return props.docKey;
   const id = props.item?.uid || props.collection?.uid || 'default';
+  if (props.docKey) {
+    return props.docKey.startsWith(`${id}:`) ? props.docKey : `${id}:${props.docKey}`;
+  }
   const mode = props.mode || 'default';
   const readOnly = props.readOnly ? 'ro' : 'rw';
   return `${id}:${mode}:${readOnly}`;
 };

Also applies to: 74-82

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

In `@packages/bruno-app/src/components/CodeEditor/state-persistence.js` around
lines 31 - 37, The explicit docKey bypasses the project's tab-scoped
normalization so cleanup (which expects keys prefixed with `${tabUid}:`) can
miss entries; update getDocKey to always normalize the key by prefixing with the
resolved tab id (use the same id calculation as in getDocKey: props.item?.uid ||
props.collection?.uid || 'default') and the same mode/readOnly suffix so that
when props.docKey is provided it is transformed into the canonical
`${id}:${mode}:${readOnly}` form; also apply the same normalization wherever
explicit keys are accepted/returned (the related logic around
set/persist/cleanup mentioned in the block covering lines ~74-82) so creation
and cleanup use the identical canonical key format.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/bruno-app/src/components/CodeEditor/state-persistence.js`:
- Around line 99-106: The current restore logic only checks contentLength before
reapplying saved history/cursor/ selections, which can reuse state when
different text shares the same length; change the persistence format and restore
guard to validate the actual content (or a strong hash) matches before restoring
history, cursor, selections, and folds: include the full content (or a
deterministic hash of doc.getValue()) alongside contentLength in the object
returned by the saver (symbols: contentLength, cursor, selections, history,
folds, scrollY) and in the loader (the restore branch around the code that
currently gates on contentLength in the restore function between lines
~112-127), and only reapply saved history/selections/cursor when the saved
content/hash exactly equals the current doc.getValue()/hash. Ensure backwards
compatibility by falling back to the strict equality check if only contentLength
exists.

---

Duplicate comments:
In `@packages/bruno-app/src/components/CodeEditor/index.js`:
- Around line 261-263: The editor is currently calling String(this.props.value)
|| '' which can produce the literal "undefined"/"null" in the editor; change the
setValue and cachedValue assignments to coalesce before stringifying (e.g., use
this.props.value ?? '' or this?.props?.value ?? ''), so update the occurrences
that set this.cachedValue and call this.editor.setValue (both the lines that set
cachedValue and the calls to setValue around the constructor/initialization and
the later update at lines ~279-280) to coalesce first and then convert to
string.

---

Nitpick comments:
In `@packages/bruno-app/src/components/CodeEditor/state-persistence.js`:
- Around line 31-37: The explicit docKey bypasses the project's tab-scoped
normalization so cleanup (which expects keys prefixed with `${tabUid}:`) can
miss entries; update getDocKey to always normalize the key by prefixing with the
resolved tab id (use the same id calculation as in getDocKey: props.item?.uid ||
props.collection?.uid || 'default') and the same mode/readOnly suffix so that
when props.docKey is provided it is transformed into the canonical
`${id}:${mode}:${readOnly}` form; also apply the same normalization wherever
explicit keys are accepted/returned (the related logic around
set/persist/cleanup mentioned in the block covering lines ~74-82) so creation
and cleanup use the identical canonical key format.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ff99a33d-6266-487d-97ca-6adf3868a6ca

📥 Commits

Reviewing files that changed from the base of the PR and between fa3515a and 91c8c70.

📒 Files selected for processing (2)
  • packages/bruno-app/src/components/CodeEditor/index.js
  • packages/bruno-app/src/components/CodeEditor/state-persistence.js

@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 (3)
packages/bruno-app/src/components/FolderSettings/Tests/index.js (1)

35-35: Scope the tests editor key to the collection too.

folder.uid alone may collide if folders are duplicated or reused across collections. Since the save/update path is already collection-scoped, including collection.uid in the docKey would make the persisted editor state match the data identity more closely.

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

In `@packages/bruno-app/src/components/FolderSettings/Tests/index.js` at line 35,
The docKey used for the Tests editor is currently scoped only to folder.uid
(docKey={`${folder.uid}:folder-tests`}) which can collide across collections;
change the docKey to include collection.uid as well (for example
`${collection.uid}:${folder.uid}:folder-tests`) where the Tests component sets
the docKey prop so the editor state is uniquely keyed by collection and folder.
packages/bruno-app/src/components/RequestPane/Tests/index.js (1)

33-33: Make the persisted editor key collection-scoped as well.

This docKey currently keys off item.uid only, but the request tests flow already depends on collection.uid too. Adding the collection to the key would avoid any chance of view-state leakage between identically keyed requests in different collections.

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

In `@packages/bruno-app/src/components/RequestPane/Tests/index.js` at line 33, The
persisted editor key currently uses docKey={`${item.uid}:tests`} which can
collide across collections; change the key to include the collection identifier
(e.g., use collection.uid along with item.uid) so the key becomes
collection-scoped (for example build docKey from collection.uid and item.uid
inside the RequestPane Tests component where docKey is set) to prevent
view-state leakage between identically keyed requests in different collections.
packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.js (1)

68-68: Scope the persistence key a bit wider.

item.uid alone may be too coarse if request IDs can repeat across collections or cloned imports. Including collection.uid here would keep the response editor state isolated to the actual request context.

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

In
`@packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.js`
at line 68, The persistence key for the response editor currently uses
docKey={`${item.uid}:response:editor`} which is too coarse; update the key
construction in QueryResultPreview to include the request's collection context
by incorporating collection.uid (e.g., use both item.uid and collection.uid in
the docKey) so the editor state is isolated per-request-per-collection; locate
the docKey usage in QueryResultPreview (where docKey is set) and change it to
include collection.uid alongside item.uid.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/bruno-app/src/components/FolderSettings/Tests/index.js`:
- Line 35: The docKey used for the Tests editor is currently scoped only to
folder.uid (docKey={`${folder.uid}:folder-tests`}) which can collide across
collections; change the docKey to include collection.uid as well (for example
`${collection.uid}:${folder.uid}:folder-tests`) where the Tests component sets
the docKey prop so the editor state is uniquely keyed by collection and folder.

In `@packages/bruno-app/src/components/RequestPane/Tests/index.js`:
- Line 33: The persisted editor key currently uses docKey={`${item.uid}:tests`}
which can collide across collections; change the key to include the collection
identifier (e.g., use collection.uid along with item.uid) so the key becomes
collection-scoped (for example build docKey from collection.uid and item.uid
inside the RequestPane Tests component where docKey is set) to prevent
view-state leakage between identically keyed requests in different collections.

In
`@packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.js`:
- Line 68: The persistence key for the response editor currently uses
docKey={`${item.uid}:response:editor`} which is too coarse; update the key
construction in QueryResultPreview to include the request's collection context
by incorporating collection.uid (e.g., use both item.uid and collection.uid in
the docKey) so the editor state is isolated per-request-per-collection; locate
the docKey usage in QueryResultPreview (where docKey is set) and change it to
include collection.uid alongside item.uid.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: fafaf55f-2e7e-4489-97a9-c1f2c05562d3

📥 Commits

Reviewing files that changed from the base of the PR and between 91c8c70 and b2b452d.

📒 Files selected for processing (4)
  • packages/bruno-app/src/components/CollectionSettings/Tests/index.js
  • packages/bruno-app/src/components/FolderSettings/Tests/index.js
  • packages/bruno-app/src/components/RequestPane/Tests/index.js
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.js

@sid-bruno

Copy link
Copy Markdown
Collaborator

LGTM, tested and state is cleared as tabs are closed, cleaned up some redundant logic

Screen.Recording.2026-04-30.at.8.50.24.PM.mov

sid-bruno
sid-bruno previously approved these changes Apr 30, 2026
@sid-bruno sid-bruno changed the title poc: persist CodeEditor state across tab switching feat: persist CodeEditor's json state across tab switching Apr 30, 2026

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/bruno-app/src/components/CodeEditor/index.js (1)

200-217: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't overwrite the restored scroll position on mount.

applyEditorState() can already restore scrollY, but Line 216 unconditionally scrolls again from initialScroll. Any mount with a defined initialScroll will discard the persisted position, and _lastScrollTop is then seeded with the wrong value too.

Suggested fix
-      applyEditorState(
-        editor,
-        readPersistedEditorState({ scope: this.props.persistenceScope, key: docKey }),
-        this.cachedValue
-      );
+      const persistedState = readPersistedEditorState({
+        scope: this.props.persistenceScope,
+        key: docKey
+      });
+      applyEditorState(editor, persistedState, this.cachedValue);
@@
-      editor.scrollTo(null, this.props.initialScroll);
-      this._lastScrollTop = this.props.initialScroll || 0;
+      const scrollTop = persistedState?.scrollY ?? this.props.initialScroll ?? 0;
+      editor.scrollTo(null, scrollTop);
+      this._lastScrollTop = scrollTop;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-app/src/components/CodeEditor/index.js` around lines 200 -
217, applyEditorState may restore scrollY but the code unconditionally calls
editor.scrollTo(this.props.initialScroll) and overwrites that; change the mount
logic to first read and store the persisted state (use the returned object from
readPersistedEditorState) and pass it to applyEditorState, then only call
editor.scrollTo(this.props.initialScroll) if this.props.initialScroll is defined
AND the persisted state has no scrollY. Also set _lastScrollTop based on
whichever source was actually applied (persisted.scrollY if present, otherwise
this.props.initialScroll or 0). Update references: applyEditorState,
readPersistedEditorState, editor.scrollTo, this.props.initialScroll, and
_lastScrollTop.
♻️ Duplicate comments (2)
packages/bruno-app/src/components/CodeEditor/index.js (1)

285-286: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Coalesce before stringifying editor content.

String(this.props.value) || '' still turns undefined/null into the literal text 'undefined'/'null' during both update paths. Build nextValue from this.props.value ?? '' once and reuse it for cachedValue and setValue().

Suggested fix
-        this.cachedValue = String(this?.props?.value ?? '');
-        this.editor.setValue(String(this.props.value) || '');
+        const nextValue = String(this.props.value ?? '');
+        this.cachedValue = nextValue;
+        this.editor.setValue(nextValue);
@@
-        this.cachedValue = String(this?.props?.value ?? '');
-        this.editor.setValue(String(this.props.value) || '');
+        const nextValue = String(this.props.value ?? '');
+        this.cachedValue = nextValue;
+        this.editor.setValue(nextValue);

Also applies to: 307-308

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

In `@packages/bruno-app/src/components/CodeEditor/index.js` around lines 285 -
286, Build a single coalesced value from this.props.value before stringifying
and reuse it for both cachedValue and editor.setValue to avoid turning
undefined/null into "undefined"/"null"; e.g., compute const nextValue =
this.props.value ?? '' then set this.cachedValue = String(nextValue) and call
this.editor.setValue(String(nextValue)) (apply the same change where cachedValue
and setValue are assigned around the other occurrence noted).
packages/bruno-app/src/components/CodeEditor/state-persistence.js (1)

69-92: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Length-only matching is still too weak for restore safety.

Line 91 only compares content length, so different text with the same length can still reuse stale history, cursor, and selections. Persist a deterministic hash (or exact content) and require that to match before restoring editor state.

Suggested fix
+const getContentHash = (value = '') => {
+  let hash = 0;
+  for (let i = 0; i < value.length; i += 1) {
+    hash = (hash * 31 + value.charCodeAt(i)) >>> 0;
+  }
+  return hash;
+};
+
 export const captureEditorState = (editor) => {
   if (!editor) return null;
   const doc = editor.getDoc();
+  const content = doc.getValue();
   const folds = editor
@@
   return {
-    contentLength: doc.getValue().length,
+    contentLength: content.length,
+    contentHash: getContentHash(content),
     cursor: doc.getCursor(),
@@
 export const applyEditorState = (editor, state, currentContent) => {
   if (!editor || !state) return;
   const doc = editor.getDoc();
-  const contentMatches = state.contentLength === (currentContent || '').length;
+  const content = currentContent || '';
+  const contentMatches =
+    state.contentHash != null
+      ? state.contentHash === getContentHash(content)
+      : state.contentLength === content.length;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-app/src/components/CodeEditor/state-persistence.js` around
lines 69 - 92, The restore logic in applyEditorState currently trusts
state.contentLength alone (state.contentLength) which allows mismatches when
different text shares the same length; update captureEditorState to also persist
either a deterministic hash (e.g., contentHash) or the exact content string, and
change applyEditorState to compare that hash/content against currentContent
before restoring cursor, selections, history, folds, and scroll. Locate
captureEditorState and add contentHash or contentField computed from
doc.getValue(), and in applyEditorState replace the length-only check with a
combined guard that requires both contentLength and the new
contentHash/contentField to match (or only the hash if you store it) before
applying state.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@packages/bruno-app/src/components/CodeEditor/index.js`:
- Around line 200-217: applyEditorState may restore scrollY but the code
unconditionally calls editor.scrollTo(this.props.initialScroll) and overwrites
that; change the mount logic to first read and store the persisted state (use
the returned object from readPersistedEditorState) and pass it to
applyEditorState, then only call editor.scrollTo(this.props.initialScroll) if
this.props.initialScroll is defined AND the persisted state has no scrollY. Also
set _lastScrollTop based on whichever source was actually applied
(persisted.scrollY if present, otherwise this.props.initialScroll or 0). Update
references: applyEditorState, readPersistedEditorState, editor.scrollTo,
this.props.initialScroll, and _lastScrollTop.

---

Duplicate comments:
In `@packages/bruno-app/src/components/CodeEditor/index.js`:
- Around line 285-286: Build a single coalesced value from this.props.value
before stringifying and reuse it for both cachedValue and editor.setValue to
avoid turning undefined/null into "undefined"/"null"; e.g., compute const
nextValue = this.props.value ?? '' then set this.cachedValue = String(nextValue)
and call this.editor.setValue(String(nextValue)) (apply the same change where
cachedValue and setValue are assigned around the other occurrence noted).

In `@packages/bruno-app/src/components/CodeEditor/state-persistence.js`:
- Around line 69-92: The restore logic in applyEditorState currently trusts
state.contentLength alone (state.contentLength) which allows mismatches when
different text shares the same length; update captureEditorState to also persist
either a deterministic hash (e.g., contentHash) or the exact content string, and
change applyEditorState to compare that hash/content against currentContent
before restoring cursor, selections, history, folds, and scroll. Locate
captureEditorState and add contentHash or contentField computed from
doc.getValue(), and in applyEditorState replace the length-only check with a
combined guard that requires both contentLength and the new
contentHash/contentField to match (or only the hash if you store it) before
applying state.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 423d249d-d0d1-404f-94aa-685cf949524d

📥 Commits

Reviewing files that changed from the base of the PR and between b2b452d and 68dde28.

📒 Files selected for processing (10)
  • packages/bruno-app/src/components/CodeEditor/index.js
  • packages/bruno-app/src/components/CodeEditor/state-persistence.js
  • packages/bruno-app/src/components/CollectionSettings/Script/index.js
  • packages/bruno-app/src/components/CollectionSettings/Tests/index.js
  • packages/bruno-app/src/components/FolderSettings/Script/index.js
  • packages/bruno-app/src/components/FolderSettings/Tests/index.js
  • packages/bruno-app/src/components/RequestPane/Script/index.js
  • packages/bruno-app/src/components/RequestPane/Tests/index.js
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.js
  • packages/bruno-app/src/hooks/usePersistedState/PersistedScopeProvider.tsx
✅ Files skipped from review due to trivial changes (5)
  • packages/bruno-app/src/components/FolderSettings/Script/index.js
  • packages/bruno-app/src/components/RequestPane/Script/index.js
  • packages/bruno-app/src/components/CollectionSettings/Script/index.js
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.js
  • packages/bruno-app/src/hooks/usePersistedState/PersistedScopeProvider.tsx
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/bruno-app/src/components/CollectionSettings/Tests/index.js
  • packages/bruno-app/src/components/FolderSettings/Tests/index.js
  • packages/bruno-app/src/components/RequestPane/Tests/index.js

Already added by ScopeProviders uptop
@sid-bruno
sid-bruno merged commit 5ced51d into usebruno:main May 4, 2026
22 of 23 checks passed
sharan-bruno pushed a commit to sharan-bruno/bruno that referenced this pull request Jun 4, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Jun 22, 2026
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants