From 9434cb77efd2fec32d87520ba84567e11e40817a Mon Sep 17 00:00:00 2001 From: le king fu Date: Sat, 14 Nov 2026 18:22:38 -0500 Subject: [PATCH 1/3] feat(sync): schedule the reminder of a task received by the pull (#206) A task created on the companion, or tomorrow by an AI assistant, never rang on the phone: only src/db/repository/tasks.ts scheduled or cancelled reminders, and applyTaskChange wrote the pulled row without touching them. A task completed or deleted elsewhere kept its reminder. - syncRules.ts: reminderPlan(action, task), pure and import-free, returns 'schedule' for an open task with a due date, 'cancel' for a completed task, a task without a due date or a deletion. - syncClient.ts: applyTaskChange executes the plan after its local write, through scheduleTaskReminder and cancelTaskReminder, awaited and with their errors swallowed as in the task repository. A deletion now falls through to the reminder instead of returning early; a row kept by keepLocal still returns before any call. - tests/syncRules.test.mjs: the cases of reminderPlan. - tests/smoke.test.cjs: wiring of applyTaskChange, checked by reading the source (syncClient.ts does not load under node). - web/src/test/sync: the notifications stub records the calls of each device, and a ninth scenario covers the reminder scheduled on receipt, cancelled once the task is completed or deleted elsewhere, and untouched for a row kept by keepLocal. No dependency added, no new host, version and versionCode unchanged. Refs #206 Co-Authored-By: Claude Fable 5.2 --- src/services/syncClient.ts | 49 +++++++++++------ src/services/syncRules.ts | 22 ++++++++ tests/smoke.test.cjs | 58 ++++++++++++++++++++ tests/syncRules.test.mjs | 40 ++++++++++++++ web/src/test/sync/harness.ts | 37 +++++++++++-- web/src/test/sync/sync.test.ts | 98 ++++++++++++++++++++++++++++++++-- 6 files changed, 282 insertions(+), 22 deletions(-) diff --git a/src/services/syncClient.ts b/src/services/syncClient.ts index f42a8fe..5867999 100644 --- a/src/services/syncClient.ts +++ b/src/services/syncClient.ts @@ -5,6 +5,7 @@ import { useSettingsStore } from '@/src/stores/useSettingsStore'; import { getAccessToken } from '@/src/lib/authToken'; import { randomUUID } from '@/src/lib/uuid'; import { syncWidgetData } from '@/src/services/widgetSync'; +import { scheduleTaskReminder, cancelTaskReminder } from '@/src/services/notifications'; import { queueOutboxEntry, setFirstSyncInProgress } from '@/src/db/repository/outbox'; import { SYNC_EPOCH, @@ -24,7 +25,9 @@ import { pendingTagIdsByTask, alignedTagIds, remapInboxEntry, + reminderPlan, type PostResponse, + type TaskRow, } from '@/src/services/syncRules'; import { canSync, @@ -256,25 +259,41 @@ async function applyListChange(id: string, action: string, payload: Record, since: string) { + // Row written by this change; stays null for a deletion + let received: TaskRow | null = null; if (action === 'delete') { await db.delete(taskTags).where(eq(taskTags.taskId, id)); await db.delete(tasks).where(eq(tasks.id, id)); - return; - } - - const [local] = await db.select().from(tasks).where(eq(tasks.id, id)); - if (keepLocal(local, payload, since)) { - // Newer offline edit: keep it and push it back to the server - await queueOutboxEntry('task', id, 'update', taskUpdatePayload(local)); - return; - } - - // Keeps the local createdAt and calendarEventId (absent from the server) - const values = pulledTaskValues(id, payload, local); - if (local) { - await db.update(tasks).set(values).where(eq(tasks.id, id)); } else { - await db.insert(tasks).values(values); + const [local] = await db.select().from(tasks).where(eq(tasks.id, id)); + if (keepLocal(local, payload, since)) { + // Newer offline edit: keep it and push it back to the server + await queueOutboxEntry('task', id, 'update', taskUpdatePayload(local)); + return; + } + + // Keeps the local createdAt and calendarEventId (absent from the server) + received = pulledTaskValues(id, payload, local); + if (local) { + await db.update(tasks).set(received).where(eq(tasks.id, id)); + } else { + await db.insert(tasks).values(received); + } + } + + // Reminder of the received task (#206), as for a task written on the device + // (src/db/repository/tasks.ts): awaited in the pull, errors swallowed. The + // row kept above has already returned: its reminder stays as the device set it. + try { + const plan = reminderPlan(action, received); + // `received` is never null when the plan is `schedule`: `&& received` only narrows its type + if (plan === 'schedule' && received) { + await scheduleTaskReminder({ id, title: received.title, dueDate: received.dueDate }); + } else { + await cancelTaskReminder(id); + } + } catch { + // Ignore notification errors } } diff --git a/src/services/syncRules.ts b/src/services/syncRules.ts index f0f5443..546cda4 100644 --- a/src/services/syncRules.ts +++ b/src/services/syncRules.ts @@ -689,3 +689,25 @@ export function remapInboxEntry( } return changed ? { entityId, payload: JSON.stringify(data) } : null; } + +// --------------------------------------------------------------------------- +// Reminder of a task received by the pull (#206) +// --------------------------------------------------------------------------- + +/** What the pull does with the reminder of a task it has just applied. */ +export type ReminderPlan = 'schedule' | 'cancel'; + +/** + * Reminder of a task received by the pull, decided as for a task written on + * the device: `schedule` for an open task with a due date (the reminder in + * place is replaced), `cancel` for a completed task, a task without a due + * date or a deletion (`task` is then null: the row is gone). A row kept by + * keepLocal never gets here: its reminder stays as the device set it. + */ +export function reminderPlan( + action: string, + task: Pick | null | undefined, +): ReminderPlan { + if (action === 'delete' || !task) return 'cancel'; + return !task.completed && task.dueDate ? 'schedule' : 'cancel'; +} diff --git a/tests/smoke.test.cjs b/tests/smoke.test.cjs index cd64232..f306d82 100644 --- a/tests/smoke.test.cjs +++ b/tests/smoke.test.cjs @@ -515,6 +515,64 @@ check('tag links: removals written by the app, pull aligned without the outbox ( assert.ok(!/applyTaskTagChange/.test(client), 'links are no longer applied one by one'); }); +// A task received by the pull gets its reminder (#206). The rule is executed +// by tests/syncRules.test.mjs (reminderPlan) and the calls by the sync harness +// (web/src/test/sync, scenario 9); this check locks the wiring in +// syncClient.ts, which node cannot load: applyTaskChange executes the plan +// once, after its local write, awaited and with its errors swallowed, a +// deletion reaches it, and a row kept by keepLocal returns before any call. +check('applyTaskChange executes reminderPlan after its write, never for a kept row (#206)', () => { + const src = fs.readFileSync(path.join(__dirname, '..', 'src/services/syncClient.ts'), 'utf8'); + assert.match( + src, + /^import \{[^}]*\bscheduleTaskReminder\b[^}]*\bcancelTaskReminder\b[^}]*\} from '@\/src\/services\/notifications';$/m, + 'syncClient.ts must take both reminder functions from the notifications service' + ); + const start = src.indexOf('async function applyTaskChange('); + assert.ok(start >= 0, 'applyTaskChange not found in syncClient.ts'); + const end = src.indexOf('\n}\n', start); + assert.ok(end > start, 'end of applyTaskChange not found'); + // Comments out: a word counted below (return, a function name) may be quoted in one + const body = src.slice(start, end).replace(/\/\/[^\n]*/g, ''); + + // The kept row returns first, and it is the only early return: a deletion + // falls through to the reminder + const kept = /if \(keepLocal\(local, payload, since\)\) \{[^}]*\breturn;\s*\}/.exec(body); + assert.ok(kept, 'the keepLocal return of applyTaskChange was not found'); + const afterKept = kept.index + kept[0].length; + assert.equal( + (body.match(/\breturn\b/g) || []).length, + 1, + 'keepLocal must be the only early return of applyTaskChange: a deletion reaches the reminder' + ); + + // One call of each, after the keepLocal return and after every local write + const lastWrite = Math.max( + ...[ + 'await db.delete(tasks).where(eq(tasks.id, id));', + 'await db.update(tasks).set(received).where(eq(tasks.id, id));', + 'await db.insert(tasks).values(received);', + ].map((write) => { + const at = body.indexOf(write); + assert.ok(at >= 0, `applyTaskChange misses ${write}`); + return at; + }) + ); + for (const call of ['reminderPlan(', 'scheduleTaskReminder(', 'cancelTaskReminder(']) { + assert.equal(body.split(call).length - 1, 1, `applyTaskChange must hold exactly one ${call}...) call`); + const at = body.indexOf(call); + assert.ok(at > afterKept, `${call}...) must come after the keepLocal return`); + assert.ok(at > lastWrite, `${call}...) must come after the local write`); + } + + // The plan is executed as it is: awaited, errors swallowed + assert.match( + body, + /try \{\s*const plan = reminderPlan\(action, received\);\s*if \(plan === 'schedule' && received\) \{\s*await scheduleTaskReminder\(\{ id, title: received\.title, dueDate: received\.dueDate \}\);\s*\} else \{\s*await cancelTaskReminder\(id\);\s*\}\s*\} catch \{\s*\}$/, + 'applyTaskChange must await the reminder plan under a try/catch that swallows its errors' + ); +}); + // The bounded wait on the persisted settings (review of PR #164) is executed // by tests/hydration.test.mjs through node's type stripping: hydration.ts // stays import-free, and useSettingsStore.ts (React Native, not loadable diff --git a/tests/syncRules.test.mjs b/tests/syncRules.test.mjs index e588c63..b72b43d 100644 --- a/tests/syncRules.test.mjs +++ b/tests/syncRules.test.mjs @@ -38,6 +38,7 @@ import { planInboxRepair, firstSyncChoice, remapInboxEntry, + reminderPlan, } from '../src/services/syncRules.ts'; const ID = '11111111-1111-4111-8111-111111111111'; @@ -972,3 +973,42 @@ test('remapInboxEntry: entries that do not name the local Inbox are left alone', assert.equal(remapInboxEntry({ entityType: 'taskTag', entityId: ID, payload: JSON.stringify({ tagId: other }) }, LIST_ID), null); assert.equal(remapInboxEntry({ entityType: 'task', entityId: ID, payload: 'not json' }, LIST_ID), null); }); + +// --------------------------------------------------------------------------- +// Reminder of a task received by the pull (#206) +// --------------------------------------------------------------------------- + +// The row applyTaskChange writes for a received task: open, due in the future +const receivedTask = (over = {}) => + pulledTaskValues(ID, taskPayload({ completed: false, completed_at: null, due_date: '2026-11-20T09:00:00.000Z', ...over })); + +test('reminderPlan: a received open task with a due date is scheduled', () => { + assert.equal(reminderPlan('update', receivedTask()), 'schedule'); + // The server only sends `update` and `delete`; a `create` is read the same way + assert.equal(reminderPlan('create', receivedTask()), 'schedule'); +}); + +test('reminderPlan: a received completed task is cancelled, even with a due date', () => { + const done = receivedTask({ completed: true, completed_at: '2026-11-14T09:00:00.000Z' }); + assert.ok(done.dueDate instanceof Date); + assert.equal(reminderPlan('update', done), 'cancel'); +}); + +test('reminderPlan: a received task without a due date is cancelled', () => { + const undated = receivedTask({ due_date: null }); + assert.equal(undated.dueDate, null); + assert.equal(reminderPlan('update', undated), 'cancel'); +}); + +test('reminderPlan: a deleted task is cancelled, with or without its row', () => { + // applyTaskChange passes no row for a deletion + assert.equal(reminderPlan('delete', null), 'cancel'); + assert.equal(reminderPlan('delete', undefined), 'cancel'); + // The action decides, even for a row that would be scheduled otherwise + assert.equal(reminderPlan('delete', receivedTask()), 'cancel'); +}); + +test('reminderPlan: no row means nothing to schedule, whatever the action', () => { + assert.equal(reminderPlan('update', null), 'cancel'); + assert.equal(reminderPlan('update', undefined), 'cancel'); +}); diff --git a/web/src/test/sync/harness.ts b/web/src/test/sync/harness.ts index 12261a1..458729a 100644 --- a/web/src/test/sync/harness.ts +++ b/web/src/test/sync/harness.ts @@ -17,13 +17,19 @@ * - Time: the scenarios run under vitest fake timers (Date, setTimeout, * clearTimeout); `drive()` lets in-flight work finish and jumps the clock to * the next timer only when everything waits for one. + * - Reminders (#206): src/services/notifications.ts is replaced by a recorder. + * Each device keeps the calls its code made, in order (`device.reminders`): + * a reminder scheduled (task id, title, due date) or cancelled (task id). * * NOT covered: the real expo-sqlite runtime (and its SQLite build), the app * start-up sequence (app/_layout.tsx, hydration of the persisted settings), * the interface (settings screen, alerts), the real Logto tokens and the * server's bearer check, the WebSocket (server notification and app socket), - * the widget, notifications and calendar (stubbed), and the production - * network (TLS, proxy, latency). The production probe is #176. + * the widget and the calendar (stubbed), what notifications.ts and + * expo-notifications do with a reminder (only the calls are recorded: not the + * permission, the « notifications off » setting, the reminder offset, a due + * date in the past, nor the notification itself), and the production network + * (TLS, proxy, latency). The production probe is #176. */ import fs from 'node:fs'; import path from 'node:path'; @@ -288,6 +294,15 @@ function migrateApp(sqlite: DatabaseSync) { type SqlParam = null | number | bigint | string | Uint8Array; +/** + * One call a device made to the notifications service (#206), as recorded by + * the stub: the reminder it asked to schedule, or the task whose reminder it + * asked to cancel. `dueDate` is the ISO instant the app passed. + */ +export type ReminderCall = + | { kind: 'schedule'; id: string; title: string; dueDate: string | null } + | { kind: 'cancel'; id: string }; + /** drizzle-orm/sqlite-proxy callback over a node:sqlite database. */ function proxyOf(sqlite: DatabaseSync) { return async (sql: string, params: unknown[], method: 'run' | 'all' | 'values' | 'get') => { @@ -311,6 +326,8 @@ export interface Device { tasks: TasksModule; tags: TagsModule; outbox: OutboxModule; + /** Reminder calls of this device, in order: repositories and sync alike (#206). */ + reminders: ReminderCall[]; /** Plain SQL on the device database, rows as objects. */ query(sql: string, params?: SqlParam[]): T[]; exec(sql: string, params?: SqlParam[]): void; @@ -341,6 +358,7 @@ export async function createDevice(name: string): Promise { migrateApp(sqlite); const settings = createSettings(); const auth: { token: string | null } = { token: null }; + const reminders: ReminderCall[] = []; vi.doMock('@/src/db/client', async () => { const { drizzle } = await import('drizzle-orm/sqlite-proxy'); @@ -358,9 +376,19 @@ export async function createDevice(name: string): Promise { })); vi.doMock('@/src/lib/uuid', () => ({ randomUUID: () => randomUUID() })); vi.doMock('@/src/services/widgetSync', () => ({ syncWidgetData: async () => {} })); + // Recorder (#206): same signatures as src/services/notifications.ts vi.doMock('@/src/services/notifications', () => ({ - scheduleTaskReminder: async () => {}, - cancelTaskReminder: async () => {}, + scheduleTaskReminder: async (task: { id: string; title: string; dueDate: Date | null }) => { + reminders.push({ + kind: 'schedule', + id: task.id, + title: task.title, + dueDate: task.dueDate ? new Date(task.dueDate).toISOString() : null, + }); + }, + cancelTaskReminder: async (taskId: string) => { + reminders.push({ kind: 'cancel', id: taskId }); + }, })); vi.doMock('@/src/services/calendar', () => ({ addTaskToCalendar: async () => `cal-${randomUUID()}`, @@ -387,6 +415,7 @@ export async function createDevice(name: string): Promise { tasks, tags, outbox, + reminders, query, exec: (sql, params = []) => { sqlite.prepare(sql).run(...params); diff --git a/web/src/test/sync/sync.test.ts b/web/src/test/sync/sync.test.ts index 3f65d0a..54d1dae 100644 --- a/web/src/test/sync/sync.test.ts +++ b/web/src/test/sync/sync.test.ts @@ -10,13 +10,15 @@ import { LOCAL_INBOX_ID, type Device, type LoggedRequest, + type ReminderCall, type Server, } from './harness'; // The post-merge sync checks of #145-#152, #165, #168/#180 and #178, run by -// `npm test` instead of by hand on two phones (#169). Each scenario seeds its -// own accounts on the shared server: the file runs shuffled. What the harness -// does not cover is listed at the top of harness.ts. +// `npm test` instead of by hand on two phones (#169), and the reminders of the +// tasks received by the pull (#206). Each scenario seeds its own accounts on +// the shared server: the file runs shuffled. What the harness does not cover +// is listed at the top of harness.ts. let server: Server; @@ -64,6 +66,11 @@ function nowS(): number { return Math.floor(Date.now() / 1000); } +/** Reminder calls a device made for one task, from call number `from` on (#206). */ +function reminderCalls(d: Device, taskId: string, from = 0): ReminderCall[] { + return d.reminders.slice(from).filter((c) => c.id === taskId); +} + describe('1. First sync « Fusionner » of a second device', () => { it('ends with one Inbox, the tasks of both devices and their completed tasks (#145, #146, #150)', async () => { const U = newAccount(); @@ -361,3 +368,88 @@ describe('8. Scheduler wiring', () => { } }); }); + +describe('9. Reminders of tasks received by the pull', () => { + it('schedules the reminder of a dated task received from another device, cancels it once the task is completed or deleted there, and makes no call for a row kept by keepLocal (#206)', async () => { + const U = newAccount(); + const a = await createDevice('a'); + await a.startup(); + a.signIn(U); + await a.firstSync('merge'); + const b = await createDevice('b'); + await b.startup(); + b.signIn(U); + await b.firstSync('reset'); + expect(b.reminders).toEqual([]); + + const inbox = await a.lists.getInboxId(); + const checked = await a.tasks.createTask({ title: 'Dentiste', listId: inbox, dueDate: new Date('2026-11-20T09:00:00.000Z') }); + const removed = await a.tasks.createTask({ title: 'Garage', listId: inbox, dueDate: new Date('2026-11-21T14:30:00.000Z') }); + const kept = await a.tasks.createTask({ title: 'Rapport', listId: inbox, dueDate: new Date('2026-11-22T13:00:00.000Z') }); + const undated = await a.tasks.createTask({ title: 'Sans date', listId: inbox }); + await a.syncNow(); + + // Received by b: one reminder per dated task, with its title and its due date + await b.syncNow(); + expect(reminderCalls(b, checked)).toEqual([ + { kind: 'schedule', id: checked, title: 'Dentiste', dueDate: '2026-11-20T09:00:00.000Z' }, + ]); + expect(reminderCalls(b, removed)).toEqual([ + { kind: 'schedule', id: removed, title: 'Garage', dueDate: '2026-11-21T14:30:00.000Z' }, + ]); + expect(reminderCalls(b, kept)).toEqual([ + { kind: 'schedule', id: kept, title: 'Rapport', dueDate: '2026-11-22T13:00:00.000Z' }, + ]); + // Without a due date there is nothing to schedule: the plan cancels + expect(reminderCalls(b, undated)).toEqual([{ kind: 'cancel', id: undated }]); + + // Completed on a, deleted on a: b cancels both reminders + await a.tasks.toggleComplete(checked); + await a.tasks.deleteTask(removed); + await a.syncNow(); + let mark = b.reminders.length; + await b.syncNow(); + expect(reminderCalls(b, checked, mark)).toEqual([{ kind: 'cancel', id: checked }]); + expect(reminderCalls(b, removed, mark)).toEqual([{ kind: 'cancel', id: removed }]); + expect(localTasks(b).find((r) => r.id === checked)?.completed).toBe(1); + expect(localTasks(b).find((r) => r.id === removed)).toBeUndefined(); + // The task nobody touched is still scheduled + expect(reminderCalls(b, kept).at(-1)).toMatchObject({ kind: 'schedule', title: 'Rapport' }); + + // a signs out, then edits the task offline: its repository sets the reminder + expect(await a.signOut()).toBe(0); + vi.setSystemTime(Date.now() + 10_000); + await a.tasks.updateTask(kept, { title: 'Rapport v2', dueDate: new Date('2026-11-23T08:00:00.000Z') }); + const own: ReminderCall = { kind: 'schedule', id: kept, title: 'Rapport v2', dueDate: '2026-11-23T08:00:00.000Z' }; + expect(reminderCalls(a, kept).at(-1)).toEqual(own); + // Meanwhile another dated task reaches the server + const fresh = await b.tasks.createTask({ + title: 'Courses', + listId: await b.lists.getInboxId(), + dueDate: new Date('2026-11-24T17:00:00.000Z'), + }); + await b.syncNow(); + + // « Fusionner » again: the full pull keeps the newer local row (keepLocal) + a.signIn(U); + mark = a.reminders.length; + await a.firstSync('merge'); + expect(localTasks(a).find((r) => r.id === kept)?.title).toBe('Rapport v2'); + expect( + a.query('SELECT action FROM sync_outbox WHERE entity_id = ? AND synced_at IS NULL', [kept]), + 'the kept row is queued again', + ).toEqual([{ action: 'update' }]); + // The same pull scheduled the task it applied... + expect(reminderCalls(a, fresh, mark)).toEqual([ + { kind: 'schedule', id: fresh, title: 'Courses', dueDate: '2026-11-24T17:00:00.000Z' }, + ]); + // ...and made no call for the kept row: its reminder is still the one the device set + expect(reminderCalls(a, kept, mark)).toEqual([]); + expect(reminderCalls(a, kept).at(-1)).toEqual(own); + + // Pushed back, the kept row reaches b, which reschedules with the new title and due date + await a.syncNow(); + await b.syncNow(); + expect(reminderCalls(b, kept).at(-1)).toEqual(own); + }); +}); -- 2.52.0 From d6adcf71335c8864f1e3a694a830fdef802082ba Mon Sep 17 00:00:00 2001 From: le king fu Date: Sat, 14 Nov 2026 18:37:11 -0500 Subject: [PATCH 2/3] docs(review): reminder at the pull and ninth sync scenario (#206) - Sync zone: a task received by the pull gets its reminder through reminderPlan, executed by applyTaskChange after its local write; a row kept by keepLocal is left alone; cost per received task and known limits. - Verification commands: the sync harness counts nine scenarios. Its notifications stub records the calls, answers at once and never throws, so the await and the try/catch of applyTaskChange hold by the smoke check alone. Refs #206 Co-Authored-By: Claude Fable 5.2 --- REVIEW.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/REVIEW.md b/REVIEW.md index c0a8568..da49ed5 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -113,6 +113,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm - Pas de fusion entre comptes : `dataOwnerId` (store de réglages, persisté, gardé à la déconnexion) nomme le compte des données locales ; un appareil qui porte les données d'un autre compte n'offre que « Charger ce compte » (`initialReset`) ou « Annuler » (déconnexion sans toucher aux données), règle `firstSyncChoice`. La sync reste éteinte jusqu'à la réussite de `initialMerge` / `initialReset` (un seul `setSyncEnabled(true)`, dans `runFirstSync`), et le planificateur refuse toute sync tant que `dataOwnerId` diffère du compte connecté (`canSync`) : sinon l'outbox de l'ancien compte part sous le nouveau. La déconnexion envoie d'abord l'outbox (`pushBeforeSignOut`, 10 s, état « sync initiale », une requête réservée hors budget). — `src/services/syncRules.ts`, `src/services/syncSchedule.ts`, `src/services/syncClient.ts`, `app/(tabs)/settings.tsx`, `tests/smoke.test.cjs`, #165 - Une suppression côté serveur est un soft-delete (`deletedAt`), relayé à l'app par le pull. — `web/src/app/api/sync/route.ts` - Le pull garde le `createdAt` local d'une ligne existante, et le `calendarEventId` d'une tâche (colonne absente du serveur). — `src/services/syncRules.ts` (`pulled*Values`), #149 +- Une tâche reçue par le pull reçoit son rappel comme une tâche écrite sur l'appareil (décision de Max du 2026-11-14) : après son écriture locale, `applyTaskChange` exécute `reminderPlan`. Pour une tâche non terminée qui a une échéance, il appelle `scheduleTaskReminder`, qui remplace le rappel en place et ne planifie rien pour une heure passée ni quand les notifications sont coupées dans les réglages ; pour une tâche terminée, sans échéance ou supprimée, il appelle `cancelTaskReminder`. Les deux appels sont attendus dans le pull et leurs erreurs avalées, comme dans `src/db/repository/tasks.ts`. Une ligne gardée par `keepLocal` sort avant tout appel : son rappel reste celui que l'appareil a posé. Le pull fait au moins un appel natif par tâche reçue, l'un après l'autre : la durée d'une première sync de plusieurs centaines de tâches se mesure sur un appareil. La sync ne tourne qu'au premier plan, donc le rappel d'une tâche reçue n'existe qu'après une ouverture de l'app ; `initialReset` efface les tâches locales sans annuler leurs rappels (limite connue). — `src/services/syncRules.ts` (`reminderPlan`), `src/services/syncClient.ts`, `tests/syncRules.test.mjs`, `tests/smoke.test.cjs`, `web/src/test/sync/sync.test.ts` (scénario 9), #206 - Dans un pull depuis `SYNC_EPOCH` (première sync, ou après une déconnexion qui remet `lastSyncAt` à null), une liste ou une tâche locale strictement plus récente que le serveur est gardée et remise dans l'outbox (`queueOutboxEntry`, action `update`, écrite même sync éteinte : la première sync tourne avant l'activation, #165). Jamais une étiquette : l'app ne garde pas de date de modification pour les étiquettes, donc un renommage hors connexion d'étiquette reste perdu face au serveur (check smoke « applyTagChange never keeps a local tag »). — `src/services/syncRules.ts` (`keepLocal`), `src/services/syncClient.ts`, #149, #181 - Une étiquette a un `updatedAt` serveur (migration `0003_tag_updated_at`, rempli par `created_at` pour les lignes existantes) : `GET /api/sync` la tire sur `updatedAt >= since` et renvoie `updated_at` = `updatedAt`. Toute écriture d'une étiquette (`PUT`/`DELETE /api/tags/[id]`, `tag update`/`tag delete` de `POST /api/sync`) avance `updatedAt`. La suppression d'une étiquette retire ses liens `sl_task_tags` et avance `updatedAt` des tâches touchées dans la même transaction, pour que l'app réaligne leurs liens. La suppression d'une tâche (`task delete` de `POST /api/sync`, `DELETE /api/tasks/[id]`) passe par `deleteTask` : dans une transaction, la tâche et ses sous-tâches actives du même compte, sur un seul niveau, reçoivent `deletedAt`, et les liens de la tâche et de ses sous-tâches sont retirés. Un lien créé vers une tâche ou une étiquette supprimée n'est jamais écrit : `taskTag create` répond `applied`, `POST /api/tasks/[id]/tags` écarte les étiquettes supprimées et répond 404 pour une tâche supprimée ; la vérification se fait dans la transaction de l'écriture. Toute transaction qui écrit un lien `sl_task_tags` pour une tâche verrouille d'abord la ligne de cette tâche (`lockTaskForLinks`, `FOR NO KEY UPDATE`), avant toute autre ligne : un autre ordre fait s'interbloquer deux écritures simultanées (`40P01`), ce qu'aucun test PGlite ne voit (une seule connexion). La sonde attend 0 au contrôle 3 (`lien_tache_supprimee`). — `web/src/db/schema.ts`, `web/src/app/api/sync/route.ts`, `web/src/app/api/tags/[id]/route.ts`, `web/src/lib/taskDelete.ts`, `web/src/app/api/tasks/[id]/route.ts`, `web/src/app/api/tasks/[id]/tags/route.ts`, `web/src/app/api/tasks/[id]/tags/[tagId]/route.ts`, `web/src/db/migrations/0004_cleanup_deleted_task_links.sql`, `web/src/app/api/sync/route.test.ts`, #181, #196 - Après la fusion de la première sync, `initialMerge` tire tout le serveur depuis `SYNC_EPOCH` ; `lastSyncAt` est posé à cette date avant le pull, pour qu'un pull raté se rejoue au `fullSync` suivant (#150). — `src/services/syncClient.ts`, `src/services/syncRules.ts` (`mergeTaskData`) @@ -209,7 +210,7 @@ npm run build - Comparer deux exports : `(cd && find . -type f | sort | xargs sha256sum)` sur l'arbre de base deux fois (déterminisme), puis sur la PR ; même nombre de fichiers et mêmes empreintes, ou une différence expliquée. - Côté `web/`, vitest mélange l'ordre des tests à chaque run (`sequence.shuffle` dans `web/vitest.config.mts`, #148) et affiche sa graine (`Running tests with seed ""`). Un échec qui dépend de l'ordre se rejoue avec la même graine : `npx vitest run --sequence.seed=`. - Un `npm test` ne compte qu'après une sonde : une vérification volontairement rouge doit le faire sortir en code non nul (`smoke FAIL`, sortie 1 ; côté `web/`, une assertion de vitest volontairement fausse, sortie 1). -- Harnais de sync (`web/src/test/sync/`, #169) : il charge le code de l'app (`src/services/syncClient.ts`, les repositories, `syncRules`, `syncSchedule`) et ses dépendances depuis le `node_modules` de la **racine** ; sans `npm ci` à la racine, `npm test` de `web/` échoue à l'import. Chaque appareil a sa base `node:sqlite`, son planificateur et ses réglages ; le serveur est la vraie route sur PGlite, `fetch` y est aiguillé en mémoire, sous fausses minuteries. Huit scénarios : fusion d'un 2e appareil, réinitialisation d'un compte neuf, réparation de l'Inbox scindée, champs locaux et modifications hors ligne au pull, file de plus de 400 entrées et refus rejoués, étiquettes et sous-tâches, changement de compte, budget et 429 du planificateur. Le dossier est exclu de `tsc` (`web/tsconfig.json`) et de `web/vitest.config.mts` ; sa config, `web/src/test/sync/vitest.config.mts`, ne ramasse que lui. Les clés étrangères SQLite y sont coupées, comme sur l'appareil (aucun `PRAGMA` dans l'app). Il ne couvre pas le runtime expo-sqlite réel, le démarrage de l'app (`app/_layout.tsx`, hydratation des réglages), l'interface, Logto réel, le WebSocket, le widget, les notifications ni le calendrier (simulés) : la liste fait foi en tête de `harness.ts`. +- Harnais de sync (`web/src/test/sync/`, #169) : il charge le code de l'app (`src/services/syncClient.ts`, les repositories, `syncRules`, `syncSchedule`) et ses dépendances depuis le `node_modules` de la **racine** ; sans `npm ci` à la racine, `npm test` de `web/` échoue à l'import. Chaque appareil a sa base `node:sqlite`, son planificateur et ses réglages ; le serveur est la vraie route sur PGlite, `fetch` y est aiguillé en mémoire, sous fausses minuteries. Neuf scénarios : fusion d'un 2e appareil, réinitialisation d'un compte neuf, réparation de l'Inbox scindée, champs locaux et modifications hors ligne au pull, file de plus de 400 entrées et refus rejoués, étiquettes et sous-tâches, changement de compte, budget et 429 du planificateur, rappels des tâches reçues par le pull (#206). Les rappels y sont enregistrés par une simulation de `notifications`, appareil par appareil (appels à `scheduleTaskReminder` et à `cancelTaskReminder`) : ni `notifications.ts` ni expo-notifications ne tournent. Cette simulation répond tout de suite et ne lève jamais : un `await` retiré ou une erreur non avalée dans `applyTaskChange` n'y fait tomber aucun scénario, seul le contrôle « applyTaskChange executes reminderPlan » du smoke test les tient. Le dossier est exclu de `tsc` (`web/tsconfig.json`) et de `web/vitest.config.mts` ; sa config, `web/src/test/sync/vitest.config.mts`, ne ramasse que lui. Les clés étrangères SQLite y sont coupées, comme sur l'appareil (aucun `PRAGMA` dans l'app). Il ne couvre pas le runtime expo-sqlite réel, le démarrage de l'app (`app/_layout.tsx`, hydratation des réglages), l'interface, Logto réel, le WebSocket, le widget, les notifications ni le calendrier (simulés) : la liste fait foi en tête de `harness.ts`. - Ce que ces commandes ne prouvent pas : le comportement sur un appareil (widget, notifications, connexion Logto, runtime expo-sqlite), qui se teste sur un build de développement ; le site déployé, qui se vérifie après le déploiement manuel. ## Pièges de revue -- 2.52.0 From c9597aa703bd88b66eb761ca8fa8dad7c03848ee Mon Sep 17 00:00:00 2001 From: le king fu Date: Sat, 14 Nov 2026 18:49:08 -0500 Subject: [PATCH 3/3] docs(review): state the cost of the reminder at the pull exactly (#206) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Self-review of the PR: the Sync bullet said « au moins un appel natif par tâche reçue ». The pull makes one call to the notifications service per task it applies; the native calls behind it vary (up to two to schedule, one to cancel, none for a task to schedule while notifications are off), so the bullet now counts the service calls only. Refs #206 Co-Authored-By: Claude Fable 5.2 --- REVIEW.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/REVIEW.md b/REVIEW.md index da49ed5..941a33b 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -113,7 +113,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm - Pas de fusion entre comptes : `dataOwnerId` (store de réglages, persisté, gardé à la déconnexion) nomme le compte des données locales ; un appareil qui porte les données d'un autre compte n'offre que « Charger ce compte » (`initialReset`) ou « Annuler » (déconnexion sans toucher aux données), règle `firstSyncChoice`. La sync reste éteinte jusqu'à la réussite de `initialMerge` / `initialReset` (un seul `setSyncEnabled(true)`, dans `runFirstSync`), et le planificateur refuse toute sync tant que `dataOwnerId` diffère du compte connecté (`canSync`) : sinon l'outbox de l'ancien compte part sous le nouveau. La déconnexion envoie d'abord l'outbox (`pushBeforeSignOut`, 10 s, état « sync initiale », une requête réservée hors budget). — `src/services/syncRules.ts`, `src/services/syncSchedule.ts`, `src/services/syncClient.ts`, `app/(tabs)/settings.tsx`, `tests/smoke.test.cjs`, #165 - Une suppression côté serveur est un soft-delete (`deletedAt`), relayé à l'app par le pull. — `web/src/app/api/sync/route.ts` - Le pull garde le `createdAt` local d'une ligne existante, et le `calendarEventId` d'une tâche (colonne absente du serveur). — `src/services/syncRules.ts` (`pulled*Values`), #149 -- Une tâche reçue par le pull reçoit son rappel comme une tâche écrite sur l'appareil (décision de Max du 2026-11-14) : après son écriture locale, `applyTaskChange` exécute `reminderPlan`. Pour une tâche non terminée qui a une échéance, il appelle `scheduleTaskReminder`, qui remplace le rappel en place et ne planifie rien pour une heure passée ni quand les notifications sont coupées dans les réglages ; pour une tâche terminée, sans échéance ou supprimée, il appelle `cancelTaskReminder`. Les deux appels sont attendus dans le pull et leurs erreurs avalées, comme dans `src/db/repository/tasks.ts`. Une ligne gardée par `keepLocal` sort avant tout appel : son rappel reste celui que l'appareil a posé. Le pull fait au moins un appel natif par tâche reçue, l'un après l'autre : la durée d'une première sync de plusieurs centaines de tâches se mesure sur un appareil. La sync ne tourne qu'au premier plan, donc le rappel d'une tâche reçue n'existe qu'après une ouverture de l'app ; `initialReset` efface les tâches locales sans annuler leurs rappels (limite connue). — `src/services/syncRules.ts` (`reminderPlan`), `src/services/syncClient.ts`, `tests/syncRules.test.mjs`, `tests/smoke.test.cjs`, `web/src/test/sync/sync.test.ts` (scénario 9), #206 +- Une tâche reçue par le pull reçoit son rappel comme une tâche écrite sur l'appareil (décision de Max du 2026-11-14) : après son écriture locale, `applyTaskChange` exécute `reminderPlan`. Pour une tâche non terminée qui a une échéance, il appelle `scheduleTaskReminder`, qui remplace le rappel en place et ne planifie rien pour une heure passée ni quand les notifications sont coupées dans les réglages ; pour une tâche terminée, sans échéance ou supprimée, il appelle `cancelTaskReminder`. Les deux appels sont attendus dans le pull et leurs erreurs avalées, comme dans `src/db/repository/tasks.ts`. Une ligne gardée par `keepLocal` sort avant tout appel : son rappel reste celui que l'appareil a posé. Le pull appelle ainsi le service de notifications une fois par tâche qu'il applique, l'une après l'autre : la durée d'une première sync de plusieurs centaines de tâches se mesure sur un appareil. La sync ne tourne qu'au premier plan, donc le rappel d'une tâche reçue n'existe qu'après une ouverture de l'app ; `initialReset` efface les tâches locales sans annuler leurs rappels (limite connue). — `src/services/syncRules.ts` (`reminderPlan`), `src/services/syncClient.ts`, `tests/syncRules.test.mjs`, `tests/smoke.test.cjs`, `web/src/test/sync/sync.test.ts` (scénario 9), #206 - Dans un pull depuis `SYNC_EPOCH` (première sync, ou après une déconnexion qui remet `lastSyncAt` à null), une liste ou une tâche locale strictement plus récente que le serveur est gardée et remise dans l'outbox (`queueOutboxEntry`, action `update`, écrite même sync éteinte : la première sync tourne avant l'activation, #165). Jamais une étiquette : l'app ne garde pas de date de modification pour les étiquettes, donc un renommage hors connexion d'étiquette reste perdu face au serveur (check smoke « applyTagChange never keeps a local tag »). — `src/services/syncRules.ts` (`keepLocal`), `src/services/syncClient.ts`, #149, #181 - Une étiquette a un `updatedAt` serveur (migration `0003_tag_updated_at`, rempli par `created_at` pour les lignes existantes) : `GET /api/sync` la tire sur `updatedAt >= since` et renvoie `updated_at` = `updatedAt`. Toute écriture d'une étiquette (`PUT`/`DELETE /api/tags/[id]`, `tag update`/`tag delete` de `POST /api/sync`) avance `updatedAt`. La suppression d'une étiquette retire ses liens `sl_task_tags` et avance `updatedAt` des tâches touchées dans la même transaction, pour que l'app réaligne leurs liens. La suppression d'une tâche (`task delete` de `POST /api/sync`, `DELETE /api/tasks/[id]`) passe par `deleteTask` : dans une transaction, la tâche et ses sous-tâches actives du même compte, sur un seul niveau, reçoivent `deletedAt`, et les liens de la tâche et de ses sous-tâches sont retirés. Un lien créé vers une tâche ou une étiquette supprimée n'est jamais écrit : `taskTag create` répond `applied`, `POST /api/tasks/[id]/tags` écarte les étiquettes supprimées et répond 404 pour une tâche supprimée ; la vérification se fait dans la transaction de l'écriture. Toute transaction qui écrit un lien `sl_task_tags` pour une tâche verrouille d'abord la ligne de cette tâche (`lockTaskForLinks`, `FOR NO KEY UPDATE`), avant toute autre ligne : un autre ordre fait s'interbloquer deux écritures simultanées (`40P01`), ce qu'aucun test PGlite ne voit (une seule connexion). La sonde attend 0 au contrôle 3 (`lien_tache_supprimee`). — `web/src/db/schema.ts`, `web/src/app/api/sync/route.ts`, `web/src/app/api/tags/[id]/route.ts`, `web/src/lib/taskDelete.ts`, `web/src/app/api/tasks/[id]/route.ts`, `web/src/app/api/tasks/[id]/tags/route.ts`, `web/src/app/api/tasks/[id]/tags/[tagId]/route.ts`, `web/src/db/migrations/0004_cleanup_deleted_task_links.sql`, `web/src/app/api/sync/route.test.ts`, #181, #196 - Après la fusion de la première sync, `initialMerge` tire tout le serveur depuis `SYNC_EPOCH` ; `lastSyncAt` est posé à cette date avant le pull, pour qu'un pull raté se rejoue au `fullSync` suivant (#150). — `src/services/syncClient.ts`, `src/services/syncRules.ts` (`mergeTaskData`) -- 2.52.0