Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto-reload on app updates #3693

Open
wants to merge 16 commits into
base: master
Choose a base branch
from

Conversation

jfdoming
Copy link
Contributor

@jfdoming jfdoming commented Oct 19, 2024

I couldn't find a way to synchronously check for updates, so the best I figured out is:

  • If an update is found while we're loading the app initially, switch to updating instead.
  • Otherwise, show the user an notification and let them pick the right time to update

This is a little hard to test without pushing an update to this PR. Please let me know if you'd like me to do that so you can see what it looks like. Here's what a notification looks like:
image

Unfortunately couldn't get a good screenshot of the automatic updates since they happen pretty quick

@jfdoming jfdoming added the do not merge Don't merge this!!! label Oct 19, 2024
Copy link

netlify bot commented Oct 19, 2024

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit b202c3f
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/672448d627a5720008290e92
😎 Deploy Preview https://deploy-preview-3693.demo.actualbudget.org
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

github-actions bot commented Oct 19, 2024

Bundle Stats — desktop-client

Hey there, this message comes from a GitHub action that helps you and reviewers to understand how these changes affect the size of this project's bundle.

As this PR is updated, I'll keep you updated on how the bundle size is impacted.

Total

Files count Total bundle size % Changed
9 → 10 5.32 MB → 5.33 MB (+9.5 kB) +0.17%
Changeset
File Δ Size
node_modules/workbox-window/build/workbox-window.prod.es5.mjs 🆕 +5.69 kB 0 B → 5.69 kB
@vite-plugin-pwa/virtual:pwa-register 🆕 +2.34 kB 0 B → 2.34 kB
src/browser-preload.browser.js 📈 +530 B (+13.58%) 3.81 kB → 4.33 kB
src/index.tsx 📈 +87 B (+6.33%) 1.34 kB → 1.43 kB
src/components/FinancesApp.tsx 📈 +576 B (+5.90%) 9.54 kB → 10.1 kB
src/components/App.tsx 📈 +296 B (+5.57%) 5.19 kB → 5.48 kB
home/runner/work/actual/actual/packages/loot-core/src/client/actions/app.ts 📈 +6 B (+0.43%) 1.36 kB → 1.36 kB
node_modules/redux/es/redux.js 📈 +4 B (+0.05%) 8.47 kB → 8.48 kB
View detailed bundle breakdown

Added

Asset File Size % Changed
static/js/workbox-window.prod.es5.js 0 B → 5.69 kB (+5.69 kB) -

Removed

No assets were removed

Bigger

Asset File Size % Changed
static/js/index.js 3.33 MB → 3.34 MB (+3.8 kB) +0.11%

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/usePreviewTransactions.js 1.64 kB 0%
static/js/AppliedFilters.js 21.3 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/narrow.js 82.57 kB 0%
static/js/wide.js 232.16 kB 0%
static/js/ReportRouter.js 1.5 MB 0%

Copy link
Contributor

github-actions bot commented Oct 19, 2024

Bundle Stats — loot-core

Hey there, this message comes from a GitHub action that helps you and reviewers to understand how these changes affect the size of this project's bundle.

As this PR is updated, I'll keep you updated on how the bundle size is impacted.

Total

Files count Total bundle size % Changed
1 1.27 MB 0%

Changeset

No files were changed

View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

No assets were bigger

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
kcab.worker.js 1.27 MB 0%

@jfdoming
Copy link
Contributor Author

Tested with immediate: true, the experience is pretty bad unfortunately as Actual takes a while to download :/ Going to try showing a "reload to update" prompt instead

