Skip to content

Adding support for GraphQL Subscriptions - #8802

Open
ZaninAndrea wants to merge 22 commits into
usebruno:mainfrom
ZaninAndrea:feat/graphql-subscriptions-clean
Open

ZaninAndrea wants to merge 22 commits into
usebruno:mainfrom
ZaninAndrea:feat/graphql-subscriptions-clean

Conversation

@ZaninAndrea

@ZaninAndrea ZaninAndrea commented Jul 28, 2026 •

Copy link
Copy Markdown

Description

Add support for GraphQL subscriptions as a new type of request. It is built on the already existing Websocket and GraphQL request implementations.

The implementation is built for the graphql-transport-ws protocol, but it can be extended to also support graphql-ws protocol. I have not added it yet to keep the PR smaller.

The PR contains many changes from let to const done by the pre-commit hook, I think these are files that were not up to date with the linting configuration.

I am open to any suggestion on how to improve the implementation.

AI disclosure

I have used Claude to help in the implementation, but all the code has been reviewed by me.

Problem

#5801

Screenshots

Screenshot 2026-07-28 at 18 01 56

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.

Summary by CodeRabbit

  • New Features
    • Added GraphQL Subscription request support end-to-end: creation, presets/defaults, sidebar/tab method labeling (SUB), and request/response panes with subscribe/unsubscribe controls.
    • Added connection parameters editing and subscription-aware schema introspection, plus keep-alive handling for subscription tab types.
    • Extended import/export and BRU/JSON/YAML conversions to support GraphQL Subscription requests and connection params.
  • Bug Fixes
    • Improved subscription validation (requires valid ws:///wss://) and ensured correct long-lived connection cleanup on tab close.
  • Tests
    • Added unit, Electron/IPCs, and end-to-end (Playwright) coverage, including persistence and lifecycle scenarios.

Introduce the graphql-subscription-request item type in the shared
schema types and JSON-schema validation, laying the ground work for
the filestore, transport, and UI layers built on top of it.
… support

Teach bruno-lang, bruno-filestore, bruno-cli, and the OpenCollection
converter to read and write graphql-subscription-request items,
including connection params, so the request type round-trips through
every on-disk representation Bruno supports.
Implement the graphql-transport-ws protocol and a subscription client
built on it, so the request pipeline has a runtime piece that can open
a subscription, stream events, and tear the connection down cleanly.
Add the graphql-subscription IPC event handlers, request preparation,
and connectionParams interpolation, and extract a shared
registerAppQuitTeardown helper (reused by the existing WS client) so
both socket-based transports tear down cleanly on app quit.
Add subscribe/unsubscribe actions and reducers, IPC event listeners
that feed subscription messages into the store, and recognize
graphql-subscription-request across the tabs/snapshot/collections
utils that key behavior off request type.
…ntry points

Add the ConnectionParams and GraphQLSubscriptionQueryUrl panes, and
recognize graphql-subscription-request across every entry point and
display surface: new-request menus, request tabs, the timeline and
messages list, the runner, sharing, presets, and the sidebar icon.
Add graphql-ws powered subscriptions to the local test GraphQL server
so e2e specs and manual testing have something real to subscribe to.
…e and persistence

Cover subscribing/unsubscribing, message history, and collection
persistence for graphql-subscription-request items end to end.

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@ZaninAndrea ZaninAndrea changed the title Feat/graphql subscriptions clean Adding support for GraphQL Subscriptions Jul 28, 2026
@coderabbitai

coderabbitai Bot commented Jul 28, 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

GraphQL subscription requests are added across request creation, schema and file formats, WebSocket transport, Redux lifecycle state, response rendering, collection handling, and end-to-end coverage.

Changes

GraphQL subscription support

Layer / File(s) Summary
Request creation and editing
packages/bruno-app/src/components/...
Adds GraphQL Subscription request creation, presets, URL editing, connection parameters, schema loading, and subscription-specific request tabs.
Shared socket response rendering
packages/bruno-app/src/components/ResponsePane/...
Introduces shared socket response/message components and connects WebSocket and GraphQL subscription panes to them.
Redux lifecycle and persistence
packages/bruno-app/src/providers/ReduxStore/..., packages/bruno-app/src/utils/...
Adds request creation, connection-parameter updates, subscription event reducers, response timelines, and request classification.
Electron transport runtime
packages/bruno-electron/..., packages/bruno-requests/...
Implements the graphql-transport-ws protocol, subscription client, IPC handlers, connection cleanup, interpolation, and runner exclusions.
Formats, schemas, and tests
packages/bruno-filestore/..., packages/bruno-lang/..., packages/bruno-converters/..., packages/bruno-schema..., tests/graphql/subscription/...
Adds GraphQL subscription serialization, parsing, validation, conversion, protocol tests, fixtures, and Playwright coverage.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant BrunoApp
  participant Redux
  participant ElectronIPC
  participant GraphQLSubscriptionClient
  participant GraphQLServer
  User->>BrunoApp: Open GraphQL subscription request
  BrunoApp->>ElectronIPC: Connect and subscribe
  ElectronIPC->>GraphQLSubscriptionClient: Prepare WebSocket transport
  GraphQLSubscriptionClient->>GraphQLServer: connection_init and subscribe
  GraphQLServer-->>GraphQLSubscriptionClient: connection_ack and next frames
  GraphQLSubscriptionClient-->>ElectronIPC: Lifecycle and frame events
  ElectronIPC-->>Redux: Dispatch subscription response events
  Redux-->>BrunoApp: Render messages and connection status
Loading

Possibly related PRs

  • usebruno/bruno#8751: Updates the shared WebSocket message-rendering surface used by this PR.
  • usebruno/bruno#8788: Contains closely related GraphQL subscription request classification and UI/Redux wiring.

Suggested reviewers: bijin-bruno

Poem

A socket hums, frames softly flow,
Queries wake where subscriptions grow.
Ack arrives, the messages gleam,
Redux records the streaming dream.
Save, reconnect, and tests take flight—
GraphQL dances through the night.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding GraphQL subscription support across the app.
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.
✨ 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.

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

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/providers/ReduxStore/slices/collections/actions.js (1)

400-440: 🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

saveMultipleCollections never actually waits for the saves — outer savePromises is always empty.

The inner const savePromises = [] (Line 414) shadows the outer array declared at Line 405. Only the inner array is awaited per-collection; the outer Promise.all(savePromises) (Line 433) always resolves on an empty array almost immediately, so the returned promise settles before the IPC saves finish. Any later reject(err) from a failed collection save is then a no-op on an already-resolved promise — failures get silently swallowed and callers believe the multi-collection save succeeded.

🐛 Proposed fix
     const savePromises = [];

     each(collectionDrafts, (collectionDraft) => {
       const collection = findCollectionByUid(collections, collectionDraft.collectionUid);
       if (collection) {
         const collectionCopy = cloneDeep(collection);
         const collectionRootToSave = transformCollectionRootToSave(collectionCopy);
         const { ipcRenderer } = window;

-        const savePromises = [];
+        const collectionSavePromises = [];

-        savePromises.push(ipcRenderer.invoke('renderer:save-collection-root', collectionCopy.pathname, collectionRootToSave, collectionCopy.brunoConfig));
+        collectionSavePromises.push(ipcRenderer.invoke('renderer:save-collection-root', collectionCopy.pathname, collectionRootToSave, collectionCopy.brunoConfig));

         if (collectionCopy.draft?.brunoConfig) {
-          savePromises.push(ipcRenderer.invoke('renderer:update-bruno-config', collectionCopy.draft.brunoConfig, collectionCopy.pathname, collectionCopy.root));
+          collectionSavePromises.push(ipcRenderer.invoke('renderer:update-bruno-config', collectionCopy.draft.brunoConfig, collectionCopy.pathname, collectionCopy.root));
         }

-        Promise.all(savePromises)
-          .then(() => {
-            dispatch(saveCollectionDraft({ collectionUid: collectionDraft.collectionUid }));
-          })
-          .catch((err) => {
-            toast.error('Failed to save collection settings!');
-            reject(err);
-          });
+        savePromises.push(
+          Promise.all(collectionSavePromises)
+            .then(() => {
+              dispatch(saveCollectionDraft({ collectionUid: collectionDraft.collectionUid }));
+            })
+            .catch((err) => {
+              toast.error('Failed to save collection settings!');
+              reject(err);
+            })
+        );
       }
     });
🤖 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-app/src/providers/ReduxStore/slices/collections/actions.js`
around lines 400 - 440, Fix saveMultipleCollections so its returned promise
tracks every collection’s IPC save operation. Remove the shadowing inner
savePromises in the collectionDraft loop, add each per-collection save promise
to the outer array, and preserve dispatch on success plus rejection propagation
for failures so Promise.all does not resolve early.
🧹 Nitpick comments (9)
packages/bruno-converters/src/opencollection/items/graphql-subscription.ts (1)

57-75: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Prefer the real request/settings shapes over as any.

This PR adds packages/bruno-schema-types/src/requests/graphql-subscription.ts; reusing it here (or widening BrunoItem['request'] to carry connectionParams) keeps the converter type-checked instead of opting out twice.

As per path instructions, "When a file is converted to TypeScript, flag use of any used as a shortcut rather than a genuinely unknown/dynamic type — prefer modeling the real shape (reuse types from @usebruno/schema-types where applicable)."

🤖 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-converters/src/opencollection/items/graphql-subscription.ts`
around lines 57 - 75, Replace the `as any` casts on the converted GraphQL
subscription `request` and `settings` objects with the real types from the new
`graphql-subscription` schema definition, or widen `BrunoItem['request']` to
include `connectionParams`. Keep the existing field mappings while preserving
full type checking in the converter.

Source: Path instructions

packages/bruno-app/src/utils/network/index.js (1)

429-454: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Promise constructor wrapper is redundant here.

These three only forward resolve/reject; return ipcRenderer.invoke(...) is equivalent. Non-blocking if you're matching the surrounding file style.

♻️ Proposed simplification
 export const unsubscribeGraphqlSubscription = async (requestId) => {
-  return new Promise((resolve, reject) => {
-    const { ipcRenderer } = window;
-    ipcRenderer.invoke('renderer:gql-sub:unsubscribe', requestId).then(resolve).catch(reject);
-  });
+  const { ipcRenderer } = window;
+  return ipcRenderer.invoke('renderer:gql-sub:unsubscribe', requestId);
 };
🤖 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-app/src/utils/network/index.js` around lines 429 - 454, Remove
the redundant Promise constructors from unsubscribeGraphqlSubscription,
disconnectGraphqlSubscription, and getGraphqlSubscriptionConnectionStatus,
returning the corresponding ipcRenderer.invoke(...) promise directly while
preserving each channel and argument list.
packages/bruno-app/src/utils/network/graphql-subscription-event-listeners.js (1)

25-95: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Nine identical listeners could be table-driven.

Optional: map channel suffix → eventType and register in a loop; cleanup becomes a single unsubscribes.forEach((fn) => fn()).

♻️ Sketch
-    const removeConnectingListener = ipcRenderer.on('main:gql-sub:connecting', (requestId, collectionUid, eventData) => {
-      dispatch(graphqlSubscriptionResponseReceived({ ... }));
-    });
-    ...
+    const responseEvents = ['connecting', 'upgrade', 'redirect', 'open', 'frames', 'operation-state', 'close', 'error'];
+    const unsubscribes = responseEvents.map((eventType) =>
+      ipcRenderer.on(`main:gql-sub:${eventType}`, (requestId, collectionUid, eventData) => {
+        dispatch(graphqlSubscriptionResponseReceived({ itemUid: requestId, collectionUid, eventType, eventData }));
+      }));
🤖 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-app/src/utils/network/graphql-subscription-event-listeners.js`
around lines 25 - 95, Consolidate the repeated GraphQL subscription listener
registrations around graphqlSubscriptionResponseReceived into a table-driven
mapping of channel suffixes to eventType values, then register them in a loop
while preserving the existing requestId, collectionUid, and eventData dispatch
payload. Collect each returned unsubscribe function and update cleanup to invoke
all of them via a single iteration.
packages/bruno-app/src/components/Sidebar/NewRequest/index.js (1)

153-270: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

onSubmit duplicates the same dispatch→toast→onClose flow four times.

Each new request type (grpc/ws/graphql-subscription/default/from-curl) repeats the same .then(toast.success + onClose).catch(toast.error) boilerplate. Worth extracting into a small helper (e.g., createRequestAndNotify(actionPromise)) to avoid this growing with each future request type.

♻️ Sketch of a shared helper
+const dispatchAndNotify = (promise) =>
+  promise
+    .then(() => {
+      toast.success('New request created!');
+      onClose();
+    })
+    .catch((err) => toast.error(err ? err.message : 'An error occurred while adding the request'));
+
       if (isGrpcRequest) {
-        dispatch(newGrpcRequest({ ... }))
-          .then(() => { toast.success('New request created!'); onClose(); })
-          .catch((err) => toast.error(err ? err.message : 'An error occurred while adding the request'));
+        dispatchAndNotify(dispatch(newGrpcRequest({ ... })));
       } else if (isWsRequest) {
-        dispatch(newWsRequest({ ... }))
-          .then(...)
-          .catch(...);
+        dispatchAndNotify(dispatch(newWsRequest({ ... })));
       } else if (isGraphqlSubscriptionRequest) {
-        dispatch(newGraphqlSubscriptionRequest({ ... }))
-          .then(...)
-          .catch(...);
+        dispatchAndNotify(dispatch(newGraphqlSubscriptionRequest({ ... })));
       }
🤖 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-app/src/components/Sidebar/NewRequest/index.js` around lines
153 - 270, Extract the repeated dispatch promise handling in onSubmit into a
shared helper such as createRequestAndNotify, covering the success toast,
onClose call, and error toast. Update the grpc, WebSocket, GraphQL subscription,
from-curl, default, and ephemeral request branches to pass their dispatch result
through this helper while preserving their existing request payloads and
ephemeral tab behavior.
packages/bruno-app/src/components/ResponsePane/SocketMessagesList/index.js (2)

108-137: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Expand/collapse row is mouse-only.

The toggle handler lives on a plain div with no role="button", tabIndex, or key handler, so keyboard users can't open a message. Carried over from the old WSMessagesList, but now it's the shared path for both WS and GraphQL subscriptions — cheap to fix here once.

♿ Suggested change
       <div
         className={classnames('flex items-center justify-between', {
           'cursor-pointer': canOpenMessage,
           'cursor-not-allowed': !canOpenMessage
         })}
+        role={canOpenMessage ? 'button' : undefined}
+        tabIndex={canOpenMessage ? 0 : undefined}
+        aria-expanded={canOpenMessage ? isOpen : undefined}
+        onKeyDown={(e) => {
+          if (e.key === 'Enter' || e.key === ' ') {
+            e.preventDefault();
+            handleToggle();
+          }
+        }}
         onClick={handleToggle}
       >
🤖 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-app/src/components/ResponsePane/SocketMessagesList/index.js`
around lines 108 - 137, Add keyboard accessibility to the row containing
handleToggle: give the interactive div an appropriate button role and tabIndex,
and invoke handleToggle for Enter and Space key presses while preserving the
existing click behavior. Use the existing canOpenMessage state so non-openable
rows are not presented as actionable.

10-36: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Double parse/stringify round-trip in parseContent.

getContentMeta stringifies with indent 0, then parseContent re-parses that string just to stringify it again with indent 2. Two extra JSON passes per message per render; return the parsed value once.

♻️ Suggested simplification
-const getContentMeta = (content) => {
-  if (typeof content === 'object') {
-    return {
-      isJSON: true,
-      content: JSON.stringify(content, null, 0)
-    };
-  }
-  try {
-    return {
-      isJSON: true,
-      content: JSON.stringify(JSON.parse(content), null, 0)
-    };
-  } catch {
-    return {
-      isJSON: false,
-      content: content
-    };
-  }
-};
-
-const parseContent = (content) => {
-  const contentMeta = getContentMeta(content);
-  return {
-    type: contentMeta.isJSON ? 'application/json' : 'text/plain',
-    content: contentMeta.isJSON ? JSON.stringify(JSON.parse(contentMeta.content), null, 2) : contentMeta.content
-  };
-};
+const parseContent = (content) => {
+  if (typeof content === 'object') {
+    return { type: 'application/json', content: JSON.stringify(content, null, 2) };
+  }
+  try {
+    return { type: 'application/json', content: JSON.stringify(JSON.parse(content), null, 2) };
+  } catch {
+    return { type: 'text/plain', content };
+  }
+};
🤖 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-app/src/components/ResponsePane/SocketMessagesList/index.js`
around lines 10 - 36, Update getContentMeta and parseContent to retain and reuse
the parsed JSON value instead of stringifying it with indent 0 and parsing it
again before formatting with indent 2. Ensure valid object and JSON-string
inputs still produce type application/json with two-space formatting, while
invalid JSON continues returning text/plain unchanged.
packages/bruno-app/src/components/ResponsePane/SocketResponsePane/index.js (1)

8-16: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

Shared pane depends on WS-specific folder.

SocketResponsePane is now the shell for both ws-request and graphql-subscription-request, but pulls WSStatusCode / WSResponseHeaders out of ../WsResponsePane/. Dependency points the wrong way — worth relocating them next to the shared pane (or a neutral folder) so WsResponsePane stays a leaf wrapper.

🤖 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-app/src/components/ResponsePane/SocketResponsePane/index.js`
around lines 8 - 16, Relocate the shared WSStatusCode and WSResponseHeaders
components from WsResponsePane into SocketResponsePane or another neutral shared
location, then update imports in SocketResponsePane and WsResponsePane to use
the new location. Keep WsResponsePane as a leaf wrapper without being a
dependency of the shared pane.
packages/bruno-electron/src/ipc/network/graphql-subscription-event-handlers.js (1)

71-81: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Warning is computed from pre-merge headers.

droppedProtocolHeader scans rawHeaders (captured before mergeHeaders), while the deletion below operates on the merged headers. A Sec-WebSocket-Protocol inherited from a folder/collection gets silently dropped with no warning. Deriving the warning from headers would keep both in sync.

🤖 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/network/graphql-subscription-event-handlers.js`
around lines 71 - 81, Update the warning logic in the subscription event handler
to inspect the merged headers object rather than the pre-merge rawHeaders
collection. Preserve the existing detection and warning message for enabled
Sec-WebSocket-Protocol headers, keeping it aligned with the subsequent deletion
loop over headers.
tests/utils/page/graphql-subscription.ts (1)

8-19: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Centralize stable semantic GraphQL-subscription locators.

The page module and specs currently rely on CSS/id selectors, contrary to the E2E locator contract. Add stable test IDs or semantic roles in the UI, expose them through page-module builders/actions, and consume only those helpers from specs.

  • tests/utils/page/graphql-subscription.ts#L8-L19: replace CSS-class-based message/editor locators with semantic test-ID or role-based locators.
  • tests/graphql/subscription/subscription-persistence.spec.ts#L8-L9: expose collection and request-opening actions through page helpers.
  • tests/graphql/subscription/subscription-persistence.spec.ts#L19-L20: expose the connection-params editing target/action through the GraphQL subscription page module.
  • tests/graphql/subscription/subscription-persistence.spec.ts#L32-L33: reuse the page helpers after restart.
  • tests/graphql/subscription/subscription.spec.ts#L6-L10: expose sidebar request-item locators through the page module.
  • tests/graphql/subscription/subscription.spec.ts#L17-L18: use a page-module request-opening action.
  • tests/graphql/subscription/subscription.spec.ts#L59-L60: use the same sidebar locator/action rather than inline CSS.
  • tests/graphql/subscription/subscription.spec.ts#L87-L87: expose the subscription message scroller through the page module.

As per path instructions, GraphQL subscription specs must avoid inline raw selectors and page modules must use semantic selectors.

🤖 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 `@tests/utils/page/graphql-subscription.ts` around lines 8 - 19, Centralize
stable semantic GraphQL-subscription locators and remove raw CSS/id selectors.
In tests/utils/page/graphql-subscription.ts:8-19, update the messages,
infoMessage, connectionParams, and connectionParamsEditor builders to use UI
test IDs or semantic roles; add the required UI hooks if absent. In
tests/graphql/subscription/subscription-persistence.spec.ts:8-9, :19-20, and
:32-33, expose collection, request-opening, and connection-params editing
actions through the page module and reuse them after restart. In
tests/graphql/subscription/subscription.spec.ts:6-10, :17-18, :59-60, and :87,
expose and reuse sidebar request-item, request-opening, and message-scroller
helpers so both specs contain no inline raw selectors.

Sources: Coding guidelines, Path instructions

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

Inline comments:
In
`@packages/bruno-app/src/components/RequestPane/GraphQLSubscriptionQueryUrl/index.js`:
- Around line 78-120: Replace the clickable div controls in the save, subscribe,
and unsubscribe branches with semantic button type="button" elements, preserving
their existing click behavior and test identifiers while adding accessible
labels. Move cursor and animation styling from Tailwind className values into
the relevant StyledWrapper components, keeping Tailwind only for layout classes
and retaining the existing visual state differences.

In `@packages/bruno-app/src/components/RequestTabs/RequestTab/index.js`:
- Around line 90-91: Update the handleMouseUp middle-click close path to
disconnect active WS and GraphQL subscription connections before dispatching
closeTabs, matching the existing cleanup in the other close paths. Reuse
closeWsConnection and disconnectGraphqlSubscription with the tab item’s uid,
while preserving the current behavior for other tab types.

In `@packages/bruno-app/src/components/ResponsePane/SocketMessagesList/index.js`:
- Around line 266-268: Update the empty-state branch in the messages list
component to apply the same `${classPrefix}-messages-list` class used by the
populated branch, while preserving the existing `empty-state` content and
StyledWrapper behavior.
- Around line 194-210: Reset the openMessages state in SocketMessagesList when
messages becomes empty or responseCleared is observed, so reused message keys do
not inherit prior expansion state. Add the necessary effect or existing
clear-state integration near handleMessageToggle, preserving current toggle
behavior for non-empty message lists.

In `@packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js`:
- Around line 4040-4059: Clone the seeded responses array when constructing
updatedResponse so it never aliases the module-level
initiatedGraphqlSubscriptionResponse.responses array, especially when
item.response is absent. Apply the same defensive array clone in
runGraphqlSubscriptionRequestEvent, preserving existing entries while allowing
pushResponse to mutate only the current subscription item.

In `@packages/bruno-app/src/utils/collections/index.js`:
- Line 409: Wrap the `case 'oauth2'` branch in braces so the `grantType`
declaration and its associated statements are scoped to that case, while
preserving the existing OAuth2 behavior and switch flow.

In `@packages/bruno-converters/tests/opencollection/graphql-subscription.spec.js`:
- Around line 34-59: Update the round-trip assertions in the subscription
conversion test to verify the fixture’s X-Test WebSocket handshake header.
Assert its expected value in both ocItem.graphqlSubscription.headers and
item.request.headers, while preserving the existing URL, auth, body, and
settings checks.

In `@packages/bruno-electron/src/ipc/collection.js`:
- Line 1521: Update the request-type filter used by clone-folder to include
ws-request alongside the existing HTTP, GraphQL, gRPC, and subscription request
types, ensuring WebSocket requests are preserved when cloning a folder.

In
`@packages/bruno-electron/src/ipc/network/graphql-subscription-event-handlers.js`:
- Around line 196-197: Update the token-placement logic in the GraphQL
subscription event handler to assign the Authorization header only when
credentials?.access_token is present, matching the tokenValue guard used by
configureRequest. Leave the request without an Authorization header when token
retrieval fails or returns no token.

In `@packages/bruno-filestore/src/formats/yml/stringifyItem.spec.ts`:
- Around line 90-104: Extend the round-trip assertions in the parseItem test for
the graphql-subscription-request fixture to verify that supplied headers,
authentication, and tags are preserved after stringify and reparsing. Assert the
expected values alongside the existing request and settings checks, using the
fixture’s corresponding fields.

In `@packages/bruno-requests/src/graphql/graphql-subscription-client.js`:
- Around line 408-434: Update `#writeFrame` to track whether an outgoing frame was
actually sent, setting the flag only when record.socket is OPEN and send(raw)
executes. Include this sent status on buffered frame records, ensuring skipped
writes during CONNECTING or after closure are represented as unsent rather than
implying transmission.

In `@packages/bruno-schema/src/collections/index.js`:
- Around line 610-618: Update longLivedConnectionSettingsSchema in
packages/bruno-schema/src/collections/index.js:610-618 to mark both timeout and
keepAliveInterval Yup.number() fields as nullable, while preserving their
existing defaults and object-level validation. The corresponding
GraphqlSubscriptionItemSettings definitions in
packages/bruno-schema-types/src/collection/item.ts:30-35 require no direct
change.

In `@packages/bruno-tests/src/graphql/subscriptions.js`:
- Around line 33-37: In the upgrade callback returned by the surrounding
WebSocket setup, attach an error listener to the raw socket before calling
wss.handleUpgrade. Reuse the existing socket-error handling pattern from
wsRouter so handshake errors are handled without becoming unhandled events,
while preserving the current connection emission flow.

In `@tests/graphql/subscription/subscription-persistence.spec.ts`:
- Line 5: Update the test named “connectionParams and query persist across save
and app restart” to either add assertions that save and verify query persistence
through the restart flow, or narrow the test title to describe only
connectionParams persistence. Ensure the test title accurately reflects the
behavior it exercises.

In `@tests/graphql/subscription/subscription.spec.ts`:
- Around line 4-5: Remove serial execution from the graphql subscription test
suite and update each test, including “graphql-subscription-request items are
visible in the sidebar,” to independently open the required request/tab through
its own setup. Ensure every test cleans up its created subscription and relies
only on isolated fixture state so retries and parallel execution remain safe.

---

Outside diff comments:
In `@packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js`:
- Around line 400-440: Fix saveMultipleCollections so its returned promise
tracks every collection’s IPC save operation. Remove the shadowing inner
savePromises in the collectionDraft loop, add each per-collection save promise
to the outer array, and preserve dispatch on success plus rejection propagation
for failures so Promise.all does not resolve early.

---

Nitpick comments:
In `@packages/bruno-app/src/components/ResponsePane/SocketMessagesList/index.js`:
- Around line 108-137: Add keyboard accessibility to the row containing
handleToggle: give the interactive div an appropriate button role and tabIndex,
and invoke handleToggle for Enter and Space key presses while preserving the
existing click behavior. Use the existing canOpenMessage state so non-openable
rows are not presented as actionable.
- Around line 10-36: Update getContentMeta and parseContent to retain and reuse
the parsed JSON value instead of stringifying it with indent 0 and parsing it
again before formatting with indent 2. Ensure valid object and JSON-string
inputs still produce type application/json with two-space formatting, while
invalid JSON continues returning text/plain unchanged.

In `@packages/bruno-app/src/components/ResponsePane/SocketResponsePane/index.js`:
- Around line 8-16: Relocate the shared WSStatusCode and WSResponseHeaders
components from WsResponsePane into SocketResponsePane or another neutral shared
location, then update imports in SocketResponsePane and WsResponsePane to use
the new location. Keep WsResponsePane as a leaf wrapper without being a
dependency of the shared pane.

In `@packages/bruno-app/src/components/Sidebar/NewRequest/index.js`:
- Around line 153-270: Extract the repeated dispatch promise handling in
onSubmit into a shared helper such as createRequestAndNotify, covering the
success toast, onClose call, and error toast. Update the grpc, WebSocket,
GraphQL subscription, from-curl, default, and ephemeral request branches to pass
their dispatch result through this helper while preserving their existing
request payloads and ephemeral tab behavior.

In
`@packages/bruno-app/src/utils/network/graphql-subscription-event-listeners.js`:
- Around line 25-95: Consolidate the repeated GraphQL subscription listener
registrations around graphqlSubscriptionResponseReceived into a table-driven
mapping of channel suffixes to eventType values, then register them in a loop
while preserving the existing requestId, collectionUid, and eventData dispatch
payload. Collect each returned unsubscribe function and update cleanup to invoke
all of them via a single iteration.

In `@packages/bruno-app/src/utils/network/index.js`:
- Around line 429-454: Remove the redundant Promise constructors from
unsubscribeGraphqlSubscription, disconnectGraphqlSubscription, and
getGraphqlSubscriptionConnectionStatus, returning the corresponding
ipcRenderer.invoke(...) promise directly while preserving each channel and
argument list.

In `@packages/bruno-converters/src/opencollection/items/graphql-subscription.ts`:
- Around line 57-75: Replace the `as any` casts on the converted GraphQL
subscription `request` and `settings` objects with the real types from the new
`graphql-subscription` schema definition, or widen `BrunoItem['request']` to
include `connectionParams`. Keep the existing field mappings while preserving
full type checking in the converter.

In
`@packages/bruno-electron/src/ipc/network/graphql-subscription-event-handlers.js`:
- Around line 71-81: Update the warning logic in the subscription event handler
to inspect the merged headers object rather than the pre-merge rawHeaders
collection. Preserve the existing detection and warning message for enabled
Sec-WebSocket-Protocol headers, keeping it aligned with the subsequent deletion
loop over headers.

In `@tests/utils/page/graphql-subscription.ts`:
- Around line 8-19: Centralize stable semantic GraphQL-subscription locators and
remove raw CSS/id selectors. In tests/utils/page/graphql-subscription.ts:8-19,
update the messages, infoMessage, connectionParams, and connectionParamsEditor
builders to use UI test IDs or semantic roles; add the required UI hooks if
absent. In tests/graphql/subscription/subscription-persistence.spec.ts:8-9,
:19-20, and :32-33, expose collection, request-opening, and connection-params
editing actions through the page module and reuse them after restart. In
tests/graphql/subscription/subscription.spec.ts:6-10, :17-18, :59-60, and :87,
expose and reuse sidebar request-item, request-opening, and message-scroller
helpers so both specs contain no inline raw selectors.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 2080dd74-98a5-4fc8-a82b-80ffad4c465e

📥 Commits

Reviewing files that changed from the base of the PR and between 2a60fee and 924940d.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (90)
  • packages/bruno-app/src/components/AiChatSidebar/index.js
  • packages/bruno-app/src/components/AppPreviewKeepAlive/index.js
  • packages/bruno-app/src/components/CollectionSettings/Presets/index.js
  • packages/bruno-app/src/components/CreateUntitledRequest/index.js
  • packages/bruno-app/src/components/RequestPane/ConnectionParams/index.js
  • packages/bruno-app/src/components/RequestPane/GraphQLRequestPane/index.js
  • packages/bruno-app/src/components/RequestPane/GraphQLSchemaActions/useGraphqlSchema.js
  • packages/bruno-app/src/components/RequestPane/GraphQLSubscriptionQueryUrl/StyledWrapper.js
  • packages/bruno-app/src/components/RequestPane/GraphQLSubscriptionQueryUrl/index.js
  • packages/bruno-app/src/components/RequestTabPanel/index.js
  • packages/bruno-app/src/components/RequestTabs/RequestTab/index.js
  • packages/bruno-app/src/components/RequestTabs/RequestTab/resolveNewRequestTarget.js
  • packages/bruno-app/src/components/ResponsePane/GraphqlSubscriptionResponsePane/GraphqlSubscriptionMessagesList/index.js
  • packages/bruno-app/src/components/ResponsePane/GraphqlSubscriptionResponsePane/index.js
  • packages/bruno-app/src/components/ResponsePane/SocketMessagesList/StyledWrapper.js
  • packages/bruno-app/src/components/ResponsePane/SocketMessagesList/index.js
  • packages/bruno-app/src/components/ResponsePane/SocketResponsePane/StyledWrapper.js
  • packages/bruno-app/src/components/ResponsePane/SocketResponsePane/index.js
  • packages/bruno-app/src/components/ResponsePane/Timeline/index.js
  • packages/bruno-app/src/components/ResponsePane/WsResponsePane/WSMessagesList/index.js
  • packages/bruno-app/src/components/ResponsePane/WsResponsePane/index.js
  • packages/bruno-app/src/components/RunnerResults/RunConfigurationPanel/index.jsx
  • packages/bruno-app/src/components/ShareCollection/index.js
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/RequestMethod/index.js
  • packages/bruno-app/src/components/Sidebar/NewRequest/index.js
  • packages/bruno-app/src/pages/Bruno/index.js
  • packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js
  • packages/bruno-app/src/providers/ReduxStore/slices/collections/graphql-subscription-events.spec.js
  • packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js
  • packages/bruno-app/src/providers/ReduxStore/slices/tabs.js
  • packages/bruno-app/src/utils/collections/emptyStateRequest.js
  • packages/bruno-app/src/utils/collections/export.js
  • packages/bruno-app/src/utils/collections/index.js
  • packages/bruno-app/src/utils/common/constants.js
  • packages/bruno-app/src/utils/network/graphql-subscription-event-listeners.js
  • packages/bruno-app/src/utils/network/index.js
  • packages/bruno-app/src/utils/snapshot/index.js
  • packages/bruno-app/src/utils/tabs/index.js
  • packages/bruno-cli/src/utils/bru.js
  • packages/bruno-converters/src/opencollection/items/graphql-subscription.ts
  • packages/bruno-converters/src/opencollection/items/index.ts
  • packages/bruno-converters/tests/opencollection/graphql-subscription.spec.js
  • packages/bruno-electron/src/ipc/collection.js
  • packages/bruno-electron/src/ipc/network/graphql-subscription-event-handlers.js
  • packages/bruno-electron/src/ipc/network/index.js
  • packages/bruno-electron/src/ipc/network/interpolate-vars.js
  • packages/bruno-electron/src/ipc/network/register-app-quit-teardown.js
  • packages/bruno-electron/src/ipc/network/ws-event-handlers.js
  • packages/bruno-electron/src/utils/collection.js
  • packages/bruno-electron/src/utils/constants.js
  • packages/bruno-electron/tests/network/interpolate-vars.spec.js
  • packages/bruno-electron/tests/network/prepare-graphql-subscription-request.spec.js
  • packages/bruno-filestore/src/formats/bru/index.ts
  • packages/bruno-filestore/src/formats/bru/tests/graphql-subscription-request.spec.js
  • packages/bruno-filestore/src/formats/yml/items/parseGraphQLSubscriptionRequest.ts
  • packages/bruno-filestore/src/formats/yml/items/stringifyGraphQLSubscriptionRequest.ts
  • packages/bruno-filestore/src/formats/yml/parseItem.spec.ts
  • packages/bruno-filestore/src/formats/yml/parseItem.ts
  • packages/bruno-filestore/src/formats/yml/stringifyItem.spec.ts
  • packages/bruno-filestore/src/formats/yml/stringifyItem.ts
  • packages/bruno-filestore/src/formats/yml/types/graphql-subscription.ts
  • packages/bruno-filestore/src/formats/yml/utils.ts
  • packages/bruno-lang/v2/src/bruToJson.js
  • packages/bruno-lang/v2/src/jsonToBru.js
  • packages/bruno-lang/v2/tests/bruToJson.spec.js
  • packages/bruno-lang/v2/tests/jsonToBru.spec.js
  • packages/bruno-requests/src/graphql/graphql-subscription-client.js
  • packages/bruno-requests/src/graphql/graphql-subscription-client.spec.js
  • packages/bruno-requests/src/graphql/graphql-transport-ws-protocol.js
  • packages/bruno-requests/src/graphql/graphql-transport-ws-protocol.spec.js
  • packages/bruno-requests/src/index.ts
  • packages/bruno-schema-types/src/collection/item.ts
  • packages/bruno-schema-types/src/requests/graphql-subscription.ts
  • packages/bruno-schema-types/src/requests/index.ts
  • packages/bruno-schema/src/collections/index.js
  • packages/bruno-schema/src/collections/itemSchema.spec.js
  • packages/bruno-tests/package.json
  • packages/bruno-tests/src/graphql/index.js
  • packages/bruno-tests/src/graphql/schema.js
  • packages/bruno-tests/src/graphql/subscriptions.js
  • packages/bruno-tests/src/index.js
  • tests/graphql/subscription/fixtures/collection/bruno.json
  • tests/graphql/subscription/fixtures/collection/on-countdown.bru
  • tests/graphql/subscription/fixtures/collection/on-counter.bru
  • tests/graphql/subscription/fixtures/collection/on-failing.bru
  • tests/graphql/subscription/init-user-data/preferences.json
  • tests/graphql/subscription/subscription-persistence.spec.ts
  • tests/graphql/subscription/subscription.spec.ts
  • tests/utils/page/graphql-subscription.ts
  • tests/utils/page/locators.ts

import { buildCommonLocators } from '../../utils/page/locators';
import { saveRequest } from '../../utils/page/actions';

test('connectionParams and query persist across save and app restart', async ({ pageWithUserData: page, restartApp }) => {

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Test query persistence or narrow the title.

This test only mutates and verifies connectionParams; it does not exercise query persistence across the restart.

As per coding guidelines, tests should cover meaningful new functionality.

🤖 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 `@tests/graphql/subscription/subscription-persistence.spec.ts` at line 5,
Update the test named “connectionParams and query persist across save and app
restart” to either add assertions that save and verify query persistence through
the restart flow, or narrow the test title to describe only connectionParams
persistence. Ensure the test title accurately reflects the behavior it
exercises.

Source: Coding guidelines

Comment on lines +4 to +5
test.describe.serial('graphql subscription', () => {
test('graphql-subscription-request items are visible in the sidebar', async ({ pageWithUserData: page }) => {

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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Remove the cross-test state dependency.

describe.serial masks shared UI state, and the later test explicitly relies on a tab opened by the earlier one. Make each test independently open its request and clean up its subscription so retries and parallel execution are reliable.

As per coding guidelines, each E2E test must be parallel-safe and use isolated fixture state.

🤖 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 `@tests/graphql/subscription/subscription.spec.ts` around lines 4 - 5, Remove
serial execution from the graphql subscription test suite and update each test,
including “graphql-subscription-request items are visible in the sidebar,” to
independently open the required request/tab through its own setup. Ensure every
test cleans up its created subscription and relies only on isolated fixture
state so retries and parallel execution remain safe.

Source: Coding guidelines

This branch has not been deployed

No deployments
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.

2 participants