From 9434cb77efd2fec32d87520ba84567e11e40817a Mon Sep 17 00:00:00 2001 From: le king fu Date: Sat, 14 Nov 2026 18:22:38 -0500 Subject: [PATCH] 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); + }); +});