Skip to content

Fix: Terminal Resize#6448

Merged
sid-bruno merged 6 commits intousebruno:mainfrom
chirag-bruno:bugfix/terminal-resize
Dec 19, 2025
Merged

Fix: Terminal Resize#6448
sid-bruno merged 6 commits intousebruno:mainfrom
chirag-bruno:bugfix/terminal-resize

Conversation

@chirag-bruno
Copy link
Collaborator

@chirag-bruno chirag-bruno commented Dec 18, 2025

Description

This PR fixes the issue where the terminal would not resize on change in dev tools's size.
It fixes: https://usebruno.atlassian.net/browse/BRU-2324

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.

Summary by CodeRabbit

  • Bug Fixes & Improvements

    • Terminal now uses fit-driven resizing for reliable reaction to container and layout changes, skipping fits for zero-sized containers.
    • Replaced global window resize handling with a parent ResizeObserver to reduce redundant work.
    • Preserves terminal DOM on session switch to avoid disruptive reflows and retain resize behavior.
    • Improved initial sizing and reduced noisy lifecycle events.
  • Refactor

    • Session creation now handles failures gracefully and logs errors without changing public interfaces.
  • UI

    • Minor text and loading-message formatting tweaks.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 18, 2025

Walkthrough

Adds RAF-debounced fit-based resizing for terminal sessions, replacing the global window resize flow with a ResizeObserver on the terminal parent, wires a function ref (onSessionMount) to trigger fits on mount/reattach, parks terminal DOM between sessions, wraps session creation in try/catch, and cleans up frames/observers on unmount.

Changes

Cohort / File(s) Summary
Terminal auto-fit & session lifecycle
packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
Introduces fitTerminal(activeSessionId, container) with requestAnimationFrame debouncing and a fitFrameRef cancellation mechanism; skips fits for zero-sized containers; replaces global window resize + initial resize sequence with a ResizeObserver on the terminal parent; converts terminal ref to a function-based onSessionMount that assigns the node, triggers fitTerminal, and attaches the observer; parks terminal DOM into a hidden parking host during session switches to retain listeners; wraps createNewSession in try/catch and logs on error; ensures cleanup of RAF frames/observers on unmount.

Sequence Diagram(s)

sequenceDiagram
  participant DOM as Terminal DOM
  participant Parent as Parent Container
  participant RO as ResizeObserver
  participant RAF as RAF-debounced fit()
  participant IPC as Main IPC

  Note over DOM,Parent: Terminal mounts / attaches
  DOM->>RAF: onSessionMount -> fitTerminal(container)
  RAF-->>DOM: fitAddon.fit() (if visible & sized)
  RAF->>IPC: send cols/rows (IPC) if session exists

  Note over Parent,RO: Parent layout changes
  Parent->>RO: observed resize
  RO-->>RAF: schedule RAF fit
  RAF-->>DOM: fitAddon.fit()
  RAF->>IPC: send updated cols/rows

  Note over DOM: Session switch / park
  DOM->>DOM: move node -> hidden parking host
  DOM->>RAF: on re-attach -> call fitTerminal() -> schedule follow-up fit
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Verify RAF debouncing/cancel logic (fitFrameRef) and zero-size short-circuit.
  • Inspect ResizeObserver attach/detach on parent and cleanup on unmount/session switch.
  • Confirm parking host DOM moves preserve event listeners and avoid leaks.
  • Validate try/catch around createNewSession doesn't swallow necessary error handling.

Suggested labels

size/M

Suggested reviewers

  • helloanoop
  • lohit-bruno
  • naman-bruno
  • bijin-bruno

Poem

🎛️ A frame delays, then gently fits the view,
Parent eyes the size and signals something new.
Terminals sleep in parks, then wake to bind,
Rows and cols align, IPC keeps time.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Fix: Terminal Resize' directly addresses the main change—fixing terminal resizing when browser dev tools size changes, which is the primary purpose of this PR.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (3)

193-216: Empty catch block silently swallows fit errors.

