Skip to content

fix(apispec): prevent crash on non-array specs and fix Windows spec listing (BRU-3556) - #8255

Merged
engineering-bruno merged 7 commits into
usebruno:mainfrom
sundram-bruno:fix/bru-3556-apispec-crash
Jun 12, 2026
Merged

engineering-bruno merged 7 commits into
usebruno:mainfrom
sundram-bruno:fix/bru-3556-apispec-crash

Conversation

@sundram-bruno

@sundram-bruno sundram-bruno commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes two linked failures in the OpenAPI Spec viewer.

Jira: https://usebruno.atlassian.net/browse/BRU-3556

1. Crash on workspace switch / open (TypeError: ... .map is not a function)

The API Specs sidebar assumed workspace.apiSpecs is always an array and called .map(...), guarded only by specs || [] — which catches null/undefined but not a truthy non-array (e.g. specs authored as a YAML map). Such a value reached the renderer and crashed the whole app to the global error screen on render.

Defense-in-depth:

  • Coerce specs to an array at the single normalizeWorkspaceConfig chokepoint (readWorkspaceConfig), so a malformed shape never enters renderer state — this also protects the write paths that read config.specs (addApiSpecToWorkspace / removeApiSpecFromWorkspace / getWorkspaceApiSpecs).
  • Guard the loader IPC and the sidebar render with Array.isArray as a last resort.
  • Deduped the 3 copies of normalizeWorkspaceConfig into one shared export.

2. Windows: imported spec not listed until a workspace switch

The sidebar pairs each workspace.yml spec entry to its loaded counterpart by exact path-string equality. The two paths are derived independently — the workspace entry is stored posixified (forward slashes), while the loaded spec's pathname comes from the file watcher in native form (backslashes on Windows). C:/ws/api.yaml !== C:\ws\api.yaml, so the match failed and the spec stayed hidden until a workspace switch reloaded both lists. macOS/Linux use forward slashes on both sides, so it always worked there (not reproducible on macOS).

Fix: compare normalized (posixified) paths in the sidebar match (matchLoadedApiSpecs) and in the loadWorkspaceApiSpecs "already open" check. normalizePath is a no-op on posix paths, so macOS/Linux behavior is unchanged.

Testing

  • bruno-electron workspace-config.spec.js: 9 cases (valid/empty/null/map/string/number/boolean/junk-array shapes + add/remove write paths on malformed specs).
  • bruno-app matchLoadedApiSpecs.spec.js: 7 cases incl. the Windows backslash-vs-forward-slash match, order preservation, empty-path guard, non-array inputs.
  • Crash fix verified on macOS; Windows refresh fix pending QA on Windows (Windows-only reproducible).

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. (Tracked in Jira: BRU-3556)

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Enhanced Windows file path handling to prevent duplicate opening of API specifications across different path formats.
    • Improved robustness to handle malformed workspace configuration files without errors.
    • Fixed API spec matching to work correctly regardless of path separator format (Windows vs other systems).
  • Tests

    • Added comprehensive test coverage for spec path matching and malformed configuration handling.

sundram-bruno and others added 5 commits June 12, 2026 14:31
…556)

A workspace.yml whose `specs` is authored as a map (not a list) flowed
through as a truthy non-array onto workspace.apiSpecs, and the API Specs
sidebar's `workspaceApiSpecs.map(...)` threw
`TypeError: ... .map is not a function`, dropping the app to the global
error screen on workspace open/switch.

Defense-in-depth:
- Coerce `specs` to an array at every source normalizer and the loader IPC
  (workspace-config.js, app/apiSpecs.js, app/workspace-watcher.js,
  ipc/workspace.js) so a malformed shape never enters renderer state.
- Guard the sidebar render with Array.isArray as a last resort
  (Sidebar/ApiSpecs/index.js) so legacy/persisted bad state can't crash.

Adds readWorkspaceConfig regression tests for valid / malformed-map /
missing specs.

Note: 3 copies of normalizeWorkspaceConfig remain duplicated; consolidating
to one shared util is a sensible followup, out of scope here.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rite paths (BRU-3556)

The first pass only set apiSpecs, leaving raw config.specs non-array. The
write paths (addApiSpecToWorkspace .findIndex, removeApiSpecFromWorkspace
.filter, getWorkspaceApiSpecs/openApiSpec .map/.find) all read config.specs
and would still throw in the main process when importing/deleting against an
already-malformed workspace.yml.

