Skip to content

Inbuilt Terminal - #6066

Merged
sid-bruno merged 14 commits into
usebruno:mainfrom
chirag-bruno:feat/term
Dec 3, 2025
Merged

sid-bruno merged 14 commits into
usebruno:mainfrom
chirag-bruno:feat/term

Conversation

@chirag-bruno

@chirag-bruno chirag-bruno commented Nov 12, 2025 •

Copy link
Copy Markdown
Collaborator

Description

This PR delivers the Inbuilt Terminal feature from the product roadmap.
It addresses a feature request made here.

Highlights

  • Integrated Terminal Environment — available under the Terminal tab in Dev Tools.
  • Multi-Session Support — run multiple terminal sessions concurrently, enabling parallel long-running tasks.
  • Contextual Launch Points — start terminal sessions directly from the Collection or Folder level.
  • Graceful Session Management — all active sessions are automatically terminated when the app closes.

This implementation extends and refines @naman-bruno's work in #5681.

Demo:

Screen.Recording.2025-11-07.at.11.54.14.AM.mov

Contribution Checklist:

  • 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

  • New Features

    • Integrated terminal tab in DevTools with multi-session support, session list sidebar, and per-session terminal panes
    • "Open in Terminal" option for collections/folders to launch a terminal at the selected directory
    • Create/select/close sessions and open terminals at a specific working directory
  • Bug Fixes

    • Improved terminal lifecycle and cleanup to ensure sessions are disposed on app quit

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

@xianghongai

Copy link
Copy Markdown

🎉

sid-bruno and others added 4 commits November 27, 2025 13:36
…Dropdown design

- Resolved merge conflicts in Collection component
- Updated 'Open In Terminal' button to match new Dropdown design pattern
- Ensures consistent UI/UX across collection actions
@coderabbitai

coderabbitai Bot commented Dec 2, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This PR adds an in-app terminal feature: xterm-based renderer UI with per-session management, Electron main-process PTY session manager, IPC channels for terminal I/O, sidebar "Open in Terminal" actions, and small preload and utility wiring to connect them.

Changes

Cohort / File(s) Summary
Dependencies
packages/bruno-app/package.json, packages/bruno-electron/package.json
Added renderer deps @xterm/xterm and @xterm/addon-fit; added main-process PTY runtime @lydell/node-pty.
Terminal UI Components
packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js, .../SessionList.js, .../StyledWrapper.js
New TerminalTab React UI managing multiple xterm instances, IPC listeners, session lifecycle, sidebar session list (SessionList), and styling wrapper (StyledWrapper). Exports a getSessionId() helper and default TerminalTab.
Console Integration
packages/bruno-app/src/components/Devtools/Console/index.js
Added Terminal tab button and routing to render the new TerminalTab.
Sidebar Terminal Actions
packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/index.js, packages/bruno-app/src/components/Sidebar/Collections/Collection/index.js
Added "Open in Terminal" menu item that calls utility to open devtools and request a terminal at a collection/folder CWD.
Terminal Utilities
packages/bruno-app/src/utils/terminal.js
New utilities: openDevtoolsAndSwitchToTerminal(dispatch, cwd = null) to open console/switch to terminal and emit a CWD event; getSessionID() delegating to TerminalTab's helper.
Electron Main Process
packages/bruno-electron/src/ipc/terminal.js
New TerminalManager class that spawns/manages PTY sessions, exposes IPC handlers for create/input/resize/kill/list, broadcasts data/exit events, handles session cleanup and default shell/cwd detection; exported via module.exports.
Electron Lifecycle Integration
packages/bruno-electron/src/index.js
Instantiated TerminalManager; wired cleanup on main window close and killAll on app quit.
IPC Bridge / Preload
packages/bruno-electron/src/preload.js
Exposed ipcRenderer.send(channel, ...args) to renderer and normalized on-channel listener arg handling so handlers always receive an args array.

Sequence Diagrams

