Skip to content

fix: close previous SSE connection before sending new request - #7474

Merged
bijin-bruno merged 5 commits into
usebruno:mainfrom
chirag-bruno:fix/sse-close-previous-connection-on-resend
Apr 2, 2026
Merged

bijin-bruno merged 5 commits into
usebruno:mainfrom
chirag-bruno:fix/sse-close-previous-connection-on-resend

Conversation

@chirag-bruno

@chirag-bruno chirag-bruno commented Mar 13, 2026 •

Copy link
Copy Markdown
Collaborator

Description

When resending an SSE (Server-Sent Events) request using Cmd+Enter, the previous connection was not being closed, causing connection leaks.

Changes:

  • Add SSE cancellation logic to sendRequest action - checks for running stream and cancels it before sending new request
  • Add return to cancelRequest action to make it properly chainable
  • Simplify RequestTabPanel by removing duplicate cancel logic (now handled centrally in sendRequest)
  • Add SSE endpoints to test server for e2e testing
  • Add Playwright e2e test to verify SSE connection cancellation

Fixes: #7353
JIRA: https://usebruno.atlassian.net/browse/BRU-2860

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

  • New Features

    • Added local Server-Sent Events (SSE) test service with stream, connections, and reset endpoints.
    • Updated run control to avoid dispatching duplicate sends for requests already sending or queued.
  • Bug Fixes

    • Await cancellation of active SSE streams before starting a new run to prevent duplicate connections.
  • Tests

    • Added end-to-end tests, fixtures, and test preferences validating SSE connection cancellation.

@coderabbitai

coderabbitai Bot commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

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: bec411ac-bd53-45ca-a604-d2ded7100b91

📥 Commits

Reviewing files that changed from the base of the PR and between 2b1ccee and 0a34494.

📒 Files selected for processing (1)
  • tests/sse/sse-cancellation.spec.ts
✅ Files skipped from review due to trivial changes (1)
  • tests/sse/sse-cancellation.spec.ts

Walkthrough

Pre-flight SSE cancellation was moved into Redux actions: sendRequest now awaits cancelRequest when an item's SSE stream is running. The UI no longer invokes cancelRequest directly. Added a local test SSE server, fixtures, and a Playwright spec verifying previous connections are closed when re-sending.

Changes

Cohort / File(s) Summary
Request execution & cancellation
packages/bruno-app/src/components/RequestTabPanel/index.js, packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js
Removed UI-level cancelRequest call; sendRequest now detects item.response?.stream?.running and item.cancelTokenUid and awaits cancelRequest(...) before opening a new request. cancelRequest now returns the cancelNetworkRequest promise.
Test SSE server integration
packages/bruno-tests/src/index.js, packages/bruno-tests/src/sse/index.js
Added an Express SSE router mounted at /api/sse providing GET /stream, GET /connections, and POST /reset; streams events every 500ms and tracks active connections.
Test fixtures & preferences
tests/sse/fixtures/collection/bruno.json, tests/sse/fixtures/collection/sse-stream-request.bru, tests/sse/init-user-data/preferences.json
Added a collection fixture, an SSE GET request fixture that targets the test SSE server, and test preferences to initialize the environment.
Playwright test for SSE cancellation
tests/sse/sse-cancellation.spec.ts
New e2e test that resets server state, sends an SSE request, re-sends it, and asserts the previous connection was closed (only the new connection remains).

Sequence Diagram(s)

sequenceDiagram
  participant UI as Client UI
  participant Redux as Redux actions
  participant Net as cancelNetworkRequest
  participant Server as SSE Server

  UI->>Redux: sendRequest(item, collectionId)
  Redux->>Redux: if item.response?.stream?.running && item.cancelTokenUid
  Redux->>Net: cancelNetworkRequest(cancelTokenUid)
  Net-->>Redux: cancellation resolved
  Redux->>Server: open new SSE connection (HTTP GET /stream)
  Server-->>Redux: SSE events (stream)
  Redux-->>UI: dispatch response events / updates
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Suggested reviewers

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

Poem

🌊 Streams once multiplied in rows,
Orphaned echoes nobody chose.
Cancel first, then open new,
Single current — fresh and true.
Tests hum softly, connections few.

🚥 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 title accurately summarizes the main change: closing previous SSE connections before sending new requests, which directly addresses the primary objective.
Linked Issues check ✅ Passed All code changes implement the core requirement from #7353: canceling active SSE streams before new requests, with test fixtures and e2e validation confirming the fix works.
Out of Scope Changes check ✅ Passed All changes are scoped to SSE cancellation: middleware integration, Redux action updates, UI simplification, test infrastructure, and e2e testing—no unrelated modifications detected.
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.

