Skip to content

Open source personal finance application

fix(categories): harden offline sync and parent/child invariants

Ilya Komichev2dfde5282048
diff --git a/app/components/categories/Form.vue b/app/components/categories/Form.vue
index def6eb01..673bdf55 100644
--- a/app/components/categories/Form.vue
+++ b/app/components/categories/Form.vue
@@ -14,7 +14,7 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
- afterSave: []
+ afterSave: [id: CategoryId]
update: [key: keyof CategoryForm, value: CategoryForm[keyof CategoryForm]]
}>()
@@ -25,9 +25,17 @@ const editCategoryId = props.categoryId ?? generateId()
const isUpdateChildCategoriesColor = ref(true)
const prevChildIds = computed(() => props.categoryId ? categoriesStore.getChildrenIds(props.categoryId) : [])
const selectedChildIds = ref<CategoryId[]>([...prevChildIds.value])
+let lastSyncedPrevIds = [...prevChildIds.value]
+// Don't blow away user's in-progress selection when prevChildIds changes due
+// to a realtime patch on another device. Reset only if user hasn't deviated.
watch(prevChildIds, (ids) => {
- selectedChildIds.value = [...ids]
+ const sameAsLastSeen
+ = selectedChildIds.value.length === lastSyncedPrevIds.length
+ && selectedChildIds.value.every(id => lastSyncedPrevIds.includes(id))
+ if (sameAsLastSeen)
+ selectedChildIds.value = [...ids]
+ lastSyncedPrevIds = [...ids]
}, { flush: 'sync' })
const hasChildren = computed(() => selectedChildIds.value.length > 0)
@@ -248,13 +256,13 @@ async function onSave() {
}
}
- await categoriesStore.saveCategory({
+ const result = await categoriesStore.saveCategory({
id: editCategoryId,
isUpdateChildCategoriesColor: isUpdateChildCategoriesColor.value,
nextChildIds: isAllowManageChildren.value ? [...selectedChildIds.value] : undefined,
values: parsed.data,
})
- emit('afterSave')
+ emit('afterSave', result?.convexId ?? editCategoryId)
}
</script>
@@ -445,7 +453,7 @@ async function onSave() {
v-for="icon in iconGroup"
:key="icon"
:class="cn('flex-center text-icon-primary size-10 cursor-pointer rounded-full border-2 border-transparent',
- icon === props.categoryForm.icon && 'border-(--ui-primary)',
+ icon === props.categoryForm.icon && 'border-primary',
)"
:style="{ background: props.categoryForm.color }"
@click="emit('update', 'icon', icon)"
@@ -512,15 +520,15 @@ async function onSave() {
:key="id"
type="button"
:aria-pressed="selectedChildIds.includes(id)"
- :class="cn('flex w-full items-center gap-3 px-3 py-2 text-left transition hover:bg-(--ui-bg-muted)', selectedChildIds.includes(id) && 'bg-(--ui-bg-muted)')"
+ :class="cn('flex w-full items-center gap-3 px-3 py-2 text-left transition hover:bg-muted', selectedChildIds.includes(id) && 'bg-muted')"
@click="toggleChildSelection(id)"
>
- <div :class="cn('flex size-5 shrink-0 items-center justify-center rounded border transition', selectedChildIds.includes(id) ? 'border-(--ui-primary) bg-(--ui-primary)' : 'border-(--ui-border)')">
+ <div :class="cn('flex size-5 shrink-0 items-center justify-center rounded border transition', selectedChildIds.includes(id) ? 'border-primary bg-primary' : 'border-default')">
<Icon
v-if="selectedChildIds.includes(id)"
name="mdi:check"
size="14"
- class="text-(--ui-bg)"
+ class="text-icon-primary"
/>
</div>
<UiIconBase
diff --git a/app/components/categories/useCategoriesStore.test.ts b/app/components/categories/useCategoriesStore.test.ts
index 17028390..9c1e8540 100644
--- a/app/components/categories/useCategoriesStore.test.ts
+++ b/app/components/categories/useCategoriesStore.test.ts
@@ -11,16 +11,24 @@ vi.mock('~~/services/convex/api', () => ({
vi.mock('~/components/categories/utils', () => ({
compareCategoriesByParentAndName: () => 0,
compareCategoryIds: () => 0,
+ computeChildrenDiff: (prev: string[], next: string[]) => {
+ const prevSet = new Set(prev)
+ const nextSet = new Set(next)
+ return {
+ added: next.filter(id => !prevSet.has(id)),
+ removed: prev.filter(id => !nextSet.has(id)),
+ }
+ },
getTransactibleCategoriesIds: () => [],
}))
-const mutationMock = vi.fn(() => Promise.resolve())
-const actionMock = vi.fn(() => Promise.resolve())
+const mutationMock = vi.fn<(path: string, args?: unknown) => Promise<unknown>>(() => Promise.resolve(undefined))
+const actionMock = vi.fn<(path: string, args?: unknown) => Promise<unknown>>(() => Promise.resolve(undefined))
const onUpdateMock = vi.fn()
vi.stubGlobal('useConvexClientWithApi', () => ({
api: {
- categories: { create: 'categories.create', list: 'categories.list', remove: 'categories.remove', update: 'categories.update', updateWithChildren: 'categories.updateWithChildren' },
+ categories: { create: 'categories.create', list: 'categories.list', remove: 'categories.remove', setChildren: 'categories.setChildren', update: 'categories.update', updateWithChildren: 'categories.updateWithChildren' },
},
client: {
action: actionMock,
@@ -48,6 +56,8 @@ vi.mock('~/components/offline/helpers', async (importOriginal) => {
pushOfflineOp: vi.fn(actual.pushOfflineOp),
removeOfflineOp: vi.fn(actual.removeOfflineOp),
removeOfflineOpByType: vi.fn(actual.removeOfflineOpByType),
+ removeOfflineOps: vi.fn(actual.removeOfflineOps),
+ updateOfflineOpData: vi.fn(actual.updateOfflineOpData),
}
})
@@ -242,6 +252,449 @@ describe('useCategoriesStore', () => {
})
})
+ describe('saveCategory — create new parent with children', () => {
+ it('remaps children parentId from local to convex id after create resolves', async () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ child1: makeCategory({ name: 'Child 1', parentId: 'oldRoot' }),
+ child2: makeCategory({ name: 'Child 2' }),
+ oldRoot: makeCategory({ name: 'Old Root' }),
+ }
+
+ mutationMock.mockImplementation((path: string) => {
+ if (path === 'categories.create')
+ return Promise.resolve('convex_new')
+ return Promise.resolve()
+ })
+
+ store.saveCategory({
+ id: 'local_xyz',
+ isUpdateChildCategoriesColor: false,
+ nextChildIds: ['child1', 'child2'],
+ values: makeCategory({ name: 'New Parent' }),
+ })
+
+ expect(store.items.child1!.parentId).toBe('local_xyz')
+ expect(store.items.child2!.parentId).toBe('local_xyz')
+
+ await vi.waitFor(() => {
+ expect(store.items.child1!.parentId).toBe('convex_new')
+ expect(store.items.child2!.parentId).toBe('convex_new')
+ })
+ })
+
+ it('calls setChildren with convex parent id after create resolves', async () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ child1: makeCategory({ name: 'Child 1' }),
+ }
+
+ mutationMock.mockImplementation((path: string) => {
+ if (path === 'categories.create')
+ return Promise.resolve('convex_new')
+ return Promise.resolve()
+ })
+
+ store.saveCategory({
+ id: 'local_xyz',
+ isUpdateChildCategoriesColor: false,
+ nextChildIds: ['child1'],
+ values: makeCategory({ name: 'New Parent' }),
+ })
+
+ await vi.waitFor(() => {
+ expect(mutationMock).toHaveBeenCalledWith(
+ 'categories.setChildren',
+ expect.objectContaining({
+ addIds: ['child1'],
+ id: 'convex_new',
+ removeIds: [],
+ }),
+ )
+ })
+ })
+
+ it('filters local-id children from setChildren addIds', async () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ child1: makeCategory({ name: 'Child 1' }),
+ local_child: makeCategory({ name: 'Local Child' }),
+ }
+
+ mutationMock.mockImplementation((path: string) => {
+ if (path === 'categories.create')
+ return Promise.resolve('convex_new')
+ return Promise.resolve()
+ })
+
+ store.saveCategory({
+ id: 'local_parent',
+ isUpdateChildCategoriesColor: false,
+ nextChildIds: ['child1', 'local_child'],
+ values: makeCategory({ name: 'New Parent' }),
+ })
+
+ await vi.waitFor(() => {
+ expect(mutationMock).toHaveBeenCalledWith(
+ 'categories.setChildren',
+ expect.objectContaining({ addIds: ['child1'] }),
+ )
+ })
+ })
+
+ it('passes childrenColor when isUpdateChildCategoriesColor is true', async () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ child1: makeCategory({ color: '#f00', name: 'Child 1' }),
+ }
+
+ mutationMock.mockImplementation((path: string) => {
+ if (path === 'categories.create')
+ return Promise.resolve('convex_new')
+ return Promise.resolve()
+ })
+
+ store.saveCategory({
+ id: 'local_xyz',
+ isUpdateChildCategoriesColor: true,
+ nextChildIds: ['child1'],
+ values: makeCategory({ color: '#00f', name: 'New Parent' }),
+ })
+
+ await vi.waitFor(() => {
+ expect(mutationMock).toHaveBeenCalledWith(
+ 'categories.setChildren',
+ expect.objectContaining({ childrenColor: '#00f' }),
+ )
+ })
+ })
+
+ it('rolls back children parentId and color when setChildren fails', async () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ child1: makeCategory({ color: '#aaa', name: 'Child 1', parentId: 'oldRoot' }),
+ oldRoot: makeCategory({ name: 'Old Root' }),
+ }
+
+ mutationMock.mockImplementation((path: string) => {
+ if (path === 'categories.create')
+ return Promise.resolve('convex_new')
+ if (path === 'categories.setChildren')
+ return Promise.reject(new Error('Server error'))
+ return Promise.resolve()
+ })
+
+ store.saveCategory({
+ id: 'local_xyz',
+ isUpdateChildCategoriesColor: true,
+ nextChildIds: ['child1'],
+ values: makeCategory({ color: '#00f', name: 'New Parent' }),
+ })
+
+ await vi.waitFor(() => {
+ expect(store.items.child1!.parentId).toBe('oldRoot')
+ expect(store.items.child1!.color).toBe('#aaa')
+ })
+ })
+
+ it('skips setChildren when only local-id children selected', async () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ local_child: makeCategory({ name: 'Local Child' }),
+ }
+
+ mutationMock.mockImplementation((path: string) => {
+ if (path === 'categories.create')
+ return Promise.resolve('convex_new')
+ return Promise.resolve()
+ })
+
+ store.saveCategory({
+ id: 'local_parent',
+ isUpdateChildCategoriesColor: false,
+ nextChildIds: ['local_child'],
+ values: makeCategory({ name: 'New Parent' }),
+ })
+
+ await vi.waitFor(() => {
+ expect(mutationMock).toHaveBeenCalledWith('categories.create', expect.anything())
+ })
+ // Allow potential setChildren microtask to flush
+ await Promise.resolve()
+ expect(mutationMock).not.toHaveBeenCalledWith('categories.setChildren', expect.anything())
+ })
+ })
+
+ describe('saveCategory — optimistic updatedAt', () => {
+ it('stamps updatedAt on the saved category', () => {
+ const before = Date.now()
+ const store = useCategoriesStore()
+
+ store.saveCategory({
+ id: 'c1',
+ isUpdateChildCategoriesColor: false,
+ values: makeCategory(),
+ })
+
+ const after = Date.now()
+ const updatedAt = store.items.c1!.updatedAt
+ expect(updatedAt).toBeTypeOf('number')
+ expect(updatedAt!).toBeGreaterThanOrEqual(before)
+ expect(updatedAt!).toBeLessThanOrEqual(after)
+ })
+
+ it('stamps updatedAt on color-propagated children', () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ child1: makeCategory({ color: '#f00', name: 'Child 1', parentId: 'parent1', updatedAt: 1 }),
+ parent1: makeCategory({ color: '#f00', name: 'Parent', updatedAt: 1 }),
+ }
+
+ store.saveCategory({
+ id: 'parent1',
+ isUpdateChildCategoriesColor: true,
+ values: makeCategory({ color: '#00f', name: 'Parent' }),
+ })
+
+ expect(store.items.child1!.updatedAt!).toBeGreaterThan(1)
+ })
+
+ it('stamps updatedAt on reparented children', () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ child1: makeCategory({ name: 'Child 1', parentId: 0, updatedAt: 1 }),
+ parent1: makeCategory({ name: 'Parent', updatedAt: 1 }),
+ }
+
+ store.saveCategory({
+ id: 'parent1',
+ isUpdateChildCategoriesColor: false,
+ nextChildIds: ['child1'],
+ values: makeCategory({ name: 'Parent' }),
+ })
+
+ expect(store.items.child1!.parentId).toBe('parent1')
+ expect(store.items.child1!.updatedAt!).toBeGreaterThan(1)
+ })
+
+ it('applyRealtimePatch ignores stale doc with older updatedAt after in-flight clears', async () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ c1: makeCategory({ name: 'Optimistic Name', updatedAt: 5000 }),
+ }
+
+ // Skip in-flight protection: only updatedAt comparison is in play.
+ store.applyRealtimePatch({
+ deletedIds: [],
+ docs: [{
+ _creationTime: 0,
+ _id: 'c1',
+ color: '#f00',
+ icon: 'mdi:food',
+ name: 'Stale Server Name',
+ parentId: 0,
+ showInLastUsed: true,
+ showInQuickSelector: false,
+ updatedAt: 4000,
+ userId: 'u1',
+ }],
+ serverTime: Date.now(),
+ truncated: false,
+ })
+
+ expect(store.items.c1!.name).toBe('Optimistic Name')
+ })
+ })
+
+ describe('saveCategory — offline queue corrections (Phase 3)', () => {
+ it('3b: patches queued child update op parentId after parent remap', async () => {
+ const store = useCategoriesStore()
+ store.items = { ...store.items, child1: makeCategory({ name: 'Child 1' }) }
+
+ mutationMock.mockImplementation((path: string) => {
+ if (path === 'categories.create')
+ return Promise.resolve('convex_p1')
+ return Promise.resolve()
+ })
+
+ store.saveCategory({
+ id: 'local_p1',
+ isUpdateChildCategoriesColor: false,
+ nextChildIds: ['child1'],
+ values: makeCategory({ name: 'New Parent' }),
+ })
+
+ await vi.waitFor(() => {
+ expect(offlineHelpers.updateOfflineOpData).toHaveBeenCalledWith(
+ 'categories',
+ 'child1',
+ { parentId: 'convex_p1' },
+ )
+ })
+ })
+
+ it('3c: queues per-kept-child color op for offline survival', () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ child1: makeCategory({ color: '#f00', name: 'Child 1', parentId: 'parent1' }),
+ parent1: makeCategory({ color: '#f00', name: 'Parent' }),
+ }
+
+ store.saveCategory({
+ id: 'parent1',
+ isUpdateChildCategoriesColor: true,
+ values: makeCategory({ color: '#00f', name: 'Parent' }),
+ })
+
+ expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({ color: '#00f' }),
+ entity: 'categories',
+ id: 'child1',
+ type: 'update',
+ }),
+ )
+ })
+
+ it('3d: setChildren rollback drains per-child reparent ops (existing parent)', async () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ child1: makeCategory({ name: 'Child 1', parentId: 0 }),
+ parent1: makeCategory({ name: 'Parent' }),
+ }
+
+ mutationMock.mockImplementation((path: string) => {
+ if (path === 'categories.setChildren')
+ return Promise.reject(new Error('Server error'))
+ return Promise.resolve()
+ })
+
+ store.saveCategory({
+ id: 'parent1',
+ isUpdateChildCategoriesColor: false,
+ nextChildIds: ['child1'],
+ values: makeCategory({ name: 'Parent' }),
+ })
+
+ await vi.waitFor(() => {
+ expect(offlineHelpers.removeOfflineOps).toHaveBeenCalledWith(
+ 'categories',
+ expect.arrayContaining(['child1']),
+ )
+ })
+ expect(store.items.child1!.parentId).toBe(0)
+ })
+
+ it('3b/3d: existing-parent setChildren filters local-id children out of server call', async () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ local_child: makeCategory({ name: 'Local Child', parentId: 0 }),
+ parent1: makeCategory({ name: 'Parent' }),
+ server_child: makeCategory({ name: 'Server Child', parentId: 0 }),
+ }
+
+ store.saveCategory({
+ id: 'parent1',
+ isUpdateChildCategoriesColor: false,
+ nextChildIds: ['server_child', 'local_child'],
+ values: makeCategory({ name: 'Parent' }),
+ })
+
+ await vi.waitFor(() => {
+ expect(mutationMock).toHaveBeenCalledWith(
+ 'categories.setChildren',
+ expect.objectContaining({ addIds: ['server_child'] }),
+ )
+ })
+ })
+
+ it('3d: existing-parent setChildren rollback patches local-child queued op parentId', async () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ local_child: makeCategory({ name: 'Local Child', parentId: 0 }),
+ parent1: makeCategory({ name: 'Parent' }),
+ server_child: makeCategory({ name: 'Server Child', parentId: 0 }),
+ }
+
+ mutationMock.mockImplementation((path: string) => {
+ if (path === 'categories.setChildren')
+ return Promise.reject(new Error('Server error'))
+ return Promise.resolve()
+ })
+
+ store.saveCategory({
+ id: 'parent1',
+ isUpdateChildCategoriesColor: false,
+ nextChildIds: ['server_child', 'local_child'],
+ values: makeCategory({ name: 'Parent' }),
+ })
+
+ await vi.waitFor(() => {
+ expect(offlineHelpers.updateOfflineOpData).toHaveBeenCalledWith(
+ 'categories',
+ 'local_child',
+ { parentId: 0 },
+ )
+ })
+ const removeCalls = (offlineHelpers.removeOfflineOps as any).mock.calls
+ const flatRemoved = removeCalls.flatMap((c: any[]) => c[1])
+ expect(flatRemoved).not.toContain('local_child')
+ })
+
+ it('3d: setChildren rollback in new-parent branch drains non-local + patches local children', async () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ child1: makeCategory({ name: 'Child 1', parentId: 0 }),
+ local_child2: makeCategory({ name: 'Local Child', parentId: 0 }),
+ }
+
+ mutationMock.mockImplementation((path: string) => {
+ if (path === 'categories.create')
+ return Promise.resolve('convex_p1')
+ if (path === 'categories.setChildren')
+ return Promise.reject(new Error('Server error'))
+ return Promise.resolve()
+ })
+
+ store.saveCategory({
+ id: 'local_p1',
+ isUpdateChildCategoriesColor: false,
+ nextChildIds: ['child1', 'local_child2'],
+ values: makeCategory({ name: 'New Parent' }),
+ })
+
+ await vi.waitFor(() => {
+ expect(offlineHelpers.removeOfflineOps).toHaveBeenCalledWith(
+ 'categories',
+ expect.arrayContaining(['child1']),
+ )
+ })
+ // Non-local child purged, local child kept (its create op stays — patched to prev parentId).
+ const removeCalls = (offlineHelpers.removeOfflineOps as any).mock.calls
+ const flatRemoved = removeCalls.flatMap((c: any[]) => c[1])
+ expect(flatRemoved).not.toContain('local_child2')
+ expect(offlineHelpers.updateOfflineOpData).toHaveBeenCalledWith(
+ 'categories',
+ 'local_child2',
+ { parentId: 0 },
+ )
+ })
+ })
+
describe('deleteCategory — optimistic UI', () => {
it('removes item from store immediately', () => {
const store = useCategoriesStore()
diff --git a/app/components/categories/useCategoriesStore.ts b/app/components/categories/useCategoriesStore.ts
index 7db0654a..16385a84 100644
--- a/app/components/categories/useCategoriesStore.ts
+++ b/app/components/categories/useCategoriesStore.ts
@@ -6,6 +6,7 @@ import type { RemapInfo } from '~/composables/useStoreSync'
import { compareCategoryIds, computeChildrenDiff, getTransactibleCategoriesIds } from '~/components/categories/utils'
import { useDemo } from '~/components/demo/useDemo'
+import { removeOfflineOps, updateOfflineOpData } from '~/components/offline/helpers'
import { STORAGE_KEYS } from '~/components/offline/storageKeys'
import { TrnType } from '~/components/trns/types'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
@@ -13,7 +14,7 @@ import { createDebouncedPersist, handleMutationResult, isInFlight, mergeOfflineO
import { createLogger } from '~/utils/logger'
const adjustment: CategoryItem = {
- color: 'var(--text-4)',
+ color: '',
icon: 'mdi:plus-minus',
name: 'Adjustment',
parentId: 0,
@@ -22,7 +23,7 @@ const adjustment: CategoryItem = {
}
const transfer: CategoryItem = {
- color: 'var(--text-4)',
+ color: '',
icon: 'mdi:repeat',
name: 'Transfer',
parentId: 0,
@@ -208,12 +209,12 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
if (changed) {
// setCategories re-adds synthetic transfer/adjustment entries.
- const userItems: Categories = {}
+ const userItems: Record<CategoryId, CategoryItem> = {}
for (const id of Object.keys(updated)) {
if (id !== 'transfer' && id !== 'adjustment')
userItems[id] = updated[id]!
}
- setCategories(userItems)
+ setCategories(userItems as Categories)
logger.log(`realtime: ${patch.docs.length} docs, ${patch.deletedIds.length} deletes`)
}
lastSyncedAt.value = patch.serverTime
@@ -266,15 +267,16 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
colorPropagationIds: CategoryId[],
reparent?: { added: CategoryId[], removed: CategoryId[] },
) {
+ const now = Date.now()
const updatedItems: Categories = {
...items.value,
- [id]: categoryValues,
+ [id]: { ...categoryValues, updatedAt: now },
}
if (isUpdateChildCategoriesColor && colorPropagationIds.length > 0) {
for (const childId of colorPropagationIds) {
if (updatedItems[childId])
- updatedItems[childId] = { ...updatedItems[childId], color: categoryValues.color }
+ updatedItems[childId] = { ...updatedItems[childId], color: categoryValues.color, updatedAt: now }
}
}
@@ -287,11 +289,12 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
...existing,
color: isUpdateChildCategoriesColor ? categoryValues.color : existing.color,
parentId: id,
+ updatedAt: now,
}
}
for (const removeId of reparent.removed) {
if (updatedItems[removeId])
- updatedItems[removeId] = { ...updatedItems[removeId], parentId: 0 }
+ updatedItems[removeId] = { ...updatedItems[removeId], parentId: 0, updatedAt: now }
}
}
@@ -337,6 +340,24 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
if (!pushSaveOp({ entity: 'categories', id, isDemo: !!isDemo.value, isExisting: !!isExisting, values }))
return
+ // 3c — Queue per-kept-child color ops so propagation survives updateWithChildren failure.
+ const useUpdateWithChildren = !!isExisting && isUpdateChildCategoriesColor && keptChildIds.length > 0
+ if (useUpdateWithChildren) {
+ const snapshot = items.value
+ for (const cid of keptChildIds) {
+ const child = snapshot[cid]
+ if (!child)
+ continue
+ pushSaveOp({
+ entity: 'categories',
+ id: cid,
+ isDemo: !!isDemo.value,
+ isExisting: true,
+ values: { ...child, color: values.color } as unknown as Record<string, unknown>,
+ })
+ }
+ }
+
const { api, client } = useConvexClientWithApi()
const action = isExisting ? 'update' : 'create'
@@ -349,7 +370,7 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
showInQuickSelector: values.showInQuickSelector,
}
- const mutation = isExisting && isUpdateChildCategoriesColor && keptChildIds.length > 0
+ const mutation = useUpdateWithChildren
? client.mutation(api.categories.updateWithChildren, {
childIds: keptChildIds.map(cid => asConvexId<'categories'>(cid)),
id: asConvexId<'categories'>(id),
@@ -363,7 +384,8 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
action,
entity: 'categories',
errorMessage: 'categories.errors.saveFailed',
- id,
+ // When updateWithChildren is in play, drain kept-child ops on success too.
+ id: useUpdateWithChildren ? [id, ...keptChildIds] : id,
items,
mutation,
})
@@ -399,17 +421,27 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
}
if (reparentIds.length > 0 && !isLocalId(id)) {
+ // Filter local-id children out of setChildren — their create op carries
+ // the new parentId via the collapsed update op, so server picks it up
+ // when the create eventually replays. Sending local_* to setChildren
+ // would be rejected as an invalid Convex id.
+ const serverAddIds = diff.added.filter(cid => !isLocalId(cid))
+ const serverRemoveIds = diff.removed.filter(cid => !isLocalId(cid))
+
+ if (serverAddIds.length === 0 && serverRemoveIds.length === 0)
+ return coreResult
+
const reparentMutation = client.mutation(api.categories.setChildren, {
- addIds: diff.added.map(cid => asConvexId<'categories'>(cid)),
+ addIds: serverAddIds.map(cid => asConvexId<'categories'>(cid)),
childrenColor: isUpdateChildCategoriesColor ? values.color : undefined,
id: asConvexId<'categories'>(id),
- removeIds: diff.removed.map(cid => asConvexId<'categories'>(cid)),
+ removeIds: serverRemoveIds.map(cid => asConvexId<'categories'>(cid)),
})
handleMutationResult({
action: 'update',
entity: 'categories',
errorMessage: 'categories.errors.saveFailed',
- id: reparentIds,
+ id: [...serverAddIds, ...serverRemoveIds],
items,
mutation: reparentMutation,
onError: () => {
@@ -420,9 +452,95 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
restored[cid] = { ...restored[cid], color: prev.color, parentId: prev.parentId }
}
setCategories(restored)
+ // 3d — Drain non-local reparent update ops; for local-id children
+ // patch their queued create back to pre-optimistic parentId so the
+ // child is still created server-side, just under the original parent.
+ const nonLocalIds = reparentIds.filter(cid => !isLocalId(cid))
+ if (nonLocalIds.length > 0)
+ void removeOfflineOps('categories', nonLocalIds)
+ for (const cid of reparentIds) {
+ if (!isLocalId(cid))
+ continue
+ const prev = reparentRollback.get(cid)
+ if (prev)
+ void updateOfflineOpData('categories', cid, { parentId: prev.parentId })
+ }
},
})
}
+ else if (reparentIds.length > 0 && isLocalId(id)) {
+ // New parent: wait for create to remap localId → convexId, then
+ // patch children's parentId locally and call setChildren on server.
+ // Local-id children stay queued and rely on offline replay.
+ const serverAddIds = diff.added.filter(cid => !isLocalId(cid))
+ const serverRemoveIds = diff.removed.filter(cid => !isLocalId(cid))
+
+ Promise.resolve(coreResult).then((remap) => {
+ if (!remap || remap.localId !== id)
+ return
+
+ const updated: Categories = { ...items.value }
+ let changed = false
+ for (const addId of diff.added) {
+ const child = updated[addId]
+ if (child && child.parentId === remap.localId) {
+ updated[addId] = { ...child, parentId: remap.convexId }
+ changed = true
+ }
+ }
+ if (changed)
+ setCategories(updated)
+
+ // 3b — Patch queued child ops so their data.parentId no longer points
+ // at the remapped local id. Covers both reparented existing children
+ // (queued as 'update') and local-id children with their own queued
+ // 'create' op carrying values.parentId = local_parent_id.
+ for (const addId of diff.added)
+ void updateOfflineOpData('categories', addId, { parentId: remap.convexId })
+
+ if (serverAddIds.length === 0 && serverRemoveIds.length === 0)
+ return
+
+ const reparentMutation = client.mutation(api.categories.setChildren, {
+ addIds: serverAddIds.map(cid => asConvexId<'categories'>(cid)),
+ childrenColor: isUpdateChildCategoriesColor ? values.color : undefined,
+ id: asConvexId<'categories'>(remap.convexId),
+ removeIds: serverRemoveIds.map(cid => asConvexId<'categories'>(cid)),
+ })
+ handleMutationResult({
+ action: 'update',
+ entity: 'categories',
+ errorMessage: 'categories.errors.saveFailed',
+ id: [...serverAddIds, ...serverRemoveIds],
+ items,
+ mutation: reparentMutation,
+ onError: () => {
+ const restored: Categories = { ...items.value }
+ for (const [cid, prev] of reparentRollback) {
+ if (restored[cid])
+ restored[cid] = { ...restored[cid], color: prev.color, parentId: prev.parentId }
+ }
+ setCategories(restored)
+ // 3d — Drain non-local reparent update ops; for local-id children
+ // patch their queued create back to pre-optimistic parentId.
+ const nonLocalIds = [...diff.added, ...diff.removed].filter(cid => !isLocalId(cid))
+ if (nonLocalIds.length > 0)
+ void removeOfflineOps('categories', nonLocalIds)
+ for (const cid of [...diff.added, ...diff.removed]) {
+ if (!isLocalId(cid))
+ continue
+ const prev = reparentRollback.get(cid)
+ if (prev)
+ void updateOfflineOpData('categories', cid, { parentId: prev.parentId })
+ }
+ },
+ })
+ }).catch((e) => {
+ // coreResult resolves with RemapInfo|void and never rejects (handleMutationResult
+ // catches mutation rejection internally), but guard against unforeseen throws.
+ logger.error('reparent post-create flow failed', e)
+ })
+ }
}
return coreResult
diff --git a/app/components/offline/helpers.test.ts b/app/components/offline/helpers.test.ts
index b90ebedd..f7ab7b83 100644
--- a/app/components/offline/helpers.test.ts
+++ b/app/components/offline/helpers.test.ts
@@ -7,6 +7,7 @@ import {
pushOfflineOp,
removeOfflineOp,
removeOfflineOpByType,
+ updateOfflineOpData,
} from '~/components/offline/helpers'
import { OfflineEntityType } from '~/components/offline/types'
@@ -165,6 +166,58 @@ describe('clearOfflineQueue', () => {
})
})
+describe('updateOfflineOpData', () => {
+ it('merges patch into update op data', async () => {
+ await pushOfflineOp({ data: { color: '#000', name: 'old' }, entity: OfflineEntityType.Categories, id: 'c1', type: 'update' })
+ const before = await getAllOfflineOps()
+ const t0 = before[0]!.timestamp
+
+ await new Promise(r => setTimeout(r, 2))
+ await updateOfflineOpData(OfflineEntityType.Categories, 'c1', { color: '#fff' })
+
+ const queue = await getAllOfflineOps()
+ expect(queue).toHaveLength(1)
+ expect(queue[0]).toMatchObject({ data: { color: '#fff', name: 'old' }, type: 'update' })
+ expect(queue[0]!.timestamp).toBeGreaterThan(t0)
+ })
+
+ it('merges patch into create op preserving type', async () => {
+ await pushOfflineOp({ data: { name: 'A', parentId: 'local_p1' }, entity: OfflineEntityType.Categories, id: 'local_c1', type: 'create' })
+ await updateOfflineOpData(OfflineEntityType.Categories, 'local_c1', { parentId: 'jd7xyz' })
+
+ const queue = await getAllOfflineOps()
+ expect(queue[0]).toMatchObject({ data: { name: 'A', parentId: 'jd7xyz' }, type: 'create' })
+ })
+
+ it('no-op when matching op missing', async () => {
+ await updateOfflineOpData(OfflineEntityType.Categories, 'missing', { color: '#fff' })
+ const queue = await getAllOfflineOps()
+ expect(queue).toHaveLength(0)
+ })
+
+ it('no-op when matching op is delete', async () => {
+ await pushOfflineOp({ entity: OfflineEntityType.Categories, id: 'c1', type: 'delete' })
+ await updateOfflineOpData(OfflineEntityType.Categories, 'c1', { color: '#fff' })
+
+ const queue = await getAllOfflineOps()
+ expect(queue).toHaveLength(1)
+ expect(queue[0]!.type).toBe('delete')
+ expect(queue[0]!.data).toBeUndefined()
+ })
+
+ it('serializes with concurrent push (no torn write)', async () => {
+ await pushOfflineOp({ data: { color: '#000' }, entity: OfflineEntityType.Categories, id: 'c1', type: 'update' })
+ await Promise.all([
+ pushOfflineOp({ data: { name: 'merged' }, entity: OfflineEntityType.Categories, id: 'c1', type: 'update' }),
+ updateOfflineOpData(OfflineEntityType.Categories, 'c1', { color: '#fff' }),
+ ])
+
+ const queue = await getAllOfflineOps()
+ expect(queue).toHaveLength(1)
+ expect(queue[0]!.data).toMatchObject({ color: '#fff', name: 'merged' })
+ })
+})
+
describe('cross-entity isolation', () => {
it('different entities have separate operations', async () => {
await pushOfflineOp({ data: { a: 1 }, entity: OfflineEntityType.Trns, id: 'id1', type: 'create' })
diff --git a/app/components/offline/helpers.ts b/app/components/offline/helpers.ts
index 52658084..2f583beb 100644
--- a/app/components/offline/helpers.ts
+++ b/app/components/offline/helpers.ts
@@ -1,6 +1,6 @@
import localforage from 'localforage'
-import type { EntityType, OfflineOp, OfflineOpInput } from '~/components/offline/types'
+import type { EntityType, OfflineOp, OfflineOpData, OfflineOpInput } from '~/components/offline/types'
import { STORAGE_KEYS } from '~/components/offline/storageKeys'
import { createLogger } from '~/utils/logger'
@@ -139,6 +139,37 @@ async function removeOfflineOpsImpl(entity: EntityType, ids: string[]): Promise<
}
}
+/**
+ * Merge `patch` into the queued op's `data` (shallow), bump timestamp.
+ * No-op if no op matches, op is `delete`, or op carries no `data`.
+ * Op type is preserved.
+ */
+export function updateOfflineOpData(entity: EntityType, id: string, patch: OfflineOpData): Promise<void> {
+ writeChain = writeChain.then(() => updateOfflineOpDataImpl(entity, id, patch), () => updateOfflineOpDataImpl(entity, id, patch))
+ return writeChain
+}
+
+async function updateOfflineOpDataImpl(entity: EntityType, id: string, patch: OfflineOpData): Promise<void> {
+ const queue = await readQueue()
+ const idx = findLastIndex(queue, o => o.entity === entity && o.id === id)
+ if (idx === -1) {
+ logger.log(`skip update-data (no op): ${entity}/${id}`)
+ return
+ }
+ const existing = queue[idx]!
+ if (existing.type === 'delete') {
+ logger.log(`skip update-data (delete is terminal): ${entity}/${id}`)
+ return
+ }
+ if (!existing.data) {
+ logger.warn(`skip update-data (no data field): ${entity}/${id}`)
+ return
+ }
+ queue[idx] = { ...existing, data: { ...existing.data, ...patch }, timestamp: Date.now() }
+ await writeQueue(queue)
+ logger.log(`patched ${existing.type} data: ${entity}/${id}`)
+}
+
export function removeOfflineOpByType(entity: EntityType, id: string, type: OfflineOp['type']): Promise<void> {
writeChain = writeChain.then(() => removeOfflineOpByTypeImpl(entity, id, type), () => removeOfflineOpByTypeImpl(entity, id, type))
return writeChain
diff --git a/app/composables/useStoreSync.ts b/app/composables/useStoreSync.ts
index b5c0544d..e7eccdd7 100644
--- a/app/composables/useStoreSync.ts
+++ b/app/composables/useStoreSync.ts
@@ -139,6 +139,18 @@ export function handleMutationResult<T>(opts: {
.then(async (result): Promise<RemapInfo | void> => {
logger.log(`confirmed ${opts.action}: ${ids.length > 1 ? `${ids.length} items` : ids[0]}`)
+ // Track convex id BEFORE any await so a realtime echo arriving during
+ // removeOfflineOp can't slip past the in-flight gate and overwrite
+ // our optimistic state with server-side echo data.
+ let convexIdToUntrack: string | null = null
+ if (opts.action === 'create' && !Array.isArray(opts.id) && result) {
+ const convexId = String(result)
+ if (opts.id !== convexId) {
+ trackInFlight(convexId)
+ convexIdToUntrack = convexId
+ }
+ }
+
if (ids.length === 1)
await removeOfflineOp(opts.entity, ids[0]!)
else
@@ -154,13 +166,16 @@ export function handleMutationResult<T>(opts: {
if (!_persistBlocked)
localforage.setItem(STORAGE_KEYS[opts.entity], remapped)
logger.log(`remapped ID: ${opts.id} → ${convexId}`)
- // Track convex id briefly so that a subscription echo arriving just
- // after remap is still suppressed.
- trackInFlight(convexId)
+ // Extend tracking past the await so a delayed echo is still suppressed.
setTimeout(untrackInFlight, 2000, convexId)
+ convexIdToUntrack = null
return { convexId, localId: opts.id }
}
}
+
+ // If we tracked but never remapped (e.g., result mismatch), release.
+ if (convexIdToUntrack)
+ untrackInFlight(convexIdToUntrack)
})
.catch((e) => {
logger.error(`${opts.action} failed: ${ids.length > 1 ? `${ids.length} items` : ids[0]}`, e)
diff --git a/convex/categories.test.ts b/convex/categories.test.ts
index 8cbfdebf..d9bc91b7 100644
--- a/convex/categories.test.ts
+++ b/convex/categories.test.ts
@@ -109,6 +109,38 @@ describe('convex/categories', () => {
t.mutation(api.categories.update, { id, parentId: id }),
).rejects.toThrow('Category cannot be its own parent')
})
+
+ it('rejects making a category with children into a child', async () => {
+ const t = convexTest(schema, modules)
+ const parentId = await t.mutation(api.categories.create, validCategory)
+ await t.mutation(api.categories.create, {
+ ...validCategory,
+ name: 'Groceries',
+ parentId,
+ })
+ const otherRootId = await t.mutation(api.categories.create, { ...validCategory, name: 'Transport' })
+
+ await expect(
+ t.mutation(api.categories.update, { id: parentId, parentId: otherRootId }),
+ ).rejects.toThrow('Cannot move a category that has its own children')
+ })
+
+ it('allows clearing parentId on root with children (no-op)', async () => {
+ const t = convexTest(schema, modules)
+ const parentId = await t.mutation(api.categories.create, validCategory)
+ await t.mutation(api.categories.create, {
+ ...validCategory,
+ name: 'Groceries',
+ parentId,
+ })
+
+ await t.mutation(api.categories.update, { id: parentId, name: 'Food updated', parentId: 0 })
+
+ const list = await t.query(api.categories.list)
+ const updated = list!.find(c => c._id === parentId)!
+ expect(updated.name).toBe('Food updated')
+ expect(updated.parentId).toBe(0)
+ })
})
describe('updateWithChildren', () => {
diff --git a/convex/categories.ts b/convex/categories.ts
index 6898275d..5265c468 100644
--- a/convex/categories.ts
+++ b/convex/categories.ts
@@ -54,8 +54,19 @@ async function updateCategoryCore(
const category = await getOwnEntity(ctx, id, userId)
- if (args.parentId !== undefined && args.parentId !== 0)
+ if (args.parentId !== undefined && args.parentId !== 0) {
await validateParentId(ctx, args.parentId, userId, id)
+ // Only block when the parent actually changes — a redundant resend of the
+ // current parentId (common in updateWithChildren / formless updates) is fine.
+ if (args.parentId !== category.parentId) {
+ const ownChild = await ctx.db
+ .query('categories')
+ .withIndex('by_user_parent', q => q.eq('userId', userId).eq('parentId', id))
+ .first()
+ if (ownChild)
+ throw new Error('Cannot move a category that has its own children')
+ }
+ }
if (args.name !== undefined || args.parentId !== undefined)
await validateNameUniqueness(ctx, args.name ?? category.name, args.parentId ?? category.parentId, userId, id)