Repository navigation
feature/autoSave (#582) - #6211
Conversation
WalkthroughThis PR introduces an auto-save feature that periodically persists request and collection changes. It adds UI controls in preferences, a Redux middleware to debounce and schedule saves, modifies save actions to support silent mode (suppressing notifications), updates theme configurations, and includes comprehensive Playwright test coverage. Changes
Sequence DiagramsequenceDiagram
participant User
participant UI as Preferences UI
participant Store as Redux Store
participant Middleware as Autosave Middleware
participant Actions as Save Actions
participant FS as File System
User->>UI: Enable Auto Save & set interval
UI->>Store: dispatch updatePreferences
Store->>Middleware: middleware receives action
Middleware->>Middleware: enable autosave in config
User->>UI: Edit request URL/name
UI->>Store: dispatch action (updateRequest, etc.)
Store->>Middleware: middleware intercepts
Middleware->>Middleware: schedule debounced save<br/>(clear existing timer, start new)
Note over Middleware: Wait for interval...
Middleware->>Actions: dispatch saveRequest(uid, silent=true)
Actions->>FS: persist changes to disk
Actions->>Store: update state
Note over UI: Draft indicator disappears
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 inconclusive)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (7)
packages/bruno-app/src/providers/ReduxStore/middlewares/autosave/middleware.js (2)
4-75: Consider a more maintainable approach for action interception.This hardcoded list of 71 action types is comprehensive but brittle. Adding new edit actions requires manually updating this array, which is easy to forget. Consider using a naming convention pattern (e.g., all actions starting with
collections/) or tagging actions with metadata to automatically identify draft-creating actions.
136-154: Handle missing IDs gracefully.If an intercepted action has an unexpected payload structure (missing
itemUid,folderUid, andcollectionUid), the code silently continues without scheduling a save. While this may be intentional, consider logging a warning in development to catch payload structure issues early.packages/bruno-app/src/providers/ReduxStore/slices/app.js (1)
32-35: Consider a higher default autosave interval.The default interval of 1000ms (1 second) may trigger frequent saves during active editing. While the UI enforces a minimum of 500ms, consider starting with 2-3 seconds for better balance between data safety and system load. Users can adjust based on their preference.
tests/preferences/autosave/autosave.spec.ts (4)
61-63: Replace fixedwaitForTimeoutcalls with expectation‑driven waitsThe three
page.waitForTimeout(...)calls make the tests slower and more brittle than necessary. You can instead rely on Playwright’s built‑in polling on the draft indicator, e.g. let theexpect(...).not.toBeVisible({ timeout: X })assertion handle the autosave delay without an explicit sleep:- // Wait for autosave to trigger (interval + some buffer) - await page.waitForTimeout(1000); - - // Verify draft indicator disappears after autosave - await expect(requestTab.locator('.has-changes-icon')).not.toBeVisible(); + // Draft indicator should eventually disappear after autosave + await expect(requestTab.locator('.has-changes-icon')).not.toBeVisible({ timeout: 2000 });and similarly for the other autosave waits. This keeps the intent clear while aligning with the guideline to avoid
waitForTimeoutwhere anexpectcan express the wait condition.Also applies to: 112-114, 176-177
76-80: Prefer locator assertions over manualtextContentreads for URL checksFor the final URL assertions you currently read
textContentand then assert on the string. It’s more idiomatic (and avoids anystring | null/typing edge cases) to assert directly on the locator text:- const urlEditor = page.locator('#request-url .CodeMirror'); - const urlContent = await urlEditor.locator('.CodeMirror-line').first().textContent(); - expect(urlContent).toContain('api.example.com/users'); + const urlEditor = page.locator('#request-url .CodeMirror'); + await expect(urlEditor).toContainText('api.example.com/users');and similarly for
'api.example.com/existing-draft'. This also gives you built‑in polling if the editor text updates asynchronously.Also applies to: 192-196
5-7: Consider centralizing autosave preference cleanup to avoid state leakageThe first test explicitly disables autosave at the end, but the second test leaves it enabled. If other specs assume a default disabled autosave state, this shared preference could leak across tests. Consider resetting the autosave preference in
afterEach(via the same Preferences UI flow or a helper) so each test starts from a known baseline.Also applies to: 82-99, 159-175, 197-197
21-30: Optionally extract common locators to constants for maintainabilitySelectors like
'#request-url .CodeMirror', the preferences trigger.status-bar button[data-trigger="preferences"], and the request tab locator pattern are repeated in several steps. Extracting them into well‑named constants at test scope (e.g.const urlEditor = page.locator('#request-url .CodeMirror');once per test or helperconst requestTab = (label: string) => page.locator('.request-tab').filter({ has: page.locator('.tab-label', { hasText: label }) });) would reduce duplication and make selector changes easier to manage later.Also applies to: 50-60, 101-111, 136-145, 147-157, 180-181
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (11)
packages/bruno-app/src/components/Preferences/General/index.js(4 hunks)packages/bruno-app/src/components/RequestPane/QueryUrl/index.js(1 hunks)packages/bruno-app/src/components/RequestPane/Vars/index.js(1 hunks)packages/bruno-app/src/providers/ReduxStore/index.js(1 hunks)packages/bruno-app/src/providers/ReduxStore/middlewares/autosave/middleware.js(1 hunks)packages/bruno-app/src/providers/ReduxStore/slices/app.js(1 hunks)packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js(6 hunks)packages/bruno-app/src/themes/dark.js(1 hunks)packages/bruno-app/src/themes/light.js(1 hunks)packages/bruno-electron/src/store/preferences.js(2 hunks)tests/preferences/autosave/autosave.spec.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (CODING_STANDARDS.md)
**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single parameters
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses. Keep 'em tight
Space before and after the arrow in arrow functions.() => {}is good
No space between function name and parentheses.func()notfunc ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Avoid single line abstractions where all that's being done is increasing the call stack with one additional function
Add in meaningful comments instead of obvious ones where complex code flow is explained properly
Files:
packages/bruno-app/src/providers/ReduxStore/index.jspackages/bruno-electron/src/store/preferences.jspackages/bruno-app/src/components/RequestPane/Vars/index.jstests/preferences/autosave/autosave.spec.tspackages/bruno-app/src/providers/ReduxStore/middlewares/autosave/middleware.jspackages/bruno-app/src/components/Preferences/General/index.jspackages/bruno-app/src/providers/ReduxStore/slices/app.jspackages/bruno-app/src/themes/dark.jspackages/bruno-app/src/providers/ReduxStore/slices/collections/actions.jspackages/bruno-app/src/themes/light.jspackages/bruno-app/src/components/RequestPane/QueryUrl/index.js
tests/**/**.*
⚙️ CodeRabbit configuration file
tests/**/**.*: Review the following e2e test code written using the Playwright test library. Ensure that:
Follow best practices for Playwright code and e2e automation
Try to reduce usage of
page.waitForTimeout();in code unless absolutely necessary and the locator cannot be found using existingexpect()playwright callsAvoid using
page.pause()in codeUse locator variables for locators
Avoid using test.only
Use multiple assertions
Promote the use of
test.stepas much as possible so the generated reports are easier to readEnsure that the
fixtureslike the collections are nested inside thefixturesfolderFixture Example*: Here's an example of possible fixture and test pair
. ├── fixtures │ └── collection │ ├── base.bru │ ├── bruno.json │ ├── collection.bru │ ├── ws-test-request-with-headers.bru │ ├── ws-test-request-with-subproto.bru │ └── ws-test-request.bru ├── connection.spec.ts # <- Depends on the collection in ./fixtures/collection ├── headers.spec.ts ├── persistence.spec.ts ├── variable-interpolation │ ├── fixtures │ │ └── collection │ │ ├── environments │ │ ├── bruno.json │ │ └── ws-interpolation-test.bru │ ├── init-user-data │ └── variable-interpolation.spec.ts # <- Depends on the collection in ./variable-interpolation/fixtures/collection └── subproto.spec.ts
Files:
tests/preferences/autosave/autosave.spec.ts
🧬 Code graph analysis (3)
packages/bruno-app/src/providers/ReduxStore/index.js (2)
packages/bruno-app/src/providers/App/useTelemetry.js (1)
isDevEnv(21-23)packages/bruno-app/src/providers/ReduxStore/middlewares/draft/middleware.js (2)
draftDetectMiddleware(76-82)draftDetectMiddleware(76-82)
packages/bruno-app/src/providers/ReduxStore/middlewares/autosave/middleware.js (1)
packages/bruno-js/src/sandbox/quickjs/shims/bruno-request.js (1)
setTimeout(115-117)
packages/bruno-app/src/components/RequestPane/QueryUrl/index.js (8)
packages/bruno-app/src/components/RequestPane/GrpcQueryUrl/index.js (1)
onSave(87-89)packages/bruno-app/src/components/RequestPane/QueryParams/index.js (1)
onSave(42-42)packages/bruno-app/src/components/CollectionSettings/Vars/VarsTable/index.js (1)
onSave(31-31)packages/bruno-app/src/components/FolderSettings/Vars/VarsTable/index.js (1)
onSave(28-28)packages/bruno-app/src/components/RequestPane/Vars/VarsTable/index.js (1)
onSave(30-30)packages/bruno-app/src/components/RequestPane/RequestHeaders/index.js (1)
onSave(35-35)packages/bruno-app/src/components/RequestPane/GraphQLVariables/index.js (1)
onSave(48-48)packages/bruno-app/src/components/RequestPane/GraphQLRequestPane/index.js (1)
onSave(52-52)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: SSL Tests - Windows
- GitHub Check: SSL Tests - macOS
- GitHub Check: SSL Tests - Linux
- GitHub Check: Playwright E2E Tests
- GitHub Check: Unit Tests
- GitHub Check: CLI Tests
🔇 Additional comments (14)
packages/bruno-app/src/themes/light.js (1)
558-562: Additive theme preference looks good
preferences.sidebar.borderis added in a way that’s consistent with the existing theme shape and styling in this file and matches the new dark theme counterpart, so consumers ofpreferences.sidebar.borderwill have coverage for both themes.packages/bruno-app/src/themes/dark.js (1)
548-552: Symmetric preferences addition for dark theme
preferences.sidebar.borderis added with a value consistent with the dark palette and mirrors the light theme’s newpreferencesshape, keeping the public theme API aligned across themes.packages/bruno-app/src/providers/ReduxStore/middlewares/autosave/middleware.js (2)
93-117: LGTM! Bulk draft handling is well-designed.The
saveExistingDraftsfunction correctly identifies drafts across collections, requests, and folders, and schedules debounced saves with the silent flag to avoid notification spam. The use of the helper functions maintains consistency with the codebase.
78-90: No action needed on timer cleanup.The module-level
pendingTimersobject is safe in this context. The autosave middleware is instantiated once when the Redux store is created and never recreated. The existing logic properly manages timers by clearing any previous timer for a key before scheduling a new one, and deleting the timer reference after execution. There is no HMR middleware recreation scenario that would cause stale closures.packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js (3)
97-135: LGTM! Silent parameter implementation is clean.The
silentparameter correctly suppresses success toasts while preserving error notifications. The default value maintains backward compatibility with existing callers.
199-242: Consistent implementation with saveRequest.The
saveFolderRootchanges mirror thesaveRequestpattern, maintaining consistency across the codebase.
2133-2172: Completes the silent parameter pattern.All three save functions (
saveRequest,saveFolderRoot,saveCollectionSettings) now consistently support silent mode, enabling the autosave middleware to persist changes without UI noise.packages/bruno-app/src/providers/ReduxStore/index.js (1)
12-21: Middleware integration looks correct.The
autosaveMiddlewareis properly placed afterdraftDetectMiddlewarein the chain, ensuring drafts are created before autosave attempts to persist them.packages/bruno-app/src/components/RequestPane/QueryUrl/index.js (1)
36-38: Clean removal of unused parameter.The
finalValueparameter was never used inonSave, so removing it is appropriate. The callback at line 113 still passes the argument, but it's safely ignored.packages/bruno-app/src/components/Preferences/General/index.js (4)
40-58: Validation schema is well-designed.The schema correctly handles edge cases:
- Transforms empty strings to undefined for proper validation
- Validates interval as a number ≥ 500ms
- Requires interval when autosave is enabled via custom test
- Clear error messages for each validation rule
75-78: Data handling is correct.Initial values properly extract autoSave preferences with safe defaults, and
handleSavecorrectly includes them in the persisted preferences.Also applies to: 109-112
118-118: Good attention to consistency.Adding the period to the success message maintains consistent punctuation across toast notifications.
321-321: Improved testability and accessibility.Adding
id="defaultCollectionLocation"improves both automated testing selectors and screen reader navigation.tests/preferences/autosave/autosave.spec.ts (1)
4-122: Solid end‑to‑end coverage and good use of Playwright primitivesNice use of
test.step, shared helpers (createCollection,createRequest,closeAllCollections), and multiple assertions to exercise both autosave enabled/disabled flows and persistence across tab reopen. Structure and locator usage are generally clean and follow the Playwright guidelines.Also applies to: 124-197
23b09c2 to
af707de
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
packages/bruno-app/src/providers/ReduxStore/middlewares/autosave/middleware.js (1)
119-139: Disable-branch is unreachable due to early return when autosave is offOn Line 125 you
returnearly when!autoSave?.enabled, so the laterapp/updatePreferencesbranch that clearspendingTimers(Lines 133-139) will never run when the user disables autosave. Timers for already-scheduled saves will keep firing after autosave is turned off, which is exactly what the earlier review comment warned about.You can fix this by handling
app/updatePreferencesbefore the enabled check, e.g.:export const autosaveMiddleware = ({ dispatch, getState }) => (next) => (action) => { // Let the action update the state first const result = next(action); - // Check if autosave is enabled - const { autoSave } = getState().app.preferences; - if (!autoSave?.enabled) return result; - - // When autosave is enabled (or settings change), save any existing drafts - if (action.type === 'app/updatePreferences' && action.payload?.autoSave?.enabled) { - saveExistingDrafts(dispatch, getState, autoSave.interval); - return result; - } - - if (action.type === 'app/updatePreferences' && action.payload?.autoSave?.enabled === false) { - Object.keys(pendingTimers).forEach((key) => { - clearTimeout(pendingTimers[key]); - delete pendingTimers[key]; - }); - return result; - } + const { autoSave } = getState().app.preferences; + + if (action.type === 'app/updatePreferences') { + if (action.payload?.autoSave?.enabled === false) { + Object.keys(pendingTimers).forEach((key) => { + clearTimeout(pendingTimers[key]); + delete pendingTimers[key]; + }); + return result; + } + + if (autoSave?.enabled && action.payload?.autoSave?.enabled) { + saveExistingDrafts(dispatch, getState, autoSave.interval); + return result; + } + } + + // Check if autosave is enabled + if (!autoSave?.enabled) return result;This ensures:
- Disabling autosave always clears and stops pending timers.
- Enabling (or re-enabling) autosave still triggers
saveExistingDrafts.- Other actions still short‑circuit when autosave is off.
🧹 Nitpick comments (2)
packages/bruno-app/src/components/Preferences/General/index.js (1)
280-310: UI controls are well-implemented with good accessibility.The auto-save controls are properly structured with:
- Checkbox and input linked via id/htmlFor
- Conditional disabled state on the interval input
- Visual feedback via opacity when disabled
Minor consistency note: line 293 uses
opacity-50for the disabled state, while other disabled field groups in this file (CA certificate at lines 179, 196, etc.) useopacity-25. Consider standardizing toopacity-25for consistency, though this is purely a visual polish item.packages/bruno-app/src/providers/ReduxStore/middlewares/autosave/middleware.js (1)
144-162: Defensive destructuring fromaction.payloadto avoid runtime errorsLine 144 destructures from
action.payloadwithout a default. If any of theactionsToInterceptever fires with a missing orundefinedpayload, this middleware will throw before it can fall through. Even if current actions always supply payloads, this is fragile for future additions.A small defensive tweak keeps behavior identical when payload exists:
- const { itemUid, folderUid, collectionUid } = action.payload; + const { itemUid, folderUid, collectionUid } = action.payload || {};Please double‑check that all currently intercepted actions indeed carry these fields; if any don’t, this change also prevents hard‑to‑trace crashes when you add them to
actionsToInterceptlater.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
packages/bruno-app/src/components/Preferences/General/index.js(4 hunks)packages/bruno-app/src/providers/ReduxStore/middlewares/autosave/middleware.js(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (CODING_STANDARDS.md)
**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single parameters
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses. Keep 'em tight
Space before and after the arrow in arrow functions.() => {}is good
No space between function name and parentheses.func()notfunc ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Avoid single line abstractions where all that's being done is increasing the call stack with one additional function
Add in meaningful comments instead of obvious ones where complex code flow is explained properly
Files:
packages/bruno-app/src/components/Preferences/General/index.jspackages/bruno-app/src/providers/ReduxStore/middlewares/autosave/middleware.js
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: CLI Tests
- GitHub Check: Playwright E2E Tests
- GitHub Check: Unit Tests
- GitHub Check: SSL Tests - Windows
- GitHub Check: SSL Tests - macOS
- GitHub Check: SSL Tests - Linux
🔇 Additional comments (4)
packages/bruno-app/src/components/Preferences/General/index.js (3)
40-58: LGTM! Validation schema is well-structured.The autoSave validation correctly handles:
- Empty string transformation to undefined for numeric validation
- Minimum interval of 100ms (reasonable for auto-save)
- Cross-field validation ensuring interval is required when auto-save is enabled
311-316: Error display correctly handles both validation levels.The implementation now properly displays both object-level errors (line 311-313) and property-level errors (line 314-316), addressing the past review comment. The logic correctly distinguishes between:
- Object-level validation failure (autoSave as string)
- Property-level validation failure (autoSave.interval as string)
These are mutually exclusive with
abortEarly: true, ensuring clean error messaging.
75-78: LGTM! Auto-save preferences correctly integrated.Initial values provide sensible defaults (enabled: false, interval: 1000ms), and the save handler properly persists the autoSave configuration to the Redux store.
Also applies to: 109-112
packages/bruno-app/src/providers/ReduxStore/middlewares/autosave/middleware.js (1)
77-117: Autosave scheduling and draft sweep look solidThe
pendingTimersmap,scheduleAutoSave, andsaveExistingDrafts(Lines 77-117) are clean and predictable: per-entity keys prevent cross-talk between timers, and the draft sweep correctly differentiates between collection, request, and folder saves while using the silent variants of the save actions. No changes needed here.
Description
Extension of the base PR from #582
JIRA
Contribution Checklist:
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
Tests
✏️ Tip: You can customize this high-level summary in your review settings.