Line 214's empty catch (e) {} hides potential issues. Consider at minimum logging at warn level for debugging, consistent with other error handling in this file.

🔎 Suggested fix
       try {
         instance.fitAddon.fit();
-      } catch (e) {}
+      } catch (e) {
+        console.warn('Error during terminal fit:', e);
+      }

391-439: Missing fit in dependency array.

The effect uses fit (lines 403, 405) but doesn't include it in the dependency array. While it works because fit and the effect both depend on activeSessionId, adding fit explicitly satisfies exhaustive-deps and makes the intent clearer.

🔎 Suggested fix
-  }, [activeSessionId]);
+  }, [activeSessionId, fit]);

358-388: Consider adding loadSessions to the dependency array.

The polling effect uses loadSessions but has an empty dependency array. While loadSessions is currently stable (memoized with useCallback and empty deps), adding it explicitly would satisfy linter rules and future-proof against changes.

🔎 Suggested fix
-  }, []);
+  }, [loadSessions]);
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 678fa88 and 6868f0d.

📒 Files selected for processing (1)
  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
🧠 Learnings (1)
📚 Learning: 2025-12-17T21:41:24.730Z
Learnt from: naman-bruno
Repo: usebruno/bruno PR: 6407
File: packages/bruno-app/src/components/Environments/ConfirmCloseEnvironment/index.js:5-41
Timestamp: 2025-12-17T21:41:24.730Z
Learning: Do not suggest PropTypes validation for React components in the Bruno codebase. The project does not use PropTypes, so reviews should avoid proposing PropTypes and rely on the existing typing/validation approach (e.g., TypeScript or alternative runtime checks) if applicable. This guideline applies broadly to all JavaScript/JSX components in the repo.

Applied to files:

  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: CLI Tests
  • GitHub Check: Unit Tests
🔇 Additional comments (3)
packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (3)

218-222: LGTM!

Clean window resize listener setup with proper cleanup.


224-239: LGTM!

Solid ResizeObserver implementation. Watching the parent element captures layout changes from split panes and sidebar collapses effectively. The guard for ResizeObserver availability and the initial fit() call after attaching are good practices.


241-249: LGTM!

Proper cleanup of pending RAF on unmount prevents potential memory leaks and errors from calling fit on an unmounted component.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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)
packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (2)

193-216: Consider cleanup for pending RAF on unmount.

The empty catch block at line 214 silently suppresses errors, which might make debugging difficult. Additionally, if the component unmounts while fitRafRef.current holds a pending RAF ID, that frame callback will still execute and attempt to access container and instance, potentially causing issues.

🔎 Add cleanup logic to cancel pending RAF on unmount:

Consider adding a cleanup effect:

+  useEffect(() => {
+    return () => {
+      if (fitRafRef.current) {
+        cancelAnimationFrame(fitRafRef.current);
+        fitRafRef.current = null;
+      }
+    };
+  }, []);

For the empty catch block, consider at least logging the error:

       try {
         instance.fitAddon.fit();
-      } catch (e) {}
+      } catch (e) {
+        console.warn('Failed to fit terminal:', e);
+      }

368-384: Verify if triple fitting is necessary.

The terminal undergoes three separate fit operations for a single session activation:

  1. Line 176 in openTerminalIntoContainer (after 50ms delay)
  2. Line 370 immediately after setup
  3. Line 372 after 100ms timeout

While terminal sizing can require layout settling time, three fits may cause unnecessary reflows and performance overhead.

Consider consolidating these fits or verifying whether all three are essential for proper sizing across different scenarios.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6868f0d and 4c55eed.

📒 Files selected for processing (1)
  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
🧠 Learnings (2)
📚 Learning: 2025-12-02T20:48:05.670Z
Learnt from: NikHillAgar
Repo: usebruno/bruno PR: 6279
File: packages/bruno-app/src/components/RequestPane/PromptVariables/PromptVariablesModal/index.js:79-86
Timestamp: 2025-12-02T20:48:05.670Z
Learning: In React 19+, ref callbacks support returning cleanup functions. When a ref callback returns a function, React will call it when the element unmounts or the ref changes, similar to useEffect cleanup. This is documented at https://react.dev/learn/manipulating-the-dom-with-refs#how-to-manage-a-list-of-refs-using-a-ref-callback