Coerce `specs` once inside normalizeWorkspaceConfig so every readWorkspaceConfig
consumer gets an array (apiSpecs mirrors the same reference). sanitizeSpecs
already guarded the write output; this guards the in-memory mutations too.

Regression coverage: parametrized readWorkspaceConfig cases proving the
`|| []` -> Array.isArray swap preserves every valid shape (populated/empty
list) and only changes non-array inputs (null/map/string/number -> []), plus
add/remove write-path tests against a malformed workspace.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The helper was copy-pasted in workspace-config.js, app/apiSpecs.js and
app/workspace-watcher.js. After the specs-coercion fix the copies drifted
(only workspace-config.js coerced `specs` itself), leaving the other two
emitting a raw non-array `specs` to the renderer. Export the single
normalizeWorkspaceConfig from workspace-config.js and import it in both
callers so all three paths behave identically.

Also drop the ticket id from the test describe block.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Adds review-flagged gaps: boolean `specs: true` coerces to [], and an array
with non-object elements is preserved as-is (no crash on render; sanitizeSpecs
drops invalid entries on write).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ws (BRU-3556)

An imported OpenAPI spec did not appear in the API Specs sidebar until the user
switched workspaces, on Windows only.

The sidebar pairs each workspace.yml spec entry to its loaded counterpart by
exact path-string equality. The two paths are derived independently: the
workspace entry is stored posixified (forward slashes) while the loaded spec's
pathname comes from the file watcher in native form (backslashes on Windows).
`C:/ws/api.yaml` !== `C:\ws\api.yaml`, so the match failed and the spec was
dropped by filter(Boolean) until a workspace switch reloaded both lists. On
macOS/Linux both are forward-slash, so it always worked (and was not reproducible).

Compare normalized (posixified) paths in both the sidebar match
(matchLoadedApiSpecs) and the loadWorkspaceApiSpecs "already open" check.
normalizePath is a no-op on posix paths, so macOS/Linux behavior is unchanged.

Adds matchLoadedApiSpecs unit tests covering the Windows separator case, order
preservation, empty-path guard, and non-array inputs.

Out of scope (separate follow-up if needed): fs-level unlink watcher for specs
deleted outside the app, and a warning when a workspace's spec list is malformed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 68a62ea1-7cf8-4554-b211-a501a44c132c

📥 Commits

Reviewing files that changed from the base of the PR and between 408111d and 37e6b77.

📒 Files selected for processing (1)
  • packages/bruno-electron/src/app/apiSpecs.js

Walkthrough

Coerces workspace specs to arrays, centralizes and exports normalizeWorkspaceConfig, normalizes API spec paths across POSIX/Windows, adds a frontend matchLoadedApiSpecs helper with tests, and updates IPC/electron/frontend logic to use normalized comparisons.

Changes

API Spec Path Normalization and Deduplication

Layer / File(s) Summary
Workspace config normalization foundation
packages/bruno-electron/src/utils/workspace-config.js, packages/bruno-electron/tests/utils/workspace-config.spec.js
normalizeWorkspaceConfig is exported and updated to coerce config.specs to an array and derive apiSpecs as a distinct array. Tests validate coercion across malformed YAML shapes and ensure add/remove operations do not throw.
Electron consolidation and IPC normalization
packages/bruno-electron/src/app/apiSpecs.js, packages/bruno-electron/src/app/workspace-watcher.js, packages/bruno-electron/src/ipc/workspace.js
Remove local normalize implementations and import the centralized normalizeWorkspaceConfig; IPC handler now reads specs only when it's an array, avoiding non-array inputs; apiSpecs.js no longer applies local normalization before sending config to renderer.
Frontend spec matching helper
packages/bruno-app/src/components/Sidebar/ApiSpecs/matchLoadedApiSpecs.js, packages/bruno-app/src/components/Sidebar/ApiSpecs/matchLoadedApiSpecs.spec.js
New matchLoadedApiSpecs normalizes workspace path and loaded apiSpec.pathname values to match specs reliably across separators; tests cover POSIX/Windows separators, mixed separators, ordering/filtering, empty paths, and invalid inputs.
Frontend integration
packages/bruno-app/src/components/Sidebar/ApiSpecs/index.js, packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js
Sidebar now uses matchLoadedApiSpecs and treats activeWorkspace.apiSpecs as a validated array; Redux loadWorkspaceApiSpecs uses normalized path comparisons to skip already-loaded specs.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • usebruno/bruno#7104: Both PRs modify renderer:load-workspace-apispecs and related path normalization/resolution behavior.
  • usebruno/bruno#6495: Overlaps in apiSpecs.js workspace config shaping and how workspace specs are prepared for the renderer.
  • usebruno/bruno#6337: Earlier workspace API-spec handling changes that touch utils/workspace-config.js and ipc/workspace.js, related to this PR's normalization work.