Comment on lines +61 to 67
const compose = window['__REDUX_DEVTOOLS_EXTENSION_COMPOSE__'] || (f => f);
const store = createStore(
rootReducer,
undefined,
compose(applyMiddleware(thunk)),
);
const boundActions = bindActionCreators(
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Enabling Redux devtools to work. Let me know if I should remove the change, I found it useful when debugging.

@jfdoming jfdoming changed the title [WIP]: Auto-reload on app updates Auto-reload on app updates Oct 20, 2024
@jfdoming jfdoming removed the do not merge Don't merge this!!! label Oct 20, 2024
@@ -152,7 +152,7 @@ export default defineConfig(async ({ mode }) => {
mode === 'desktop'
? undefined
: VitePWA({
registerType: 'autoUpdate',
registerType: 'prompt',
Copy link
Contributor Author

Choose a reason for hiding this comment

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

'prompt' is misleading here. It's just needed so that we can hook into the "update ready" event. We only show a prompt if an update is available later

Copy link
Contributor

coderabbitai bot commented Oct 20, 2024

Walkthrough

The pull request introduces several enhancements to the application's update management system across multiple files. In browser-preload.browser.js, new functionality is added for service worker registration and application update handling, including methods to check for and apply updates. The App.tsx component is modified to incorporate a new asynchronous function, maybeUpdate, which checks for updates during critical initialization processes. In FinancesApp.tsx, a useEffect hook is added to proactively check for updates and notify users when a new version is available. The index.tsx file updates the Redux store setup to integrate the Redux DevTools extension and expands the global interface for better interaction with the main process. Lastly, the Vite configuration is altered to change the service worker registration behavior from automatic to a prompt for users. These changes collectively enhance the application's ability to manage updates and improve user interaction with update notifications.

Possibly related PRs

Suggested labels

:sparkles: Merged

Suggested reviewers

  • MikesGlitch

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (2)
packages/desktop-client/src/index.tsx (1)

Line range hint 70-95: LGTM with a security consideration.

The addition of the inputFocused function and its exposure to the main process via __actionsForMenu improves the interaction between the renderer and the main process. This is particularly useful for managing menu items based on the active element's type.

However, consider the security implications of exposing functionality to the global scope. While this approach is valid for inter-process communication in Electron, it's important to ensure that only necessary functions are exposed and that proper input validation is implemented in the main process when using these exposed functions.

packages/desktop-client/src/components/FinancesApp.tsx (1)

104-121: Add error handling to the async function

The async function run does not include error handling for the awaited calls. If an error occurs during await global.Actual.waitForUpdateReadyForDownload() or while dispatching the notification, it may go unhandled. Consider adding a try-catch block to handle potential errors gracefully.

 useEffect(() => {
   async function run() {
+    try {
       await global.Actual.waitForUpdateReadyForDownload();
       dispatch(
         addNotification({
           // ... notification details ...
         }),
       );
+    } catch (error) {
+      console.error('Error checking for updates:', error);
+      // Optionally, dispatch an error notification or handle the error appropriately.
+    }
   }

   run();
 }, []);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 03f2cab and 89c4994.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/3693.md is excluded by !**/*.md
📒 Files selected for processing (6)
  • packages/desktop-client/src/browser-preload.browser.js (3 hunks)
  • packages/desktop-client/src/components/App.tsx (3 hunks)
  • packages/desktop-client/src/components/FinancesApp.tsx (1 hunks)
  • packages/desktop-client/src/index.tsx (1 hunks)
  • packages/desktop-client/vite.config.mts (1 hunks)
  • packages/loot-core/src/client/actions/app.ts (1 hunks)
🧰 Additional context used
🪛 Biome
packages/desktop-client/src/components/App.tsx

[error] 105-105: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (9)
packages/loot-core/src/client/actions/app.ts (1)

21-22: Excellent improvement to the update process!

The addition of await to global.Actual.applyAppUpdate() is a significant enhancement. This change ensures that the app update is fully applied before updating the app state, which prevents potential race conditions and improves the reliability of the update process. This modification aligns well with the PR objectives and the changes made in other files.

packages/desktop-client/src/index.tsx (1)

61-66: LGTM: Redux DevTools integration looks good.

The integration of Redux DevTools enhances debugging capabilities and follows Redux best practices. This change aligns with the previous comment about its usefulness during debugging.

packages/desktop-client/vite.config.mts (1)

155-155: Approved: Improved update mechanism aligns with PR objectives

The change from registerType: 'autoUpdate' to registerType: 'prompt' in the VitePWA plugin configuration is a positive improvement. This modification aligns well with the PR objectives and addresses the user experience issues reported in the PR comments. By prompting users for updates instead of applying them automatically, it provides more control over the update process and prevents unexpected delays during app loading.

This change works in conjunction with the new update handling mechanisms implemented in other components, as mentioned in the AI summary. It contributes to a more user-friendly update experience, allowing users to choose an appropriate time to perform updates.

packages/desktop-client/src/browser-preload.browser.js (3)

43-50: Deferred update readiness promise is correctly implemented

The implementation of isUpdateReadyForDownloadPromise and markUpdateReadyForDownload effectively creates a promise that resolves when an update is ready, allowing asynchronous waiting on the update status.


51-55: Service worker registration with update handler

registerSW is correctly called with immediate: true and onNeedRefresh: markUpdateReadyForDownload, setting up the service worker to check for updates and mark them as ready when necessary.


157-158: Exposing update readiness methods

The methods isUpdateReadyForDownload and waitForUpdateReadyForDownload are properly added to the global.Actual object, giving external access to the update readiness state.

packages/desktop-client/src/components/App.tsx (3)

54-64: Well-implemented 'maybeUpdate' utility function

The maybeUpdate function is correctly designed to check for updates and apply them before proceeding with the provided callback. The use of generics ensures type safety, and wrapping asynchronous operations enhances code reuse and maintainability.


74-74: Usage of 'await' with 'maybeUpdate' is appropriate

The asynchronous call to initConnection(socketName) is properly wrapped with maybeUpdate and awaited, ensuring that updates are applied before initializing the connection.


90-90: ⚠️ Potential issue

Ensure 'await' is used with 'maybeUpdate'

At this line, maybeUpdate wraps an asynchronous operation but is not awaited. This might cause get-last-opened-backup to execute without ensuring that updates have been applied first.

Apply this diff to fix the issue:

- const budgetId = await maybeUpdate(() => send('get-last-opened-backup'));
+ const budgetId = await maybeUpdate(() => send('get-last-opened-backup'));

Likely invalid or redundant comment.

packages/desktop-client/src/components/App.tsx Outdated Show resolved Hide resolved
packages/desktop-client/src/components/App.tsx Outdated Show resolved Hide resolved
packages/desktop-client/src/components/App.tsx Outdated Show resolved Hide resolved
packages/desktop-client/src/components/FinancesApp.tsx Outdated Show resolved Hide resolved
@jfdoming
Copy link
Contributor Author

^ for electron changes

@MikesGlitch
Copy link
Contributor

^ for electron changes

What electron changes 😅

@youngcw youngcw added this to the v24.11.0 milestone Oct 20, 2024
@MikesGlitch MikesGlitch self-assigned this Oct 20, 2024
@jfdoming
Copy link
Contributor Author

^ for electron changes

What electron changes 😅

Ah sorry, I was just referring to the changes to preload.js/ts to make sure I didn't miss something obvious that needs to be implemented there. I briefly tested out the Electron app and it seemed to work as expected, but not 100% versed in these things yet.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (3)
packages/desktop-client/src/browser-preload.browser.js (1)

157-164: Add error handling to applyAppUpdate.

While the infinite Promise is intentionally used to prevent subsequent async calls from resolving (as clarified in previous discussions), consider adding error handling for updateSW().

Apply this diff to improve error handling:

 applyAppUpdate: async () => {
-  updateSW();
+  try {
+    await updateSW();
+  } catch (error) {
+    console.error('Failed to update service worker:', error);
+    throw error;
+  }

   // Wait for the app to reload
   await new Promise(() => {});
 },
packages/desktop-client/src/components/App.tsx (2)

54-64: Consider handling the no-callback case more explicitly.

The function returns undefined when no callback is provided. Consider making this more explicit in the return type.

-  const maybeUpdate = async <T,>(cb?: () => T): Promise<T> => {
+  const maybeUpdate = async <T,>(cb?: () => T): Promise<T | undefined> => {

104-105: Simplify condition with optional chaining.

The condition can be simplified using optional chaining.

-        const remoteFile = files.find(f => f.fileId === cloudFileId);
-        if (remoteFile && remoteFile.deleted) {
+        if (files.find(f => f.fileId === cloudFileId)?.deleted) {
🧰 Tools
🪛 Biome

[error] 105-105: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f29cf0a and b202c3f.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/3693.md is excluded by !**/*.md
📒 Files selected for processing (7)
  • packages/desktop-client/src/browser-preload.browser.js (3 hunks)
  • packages/desktop-client/src/components/App.tsx (2 hunks)
  • packages/desktop-client/src/components/FinancesApp.tsx (1 hunks)
  • packages/desktop-client/src/index.tsx (1 hunks)
  • packages/desktop-client/vite.config.mts (1 hunks)
  • packages/desktop-electron/preload.ts (1 hunks)
  • packages/loot-core/src/client/actions/app.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/desktop-client/src/components/FinancesApp.tsx
  • packages/desktop-client/src/index.tsx
  • packages/desktop-client/vite.config.mts
  • packages/loot-core/src/client/actions/app.ts
🧰 Additional context used
📓 Learnings (1)
packages/desktop-client/src/browser-preload.browser.js (1)
Learnt from: jfdoming
PR: actualbudget/actual#3693
File: packages/desktop-client/src/browser-preload.browser.js:159-164
Timestamp: 2024-10-20T19:11:51.750Z
Learning: In the `applyAppUpdate` function, the use of `await new Promise(() => {});` is intentional to ensure that any subsequent async calls don't resolve until the app reloads.
🪛 Biome
packages/desktop-client/src/components/App.tsx

[error] 105-105: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (3)
packages/desktop-electron/preload.ts (1)

69-71: Verify the update mechanism integration.

Let's verify how these methods are used in the renderer process to ensure the no-op implementations won't cause issues.

✅ Verification successful

No-op update implementations are safe to use

The verification shows these methods are properly handled in the codebase:

  • In packages/desktop-client/src/browser-preload.browser.js, there's a web-based implementation that manages updates properly
  • In packages/desktop-client/src/components/App.tsx and FinancesApp.tsx, the methods are used defensively:
    • isUpdateReadyForDownload() is checked before taking any action
    • waitForUpdateReadyForDownload() is awaited properly

The no-op implementations in the desktop electron preload are intentional and won't cause issues since the code gracefully handles the "no updates available" case.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how these update-related methods are used in the renderer

# Test 1: Find direct usage of these methods
echo "Searching for direct method usage..."
rg "isUpdateReadyForDownload|waitForUpdateReadyForDownload" --type ts --type tsx

# Test 2: Look for update-related error handling
echo "Checking for update-related error handling..."
rg "catch.*update" --type ts --type tsx -A 3

Length of output: 369


Script:

#!/bin/bash
# Let's try a different approach without file type restrictions
# Search for direct usage of these methods
echo "Searching for direct method usage..."
rg "isUpdateReadyForDownload|waitForUpdateReadyForDownload"

# Look for any update-related code patterns
echo "Checking for update-related patterns..."
rg "update.*ready|ready.*update|checkForUpdates"

# Check the interface or type definitions for these methods
echo "Checking interface definitions..."
rg "interface.*\{[\s\S]*?(isUpdateReadyForDownload|waitForUpdateReadyForDownload)"

Length of output: 1621

packages/desktop-client/src/browser-preload.browser.js (1)

43-54: ⚠️ Potential issue

Consider removing immediate: true flag based on PR feedback.

Based on the PR comments, setting immediate: true resulted in poor user experience due to update download times. Consider removing this flag to align with the proposed "reload to update" approach.

Apply this diff to improve the user experience:

 const updateSW = registerSW({
-  immediate: true,
   onNeedRefresh: markUpdateReadyForDownload,
 });
packages/desktop-client/src/components/App.tsx (1)

67-67: LGTM: Strategic placement of update checks.

The implementation with two update checks (start and end of initialization) provides a good balance between update availability and user experience, as discussed in the PR comments.

Also applies to: 110-110

Comment on lines +69 to +71
// No auto-updates in the desktop app
isUpdateReadyForDownload: () => false,
waitForUpdateReadyForDownload: () => new Promise<void>(() => {}),
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve the update-related implementations and documentation.

The current implementation has a few areas for improvement:

  1. The never-resolving promise in waitForUpdateReadyForDownload could lead to memory leaks
  2. The comment could be more descriptive about why auto-updates are disabled

Consider applying these changes:

-  // No auto-updates in the desktop app
+  // Auto-updates are handled differently in the desktop app through Electron's built-in
+  // auto-update mechanism rather than through the web app's service worker updates
   isUpdateReadyForDownload: () => false,
-  waitForUpdateReadyForDownload: () => new Promise<void>(() => {}),
+  waitForUpdateReadyForDownload: () => Promise.resolve(),
📝 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
// No auto-updates in the desktop app
isUpdateReadyForDownload: () => false,
waitForUpdateReadyForDownload: () => new Promise<void>(() => {}),
// Auto-updates are handled differently in the desktop app through Electron's built-in
// auto-update mechanism rather than through the web app's service worker updates
isUpdateReadyForDownload: () => false,
waitForUpdateReadyForDownload: () => Promise.resolve(),

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants