From 1bad78205d6f25e1d2fe6655ee3ad1db7008531a Mon Sep 17 00:00:00 2001 From: le king fu Date: Sat, 24 Oct 2026 13:58:22 -0400 Subject: [PATCH 1/2] fix(sync): insert the new inbox before merging, and redirect tasks sent to an archived inbox A list create with isInbox: true moved the tasks of the active inbox into the new id before inserting it. sl_tasks.list_id -> sl_lists.id is not deferrable, so the operation was skipped as soon as the old inbox held a task, typically on the first sync of a second device. The transaction now inserts the new inbox first, then merges every other active inbox of the account into it. An insert that creates nothing (an id already in the caller's account, such as an inbox pushed back by initialMerge) merges nothing. Only one new inbox is created per POST; the next one is skipped with "Only one new inbox per request". Task create and update send a task aimed at an archived inbox to the active one. REVIEW.md (Sync) states the exact rule. Refs #145 Co-Authored-By: Claude Opus 5.5 --- REVIEW.md | 2 +- web/src/app/api/sync/route.test.ts | 141 ++++++++++++++++++++++++++++- web/src/app/api/sync/route.ts | 92 +++++++++++++++---- 3 files changed, 212 insertions(+), 23 deletions(-) diff --git a/REVIEW.md b/REVIEW.md index a0b3033..c01a0a4 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -100,7 +100,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm - Toute écriture locale d'une liste, d'une tâche, d'une étiquette ou d'un lien tâche-étiquette passe par `writeOutboxEntry` quand la sync est active ; l'identifiant de l'entrée sert de clé d'idempotence côté serveur. — `src/db/repository/outbox.ts`, `src/db/repository/{lists,tasks,tags}.ts`, `web/src/app/api/sync/route.ts` - Les formes de données sont croisées : le client pousse en camelCase (`listId`, `dueDate`), le serveur renvoie en snake_case (`list_id`, `due_date`). Un champ ajouté l'est des deux côtés, avec la conversion des dates. — `src/services/syncClient.ts`, `web/src/app/api/sync/route.ts` -- L'Inbox locale a l'identifiant fixe `00000000-0000-0000-0000-000000000001`, remappé vers un UUID serveur à la première sync (`initialMerge`) ; le serveur fusionne les Inbox en double. — `src/services/syncClient.ts`, PR #58, #64, `web/src/db/migrations/0002_cleanup_duplicate_inboxes.sql` +- L'Inbox locale a l'identifiant fixe `00000000-0000-0000-0000-000000000001`, remappé vers un UUID serveur à la première sync (`initialMerge`). Une Inbox créée par la sync absorbe toutes les autres Inbox actives du compte (tâches déplacées, Inbox archivées), et elle est insérée avant le déplacement, car la clé étrangère `sl_tasks.list_id` n'est pas différable. Un id déjà présent dans le compte ne fusionne rien. Une seule Inbox est créée par POST, la suivante revient `skipped`. Une tâche envoyée vers une Inbox archivée, à la création comme à la mise à jour, va dans l'Inbox active. — `src/services/syncClient.ts`, `web/src/app/api/sync/route.ts`, PR #58, #64, #145, `web/src/db/migrations/0002_cleanup_duplicate_inboxes.sql` - `initialReset` efface toutes les données locales avant de tirer celles du serveur : un appel ajouté se justifie, et il reste derrière une confirmation de l'utilisateur. — `src/services/syncClient.ts`, `app/(tabs)/settings.tsx` - Une suppression côté serveur est un soft-delete (`deletedAt`), relayé à l'app par le pull. — `web/src/app/api/sync/route.ts` - Après un push ou un pull qui applique des changements, le widget est rafraîchi (`syncWidgetData`). — PR #66, `src/services/syncClient.ts` diff --git a/web/src/app/api/sync/route.test.ts b/web/src/app/api/sync/route.test.ts index cd686b8..014f0c4 100644 --- a/web/src/app/api/sync/route.test.ts +++ b/web/src/app/api/sync/route.test.ts @@ -36,7 +36,13 @@ const { POST } = await import('./route'); type Op = [entityType: string, action: string, entityId: string, data?: Record]; +type Result = { status: string; error?: string }; + async function push(userId: string, ops: Op[]): Promise { + return (await pushResults(userId, ops)).map((r) => r.status); +} + +async function pushResults(userId: string, ops: Op[]): Promise { h.userId = userId; const operations = ops.map(([entityType, action, entityId, data]) => ({ idempotencyKey: u(), entityType, action, entityId, ...(data ? { data } : {}), @@ -46,8 +52,8 @@ async function push(userId: string, ops: Op[]): Promise { body: JSON.stringify({ operations }), })); expect(res.status).toBe(200); - const body = await res.json() as { results: { status: string }[] }; - return body.results.map((r) => r.status); + const body = await res.json() as { results: (Result & { idempotencyKey: string })[] }; + return body.results.map(({ status, error }) => (error === undefined ? { status } : { status, error })); } async function row>(sql: string, params: unknown[]): Promise { @@ -239,3 +245,134 @@ describe('POST /api/sync: owner deletes', () => { expect(await row('select count(*)::int c from sl_task_tags where task_id=$1', [B.task])).toEqual({ c: 0 }); }); }); + +// Inbox merge on list create with isInbox: true (#145). The FK +// sl_tasks.list_id -> sl_lists.id is not deferrable: the new inbox must exist +// before tasks move into it. +function inboxOp(id: string): Op { + return ['list', 'create', id, { name: 'Inbox', color: null, icon: null, position: 0, isInbox: true }]; +} + +async function deletedAt(listId: string): Promise { + return (await row<{ deleted_at: Date | null }>('select deleted_at from sl_lists where id=$1', [listId]))?.deleted_at; +} + +async function listOf(taskId: string): Promise { + return (await row<{ list_id: string }>('select list_id from sl_tasks where id=$1', [taskId]))?.list_id; +} + +async function activeInboxes(userId: string): Promise { + return (await h.pg.query<{ id: string }>( + 'select id from sl_lists where user_id=$1 and is_inbox and deleted_at is null order by id', [userId])).rows.map((r) => r.id); +} + +// Account B after a first device synced, then a second device created its own inbox N. +async function merged(): Promise<{ A: AccountA; B: AccountB; N: string }> { + const { A, B } = await seed(); + const N = u(); + expect(await push(B.userId, [inboxOp(N)])).toEqual(['applied']); + expect(await activeInboxes(B.userId)).toEqual([N]); + return { A, B, N }; +} + +describe('POST /api/sync: inbox merge', () => { + it('(a) moves the tasks and subtasks of the old inbox into a new inbox, then archives the old one', async () => { + const { B } = await seed(); + const sub = u(); + expect(await push(B.userId, [['task', 'create', sub, { title: 'B inbox sub', listId: B.inbox, parentId: B.task }]])).toEqual(['applied']); + const N = u(); + expect(await push(B.userId, [inboxOp(N)])).toEqual(['applied']); + expect(await listOf(B.task)).toBe(N); + expect(await listOf(sub)).toBe(N); + expect(await deletedAt(B.inbox)).not.toBeNull(); + expect(await deletedAt(N)).toBeNull(); + expect(await activeInboxes(B.userId)).toEqual([N]); + }); + + it('(b) applies a second device batch: new inbox, task in it, tag and link', async () => { + const { B } = await seed(); + const N = u(); + const task = u(); + const tag = u(); + expect(await push(B.userId, [ + inboxOp(N), + ['task', 'create', task, { id: task, title: 'device 2 task', notes: null, completed: false, completedAt: null, priority: 0, dueDate: null, listId: N, parentId: null, recurrence: null }], + ['tag', 'create', tag, { id: tag, name: 'device-2', color: '#4DB6AC' }], + ['taskTag', 'create', task, { tagId: tag }], + ])).toEqual(['applied', 'applied', 'applied', 'applied']); + expect(await listOf(task)).toBe(N); + expect(await listOf(B.task)).toBe(N); + expect(await row('select count(*)::int c from sl_task_tags where task_id=$1 and tag_id=$2', [task, tag])).toEqual({ c: 1 }); + }); + + it('(c) merges nothing when the old inbox id is pushed again after the new inbox in the batch', async () => { + const { B } = await seed(); + const N = u(); + expect(await push(B.userId, [inboxOp(N), inboxOp(B.inbox)])).toEqual(['applied', 'applied']); + expect(await listOf(B.task)).toBe(N); + expect(await deletedAt(N)).toBeNull(); + expect(await deletedAt(B.inbox)).not.toBeNull(); + expect(await activeInboxes(B.userId)).toEqual([N]); + }); + + it('(c) merges nothing when the old inbox id is pushed again before the new inbox in the batch', async () => { + const { B } = await seed(); + const N = u(); + expect(await push(B.userId, [inboxOp(B.inbox), inboxOp(N)])).toEqual(['applied', 'applied']); + // A later push of the archived id changes nothing either. + expect(await push(B.userId, [inboxOp(B.inbox)])).toEqual(['applied']); + expect(await listOf(B.task)).toBe(N); + expect(await deletedAt(N)).toBeNull(); + expect(await deletedAt(B.inbox)).not.toBeNull(); + expect(await activeInboxes(B.userId)).toEqual([N]); + }); + + it('(d) archives every other active inbox of the account and gathers all their tasks', async () => { + const { B } = await seed(); + const second = u(); + const secondTask = u(); + await h.pg.query("insert into sl_lists (id, user_id, name, is_inbox) values ($1, $2, 'Inbox', true)", [second, B.userId]); + await h.pg.query("insert into sl_tasks (id, user_id, title, list_id) values ($1, $2, 'second inbox task', $3)", [secondTask, B.userId, second]); + expect((await activeInboxes(B.userId)).length).toBe(2); + const N = u(); + expect(await push(B.userId, [inboxOp(N)])).toEqual(['applied']); + expect(await listOf(B.task)).toBe(N); + expect(await listOf(secondTask)).toBe(N); + expect(await deletedAt(B.inbox)).not.toBeNull(); + expect(await deletedAt(second)).not.toBeNull(); + expect(await activeInboxes(B.userId)).toEqual([N]); + }); + + it('(e) redirects a task update aimed at the archived inbox to the active one', async () => { + const { B, N } = await merged(); + expect(await push(B.userId, [['task', 'update', B.sub, { listId: B.inbox }]])).toEqual(['applied']); + expect(await listOf(B.sub)).toBe(N); + }); + + it('(f) redirects a task created in the archived inbox to the active one', async () => { + const { B, N } = await merged(); + const id = u(); + expect(await push(B.userId, [['task', 'create', id, { title: 'late', listId: B.inbox }]])).toEqual(['applied']); + expect(await listOf(id)).toBe(N); + }); + + it('still refuses a task sent to another account\'s archived inbox', async () => { + const { A, B } = await merged(); + const id = u(); + expect(await push(A.userId, [['task', 'create', id, { title: 'x', listId: B.inbox }]])).toEqual(['skipped']); + expect(await row('select count(*)::int c from sl_tasks where id=$1', [id])).toEqual({ c: 0 }); + }); + + it('(g) creates only one new inbox per request', async () => { + const { B } = await seed(); + const N1 = u(); + const N2 = u(); + expect(await pushResults(B.userId, [inboxOp(N1), inboxOp(N2)])).toEqual([ + { status: 'applied' }, + { status: 'skipped', error: 'Only one new inbox per request' }, + ]); + expect(await activeInboxes(B.userId)).toEqual([N1]); + expect(await row('select count(*)::int c from sl_lists where id=$1', [N2])).toEqual({ c: 0 }); + expect(await listOf(B.task)).toBe(N1); + }); +}); diff --git a/web/src/app/api/sync/route.ts b/web/src/app/api/sync/route.ts index cb14996..7dcaeae 100644 --- a/web/src/app/api/sync/route.ts +++ b/web/src/app/api/sync/route.ts @@ -1,7 +1,7 @@ import { NextRequest, NextResponse } from 'next/server'; import { db } from '@/db/client'; import { slLists, slTasks, slTags, slTaskTags } from '@/db/schema'; -import { eq, and, gte, isNull } from 'drizzle-orm'; +import { eq, and, gte, isNull, ne, inArray, desc } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; import { syncPushSchema, type SyncOperation } from '@/lib/validators'; @@ -66,7 +66,6 @@ export async function GET(request: NextRequest) { const taskIds = tasks.map((t) => t.id); let taskTags: { taskId: string; tagId: string }[] = []; if (taskIds.length > 0) { - const { inArray } = await import('drizzle-orm'); taskTags = await db .select() .from(slTaskTags) @@ -169,6 +168,7 @@ export async function POST(request: Request) { cleanupIdempotencyKeys(); const results: { idempotencyKey: string; status: 'applied' | 'skipped'; error?: string }[] = []; + const ctx: RequestContext = { inboxCreated: false }; for (const op of body.data.operations) { const storeKey = `${auth.userId}:${op.idempotencyKey}`; @@ -181,7 +181,7 @@ export async function POST(request: Request) { } try { - await processOperation(op, auth.userId); + await processOperation(op, auth.userId, ctx); idempotencyStore.set(storeKey, { result: true, expiresAt: Date.now() + TTL_24H, @@ -199,7 +199,14 @@ export async function POST(request: Request) { return NextResponse.json({ results, syncedAt: new Date().toISOString() }); } -async function processOperation(op: SyncOperation, userId: string) { +// State shared by the operations of one POST. +type RequestContext = { + // Set once a list create with isInbox: true has inserted a row and its + // transaction has committed. + inboxCreated: boolean; +}; + +async function processOperation(op: SyncOperation, userId: string, ctx: RequestContext) { const { entityType, entityId, action } = op; const data = op.data ?? {}; const now = new Date(); @@ -220,27 +227,51 @@ async function processOperation(op: SyncOperation, userId: string) { isInbox: d.isInbox, }; - // If the incoming list is an inbox, check for an existing inbox and merge if (d.isInbox) { - await db.transaction(async (tx) => { - const [existingInbox] = await tx - .select() - .from(slLists) - .where(and(eq(slLists.userId, userId), eq(slLists.isInbox, true), isNull(slLists.deletedAt))); + const created = await db.transaction(async (tx) => { + // Insert first: sl_tasks.list_id -> sl_lists.id is not deferrable, + // so moving tasks into an inbox that does not exist yet fails. + const inserted = await tx.insert(slLists) + .values(listValues) + .onConflictDoNothing() + .returning({ id: slLists.id }); - if (existingInbox && existingInbox.id !== entityId) { - // Reassign all tasks (including subtasks) from the old inbox to the new one + // The id already exists in the caller's account (assertIdNotTaken + // ran above): typically initialMerge pushing back an inbox the + // device pulled from the server, which a previous merge may have + // archived. Merging into it would empty the current inbox into an + // archived one, so nothing is moved or archived. + if (inserted.length === 0) return false; + + // Each new inbox rewrites every task of the other inboxes: one per + // POST bounds that write amplification. The app creates at most one. + if (ctx.inboxCreated) throw new Error('Only one new inbox per request'); + + const others = await tx + .select({ id: slLists.id }) + .from(slLists) + .where(and( + eq(slLists.userId, userId), + eq(slLists.isInbox, true), + isNull(slLists.deletedAt), + ne(slLists.id, entityId), + )); + + if (others.length > 0) { + const ids = others.map((o) => o.id); + // Reassign all tasks (including subtasks) of every other inbox await tx.update(slTasks) .set({ listId: entityId, updatedAt: now }) - .where(and(eq(slTasks.listId, existingInbox.id), eq(slTasks.userId, userId))); - // Soft-delete the old inbox + .where(and(inArray(slTasks.listId, ids), eq(slTasks.userId, userId))); + // Soft-delete the other inboxes await tx.update(slLists) .set({ deletedAt: now, updatedAt: now }) - .where(eq(slLists.id, existingInbox.id)); + .where(and(inArray(slLists.id, ids), eq(slLists.userId, userId))); } - - await tx.insert(slLists).values(listValues).onConflictDoNothing(); + return true; }); + // Only after the commit: a rolled-back insert created nothing. + if (created) ctx.inboxCreated = true; } else { await db.insert(slLists).values(listValues).onConflictDoNothing(); } @@ -261,7 +292,7 @@ async function processOperation(op: SyncOperation, userId: string) { case 'task': { if (action === 'create') { const d = taskCreateData.parse(data); - await verifyOwnership(slLists, d.listId, userId); + const listId = await resolveTaskListId(d.listId, userId); // Not verifyOwnership: initialMerge pushes all tasks in one batch, a // subtask may arrive before its parent (parent_id has no FK). if (d.parentId) await assertIdNotTaken(slTasks, d.parentId, userId); @@ -269,7 +300,7 @@ async function processOperation(op: SyncOperation, userId: string) { id: entityId, userId, title: d.title || 'Untitled', - listId: d.listId, + listId, notes: d.notes, priority: d.priority, dueDate: d.dueDate, @@ -280,7 +311,7 @@ async function processOperation(op: SyncOperation, userId: string) { } else if (action === 'update') { const d = taskUpdateData.parse(data); await verifyOwnership(slTasks, entityId, userId); - if (d.listId) await verifyOwnership(slLists, d.listId, userId); + if (d.listId) d.listId = await resolveTaskListId(d.listId, userId); if (d.parentId) await assertIdNotTaken(slTasks, d.parentId, userId); await db.update(slTasks) .set({ ...d, updatedAt: now }) @@ -345,6 +376,27 @@ async function verifyOwnership(table: any, entityId: string, userId: string) { if (!row) throw new Error('Entity not found or access denied'); } +// Check that a task's target list belongs to the caller and return the id to +// write. A task sent to an archived inbox (pending on a device that has not +// pulled the merge yet) goes to the active inbox instead: an archived list is +// hidden by the site and removed from the devices by the pull. +async function resolveTaskListId(listId: string, userId: string): Promise { + const [list] = await db + .select({ isInbox: slLists.isInbox, deletedAt: slLists.deletedAt }) + .from(slLists) + .where(and(eq(slLists.id, listId), eq(slLists.userId, userId))); + if (!list) throw new Error('Entity not found or access denied'); + if (!list.isInbox || !list.deletedAt) return listId; + + const [active] = await db + .select({ id: slLists.id }) + .from(slLists) + .where(and(eq(slLists.userId, userId), eq(slLists.isInbox, true), isNull(slLists.deletedAt))) + .orderBy(desc(slLists.createdAt), desc(slLists.id)) + .limit(1); + return active?.id ?? listId; +} + async function verifyTagOwnership(entityId: string, userId: string) { const [row] = await db .select({ id: slTags.id }) -- 2.52.0 From 7b4331176d6a58cdfe206ca726787d5e61faf13b Mon Sep 17 00:00:00 2001 From: le king fu Date: Sat, 24 Oct 2026 14:01:26 -0400 Subject: [PATCH 2/2] test(sync): pin the account filter of the archived-inbox redirection A task sent to the caller's archived inbox must land in the caller's active inbox, never in a more recent inbox of another account. Refs #145 Co-Authored-By: Claude Opus 5.5 --- web/src/app/api/sync/route.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/web/src/app/api/sync/route.test.ts b/web/src/app/api/sync/route.test.ts index 014f0c4..e7704b2 100644 --- a/web/src/app/api/sync/route.test.ts +++ b/web/src/app/api/sync/route.test.ts @@ -363,6 +363,20 @@ describe('POST /api/sync: inbox merge', () => { expect(await row('select count(*)::int c from sl_tasks where id=$1', [id])).toEqual({ c: 0 }); }); + it('redirects to the caller\'s active inbox, never to a newer inbox of another account', async () => { + const { A, B, N } = await merged(); + const otherInbox = u(); + expect(await push(A.userId, [inboxOp(otherInbox)])).toEqual(['applied']); + const id = u(); + expect(await push(B.userId, [ + ['task', 'create', id, { title: 'late', listId: B.inbox }], + ['task', 'update', B.sub, { listId: B.inbox }], + ])).toEqual(['applied', 'applied']); + expect(await listOf(id)).toBe(N); + expect(await listOf(B.sub)).toBe(N); + expect(await row('select count(*)::int c from sl_tasks where list_id=$1', [otherInbox])).toEqual({ c: 0 }); + }); + it('(g) creates only one new inbox per request', async () => { const { B } = await seed(); const N1 = u(); -- 2.52.0