Applied to files:

  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
📚 Learning: 2025-12-17T21:41:24.730Z
Learnt from: naman-bruno
Repo: usebruno/bruno PR: 6407
File: packages/bruno-app/src/components/Environments/ConfirmCloseEnvironment/index.js:5-41
Timestamp: 2025-12-17T21:41:24.730Z
Learning: Do not suggest PropTypes validation for React components in the Bruno codebase. The project does not use PropTypes, so reviews should avoid proposing PropTypes and rely on the existing typing/validation approach (e.g., TypeScript or alternative runtime checks) if applicable. This guideline applies broadly to all JavaScript/JSX components in the repo.

Applied to files:

  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: SSL Tests - Windows

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

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

454-461: CRITICAL: Fix the ResizeObserver cleanup pattern.

This is a duplicate of the previously flagged memory leak concern. The ref callback pattern needs adjustment to ensure proper cleanup. Additionally, as noted by sid-bruno, this can be simplified.

The current implementation creates a new ResizeObserver on every render (because the ref callback is recreated), and while React 19 should call the cleanup function, the early return pattern when node is null may not interact correctly with the cleanup mechanism.

🔎 Apply the suggested fix to ensure proper cleanup:
           <div
             ref={(node) => {
-              if (!node) return;
+              if (!node) {
+                terminalRef.current = null;
+                return;
+              }
               terminalRef.current = node;
               fit();
               const ro = new ResizeObserver(() => fit());
               ro.observe(node.parentNode);
               return () => {
                 ro.disconnect();
               };
             }}
             className="terminal-container"

Based on learnings, React 19 ref callbacks support cleanup functions similar to useEffect, but the pattern must handle the null case explicitly.

🧹 Nitpick comments (1)
packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (1)

193-216: Consider documenting or logging the empty catch.

The RAF-debounced fitting logic is sound. However, the empty catch block on line 214 silently suppresses fitAddon.fit() errors. While this may be intentional to prevent UI breakage, consider adding a comment explaining why errors are ignored, or use console.warn for debugging purposes.

🔎 Optional: Add error context
       try {
         instance.fitAddon.fit();
-      } catch (e) {}
+      } catch (e) {
+        // Ignore fit errors during layout transitions
+      }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4c55eed and 9d4020d.

📒 Files selected for processing (1)
  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
🧠 Learnings (2)
📚 Learning: 2025-12-02T20:48:05.670Z
Learnt from: NikHillAgar
Repo: usebruno/bruno PR: 6279
File: packages/bruno-app/src/components/RequestPane/PromptVariables/PromptVariablesModal/index.js:79-86
Timestamp: 2025-12-02T20:48:05.670Z
Learning: In React 19+, ref callbacks support returning cleanup functions. When a ref callback returns a function, React will call it when the element unmounts or the ref changes, similar to useEffect cleanup. This is documented at https://react.dev/learn/manipulating-the-dom-with-refs#how-to-manage-a-list-of-refs-using-a-ref-callback

Applied to files:

  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
📚 Learning: 2025-12-17T21:41:24.730Z
Learnt from: naman-bruno
Repo: usebruno/bruno PR: 6407
File: packages/bruno-app/src/components/Environments/ConfirmCloseEnvironment/index.js:5-41
Timestamp: 2025-12-17T21:41:24.730Z
Learning: Do not suggest PropTypes validation for React components in the Bruno codebase. The project does not use PropTypes, so reviews should avoid proposing PropTypes and rely on the existing typing/validation approach (e.g., TypeScript or alternative runtime checks) if applicable. This guideline applies broadly to all JavaScript/JSX components in the repo.

Applied to files:

  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: Unit Tests
  • GitHub Check: CLI Tests
🔇 Additional comments (2)
packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (2)

