Skip to content

Feature/scratch requests - #7087

Merged
sid-bruno merged 22 commits into
usebruno:mainfrom
chirag-bruno:feature/scratch-requests
Feb 13, 2026
Merged

sid-bruno merged 22 commits into
usebruno:mainfrom
chirag-bruno:feature/scratch-requests

Conversation

@chirag-bruno

@chirag-bruno chirag-bruno commented Feb 9, 2026 •

Copy link
Copy Markdown
Collaborator

JIRA

Description

This PR refactors the scratch requests feature by unifying the tab system and leveraging existing transient request infrastructure. The main goal was to simplify the architecture by removing parallel systems and reusing existing components.

Key Changes

Architecture Simplification

  • Removed the separate WorkspaceTabs system and integrated workspace tabs (Overview, Environments) into the existing RequestTabs system
  • Scratch requests now use the existing CreateTransientRequest component instead of a custom CreateScratchRequest component
  • Workspace tabs are now stored as special tabs in a "scratch collection" - a temporary collection created per workspace

Scratch Collection Approach

  • Each workspace gets a scratch collection mounted in a temp directory (/tmp/bruno-scratch-*)
  • The scratch collection uses YAML format and is registered as a transient directory
  • Workspace tabs (workspaceOverview, workspaceEnvironments) are non-closable tabs tied to this scratch collection
  • Scratch requests are created as transient requests within this collection

SaveTransientRequest Enhancement

  • Added collection selector with breadcrumb navigation when saving from scratch collection
  • Users can now select any mounted collection in the workspace as the save target
  • Proper handling of unmounted collections - mounts them first, then enters
  • Format conversion from YAML (scratch) to BRU (target) handled automatically

Architecture Overview

+-------------------------------------------------------------+
|                        Workspace                            |
+-------------------------------------------------------------+
|  scratchCollectionUid --> Scratch Collection (temp dir)     |
|                            |-- opencollection.yml           |
|                            |-- metadata.json                |
|                            +-- [transient requests...]      |
+-------------------------------------------------------------+
|                      RequestTabs                            |
|  +-------------+---------------+------------------------+   |
|  |  Overview   |  Environments |    Request Tabs...     |   |
|  | (non-close) |  (non-close)  |      (closable)        |   |
|  +-------------+---------------+------------------------+   |
+-------------------------------------------------------------+
|                 SaveTransientRequest                        |
|  +--------------------------------------------------------+ |
|  | Collections > Selected Collection > Folder > ...       | |
|  | [Select target collection when saving from scratch]    | |
|  +--------------------------------------------------------+ |
+-------------------------------------------------------------+

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.
scratch-request.mov

Summary by CodeRabbit

  • New Features

    • Workspace Overview and Environments available as persistent tabs; scratch collections for temporary request drafting; improved save flow with collection picker and breadcrumbs.
  • UI Improvements

    • Consolidated workspace/collection actions into a unified collection header; integrated workspace navigation into the main tab bar; tab-count badges added.
  • Bug Fixes

    • Collection lists now correctly exclude scratch collections; improved stability for tab open/close behavior and save workflows.

Add support for temporary "scratch" requests at the workspace level that
are not tied to any collection. These requests are stored in a temp
directory and displayed as tabs in the workspace home.

Key changes:
- Add IPC handlers for mounting scratch directory and creating requests
- Add scratch directory watcher in collection-watcher.js
- Extend workspaces Redux slice with scratch state and reducers
- Add IPC listeners for scratch request events
- Create ScratchRequestPane and CreateScratchRequest components
- Update WorkspaceTabs with "+" button for creating scratch requests
- Update WorkspaceHome to render scratch request tabs
- Filter scratch collections from sidebar display

Supports all request types: HTTP, GraphQL, gRPC, and WebSocket.
- Use Button component with ghost variant and primary color
- Position button inside scrollable tab area
- Vertically center button with tabs
- Clean up unnecessary CSS properties
- Add centralized scratch path tracking in backend (scratchCollectionPaths Set)
- Register scratch paths when created via renderer:mount-workspace-scratch
- Set brunoConfig.type='scratch' based on registered paths instead of string pattern
- Store scratchTempDirectory path in workspace state for frontend validation
- Update schema to accept 'scratch' as valid collection type
- Simplify frontend filtering to use brunoConfig.type or path comparison
- Remove fragile 'bruno-scratch-' string pattern matching
- Prevent scratch collections from being added to workspace.collections
…e tabs

- Remove CreateScratchRequest component in favor of reusing CreateTransientRequest
- Register scratch collection temp directory via addTransientDirectory for transient request creation
- Add scratch collection item sync with workspace tabs
- Display HTTP method with color on scratch request tabs
Remove separate WorkspaceTabs system and integrate workspace views (Overview, Environments) into the unified RequestTabs architecture using scratch collections.

Key changes:
- Remove WorkspaceTabs component and Redux slice
- Add workspaceOverview and workspaceEnvironments as special tab types
- Create WorkspaceHeader component to display workspace name in toolbar
- Make workspace tabs non-closable and always present
- Update tab creation on workspace switch to automatically add Overview and Environments tabs
- Simplify WorkspaceHome component by removing redundant header
- Update all references from WorkspaceTabs to unified tab system

Benefits:
- Single tab system for all content (collections and workspace views)
- Consistent UX with unified navigation pattern
- Reduced code complexity (~1000+ lines removed)
- Easier maintenance and feature development
…equests

- Add updateCollectionMountStatus to properly set scratch collection mount status to 'mounted'
- Create new renderer:add-collection-watcher IPC handler for explicit watcher setup
- Move workspace tab type checks before collection validation in RequestTabPanel
- Update mountScratchCollection to use explicit watcher setup instead of open-multiple-collections

This ensures the task middleware recognizes scratch collections as fully mounted,
allowing transient requests to automatically open in tabs when created.
@coderabbitai

coderabbitai Bot commented Feb 9, 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

This PR removes the legacy workspace-tabs subsystem and replaces workspace-specific pages with tab-based workspaceOverview/workspaceEnvironments tabs; adds scratch-collection support (mounting, watchers, saving scratch requests) via new IPC handlers and Redux actions; introduces CollectionHeader and collection-picker UI for saving transient requests; and updates tests and teardown flow.

Changes

Cohort / File(s) Summary
Redux: workspace → tabs
packages/bruno-app/src/providers/ReduxStore/slices/workspaceTabs.js (deleted), packages/bruno-app/src/providers/ReduxStore/index.js, packages/bruno-app/src/providers/ReduxStore/slices/tabs.js, packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js, packages/bruno-app/src/providers/ReduxStore/slices/workspaces/index.js
Removed workspaceTabs slice and its exports; extended tabs to treat workspaceOverview/workspaceEnvironments as non-replaceable; added workspace scratch collection actions (get/mount/set) and wiring to create/focus overview/environment tabs.
IPC / Electron: scratch lifecycle
packages/bruno-electron/src/ipc/collection.js, packages/bruno-electron/src/app/collections.js
Added handlers: renderer:mount-workspace-scratch, renderer:add-collection-watcher, renderer:save-scratch-request; added registerScratchCollectionPath; findCollectionPathByItemPath now considers scratch metadata.
Save Transient Requests UI
packages/bruno-app/src/components/SaveTransientRequest/index.js, .../CollectionListItem/index.js, .../FolderBreadcrumbs/index.js, .../StyledWrapper.js
Major refactor: collection picker UI, collection list item and breadcrumbs, mount/select collection flow, target selection and save logic, and styles.
Collection header & toolbar replacement
packages/bruno-app/src/components/RequestTabs/CollectionHeader/index.js, .../CollectionHeader/StyledWrapper.js, packages/bruno-app/src/components/RequestTabs/CollectionToolBar/index.js (deleted), .../CollectionToolBar/StyledWrapper.js (deleted), packages/bruno-app/src/components/RequestTabs/index.js
Introduced CollectionHeader component (workspace/collection switcher, rename, actions); removed old CollectionToolBar and replaced usage in RequestTabs.
Request tabs / workspace overview rendering
packages/bruno-app/src/components/RequestTabs/RequestTab/SpecialTab.js, .../RequestTab/index.js, packages/bruno-app/src/components/RequestTabPanel/index.js
Added workspaceOverview/workspaceEnvironments tab variants and rendering; RequestTabPanel now can render WorkspaceOverview when focused tab type is workspaceOverview.
Sidebar & utilities
packages/bruno-app/src/components/Sidebar/Collections/index.js, .../Sections/CollectionsSection/index.js, packages/bruno-app/src/utils/collections/index.js, packages/bruno-app/src/hooks/useCollectionFolderTree/index.js
Added isScratchCollection util and updated collection filtering to exclude scratch collections; added effect to reset folder tree when collection changes.
App wiring: titlebar/status/hotkeys/pages
packages/bruno-app/src/components/AppTitleBar/index.js, packages/bruno-app/src/components/StatusBar/index.js, packages/bruno-app/src/providers/Hotkeys/index.js, packages/bruno-app/src/pages/Bruno/index.js, packages/bruno-app/src/providers/App/useIpcEvents.js
Switched flows to use focusTab / addTab and scratch-aware collectionUid fallbacks; removed showHomePage and workspaceTabs usage; simplified hotkey and IPC preference handling.
Workspace UI removals
packages/bruno-app/src/components/WorkspaceHome/index.js (deleted), .../StyledWrapper.js (deleted), components/WorkspaceTabs/... (deleted)
Removed legacy WorkspaceHome component and WorkspaceTabs components and styling (files deleted).
Tests & test harness
tests/scratch-requests/scratch-requests.spec.ts, playwright/index.ts
Added E2E tests for scratch requests and updated Playwright teardown to handle modal prompts during app close.
Misc UI styling
packages/bruno-app/src/components/Dropdown/StyledWrapper.js, packages/bruno-app/src/components/RequestTabs/CollectionHeader/StyledWrapper.js, others
Added small UI styling (dropdown tab-count) and new CollectionHeader styles.

Sequence Diagram(s)

sequenceDiagram
    participant UI as CollectionHeader (UI)
    participant Redux as Redux (workspaces/tabs/collections)
    participant IPC as Electron IPC
    participant FS as File System / Temp Dir
    rect rgba(120, 200, 240, 0.5)
    UI->>Redux: dispatch mountScratchCollection(workspaceUid)
    Redux->>IPC: invoke renderer:mount-workspace-scratch({workspaceUid, workspacePath})
    IPC->>FS: create temp directory, write opencollection.yml, register path
    FS-->>IPC: tempPath
    IPC-->>Redux: return tempPath
    Redux->>Redux: create scratch collection entry, setWorkspaceScratchCollection(uid, tempPath)
    Redux->>IPC: invoke renderer:add-collection-watcher({collectionPath, collectionUid})
    IPC-->>Redux: watcher registered
    Redux->>Redux: dispatch addTab({ type: 'workspaceOverview', uid: overviewUid, collectionUid: scratchUid })
    UI-->>Redux: focusTab(overviewUid)
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

Suggested reviewers

  • helloanoop
  • lohit-bruno
  • naman-bruno

Poem

✨ Tabs unify where workspaces roamed,

Scratch requests find a transient home,
New headers guide where toolbars stood,
IPC mounts temp paths like they should,
Redux sings — the UI hums along. 🚀

🚥 Pre-merge checks | ✅ 3 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Merge Conflict Detection ⚠️ Warning ❌ Merge conflicts detected (121 files):