@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

🧹 Nitpick comments (2)
tests/sse/sse-cancellation.spec.ts (2)

9-33: Consider using test.step for better test report readability.

Per guidelines, test.step is encouraged for clearer generated reports:

♻️ Example structure
test('should close previous SSE connection when resending request', async ({ pageWithUserData: page }) => {
  await test.step('Open SSE request', async () => {
    await page.locator('#sidebar-collection-name').click();
    await page.getByTestId('sidebar-collection-item-row').filter({ hasText: 'sse-stream-request' }).click();
  });

  await test.step('Send initial request and verify connection', async () => {
    await page.getByTestId('send-arrow-icon').waitFor({ state: 'visible' });
    await page.getByTestId('send-arrow-icon').click();
    // ... polling assertion
  });

  await test.step('Resend and verify old connection is closed', async () => {
    // ... resend and final assertion
  });
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/sse/sse-cancellation.spec.ts` around lines 9 - 33, Wrap the test body
of "should close previous SSE connection when resending request" in explicit
test.step blocks to improve report readability: create a step "Open SSE request"
that performs the sidebar click and selection using page.locator and
page.getByTestId('sidebar-collection-item-row'), a step "Send initial request
and verify connection" that waits for and clicks getByTestId('send-arrow-icon'),
polls the connections endpoint via
page.request.get('http://localhost:8081/api/sse/connections') and asserts
initialData.activeConnections, and a step "Resend and verify old connection is
closed" that uses page.keyboard.press('Meta+Enter'), re-checks the connections
endpoint and asserts finalData.activeConnections; keep the existing
waits/timeouts and assertions but move their code into these named test.step
blocks.

18-22: Replace fixed timeouts with polling for more reliable tests.

Per coding guidelines, waitForTimeout should be avoided unless absolutely necessary. Consider polling the /api/sse/connections endpoint until the expected state is reached:

♻️ Suggested approach
-    await page.waitForTimeout(1000);
-
-    const initialResponse = await page.request.get('http://localhost:8081/api/sse/connections');
-    const initialData = await initialResponse.json();
-    expect(initialData.activeConnections).toBe(1);
+    await expect.poll(async () => {
+      const response = await page.request.get('http://localhost:8081/api/sse/connections');
+      const data = await response.json();
+      return data.activeConnections;
+    }, { timeout: 5000 }).toBe(1);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/sse/sse-cancellation.spec.ts` around lines 18 - 22, The test currently
uses page.waitForTimeout(1000) which is brittle; replace it by polling the
/api/sse/connections endpoint (the same request used via page.request.get) in a
loop until initialData.activeConnections === 1 or a short overall timeout
elapses; use a small interval between polls and fail the test if the timeout is
reached. Update the snippet that creates initialResponse/initialData to perform
the polling logic (checking activeConnections) instead of the fixed sleep so the
expectation assert runs only after the endpoint reports the expected state.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/sse/sse-cancellation.spec.ts`:
- Around line 24-26: The test uses a macOS-only modifier string 'Meta+Enter' in
the page.keyboard.press call; replace that with Playwright's platform-agnostic
modifier 'Mod+Enter' (i.e., change the invocation that contains
"page.keyboard.press('Meta+Enter')" to "page.keyboard.press('Mod+Enter')") so
the keyboard shortcut works across macOS, Windows and Linux.

---

Nitpick comments:
In `@tests/sse/sse-cancellation.spec.ts`:
- Around line 9-33: Wrap the test body of "should close previous SSE connection
when resending request" in explicit test.step blocks to improve report
readability: create a step "Open SSE request" that performs the sidebar click
and selection using page.locator and
page.getByTestId('sidebar-collection-item-row'), a step "Send initial request
and verify connection" that waits for and clicks getByTestId('send-arrow-icon'),
polls the connections endpoint via
page.request.get('http://localhost:8081/api/sse/connections') and asserts
initialData.activeConnections, and a step "Resend and verify old connection is
closed" that uses page.keyboard.press('Meta+Enter'), re-checks the connections
endpoint and asserts finalData.activeConnections; keep the existing
waits/timeouts and assertions but move their code into these named test.step
blocks.
- Around line 18-22: The test currently uses page.waitForTimeout(1000) which is
brittle; replace it by polling the /api/sse/connections endpoint (the same
request used via page.request.get) in a loop until initialData.activeConnections
=== 1 or a short overall timeout elapses; use a small interval between polls and
fail the test if the timeout is reached. Update the snippet that creates
initialResponse/initialData to perform the polling logic (checking
activeConnections) instead of the fixed sleep so the expectation assert runs
only after the endpoint reports the expected state.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 894e3a65-2338-4af8-845a-b3b9e11ebb9e

📥 Commits

Reviewing files that changed from the base of the PR and between ab8a730 and 28591a9.

📒 Files selected for processing (8)
  • packages/bruno-app/src/components/RequestTabPanel/index.js
  • packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js
  • packages/bruno-tests/src/index.js
  • packages/bruno-tests/src/sse/index.js
  • tests/sse/fixtures/collection/bruno.json
  • tests/sse/fixtures/collection/sse-stream-request.bru
  • tests/sse/init-user-data/preferences.json
  • tests/sse/sse-cancellation.spec.ts

Comment thread tests/sse/sse-cancellation.spec.ts Outdated
Comment on lines +24 to +26
// Press Cmd+Enter to resend the request (this should cancel the old connection and start a new one)
await page.keyboard.press('Meta+Enter');
await page.waitForTimeout(1500);

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.

⚠️ Potential issue | 🟡 Minor

Use platform-agnostic modifier for cross-platform compatibility.

Meta+Enter only works on macOS. Bruno is a cross-platform Electron app (macOS, Windows, Linux). Use Playwright's platform-aware modifier:

♻️ Proposed fix
-    await page.keyboard.press('Meta+Enter');
-    await page.waitForTimeout(1500);
+    const modifier = process.platform === 'darwin' ? 'Meta' : 'Control';
+    await page.keyboard.press(`${modifier}+Enter`);
+
+    await expect.poll(async () => {
+      const response = await page.request.get('http://localhost:8081/api/sse/connections');
+      const data = await response.json();
+      return data.activeConnections;
+    }, { timeout: 5000 }).toBe(1);

As per coding guidelines: "Ensure that all code is OS-agnostic."

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Press Cmd+Enter to resend the request (this should cancel the old connection and start a new one)
await page.keyboard.press('Meta+Enter');
await page.waitForTimeout(1500);
// Press Cmd+Enter to resend the request (this should cancel the old connection and start a new one)
const modifier = process.platform === 'darwin' ? 'Meta' : 'Control';
await page.keyboard.press(`${modifier}+Enter`);
await expect.poll(async () => {
const response = await page.request.get('http://localhost:8081/api/sse/connections');
const data = await response.json();
return data.activeConnections;
}, { timeout: 5000 }).toBe(1);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/sse/sse-cancellation.spec.ts` around lines 24 - 26, The test uses a
macOS-only modifier string 'Meta+Enter' in the page.keyboard.press call; replace
that with Playwright's platform-agnostic modifier 'Mod+Enter' (i.e., change the
invocation that contains "page.keyboard.press('Meta+Enter')" to
"page.keyboard.press('Mod+Enter')") so the keyboard shortcut works across macOS,
Windows and Linux.

@sanish-bruno sanish-bruno left a comment

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.

PR Review

Found 3 issue(s): 0 major, 2 minor, 1 nit.

Summary

  • The core fix is well-designed: moving SSE cancel-before-resend logic into sendRequest centralizes the concern and eliminates the need for the caller to handle it. The return addition to cancelRequest is a good fix.
  • The SSE test server and e2e test are well-structured with proper cleanup via the /reset endpoint.
  • Two issues in the test and one minor dead-code issue in the action.

Comment thread tests/sse/sse-cancellation.spec.ts Resolved
Comment thread tests/sse/sse-cancellation.spec.ts Resolved

@sanish-bruno sanish-bruno left a comment

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.

please rebase with main, also check why CLI tests are failing

sid-bruno and others added 2 commits April 1, 2026 23:23
* fix: update system proxy fetching to use finally for improved reliability

* Update packages/bruno-electron/src/index.js

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

---------

Co-authored-by: Copilot <[email protected]>
@chirag-bruno
chirag-bruno force-pushed the fix/sse-close-previous-connection-on-resend branch from 28591a9 to aa3dd80 Compare April 2, 2026 06:47

@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-app/src/components/RequestTabPanel/index.js (1)

301-306: ⚠️ Potential issue | 🟡 Minor

Remove unused err parameter in catch handler.

The err parameter is never referenced. Change to empty parentheses or use _ prefix to signal intentional discard:

Suggested fix
-    if (item.requestState !== 'sending' && item.requestState !== 'queued') {
-      dispatch(sendRequest(item, collection.uid)).catch((err) =>
+    if (item.requestState !== 'sending' && item.requestState !== 'queued') {
+      dispatch(sendRequest(item, collection.uid)).catch(() =>
         toast.custom((t) => <NetworkError onClose={() => toast.dismiss(t.id)} />, {
           duration: 5000
         }));
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-app/src/components/RequestTabPanel/index.js` around lines 301
- 306, The catch handler for the dispatch(sendRequest(item, collection.uid))
call declares an unused err parameter; update the arrow function to drop the
unused param (use () => ...) or rename to a discard like (_err) => to signal
intentional ignore, leaving the existing toast.custom(NetworkError...) behavior
intact; locate this in the block that checks item.requestState and calls
dispatch/sendRequest and toast.custom/NetworkError.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@packages/bruno-app/src/components/RequestTabPanel/index.js`:
- Around line 301-306: The catch handler for the dispatch(sendRequest(item,
collection.uid)) call declares an unused err parameter; update the arrow
function to drop the unused param (use () => ...) or rename to a discard like
(_err) => to signal intentional ignore, leaving the existing
toast.custom(NetworkError...) behavior intact; locate this in the block that
checks item.requestState and calls dispatch/sendRequest and
toast.custom/NetworkError.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 87beeeb3-65e9-4eba-9760-08f75543ac2e

📥 Commits

Reviewing files that changed from the base of the PR and between 28591a9 and aa3dd80.

📒 Files selected for processing (2)
  • packages/bruno-app/src/components/RequestTabPanel/index.js
  • packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js

@sanish-bruno sanish-bruno left a comment

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.

PR Review

Found 3 issue(s): 0 major, 1 minor, 1 suggestion, 1 nit.

Summary

  • Good fix for SSE connection leak — centralizing cancellation in sendRequest is the right call
  • The cancelRequest error swallowing means sendRequest can't detect cancellation failure, which could silently leave the old stream running
  • E2E test structure follows project conventions correctly
  • The behavioral change (cancel+resend in one press vs. cancel-only then resend) is a UX improvement

return reject(new Error('Collection not found'));
}

if (item.response?.stream?.running && item.cancelTokenUid) {

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.

Bug (Minor): cancelRequest swallows all errors via .catch((err) => console.log(err)) on line 650, so the await here always resolves successfully — even if the cancellation actually failed. This means if cancelNetworkRequest throws (e.g. the cancel token is stale or the IPC call fails), the code silently proceeds to send a new request while the old SSE stream is still running — exactly the connection leak this PR aims to fix.

Consider either:

  1. Letting cancelRequest propagate the error and handling it here, or
  2. At minimum, logging a warning so silent failures are visible:

Suggested fix:

try {
  await dispatch(cancelRequest(item.cancelTokenUid, item, collection));
} catch (err) {
  console.warn('Failed to cancel previous SSE stream, proceeding with new request:', err);
}

Comment thread tests/sse/sse-cancellation.spec.ts Outdated
const response = await page.request.get('http://localhost:8081/api/sse/connections');
const data = await response.json();
return data.activeConnections;
}, { timeout: 5000 }).toBe(1);

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.

Suggestion: The final assertion toBe(1) verifies there's exactly one connection, but doesn't confirm it's a new connection (as opposed to the original one surviving and the new one failing to open). Consider also checking that the connectionId changed:

// Before resend, capture the current connection ID
const beforeResend = await page.request.get('http://localhost:8081/api/sse/connections');
const beforeData = await beforeResend.json();
const oldConnectionId = beforeData.connectionIds[0];

// ... resend ...

await expect.poll(async () => {
  const response = await page.request.get('http://localhost:8081/api/sse/connections');
  const data = await response.json();
  return data.activeConnections === 1 && data.connectionIds[0] !== oldConnectionId;
}, { timeout: 5000 }).toBe(true);

This makes the test more resilient against false positives where the cancel failed but the new request also failed.

Comment thread packages/bruno-tests/src/sse/index.js Resolved
cchirag added 2 commits April 2, 2026 17:57
When resending an SSE (Server-Sent Events) request using Cmd+Enter,
the previous connection was not being closed, causing connection leaks.

Changes:
- Add SSE cancellation logic to sendRequest action - checks for running
  stream and cancels it before sending new request
- Add return to cancelRequest action to make it properly chainable
- Simplify RequestTabPanel by removing duplicate cancel logic (now
  handled centrally in sendRequest)
- Add SSE endpoints to test server for e2e testing
- Add Playwright e2e test to verify SSE connection cancellation
- Use platform-aware modifier (Meta on macOS, Control on Linux/Windows)
  instead of hardcoded Meta+Enter for cross-platform CI compatibility
- Replace waitForTimeout with expect.poll for deterministic assertions
- Remove dead try/catch around cancelRequest (errors already swallowed
  by cancelRequest's internal .catch)
@chirag-bruno
chirag-bruno force-pushed the fix/sse-close-previous-connection-on-resend branch from aa3dd80 to 2b1ccee Compare April 2, 2026 12:27

@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)
tests/sse/sse-cancellation.spec.ts (2)

9-35: Test structure looks good; consider adding test.step blocks for report clarity.

The platform-aware modifier on line 26 and the expect.poll() approach on lines 19-23 and 30-34 address the previous review feedback correctly.

For improved Playwright report readability per coding guidelines, consider wrapping logical sections in test.step:

♻️ Suggested structure with test.step
 test('should close previous SSE connection when resending request', async ({ pageWithUserData: page }) => {
+  await test.step('Navigate to SSE request', async () => {
     await page.locator('#sidebar-collection-name').click();
-
     await page.getByTestId('sidebar-collection-item-row').filter({ hasText: 'sse-stream-request' }).click();
-
     await page.getByTestId('send-arrow-icon').waitFor({ state: 'visible' });
+  });

+  await test.step('Send initial SSE request', async () => {
     await page.getByTestId('send-arrow-icon').click();
-
-    // Poll until the SSE connection is established
     await expect.poll(async () => {
       const response = await page.request.get('http://localhost:8081/api/sse/connections');
       const data = await response.json();
       return data.activeConnections;
     }, { timeout: 5000 }).toBe(1);
+  });

-    // Resend the request (this should cancel the old connection and start a new one)
+  await test.step('Resend request and verify old connection is closed', async () => {
     const resendShortcut = process.platform === 'darwin' ? 'Meta+Enter' : 'Control+Enter';
     await page.keyboard.press(resendShortcut);
-
-    // Poll until the old connection is closed and a new one is established
     await expect.poll(async () => {
       const response = await page.request.get('http://localhost:8081/api/sse/connections');
       const data = await response.json();
       return data.activeConnections;
     }, { timeout: 5000 }).toBe(1);
+  });
 });

As per coding guidelines: "Promote the use of test.step as much as possible so the generated reports are easier to read."

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

In `@tests/sse/sse-cancellation.spec.ts` around lines 9 - 35, Wrap the logical
sections of the test 'should close previous SSE connection when resending
request' into test.step blocks to improve report clarity: create steps for "open
collection" (clicking '#sidebar-collection-name' and selecting
'sse-stream-request'), "send initial request" (clicking 'send-arrow-icon'),
"assert connection established" (the first expect.poll that checks
/api/sse/connections), "resend request" (the platform-aware resendShortcut
press), and "assert new connection" (the second expect.poll); keep the same
locators and variables (e.g., resendShortcut, page.request.get) but move their
corresponding actions/assertions inside those test.step blocks so the Playwright
report shows each phase as a named step.

30-34: Optional: Verify connectionId changes to strengthen assertion.

The current assertion confirms exactly one connection exists after resend but doesn't verify it's a new connection. If cancellation fails silently and the new request also fails to connect, you'd still have 1 connection (the old one) and the test would pass incorrectly.

♻️ Suggested enhancement
// Capture connection ID before resend
const beforeResend = await page.request.get('http://localhost:8081/api/sse/connections');
const beforeData = await beforeResend.json();
const oldConnectionId = beforeData.connectionIds?.[0];

// Resend...

// Verify new connection replaced the old one
await expect.poll(async () => {
  const response = await page.request.get('http://localhost:8081/api/sse/connections');
  const data = await response.json();
  return data.activeConnections === 1 && data.connectionIds?.[0] !== oldConnectionId;
}, { timeout: 5000 }).toBe(true);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/sse/sse-cancellation.spec.ts` around lines 30 - 34, Capture the current
connection ID before triggering the resend and then assert that after resend the
connection list has one active connection whose connectionIds[0] is different
from the saved ID: use
page.request.get('http://localhost:8081/api/sse/connections') to read
beforeData.connectionIds?.[0] (oldConnectionId), perform the resend, then change
the expect.poll call (the existing expect.poll async block) to return a boolean
that checks data.activeConnections === 1 && data.connectionIds?.[0] !==
oldConnectionId and assert toBe(true) to ensure the connection was replaced.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@tests/sse/sse-cancellation.spec.ts`:
- Around line 9-35: Wrap the logical sections of the test 'should close previous
SSE connection when resending request' into test.step blocks to improve report
clarity: create steps for "open collection" (clicking '#sidebar-collection-name'
and selecting 'sse-stream-request'), "send initial request" (clicking
'send-arrow-icon'), "assert connection established" (the first expect.poll that
checks /api/sse/connections), "resend request" (the platform-aware
resendShortcut press), and "assert new connection" (the second expect.poll);
keep the same locators and variables (e.g., resendShortcut, page.request.get)
but move their corresponding actions/assertions inside those test.step blocks so
the Playwright report shows each phase as a named step.
- Around line 30-34: Capture the current connection ID before triggering the
resend and then assert that after resend the connection list has one active
connection whose connectionIds[0] is different from the saved ID: use
page.request.get('http://localhost:8081/api/sse/connections') to read
beforeData.connectionIds?.[0] (oldConnectionId), perform the resend, then change
the expect.poll call (the existing expect.poll async block) to return a boolean
that checks data.activeConnections === 1 && data.connectionIds?.[0] !==
oldConnectionId and assert toBe(true) to ensure the connection was replaced.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 55f73bb4-3981-4fc7-8157-b7d5a8605fc8

📥 Commits

Reviewing files that changed from the base of the PR and between aa3dd80 and 2b1ccee.

📒 Files selected for processing (8)
  • packages/bruno-app/src/components/RequestTabPanel/index.js
  • packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js
  • packages/bruno-tests/src/index.js
  • packages/bruno-tests/src/sse/index.js
  • tests/sse/fixtures/collection/bruno.json
  • tests/sse/fixtures/collection/sse-stream-request.bru
  • tests/sse/init-user-data/preferences.json
  • tests/sse/sse-cancellation.spec.ts
✅ Files skipped from review due to trivial changes (4)
  • packages/bruno-tests/src/index.js
  • tests/sse/fixtures/collection/sse-stream-request.bru
  • tests/sse/fixtures/collection/bruno.json
  • tests/sse/init-user-data/preferences.json
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/bruno-app/src/components/RequestTabPanel/index.js
  • packages/bruno-tests/src/sse/index.js

sid-bruno
sid-bruno previously approved these changes Apr 2, 2026
@sid-bruno

Copy link
Copy Markdown
Collaborator

LGTM, waiting on tests

@lohit-bruno
lohit-bruno dismissed sid-bruno’s stale review April 2, 2026 15:34

The merge-base changed after approval.

bijin-bruno
bijin-bruno previously approved these changes Apr 2, 2026
@chirag-bruno
chirag-bruno dismissed bijin-bruno’s stale review April 2, 2026 20:29

The merge-base changed after approval.

@bijin-bruno
bijin-bruno merged commit 5e1a36f into usebruno:main Apr 2, 2026
11 checks passed
maxenceleblanc pushed a commit to maxenceleblanc/curly_cats2 that referenced this pull request Jul 20, 2026
…no#7474)

* fix: update system proxy fetching to use finally (usebruno#7652)

* fix: update system proxy fetching to use finally for improved reliability

* Update packages/bruno-electron/src/index.js

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

---------

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

* fix: allow file selection in multipart form without entering a key first (usebruno#7640)

* fix: close previous SSE connection before sending new request

When resending an SSE (Server-Sent Events) request using Cmd+Enter,
the previous connection was not being closed, causing connection leaks.

Changes:
- Add SSE cancellation logic to sendRequest action - checks for running
  stream and cancels it before sending new request
- Add return to cancelRequest action to make it properly chainable
- Simplify RequestTabPanel by removing duplicate cancel logic (now
  handled centrally in sendRequest)
- Add SSE endpoints to test server for e2e testing
- Add Playwright e2e test to verify SSE connection cancellation

* fix: address PR review feedback for SSE connection cancellation

- Use platform-aware modifier (Meta on macOS, Control on Linux/Windows)
  instead of hardcoded Meta+Enter for cross-platform CI compatibility
- Replace waitForTimeout with expect.poll for deterministic assertions
- Remove dead try/catch around cancelRequest (errors already swallowed
  by cancelRequest's internal .catch)

* fix: updated the test to check of connectionIds

---------

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

SSE: previous connections are not closed when re-sending a request

6 participants