A local-first personal finance app
[AI] :adhesive_bandage: handle dashboard widgets not showing on some devices (#9278)
youngcw767068b64e96
diff --git a/packages/desktop-client/src/hooks/useDashboardPages.test.ts b/packages/desktop-client/src/hooks/useDashboardPages.test.tsnew file mode 100644index 0000000000..34b4fb3f39--- /dev/null+++ b/packages/desktop-client/src/hooks/useDashboardPages.test.ts@@ -0,0 +1,99 @@+import type { Query } from '@actual-app/core/shared/query';+import { renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { resetTestProviders, TestProviders } from '#mocks';++import { useDashboardPageWidgets } from './useDashboardPages';++type TestWidget = { id: string; dashboard_page_id: string | null };++// Pages come back ordered by sort_order, so the first entry is the page+// that adopts widgets whose own page is missing+let pages: Array<{ id: string; name: string }> = [];+let widgets: TestWidget[] = [];++vi.mock('#queries/aqlQuery', () => ({+ aqlQuery: (query: Query) => {+ switch (query.state.table) {+ case 'dashboard_pages':+ return Promise.resolve({ data: pages });+ case 'dashboard':+ return Promise.resolve({ data: widgets });+ default:+ throw new Error(`Unexpected query table: ${query.state.table}`);+ }+ },+}));++function renderWidgets(dashboardPageId: string) {+ return renderHook(() => useDashboardPageWidgets(dashboardPageId), {+ wrapper: TestProviders,+ });+}++describe('useDashboardPageWidgets', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetTestProviders();+ pages = [+ { id: 'first-page', name: 'Main' },+ { id: 'second-page', name: 'Second' },+ ];+ widgets = [];+ });++ it('returns the widgets belonging to the page', async () => {+ widgets = [+ { id: 'a', dashboard_page_id: 'first-page' },+ { id: 'b', dashboard_page_id: 'second-page' },+ ];++ const { result } = renderWidgets('second-page');++ await waitFor(() => expect(result.current.data).toHaveLength(1));+ expect(result.current.data?.map(w => w.id)).toEqual(['b']);+ });++ it('shows a widget whose page does not exist on the first page', async () => {+ widgets = [+ { id: 'a', dashboard_page_id: 'first-page' },+ // Synced in from a device whose seeded page has a different id+ { id: 'orphan', dashboard_page_id: 'page-from-the-other-device' },+ { id: 'page-less', dashboard_page_id: null },+ ];++ const { result } = renderWidgets('first-page');++ await waitFor(() => expect(result.current.data).toHaveLength(3));+ expect(result.current.data?.map(w => w.id)).toEqual([+ 'a',+ 'orphan',+ 'page-less',+ ]);+ });++ it('does not show orphaned widgets on the other pages', async () => {+ widgets = [+ { id: 'b', dashboard_page_id: 'second-page' },+ { id: 'orphan', dashboard_page_id: 'page-from-the-other-device' },+ ];++ const { result } = renderWidgets('second-page');++ await waitFor(() => expect(result.current.data).toHaveLength(1));+ expect(result.current.data?.map(w => w.id)).toEqual(['b']);+ });++ it('adopts onto whichever page sorts first', async () => {+ pages = [{ id: 'only-page', name: 'Only' }];+ widgets = [+ { id: 'orphan', dashboard_page_id: 'page-from-the-other-device' },+ ];++ const { result } = renderWidgets('only-page');++ await waitFor(() => expect(result.current.data).toHaveLength(1));+ expect(result.current.data?.map(w => w.id)).toEqual(['orphan']);+ });+});diff --git a/packages/desktop-client/src/hooks/useDashboardPages.ts b/packages/desktop-client/src/hooks/useDashboardPages.tsindex d2c65ab7d1..a01e5e07fe 100644--- a/packages/desktop-client/src/hooks/useDashboardPages.ts+++ b/packages/desktop-client/src/hooks/useDashboardPages.ts@@ -13,7 +13,27 @@ export function useDashboardPages() {export function useDashboardPageWidgets<W extends DashboardWidgetEntity>(dashboardPageId?: DashboardPageEntity['id'] | null,) {- return useQuery(- dashboardQueries.listDashboardPageWidgets<W>(dashboardPageId),- );+ const { data: dashboardPages } = useDashboardPages();++ const knownPageIds = new Set((dashboardPages ?? []).map(page => page.id));++ // A widget whose page does not exist locally would be filtered off every+ // page and so be invisible. That is what happens to widgets synced from+ // another device: the default page is seeded by a migration, which runs+ // locally and emits no sync messages, so each device generated its own+ // id for it. Show those widgets on the first page, which `sort_order`+ // makes the seeded one on every device.+ const isAdoptingPage =+ dashboardPageId != null && dashboardPageId === dashboardPages?.[0]?.id;++ return useQuery({+ ...dashboardQueries.listDashboardWidgets<W>(),+ select: widgets =>+ widgets.filter(+ widget =>+ widget.dashboard_page_id === dashboardPageId ||+ (isAdoptingPage && !knownPageIds.has(widget.dashboard_page_id)),+ ),+ enabled: !!dashboardPageId,+ });}diff --git a/packages/desktop-client/src/reports/queries.ts b/packages/desktop-client/src/reports/queries.tsindex e461203ab8..b8fb68809e 100644--- a/packages/desktop-client/src/reports/queries.ts+++ b/packages/desktop-client/src/reports/queries.ts@@ -34,15 +34,6 @@ export const dashboardQueries = {return data;},}),- listDashboardPageWidgets: <T extends DashboardWidgetEntity>(- dashboardPageId?: DashboardPageEntity['id'] | null,- ) =>- queryOptions<T[]>({- ...dashboardQueries.listDashboardWidgets<T>(),- select: widgets =>- widgets.filter(w => w.dashboard_page_id === dashboardPageId),- enabled: !!dashboardPageId,- }),listDashboardPages: () =>queryOptions<DashboardPageEntity[]>({queryKey: [...dashboardQueries.lists(), 'pages'],diff --git a/packages/loot-core/migrations/1792441821604_dashboard_page_sort_order.sql b/packages/loot-core/migrations/1792441821604_dashboard_page_sort_order.sqlnew file mode 100644index 0000000000..6db25819fa--- /dev/null+++ b/packages/loot-core/migrations/1792441821604_dashboard_page_sort_order.sql@@ -0,0 +1,15 @@+BEGIN TRANSACTION;++-- The default keeps a page created by a client that predates this column+-- (which syncs id and name but no sort_order) sorting last rather than+-- first: SQLite orders NULL ahead of every number, which would have such a+-- page displace the seeded one below.+ALTER TABLE dashboard_pages ADD COLUMN sort_order REAL DEFAULT 1000000000;++-- Backfill in insertion order. The page the `multiple_dashboards` migration+-- seeded is always the first row in this table, so it sorts first on every+-- device -- which is what makes it the page that adopts widgets synced from+-- a device whose seeded page has a different id. 16384 is SORT_INCREMENT.+UPDATE dashboard_pages SET sort_order = rowid * 16384;++COMMIT;diff --git a/packages/loot-core/src/server/aql/schema/index.ts b/packages/loot-core/src/server/aql/schema/index.tsindex 2ecf4a6508..84b193c11f 100644--- a/packages/loot-core/src/server/aql/schema/index.ts+++ b/packages/loot-core/src/server/aql/schema/index.ts@@ -203,6 +203,7 @@ export const schema = {dashboard_pages: {id: f('id'),name: f('string'),+ sort_order: f('float'),tombstone: f('boolean'),},dashboard: {@@ -296,6 +297,8 @@ export const schemaConfig: SchemaConfig = {return ['sort_order', 'name'];case 'account_groups':return ['sort_order', 'id'];+ case 'dashboard_pages':+ return ['sort_order', 'id'];case 'schedules':return [{ $condition: { completed: true } }, 'next_date'];default:diff --git a/packages/loot-core/src/server/dashboard/app.ts b/packages/loot-core/src/server/dashboard/app.tsindex c0c751b28c..fffe09f9f1 100644--- a/packages/loot-core/src/server/dashboard/app.ts+++ b/packages/loot-core/src/server/dashboard/app.ts@@ -6,6 +6,7 @@ import * as fs from '#platform/server/fs';import { createApp } from '#server/app';import { aqlQuery } from '#server/aql';import * as db from '#server/db';+import { SORT_INCREMENT } from '#server/db/sort';import { ValidationError } from '#server/errors';import { requiredFields } from '#server/models';import { mutator } from '#server/mutators';@@ -107,8 +108,14 @@ const exportModel = {};async function createDashboardPage({ name }: { name: string }) {+ const lastPage = await db.first<Pick<db.DbDashboardPage, 'sort_order'>>(+ `SELECT sort_order FROM dashboard_pages+ ORDER BY sort_order DESC, id DESC LIMIT 1`,+ );+ const sort_order = (lastPage?.sort_order ?? 0) + SORT_INCREMENT;+const id = uuidv4();- await db.insertWithSchema('dashboard_pages', { id, name });+ await db.insertWithSchema('dashboard_pages', { id, name, sort_order });return id;}diff --git a/packages/loot-core/src/server/dashboard/dashboard-pages.test.ts b/packages/loot-core/src/server/dashboard/dashboard-pages.test.tsnew file mode 100644index 0000000000..26940faaa2--- /dev/null+++ b/packages/loot-core/src/server/dashboard/dashboard-pages.test.ts@@ -0,0 +1,120 @@+import { beforeEach, describe, expect, it } from 'vitest';++import { aqlQuery } from '#server/aql';+import * as db from '#server/db';+import { loadMappings } from '#server/db/mappings';+import { SORT_INCREMENT } from '#server/db/sort';+import { runMutator } from '#server/mutators';+import { q } from '#shared/query';+import type { DashboardPageEntity } from '#types/models';++import { app as dashboardApp } from './app';++async function getPages() {+ const { data } = await aqlQuery(q('dashboard_pages').select('*'));+ return data as DashboardPageEntity[];+}++function createPage(name: string) {+ return runMutator(() => dashboardApp.handlers['dashboard-create']({ name }));+}++describe('dashboard page ordering', () => {+ beforeEach(async () => {+ await global.emptyDatabase()();+ await loadMappings();+ });++ it('gives the seeded page a sort order', async () => {+ const pages = await getPages();++ // `multiple_dashboards` seeds exactly one page, and it is the first row+ // in the table on every device — which is what lets it be the page that+ // adopts widgets synced from a device whose seeded page has another id+ expect(pages).toHaveLength(1);+ expect(pages[0].sort_order).toBe(SORT_INCREMENT);+ });++ it('appends newly created pages after the existing ones', async () => {+ const [seeded] = await getPages();++ await createPage('Second');+ await createPage('Third');++ expect((await getPages()).map(({ sort_order }) => sort_order)).toEqual([+ seeded.sort_order,+ seeded.sort_order + SORT_INCREMENT,+ seeded.sort_order + SORT_INCREMENT * 2,+ ]);+ });++ it('returns pages in sort order, seeded page first', async () => {+ await createPage('Second');+ await createPage('Third');++ expect((await getPages()).map(({ name }) => name)).toEqual([+ 'Main',+ 'Second',+ 'Third',+ ]);+ });++ it('sorts a page from a client without the column last', async () => {+ // A client that predates sort_order syncs a page's id and name only,+ // leaving the column at its default. It must not displace the seeded+ // page, which is what adopts widgets synced from another device+ db.runQuery('INSERT INTO dashboard_pages (id, name) VALUES (?, ?)', [+ 'from-an-older-client',+ 'Older',+ ]);++ expect((await getPages()).map(({ name }) => name)).toEqual([+ 'Main',+ 'Older',+ ]);+ });++ it('keeps the remaining pages ordered after a delete', async () => {+ const secondId = await createPage('Second');+ await createPage('Third');++ await runMutator(() =>+ dashboardApp.handlers['dashboard-delete'](secondId as string),+ );++ expect((await getPages()).map(({ name }) => name)).toEqual([+ 'Main',+ 'Third',+ ]);+ });+});++describe('dashboard page widgets', () => {+ beforeEach(async () => {+ await global.emptyDatabase()();+ await loadMappings();+ });++ it('keeps a widget pointed at the page it was added to', async () => {+ const [seeded] = await getPages();+ const secondId = (await createPage('Second')) as string;++ await runMutator(() =>+ dashboardApp.handlers['dashboard-add-widget']({+ type: 'markdown-card',+ width: 4,+ height: 2,+ meta: { content: 'hi' },+ dashboard_page_id: secondId,+ }),+ );++ const { data } = await aqlQuery(+ q('dashboard')+ .filter({ type: 'markdown-card', dashboard_page_id: secondId })+ .select('*'),+ );+ expect(data).toHaveLength(1);+ expect(seeded.id).not.toBe(secondId);+ });+});diff --git a/packages/loot-core/src/server/db/types/index.ts b/packages/loot-core/src/server/db/types/index.tsindex cff2c7ad96..da20dd1499 100644--- a/packages/loot-core/src/server/db/types/index.ts+++ b/packages/loot-core/src/server/db/types/index.ts@@ -281,6 +281,7 @@ export type DbCustomReport = {export type DbDashboardPage = {id: string;name: string;+ sort_order: number;tombstone: 1 | 0;};diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.tsindex 6e0994383d..38de77593b 100644--- a/packages/loot-core/src/types/models/dashboard.ts+++ b/packages/loot-core/src/types/models/dashboard.ts@@ -5,6 +5,7 @@ import type { RuleConditionEntity } from './rule';export type DashboardPageEntity = {id: string;name: string;+ sort_order: number;tombstone: boolean;};diff --git a/upcoming-release-notes/fix-dashboard-page-id-skew.md b/upcoming-release-notes/fix-dashboard-page-id-skew.mdnew file mode 100644index 0000000000..18fd1d6a7e--- /dev/null+++ b/upcoming-release-notes/fix-dashboard-page-id-skew.md@@ -0,0 +1,6 @@+---+category: Bugfix+authors: [youngcw]+---++Fix reports added on one device never showing up on your other devices, and bring back any that went missing