⚔️ .github/workflows/flaky-test-detector.yml (content)
⚔️ package-lock.json (content)
⚔️ packages/bruno-app/package.json (content)
⚔️ packages/bruno-app/src/components/AppTitleBar/index.js (content)
⚔️ packages/bruno-app/src/components/CodeEditor/index.js (content)
⚔️ packages/bruno-app/src/components/ColorBadge/index.js (content)
⚔️ packages/bruno-app/src/components/ColorPicker/index.js (content)
⚔️ packages/bruno-app/src/components/ColorRange/StyledWrapper.js (content)
⚔️ packages/bruno-app/src/components/ColorRange/index.js (content)
⚔️ packages/bruno-app/src/components/Dropdown/StyledWrapper.js (content)
⚔️ packages/bruno-app/src/components/EditableTable/StyledWrapper.js (content)
⚔️ packages/bruno-app/src/components/EnvironmentVariablesTable/index.js (content)
⚔️ packages/bruno-app/src/components/Environments/Common/ImportEnvironmentModal/index.js (content)
⚔️ packages/bruno-app/src/components/Environments/ConfirmCloseEnvironment/index.js (content)
⚔️ packages/bruno-app/src/components/Environments/DotEnvFileEditor/index.js (content)
⚔️ packages/bruno-app/src/components/Environments/EnvironmentSelector/EnvironmentListContent/index.js (content)
⚔️ packages/bruno-app/src/components/Environments/EnvironmentSettings/EnvironmentList/EnvironmentDetails/index.js (content)
⚔️ packages/bruno-app/src/components/Environments/EnvironmentSettings/EnvironmentList/index.js (content)
⚔️ packages/bruno-app/src/components/ErrorCapture/index.js (content)
⚔️ packages/bruno-app/src/components/Help/index.js (content)
⚔️ packages/bruno-app/src/components/MultiLineEditor/index.js (content)
⚔️ packages/bruno-app/src/components/Preferences/General/index.js (content)
⚔️ packages/bruno-app/src/components/RequestPane/GrpcQueryUrl/index.js (content)
⚔️ packages/bruno-app/src/components/RequestPane/QueryEditor/index.js (content)
⚔️ packages/bruno-app/src/components/RequestPane/Settings/Tags/index.js (content)
⚔️ packages/bruno-app/src/components/RequestTabPanel/index.js (content)
⚔️ packages/bruno-app/src/components/RequestTabs/RequestTab/SpecialTab.js (content)
⚔️ packages/bruno-app/src/components/RequestTabs/RequestTab/index.js (content)
⚔️ packages/bruno-app/src/components/RequestTabs/index.js (content)
⚔️ packages/bruno-app/src/components/SaveTransientRequest/StyledWrapper.js (content)
⚔️ packages/bruno-app/src/components/SaveTransientRequest/index.js (content)
⚔️ packages/bruno-app/src/components/Sidebar/Collections/index.js (content)
⚔️ packages/bruno-app/src/components/Sidebar/ImportCollection/index.js (content)
⚔️ packages/bruno-app/src/components/Sidebar/ImportCollectionLocation/index.js (content)
⚔️ packages/bruno-app/src/components/Sidebar/Sections/CollectionsSection/index.js (content)
⚔️ packages/bruno-app/src/components/SingleLineEditor/index.js (content)
⚔️ packages/bruno-app/src/components/StatusBar/index.js (content)
⚔️ packages/bruno-app/src/components/TagList/index.js (content)
⚔️ packages/bruno-app/src/components/WorkspaceHome/WorkspaceEnvironments/EnvironmentList/EnvironmentDetails/index.js (content)
⚔️ packages/bruno-app/src/components/WorkspaceHome/WorkspaceEnvironments/EnvironmentList/index.js (content)
⚔️ packages/bruno-app/src/components/WorkspaceHome/WorkspaceOverview/CollectionsList/index.js (content)
⚔️ packages/bruno-app/src/components/WorkspaceHome/WorkspaceOverview/index.js (content)
⚔️ packages/bruno-app/src/hooks/useCollectionFolderTree/index.js (content)
⚔️ packages/bruno-app/src/hooks/useProtoFileManagement/index.js (content)
⚔️ packages/bruno-app/src/hooks/useReflectionManagement/index.js (content)
⚔️ packages/bruno-app/src/pages/Bruno/index.js (content)
⚔️ packages/bruno-app/src/providers/App/ConfirmAppClose/SaveRequestsModal.js (content)
⚔️ packages/bruno-app/src/providers/App/useIpcEvents.js (content)
⚔️ packages/bruno-app/src/providers/Hotkeys/index.js (content)
⚔️ packages/bruno-app/src/providers/ReduxStore/index.js (content)
⚔️ packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js (content)
⚔️ packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js (content)
⚔️ packages/bruno-app/src/providers/ReduxStore/slices/global-environments.js (content)
⚔️ packages/bruno-app/src/providers/ReduxStore/slices/tabs.js (content)
⚔️ packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js (content)
⚔️ packages/bruno-app/src/providers/ReduxStore/slices/workspaces/index.js (content)
⚔️ packages/bruno-app/src/themes/light/light-pastel.js (content)
⚔️ packages/bruno-app/src/utils/codemirror/autocomplete.js (content)
⚔️ packages/bruno-app/src/utils/collections/index.js (content)
⚔️ packages/bruno-app/src/utils/curl/content-type.js (content)
⚔️ packages/bruno-app/src/utils/curl/index.js (content)
⚔️ packages/bruno-app/src/utils/environments.js (content)
⚔️ packages/bruno-app/src/utils/exporters/bruno-environment.js (content)
⚔️ packages/bruno-app/src/utils/importers/bruno-environment.js (content)
⚔️ packages/bruno-cli/src/runner/interpolate-vars.js (content)
⚔️ packages/bruno-cli/src/runner/prepare-request.js (content)
⚔️ packages/bruno-cli/src/runner/run-single-request.js (content)
⚔️ packages/bruno-cli/tests/runner/prepare-request.spec.js (content)
⚔️ packages/bruno-converters/src/openapi/openapi-to-bruno.js (content)
⚔️ packages/bruno-converters/src/opencollection/environment.ts (content)
⚔️ packages/bruno-converters/src/postman/bruno-to-postman.js (content)
⚔️ packages/bruno-converters/src/postman/postman-to-bruno.js (content)
⚔️ packages/bruno-converters/src/postman/postman-translations.js (content)
⚔️ packages/bruno-converters/src/utils/bruno-to-postman-translator.js (content)
⚔️ packages/bruno-converters/src/utils/postman-to-bruno-translator.js (content)
⚔️ packages/bruno-converters/tests/bruno/bruno-to-postman-translations/request.test.js (content)
⚔️ packages/bruno-converters/tests/bruno/bruno-to-postman-translations/variables.test.js (content)
⚔️ packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-body.spec.js (content)
⚔️ packages/bruno-converters/tests/postman/bruno-to-postman.spec.js (content)
⚔️ packages/bruno-converters/tests/postman/postman-to-bruno/postman-to-bruno.spec.js (content)
⚔️ packages/bruno-converters/tests/postman/postman-translations/postman-comments.spec.js (content)
⚔️ packages/bruno-converters/tests/postman/postman-translations/postman-cookie-conversions.spec.js (content)
⚔️ packages/bruno-converters/tests/postman/postman-translations/postman-edge-cases.spec.js (content)
⚔️ packages/bruno-converters/tests/postman/postman-translations/postman-variables.spec.js (content)
⚔️ packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/combined.test.js (content)
⚔️ packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/legacy-global-apis.test.js (content)
⚔️ packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/multiline-syntax.test.js (content)
⚔️ packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/request.test.js (content)
⚔️ packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/response.test.js (content)
⚔️ packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/testing-framework.test.js (content)
⚔️ packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/variables.test.js (content)
⚔️ packages/bruno-electron/package.json (content)
⚔️ packages/bruno-electron/src/app/collections.js (content)
⚔️ packages/bruno-electron/src/ipc/collection.js (content)
⚔️ packages/bruno-electron/src/ipc/global-environments.js (content)
⚔️ packages/bruno-electron/src/ipc/network/cert-utils.js (content)
⚔️ packages/bruno-electron/src/ipc/network/index.js (content)
⚔️ packages/bruno-electron/src/ipc/network/interpolate-vars.js (content)
⚔️ packages/bruno-electron/src/ipc/workspace.js (content)
⚔️ packages/bruno-electron/src/store/global-environments.js (content)
⚔️ packages/bruno-electron/src/store/workspace-environments.js (content)
⚔️ packages/bruno-electron/tests/network/prepare-request.spec.js (content)
⚔️ packages/bruno-filestore/src/formats/yml/items/stringifyHttpRequest.ts (content)
⚔️ packages/bruno-js/src/bru.js (content)
⚔️ packages/bruno-js/src/bruno-request.js (content)
⚔️ packages/bruno-js/src/sandbox/node-vm/index.js (content)
⚔️ packages/bruno-js/src/sandbox/node-vm/index.spec.js (content)
⚔️ packages/bruno-js/src/sandbox/quickjs/shims/bru.js (content)
⚔️ packages/bruno-js/src/sandbox/quickjs/shims/bruno-request.js (content)
⚔️ packages/bruno-js/src/sandbox/quickjs/shims/lib/axios.js (content)
⚔️ packages/bruno-js/src/utils.js (content)
⚔️ packages/bruno-js/tests/utils.spec.js (content)
⚔️ packages/bruno-requests/rollup.config.js (content)
⚔️ packages/bruno-requests/src/cookies/index.spec.ts (content)
⚔️ packages/bruno-requests/src/cookies/index.ts (content)
⚔️ packages/bruno-requests/src/utils/http-https-agents.ts (content)
⚔️ packages/bruno-schema/src/collections/index.js (content)
⚔️ packages/bruno-tests/collection/bruno.json (content)
⚔️ packages/bruno-tests/collection/package-lock.json (content)
⚔️ packages/bruno-tests/collection/package.json (content)
⚔️ playwright/index.ts (content)

These conflicts must be resolved before merging into main.
Resolve conflicts locally and push changes to this branch.
✅ 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 'Feature/scratch requests' directly relates to the main architectural refactor in the changeset, which introduces scratch request support with unified workspace tabs and transient request infrastructure.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing touches
🧪 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.

…requests

Add multi-step save flow for scratch collection requests with collection selection before folder selection. Includes breadcrumb navigation showing "Collections > [Selected Collection] > [Folders...]" that allows users to navigate back to collection selector.

Refactor scratch collection detection to use workspace.scratchCollectionUid instead of persisting type to brunoConfig, providing cleaner separation of concerns without disk persistence.

Add backend support for automatic format conversion when saving from YAML scratch collections to BRU collections.
- Create dedicated openScratchCollectionEvent function for scratch collections
- Revert openCollectionEvent to clean state without scratch-specific logic
- Simplify closeTabs and closeAllCollectionTabs reducers in tabs slice
- Remove unused isScratchCollectionPath helper function
@chirag-bruno
chirag-bruno marked this pull request as ready for review February 10, 2026 06:30

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

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/RequestTabs/RequestTab/index.js (1)

175-179: ⚠️ Potential issue | 🟠 Major

Workspace tabs can be closed via middle-click despite being "non-closable".

The StyledWrapper at line 179 has onMouseUp={handleMouseUp}, which dispatches closeTabs on middle-click (button === 1). Since workspace tabs (workspaceOverview, workspaceEnvironments) are intended to be non-closable, middle-click should be suppressed for these tab types.

Proposed fix
       <StyledWrapper
         className={`flex items-center justify-between tab-container px-2 ${tab.preview ? 'italic' : ''}`}
-        onMouseUp={handleMouseUp}
+        onMouseUp={['workspaceOverview', 'workspaceEnvironments'].includes(tab.type) ? undefined : handleMouseUp}
       >
🤖 Fix all issues with AI agents
In `@packages/bruno-app/src/components/RequestTabPanel/index.js`:
- Around line 56-57: The new useSelector call (useSelector retrieving workspaces
and activeWorkspaceUid, and the derived activeWorkspace) is placed after an
early return guarded by typeof window == 'undefined', violating the Rules of
Hooks; move all hook calls for this component (including useSelector and any
other hooks used in RequestTabPanel) above the early-return conditional so hooks
run unconditionally, and refactor the SSR guard (the typeof window ==
'undefined' check) to use a precomputed variable or conditional rendering after
hooks (e.g., compute isServer before hooks or return null from render logic that
runs after hooks) to preserve SSR safety while keeping hooks at the top of the
component.

In `@packages/bruno-app/src/components/RequestTabs/WorkspaceHeader/index.js`:
- Around line 86-94: The validation in validateWorkspaceName checks name.length
before trimming, so inputs like 256 spaces are rejected for length instead of
being treated as empty; update validateWorkspaceName to operate on the trimmed
value (e.g., compute const trimmed = name?.trim() and use trimmed for the empty
and length checks) or reorder checks to trim first, then validate trimmed === ''
and trimmed.length > 255, returning the same error messages from the function.

In `@packages/bruno-app/src/components/SaveTransientRequest/index.js`:
- Around line 40-47: The fallback object in availableCollections uses uid: null
which leads handleSelectCollection (via selectedCollection.uid || uuid()) to
generate transient random UUIDs and can cause duplicate Redux entries when the
file-watcher later assigns a real UID; instead assign a stable deterministic UID
when building availableCollections (e.g., derive a hash or canonical string from
wc.path or wc.pathname) or cache/pre-assign a UID there so mountCollection
receives that same stable identifier; update availableCollections creation to
set uid to that deterministic value and ensure
handleSelectCollection/mountCollection use the provided uid rather than
generating a new uuid().

In `@packages/bruno-app/src/providers/App/useIpcEvents.js`:
- Around line 274-291: The addTab call in removeShowPreferencesListener
currently uses the explicit assignment "collectionUid: collectionUid"; change it
to ES6 shorthand by passing just "collectionUid" in the addTab payload (keep the
uid logic the same), so update the object passed to addTab inside
removeShowPreferencesListener to use the shorthand form for the collectionUid
property while leaving the rest unchanged.

In `@packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js`:
- Around line 2442-2474: The thunk openScratchCollectionEvent currently calls
ipcRenderer.invoke('renderer:get-collection-security-config', pathname) without
handling rejections so the outer Promise can hang; update
openScratchCollectionEvent to attach a .catch handler (or use async/await with
try/catch) to the ipcRenderer.invoke call and call reject(error) when it fails,
and ensure any errors from collectionSchema.validate or
dispatch(_createCollection(...)) still propagate to reject; also add a JSDoc
block above openScratchCollectionEvent describing parameters (uid, pathname,
brunoConfig), return value (Promise) and behavior.

In `@packages/bruno-app/src/providers/ReduxStore/slices/tabs.js`:
- Around line 208-210: When closing all tabs for a collection (handling
action.payload.collectionUid) the reducer currently resets state.activeTabUid
unconditionally; instead, capture the previous activeTabUid (state.activeTabUid)
before filtering state.tabs, then filter tabs as done now, and only reassign
state.activeTabUid if the previous active tab was removed (i.e., no tab in the
new state.tabs has uid === prevActive); otherwise keep prevActive; if prevActive
was removed set state.activeTabUid = state.tabs.length > 0 ?
last(state.tabs).uid : null.

In `@packages/bruno-electron/src/ipc/collection.js`:
- Around line 1921-1957: The save-scratch-request handler doesn't update the
example UID cache; after successfully writing the new scratch file (after
writeFile(targetPathname, content)) call syncExampleUidsCache for the affected
collection (e.g., syncExampleUidsCache(collectionPath)) so the example UID
mappings stay in sync; ensure you import/require syncExampleUidsCache if needed
and only call it on successful save before returning { newPathname:
targetPathname }.
- Around line 393-429: In the ipcMain handler for
'renderer:save-transient-request' ensure the chosen filename's extension matches
the targetFormat when targetFilename is omitted (and optionally enforce when
provided): use path.parse(sourcePathname) to get base name, map targetFormat ->
desired extension (e.g., 'bru' -> '.bru', 'yml' -> '.yml'), then set filename =
`${name}${desiredExt}` instead of using path.basename(sourcePathname) directly;
update references to filename/targetPathname so converted files get the correct
extension and watchers will pick them up (symbols: targetFilename, filename,
targetFormat, actualSourceFormat, targetPathname in the handler).
🧹 Nitpick comments (10)
packages/bruno-app/src/components/StatusBar/index.js (1)

42-48: Trailing comma on Line 46 violates coding guidelines.

Proposed fix
     dispatch(
       addTab({
         type: 'preferences',
         uid: collectionUid ? `${collectionUid}-preferences` : 'preferences',
-        collectionUid: collectionUid
+        collectionUid
       })
     );

Also used shorthand property since key and value share the same name.

As per coding guidelines: "No trailing commas in code".

packages/bruno-app/src/hooks/useCollectionFolderTree/index.js (1)

66-70: Consider resetting via a key prop instead of useEffect.

This useEffect duplicates the logic in the existing reset callback (lines 147-150). More importantly, resetting state in response to a prop change is a well-known case where React's key-based remounting is the idiomatic, effect-free alternative — the parent simply renders <Component key={collectionUid} ... /> and the hook's useState initializers handle the rest.