sequenceDiagram
    participant User
    participant Renderer as Renderer (React)
    participant Preload as IPC Bridge (preload)
    participant Main as Main Process (TerminalManager)
    participant PTY as PTY Process

    User->>Renderer: Click "Open in Terminal" (folder/collection)
    Renderer->>Renderer: dispatch openConsole & set active tab = terminal
    Renderer->>Renderer: emit CustomEvent "terminal:open-at-cwd" (cwd)
    Renderer->>Preload: IPC request to open/initialize session (via send/on)
    Preload->>Main: IPC: create session with cwd
    Main->>Main: generate sessionId, detect shell, determine cwd
    Main->>PTY: spawn PTY at cwd with shell
    PTY-->>Main: PTY ready / emits data
    Main->>Preload: IPC: terminal:session-created {id, cwd}
    Preload->>Renderer: forward session-created
    Renderer->>Renderer: create xterm instance, mount to DOM, subscribe to input events

    User->>Renderer: Type input
    Renderer->>Preload: ipcRenderer.send("terminal:input", sessionId, data)
    Preload->>Main: forward input
    Main->>PTY: write(data)
    PTY-->>Main: output data
    Main->>Preload: ipc channel terminal:data:<id> (data)
    Preload->>Renderer: deliver data event
    Renderer->>Renderer: xterm.write(output)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Pay close attention to:
    • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js — IPC listener setup/teardown, DOM parking/unparking, resize/fit logic.
    • packages/bruno-electron/src/ipc/terminal.js — PTY spawn options, session lifecycle, error handling, and channel naming/versioning.
    • packages/bruno-electron/src/preload.js — argument normalization and ensuring compatibility with existing renderer IPC usage.
    • Cross-file IPC channel name consistency and event payload shapes between renderer, preload, and main.

Poem

🖥️ Terminals awaken, shells begin to hum,
Sessions line the sidebar, ready to become,
PTY and xterm whisper, IPC threads entwine—
Click, spawn, type, and watch the prompt align. 🚀

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 'Inbuilt Terminal' directly and concisely captures the main feature added across the entire changeset—a terminal UI integrated into the dev tools.
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

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

🧹 Nitpick comments (16)
packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/index.js (1)

660-672: Missing icon for "Open in Terminal" dropdown item.

Other dropdown items include an icon in a <span className="dropdown-icon"> wrapper. This item lacks an icon, creating visual inconsistency.

+import { IconTerminal2 } from '@tabler/icons';

Then update the dropdown item:

               {isFolder && (
                 <div
                   className="dropdown-item"
                   onClick={async (e) => {
                     dropdownTippyRef.current.hide();
                     // Get folder pathname
                     const folderCwd = item.pathname || collectionPathname;
                     await openDevtoolsAndSwitchToTerminal(dispatch, folderCwd);
                   }}
                 >
+                  <span className="dropdown-icon">
+                    <IconTerminal2 size={16} strokeWidth={2} />
+                  </span>
                   Open in Terminal
                 </div>
               )}
packages/bruno-app/src/components/Devtools/Console/index.js (1)

505-511: Consider using a distinct icon for the Terminal tab.

Both the Console tab (line 485) and Terminal tab use IconTerminal2. This may cause visual confusion. Consider using a different icon for Terminal, such as IconPrompt or keeping as-is if intentional.

packages/bruno-electron/src/index.js (2)

166-169: Redundant null check on terminalManager.

terminalManager is always instantiated at line 55. The if (terminalManager) check is unnecessary.

     // Clean up terminal sessions for this window
-    if (terminalManager) {
-      terminalManager.cleanup(mainWindow.webContents);
-    }
+    terminalManager.cleanup(mainWindow.webContents);

239-243: Redundant null check; also ensure killAll() handles errors gracefully.

Same redundant check. Also consider wrapping in try-catch for robustness during shutdown, similar to the cookies save above it.

   // Clean up terminal sessions
-  if (terminalManager) {
-    terminalManager.killAll();
-  }
+  try {
+    terminalManager.killAll();
+  } catch (err) {
+    console.warn('Failed to kill terminal sessions on quit', err);
+  }
packages/bruno-electron/src/preload.js (1)

8-12: Redundant check in safeArgs normalization.

The args rest parameter is always an array (possibly empty). The condition args && args.length is redundant since an empty array [] is truthy but has length 0, making the fallback trigger unnecessarily for valid empty arrays.

This is harmless but could be simplified:

-      const safeArgs = args && args.length ? args : [];
-      handler(...safeArgs);
+      handler(...args);
packages/bruno-app/src/components/Devtools/Console/TerminalTab/StyledWrapper.js (1)

66-83: Potential style duplication with SessionList.js.

These session item styles (.terminal-session-item, .terminal-session-name, .terminal-session-path) overlap with StyledSessionList in SessionList.js. Consider consolidating to avoid drift.

packages/bruno-app/src/components/Devtools/Console/TerminalTab/SessionList.js (1)

2-2: Unused import IconPlus.

IconPlus is imported but never used in this component.