Suggested labels

size/M

Suggested reviewers

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

"Paths whisper backslashes, forward slashes align,
Specs find their partners, no duplicates in line.
Configs now safe when YAML goes wild,
Tests stand guard for each malformed child.
A tiny chorus of normalized files—cheers!"

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately describes the two main fixes: preventing crashes on non-array specs and fixing Windows path-separator issues in spec listing.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

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

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (3)
packages/bruno-electron/src/app/apiSpecs.js (2)

50-50: ⚡ Quick win

Redundant fallback after normalization.

readWorkspaceConfig (line 49) already normalizes the config and ensures specs is an array, so the || [] fallback is now redundant.

♻️ Simplify by removing the redundant fallback
-    const specs = workspaceConfig.specs || [];
+    const specs = workspaceConfig.specs;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/bruno-electron/src/app/apiSpecs.js` at line 50, The assignment
"const specs = workspaceConfig.specs || [];" contains a redundant fallback
because readWorkspaceConfig already ensures workspaceConfig.specs is an array;
remove the "|| []" from the assignment so it simply reads the normalized value
(refer to workspaceConfig.specs and the readWorkspaceConfig normalization logic)
to avoid unnecessary duplication.

68-69: ⚡ Quick win

Redundant normalization call.

readWorkspaceConfig already calls normalizeWorkspaceConfig internally (line 231 in workspace-config.js), so calling it again here is redundant.

♻️ Remove the redundant normalization
     const updatedConfig = readWorkspaceConfig(options.workspacePath);
-    const normalizedConfig = normalizeWorkspaceConfig(updatedConfig);
     const workspaceUid = getWorkspaceUid(options.workspacePath);
     const isDefault = workspaceUid === 'default';
-    const configForClient = prepareWorkspaceConfigForClient(normalizedConfig, isDefault);
+    const configForClient = prepareWorkspaceConfigForClient(updatedConfig, isDefault);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/bruno-electron/src/app/apiSpecs.js` around lines 68 - 69, The code
calls normalizeWorkspaceConfig twice: readWorkspaceConfig(options.workspacePath)
already returns a normalized config, so remove the redundant
normalizeWorkspaceConfig call; replace the two lines that set updatedConfig and
normalizedConfig with a single assignment using readWorkspaceConfig (e.g., const
workspaceConfig = readWorkspaceConfig(options.workspacePath)) and update any
uses of normalizedConfig to use that single variable, ensuring references to
updatedConfig/normalizedConfig are adjusted accordingly.
packages/bruno-electron/src/ipc/workspace.js (1)

210-217: ⚡ Quick win

Duplicated coercion logic - prefer centralized utility.

This handler manually parses the YAML and applies an inline Array.isArray guard, duplicating the logic from normalizeWorkspaceConfig. For consistency and maintainability, consider using readWorkspaceConfig (which includes normalization) or at least calling normalizeWorkspaceConfig after parsing.

♻️ Use centralized normalization

Option 1 (preferred): Use readWorkspaceConfig

-    const yamlContent = fs.readFileSync(workspaceFilePath, 'utf8');
-    const workspaceConfig = yaml.load(yamlContent);
-
-    if (!workspaceConfig || typeof workspaceConfig !== 'object') {
-      return [];
-    }
-
-    const specs = Array.isArray(workspaceConfig.specs) ? workspaceConfig.specs : [];
+    const workspaceConfig = readWorkspaceConfig(workspacePath);
+    const specs = workspaceConfig.specs;

Option 2: Call normalizeWorkspaceConfig after parsing

+    const { normalizeWorkspaceConfig } = require('../utils/workspace-config');
+
     const yamlContent = fs.readFileSync(workspaceFilePath, 'utf8');
-    const workspaceConfig = yaml.load(yamlContent);
+    const rawConfig = yaml.load(yamlContent);
 
-    if (!workspaceConfig || typeof workspaceConfig !== 'object') {
+    if (!rawConfig || typeof rawConfig !== 'object') {
       return [];
     }
 
-    const specs = Array.isArray(workspaceConfig.specs) ? workspaceConfig.specs : [];
+    const workspaceConfig = normalizeWorkspaceConfig(rawConfig);
+    const specs = workspaceConfig.specs;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/bruno-electron/src/ipc/workspace.js` around lines 210 - 217, The
handler duplicates array-coercion logic when parsing the YAML; replace the
manual parse+Array.isArray flow by calling the centralized
readWorkspaceConfig(workspaceFilePath) which returns a normalized config (or, if
you must parse here, call normalizeWorkspaceConfig(workspaceConfig) immediately
after yaml.load) so specs come from the normalized object; update references to
use the returned config.specs instead of the inline coercion.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/bruno-electron/src/app/apiSpecs.js`:
- Line 50: The assignment "const specs = workspaceConfig.specs || [];" contains
a redundant fallback because readWorkspaceConfig already ensures
workspaceConfig.specs is an array; remove the "|| []" from the assignment so it
simply reads the normalized value (refer to workspaceConfig.specs and the
readWorkspaceConfig normalization logic) to avoid unnecessary duplication.
- Around line 68-69: The code calls normalizeWorkspaceConfig twice:
readWorkspaceConfig(options.workspacePath) already returns a normalized config,
so remove the redundant normalizeWorkspaceConfig call; replace the two lines
that set updatedConfig and normalizedConfig with a single assignment using
readWorkspaceConfig (e.g., const workspaceConfig =
readWorkspaceConfig(options.workspacePath)) and update any uses of
normalizedConfig to use that single variable, ensuring references to
updatedConfig/normalizedConfig are adjusted accordingly.

In `@packages/bruno-electron/src/ipc/workspace.js`:
- Around line 210-217: The handler duplicates array-coercion logic when parsing
the YAML; replace the manual parse+Array.isArray flow by calling the centralized
readWorkspaceConfig(workspaceFilePath) which returns a normalized config (or, if
you must parse here, call normalizeWorkspaceConfig(workspaceConfig) immediately
after yaml.load) so specs come from the normalized object; update references to
use the returned config.specs instead of the inline coercion.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d8666db3-353c-4533-904f-c30b57170cbc

📥 Commits

Reviewing files that changed from the base of the PR and between db195fe and 3d9bd91.

📒 Files selected for processing (9)
  • packages/bruno-app/src/components/Sidebar/ApiSpecs/index.js
  • packages/bruno-app/src/components/Sidebar/ApiSpecs/matchLoadedApiSpecs.js
  • packages/bruno-app/src/components/Sidebar/ApiSpecs/matchLoadedApiSpecs.spec.js
  • packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js
  • packages/bruno-electron/src/app/apiSpecs.js
  • packages/bruno-electron/src/app/workspace-watcher.js
  • packages/bruno-electron/src/ipc/workspace.js
  • packages/bruno-electron/src/utils/workspace-config.js
  • packages/bruno-electron/tests/utils/workspace-config.spec.js

sundram-bruno and others added 2 commits June 12, 2026 19:38
normalizeWorkspaceConfig returned `apiSpecs` as the same array reference as
`specs`. Harmless today, but write paths mutate `config.specs` in place, so a
future consumer reading `apiSpecs` after such a mutation could see it change
unexpectedly. Return a shallow copy so the two fields can't alias.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… (CodeRabbit nitpicks)

readWorkspaceConfig already returns a normalized config (specs coerced to an
array), so:
- `workspaceConfig.specs || []` no longer needs the fallback.
- re-running normalizeWorkspaceConfig on its result was a no-op double-normalize;
  use the readWorkspaceConfig result directly.

Skipped the third nitpick (route renderer:load-workspace-apispecs through
readWorkspaceConfig): that handler parses YAML directly and returns [] for a
malformed/missing file, whereas readWorkspaceConfig throws — out of scope for
this fix; its Array.isArray guard is correct standalone.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@engineering-bruno
engineering-bruno merged commit 2bc735e into usebruno:main Jun 12, 2026
17 of 19 checks passed
lohit-bruno pushed a commit that referenced this pull request Jun 15, 2026
abhishekp-bruno pushed a commit to abhishekp-bruno/bruno that referenced this pull request Jun 17, 2026
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