Skip to content

fix(system proxy): app needs restart to fetch system proxy when set from terminal - #8159

Closed
abhishekp-bruno wants to merge 14 commits into
usebruno:mainfrom
abhishekp-bruno:fix(system-proxy)app-needs-restart-to-fetch-system-proxy
Closed

abhishekp-bruno wants to merge 14 commits into
usebruno:mainfrom
abhishekp-bruno:fix(system-proxy)app-needs-restart-to-fetch-system-proxy

Conversation

@abhishekp-bruno

@abhishekp-bruno abhishekp-bruno commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

JIRA Link - https://usebruno.atlassian.net/browse/BRU-3202

Fixes: #7559

Description

When users configured proxy settings via shell environment variables (e.g. http_proxy, https_proxy in .zshrc/.bashrc), Bruno would only pick them up at startup. Changing or removing those exports in the terminal had no effect until the app was fully restarted — the cached process.env proxy values went
stale, and the "refresh" path never re-read the shell.

Fix

Added refreshShellEnvProxyVars() in bruno-requests, which re-syncs proxy-related variables from the user's login shell on demand:

  • Clears stale proxy vars first (delete process.env[key]) before spawning the login shell, so a removed export in .zshrc doesn't persie subprocess.
  • Re-fetches the shell environment and re-applies any proxy values that are still set.
  • Covers the full set of proxy keys: http_proxy/HTTP_PROXY, https_proxy/HTTPS_PROXY, no_proxy/NO_PROXY, all_proxy/ALL_PROXY.

Wired this into the Electron system-proxy store: fetchSystemProxy({ refresh: true }) now passes refreshShellEnv: true down to `loadSystemP re-reads the terminal environment rather than serving cached values.

Changes

  • packages/bruno-requests/src/utils/shell-env.ts — new refreshShellEnvProxyVars() + exported PROXY_ENV_KEYS.
  • packages/bruno-requests/src/index.ts — export the new function.
  • packages/bruno-electron/src/store/system-proxy.js — refresh shell env on proxy refresh.

Testing

Added unit tests covering the refresh behavior (re-syncing updated vars and clearing removed vars).

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

    • System proxy reloads can now refresh shell environment proxy variables first, ensuring proxy settings stay in sync across the app.
    • Reload behavior now aligns with the existing “refresh” toggle, updating cached proxy values consistently.
  • Public API

    • Exposed a capability to refresh shell-environment proxy variables programmatically.
    • Added a shared list of supported proxy environment variable keys.
  • Tests

    • Added Jest coverage to verify proxy env var updates, removal when absent, and cleanup of stale lowercase/uppercase proxy variables.

@coderabbitai

coderabbitai Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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

Adds PROXY_ENV_KEYS and refreshShellEnvProxyVars(), tests them, re-exports the utility from bruno-requests, and wires optional shell-env proxy var refresh into Electron's system-proxy reload flow.

Changes

Shell Proxy Environment Refresh Integration

Layer / File(s) Summary
Proxy environment refresh utility
packages/bruno-requests/src/utils/shell-env.ts
Exports PROXY_ENV_KEYS constant and refreshShellEnvProxyVars() which clears proxy env keys from process.env, fetches shell env via fetchShellEnv(), sets truthy proxy keys, and returns the fetched env.
Utility tests
packages/bruno-requests/src/utils/shell-env.spec.ts
Adds Jest suite with afterEach cleanup for lowercase and uppercase proxy vars; tests updating vars from shell config, removing absent vars, and clearing stale vars when shell config is empty.
Package export and Electron integration
packages/bruno-requests/src/index.ts, packages/bruno-electron/src/store/system-proxy.js
Re-exports refreshShellEnvProxyVars from bruno-requests index; loadSystemProxy accepts { refreshShellEnv } and conditionally awaits refreshShellEnvProxyVars() before initializing cached proxy; fetchSystemProxy forwards its refresh flag to that call.

Sequence Diagram

sequenceDiagram
  participant ElectronStore as Electron fetchSystemProxy
  participant LoadProxy as loadSystemProxy()
  participant RefreshUtil as refreshShellEnvProxyVars()
  participant ProcessEnv as process.env
  participant GetSystemProxy as getSystemProxy()
  ElectronStore->>LoadProxy: call with {refreshShellEnv}
  alt refreshShellEnv true
    LoadProxy->>RefreshUtil: await refreshShellEnvProxyVars()
    RefreshUtil->>ProcessEnv: sync proxy keys
    RefreshUtil-->>LoadProxy: return shell env
  end
  LoadProxy->>GetSystemProxy: fetch system proxy
  GetSystemProxy-->>LoadProxy: return proxy config
  LoadProxy-->>ElectronStore: cache and return
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

  • usebruno/bruno#6990: Introduces cached system-proxy/refresh plumbing in packages/bruno-electron/src/store/system-proxy.js; this PR extends that same module's reload logic by adding refreshShellEnv to loadSystemProxy.
  • usebruno/bruno#7264: Also modifies packages/bruno-electron/src/store/system-proxy.js around loadSystemProxy/fetchSystemProxy and the cached async initialization flow.
  • usebruno/bruno#7652: Changes the Electron system-proxy fetching flow around fetchSystemProxy/system proxy reloads when shell-env initialization is involved.

Suggested reviewers

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

Poem

✨ A tiny refresh, the proxy sings,
Env keys swept like fallen things.
Shell's whispers set in process light,
No stale routes left to haunt the night. 🧭

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main fix: refreshing system proxy settings set from the terminal without restarting the app.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

Review ran into problems

🔥 Problems

Stopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a @coderabbit review after the pipeline has finished.


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.

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/bruno-requests/src/utils/shell-env.ts (1)

20-33: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Asymmetric error handling between Windows and Unix paths.

The win32 branch returns fetchWindowsShellEnv() outside the try/catch, whereas the Unix path swallows failures and returns {}. If the Windows registry fetch throws, it propagates into both initializeShellEnv() (startup) and refreshShellEnvProxyVars(), instead of degrading gracefully like the Unix path. Consider wrapping the Windows branch too.

🛡️ Proposed fix
 const fetchShellEnv = async (): Promise<Record<string, string>> => {
-  if (process.platform === 'win32') {
-    return fetchWindowsShellEnv();
-  }
-
   try {
+    if (process.platform === 'win32') {
+      return await fetchWindowsShellEnv();
+    }
     // shell-env is ESM-only, so we use dynamic import
     const { shellEnv } = await import('shell-env');
     const env = await shellEnv();
     return env;
   } catch (error) {
     return {};
   }
 };
🤖 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-requests/src/utils/shell-env.ts` around lines 20 - 33,
fetchShellEnv currently calls fetchWindowsShellEnv() outside the try/catch so
Windows errors propagate while Unix errors are swallowed; modify fetchShellEnv
to wrap the Windows branch in the same try/catch (or surround the
fetchWindowsShellEnv() call with its own try/catch) so any thrown error is
caught and the function returns an empty {} like the Unix path, ensuring callers
such as initializeShellEnv and refreshShellEnvProxyVars degrade gracefully.
🧹 Nitpick comments (1)
packages/bruno-requests/src/utils/shell-env-windows.ts (1)