-import { IconTerminal, IconPlus, IconX } from '@tabler/icons';
+import { IconTerminal, IconX } from '@tabler/icons';
packages/bruno-app/src/utils/terminal.js (2)

19-24: Timing-based mount assumption is fragile.

The 100ms setTimeout assumes the terminal tab mounts within that window. Consider using a more reliable approach like event acknowledgment or a retry mechanism if the component isn't ready.


31-33: Redundant wrapper function.

getSessionID just delegates to getSessionId. Consumers could import getSessionId directly unless you're planning to add logic here later.

packages/bruno-electron/src/ipc/terminal.js (1)

96-106: Potential double-delete of session.

terminal:kill deletes the session (line 101), but onExit callback (line 55) also deletes it. While Map.delete is idempotent, the onExit handler might still fire and send an exit event to a potentially destroyed webContents.

Consider skipping the delete in terminal:kill and letting onExit handle cleanup, or flag the session as "killing" to suppress the exit event.

packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (6)

96-106: Variable shadowing: rename inner instance to avoid confusion.

Line 98 declares instance which shadows the outer instance from line 85. While functional (the re-fetch is intentional to avoid stale closures), the name collision reduces readability.

     const onData = (data) => {
       if (!data) return;
-      const instance = terminalInstances.get(sessionId);
-      if (instance && instance.terminal) {
+      const termInstance = terminalInstances.get(sessionId);
+      if (termInstance && termInstance.terminal) {
         try {
-          instance.terminal.write(data);
+          termInstance.terminal.write(data);
         } catch (err) {
           console.warn('Failed to write terminal data:', err);
         }
       }
     };

174-184: Add comment explaining the 50ms delay.

Magic numbers reduce maintainability. A brief comment explaining why this delay is needed (e.g., waiting for DOM layout) would help future readers.

-  await new Promise((resolve) => setTimeout(resolve, 50));
+  // Allow DOM to settle before fitting terminal to container dimensions
+  await new Promise((resolve) => setTimeout(resolve, 50));

298-329: Missing dependency loadSessions in useEffect.

The effect references loadSessions but the dependency array is empty. While the inline comment explains the intent, this will trigger ESLint react-hooks/exhaustive-deps warnings if enabled. Consider adding it to deps since it's a stable useCallback.

     return () => {
       mounted = false;
       clearInterval(pollInterval);
     };
-  }, []);
+  }, [loadSessions]);

343-347: Empty catch block silently swallows errors.

Even if resize failures are non-critical, consider at minimum a debug-level log to aid troubleshooting.

           const onResize = () => {
             try {
               instance.fitAddon.fit();
-            } catch (e) {}
+            } catch (e) {
+              // Resize failures are non-critical; log for debugging only
+              console.debug('Terminal resize failed:', e);
+            }
           };

379-386: Async cleanup pattern is unconventional but functional.

The Promise.resolve(cleanup).then(...) pattern handles both sync and async cleanup returns. This works but is subtle. A comment would clarify intent for maintainers.

     return () => {
       mounted = false;
+      // setupTerminal may return a cleanup function; handle both sync and async cases
       Promise.resolve(cleanup).then((fn) => {
         if (typeof fn === 'function') fn();
       });
     };

108-120: Same variable shadowing issue in onExit handler.