188-188: LGTM: RAF tracking ref.

The fitRafRef is correctly used to track pending animation frames for debouncing.


368-394: LGTM: Terminal lifecycle handling.

The double-fit approach (immediate + delayed) properly handles layout settling, and parking the terminal DOM on session switch is an efficient pattern.

- Refactored fit logic to avoid unnecessary calls during hidden states.
- Enhanced error handling when creating new terminal sessions.
- Updated ResizeObserver to ensure proper fitting on container resize.
@pull-request-size pull-request-size bot added size/L and removed size/M labels Dec 19, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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)
packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (1)

203-206: Add comment or logging to empty catch block.

The empty catch block silently swallows any errors from fitAddon.fit(). Consider adding a comment explaining why errors are intentionally ignored, or use console.warn for debugging purposes.

🔎 Suggested improvement
     try {
       instance.fitAddon.fit();
-    } catch (e) {}
+    } catch (e) {
+      // Silently ignore fit errors that can occur during rapid layout changes
+    }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 763a4e3 and 2b7cb5c.

📒 Files selected for processing (1)
  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (5 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
🧠 Learnings (2)
📚 Learning: 2025-12-02T20:48:05.670Z
Learnt from: NikHillAgar
Repo: usebruno/bruno PR: 6279
File: packages/bruno-app/src/components/RequestPane/PromptVariables/PromptVariablesModal/index.js:79-86
Timestamp: 2025-12-02T20:48:05.670Z
Learning: In React 19+, ref callbacks support returning cleanup functions. When a ref callback returns a function, React will call it when the element unmounts or the ref changes, similar to useEffect cleanup. This is documented at https://react.dev/learn/manipulating-the-dom-with-refs#how-to-manage-a-list-of-refs-using-a-ref-callback

Applied to files:

  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
📚 Learning: 2025-12-17T21:41:24.730Z
Learnt from: naman-bruno
Repo: usebruno/bruno PR: 6407
File: packages/bruno-app/src/components/Environments/ConfirmCloseEnvironment/index.js:5-41
Timestamp: 2025-12-17T21:41:24.730Z
Learning: Do not suggest PropTypes validation for React components in the Bruno codebase. The project does not use PropTypes, so reviews should avoid proposing PropTypes and rely on the existing typing/validation approach (e.g., TypeScript or alternative runtime checks) if applicable. This guideline applies broadly to all JavaScript/JSX components in the repo.

Applied to files:

  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: Unit Tests
  • GitHub Check: CLI Tests
🔇 Additional comments (2)
packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (2)

249-267: Good error handling in session creation.

The try/catch wrapper with error logging and explicit null return provides clear failure handling.


368-376: LGTM!

The initial resize logic properly handles errors and validates the instance before sending IPC messages.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

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

401-411: Critical: Stale activeSessionId in ResizeObserver callback.

This issue was previously flagged in past reviews and remains unresolved. When activeSessionId changes (user switches sessions), the ref callback doesn't re-execute because the DOM node doesn't change. The ResizeObserver continues calling fitTerminal with the old session ID, breaking resize functionality after session switches—the exact issue this PR aims to fix.

Example:

  1. Mount with session 'A' → observer uses 'A'
  2. Switch to session 'B' → observer still uses 'A' (ref callback doesn't fire)
  3. Resize devtools → fitTerminal('A', node) called instead of fitTerminal('B', node)
🔎 Recommended fix using a ref to track current session

Store activeSessionId in a ref and read from it in the observer callback:

 const TerminalTab = () => {
   const terminalRef = useRef(null);
+  const activeSessionIdRef = useRef(null);
   const [sessions, setSessions] = useState([]);
   const [activeSessionId, setActiveSessionId] = useState(null);
   const [isLoading, setIsLoading] = useState(true);
+
+  // Keep ref in sync with state
+  useEffect(() => {
+    activeSessionIdRef.current = activeSessionId;
+  }, [activeSessionId]);

Then update the ref callback to use the ref:

   const onSessionMount = useCallback(
     (node) => {
-      if (!node) return;
+      if (!node) {
+        terminalRef.current = null;
+        return;
+      }
       terminalRef.current = node;
-      fitTerminal(activeSessionId, node);
-      const ro = new ResizeObserver(() => fitTerminal(activeSessionId, node));
+      fitTerminal(activeSessionIdRef.current, node);
+      const ro = new ResizeObserver(() => fitTerminal(activeSessionIdRef.current, node));
       ro.observe(node.parentNode);
       return () => ro.disconnect();
     },
-    [activeSessionId]
+    []
   );

Note: Remove activeSessionId from dependencies since we're using the ref.

Based on past review feedback.

🧹 Nitpick comments (1)
packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (1)

186-207: Module-level fitFrameRef could cause issues with multiple component instances.

fitFrameRef is declared at module scope, meaning if multiple TerminalTab components are rendered simultaneously (e.g., in different windows or contexts), they'll share the same frame reference. This could lead to cancelled fit operations affecting the wrong component.

Consider moving fitFrameRef into component state via useRef:

🔎 Proposed refactor to scope fitFrameRef per component
 const TerminalTab = () => {
   const terminalRef = useRef(null);
+  const fitFrameRef = useRef(null);
   const [sessions, setSessions] = useState([]);
   // ...

Then update fitTerminal to accept the ref:

-let fitFrameRef;
-const fitTerminal = (activeSessionId, container) => {
+const fitTerminal = (activeSessionId, container, fitFrameRef) => {
   if (!container) return;
 
   const instance = terminalInstances.get(activeSessionId);
   if (!instance?.fitAddon) return;
 
-  if (fitFrameRef) {
-    cancelAnimationFrame(fitFrameRef);
+  if (fitFrameRef.current) {
+    cancelAnimationFrame(fitFrameRef.current);
   }
 
-  fitFrameRef = requestAnimationFrame(() => {
-    fitFrameRef = null;
+  fitFrameRef.current = requestAnimationFrame(() => {
+    fitFrameRef.current = null;
     // ...
   });
 };

And update all fitTerminal calls to pass the ref.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2b7cb5c and 5caa206.

📒 Files selected for processing (1)
  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (6 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
🧠 Learnings (2)
📚 Learning: 2025-12-02T20:48:05.670Z
Learnt from: NikHillAgar
Repo: usebruno/bruno PR: 6279
File: packages/bruno-app/src/components/RequestPane/PromptVariables/PromptVariablesModal/index.js:79-86
Timestamp: 2025-12-02T20:48:05.670Z
Learning: In React 19+, ref callbacks support returning cleanup functions. When a ref callback returns a function, React will call it when the element unmounts or the ref changes, similar to useEffect cleanup. This is documented at https://react.dev/learn/manipulating-the-dom-with-refs#how-to-manage-a-list-of-refs-using-a-ref-callback

Applied to files:

  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
📚 Learning: 2025-12-17T21:41:24.730Z
Learnt from: naman-bruno
Repo: usebruno/bruno PR: 6407
File: packages/bruno-app/src/components/Environments/ConfirmCloseEnvironment/index.js:5-41
Timestamp: 2025-12-17T21:41:24.730Z
Learning: Do not suggest PropTypes validation for React components in the Bruno codebase. The project does not use PropTypes, so reviews should avoid proposing PropTypes and rely on the existing typing/validation approach (e.g., TypeScript or alternative runtime checks) if applicable. This guideline applies broadly to all JavaScript/JSX components in the repo.

Applied to files:

  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: CLI Tests
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: Unit Tests
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: SSL Tests - Windows
🔇 Additional comments (2)
packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (2)

249-267: Good addition of error handling.

The try/catch wrapper provides graceful error handling while preserving the original success behavior. Clear error logging helps with debugging.


368-376: LGTM.

Initial resize signaling with proper error handling looks correct.

@sid-bruno sid-bruno merged commit 3552e7e into usebruno:main Dec 19, 2025
8 checks passed
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.

2 participants