34-37: 💤 Low value

Heads-up: case-sensitive lookup vs case-insensitive Windows env names.

%VAR% resolution uses expanded[name] with exact casing. Registry value names usually match (%SystemRoot%, %USERPROFILE%), and the process.env[name] fallback is case-insensitive on Windows, so this mostly works — but a %path% reference against a Path key would skip the local map and only resolve via process.env. Acceptable for now; calling it out in case mixed-case configs surface.

🤖 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-requests/src/utils/shell-env-windows.ts` around lines 34 - 37,
The replacement currently looks up expanded[name] with exact casing which can
miss Windows env keys with different case (e.g., '%path%' vs 'Path'); update the
lookup inside the RegExp replacer in the loop over expanded so it performs a
case-insensitive lookup: derive a normalized key (e.g., lowercased name) and
check expanded for that normalized key before falling back to process.env (and
optionally check process.env with the same normalization), ensuring references
like '%path%' resolve against expanded and process.env regardless of casing;
update any creation of expanded to also populate a lowercase-key map or perform
normalized lookups when accessing expanded and process.env.
🤖 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.

Outside diff comments:
In `@packages/bruno-requests/src/utils/shell-env.ts`:
- Around line 20-33: fetchShellEnv currently calls fetchWindowsShellEnv()
outside the try/catch so Windows errors propagate while Unix errors are
swallowed; modify fetchShellEnv to wrap the Windows branch in the same try/catch
(or surround the fetchWindowsShellEnv() call with its own try/catch) so any
thrown error is caught and the function returns an empty {} like the Unix path,
ensuring callers such as initializeShellEnv and refreshShellEnvProxyVars degrade
gracefully.

---

Nitpick comments:
In `@packages/bruno-requests/src/utils/shell-env-windows.ts`:
- Around line 34-37: The replacement currently looks up expanded[name] with
exact casing which can miss Windows env keys with different case (e.g., '%path%'
vs 'Path'); update the lookup inside the RegExp replacer in the loop over
expanded so it performs a case-insensitive lookup: derive a normalized key
(e.g., lowercased name) and check expanded for that normalized key before
falling back to process.env (and optionally check process.env with the same
normalization), ensuring references like '%path%' resolve against expanded and
process.env regardless of casing; update any creation of expanded to also
populate a lowercase-key map or perform normalized lookups when accessing
expanded and process.env.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 65e8826c-f110-4f55-83d9-0ba4b743159d

📥 Commits

Reviewing files that changed from the base of the PR and between 5a7fde2 and ee42913.

📒 Files selected for processing (3)
  • packages/bruno-requests/src/utils/shell-env-windows.ts
  • packages/bruno-requests/src/utils/shell-env.spec.ts
  • packages/bruno-requests/src/utils/shell-env.ts
💤 Files with no reviewable changes (1)
  • packages/bruno-requests/src/utils/shell-env.spec.ts

Comment thread package-lock.json Outdated
"version": "7.26.3",
"resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.26.3.tgz",
"integrity": "sha512-G7ZRb40uUgdKOQqPLjfD12ZmGA54PzqDFUv2BKImnC9QIfGhIHKvVML0oN8IUiDq4iRqpq74ABpvOaerfWdong==",
"devOptional": true,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

rm these changes

if (value) {
process.env[key] = value;
} else {
delete process.env[key];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

the delete seems to be redundant, we are already deleting them above,if block will be enough!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

REMOVED

@abhishekp-bruno
abhishekp-bruno force-pushed the fix(system-proxy)app-needs-restart-to-fetch-system-proxy branch from e9417ee to 502027f Compare June 24, 2026 11:24
lohit-bruno
lohit-bruno previously approved these changes Jun 24, 2026
@abhishekp-bruno
abhishekp-bruno force-pushed the fix(system-proxy)app-needs-restart-to-fetch-system-proxy branch from 502027f to 442e75f Compare June 29, 2026 09:51
@sid-bruno sid-bruno changed the title Fix(system proxy):app needs restart to fetch system proxy when set from terminal fix(system proxy): app needs restart to fetch system proxy when set from terminal Jun 30, 2026
@pull-request-size pull-request-size Bot added size/XL and removed size/L labels Jul 1, 2026
@abhishekp-bruno
abhishekp-bruno force-pushed the fix(system-proxy)app-needs-restart-to-fetch-system-proxy branch from a3898fb to 5fa6785 Compare July 2, 2026 08:07
@abhishekp-bruno
abhishekp-bruno force-pushed the fix(system-proxy)app-needs-restart-to-fetch-system-proxy branch 2 times, most recently from f3cecf1 to 46d23e9 Compare July 6, 2026 14:07

// Clear stale proxy vars first so shell-env does not inherit them into the
// login shell subprocess (removed .zshrc exports would otherwise persist).
for (const key of PROXY_ENV_KEYS) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Since we are actually deleting all the PROXY_ENVs here, then calling the fetchShellEnv, if any error the happens in fetchShellEnv, as it returns {} within the catch, refresh will remove all the existing values. Edge case, but something to be mindful about. @abhishekp-bruno cc: @vijayh-bruno

something like this can work, may also need to update the failing test accordingly

  // New helper that surfaces failure. Keep fetchShellEnv as-is for initializeShellEnv's additive path.
  const tryFetchShellEnv = async (): Promise<Record<string, string> | null> => {
    if (process.platform === 'win32') return {};
    try {
      const { shellEnv } = await import('shell-env');
      return await shellEnv();
    } catch {
      return null;
    }
  };

  export const refreshShellEnvProxyVars = async (): Promise<Record<string, string>> => {
    if (process.platform === 'win32') return {};

    const snapshot: Record<string, string | undefined> = {};
    for (const key of PROXY_ENV_KEYS) {
      snapshot[key] = process.env[key];
      delete process.env[key];
    }

    const shellEnvVars = await tryFetchShellEnv();

    if (shellEnvVars === null) {
      // Subprocess failed — restore prior values rather than leave the user unproxied.
      for (const key of PROXY_ENV_KEYS) {
        if (snapshot[key] !== undefined) process.env[key] = snapshot[key];
      }
      return {};
    }

    for (const key of PROXY_ENV_KEYS) {
      const value = shellEnvVars[key];
      if (value) process.env[key] = value;
    }
    return shellEnvVars;
  };

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@abhishekp-bruno this is still valid in a situation where the race function causes this one to just be left in the timeout, we'll end up with a partial snapshot which isn't something we want.

Needs to be addressed.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I have updated the code to handle the race condition inside the function itself

@sid-bruno sid-bruno Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Timeout shouldn't be in bruno-requests, it shouldn't be holding business and rate limiting in here but should be in the app / cli layer only. you can just move the delete logic to be run after fetching has finished instead.

The rest looks good, let me discuss with @bijin-bruno and get back

vijayh-bruno
vijayh-bruno previously approved these changes Jul 6, 2026
@vijayh-bruno
vijayh-bruno requested a review from bijin-bruno July 6, 2026 19:37
@abhishekp-bruno
abhishekp-bruno force-pushed the fix(system-proxy)app-needs-restart-to-fetch-system-proxy branch 2 times, most recently from 07e41cd to 7f7a0c7 Compare July 7, 2026 12:34
@abhishekp-bruno
abhishekp-bruno force-pushed the fix(system-proxy)app-needs-restart-to-fetch-system-proxy branch from 7f7a0c7 to c752f79 Compare July 8, 2026 05:54
@abhishekp-bruno
abhishekp-bruno force-pushed the fix(system-proxy)app-needs-restart-to-fetch-system-proxy branch from 036c530 to 05a779b Compare July 8, 2026 12:07
@sid-bruno sid-bruno mentioned this pull request Jul 8, 2026
6 tasks
@bijin-bruno

Copy link
Copy Markdown
Collaborator

Closed as merged via #8535

@bijin-bruno bijin-bruno closed this Jul 8, 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.

System proxy changes require app restart to take effect

7 participants