If the key approach isn't feasible here, at minimum deduplicate by calling reset() inside the effect rather than repeating the two setter calls.

Based on learnings: "Avoid useEffect unless absolutely needed. Prefer derived state and event handlers (MUST)."

Option A – eliminate the effect entirely (preferred)

Remove the useEffect from this hook and have the consumer add a key:

// In the consuming component:
<CollectionFolderTree key={collectionUid} collectionUid={collectionUid} />
-import { useState, useMemo, useCallback, useEffect } from 'react';
+import { useState, useMemo, useCallback } from 'react';
-
-  useEffect(() => {
-    setCurrentFolderPath([]);
-    setSelectedFolderUid(null);
-  }, [collectionUid]);
-
Option B – at least deduplicate with `reset`
   useEffect(() => {
-    setCurrentFolderPath([]);
-    setSelectedFolderUid(null);
+    reset();
-  }, [collectionUid]);
+  }, [collectionUid, reset]);
packages/bruno-app/src/components/Sidebar/Collections/index.js (1)

19-29: Duplicated scratch-collection filtering logic across files.

This filter (lines 22-26) is identical to the one in CollectionsSection/index.js (lines 51-55). Consider extracting a shared utility like isNonScratchCollection(collection, workspaces) to keep the logic DRY. Not blocking, but worth noting for maintainability.

packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js (1)

859-943: Defer workspace scratch state updates until the mount succeeds.
This avoids leaving scratchCollectionUid/scratchTempDirectory in Redux if any mount step fails.

♻️ Suggested refactor
-      dispatch(setWorkspaceScratchCollection({
-        workspaceUid,
-        scratchCollectionUid,
-        scratchTempDirectory: tempDirectoryPath
-      }));
@@
-      await dispatch(openScratchCollectionEvent(scratchCollectionUid, tempDirectoryPath, brunoConfig));
+      await dispatch(openScratchCollectionEvent(scratchCollectionUid, tempDirectoryPath, brunoConfig));
+      dispatch(setWorkspaceScratchCollection({
+        workspaceUid,
+        scratchCollectionUid,
+        scratchTempDirectory: tempDirectoryPath
+      }));
packages/bruno-app/src/components/RequestTabs/index.js (1)

51-52: Consider memoizing the scratch-collection derivation.

isScratchCollection and activeWorkspace are recomputed on every render with two separate array traversals. This is fine for a small workspace list, but since workspaces selector returns the full array (any workspace mutation triggers re-render), you could wrap these in a useMemo keyed on [workspaces, activeCollection] to avoid redundant work as the feature scales.

♻️ Optional memoization
- const isScratchCollection = activeCollection && workspaces.some((w) => w.scratchCollectionUid === activeCollection.uid);
- const activeWorkspace = isScratchCollection ? workspaces.find((w) => w.scratchCollectionUid === activeCollection.uid) : null;
+ const { isScratchCollection, activeWorkspace } = useMemo(() => {
+   const ws = activeCollection ? workspaces.find((w) => w.scratchCollectionUid === activeCollection.uid) : null;
+   return { isScratchCollection: !!ws, activeWorkspace: ws };
+ }, [workspaces, activeCollection]);

This also removes the double traversal by doing a single find.

packages/bruno-app/src/components/SaveTransientRequest/CollectionListItem/index.js (1)

36-38: Use theme color instead of Tailwind text-green-600.

Per project conventions, Tailwind classes are for layout only — colors should come from the styled-component theme. The parent StyledWrapper or an inline style using the theme should provide the green color.

Based on learnings: "Tailwind classes are used specifically for layout-based styles, not colors" and "Use styled component's theme prop to manage CSS colors."

packages/bruno-app/src/components/RequestTabs/WorkspaceHeader/index.js (1)

25-38: Missing handleCancelWorkspaceRename in the effect's dependency array.

The handleClickOutside closure captures handleCancelWorkspaceRename, but it's not listed in the [isRenamingWorkspace] dependency array. This works today because the function only calls stable state setters, but a linter would flag this. Either add it to deps (and wrap it in useCallback), or extract the reset logic inline.

packages/bruno-app/src/components/SaveTransientRequest/index.js (3)

76-82: Effect dependency is incomplete — selectedTargetCollection fields aren't deeply tracked.

The effect depends on [selectedTargetCollectionPath, selectedTargetCollection], but selectedTargetCollection is derived from availableCollections which is a new object reference on each memo recomputation. This means the effect runs more often than necessary, though it's functionally harmless since the body is gated by selectedTargetCollectionPath && isFullyLoaded.

Also, per project conventions, consider whether this can be handled as a derived-state check inside handleSelectCollection + the CollectionListItem's own state, rather than a separate effect.

Based on learnings: "Avoid useEffect unless absolutely needed. Prefer derived state and event handlers."


111-115: resetForm is not in the effect dependency array.

resetForm captures isScratchCollection and item.name via closure but isn't listed as a dependency. If isScratchCollection changes while the modal is open, resetForm would use a stale value. This is unlikely to cause a user-visible bug since the modal is typically opened fresh, but it will trigger a linter warning.

♻️ Quick fix: wrap resetForm in useCallback and add to deps
- const resetForm = () => {
+ const resetForm = useCallback(() => {
    setRequestName(item.name || '');
    setSearchText('');
    reset();
    setShowNewFolderInput(false);
    setNewFolderName('');
    setNewFolderDirectoryName('');
    setShowFilesystemName(false);
    setIsEditingFolderFilename(false);
    setPendingFolderNavigation(null);
    setSelectedTargetCollectionPath(null);
    setIsSelectingCollection(isScratchCollection);
- };
+ }, [item?.name, isScratchCollection, reset]);

  useEffect(() => {
    if (isOpen && item) {
      resetForm();
    }
- }, [isOpen, item]);
+ }, [isOpen, item, resetForm]);

337-385: Breadcrumb rendering is duplicated between scratch and non-scratch paths.

The breadcrumb JSX (chevrons + clickable names + root navigation) at lines 353-382 is nearly identical to lines 414-441. Extract a shared BreadcrumbNav component or helper to reduce duplication.

Also applies to: 413-442

- Add tests for creating scratch requests (HTTP, GraphQL, gRPC, WebSocket)
- Add tests for sending scratch requests and verifying response
- Add tests for saving scratch requests to a collection
- Add tests for multiple tabs and closing tabs
- Handle "Don't Save" modal in playwright fixture during app close

@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

🤖 Fix all issues with AI agents
In `@playwright/index.ts`:
- Around line 123-131: The code uses dontSaveButton.isVisible({ timeout: 1000 })
but Playwright ignores the timeout option; replace that check with an explicit
wait on the locator (e.g., use dontSaveButton.waitFor({ state: 'visible',
timeout: 1000 }) or page.waitForSelector with the same selector) and handle the
timeout with .catch(() => false) before clicking; update the handleModal
function to await the locator.waitFor call and only click if it resolved to
visible to ensure the modal is reliably detected and clicked.

In `@tests/scratch-requests/scratch-requests.spec.ts`:
- Around line 168-171: The test step uses a macOS-only shortcut ('Meta+s') and
an unnecessary wait; update the step that calls page.keyboard.press inside the
'Trigger save action using keyboard shortcut' test.step to use a platform-aware
key (prefer 'Control+s' or conditionally choose 'Meta+s' on darwin via
process.platform) so the shortcut works on Linux/Windows CI, and remove the
extra await page.waitForTimeout(500) since the following step already waits for
the modal (5s). Locate the test.step block and modify the page.keyboard.press
call and delete the redundant waitForTimeout.
- Around line 250-259: The "Verify tab is closed" test step currently contains
no assertion; locate the test step named 'Verify tab is closed' and replace the
empty if block that checks isVisible (from activeTab =
page.locator('.request-tab.active') and isVisible = await activeTab.isVisible())
with a concrete assertion that the closed tab is no longer present — e.g.,
assert isVisible is false or assert the active tab count does not include the
closed tab id; ensure you use the existing activeTab locator
('.request-tab.active') or the closed tab identifier used earlier in the test to
make the assertion.
🧹 Nitpick comments (5)
tests/scratch-requests/scratch-requests.spec.ts (5)

39-42: Avoid page.waitForTimeout(300) — prefer a meaningful wait condition.

After asserting the active tab contains "Untitled" (line 41), the 300ms sleep is unnecessary. If there's a specific UI transition to wait for, use an expect or waitFor on that element instead. As per coding guidelines: "Try to reduce usage of page.waitForTimeout(); in code unless absolutely necessary and the locator cannot be found using existing expect() playwright calls."

Suggested fix
       // Wait for the request tab to be active
       await page.locator('.request-tab.active').waitFor({ state: 'visible' });
       await expect(page.locator('.request-tab.active')).toContainText('Untitled');
-      await page.waitForTimeout(300);
     });

49-56: Same waitForTimeout concern in goToWorkspaceOverview.

Replace page.waitForTimeout(300) with a condition that confirms the workspace overview is actually visible (e.g., waiting for a workspace-specific element). As per coding guidelines, reduce usage of page.waitForTimeout().

Suggested fix
   const goToWorkspaceOverview = async (page: Page) => {
     await test.step('Navigate to workspace overview', async () => {
       const homeButton = page.locator('.titlebar-left .home-button');
       await homeButton.click();
-      await page.waitForTimeout(300);
+      // Wait for workspace overview to be visible
+      await page.locator('.workspace-title').waitFor({ state: 'visible' });
     });
   };

6-9: locators is built but barely used — prefer consistent locator usage.

buildCommonLocators is initialized in beforeAll but used only twice (lines 200, 203). Throughout the file, raw page.locator('.request-tab.active') appears repeatedly when locators.tabs.activeRequestTab() already exists. Same for locators.tabs.closeTab(...), locators.response.*, etc. Pick one pattern and stick with it. As per coding guidelines: "Use locator variables for locators."

Also applies to: 69-71


223-230: Weak assertion for "multiple tabs" — doesn't verify two distinct scratch tabs.

toBeGreaterThanOrEqual(2) is fragile in a serial suite where prior tests may leave tabs. The comment says "different numbers" but there's no assertion on that. Consider filtering to scratch-specific tabs and asserting an exact count or verifying both tab labels.


58-79: Creation tests across all four request types are solid but repetitive.

The four creation tests (HTTP, GraphQL, gRPC, WebSocket) follow the same pattern. They work fine, but consider whether a parameterized approach (e.g., a loop or test.describe with a data array) would reduce duplication without sacrificing readability. Not blocking — just a thought for maintainability.

Also applies to: 81-96, 98-113, 115-130

Comment thread playwright/index.ts Resolved
- Fix RequestTabPanel hooks violation by moving SSR guard after hooks
- Fix validateWorkspaceName to trim before length check
- Use stable deterministic UID in SaveTransientRequest
- Use ES6 shorthand for collectionUid in useIpcEvents
- Add JSDoc and error handling to openScratchCollectionEvent
- Fix closeAllCollectionTabs to preserve activeTabUid when not removed
- Add syncExampleUidsCache call to save-scratch-request handler
- Use getCollectionFormat for save-transient-request extension handling
- Fix Playwright modal handling with proper waitFor pattern
- Make keyboard shortcut platform-aware in scratch tests
- Remove flaky close tab test, handled by fixture cleanup
- Extract isScratchCollection utility to reduce duplication
- Memoize scratch collection derivation in RequestTabs
- Use theme color instead of Tailwind class for success icon
- Wrap resetForm and handleCancelWorkspaceRename in useCallback
- Extract FolderBreadcrumbs into separate component
- Call reset() inside useEffect in useCollectionFolderTree hook
- Defer workspace scratch state updates until mount succeeds

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

🤖 Fix all issues with AI agents
In `@packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js`:
- Around line 934-940: The catch block can read stale `workspace` captured
earlier, so change the cleanup to read the current workspace from the Redux
state (via getState()) instead of using the local `workspace` variable;
specifically, in the catch of the async action that calls
setWorkspaceScratchCollection, addTransientDirectory, and
updateCollectionMountStatus, call getState() to obtain the latest workspace and
then use its scratchCollectionUid when dispatching updateCollectionMountStatus
(and any other cleanup) so orphaned scratch state is cleared even if errors
occur after setWorkspaceScratchCollection.

In `@packages/bruno-electron/src/ipc/collection.js`:
- Around line 1959-1961: The call to syncExampleUidsCache is passing
collectionPath (the collection root) instead of the saved request's filepath,
causing UID mappings to point to the wrong location; update the call in the
handler that currently uses collectionPath to pass targetPathname (the file path
of the saved request) as the first argument so
syncExampleUidsCache(collectionPath, request.examples) becomes
syncExampleUidsCache(targetPathname, request.examples), leaving the examples
argument unchanged and ensuring UID mapping matches the saved request file.
- Around line 429-433: syncExampleUidsCache is being called with sourcePathname
(transient path) instead of the actual save destination, so update the two calls
that pass sourcePathname to instead pass targetPathname (the variable used when
saving the file). Specifically, in the branch that sets finalContent =
stringifyRequest(mergedRequest, { format: targetFormat }) and the branch that
awaits stringifyRequestViaWorker(request, { format: targetFormat }), replace
syncExampleUidsCache(sourcePathname, ...) with
syncExampleUidsCache(targetPathname, ...) so the UID cache tracks the permanent
file location.
- Around line 424-425: Remove the redundant inner require that re-declares
parseRequest and stringifyRequest inside the needsConversion branch; instead
reference the top-level imports parseRequest and stringifyRequest already
declared at file scope so you don't shadow them—delete the inner "const {
parseRequest, stringifyRequest } = require('@usebruno/filestore')" and use
parseRequest/stringifyRequest directly within the needsConversion block.
🧹 Nitpick comments (9)
packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js (4)

864-873: Consider using a selector instead of a thunk for pure state reads.

getScratchCollection only reads state and returns a value — it never dispatches. A memoized selector (e.g., via reselect) would be more idiomatic and avoids the overhead of dispatching a thunk for a synchronous read.

That said, this pattern exists elsewhere in the file, so it's consistent with the current codebase style.


887-894: Inconsistent return shapes.

