A local-first personal finance app
:chart_with_upwards_trend: Monte carlo - improve loading speed of dashboard widget (#9320)
Michael Clarke13ae7506ca7
diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsxindex d65424e8c2..fcf4cc39b0 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsx@@ -92,7 +92,8 @@ export function MonteCarlo() {? selectedRun.index: null;- const resolvedConfig = useResolvedMonteCarloConfig(config);+ const { resolvedConfig, hasLiveBalances } =+ useResolvedMonteCarloConfig(config);// reset when widget changesuseEffect(() => {@@ -168,9 +169,10 @@ export function MonteCarlo() {// The simulation is the expensive part of this page (thousands of// runs on the main thread), so it is memoised by hand on its actual// inputs: view switches, run selection and other UI state must not- // re-run it. Nothing runs until the saved config has been loaded+ // re-run it. Nothing runs until the saved config has been loaded and+ // every linked balance has arrivedconst simulation = useMemo(() => {- if (!selectionsInitialized) {+ if (!selectionsInitialized || !hasLiveBalances) {return null;}const params = {@@ -179,7 +181,7 @@ export function MonteCarlo() {deflateToTodaysMoney: showTodaysMoney,};return { params, result: runMonteCarloSimulation(params) };- }, [resolvedConfig, showTodaysMoney, selectionsInitialized]);+ }, [resolvedConfig, showTodaysMoney, selectionsInitialized, hasLiveBalances]);// The worst-first ranking shared by the runs table and the cashflow// view's percentile picker, sorted once per simulationdiff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloCard.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloCard.tsxindex 627f87d8bb..c5ec37dba9 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloCard.tsx@@ -7,10 +7,12 @@ import { styles } from '@actual-app/components/styles';import { theme } from '@actual-app/components/theme';import { View } from '@actual-app/components/view';import type { MonteCarloWidget } from '@actual-app/core/types/models';+import { useQuery } from '@tanstack/react-query';import { FinancialText } from '#components/FinancialText';import { PrivacyFilter } from '#components/PrivacyFilter';import { MonteCarloGraph } from '#components/reports/graphs/MonteCarloGraph';+import { LoadingIndicator } from '#components/reports/LoadingIndicator';import { ReportCard } from '#components/reports/ReportCard';import { ReportCardName } from '#components/reports/ReportCardName';import {@@ -46,19 +48,34 @@ export function MonteCarloCard({// Memoised by hand so hovering the card (which toggles state) doesn't// re-run thousands of simulationsconst config = useMemo(() => monteCarloConfigFromMeta(meta), [meta]);- const resolvedConfig = useResolvedMonteCarloConfig(config);- const result = useMemo(- () =>+ const { resolvedConfig, hasLiveBalances } =+ useResolvedMonteCarloConfig(config);++ // Thousands of simulations take a noticeable slice of a second, so they+ // run as a query: after the dashboard has painted rather than inside+ // render, only once every linked balance is in (each arrival would+ // otherwise trigger a full re-run on stale numbers), and cached by+ // config so coming back to the dashboard doesn't simulate again. The+ // engine is deterministic, so a cached result never goes stale+ const { data } = useQuery({+ queryKey: ['monte-carlo-card', resolvedConfig],+ queryFn: () =>runMonteCarloSimulation({...resolvedConfig,horizonYears: getMonteCarloHorizonYears(resolvedConfig),deflateToTodaysMoney: true,}),- [resolvedConfig],- );+ enabled: hasLiveBalances,+ staleTime: Infinity,+ });+ // While the live balances are still loading the config holds the stored+ // ones, and a result cached for those would flash a since-changed number+ // before the live key replaces it+ const result = hasLiveBalances ? (data ?? null) : null;- const endAge = config.currentAge + result.horizonYears;- const successPercent = Math.round(result.successRate * 1000) / 10;+ const endAge = config.currentAge + getMonteCarloHorizonYears(config);+ const successPercent =+ result != null ? Math.round(result.successRate * 1000) / 10 : null;return (<ReportCard@@ -97,7 +114,9 @@ export function MonteCarloCard({}}><PrivacyFilter activationFilters={[!isCardHovered]}>- <FinancialText>{`${successPercent}%`}</FinancialText>+ <FinancialText>+ {successPercent != null ? `${successPercent}%` : '…'}+ </FinancialText></PrivacyFilter></Block><Block@@ -111,13 +130,17 @@ export function MonteCarloCard({</View></View>- <MonteCarloGraph- percentileBands={result.percentileBands}- startAge={config.currentAge}- compact- showTooltip={!isEditing && !isNarrowWidth}- style={{ height: 'auto', flex: 1 }}- />+ {result != null ? (+ <MonteCarloGraph+ percentileBands={result.percentileBands}+ startAge={config.currentAge}+ compact+ showTooltip={!isEditing && !isNarrowWidth}+ style={{ height: 'auto', flex: 1 }}+ />+ ) : (+ <LoadingIndicator />+ )}</View></ReportCard>);diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/useResolvedMonteCarloConfig.ts b/packages/desktop-client/src/components/reports/reports/monte-carlo/useResolvedMonteCarloConfig.tsindex cda7269e68..38b4607726 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/useResolvedMonteCarloConfig.ts+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/useResolvedMonteCarloConfig.ts@@ -3,6 +3,16 @@ import { useMemo } from 'react';import type { MonteCarloConfig } from '#components/reports/reports/monte-carlo/monteCarloSimulation';import { useAccountBalances } from '#hooks/useAccountBalances';+type ResolvedMonteCarloConfig = {+ resolvedConfig: MonteCarloConfig;+ /**+ * False while any linked account's balance is still on its way: the+ * balances arrive one at a time, so simulating before they all have+ * would run on stale starting balances and then re-run per arrival+ */+ hasLiveBalances: boolean;+};+/*** Resolves account-linked pots to their live balances: a linked pot takes* the account's current balance, falling back to its stored starting@@ -11,18 +21,23 @@ import { useAccountBalances } from '#hooks/useAccountBalances';*/export function useResolvedMonteCarloConfig(config: MonteCarloConfig,-): MonteCarloConfig {- const accountBalances = useAccountBalances(- config.pots- .map(pot => pot.accountId)- .filter((id): id is string => id != null),+): ResolvedMonteCarloConfig {+ const linkedAccountIds = config.pots+ .map(pot => pot.accountId)+ .filter((id): id is string => id != null);+ const accountBalances = useAccountBalances(linkedAccountIds);++ // An account the spreadsheet can't value reports null, which still+ // counts as arrived (the pot keeps its stored balance)+ const hasLiveBalances = linkedAccountIds.every(+ accountId => accountId in accountBalances,);// Memoized by hand: this plain .ts file sits outside the React// Compiler's include (.tsx only), and the compiled consumers key their// auto-memoized simulation runs on this object's identity - a fresh// object every render would re-simulate on every unrelated re-render- return useMemo(+ const resolvedConfig = useMemo(() => ({...config,pots: config.pots.map(pot => {@@ -35,4 +50,9 @@ export function useResolvedMonteCarloConfig(}),[config, accountBalances],);++ return useMemo(+ () => ({ resolvedConfig, hasLiveBalances }),+ [resolvedConfig, hasLiveBalances],+ );}diff --git a/upcoming-release-notes/monte-carlo-card-loading.md b/upcoming-release-notes/monte-carlo-card-loading.mdnew file mode 100644index 0000000000..9ad999f032--- /dev/null+++ b/upcoming-release-notes/monte-carlo-card-loading.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [MikesGlitch]+---++Monte carlo - Load the reports dashboard faster when it has a Monte Carlo card