Skip to content

chore: add a promise based wait group for the shell variables - #7647

Merged
sid-bruno merged 4 commits into
usebruno:mainfrom
sid-bruno:fix/shell-wait-group
Apr 1, 2026
Merged

sid-bruno merged 4 commits into
usebruno:mainfrom
sid-bruno:fix/shell-wait-group

Conversation

@sid-bruno

@sid-bruno sid-bruno commented Apr 1, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Adds in a singleton promise based wait group for the shell env, so as to avoid blocking app start.

Contribution Checklist:

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

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

Publishing to New Package Managers

Please see here for more information.

Summary by CodeRabbit

  • Improvements

    • App startup no longer blocks on shell environment setup, improving launch responsiveness.
    • System proxy loading is deferred until shell environment is available to avoid startup stalls.
    • Shell environment setup now has a 60-second timeout with proper cleanup on timeout.
  • Tests

    • Added comprehensive tests covering initialization behavior, in-flight deduplication, timeout handling, and retry semantics.

Copilot AI review requested due to automatic review settings April 1, 2026 13:00
@coderabbitai

coderabbitai Bot commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors shell environment initialization into a memoized, timeout-wrapped module exported as initializeShellEnv() and waitForShellEnv(). Startup no longer awaits initialization; fetchSystemProxy() is deferred until waitForShellEnv() resolves.

Changes

Cohort / File(s) Summary
Shell Environment State
packages/bruno-electron/src/store/shell-env-state.js
New module that memoizes an in-flight initialization promise, wraps initializeShellEnv with a 60s Promise.race timeout, exposes fire-and-forget initializeShellEnv() and awaitable waitForShellEnv().
App Startup Flow
packages/bruno-electron/src/index.js
Removed awaiting initializeShellEnv() in app.on('ready'); now calls initializeShellEnv() non-blocking and defers fetchSystemProxy() inside waitForShellEnv().then(...).catch(...).
Tests
packages/bruno-electron/src/store/tests/shell-env-state.spec.js
Adds Jest suite verifying memoization, promise reuse, resolution/rejection propagation, 60s timeout behavior, timeout cleanup and retry semantics.

Sequence Diagram

sequenceDiagram
    participant App as App (ready)
    participant ShellEnv as Shell Env Module
    participant Init as initializeShellEnv<br/>(`@usebruno/requests`)
    participant SysProxy as SystemProxy

    App->>ShellEnv: initializeShellEnv() (fire-and-forget)
    ShellEnv->>ShellEnv: start _promise = Promise.race([Init, 60s timeout])
    ShellEnv-->>App: returns undefined

    App->>ShellEnv: waitForShellEnv()
    ShellEnv-->>App: returns _promise

    App->>ShellEnv: on _promise.then() -> fetchSystemProxy()
    activate Init
    Init-->>ShellEnv: resolves/rejects
    deactivate Init

    ShellEnv->>ShellEnv: clear timeout on resolve
    SysProxy-->>App: cache initialized (after shell env ready)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Suggested labels

size/M

Suggested reviewers

  • helloanoop
  • naman-bruno

Poem

A promise set to race the clock, not bind the start,
Fire-and-forget begins the shell's slow art,
Sixty ticks to settle, then proxies come through,
Startup hums along while the quiet task grew 🚀

🚥 Pre-merge checks | ✅ 3
✅ 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 accurately describes the main change: introducing a promise-based mechanism (wait group) for shell environment initialization.
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

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.

Copilot AI 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.

Pull request overview

Adds a shared, promise-backed “wait group” for shell environment initialization in the Electron app so startup can kick off shell env loading without awaiting it, while still allowing specific operations to wait until it’s settled.

Changes:

  • Added shell-env-state module to memoize the in-flight shell env initialization promise and expose a wait helper.
  • Updated Electron startup to trigger shell env initialization without blocking app.on('ready').
  • Deferred fetchSystemProxy() until the shell env initialization promise settles.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
packages/bruno-electron/src/store/shell-env-state.js Introduces a module-level singleton promise to coordinate shell env initialization and waiting.
packages/bruno-electron/src/index.js Switches startup to fire-and-forget shell env init and gates system proxy warmup on shell env readiness.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@pull-request-size pull-request-size Bot added size/M and removed size/S labels Apr 1, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/bruno-electron/src/store/tests/shell-env-state.spec.js (1)

41-43: Remove redundant in-test re-requires for clarity.

At Line 42 and Line 62, re-requiring ../shell-env-state is unnecessary in this setup and makes the tests harder to follow. waitForShellEnv is already loaded in beforeEach, and reassigning mockInitialize is sufficient before first invocation.

Suggested cleanup
    it('resolves when the underlying promise resolves', async () => {
      mockInitialize = jest.fn(() => Promise.resolve('shell-ready'));
-      ({ waitForShellEnv } = require('../shell-env-state'));
 
      await expect(waitForShellEnv()).resolves.toBe('shell-ready');
    });
...
    it('propagates rejection from the underlying initializer', async () => {
      const err = new Error('shell init failed');
      mockInitialize = jest.fn(() => Promise.reject(err));
-      ({ waitForShellEnv } = require('../shell-env-state'));
 
      await expect(waitForShellEnv()).rejects.toThrow('shell init failed');
    });

As per coding guidelines: "Keep tests readable and maintainable. Optimise for clarity over cleverness."

Also applies to: 61-63

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

In `@packages/bruno-electron/src/store/tests/shell-env-state.spec.js` around lines
41 - 43, Tests re-require '../shell-env-state' inside individual tests which is
redundant because waitForShellEnv is already imported in beforeEach; remove the
in-test re-requires and instead just reset/mock mockInitialize before invoking
waitForShellEnv so tests use the originally required waitForShellEnv; update
occurrences around mockInitialize and waitForShellEnv (the
require('../shell-env-state') lines at ~Line 42 and ~Line 62) to be removed and
ensure beforeEach sets up mockInitialize and imports waitForShellEnv once.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/bruno-electron/src/store/tests/shell-env-state.spec.js`:
- Around line 41-43: Tests re-require '../shell-env-state' inside individual
tests which is redundant because waitForShellEnv is already imported in
beforeEach; remove the in-test re-requires and instead just reset/mock
mockInitialize before invoking waitForShellEnv so tests use the originally
required waitForShellEnv; update occurrences around mockInitialize and
waitForShellEnv (the require('../shell-env-state') lines at ~Line 42 and ~Line
62) to be removed and ensure beforeEach sets up mockInitialize and imports
waitForShellEnv once.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6e2da5c5-0c3a-4f74-a331-fb0f665721ef

📥 Commits

Reviewing files that changed from the base of the PR and between 8d8b98b and 1a76d8f.

📒 Files selected for processing (1)
  • packages/bruno-electron/src/store/tests/shell-env-state.spec.js

@pull-request-size pull-request-size Bot added size/L and removed size/M labels Apr 1, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
packages/bruno-electron/src/store/tests/shell-env-state.spec.js (2)

17-26: Seven calls is overkill to prove "exactly once" behavior.

Two or three invocations suffice to demonstrate memoization. Reducing this keeps the test concise.

🔧 Suggested simplification
     it('calls the underlying initializer exactly once on first call', () => {
       initializeShellEnv();
       initializeShellEnv();
       initializeShellEnv();
-      initializeShellEnv();
-      initializeShellEnv();
-      initializeShellEnv();
-      initializeShellEnv();
       expect(mockInitialize).toHaveBeenCalledTimes(1);
     });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-electron/src/store/tests/shell-env-state.spec.js` around lines
17 - 26, Test uses seven repeated calls to initializeShellEnv to assert
memoization; reduce to two or three calls to prove "exactly once" behavior.
Update the spec in shell-env-state.spec.js to call initializeShellEnv only 2-3
times before asserting expect(mockInitialize).toHaveBeenCalledTimes(1), keeping
mockInitialize as the referenced mock to verify the initializer was invoked
once.

69-77: Redundant require — module is already loaded by outer beforeEach.

Since the outer beforeEach calls jest.resetModules() and then requires the module, line 71's require returns the cached instance. The reassignment of mockInitialize on line 70 is sufficient because the mock uses a closure. Keeping the require isn't harmful, but it's misleading and can be removed for clarity.

🧹 Cleaner version
       it('rejects after 60 seconds', async () => {
         mockInitialize = jest.fn(() => new Promise(() => {})); // never resolves
-        ({ waitForShellEnv } = require('../shell-env-state'));

         const p = waitForShellEnv();
         jest.advanceTimersByTime(60_000);

         await expect(p).rejects.toThrow('Shell environment initialization timed out');
       });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-electron/src/store/tests/shell-env-state.spec.js` around lines
69 - 77, Remove the redundant require call inside the test: since the outer
beforeEach already calls jest.resetModules() and requires the module, simply
rely on reassigning mockInitialize (the closure used by the module) and call
waitForShellEnv (from the module-scoped binding) without re-requiring; update
the test that currently does "({ waitForShellEnv } =
require('../shell-env-state'))" to use the existing waitForShellEnv reference
and keep mockInitialize assignment as-is to avoid confusion and clarify intent.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/bruno-electron/src/store/tests/shell-env-state.spec.js`:
- Around line 17-26: Test uses seven repeated calls to initializeShellEnv to
assert memoization; reduce to two or three calls to prove "exactly once"
behavior. Update the spec in shell-env-state.spec.js to call initializeShellEnv
only 2-3 times before asserting expect(mockInitialize).toHaveBeenCalledTimes(1),
keeping mockInitialize as the referenced mock to verify the initializer was
invoked once.
- Around line 69-77: Remove the redundant require call inside the test: since
the outer beforeEach already calls jest.resetModules() and requires the module,
simply rely on reassigning mockInitialize (the closure used by the module) and
call waitForShellEnv (from the module-scoped binding) without re-requiring;
update the test that currently does "({ waitForShellEnv } =
require('../shell-env-state'))" to use the existing waitForShellEnv reference
and keep mockInitialize assignment as-is to avoid confusion and clarify intent.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3ef6e43b-b9a1-4b16-8138-908675d3832b

📥 Commits

Reviewing files that changed from the base of the PR and between 56c35c2 and 8e6c699.

📒 Files selected for processing (1)
  • packages/bruno-electron/src/store/tests/shell-env-state.spec.js

@sid-bruno
sid-bruno merged commit 87ca5a8 into usebruno:main Apr 1, 2026
10 checks passed
lohit-bruno pushed a commit to lohit-bruno/bruno that referenced this pull request Apr 1, 2026
maxenceleblanc pushed a commit to maxenceleblanc/curly_cats2 that referenced this pull request Jul 20, 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