Line 110 also shadows the outer instance variable, similar to the onData handler.

     const onExit = ({ exitCode, signal } = {}) => {
       const msg = `\r\n[Process exited with code ${exitCode ?? ''} ${signal ? `(signal ${signal})` : ''}]\r\n`;
-      const instance = terminalInstances.get(sessionId);
-      if (instance && instance.terminal) {
+      const termInstance = terminalInstances.get(sessionId);
+      if (termInstance && termInstance.terminal) {
         try {
-          instance.terminal.write(msg);
+          termInstance.terminal.write(msg);
         } catch (err) {
           console.warn('Failed to write terminal exit message:', err);
         }
       }
📜 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 dd72ee5 and 8e85e29.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (12)
  • packages/bruno-app/package.json (1 hunks)
  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/SessionList.js (1 hunks)
  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/StyledWrapper.js (1 hunks)
  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (1 hunks)
  • packages/bruno-app/src/components/Devtools/Console/index.js (4 hunks)
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/index.js (2 hunks)
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/index.js (3 hunks)
  • packages/bruno-app/src/utils/terminal.js (1 hunks)
  • packages/bruno-electron/package.json (1 hunks)
  • packages/bruno-electron/src/index.js (4 hunks)
  • packages/bruno-electron/src/ipc/terminal.js (1 hunks)
  • packages/bruno-electron/src/preload.js (1 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
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single parameters
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses. Keep 'em tight
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
Avoid single line abstractions where all that's being done is increasing the call stack with one additional function
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/SessionList.js
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/index.js
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/index.js
  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/StyledWrapper.js
  • packages/bruno-app/src/components/Devtools/Console/index.js
  • packages/bruno-app/src/utils/terminal.js
  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js
  • packages/bruno-electron/src/preload.js
  • packages/bruno-electron/src/index.js
  • packages/bruno-electron/src/ipc/terminal.js
🧬 Code graph analysis (4)
packages/bruno-app/src/components/Sidebar/Collections/Collection/index.js (1)
packages/bruno-app/src/utils/terminal.js (2)
  • openDevtoolsAndSwitchToTerminal (11-25)
  • openDevtoolsAndSwitchToTerminal (11-25)
packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/index.js (3)
packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/DeleteCollectionItem/index.js (1)
  • isFolder (13-13)
packages/bruno-js/src/sandbox/quickjs/index.js (1)
  • e (79-79)
packages/bruno-app/src/utils/terminal.js (2)
  • openDevtoolsAndSwitchToTerminal (11-25)
  • openDevtoolsAndSwitchToTerminal (11-25)
packages/bruno-app/src/components/Devtools/Console/index.js (3)
packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (1)
  • TerminalTab (186-447)
packages/bruno-app/src/components/Devtools/Console/RequestDetailsPanel/index.js (1)
  • activeTab (160-160)
packages/bruno-app/src/components/Devtools/Console/ErrorDetailsPanel/index.js (1)
  • activeTab (191-191)
packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (2)
packages/bruno-app/src/components/Devtools/Console/TerminalTab/StyledWrapper.js (1)
  • StyledWrapper (3-199)
packages/bruno-app/src/components/Devtools/Console/TerminalTab/SessionList.js (1)
  • SessionList (80-149)
🪛 Biome (2.1.2)
packages/bruno-app/src/components/Devtools/Console/TerminalTab/SessionList.js

[error] 119-124: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

⏰ 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: Playwright E2E Tests
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: Unit Tests
  • GitHub Check: CLI Tests
🔇 Additional comments (18)
packages/bruno-app/src/components/Sidebar/Collections/Collection/index.js (1)

400-412: LGTM! "Open in Terminal" dropdown item implemented correctly.

Proper icon, async handler, and pathname usage. Consistent with existing dropdown patterns in this file.

packages/bruno-app/src/components/Devtools/Console/index.js (2)

393-394: LGTM! Terminal tab case added correctly.

Follows the existing switch-case pattern for tab content rendering.


448-449: LGTM! No controls needed for terminal tab.

Returning null is appropriate since TerminalTab manages its own session controls internally.

packages/bruno-electron/src/index.js (2)

45-45: LGTM! TerminalManager import follows existing patterns.

Consistent with how other IPC modules are imported in this file.


55-55: LGTM! TerminalManager instantiation follows existing patterns.

Mirrors the instantiation style of lastOpenedCollections and systemMonitor.

packages/bruno-electron/package.json (1)

35-35: Verify cross-platform compatibility of @lydell/node-pty.

Native PTY module added for terminal session management. Ensure electron-builder is configured to rebuild this native module for all target platforms (macOS, Windows, Linux).

packages/bruno-app/package.json (1)

24-25: Xterm dependencies are at the latest stable versions.

Both packages are correctly specified: @xterm/[email protected] and @xterm/[email protected] are the latest stable releases as of December 2, 2025. The caret versioning allows for appropriate patch and minor updates. Looks good.

packages/bruno-electron/src/preload.js (1)

5-5: LGTM on send exposure.

Appropriate addition for fire-and-forget terminal IPC operations (input, resize, kill).

packages/bruno-app/src/components/Devtools/Console/TerminalTab/StyledWrapper.js (1)

1-201: LGTM overall.

Clean, well-organized styling with proper theme integration and xterm overrides.

packages/bruno-app/src/components/Devtools/Console/TerminalTab/SessionList.js (1)

81-105: LGTM on display logic.

Clean fallback chain: session.name → folder name from cwd → Terminal {shortId}. Edge cases for root paths handled well.

packages/bruno-electron/src/ipc/terminal.js (3)

26-32: Environment passthrough.

Passing process.env directly to the PTY exposes all environment variables to terminal sessions. This is likely intentional for shell functionality, but ensure no sensitive build-time secrets are in process.env at runtime.


169-179: LGTM on killAll implementation.

Clean shutdown logic with proper iteration and final clear().


115-127: No action needed on Windows compatibility.

process.kill(pid, 0) is explicitly supported on Windows in Node.js as a cross-platform existence check. Node emulates signals on Windows and handles signal 0 portably. The existing try-catch already correctly handles the expected errors (ESRCH for non-existent processes, EPERM for permission issues) on all platforms.

packages/bruno-app/src/utils/terminal.js (1)

50-53: Missing IPC handler terminal:has-active-process.

callIpc('terminal:has-active-process', sessionId) is invoked at line 52, but no corresponding ipcMain.handle('terminal:has-active-process', ...) could be verified to exist in the codebase. This will cause the IPC call to fail if the handler is not registered.

packages/bruno-app/src/components/Devtools/Console/TerminalTab/index.js (4)

131-157: LGTM!

Cleanup logic properly disposes all resources and removes session-specific IPC listeners. The try-catch blocks ensure graceful degradation on errors.


389-445: LGTM!

The JSX structure is clean with proper conditional rendering for loading states and empty sessions. The SessionList integration and inline styles for the placeholder states are appropriate.


316-323: Consider switching to an event-driven approach if session lifecycle IPC events are available.

The current 2-second polling for session updates could be replaced with an event-driven mechanism where the main process emits session lifecycle events (created/destroyed) instead. This would reduce IPC overhead and provide instant updates. First, verify that the necessary terminal session lifecycle IPC events exist in the main process implementation before undertaking this refactor.


41-68: Verify if Terminal theme should adapt to app theme configuration.

The hardcoded xterm terminal theme colors may not adapt if Bruno supports dynamic theme switching. Confirm whether the application implements light/dark themes, whether theme values are available through context or props, and if the Terminal component should pull theme colors from a shared theme configuration rather than hardcoding them.

- Add terminal icon to 'Open in Terminal' dropdown item in CollectionItem
- Remove unused imports and functions (IconPlus, callIpc, canWriteToTerminal)
- Fix React key prop placement in SessionList component
- Replace deprecated substr with substring in terminal session ID generation
- Improve error handling for terminal cleanup on app quit
- Simplify terminal cleanup logic in window close handler

@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: 0

🧹 Nitpick comments (6)
packages/bruno-electron/src/index.js (1)

164-168: Cleanup order may leave terminals running during quit flow.

terminalManager.cleanup() runs, then main:start-quit-flow fires. If the quit flow is lengthy or async, terminal cleanup happens early which is fine. However, since cleanup() only cleans terminals for this specific webContents, and killAll() is called in before-quit, this is effectively redundant but harmless.

Consider whether you need both—killAll() in before-quit should suffice for shutdown scenarios.

packages/bruno-electron/src/ipc/terminal.js (5)

15-25: No validation on user-supplied cwd path.

The options.cwd is used directly without checking if the path exists or is accessible. This could cause silent failures or unexpected behavior. Consider adding a path existence check.

+const fs = require('fs');
     ipcMain.handle('terminal:create', (event, options = {}) => {
       try {
         const sessionId = this.generateSessionId();
         const shell = this.getDefaultShell();
-        // Use provided cwd or default to home directory
-        const cwd = options.cwd || this.getDefaultCwd();
+        // Use provided cwd or default to home directory
+        let cwd = options.cwd || this.getDefaultCwd();
+        // Validate cwd exists, fallback to default if not
+        if (!fs.existsSync(cwd)) {
+          console.warn(`Terminal cwd does not exist: ${cwd}, falling back to default`);
+          cwd = this.getDefaultCwd();
+        }

96-106: Wrap entire handler in try/catch for consistency.

Other handlers have the try/catch at the outermost level. This one has it only around the kill operation, meaning a thrown error from this.terminals.get() would be unhandled.

     ipcMain.on('terminal:kill', (event, sessionId) => {
+      try {
         const terminal = this.terminals.get(sessionId);
         if (terminal && terminal.pty) {
-          try {
-            terminal.pty.kill();
-            this.terminals.delete(sessionId);
-          } catch (error) {
-            console.error('Failed to kill terminal:', error);
-          }
+          terminal.pty.kill();
+          this.terminals.delete(sessionId);
         }
+      } catch (error) {
+        console.error('Failed to kill terminal:', error);
+      }
     });

151-153: Session ID entropy is limited.

substring(2, 9) extracts 7 characters (indices 2 through 8). Combined with Date.now(), this should be unique enough for typical use, but if high session creation rates are expected, consider using crypto.randomUUID() for guaranteed uniqueness.


7-11: Consider limiting maximum concurrent terminal sessions.

No upper bound on session count. A misbehaving client or bug could spawn unlimited terminals, exhausting system resources.

 class TerminalManager {
+  static MAX_SESSIONS = 10;
+
   constructor() {
     this.terminals = new Map();
     this.setupIpcHandlers();
   }

Then in terminal:create:

if (this.terminals.size >= TerminalManager.MAX_SESSIONS) {
  console.warn('Maximum terminal sessions reached');
  return null;
}

26-32: Consider environment variable filtering for spawned terminals.

Passing the entire process.env to spawned terminals could expose process-level environment variables to terminal sessions. While this is common in Electron apps, consider filtering sensitive keys if your application stores secrets in the Node process environment.

📜 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 8e85e29 and 7233831.

📒 Files selected for processing (5)
  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/SessionList.js (1 hunks)
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/index.js (3 hunks)
  • packages/bruno-app/src/utils/terminal.js (1 hunks)
  • packages/bruno-electron/src/index.js (4 hunks)
  • packages/bruno-electron/src/ipc/terminal.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/index.js
  • packages/bruno-app/src/utils/terminal.js
  • packages/bruno-app/src/components/Devtools/Console/TerminalTab/SessionList.js
🧰 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
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single parameters
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses. Keep 'em tight
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
Avoid single line abstractions where all that's being done is increasing the call stack with one additional function
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-electron/src/ipc/terminal.js
  • packages/bruno-electron/src/index.js
🧬 Code graph analysis (1)
packages/bruno-electron/src/ipc/terminal.js (2)
packages/bruno-electron/src/index.js (11)
  • require (14-14)
  • require (15-15)
  • require (16-16)
  • require (34-34)
  • require (42-42)
  • require (46-46)
  • require (47-47)
  • require (48-48)
  • require (51-51)
  • require (82-82)
  • TerminalManager (45-45)
packages/bruno-electron/src/preload.js (1)
  • require (1-1)
⏰ 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: Unit Tests
  • GitHub Check: CLI Tests
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: SSL Tests - macOS
🔇 Additional comments (6)
packages/bruno-electron/src/index.js (1)

236-241: LGTM on error-wrapped terminal shutdown.

The try/catch around terminalManager.killAll() ensures a failing terminal cleanup doesn't block the quit flow. Consistent with the cookie save pattern above.

packages/bruno-electron/src/ipc/terminal.js (5)

42-50: LGTM on data handler.

Good defensive check for event.sender.isDestroyed() before sending data. Prevents crashes when the renderer is gone.


52-62: LGTM on exit handler.

Properly cleans up the session from the map and notifies the renderer. Error handling is appropriate.


108-134: LGTM on list-sessions handler.

Good use of process.kill(pid, 0) to verify process liveness. Auto-cleanup of dead sessions is a nice touch.


155-167: LGTM on cleanup method.

Correctly iterates and kills only terminals associated with the specific webContents. Safe deletion during iteration since Map.prototype.entries() snapshot behavior handles this.


169-179: LGTM on killAll method.

Properly iterates all terminals, kills each, and clears the map. Error handling per-terminal ensures one failure doesn't prevent others from being cleaned up.

maxenceleblanc pushed a commit to maxenceleblanc/curly_cats2 that referenced this pull request Jul 20, 2026
* add: terminal

* added support for multiple terminal sessions and opening terminal from collection's working directory

* Use PowerShell as default shell on Windows

Replace cmd.exe with powershell.exe for terminal sessions on Windows.
Falls back to PWSH environment variable if set (for PowerShell Core).

* refactor(ui): improved session list by moving path display to hover for cleaner view

* chore: format

* refactor: improve terminal code quality and UI consistency

- Add terminal icon to 'Open in Terminal' dropdown item in CollectionItem
- Remove unused imports and functions (IconPlus, callIpc, canWriteToTerminal)
- Fix React key prop placement in SessionList component
- Replace deprecated substr with substring in terminal session ID generation
- Improve error handling for terminal cleanup on app quit
- Simplify terminal cleanup logic in window close handler

---------

Co-authored-by: naman-bruno <[email protected]>
Co-authored-by: Sid <[email protected]>
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.

4 participants