The early-return path (line 892) returns the full Redux collection object, while the fresh-mount path (line 933) returns { uid, pathname }. The caller only uses .uid today, so it works — but this inconsistency will bite if a future caller expects a uniform shape.

Consider returning the same minimal shape from the early-return path:

Proposed fix
       if (existingCollection) {
-        return existingCollection;
+        return { uid: existingCollection.uid, pathname: existingCollection.pathname };
       }

Also applies to: 933-933


897-900: Magic string 'default' as fallback workspace path.

Line 899 falls back to 'default' when workspace.pathname is falsy. If this is a well-known sentinel for the default workspace, consider extracting it as a named constant to make the intent clear and avoid duplication if used elsewhere.


902-903: Dynamic import of generateUidBasedOnHash could be a static import.

This module is loaded on every workspace switch. Since the bundler caches the module after the first load the runtime cost is negligible, but a static import at the top of the file would be simpler and make the dependency explicit.

packages/bruno-app/src/components/RequestTabPanel/index.js (1)

189-195: workspaceEnvironments renders the same component as global-environment-settings.

Both focusedTab.type === 'global-environment-settings' (line 181) and focusedTab.type === 'workspaceEnvironments' (line 193) render <GlobalEnvironmentSettings />. If these are intentionally the same view accessed via different tab types, consider extracting a shared set or adding a brief comment explaining why two distinct tab types map to the same component — helps future maintainers.

packages/bruno-app/src/components/RequestTabs/index.js (1)

51-54: Inline scratch-collection check duplicates the shared isScratchCollection utility logic.

The isScratchCollection utility from utils/collections checks workspaces.some((w) => w.scratchCollectionUid === collection.uid) — same concept as the find here. The difference is you also need the workspace object itself. Consider using the utility for the boolean and a separate find for the workspace, or extending the utility to return the matched workspace.

packages/bruno-app/src/components/SaveTransientRequest/index.js (1)

69-85: selectedTargetCollection is re-derived every render without memoization, used in useEffect deps.

Lines 75-77 compute selectedTargetCollection via a find on every render. While availableCollections is memoized, the returned object reference can change when allCollections updates (which is the desired behavior for detecting mount status changes). This is functionally correct, but wrapping it in a useMemo would make the intent clearer and prevent the effect at lines 79-85 from firing on unrelated re-renders.

♻️ Optional: memoize selectedTargetCollection
- const selectedTargetCollection = selectedTargetCollectionPath
-   ? availableCollections.find((c) => (c.path || c.pathname) === selectedTargetCollectionPath)
-   : null;
+ const selectedTargetCollection = useMemo(() => {
+   return selectedTargetCollectionPath
+     ? availableCollections.find((c) => (c.path || c.pathname) === selectedTargetCollectionPath)
+     : null;
+ }, [selectedTargetCollectionPath, availableCollections]);
packages/bruno-electron/src/ipc/collection.js (2)

1906-1926: Consider extracting the async-load threshold logic into a shared helper.

Lines 1912–1917 duplicate the same shouldLoadCollectionAsync computation from renderer:mount-collection (lines 1856–1863). A small helper like shouldLoadAsync(stats) would eliminate the copy-paste.

Example helper extraction
+const shouldLoadAsync = ({ size, filesCount, maxFileSize }) =>
+  (size > MAX_COLLECTION_SIZE_IN_MB)
+    || (filesCount > MAX_COLLECTION_FILES_COUNT)
+    || (maxFileSize > MAX_SINGLE_FILE_SIZE_IN_COLLECTION_IN_MB);

Then replace both occurrences with shouldLoadAsync(await getCollectionStats(collectionPath)).


1928-1968: Handler largely duplicates save-transient-request — consider consolidating.

The validation, filename normalization, and write logic in save-scratch-request (lines 1928–1968) closely mirrors save-transient-request (lines 393–441), minus the format conversion. If scratch requests always use the target collection's format directly, the two handlers could share a common utility to reduce duplication.

- Create CollectionHeader component that replaces WorkspaceHeader and CollectionToolBar
- Add dropdown to switch between workspace and mounted collections
- Display tab count badge next to collection/workspace name in header and dropdown
- Remove unused WorkspaceHeader and CollectionToolBar components
- Handle null/undefined values elegantly throughout

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@packages/bruno-app/src/components/Dropdown/StyledWrapper.js`:
- Around line 88-97: The badge (.dropdown-tab-count) currently uses the same
theme token (props.theme.dropdown.hoverBg) as the dropdown item hover
(.dropdown-item:hover) which makes the badge blend in on hover; update the
styling for .dropdown-tab-count to use a distinct token or adjusted value (e.g.,
props.theme.dropdown.badgeBg or a darken/lighten variant of hoverBg) and/or add
a subtle outline (e.g., 1px solid props.theme.dropdown.badgeBorder or a soft
box-shadow) so the badge remains visually distinct when .dropdown-item:hover is
active.

In `@packages/bruno-app/src/components/RequestTabs/CollectionHeader/index.js`:
- Around line 225-246: The workspace name is being validated trimmed but saved
untrimmed; in handleSaveWorkspaceRename you should trim workspaceNameInput
before dispatching renameWorkspaceAction and before clearing/resetting state:
compute a const trimmed = workspaceNameInput.trim(), use trimmed when calling
dispatch(renameWorkspaceAction(...)) and when setting success messages or
resetting setWorkspaceNameInput(''), and also use trimmed for setting/clearing
setWorkspaceNameError if needed so stored workspace names never include
surrounding whitespace; keep validateWorkspaceName as-is but ensure rename uses
the trimmed value.
🧹 Nitpick comments (3)
packages/bruno-app/src/components/RequestTabs/index.js (1)

50-52: Consider reusing the isScratchCollection utility from utils/collections/index.js.

There's already an exported utility that does exactly this check. Using it here avoids duplicating the logic and keeps the source of truth in one place.

♻️ Suggested refactor
+import { isScratchCollection as checkIsScratchCollection } from 'utils/collections';

-  const isScratchCollection = useMemo(() => {
-    return activeCollection ? workspaces.some((w) => w.scratchCollectionUid === activeCollection.uid) : false;
-  }, [workspaces, activeCollection]);
+  const isScratchCollection = useMemo(() => {
+    return checkIsScratchCollection(activeCollection, workspaces);
+  }, [workspaces, activeCollection]);
packages/bruno-app/src/components/RequestTabs/CollectionHeader/index.js (2)

82-90: mountedCollections filter re-runs on every render.

This filter iterates all collections and workspaces on each render. It's fine for small datasets, but given the learning to "memoize only when necessary," just flagging for awareness — if workspace/collection counts grow, wrapping this in useMemo with [collections, workspaces, currentWorkspace] deps would be straightforward.


32-449: Large component — consider extracting workspace-specific logic.

This component handles two distinct concerns: workspace header (rename, export, close, show in folder) and collection header (runner, variables, settings, environment). Extracting the workspace rename flow and workspace actions into a custom hook or sub-component would improve readability and testability. Not urgent, but worth considering as this feature matures.

@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

🤖 Fix all issues with AI agents
In `@packages/bruno-app/src/components/RequestTabs/CollectionHeader/index.js`:
- Around line 118-134: The tabs.find check in handleSwitchToCollection currently
matches any tab with the same collectionUid and can pick a request/other tab;
update the find predicate (used in the function handleSwitchToCollection) to
require t.type === 'collection-settings' as well so it only focuses an existing
collection-settings tab, and keep the existing addTab call (addTab({... type:
'collection-settings' })) and dispatch(focusTab(...)) behavior unchanged.
🧹 Nitpick comments (3)
packages/bruno-app/src/components/Dropdown/StyledWrapper.js (1)

88-97: Duplicated badge styles with .tab-count in CollectionHeader/StyledWrapper.js.

The font-size, padding, border-radius, min-width, and text-align values here are identical to the .tab-count class in the new CollectionHeader/StyledWrapper.js (lines 36-43). Consider extracting a shared CSS mixin or a small reusable badge snippet to keep these in sync.

packages/bruno-app/src/components/RequestTabs/CollectionHeader/index.js (2)

82-90: Inline mountedCollections computation runs on every render.

This filter chains through collections, workspaces, and currentWorkspace.collections on each render. For typical workload it's fine, but if the collection/workspace list grows, consider wrapping in useMemo keyed on [collections, workspaces, currentWorkspace].


1-30: Large import surface — component handles many responsibilities.

This component manages workspace switching, renaming, exporting, closing, collection tab navigation, and collection actions (runner, variables, settings). At ~450 lines, it's manageable today but could be a candidate for splitting into WorkspaceSwitcher + CollectionActions sub-components if it grows further.

Comment thread playwright/index.ts Resolved
sid-bruno and others added 4 commits February 13, 2026 11:06
…h StyledWrapper

- Introduced StyledWrapper component to encapsulate styling for transient request cards.
- Updated SaveTransientRequest and ConfirmAppClose modals to utilize StyledWrapper for improved layout and styling consistency.
- Enhanced transient request display with better class naming and structure for readability.
- Added handling for transient requests in SaveRequestsModal, separating them from regular drafts for clarity.
- Revert playwright/index.ts modal handling hack
- Add closeAllTabs helper to test utils for proper tab cleanup
- Update scratch-requests test to use closeAllTabs in afterAll
- Fix test assertion for new collection header dropdown structure
@sid-bruno
sid-bruno merged commit 53e158c into usebruno:main Feb 13, 2026
6 of 7 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Apr 17, 2026
6 tasks
prateek-bruno added a commit to prateek-bruno/bruno that referenced this pull request May 14, 2026
* Feat/support missing env apis (#7069)

* feat: add support for new variable management functions in Bruno

- Implemented methods to retrieve and delete all environment and global variables.
- Added corresponding translations for new functions in Postman and Bruno converters.
- Updated request handling to include header deletion functionality.
- Enhanced test cases to cover new variable management features.

* feat: add new scripts for environment and global variable management

- Introduced scripts to delete all environment and global variables.
- Added functionality to retrieve all environment and global variables.
- Implemented tests to validate the behavior of new variable management features.

* feat: implement collection variable management in Bruno

- Added methods for managing collection variables: set, get, has, delete, and retrieve all.
- Updated Postman translation functions to reflect new collection variable methods.
- Enhanced tests to validate the functionality of collection variable management.
- Refactored existing code to replace environment variable references with collection variable equivalents.

* feat: enhance collection variable translations in Bruno

- Updated translation functions for collection variable management to align with Postman API.
- Added tests for new collection variable methods: set, has, delete, retrieve all, and clear.
- Refactored existing tests to ensure accurate translation of collection variable operations.

* feat: expand API hints for variable management in Bruno

* fix: test cases

* fix: remove unnecessary return in deleteEnvVar function

* fix: cURL import NDJSON in request body as text (#7002)

* fix: cURL import NDJSON request body as text

* fix: cURL import NDJSON request body as text

* fix: cURL import NDJSON request body as text

* fix: resolved comments for body.text

* fix: add NDJSON content type detection

---------

Co-authored-by: shubh-bruno <[email protected]>

* Feature/scratch requests (#7087)

* feat: implement workspace-level scratch requests

Add support for temporary "scratch" requests at the workspace level that
are not tied to any collection. These requests are stored in a temp
directory and displayed as tabs in the workspace home.

Key changes:
- Add IPC handlers for mounting scratch directory and creating requests
- Add scratch directory watcher in collection-watcher.js
- Extend workspaces Redux slice with scratch state and reducers
- Add IPC listeners for scratch request events
- Create ScratchRequestPane and CreateScratchRequest components
- Update WorkspaceTabs with "+" button for creating scratch requests
- Update WorkspaceHome to render scratch request tabs
- Filter scratch collections from sidebar display

Supports all request types: HTTP, GraphQL, gRPC, and WebSocket.

* style: improve create scratch request button styling

- Use Button component with ghost variant and primary color
- Position button inside scrollable tab area
- Vertically center button with tabs
- Clean up unnecessary CSS properties

* fix: append scratch request dropdown to body to fix z-index issue

* refactor: improve scratch collection detection with path registration

- Add centralized scratch path tracking in backend (scratchCollectionPaths Set)
- Register scratch paths when created via renderer:mount-workspace-scratch
- Set brunoConfig.type='scratch' based on registered paths instead of string pattern
- Store scratchTempDirectory path in workspace state for frontend validation
- Update schema to accept 'scratch' as valid collection type
- Simplify frontend filtering to use brunoConfig.type or path comparison
- Remove fragile 'bruno-scratch-' string pattern matching
- Prevent scratch collections from being added to workspace.collections

* refactor: use CreateTransientRequest for scratch requests in workspace tabs

- Remove CreateScratchRequest component in favor of reusing CreateTransientRequest
- Register scratch collection temp directory via addTransientDirectory for transient request creation
- Add scratch collection item sync with workspace tabs
- Display HTTP method with color on scratch request tabs

* refactor: unify WorkspaceTabs with RequestTabs system

Remove separate WorkspaceTabs system and integrate workspace views (Overview, Environments) into the unified RequestTabs architecture using scratch collections.

Key changes:
- Remove WorkspaceTabs component and Redux slice
- Add workspaceOverview and workspaceEnvironments as special tab types
- Create WorkspaceHeader component to display workspace name in toolbar
- Make workspace tabs non-closable and always present
- Update tab creation on workspace switch to automatically add Overview and Environments tabs
- Simplify WorkspaceHome component by removing redundant header
- Update all references from WorkspaceTabs to unified tab system

Benefits:
- Single tab system for all content (collections and workspace views)
- Consistent UX with unified navigation pattern
- Reduced code complexity (~1000+ lines removed)
- Easier maintenance and feature development

* fix: enable automatic tab creation for scratch collection transient requests

- Add updateCollectionMountStatus to properly set scratch collection mount status to 'mounted'
- Create new renderer:add-collection-watcher IPC handler for explicit watcher setup
- Move workspace tab type checks before collection validation in RequestTabPanel
- Update mountScratchCollection to use explicit watcher setup instead of open-multiple-collections

This ensures the task middleware recognizes scratch collections as fully mounted,
allowing transient requests to automatically open in tabs when created.

* feat: add collection selector with breadcrumb navigation for scratch requests

Add multi-step save flow for scratch collection requests with collection selection before folder selection. Includes breadcrumb navigation showing "Collections > [Selected Collection] > [Folders...]" that allows users to navigate back to collection selector.

Refactor scratch collection detection to use workspace.scratchCollectionUid instead of persisting type to brunoConfig, providing cleaner separation of concerns without disk persistence.

Add backend support for automatic format conversion when saving from YAML scratch collections to BRU collections.

* chore: remove redundant comments and simplify code

* fix: use focusTab for home button, remove unused ScratchRequestPane

* fix: improve SaveTransientRequest collection mounting and selection flow

* refactor: use WorkspaceOverview directly, remove WorkspaceHome wrapper

* feat: add workspace management dropdown with rename, export, and close options

* refactor: extract CollectionListItem component with Redux selector for mount status

* refactor: separate scratch collection handling from openCollectionEvent

- Create dedicated openScratchCollectionEvent function for scratch collections
- Revert openCollectionEvent to clean state without scratch-specific logic
- Simplify closeTabs and closeAllCollectionTabs reducers in tabs slice
- Remove unused isScratchCollectionPath helper function

* test: add scratch requests test suite

- Add tests for creating scratch requests (HTTP, GraphQL, gRPC, WebSocket)
- Add tests for sending scratch requests and verifying response
- Add tests for saving scratch requests to a collection
- Add tests for multiple tabs and closing tabs
- Handle "Don't Save" modal in playwright fixture during app close

* refactor: address code review feedback for scratch requests feature

- Fix RequestTabPanel hooks violation by moving SSR guard after hooks
- Fix validateWorkspaceName to trim before length check
- Use stable deterministic UID in SaveTransientRequest
- Use ES6 shorthand for collectionUid in useIpcEvents
- Add JSDoc and error handling to openScratchCollectionEvent
- Fix closeAllCollectionTabs to preserve activeTabUid when not removed
- Add syncExampleUidsCache call to save-scratch-request handler
- Use getCollectionFormat for save-transient-request extension handling
- Fix Playwright modal handling with proper waitFor pattern
- Make keyboard shortcut platform-aware in scratch tests
- Remove flaky close tab test, handled by fixture cleanup
- Extract isScratchCollection utility to reduce duplication
- Memoize scratch collection derivation in RequestTabs
- Use theme color instead of Tailwind class for success icon
- Wrap resetForm and handleCancelWorkspaceRename in useCallback
- Extract FolderBreadcrumbs into separate component
- Call reset() inside useEffect in useCollectionFolderTree hook
- Defer workspace scratch state updates until mount succeeds

* feat: add unified collection header with context switcher dropdown

- Create CollectionHeader component that replaces WorkspaceHeader and CollectionToolBar
- Add dropdown to switch between workspace and mounted collections
- Display tab count badge next to collection/workspace name in header and dropdown
- Remove unused WorkspaceHeader and CollectionToolBar components
- Handle null/undefined values elegantly throughout

* chore: allow pr to comment

* refactor: improve scratch requests test cleanup with closeAllTabs helper

- Revert playwright/index.ts modal handling hack
- Add closeAllTabs helper to test utils for proper tab cleanup
- Update scratch-requests test to use closeAllTabs in afterAll
- Fix test assertion for new collection header dropdown structure

---------
Co-authored-by: Chirag Chandrashekhar <[email protected]>

* fix: env draft loss on color change and rename (#7130)

* tests: fix breaking tests (#7132)

* fix: update placeholder text for environment variable input

* fix: handle undefined color in environment objects

Don't export if `undefined`

* fix: update collection import logic for YML and BRU formats

* fix: ensure error icon is not visible after header validation

* fix: specify format for collection and environment serialization

* feat: move import collection from git url and spec url from enterprise edition to opensource (#7127)

* feat: move import collection from git url and spec url from enterprise edition to opensource

* fix: corrected a typo

* test: add unit and e2e tests for import collection migration

* fix: guard against missing userAgentData platform in getOSName — Default platform to '' to prevent TypeError when navigator.userAgentData is unavailable (GitNotFoundModal/index.js)

fix: UID mismatch between status tracking and UI rendering in bulk import — Preserve synthetic file-${index} UID on converted collections so initialStatus, rename tracking, and the render loop all use the same key (BulkImportCollectionLocation/index.js)

fix: isConfirmDisabled returning non-boolean value — Changed .length checks to explicit comparisons (> 0, === 0) so the function always returns true/false (CloneGitRespository/index.js)

fix: missing ipcRenderer declaration in cloneGitRepository and scanForBrunoFiles — Added const { ipcRenderer } = window; to both actions to prevent ReferenceError at runtime (collections/actions.js)

fix: use strict equality in filterItemsInCollection — Changed == to === for item.name and item.type comparisons (importers/common.js)

fix: variable shadowing in transformItemsInCollection and hydrateSeqInCollection — Renamed forEach callback parameter from collection to col to avoid shadowing the outer parameter (importers/common.js)

fix: scanForBrunoFiles traversing node_modules and .git directories — Added exclusion for node_modules and .git to match getCollectionStats pattern, preventing app freezes on large repos (filesystem.js)

fix: diff hunk header using string character count instead of line count — Preserved prefixedLines array to compute lineCount before joining, so the @@ header has the correct line count (git.js)

fix: test locators not scoped to modal in bulk import e2e test — Changed page.getByTestId to bulkImportModal.getByTestId for grouping dropdown interactions (002-all-collection-types.spec.ts)

fix: missing afterEach cleanup in GitHub repository import test — Added closeAllCollections hook to match sibling test specs, replaced unused dotenv/config import (github-repository-import.spec.ts)

* fix: batch name tracking and git utility fixes

- Fix usedNamesInBatch tracking original name instead of final name, which
  could produce duplicate environment names within the same batch
  (BulkImportCollectionLocation/index.js)

- Remove unused lodash import (git.js)

- Add missing early return in fetchRemotes when gitRootPath is falsy,
  preventing getSimpleGitInstanceForPath from running with undefined (git.js)

* fix: correct variable naming and state management in CloneGitRepository component

- Renamed `collectionpaths` to `collectionPaths` for consistency and clarity.
- Updated references throughout the component to use the corrected variable name.
- Removed error toast notification to streamline error handling during repository cloning.

* fix: update header validation test to use triple-click for selecting all text (#7140)

* fix: flaky tests - standardize save keyboard shortcut across tests (#7141)

* chore: fix flaky tests (#7144)

* feat: remove headers from request using scripts (#7122)

* fix: improve visual hierarchy of markdown headers in docs (#7145)

* fix: importing from openapi excludes documentation for requests (#6439)

* fix: importing from openapi excludes documentation for requests

fixes issue 5094 for requests

* fix: revert accidental changes

---------

Co-authored-by: Simon PAUGET <[email protected]>
Co-authored-by: Simon PAUGET <[email protected]>

* fix: incorrect response formatting when saving examples (#6528)

* Feature: Object Variable Interpolation (#6317)

* Added JSON stringify for object values to allow for proper display
Added styling changes to accommodate objects

* Switching to a multi line approach

* feat: add some doc about variable usage (#6443)

* add some doc about variable usage

* add some doc about variable usage

* add some doc about variable usage

* chore: fix flaky playwright tests (#7159)

* fix: update protobuf and import path handling in opencollection (#7166)

* fix: sse response download button (#7081)

Co-authored-by: Sid <[email protected]>

* fix: parsing dates from insomnia (#7003)

js-yaml uses DEFAULT_SCHEMA by default and implicitly casts date-like strings to Date (timestamp). This caused unexpected config values where dates were supposed to remain plain strings.

Switched YAML parsing to JSON_SCHEMA to disable timestamp resolution and keep date-like values as strings.

* fix cookies not being set when follow redirect = false (#6679)

* fix follow redirect cookies not being set

* Set default value of followredirects in axios-instance

Co-authored-by: Copilot <[email protected]>

---------

Co-authored-by: Jeroen Vinke <[email protected]>
Co-authored-by: Copilot <[email protected]>

* chore(playwright): enhance playwright config to reduce flakiness (#7174)

* update redux state to keep currently active script tab in state (#6947)

* feature/f2-rename-shortcut (#7077)

* feature/f2-rename-shortcut

* feat(hotkeys): added OS-specific key bindings for renaming items

* fix(hotkeys): updated hotkey function call to somethhing more performant and standard

* fix: `isJson` assertion fails after `res.setBody()` with object in `node-vm` (#7191)

* fix: isJson assertion fails after res.setBody() with object in node-vm

Objects created inside Node's vm.createContext() have a different Object
constructor than the host realm. When res.setBody() is called with a JS
object from a script, _.cloneDeep preserves the cross-realm prototype,
causing obj.constructor === Object to fail in the isJson assertion.

Replace with Object.prototype.toString.call() which is cross-realm safe.

* fix: register isJson chai assertion in QuickJS test runtime

The bundled chai in QuickJS only exposes { expect, assert } via
requireObject — no Assertion class. Access the prototype through
Object.getPrototypeOf(expect(null)) and use Object.defineProperty
to register the json property directly.

* fix: enable assertion chaining on isJson in QuickJS runtime

The QuickJS isJson property getter was missing `return this`, preventing
chai assertion chaining (e.g. expect(body).to.be.json.and...).

* fix: change transient request directory from os temp to app data (#7184)

* fix: change transient request directory from os temp to app data

Move transient request files from os.tmpdir() to app.getPath('userData')/transient
to prevent data loss when the OS clears temporary files.

Changes:
- Add helper functions for transient directory paths
- Update findCollectionPathByItemPath to use new transient path check
- Update renderer:mount-collection to create temp dirs in app data
- Update renderer:mount-workspace-scratch to create temp dirs in app data
- Update renderer:delete-transient-requests prefix validation

* change transient directory path to userData/tmp/transient

---------

Co-authored-by: Chirag Chandrashekhar <[email protected]>
Co-authored-by: naman-bruno <[email protected]>

* fix: normalize Windows paths for cross-platform compatibility (#7185)

* fix: normalize Windows paths for cross-platform compatibility in workspace

* fixes

* fix: collection scope undefined var (#7211)

* fix: import ndjson-curl handling binary data check with type file or not (#7210)

* fix: import ndjson-curl handling binary data check with type file

* chore: handle ansi escaping manually

* chore: avoid duplicate replacements

---------

Co-authored-by: shubh-bruno <[email protected]>

* fix: env var edit (#7066)

* Fix: incorrect translations (#7214)

* feat: update req.setHeader translation to use pm.request.headers.add with object argument

empty commit

* refactor: update req.setHeader translation to use pm.request.headers.upsert

* fix: consistent button size on save requests modal (#7197)

* Prevent cursor state loss on empty nextValue (#7180)

* fix(cli): preserve request item type during import and fail on unsupported types (#7207)

* fix(cli): preserve request type when importing collections

* fix(cli): fail fast on unsupported imported item types

* fix(cli): force BRU format when writing imported files

* chore: apply code rabbit fixes

* chore: adress review comment - keep changes minimal

* add additional test to test bru folder format

* agree with coderabbit, error handling is required

---------

Co-authored-by: Ramesh Sunkara <[email protected]>

* fix: `oauth2 credential` management improvements (#7220)

* fix: oauth2 credential management improvements

Add bru.resetOauth2Credential() API for programmatic credential invalidation
from scripts, fix credential clearing to match on credentialsId, expose
oauth2 credential variables in test runtime, and add input validation
with deduplication to prevent redundant IPC messages. Remove unused
collectionGetOauth2CredentialsByUrlAndCredentialsId reducer.

* fix: handle invalid URLs in oauth2 callback redirect handler

Wrap new URL() calls in try-catch within onWindowRedirect to prevent
uncaught TypeError when redirect or callback URLs are invalid.

* Update packages/bruno-app/src/utils/codemirror/autocomplete.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* fix: load shell environment variables on app startup (#7223)

Add shell-env integration to fetch environment variables from the user's
shell config files (.zshrc, .zshenv, etc.) so that proxy settings and
other exports are available in process.env for both Electron and CLI.

* feat: add reveal in file manager option to workspace collections menu (#6944)

* fix: call initializeShellEnv directly in app ready handler (#7228)

Move the shell environment initialization from module-level into the
app ready callback, avoiding a dangling promise at import time.

* fix: updated error message for renaming requests (#7010)

Co-authored-by: shubh-bruno <[email protected]>

* fix: collection reorder not persisting after restart (#7093)

* feat: implement workspace collection reordering functionality

feat: add tests and improve collection reordering functionality

fix: handle IPC errors during collection reordering and update tests for persistence validation

refactor: enhance collection reordering logic and update related tests for path consistency

fix: prevent unnecessary promise resolution in collection reordering when no collections are present

* fix: ensure consistent path normalization for workspace collections during reordering

* fix: window normlize path comparison (#7240)

* feat(CI): refactor github workflow for tests (#7252)

* feat: interface zoom control settings (#7255)

* feat: interface zoom control settings

* fix: allow zoom controls using shortcuts

* fix: maintain consitency in zoom shortcuts and ui interface

* fix: added min max to 50% and 150% for zoom

* fix: moved percentageToZoomLevel function in bruno-common

* chore: abstractions

---------

Co-authored-by: shubh-bruno <[email protected]>

* fix: openapi cli import (#7028)

* fix: openapi cli import

* chore: seperate bru and opencollection by a flag

* fix: pass down format correctly

* fix: pass format option correctly in collection tests

* Add opencollection version for YAML format

Set opencollection version for YAML format.

---------

Co-authored-by: Sid <[email protected]>

* chore: fix tab selection (#7260)

* fix: response viewer not updating when focused (read-only editors) (#7218)

* fix: update cursor state handling in CodeEditor for read-only mode

* tests: add response pane update test for re-sent requests

* refactor: add data-testid attributes for improved testing in RequestBody and RequestBodyMode components; update locators and tests accordingly

* test: verify response status code is 200

* test: enhance response pane update tests to verify body editor content after request re-sent

* test: add data-testid for method selector and update locators for improved testability

* fix: handle special characters in collection path for dotenv watcher (#7190)

* fix: handle special characters in collection path for dotenv watcher

* fix

* fix: normalize collection pathnames in EnvironmentSecretsStore (#7283)

* fix: normalize collection pathnames in EnvironmentSecretsStore

* fix

* fix

* fix: phone number faker function (#7046)

* fix: skip null query parameters in Postman to Bruno conversion (#7193)

* fix: skip null query parameters in Postman to Bruno conversion

Updated the importPostmanV2CollectionItem function to skip query parameters where both key and value are null. Added a test case to ensure that such parameters are not included in the converted Bruno collection, while preserving other valid parameters.

* fix: skip null parameters in Postman to Bruno conversion

Updated the importPostmanV2CollectionItem function to skip headers, URL-encoded parameters, and form data where both key and value are null. Added corresponding test cases to ensure proper handling of these scenarios in the conversion process.

* perf: Improve search performance in code editor (#6920)

* perf: Improve search performance in code editor

Added cache key to reduce duplicate searches over the complete text.
Added incremental update logic, to not update every marked entry when
clicking "next" or "previous".

Fixes: https://github.com/usebruno/bruno/issues/6913

* Update delimeter to unicode symbol

* feat: add options to skip request and response bodies in reporter output (#7114)

* feat: add options to skip request and response bodies in reporter output

- Introduced `--reporter-skip-request-body` and `--reporter-skip-response-body` flags to omit respective bodies from the reporter output.
- Updated examples in the CLI documentation to reflect new options.
- Refactored result sanitization to handle new flags.

* feat: add shorthand option to skip both request and response bodies in reporter output

- Introduced `--reporter-skip-body` as a shorthand for omitting both request and response bodies from the reporter output.
- Updated CLI documentation examples to include the new shorthand option.
- Adjusted result sanitization to accommodate the new option.

* refactor: simplify documentation and tests for reporter-skip-body option

- Updated the description of the `--reporter-skip-body` option to remove redundancy.
- Removed outdated shorthand references from the test suite for clarity.
- Cleaned up examples in the CLI documentation to focus on the current functionality.

* fix: handle optional chaining for request and response properties in result sanitization

- Updated the `sanitizeResultsForReporter` function to use optional chaining when accessing request and response headers and data.
- This change prevents potential errors when these properties are undefined.

* test: enhance reporter-skip-body tests for JSON and HTML outputs

- Added comprehensive tests for the `--reporter-skip-request-body` and `--reporter-skip-response-body` options in both JSON and HTML report formats.
- Verified that the appropriate request and response bodies are included or excluded based on the specified flags.
- Improved test coverage for scenarios where both flags are used simultaneously.

* fix: remove optional chaining for request and response headers in result sanitization

- Updated the `sanitizeResultsForReporter` function to directly assign empty objects to request and response headers, ensuring consistent behavior regardless of their initial state.
- This change simplifies the code and maintains functionality for skipping headers.

* fix: default normalizeProxyUrl to http protocol for all proxy URLs (#7285)

* Performance/file parse and mount (#6975)

* Refactor: optimize collection updates with batch processing

- Introduced BatchAggregator to handle IPC events in batches, reducing Redux dispatch overhead during collection mounting.
- Updated collection watcher to utilize batch processing for adding files and directories, improving UI performance.
- Implemented ParsedFileCacheStore using LMDB for efficient caching of parsed file content, enhancing loading speed and reducing redundant parsing.
- Adjusted collection slice to support batch addition of items, minimizing re-renders and improving state management.
- Updated relevant components to reflect changes in loading states and collection data handling.

* feat: add cache management to preferences

- Introduced a new Cache component in the Preferences section to display cache statistics and allow users to purge the cache.
- Implemented IPC handlers for fetching cache stats and purging the cache in the Electron main process.
- Added styled components for better UI presentation of cache information.
- Updated Preferences component to include a new tab for cache management.

* fix: update package-lock.json to change 'devOptional' to 'dev' for several Babel dependencies

* refactor: update batch aggregation parameters for improved performance

- Increased DISPATCH_INTERVAL_MS from 150ms to 200ms for better timing control.
- Adjusted MAX_BATCH_SIZE from 200 to 300 items to enhance batch processing efficiency.

* feat: enhance collection loading state and improve batch aggregator functionality

- Added isLoading property to collections slice to manage loading state during collection operations.
- Updated getAggregator function calls in collection-watcher to include collectionUid for better context in batch processing.
- Normalized directory path handling in parsed-file-cache to ensure consistent prefix creation for cache keys.

* fix: update loading state and transient file handling in collections slice

- Changed isLoading property to false during collection initialization for accurate loading state representation.
- Introduced isTransient flag for directories and files to differentiate between transient and non-transient items.
- Enhanced logic for handling transient directories and files during collection processing to improve state management.

* feat: add batch processing support for file additions in task middleware

- Implemented a new listener for collectionBatchAddItems to handle batch file additions.
- Enhanced task management by checking for pending OPEN_REQUEST tasks that match added files.
- Improved tab management by dispatching addTab actions for matching files and removing corresponding tasks from the queue.

* feat: enable ASAR packaging and unpacking for LMDB binaries in Electron build configuration

- Added ASAR support to the Electron build configuration for the Bruno application.
- Specified unpacking rules for LMDB native binaries to ensure proper loading during runtime.

* feat: implement parsed file cache using IndexedDB for improved performance

- Introduced a new `parsedFileCacheStore` utilizing IndexedDB for caching parsed file data.
- Replaced the previous LMDB-based cache implementation to enhance performance and reliability.
- Updated IPC handlers to manage cache operations such as get, set, invalidate, and clear.
- Integrated the new cache store into various components, ensuring efficient data retrieval and storage.
- Added pruning functionality to remove outdated cache entries on startup.

* refactor: update collection root and item handling to preserve UIDs

- Modified the way collection roots and folder items are assigned by using `mergeRootWithPreservedUids` and `mergeRequestWithPreservedUids` to ensure UIDs are maintained during updates.
- This change enhances data integrity when managing collections and their associated files.

* refactor: pass mainWindow reference to parsedFileCacheStore initialization

- Updated the `initialize` method in `ParsedFileCacheStore` to accept a `mainWindow` parameter, allowing for direct access to the main window instance in IPC handlers.
- This change improves the handling of IPC requests by ensuring the correct window context is used for sending messages.

* refactor: optimize getStats method in parsedFileCacheStore for performance

- Replaced manual counting of total files with a direct count() call for O(1) performance.
- Updated the collection counting logic to utilize openKeyCursor with 'nextunique' for improved efficiency in counting unique collection paths.
- These changes enhance the performance of the getStats method by reducing the complexity of file and collection counting.

* fix: update key generation in parsedFileCache to use newline separator

- Changed the key generation logic in `generateKey` from a null character to a newline character for improved readability and consistency in cache keys.

* refactor: rename batch-aggregator to collection-tree-batcher and add tests

- Rename BatchAggregator class to CollectionTreeBatcher
- Rename getAggregator/removeAggregator to getBatcher/removeBatcher
- Update imports and variable names in collection-watcher.js
- Add backward-compatible aliases for old names
- Add 22 unit tests covering all functionality

* refactor: update key generation in parsedFileCache to use custom separator

- Changed the key generation logic in `generateKey` to use a custom separator (↝) instead of a newline character for improved readability and consistency in cache keys.

* fix: add missing reject handler and fix directory prefix collision

- Add reject to Promise and pendingRequests in parsed-file-cache-idb.js
- Normalize dirPath with trailing separator in invalidateDirectory to
  prevent false matches (e.g., /foo/bar matching /foo/barley)
- Use platform-specific path.sep for cross-platform compatibility

* fix: add error handling in parsedFileCache and update window close event

- Added a catch block to handle errors in the database promise in parsedFileCache.
- Updated the window close event listener in collection-tree-batcher to use `once` for better resource management.

* fix: add LRU eviction when IndexedDB quota is exceeded

Handle QuotaExceededError in setEntry by automatically evicting
the oldest 20% of cache entries and retrying the write operation.

* fix: use once instead of on in mock window for batcher tests

---------

Co-authored-by: Chirag Chandrashekhar <[email protected]>

* feature: added support for unix sockets and named pipes(windows) for grpc local IPC support (#7021)

* Fix Environment Search Behavior, UI Updates, and Result Handling (#7287)

* feat: change default collection location to default location (#7291)

* feat: change default collection location to default location

* refactor: migrate defaultCollectionLocation to defaultLocation in preference.json

* refactor: resolveDefaultLocation function

* fix: rename variables in default-location

* fix: storing status in example for yml file (#6876)

* fix: storing status in example for yml file

* fix: temporary check for tests

* fix: temporary check for tests

* fix: temporary check for tests

* fix: temporary check for tests

* fix: temporary check for tests

* fix: temporary check for tests

* fix: temporary check for tests

* fix: temporary check for tests

* fix: temporary check for tests

* fix: temporary check for tests

* fix: temporary check for tests

* fix: temporary check for tests

* fix: test cases for status and statusText

* chore: removed logs

* fix: test cases for response status and text

* fix: test cases for response status and text

* fix: resolved comments

* fix: openapi test import test cases

* chore: removed console logs

* fix: status type in response example while import/export of collection

* fix: postman to bruno import

---------

Co-authored-by: shubh-bruno <[email protected]>

* Feat: Support `multipart/mixed` (#7155)

* feat(): support multipart mixed

fix: support vars interpolation on mixed multi-part

Update packages/bruno-electron/src/ipc/network/interpolate-vars.js

Co-authored-by: Timon <[email protected]>

refactor: use startsWith

feat: best effort for other multipart/* contentypes

* feat: enhance variable interpolation for multipart requests

- Updated `interpolateVars` function to support interpolation in multipart/form-data and multipart/mixed requests.
- Added handling for empty multipart arrays and parts with missing or undefined values.
- Improved type checks for content types to ensure proper interpolation behavior.

Includes new tests to validate the interpolation functionality for multipart requests.

* fix: normalize error handling in sendRequest and improve test reliability

---------

Co-authored-by: Alfonso Presa <[email protected]>

* fix(graphql): handle invalid schemas gracefully in query editor (#7269)

Prevent app crashes when loading GraphQL schemas with validation errors
(e.g., object types with no fields). The fix:

- Validates schemas using validateSchema() and shows warnings for issues
- Still loads the schema so autocomplete continues to work
- Wraps the CodeMirror GraphQL linter with error handling to catch
  any validation errors during linting

Fixes #4529

Co-authored-by: Chirag Chandrashekhar <[email protected]>

* fix(schema): support all Unicode letters in tag validation (#7311)

* allow international characters in tag regex for UI and schema
  validation
* update validation messages to match this

Co-authored-by: Miro Metsänheimo <[email protected]>

* fix#6247: Interpolate dynamic variables in path param (#6251)

* fix: prevent triggering rename action with modifier keys (#7322)

* fix(batch-events): fix order of directory file and folder events (#7300)

* fix: order of events

* fix: update constants handling in CollectionTreeBatcher and related tests

* fix: tags validation error for openapi import for BRU and YAML compatibility (#7294)

* fix: tags schema updatd to array of string

* tests: added test cases for sanitizing tags, openapi-tags

* fix: enhance tag sanitization to support object input and UTF characters

---------

Co-authored-by: shubh-bruno <[email protected]>

* Force text/plain mimetype when copying request code (#7321)

* Force text/plain mimetype when copying requests

* chore: lint

---------

Co-authored-by: Austen Adler <[email protected]>

* fix: wrong workspace request shown after closing tab (#7259)

* feat: add ensureActiveTabInCurrentWorkspace action and improve tab management

* refactor: enhance tab focus logic for current workspace and improve tab management

* tests: implement test for getTabToFocusForCurrentWorkspace logic and added a playwright

* refactor: improve comments for tab management logic and enhance workspace tab focus handling in tests

* refactor: ensure active tab in current workspace after collection removal and enhance tests for tab focus logic

* trigger build

* Enable encodeUrl setting to control URL encoding in generated snippets (#7187)

* feat(snippet-generator): implement encodeUrl setting to control URL encoding in generated snippets

* refactor(snippet-generator): rename and enhance URL encoding logic for better clarity and functionality

* feat(snippet-generator): enhance raw URL handling to preserve user encoding choices and improve snippet generation

* test(snippet-generator): add tests for URL fragment handling based on encodeUrl setting

* test(snippet-generator): improve comments on URL fragment handling to clarify RFC compliance

* feat(url): enhance interpolateUrlPathParams to support raw URL handling, preserving user encoding choices for snippet generation

* fix(url): ensure URLs are prefixed with http:// if missing in interpolateUrlPathParams function

* refactor(snippet-generator): streamline URL handling logic to improve snippet generation and ensure proper encoding based on settings

* feat(url): add stripOrigin utility to simplify URL processing in snippet generation

* test(snippet-generator): add test for double-encoding of pre-encoded URLs when encodeUrl is true

* feat(encoding): implement URL encoding settings and add tests for encoding behavior

* fix: address PR review comments (#7187)

- Remove unnecessary no-op jest.mock for @usebruno/common/utils
- Add length guard to prevent catastrophic replaceAll('/') on root-path URLs

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* empty commit

* fix(tests): update interpolateUrlPathParams tests to use correct parameter structure

* empty commit

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>

* feat: implement onboarding preferences and welcome modal for new users (#7319)

* feat: implement onboarding preferences and welcome modal for new users

* fixes

* adding: defaultPreferences

* fixes

* fix: tests

* fixes

* fix: test

* fix: test

* fixes

* fixes

* Update copyright year to 2026 (#7302)

* Update copyright year to 2026

* Update footer year to current year dynamically

* fix: Postman import compatibility for multipart form-data file params (#7325)

* fix: multipart form-data file param export/import for Postman

* fix: Postman import compatibility for multipart form-data file params

This commit fixes two issues that caused Postman to fail importing
Bruno-exported collections with multipart form-data file parameters:

1. Changed `src` field format to match Postman's export format:
   - Single file: export as string (e.g., "/path/to/file")
   - Multiple files: export as array (e.g., ["/path/a", "/path/b"])
   - Empty/null: export as null

   Previously, Bruno always exported `src` as an array, but Postman's
   importer expects a string for single files and fails to recognize
   the file type and path when given an array.

2. Added `protocolProfileBehavior.disableBodyPruning` for GET/HEAD/OPTIONS
   requests that have a body:

   By default, Postman discards request bodies for HTTP methods that
   typically don't have bodies (GET, HEAD, OPTIONS). Without this flag,
   importing a GET request with a form-data body would result in the
   body being silently dropped, making Postman unable to identify that
   the request has a formdata body at all.

Both changes align Bruno's Postman export format with Postman's own
export format, ensuring full import compatibility.

---------

Co-authored-by: Chirag Chandrashekhar <[email protected]>

* fix(`oauth2`): prevent false callback matches on `root path URLs` (#7315)

* fix(oauth2): prevent false callback matches on root path URLs and handle errors first

Move error check before callback URL matching in onWindowRedirect so
OAuth error responses are rejected immediately. Remove redundant error
param check from matchesCallbackUrl and require a code param or hash
fragment to match, preventing false positives on intermediate pages
when the callback URL is a root path like https://hostname/.

* fix(oauth2): clarify error handling comment

Remove "on the callback URL" from comment since error checking
now happens before callback URL matching.

* feat: add `tokenType` support for OAuth2 (#7314)

* feat: add tokenType support for OAuth2

* refactor: rename tokenType to source in OpenCollection OAuth2 mapping

* refactor: rename tokenType to source in OAuth2 configuration

* chore: bump @opencollection/types to ~0.8.0

* fix: correct OAuth2 token type label in token viewer

* refactor: replace Dropdown with MenuDropdown in OAuth2 components

Migrate all 12 dropdown instances across 5 OAuth2 auth components to use
the MenuDropdown component, removing manual tippy ref management and
forwardRef icon patterns in favor of a declarative items-based API.

* feat: improve stack traces for script and test failures (#7181)

* chore: update package-lock.json to include yaml dependency

* feat: add script-aware stack traces and source context for script/test failures

* chore: sync package-lock.json with yaml dependency in bruno-js

* fix: handle null check in getErrorTypeName and align JSDoc style

* refactor: derive script path from request.pathname and use SCRIPT_TYPES constant

* fix: avoid showing source context for collection/folder script errors

* feat: map collection/folder script errors to source file and line

* fix: update error formatting and avoid undefined message

* fix: resolve script block location in collection/folder yml files

* refactor: use script wrapper utils and rename wrapper offsets

* refactor: move script wrapper to utils, add wrapScriptInClosure fn

* fix: resolved zoom ui remarks (#7326)

* fix: resolved zoom ui remarks

* fix: resolved comments

* fix: resolved comments

---------

Co-authored-by: shubh-bruno <[email protected]>

* fix: ensure system proxy is initialized before use in network calls (#7264)

getCachedSystemProxy now awaits the initialization promise, preventing a race
condition where API calls made early in startup would bypass the system proxy.

* fix: allow user to delete default bruno headers in pre-request (#7331)

* fix: allow user to delete default bruno headers

* fix: resolved comments

---------

Co-authored-by: shubh-bruno <[email protected]>

* feat: add functionality to create new HTTP requests from the welcome modal and collections section (#7350)

* feat(sidebar): show "Add request" cta when collection or folder is empty (#7273)

* feat(sidebar): show "Add request" cta when collection or folder is empty

* fix: add connector lines and keyboard accessibility to empty-state CTA

* fix: debounce empty collection state to prevent flicker

Add 300ms delay before showing "Add request" button for empty collections.
This fixes a race condition where isLoading becomes false before the
items batch arrives from IPC, causing a brief flicker of the empty state.

Made-with: Cursor

---------

Co-authored-by: naman-bruno <[email protected]>

* refactor: streamline onboarding process and preferences handling (#7349)

* refactor: streamline onboarding process and preferences handling

* fixes

* fixes

* feat(phase-1): allow user to customize keybindings (#7163)

* feat(phase-1): allow user to customize keybindings

* fix: necessary changes for customizied keybindings to work

* fix: updated hotkeys provider

* fix: test cases for edit keybindings in preferences

* fix: removed old keyboard shortcuts test cases

* fix: resolved coderabbit coments

* fix: fixed move tabs test cases

* feat: provided customized keybindings shorcut for codemirror instacnces

* fix: handle closetabs/closeAllTabs in RequestTab/index.js for better consitency

* fix: resolved comments

* fix: resolved zoom issues

* fix: revert codemirror instacnces

* fix: handle codemirror instances shortcut in .Pass

* feat: integrate shorcut keys with codemirror instacneces

* fix: ui updates

* fix: updated shortcuts

* fix: test cases

* chore: revert `alt-enter` keybind

* chore: allow jest to replace esm spec in store

* chore: lint whitespace fix

---------

Co-authored-by: shubh-bruno <[email protected]>

* fix: file extension for clone and rename request (#7278)

* fix: file extension for clone and rename request

* fix

* feat: add collection creation flow in SaveTransientRequest modal (#7328)

* feat: enhance API spec export with environment variables support (#7170)

* feat: enhance API spec export with environment variables support

- Updated `exportApiSpec` function to accept and process environment variables for multi-server exports.
- Added logic to convert environment variables into a structured format for OpenAPI server entries.
- Enhanced the `CreateApiSpec` component to include environments in the exported YAML content.
- Introduced unit tests to validate the handling of server variables and their integration into the exported API specifications.

* refactor: streamline API spec export logic and improve variable handling

- Simplified variable extraction in `exportApiSpec` by directly assigning capture groups.
- Updated URL interpolation to use request variables instead of global variables for better accuracy.
- Enhanced handling of request body types by replacing early returns with breaks for clearer flow control.
- Adjusted tests to ensure backward compatibility with OpenAPI specifications and server variable handling.

* refactor: improve variable handling and URL processing in OpenAPI exporters

- Streamlined server variable assignment in `exportApiSpec` to handle undefined values more gracefully.
- Enhanced URL path extraction to ensure leading slashes are preserved in `getDefaultUrl` and `extractServerVars`.
- Updated string replacement logic to use `replaceAll` for consistent variable substitution in URLs.

* Fix persistence of additional parameters using open-collection format (#7296)

Co-authored-by: TaylorJerry <[email protected]>
Co-authored-by: MrcBoo <[email protected]>

* feat: inline create collection and workspace editor (#7324)

* feat: inline create collection and workspace editor

* refactor: use inline collection creation from workspace overview

* fix: improve inline collection creation UX from workspace overview

* fix: update E2E tests for inline collection creation flow

* fix: update default location test for inline collection creation flow

* fix: derive inline workspace/collection names from filesystem

* feat: inline workspace create form manage workspace

* feat: prefill create modal with name

* fix: minor code style fixes

---------

Co-authored-by: naman-bruno <[email protected]>

* chore: update coderabbit instructions to make sure the code is os agnostic (#7355)

* refactor: comment out unused APIs (#7323)

* refactor: comment out unused API hints in autocomplete.js

* refactor: comment out unused API translations in postman and bruno translators

Temporarily disable certain API translations due to UI update issues affecting their functionality. A note has been added to restore these translations once the UI fixes are implemented.

* refactor: temporarily skip tests for collection variable translations due to UI update issues

Commented out tests related to `setCollectionVar`, `deleteCollectionVar`, and related functionalities until the necessary UI updates are implemented. A note has been added to restore these tests once the fixes are live.

* refactor: comment out variable deletion and retrieval methods due to UI sync issues

* revert: ping.bru

* refactor: update postman translation tests to enable previously skipped cases

* Revert "Performance/file parse and mount (#6975)" (#7360)

* Revert "Performance/file parse and mount (#6975)"

This reverts commit f76f487211d3859edf2d14f0b11812811df3a758.

* fix: import duplication

* Revert "fix(batch-events): fix order of directory file and folder events (#7300)"

This reverts commit bf4af42a25522d10f44e1fec17af63b3f0db0077.

---------

Co-authored-by: Chirag Chandrashekhar <[email protected]>
Co-authored-by: Sid <[email protected]>

* fix: show '+ Add request' when only transient items exist (#7361)

* fix: focus and text selection in workspace creation flow (#7363)

* fix: workspace creation rename focus

* refactor: remove duplicate focus/select timer from rename handler

* feat/openapi sync (#7279)

* feat: implement OpenAPI Sync

* feat: enhance focus styles and error handling across components

- Added focus-visible styles for buttons and tags in Swagger and Modal components to improve accessibility.
- Updated ConnectSpecForm to ensure source URL is set only if the file path is valid.
- Enhanced clipboard copy functionality in SpecInfoCard with error handling and success notifications.
- Improved ExpandableEndpointRow to handle loading state more robustly.
- Refined SyncReviewPage to ensure correct filtering of updated endpoints.
- Updated file handling in OpenAPI Sync IPC to support both .yml and .yaml extensions.

* fix: improve filename sanitization in OpenAPI Sync IPC

- Updated filename sanitization logic to ensure proper handling of both `name` and `filename` properties, enhancing compatibility with various file formats.
- Adjusted the logic to derive the base name from the filename when necessary, ensuring consistent output for generated files.

* feat: enhance OpenAPI Sync tab with new overview and header components

- Introduced OverviewSection to display summary of collection and spec status, including total endpoints, in-sync counts, and pending updates.
- Added OpenAPISyncHeader for improved navigation and actions related to the OpenAPI spec.
- Updated CollectionStatusSection to better handle and display collection drift information.
- Refined styling for status banners and added new visual elements for better user experience.
- Enhanced tooltip functionality in Help component for improved accessibility.

* refactor: remove VisualDiffViewer components and add diff package

- Deleted VisualDiffViewer components including VisualDiffMeta, VisualDiffDocs, VisualDiffVars, and others to streamline the codebase.
- Introduced the 'diff' package in package-lock.json to enhance diff functionality.
- Updated utility functions to improve diff status handling and maintainability.

* feat: enhance OpenAPI Sync tab with sync status indicators and improved styling (#7371)

- Added sync status logic to determine if the collection is in sync with the spec, displaying appropriate indicators in the UI.
- Updated OpenAPISyncHeader to include linked collection information and sync status icons.
- Refined styling in StyledWrapper for better layout and visual feedback on sync status.
- Removed unused styles and components to streamline the codebase.

* fix: enable `SSL session caching` and `HTTP agent reuse` for faster consecutive requests (#6987)

* fix: enable SSL session caching for faster consecutive requests (#6929)

* fix: enable SSL session caching for faster consecutive requests

Previously, Bruno created a new HTTPS agent for every request, which meant
SSL/TLS sessions couldn't be reused. This caused the full TLS handshake
(~450ms) to run on every request, even to the same endpoint.

Changes:
- Add agent caching based on TLS configuration (certs, proxy, SSL options)
- Reuse cached agents for requests with matching configuration
- SSL sessions are now cached and reused, significantly reducing
  response time for consecutive requests to the same host

The fix maintains backward compatibility:
- Timeline logging moved to setup phase (before agent creation)
- Proxy and SSL validation behavior unchanged
- Added clearAgentCache() for testing and configuration changes

Fixes #5574

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* fix: address review feedback for SSL session caching

- Add passphrase to cache key to prevent incorrect agent reuse
- Add MAX_AGENT_CACHE_SIZE (100) with LRU-style eviction
- Use consistent node: prefix for crypto import

Co-Authored-By: Claude Opus 4.5 <[email protected]>

---------

Co-authored-by: Claude Opus 4.5 <[email protected]>
Co-authored-by: lohit <[email protected]>

* feat(bruno-requests): add timeline agent for TLS event logging

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* feat(bruno-requests): add agent cache for SSL session reuse

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* test(bruno-requests): add tests for agent cache

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* feat(bruno-requests): integrate agent cache into http-https-agents

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* refactor(bruno-electron): use shared agent cache from bruno-requests

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* feat(bruno-cli): use agent cache for SSL session reuse

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* feat(bruno-requests): add HTTP agent timeline support

Add createTimelineHttpAgentClass for logging HTTP connection events
including proxy usage, DNS lookups, and connection establishment.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* refactor(bruno-requests): extract shared agent caching logic

Add getOrCreateAgentInternal helper to reduce code duplication
between getOrCreateAgent and getOrCreateHttpAgent functions.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* feat(bruno-requests): use HTTP agent cache for connection reuse

Export getOrCreateHttpAgent and use it in http-https-agents for
HTTP requests to enable connection pooling.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* fix(bruno-cli): improve HTTP agent handling and error logging

- Use { keepAlive: true } instead of tlsOptions for HTTP agents
- Add warning log for system proxy configuration errors
- Fix brace style consistency

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* fix(bruno-electron): improve HTTP agent handling

- Use { keepAlive: true } instead of tlsOptions for HTTP agents
- Fix brace style consistency
- Add missing newline at EOF

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* fix(bruno-requests): address code review findings for agent caching

- Fix Buffer hashing bug: properly handle Buffer values in hashValue()
- Add CA array support: new hashCaValue() handles string[] | Buffer[]
- Fix timeline race condition: capture timeline reference in closure
  at createConnection start to isolate concurrent requests
- Fix SSL verify message: check socket.authorized for accurate status
- Fix HTTP/HTTPS agent logic: only set httpsAgent for HTTPS requests
- Add tests for concurrent requests timeline isolation

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* feat(bruno-requests): log when reusing cached agent

- HTTPS agents: "Reusing cached agent (SSL session reuse enabled)"
- HTTP agents: "Reusing cached agent (connection reuse enabled)"

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* feat(preferences): add cache.httpHttpsAgents.enabled preference

* feat(agent-cache): add disableCache option to getOrCreateAgent

* feat(proxy-util): respect httpHttpsAgents cache preference

* refactor(agent-cache): use named props for getOrCreateAgent and getOrCreateHttpAgent

* feat(ipc): add renderer:clear-http-https-agent-cache handler

* feat(redux): add cache.httpHttpsAgents preferences to initial state

* feat(ui): add Cache tab to Preferences

* feat(cli): add --disable-http-https-agents-cache flag

* refactor(cache): replace window.ipcRenderer calls with redux actions

Add getCacheStats, purgeCache, and clearHttpHttpsAgentCache thunks to
the app slice. Update the Cache preferences component to dispatch these
actions instead of calling window.ipcRenderer directly.

Also move handleSave and handleSaveRef above useFormik to fix declaration
order — onSubmit closes over handleSaveRef, so the ref must be initialized
before useFormik is called.

* fix: tests

* fix(cache): thread disableCache and hostname through all agent-creation paths

- Forward disableHttpHttpsAgentsCache through getHttpHttpsAgents → createAgents
  so OAuth2 token requests and bru.sendRequest honour the CLI flag
- Add hostname to agent cache keys (getAgentCacheKey, getHttpAgentCacheKey)
  for per-host TLS session reuse; extract hostname at every call site in
  run-single-request.js, proxy-util.js, and http-https-agents.ts
- Add extractHostname helper in http-https-agents.ts to safely parse hostnames
- Add test coverage for cert, key, pfx, passphrase, and hostname cache-key
  differentiation in agent-cache.spec.ts

* refactor(cache): rename getOrCreateAgent to getOrCreateHttpsAgent

* refactor: simplify UI labels, optimize agent timeline wrapping, silence proxy errors

* fix: tests

* fix(proxy): fix proxy agent construction and CA cert handling

Three fixes:

1. Proxy agents (HttpsProxyAgent, HttpProxyAgent, SocksProxyAgent) expect
   (proxyUri, options) constructor signature, but the agent cache was packing
   proxyUri into options as a single argument. Fixed the non-timeline code
   path in getOrCreateAgentInternal.

2. HTTP requests through an HTTPS proxy need TLS options (ca certs) to
   validate the proxy's certificate. All getOrCreateHttpAgent call sites
   now pass TLS options when the proxy protocol is HTTPS.

3. Setting the `ca` option on any Node.js TLS connection replaces the
   default OpenSSL trust store entirely. CAs only in the OpenSSL default
   trust store (e.g. /etc/ssl/cert.pem) but not in tls.rootCertificates
   were lost. Fixed by converting `ca` to a secureContext via addCACert(),
   which appends custom CAs on top of the OpenSSL defaults instead of
   replacing them.

Also simplified PatchedHttpsProxyAgent to selectively forward only the
relevant TLS options (cert, key, pfx, passphrase, rejectUnauthorized,
secureContext) to the target TLS upgrade instead of blindly merging all
constructor options.

* fix(tls): load client certs into secureContext to prevent silent drop

Add Cache tab to Preferences UI

* fix(proxy): align proxy auth check to use auth.disabled field consistently

* refactor(cache): rename CLI flag to --cache-ssl-session and disable caching by default

- Rename --disable-http-https-agents-cache to --cache-ssl-session (opt-in)
- Rename disableHttpHttpsAgentsCache to cacheSslSession across CLI and bruno-requests
- Default caching to disabled in both bruno-electron and bruno-cli
- Add cacheSslSession to buildCertsAndProxyConfig for bru.sendRequest
- Update Preferences UI labels to "Cache SSL Session"

* refactor(cache): rename httpHttpsAgents to sslSession across preferences and UI

* refactor(cache): remove unused getCacheStats and purgeCache IPC actions

---------

Co-authored-by: karthik <[email protected]>
Co-authored-by: Claude Opus 4.5 <[email protected]>

* Feat/opeanpi sync updates (#7374)

* fix: update button colors and streamline props in OpenAPISyncTab and CollectionHeader

- Changed button color from 'warning' to 'primary' in OpenAPISyncTab for better visual consistency.
- Simplified prop usage for OpenAPISyncIcon in CollectionHeader by removing unnecessary function wrapper.

* fix: update StatusBadge variant in OpenAPISyncHeader for improved styling

- Changed StatusBadge in OpenAPISyncHeader to use 'outline' variant for better visual distinction of version information.

* refactor: simplify OpenAPISyncTab and related components by removing unused state and styles (#7378)

- Removed the `viewMode` state and associated logic from OpenAPISyncTab and useSyncFlow, streamlining the component's functionality.
- Eliminated the `review-active` class from StyledWrapper, cleaning up the styling.
- Updated Redux state management by removing `viewMode` from the tab UI state structure, reducing complexity.

* chore: UI Polish for Zoom and Keybindings panel (#7376)

* chore: ui polishing for zoom panel

* fix: replace IconRefresh with IconReload in Zoom and Keybindings components

* chore: resolved ui issues

* test: check test cases

* fix: adjust width properties in StyledWrapper component

* fix: update keybindings UI layout and tooltip removal

* chore: semantics

---------

Co-authored-by: Sid <[email protected]>
Co-authored-by: shubh-bruno <[email protected]>

* fix: use Title Case for default "Untitled Collection" and "Untitled Workspace" (#7389)

* fix: preserve existing process.env values in initializeShellEnv (#7390)

* refactor: enhance OpenAPISyncTab functionality and clean up unused code (#7392)

- Updated OpenAPISyncTab to utilize Redux state for active tab management, improving state consistency.
- Removed unnecessary loading state checks from OverviewSection and SpecStatusSection for cleaner logic.
- Streamlined prop usage in OverviewSection by eliminating the isLoading prop.
- Cleaned up useOpenAPISync hook by removing unused state clearing logic on unmount.
- Improved file handling in openapi-sync IPC by ensuring new files are created in the appropriate folder based on tags.

* fix: update collection path handling to use path.join for consistency across components (#7394)

* Fix: resolve default location missing path (#7391)

* fix: refocus collection name input on error and resolve missing default location folder

* revert: remove focus refocus logic from InlineCollectionCreator

Reverts the setTimeout focus change that was causing test failures.
Keeps the preferences.js fix for default location validation.

Made-with: Cursor

* fix: update default-collection-location test to use project path

Use {{projectRoot}} template variable for defaultLocation so the path
exists when the app validates it with fs.existsSync.

Made-with: Cursor

* fix: improve save test to use alternate path and verify persistence

Made-with: Cursor

---------

Co-authored-by: naman-bruno <[email protected]>

* fix: allow edit keybinding shortcuts (#7404)

Co-authored-by: shubh-bruno <[email protected]>

* fix:  app crash error (Rendered fewer hooks than expected) (#7407)

* fix:  app crash error (Rendered fewer hooks than expected)

* empty commit

* enhance OpenAPI sync with validation, enum support, and bug fixes (#7408)

* Enhance OpenAPISyncTab functionality with error handling and UI improvements

- Updated ConnectSpecForm to include error handling for invalid OpenAPI specifications when uploading files.
- Added a sync info notice in CollectionStatusSection to inform users about tracked changes.
- Improved styling in StyledWrapper for better visual feedback and layout consistency.
- Adjusted button colors and properties in ConfirmSyncModal and ConnectionSettingsModal for better UX.
- Refactored useOpenAPISync hook to validate URLs before syncing, ensuring only valid OpenAPI specs are processed.
- Enhanced parameter handling in openapi-to-bruno.js to support enum and default values more effectively.

* Refactor OpenAPISyncTab components for improved URL validation and error handling

- Updated ConnectSpecForm to streamline file upload error handling for OpenAPI specifications.
- Enhanced OpenAPISyncHeader to utilize isHttpUrl for better URL validation.
- Refactored useOpenAPISync hook to replace isValidUrl with isHttpUrl for consistency in URL checks.
- Improved file parsing logic in file-reader.js to handle case-insensitive JSON file extensions.
- Added isHttpUrl utility function to validate HTTP/HTTPS URLs effectively.

* Enhance file parsing logic in file-reader.js to improve error handling for JSON and YAML files

- Updated parseFileAsJsonOrYaml function to handle case-insensitive JSON file extensions more robustly.
- Added error handling to ensure the document root is an object and not an array, improving data validation.

* Update StatusBadge component to include new 'xs' size preset and adjust documentation accordingly

- Added 'xs' size preset with specific font size and padding for minimal use cases.
- Updated documentation to reflect the new size options available for the StatusBadge component.

* feat(request-pane): restore body tab scroll position on tab switch (#7250)

* feat(request-pane): restore body tab scroll position on tab switch

When editing large request bodies (JSON/XML/text/sparql), switching to
another tab (params, headers, auth, etc.) and back would reset the
CodeMirror editor scroll position to the top.

Fix by persisting the scroll position to Redux on editor unmount (via
CodeEditor's onScroll prop) and restoring it on mount (via initialScroll),
mirroring the existing scroll restoration pattern in QueryResultPreview.

* test: add playwright tests for body scroll restoration

---------

Co-authored-by: naman-bruno <[email protected]>…
maxenceleblanc pushed a commit to maxenceleblanc/curly_cats2 that referenced this pull request Jul 20, 2026
* feat: implement workspace-level scratch requests

Add support for temporary "scratch" requests at the workspace level that
are not tied to any collection. These requests are stored in a temp
directory and displayed as tabs in the workspace home.

Key changes:
- Add IPC handlers for mounting scratch directory and creating requests
- Add scratch directory watcher in collection-watcher.js
- Extend workspaces Redux slice with scratch state and reducers
- Add IPC listeners for scratch request events
- Create ScratchRequestPane and CreateScratchRequest components
- Update WorkspaceTabs with "+" button for creating scratch requests
- Update WorkspaceHome to render scratch request tabs
- Filter scratch collections from sidebar display

Supports all request types: HTTP, GraphQL, gRPC, and WebSocket.

* style: improve create scratch request button styling

- Use Button component with ghost variant and primary color
- Position button inside scrollable tab area
- Vertically center button with tabs
- Clean up unnecessary CSS properties

* fix: append scratch request dropdown to body to fix z-index issue

* refactor: improve scratch collection detection with path registration

- Add centralized scratch path tracking in backend (scratchCollectionPaths Set)
- Register scratch paths when created via renderer:mount-workspace-scratch
- Set brunoConfig.type='scratch' based on registered paths instead of string pattern
- Store scratchTempDirectory path in workspace state for frontend validation
- Update schema to accept 'scratch' as valid collection type
- Simplify frontend filtering to use brunoConfig.type or path comparison
- Remove fragile 'bruno-scratch-' string pattern matching
- Prevent scratch collections from being added to workspace.collections

* refactor: use CreateTransientRequest for scratch requests in workspace tabs

- Remove CreateScratchRequest component in favor of reusing CreateTransientRequest
- Register scratch collection temp directory via addTransientDirectory for transient request creation
- Add scratch collection item sync with workspace tabs
- Display HTTP method with color on scratch request tabs

* refactor: unify WorkspaceTabs with RequestTabs system

Remove separate WorkspaceTabs system and integrate workspace views (Overview, Environments) into the unified RequestTabs architecture using scratch collections.

Key changes:
- Remove WorkspaceTabs component and Redux slice
- Add workspaceOverview and workspaceEnvironments as special tab types
- Create WorkspaceHeader component to display workspace name in toolbar
- Make workspace tabs non-closable and always present
- Update tab creation on workspace switch to automatically add Overview and Environments tabs
- Simplify WorkspaceHome component by removing redundant header
- Update all references from WorkspaceTabs to unified tab system

Benefits:
- Single tab system for all content (collections and workspace views)
- Consistent UX with unified navigation pattern
- Reduced code complexity (~1000+ lines removed)
- Easier maintenance and feature development

* fix: enable automatic tab creation for scratch collection transient requests

- Add updateCollectionMountStatus to properly set scratch collection mount status to 'mounted'
- Create new renderer:add-collection-watcher IPC handler for explicit watcher setup
- Move workspace tab type checks before collection validation in RequestTabPanel
- Update mountScratchCollection to use explicit watcher setup instead of open-multiple-collections

This ensures the task middleware recognizes scratch collections as fully mounted,
allowing transient requests to automatically open in tabs when created.

* feat: add collection selector with breadcrumb navigation for scratch requests

Add multi-step save flow for scratch collection requests with collection selection before folder selection. Includes breadcrumb navigation showing "Collections > [Selected Collection] > [Folders...]" that allows users to navigate back to collection selector.

Refactor scratch collection detection to use workspace.scratchCollectionUid instead of persisting type to brunoConfig, providing cleaner separation of concerns without disk persistence.

Add backend support for automatic format conversion when saving from YAML scratch collections to BRU collections.

* chore: remove redundant comments and simplify code

* fix: use focusTab for home button, remove unused ScratchRequestPane

* fix: improve SaveTransientRequest collection mounting and selection flow

* refactor: use WorkspaceOverview directly, remove WorkspaceHome wrapper

* feat: add workspace management dropdown with rename, export, and close options

* refactor: extract CollectionListItem component with Redux selector for mount status

* refactor: separate scratch collection handling from openCollectionEvent

- Create dedicated openScratchCollectionEvent function for scratch collections
- Revert openCollectionEvent to clean state without scratch-specific logic
- Simplify closeTabs and closeAllCollectionTabs reducers in tabs slice
- Remove unused isScratchCollectionPath helper function

* test: add scratch requests test suite

- Add tests for creating scratch requests (HTTP, GraphQL, gRPC, WebSocket)
- Add tests for sending scratch requests and verifying response
- Add tests for saving scratch requests to a collection
- Add tests for multiple tabs and closing tabs
- Handle "Don't Save" modal in playwright fixture during app close

* refactor: address code review feedback for scratch requests feature

- Fix RequestTabPanel hooks violation by moving SSR guard after hooks
- Fix validateWorkspaceName to trim before length check
- Use stable deterministic UID in SaveTransientRequest
- Use ES6 shorthand for collectionUid in useIpcEvents
- Add JSDoc and error handling to openScratchCollectionEvent
- Fix closeAllCollectionTabs to preserve activeTabUid when not removed
- Add syncExampleUidsCache call to save-scratch-request handler
- Use getCollectionFormat for save-transient-request extension handling
- Fix Playwright modal handling with proper waitFor pattern
- Make keyboard shortcut platform-aware in scratch tests
- Remove flaky close tab test, handled by fixture cleanup
- Extract isScratchCollection utility to reduce duplication
- Memoize scratch collection derivation in RequestTabs
- Use theme color instead of Tailwind class for success icon
- Wrap resetForm and handleCancelWorkspaceRename in useCallback
- Extract FolderBreadcrumbs into separate component
- Call reset() inside useEffect in useCollectionFolderTree hook
- Defer workspace scratch state updates until mount succeeds

* feat: add unified collection header with context switcher dropdown

- Create CollectionHeader component that replaces WorkspaceHeader and CollectionToolBar
- Add dropdown to switch between workspace and mounted collections
- Display tab count badge next to collection/workspace name in header and dropdown
- Remove unused WorkspaceHeader and CollectionToolBar components
- Handle null/undefined values elegantly throughout

* chore: allow pr to comment

* refactor: improve scratch requests test cleanup with closeAllTabs helper

- Revert playwright/index.ts modal handling hack
- Add closeAllTabs helper to test utils for proper tab cleanup
- Update scratch-requests test to use closeAllTabs in afterAll
- Fix test assertion for new collection header dropdown structure

---------
Co-authored-by: Chirag Chandrashekhar <[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.

3 participants