From b03f070a5147dcf753dced1eb57977accab00592 Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 20:43:41 -0500 Subject: [PATCH 01/18] feat(web): notify open pages over WebSocket after every mutation The companion never told an open page that its data changed: broadcastToUser() had no caller, and the client set existed twice because server.ts is bundled apart from the Next routes, so the routes (and /api/health) saw an empty set. - Keep the client set on globalThis.__wsClients, like the ticket store. - WsMessage sync variant is now { type: 'sync' } with no detail. - notifyUserChanged(userId) coalesces per account with a 1 s trailing debounce; a send that throws drops the socket instead of crashing. - POST /api/sync notifies once per batch when at least one operation is applied; every REST mutation handler of lists, tasks and tags notifies after success. - useSync refreshes only on a sync message, debounced 500 ms; auth_expired no longer triggers a refresh. Tests: ws.test.ts (payload, coalescing, shared set across module instances, source guard on mutation handlers) and sync route tests (one notification per applied batch, none for refused or duplicate batches, never another account). Refs #177 Refs #167 Co-Authored-By: Claude Opus 5.5 --- web/src/app/api/lists/[id]/route.ts | 3 + web/src/app/api/lists/reorder/route.ts | 2 + web/src/app/api/lists/route.ts | 2 + web/src/app/api/sync/route.test.ts | 56 +++++- web/src/app/api/sync/route.ts | 5 + web/src/app/api/tags/[id]/route.ts | 3 + web/src/app/api/tags/route.ts | 2 + web/src/app/api/tasks/[id]/route.ts | 3 + .../app/api/tasks/[id]/tags/[tagId]/route.ts | 2 + web/src/app/api/tasks/[id]/tags/route.ts | 2 + web/src/app/api/tasks/reorder/route.ts | 2 + web/src/app/api/tasks/route.ts | 2 + web/src/components/useSync.ts | 23 ++- web/src/lib/ws.test.ts | 168 ++++++++++++++++++ web/src/lib/ws.ts | 58 +++++- 15 files changed, 326 insertions(+), 7 deletions(-) create mode 100644 web/src/lib/ws.test.ts diff --git a/web/src/app/api/lists/[id]/route.ts b/web/src/app/api/lists/[id]/route.ts index 59b40dc..ceabcc0 100644 --- a/web/src/app/api/lists/[id]/route.ts +++ b/web/src/app/api/lists/[id]/route.ts @@ -4,6 +4,7 @@ import { slLists } from '@/db/schema'; import { eq, and } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { updateListSchema } from '@/lib/validators'; export async function PUT( @@ -29,6 +30,7 @@ export async function PUT( return NextResponse.json({ error: 'Not found' }, { status: 404 }); } + notifyUserChanged(auth.userId); return NextResponse.json(updated); } @@ -53,5 +55,6 @@ export async function DELETE( return NextResponse.json({ error: 'Not found' }, { status: 404 }); } + notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }); } diff --git a/web/src/app/api/lists/reorder/route.ts b/web/src/app/api/lists/reorder/route.ts index 885689e..afe2a77 100644 --- a/web/src/app/api/lists/reorder/route.ts +++ b/web/src/app/api/lists/reorder/route.ts @@ -4,6 +4,7 @@ import { slLists } from '@/db/schema'; import { eq, and, inArray } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { reorderSchema } from '@/lib/validators'; export async function PUT(request: Request) { @@ -35,5 +36,6 @@ export async function PUT(request: Request) { ) ); + notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }); } diff --git a/web/src/app/api/lists/route.ts b/web/src/app/api/lists/route.ts index f300a74..d62df43 100644 --- a/web/src/app/api/lists/route.ts +++ b/web/src/app/api/lists/route.ts @@ -4,6 +4,7 @@ import { slLists } from '@/db/schema'; import { eq, isNull, and, asc } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { createListSchema } from '@/lib/validators'; export async function GET() { @@ -35,5 +36,6 @@ export async function POST(request: Request) { .values({ ...body.data, userId: auth.userId }) .returning(); + notifyUserChanged(auth.userId); return NextResponse.json(list, { status: 201 }); } diff --git a/web/src/app/api/sync/route.test.ts b/web/src/app/api/sync/route.test.ts index 1d59dbf..5baa212 100644 --- a/web/src/app/api/sync/route.test.ts +++ b/web/src/app/api/sync/route.test.ts @@ -10,7 +10,7 @@ import type { PGlite } from 'electric-sql-pglite'; const h = await vi.hoisted(async () => { const { PGlite } = await import('electric-sql-pglite'); - return { pg: new PGlite() as PGlite, userId: '', cleanups: 0 }; + return { pg: new PGlite() as PGlite, userId: '', cleanups: 0, notified: [] as string[] }; }); vi.mock('@/db/client', async () => { @@ -28,6 +28,9 @@ vi.mock('@/lib/api', async (importOriginal) => ({ vi.mock('@/lib/rateLimit', () => ({ rateLimit: () => null })); +// WebSocket notifications (#177): record which accounts the route notifies. +vi.mock('@/lib/ws', () => ({ notifyUserChanged: (userId: string) => { h.notified.push(userId); } })); + // Real idempotency store, with its cleanup counted: the route must call it (#147). vi.mock('@/lib/idempotency', async (importOriginal) => { const mod = await importOriginal(); @@ -626,3 +629,54 @@ describe('POST /api/sync: results contract (#151)', () => { expect((replay.error as string).length).toBeGreaterThan(0); }); }); + +describe('POST /api/sync: open pages notified over WebSocket (#177)', () => { + // Calls made during one push, by any account: tests run one at a time. + async function notifiedBy(fn: () => Promise): Promise { + h.notified.length = 0; + await fn(); + return [...h.notified]; + } + + it('notifies the caller once for a batch that applies at least one operation', async () => { + const { B } = await seed(); + const t1 = u(); + const t2 = u(); + const calls = await notifiedBy(async () => { + expect(await push(B.userId, [ + ['task', 'create', t1, { title: 'one', listId: B.list }], + ['task', 'create', t2, { title: 'two', listId: B.list }], + ['task', 'update', u(), { title: 'missing' }], + ])).toEqual(['applied', 'applied', 'skipped']); + }); + expect(calls).toEqual([B.userId]); + }); + + it('does not notify for a batch entirely refused, and never another account', async () => { + const { A, B } = await seed(); + const calls = await notifiedBy(async () => { + expect(await push(B.userId, [ + ['task', 'update', A.task, { title: 'stolen' }], + ['list', 'delete', A.list], + ['taskTag', 'create', A.task, { tagId: B.tag }], + ])).toEqual(['skipped', 'skipped', 'skipped']); + }); + expect(calls).toEqual([]); + }); + + it('does not notify for a batch of duplicates already applied', async () => { + const { B } = await seed(); + h.userId = B.userId; + const body = JSON.stringify({ operations: [{ + idempotencyKey: u(), entityType: 'task', action: 'update', entityId: B.task, data: { title: 'once' }, + }] }); + const send = () => POST(new Request('http://localhost/api/sync', { method: 'POST', body })); + expect(await notifiedBy(send)).toEqual([B.userId]); + const calls = await notifiedBy(async () => { + const res = await send(); + const { results } = await res.json() as { results: Result[] }; + expect(results.map((r) => r.status)).toEqual(['skipped']); + }); + expect(calls).toEqual([]); + }); +}); diff --git a/web/src/app/api/sync/route.ts b/web/src/app/api/sync/route.ts index df799f0..2972174 100644 --- a/web/src/app/api/sync/route.ts +++ b/web/src/app/api/sync/route.ts @@ -6,6 +6,7 @@ import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; import { syncPushSchema, type SyncOperation } from '@/lib/validators'; import { createIdempotencyStore } from '@/lib/idempotency'; +import { notifyUserChanged } from '@/lib/ws'; import { listCreateData, listUpdateData, @@ -181,6 +182,10 @@ export async function POST(request: Request) { } } + // One notification per batch, and none when nothing was written: a batch of + // duplicates or refusals changes nothing an open page shows (#177). + if (results.some((r) => r.status === 'applied')) notifyUserChanged(auth.userId); + return NextResponse.json({ results, syncedAt: new Date().toISOString() }); } diff --git a/web/src/app/api/tags/[id]/route.ts b/web/src/app/api/tags/[id]/route.ts index 3c4a1f3..dfa7af5 100644 --- a/web/src/app/api/tags/[id]/route.ts +++ b/web/src/app/api/tags/[id]/route.ts @@ -4,6 +4,7 @@ import { slTags } from '@/db/schema'; import { eq, and } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { updateTagSchema } from '@/lib/validators'; export async function PUT( @@ -29,6 +30,7 @@ export async function PUT( return NextResponse.json({ error: 'Not found' }, { status: 404 }); } + notifyUserChanged(auth.userId); return NextResponse.json(updated); } @@ -53,5 +55,6 @@ export async function DELETE( return NextResponse.json({ error: 'Not found' }, { status: 404 }); } + notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }); } diff --git a/web/src/app/api/tags/route.ts b/web/src/app/api/tags/route.ts index aa7d48f..378dc3d 100644 --- a/web/src/app/api/tags/route.ts +++ b/web/src/app/api/tags/route.ts @@ -4,6 +4,7 @@ import { slTags } from '@/db/schema'; import { eq, isNull, and, asc } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { createTagSchema } from '@/lib/validators'; export async function GET() { @@ -35,5 +36,6 @@ export async function POST(request: Request) { .values({ ...body.data, userId: auth.userId }) .returning(); + notifyUserChanged(auth.userId); return NextResponse.json(tag, { status: 201 }); } diff --git a/web/src/app/api/tasks/[id]/route.ts b/web/src/app/api/tasks/[id]/route.ts index 3bc57f3..f1fa13a 100644 --- a/web/src/app/api/tasks/[id]/route.ts +++ b/web/src/app/api/tasks/[id]/route.ts @@ -4,6 +4,7 @@ import { slTasks } from '@/db/schema'; import { eq, and } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { updateTaskSchema } from '@/lib/validators'; export async function PUT( @@ -44,6 +45,7 @@ export async function PUT( return NextResponse.json({ error: 'Not found' }, { status: 404 }); } + notifyUserChanged(auth.userId); return NextResponse.json(updated); } @@ -68,5 +70,6 @@ export async function DELETE( return NextResponse.json({ error: 'Not found' }, { status: 404 }); } + notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }); } diff --git a/web/src/app/api/tasks/[id]/tags/[tagId]/route.ts b/web/src/app/api/tasks/[id]/tags/[tagId]/route.ts index 32e9b55..6d64375 100644 --- a/web/src/app/api/tasks/[id]/tags/[tagId]/route.ts +++ b/web/src/app/api/tasks/[id]/tags/[tagId]/route.ts @@ -4,6 +4,7 @@ import { slTasks, slTaskTags } from '@/db/schema'; import { eq, and } from 'drizzle-orm'; import { requireAuth } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; export async function DELETE( _request: Request, @@ -30,5 +31,6 @@ export async function DELETE( .delete(slTaskTags) .where(and(eq(slTaskTags.taskId, taskId), eq(slTaskTags.tagId, tagId))); + notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }); } diff --git a/web/src/app/api/tasks/[id]/tags/route.ts b/web/src/app/api/tasks/[id]/tags/route.ts index 04139ad..4389920 100644 --- a/web/src/app/api/tasks/[id]/tags/route.ts +++ b/web/src/app/api/tasks/[id]/tags/route.ts @@ -4,6 +4,7 @@ import { slTasks, slTags, slTaskTags } from '@/db/schema'; import { eq, and, inArray } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { assignTagsSchema } from '@/lib/validators'; export async function POST( @@ -46,5 +47,6 @@ export async function POST( .values(body.data.tagIds.map((tagId) => ({ taskId, tagId }))) .onConflictDoNothing(); + notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }, { status: 201 }); } diff --git a/web/src/app/api/tasks/reorder/route.ts b/web/src/app/api/tasks/reorder/route.ts index 1db89d8..9eac9cc 100644 --- a/web/src/app/api/tasks/reorder/route.ts +++ b/web/src/app/api/tasks/reorder/route.ts @@ -4,6 +4,7 @@ import { slTasks } from '@/db/schema'; import { eq, and, inArray } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { reorderSchema } from '@/lib/validators'; export async function PUT(request: Request) { @@ -34,5 +35,6 @@ export async function PUT(request: Request) { ) ); + notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }); } diff --git a/web/src/app/api/tasks/route.ts b/web/src/app/api/tasks/route.ts index ad9c9e7..da82273 100644 --- a/web/src/app/api/tasks/route.ts +++ b/web/src/app/api/tasks/route.ts @@ -4,6 +4,7 @@ import { slTasks, slLists } from '@/db/schema'; import { eq, and } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { createTaskSchema } from '@/lib/validators'; export async function POST(request: Request) { @@ -50,5 +51,6 @@ export async function POST(request: Request) { }) .returning(); + notifyUserChanged(auth.userId); return NextResponse.json(task, { status: 201 }); } diff --git a/web/src/components/useSync.ts b/web/src/components/useSync.ts index 6f69c5c..99e2002 100644 --- a/web/src/components/useSync.ts +++ b/web/src/components/useSync.ts @@ -3,12 +3,22 @@ import { useEffect } from "react"; import { useRouter } from "next/navigation"; +// Client-side debounce on top of the server's per-account coalescing (#177): +// several messages close together trigger a single refresh. +const REFRESH_DEBOUNCE_MS = 500; + export function useSync() { const router = useRouter(); useEffect(() => { let ws: WebSocket | null = null; let retryTimeout: ReturnType; + let refreshTimeout: ReturnType | undefined; + + function scheduleRefresh() { + clearTimeout(refreshTimeout); + refreshTimeout = setTimeout(() => router.refresh(), REFRESH_DEBOUNCE_MS); + } async function connect() { try { @@ -20,9 +30,15 @@ export function useSync() { const proto = window.location.protocol === "https:" ? "wss:" : "ws:"; ws = new WebSocket(`${proto}//${window.location.host}/ws?ticket=${ticket}`); - ws.onmessage = () => { - // Any sync message triggers a data refresh - router.refresh(); + ws.onmessage = (event) => { + // Only a sync message refreshes the data; auth_expired does not. + let type: unknown; + try { + type = (JSON.parse(String(event.data)) as { type?: unknown }).type; + } catch { + return; + } + if (type === "sync") scheduleRefresh(); }; ws.onclose = () => { @@ -39,6 +55,7 @@ export function useSync() { return () => { ws?.close(); clearTimeout(retryTimeout); + clearTimeout(refreshTimeout); }; }, [router]); } diff --git a/web/src/lib/ws.test.ts b/web/src/lib/ws.test.ts new file mode 100644 index 0000000..c310b71 --- /dev/null +++ b/web/src/lib/ws.test.ts @@ -0,0 +1,168 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { EventEmitter } from 'node:events'; +import type { Server } from 'node:http'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; + +// WebSocket notifications of the companion (#177): payload, per-account +// coalescing, and the client set shared between the two bundles (server.ts is +// bundled apart from the Next routes, each gets its own copy of ws.ts). + +type FakeSocket = EventEmitter & { + userId: string; + readyState: number; + send: ReturnType; +}; + +const OPEN = 1; // WebSocket.OPEN + +const g = globalThis as unknown as { + __wsClients?: Set; + __wsNotifyTimers?: Map>; +}; + +function fakeSocket(userId: string): FakeSocket { + return Object.assign(new EventEmitter(), { userId, readyState: OPEN, send: vi.fn() }); +} + +async function freshModule() { + vi.resetModules(); + return import('./ws'); +} + +beforeEach(() => { + vi.useFakeTimers(); + for (const t of g.__wsNotifyTimers?.values() ?? []) clearTimeout(t); + delete g.__wsClients; + delete g.__wsNotifyTimers; +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('notifyUserChanged', () => { + it('sends exactly {"type":"sync"}', async () => { + const ws = await freshModule(); + const a = fakeSocket('user-a'); + g.__wsClients!.add(a); + + ws.notifyUserChanged('user-a'); + vi.advanceTimersByTime(ws.NOTIFY_DEBOUNCE_MS); + + expect(a.send).toHaveBeenCalledTimes(1); + expect(a.send.mock.calls[0][0]).toBe('{"type":"sync"}'); + }); + + it('coalesces N calls within 1 s into one message', async () => { + const ws = await freshModule(); + const a = fakeSocket('user-a'); + g.__wsClients!.add(a); + + for (let i = 0; i < 20; i++) { + ws.notifyUserChanged('user-a'); + vi.advanceTimersByTime(ws.NOTIFY_DEBOUNCE_MS - 1); + } + expect(a.send).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(1); + expect(a.send).toHaveBeenCalledTimes(1); + + // Nothing left pending afterwards. + vi.advanceTimersByTime(10 * ws.NOTIFY_DEBOUNCE_MS); + expect(a.send).toHaveBeenCalledTimes(1); + }); + + it('notifies only the sockets of that account, each account on its own timer', async () => { + const ws = await freshModule(); + const a1 = fakeSocket('user-a'); + const a2 = fakeSocket('user-a'); + const b = fakeSocket('user-b'); + const closed = fakeSocket('user-a'); + closed.readyState = 3; // CLOSED + for (const s of [a1, a2, b, closed]) g.__wsClients!.add(s); + + ws.notifyUserChanged('user-a'); + vi.advanceTimersByTime(ws.NOTIFY_DEBOUNCE_MS / 2); + ws.notifyUserChanged('user-b'); + vi.advanceTimersByTime(ws.NOTIFY_DEBOUNCE_MS / 2); + + expect(a1.send).toHaveBeenCalledTimes(1); + expect(a2.send).toHaveBeenCalledTimes(1); + expect(closed.send).not.toHaveBeenCalled(); + expect(b.send).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(ws.NOTIFY_DEBOUNCE_MS / 2); + expect(b.send).toHaveBeenCalledTimes(1); + expect(a1.send).toHaveBeenCalledTimes(1); + }); + + it('drops a socket whose send throws instead of crashing the timer', async () => { + const ws = await freshModule(); + const a = fakeSocket('user-a'); + a.send.mockImplementation(() => { throw new Error('broken'); }); + g.__wsClients!.add(a); + + ws.notifyUserChanged('user-a'); + expect(() => vi.advanceTimersByTime(ws.NOTIFY_DEBOUNCE_MS)).not.toThrow(); + expect(ws.getActiveConnections()).toBe(0); + }); +}); + +describe('client set shared between module instances', () => { + it('a socket accepted by one instance is seen and notified by another', async () => { + const serverSide = await freshModule(); + const routeSide = await freshModule(); + expect(routeSide).not.toBe(serverSide); + + const wss = serverSide.setupWebSocket(new EventEmitter() as unknown as Server); + const a = fakeSocket('user-a'); + wss.emit('connection', a); + + expect(serverSide.getActiveConnections()).toBe(1); + expect(routeSide.getActiveConnections()).toBe(1); + + routeSide.notifyUserChanged('user-a'); + vi.advanceTimersByTime(routeSide.NOTIFY_DEBOUNCE_MS); + expect(a.send).toHaveBeenCalledWith('{"type":"sync"}'); + + a.emit('close'); + expect(routeSide.getActiveConnections()).toBe(0); + wss.close(); + }); +}); + +// Source guard: every mutation handler of the REST routes notifies open pages. +describe('REST mutation routes call notifyUserChanged', () => { + const apiDir = path.join(__dirname, '../app/api'); + + function routeFiles(dir: string): string[] { + return fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => { + const p = path.join(dir, e.name); + if (e.isDirectory()) return routeFiles(p); + return e.name === 'route.ts' ? [p] : []; + }); + } + + const files = ['lists', 'tasks', 'tags'].flatMap((d) => routeFiles(path.join(apiDir, d))); + const MUTATIONS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']); + + it('finds the route files', () => { + expect(files.length).toBeGreaterThanOrEqual(12); + }); + + it.each(files.map((f) => [path.relative(apiDir, f), f]))('%s', (_rel, file) => { + const src = fs.readFileSync(file, 'utf8'); + // Only `export async function NAME` handlers are parsed: any other export + // form of a method would escape the guard, so it fails here instead. + expect(src).not.toMatch(/export\s+(const|let|var)\s+(GET|POST|PUT|PATCH|DELETE)\b/); + expect(src).not.toMatch(/export\s*\{[^}]*\b(POST|PUT|PATCH|DELETE)\b/); + + const chunks = src.split(/(?=export\s+(?:async\s+)?function\s+)/); + for (const chunk of chunks) { + const m = chunk.match(/^export\s+(?:async\s+)?function\s+(\w+)/); + if (!m || !MUTATIONS.has(m[1])) continue; + expect(chunk, `${m[1]} handler`).toContain('notifyUserChanged(auth.userId)'); + } + }); +}); diff --git a/web/src/lib/ws.ts b/web/src/lib/ws.ts index 2384ba5..a454e77 100644 --- a/web/src/lib/ws.ts +++ b/web/src/lib/ws.ts @@ -2,8 +2,11 @@ import { WebSocketServer, WebSocket } from 'ws'; import type { IncomingMessage } from 'http'; import type { Server } from 'http'; +// A sync message carries no detail: a socket stays bound to its userId up to +// 15 min after a web sign-out (REVALIDATION_INTERVAL), so it must never learn +// what changed, only that something did (#177). Never add fields here. export type WsMessage = - | { type: 'sync'; entity: 'list' | 'task' | 'tag'; action: 'create' | 'update' | 'delete'; id: string } + | { type: 'sync' } | { type: 'auth_expired' }; interface AuthenticatedSocket extends WebSocket { @@ -33,7 +36,34 @@ const ALLOWED_ORIGINS = [ const REVALIDATION_INTERVAL = 15 * 60 * 1000; // 15 minutes const HEARTBEAT_INTERVAL = 30 * 1000; // 30 seconds -const clients = new Set(); +// server.ts is bundled apart from the Next routes (web/Dockerfile, esbuild): +// each bundle gets its own copy of this module. The client set lives on +// globalThis, like the ticket store, so the routes see the sockets server.ts +// accepted (#177). +const shared = globalThis as unknown as { + __wsClients?: Set; + __wsNotifyTimers?: Map>; +}; + +function getClients() { + if (!shared.__wsClients) { + shared.__wsClients = new Set(); + } + return shared.__wsClients; +} + +function getNotifyTimers() { + if (!shared.__wsNotifyTimers) { + shared.__wsNotifyTimers = new Map(); + } + return shared.__wsNotifyTimers; +} + +const clients = getClients(); + +// Trailing debounce per account: a burst of mutations (a reorder of N items, +// a sync batch) sends one message, 1 s after the last one. +export const NOTIFY_DEBOUNCE_MS = 1000; export function setupWebSocket(server: Server) { const wss = new WebSocketServer({ noServer: true }); @@ -137,11 +167,33 @@ export function broadcastToUser(userId: string, message: WsMessage) { const payload = JSON.stringify(message); for (const ws of clients) { if (ws.userId === userId && ws.readyState === WebSocket.OPEN) { - ws.send(payload); + // Runs from a timer (notifyUserChanged): a throw here would be uncaught. + try { + ws.send(payload); + } catch { + clients.delete(ws); + } } } } +/** + * Tell every open page of an account that its data changed. Coalesced per + * account: N calls within NOTIFY_DEBOUNCE_MS of each other send one message. + */ +export function notifyUserChanged(userId: string) { + const timers = getNotifyTimers(); + const pending = timers.get(userId); + if (pending) clearTimeout(pending); + const timer = setTimeout(() => { + timers.delete(userId); + broadcastToUser(userId, { type: 'sync' }); + }, NOTIFY_DEBOUNCE_MS); + // Never keep the process alive for a pending notification. + timer.unref?.(); + timers.set(userId, timer); +} + export function getActiveConnections(): number { return clients.size; } -- 2.52.0 From 7265c6cad4c0866862472629d448145bd97ac906 Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 20:54:33 -0500 Subject: [PATCH 02/18] fix(sync): sync on write with a request-budget scheduler and a 30 s interval Every sync now goes through one scheduler (src/services/syncSchedule.ts, pure and import-free): one sync at a time, a request during a sync gives a single relaunch, a sliding budget of 6 real HTTP requests per 60 s (each POST batch and each GET counted, initialMerge and initialReset included), pushChanges sends the batches the budget allows (MAX_PUSH_BATCHES becomes a ceiling) and the rest of the queue follows once the window frees, a 429 suspends the scheduler until Retry-After, and no sync starts during initialMerge / initialReset. The repositories call requestSync() (src/services/syncTrigger.ts, 2 s debounce, single subscriber registered by _layout.tsx) after each outbox write and after the Inbox repair transaction; outbox.ts and syncClient.ts never do. _layout.tsx syncs on launch, every 30 s in the foreground, on return to the foreground and on write through scheduleSync(); the Settings button too. REVIEW.md and scripts/review-levels.py list the two new files in the Sync row. test: reproduces #178 (tests/syncSchedule.test.mjs, smoke guards) Refs #178 Refs #167 Co-Authored-By: Claude Opus 5.5 --- REVIEW.md | 12 +- app/(tabs)/settings.tsx | 5 +- app/_layout.tsx | 34 +++- package.json | 2 +- scripts/review-levels.py | 4 +- src/db/repository/lists.ts | 9 +- src/db/repository/tags.ts | 9 +- src/db/repository/tasks.ts | 9 +- src/services/syncClient.ts | 111 +++++++++--- src/services/syncRules.ts | 7 +- src/services/syncSchedule.ts | 188 +++++++++++++++++++ src/services/syncTrigger.ts | 38 ++++ tests/smoke.test.cjs | 89 ++++++++- tests/syncSchedule.test.mjs | 338 +++++++++++++++++++++++++++++++++++ 14 files changed, 791 insertions(+), 64 deletions(-) create mode 100644 src/services/syncSchedule.ts create mode 100644 src/services/syncTrigger.ts create mode 100644 tests/syncSchedule.test.mjs diff --git a/REVIEW.md b/REVIEW.md index d78e342..5fb156c 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -28,9 +28,9 @@ Motifs : chemins depuis la racine. `*` ne traverse jamais un `/` ; `**/` vaut z |---|---|---| | `src/lib/{authToken,logtoConfig,validation}.ts`, `web/src/lib/{auth,logto,api}.ts`, `web/src/middleware.ts`, `web/src/app/api/logto/**`, `web/src/app/auth/**` | toujours | Authentification | | `web/src/app/api/**`, `web/src/lib/{validators,syncData,rateLimit,ws,idempotency}.ts`, `web/server.ts` | toujours | API et isolation des comptes | -| `src/services/{syncClient,syncRules}.ts`, `src/db/repository/outbox.ts` | toujours | Sync | +| `src/services/{syncClient,syncRules,syncSchedule,syncTrigger}.ts`, `src/db/repository/outbox.ts` | toujours | Sync | | `src/db/{schema,client}.ts`, `src/db/migrations/**`, `web/src/db/{schema,client,seed}.ts`, `web/src/db/migrations/**`, `drizzle.config.ts`, `web/drizzle.config.ts`, `sql-transformer.js` | toujours | Migrations et données | -| `app/_layout.tsx` | le diff touche les migrations (`useMigrations`), `LogtoProvider`, le jeton (`setTokenGetter`) ou les appels de sync (`fullSync`, `cleanOutbox`) | Migrations et données, Authentification, Sync | +| `app/_layout.tsx` | le diff touche les migrations (`useMigrations`), `LogtoProvider`, le jeton (`setTokenGetter`) ou les appels de sync (`fullSync`, `cleanOutbox`, `scheduleSync`, `setSyncSubscriber`) | Migrations et données, Authentification, Sync | | `app/(tabs)/settings.tsx` | le diff touche la connexion, l'activation de la sync (`initialMerge`, `initialReset`, `setSyncEnabled`) ou la vérification des mises à jour (`releases/latest`, asset `.apk`) | Sync, Release | | `src/services/feedback.ts`, `src/components/FeedbackModal.tsx`, `src/hooks/useFeedback.ts` | toujours | Vie privée | | code livré : `app/**`, `src/**`, `web/src/**` | le diff ajoute un appel réseau vers une URL absolue (un `fetch`, ou une URL de base dans une constante ou un champ de configuration), ou change ce qu'un appel existant envoie | Vie privée | @@ -115,11 +115,13 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm - 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 (`writeOutboxEntry`, action `update`). Jamais une étiquette : le serveur n'a pas d'`updatedAt` sur les étiquettes et renvoie `updated_at` = `created_at`, donc un renommage hors connexion d'étiquette est perdu (check smoke « applyTagChange never keeps a local tag »). — `src/services/syncRules.ts` (`keepLocal`), `src/services/syncClient.ts`, #149 - 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`) - Une suppression serveur s'applique toujours, même sur une ligne locale plus récente : le protocole n'a pas de restauration. — `src/services/syncClient.ts`, #149 -- `src/services/syncRules.ts` reste sans import, pour que `tests/syncRules.test.mjs` le charge par le type stripping de Node (check smoke `syncRules.ts stays import-free`). — `tests/smoke.test.cjs`, `tests/syncRules.test.mjs`, #149 +- `src/services/syncRules.ts` reste sans import, pour que `tests/syncRules.test.mjs` le charge par le type stripping de Node (check smoke `syncRules.ts stays import-free`). `src/services/syncSchedule.ts` et `src/services/syncTrigger.ts` suivent la même règle pour `tests/syncSchedule.test.mjs` (check smoke `syncSchedule.ts and syncTrigger.ts stay import-free`). — `tests/smoke.test.cjs`, `tests/syncRules.test.mjs`, `tests/syncSchedule.test.mjs`, #149, #178 - Contrat des résultats d'un push : `applied` = opération écrite, `skipped` sans `error` = clé déjà vue, donc doublon déjà appliqué, `skipped` avec `error` = refus. L'app marque les deux premiers comme synchronisés et rejoue le troisième : le serveur garde cette distinction. — `src/services/syncRules.ts` (`parseResults`, `isSynced`), `web/src/app/api/sync/route.ts`, `web/src/app/api/sync/route.test.ts`, #151 - Un refus est rejoué à chaque push, 30 jours (`REJECTED_RETENTION_DAYS`) et 100 refus (`MAX_KEPT_REFUSALS`, les plus récents) au plus, et abandonné dès qu'une entrée plus récente de la même entité (`entityType` + `entityId`, plus `tagId` pour `taskTag`) passe dans le même push. Cette règle de remplacement tient parce que les refus repartent à chaque push, dans l'ordre de création, avant les entrées plus récentes : un espacement des rejeux la remet en cause. Une entrée sans résultat (lot non envoyé ou en échec) n'est pas marquée. — `src/services/syncRules.ts` (`classifyOutbox`), `src/services/syncClient.ts`, #151 -- `pushChanges` envoie 8 lots au plus (`MAX_PUSH_BATCHES`) et s'arrête au premier 429, et `initialMerge` envoie tous les lots en attendant le `Retry-After` d'un 429 (borné à 60 s, 3 renvois du même lot au plus). — `src/services/syncRules.ts` (`sendInBatches`), `src/services/syncClient.ts`, `tests/smoke.test.cjs`, #151 -- La limite `sync` (10 requêtes par minute et par compte, GET et POST confondus) est le budget d'un `fullSync` : 8 lots de push laissent la place du pull. Un lot ou une requête ajoutés se jugent contre elle. — `web/src/lib/rateLimit.ts`, `src/services/syncRules.ts`, #151 +- `pushChanges` envoie les lots que le planificateur autorise (budget restant moins la place du GET du pull, 8 au plus, `MAX_PUSH_BATCHES`) et s'arrête au premier 429, et `initialMerge` envoie tous les lots en attendant le `Retry-After` d'un 429 (borné à 60 s, 3 renvois du même lot au plus). — `src/services/syncRules.ts` (`sendInBatches`), `src/services/syncClient.ts`, `tests/smoke.test.cjs`, #151, #178 +- La limite `sync` du serveur (10 requêtes par minute et par compte, GET et POST confondus, tous appareils confondus) est partagée : l'app s'en tient à 6 requêtes HTTP réelles par 60 s glissantes (`REQUEST_BUDGET`), chaque POST de lot et chaque GET comptés, `initialMerge` et `initialReset` compris. Une requête ajoutée vers `/api/sync` passe par `RequestTracker` (`request()` avant l'envoi, `rateLimited()` sur un 429), sinon le budget ment. — `web/src/lib/rateLimit.ts`, `src/services/syncSchedule.ts`, `src/services/syncClient.ts`, #151, #178 +- Toute sync passe par le planificateur (`scheduleSync`) : lancement, intervalle de 30 s au premier plan, retour au premier plan, écriture locale et bouton « Synchroniser maintenant ». Une sync à la fois, une demande pendant une sync donne une seule relance, un 429 suspend jusqu'au `Retry-After`, et aucune sync ne part pendant `initialMerge` / `initialReset`. `fullSync` reste privé à `syncClient.ts`. — `src/services/syncSchedule.ts`, `src/services/syncClient.ts`, `app/_layout.tsx`, `app/(tabs)/settings.tsx`, `tests/syncSchedule.test.mjs`, #178 +- Les repositories (`lists`, `tasks`, `tags`) appellent `requestSync()` (anti-rebond de 2 s) après chaque écriture d'outbox et après le commit d'une transaction ; `outbox.ts` et `syncClient.ts` ne l'appellent jamais, pour que les écritures de la sync elle-même (`keepLocal`, `initialReset`) ne relancent rien. Sans abonné (widget headless, sync coupée), une demande ne fait rien. — `src/services/syncTrigger.ts`, `src/db/repository/{lists,tasks,tags}.ts`, `tests/smoke.test.cjs`, #178 - Après un push ou un pull qui applique des changements, le widget est rafraîchi (`syncWidgetData`). — PR #66, `src/services/syncClient.ts` ### Migrations et données diff --git a/app/(tabs)/settings.tsx b/app/(tabs)/settings.tsx index 653908d..7ea22e1 100644 --- a/app/(tabs)/settings.tsx +++ b/app/(tabs)/settings.tsx @@ -12,7 +12,7 @@ import { redirectUri, postSignOutRedirectUri } from '@/src/lib/logtoConfig'; import { getAllTags, createTag, updateTag, deleteTag } from '@/src/db/repository/tags'; import { initCalendar } from '@/src/services/calendar'; import { syncWidgetData } from '@/src/services/widgetSync'; -import { fullSync, initialMerge, initialReset } from '@/src/services/syncClient'; +import { scheduleSync, initialMerge, initialReset } from '@/src/services/syncClient'; import i18n from '@/src/i18n'; import FeedbackModal from '@/src/components/FeedbackModal'; @@ -215,7 +215,8 @@ export default function SettingsScreen() { setIsSyncing(true); try { - await fullSync(); + // Through the scheduler (#178): may wait for the request budget + await scheduleSync(); } catch { // Sync errors are logged internally } finally { diff --git a/app/_layout.tsx b/app/_layout.tsx index c0ffc41..f0bbc74 100644 --- a/app/_layout.tsx +++ b/app/_layout.tsx @@ -15,7 +15,8 @@ import { ensureInbox, repairInbox } from '@/src/db/repository/lists'; import { useSettingsStore } from '@/src/stores/useSettingsStore'; import { initNotifications } from '@/src/services/notifications'; import { syncWidgetData } from '@/src/services/widgetSync'; -import { fullSync, cleanOutbox } from '@/src/services/syncClient'; +import { scheduleSync } from '@/src/services/syncClient'; +import { setSyncSubscriber } from '@/src/services/syncTrigger'; import { logtoConfig } from '@/src/lib/logtoConfig'; import { setTokenGetter, clearTokenGetter } from '@/src/lib/authToken'; import '@/src/i18n'; @@ -23,6 +24,10 @@ import '@/src/global.css'; export { ErrorBoundary } from 'expo-router'; +// Foreground sync interval (decision of Max, 2026-10-29, #167); back to 2 min +// once the WebSocket of #175 replaces the polling. +const SYNC_INTERVAL_MS = 30 * 1000; + SplashScreen.preventAutoHideAsync(); const SimplLightTheme = { @@ -119,27 +124,40 @@ function AppContent() { return () => clearTokenGetter(); }, [isAuthenticated, syncEnabled, getAccessToken]); - // Sync polling: run on launch, every 2 min, and on return from background + // Sync (#178): on launch, every 30 s in the foreground, on return from + // background and after a local write, always through the scheduler (one + // sync at a time, request budget, Retry-After of a 429). useEffect(() => { if (!syncEnabled) return; + let active = true; - // Initial sync, once the Inbox is set up - prepareInbox().then(() => fullSync()).then(() => cleanOutbox()).catch(() => {}); + // Initial sync and sync on write, once the Inbox is set up: a push during + // the repair would replay the entries it rewrites + prepareInbox().then(() => { + if (!active) return; + setSyncSubscriber(() => { + scheduleSync().catch(() => {}); + }); + return scheduleSync(); + }).catch(() => {}); - // 2-minute interval + // 30-second interval, foreground only const interval = setInterval(() => { - fullSync().then(() => cleanOutbox()).catch(() => {}); - }, 2 * 60 * 1000); + if (AppState.currentState !== 'active') return; + prepareInbox().then(() => scheduleSync()).catch(() => {}); + }, SYNC_INTERVAL_MS); // AppState listener: sync when returning from background const subscription = AppState.addEventListener('change', (nextState: AppStateStatus) => { if (appState.current.match(/inactive|background/) && nextState === 'active') { - fullSync().catch(() => {}); + prepareInbox().then(() => scheduleSync()).catch(() => {}); } appState.current = nextState; }); return () => { + active = false; + setSyncSubscriber(null); clearInterval(interval); subscription.remove(); }; diff --git a/package.json b/package.json index ca1600f..45cbf22 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "version": "1.7.0", "scripts": { "start": "expo start", - "test": "node tests/smoke.test.cjs && node --test --disable-warning=ExperimentalWarning --disable-warning=MODULE_TYPELESS_PACKAGE_JSON tests/feedback.test.mjs tests/syncRules.test.mjs tests/hydration.test.mjs", + "test": "node tests/smoke.test.cjs && node --test --disable-warning=ExperimentalWarning --disable-warning=MODULE_TYPELESS_PACKAGE_JSON tests/feedback.test.mjs tests/syncRules.test.mjs tests/hydration.test.mjs tests/syncSchedule.test.mjs", "android": "expo start --android", "ios": "expo start --ios", "web": "expo start --web", diff --git a/scripts/review-levels.py b/scripts/review-levels.py index ce8a980..7913b2e 100755 --- a/scripts/review-levels.py +++ b/scripts/review-levels.py @@ -46,7 +46,7 @@ HIGH_ALWAYS = [ "web/src/lib/{auth,logto,api}.ts", "web/src/middleware.ts", "web/src/app/api/logto/**", "web/src/app/auth/**", "web/src/app/api/**", "web/src/lib/{validators,syncData,rateLimit,ws,idempotency}.ts", "web/server.ts", - "src/services/{syncClient,syncRules}.ts", "src/db/repository/outbox.ts", + "src/services/{syncClient,syncRules,syncSchedule,syncTrigger}.ts", "src/db/repository/outbox.ts", "src/db/{schema,client}.ts", "src/db/migrations/**", "web/src/db/{schema,client,seed}.ts", "web/src/db/migrations/**", "drizzle.config.ts", "web/drizzle.config.ts", "sql-transformer.js", @@ -56,7 +56,7 @@ HIGH_ALWAYS = [ ".claude/settings.json", ".mcp.json", ] LAYOUT = "app/_layout.tsx" -LAYOUT_RE = re.compile(r"useMigrations|migrations|Logto|TokenGetter|fullSync|cleanOutbox|syncClient") +LAYOUT_RE = re.compile(r"useMigrations|migrations|Logto|TokenGetter|fullSync|cleanOutbox|syncClient|scheduleSync|SyncSubscriber") SETTINGS = "app/(tabs)/settings.tsx" SETTINGS_RE = re.compile(r"initialMerge|initialReset|setSyncEnabled|syncEnabled|logtoSign|signIn|signOut|" r"releases/latest|\.apk|tag_name|checkForUpdate") diff --git a/src/db/repository/lists.ts b/src/db/repository/lists.ts index 244f2c8..98a3f68 100644 --- a/src/db/repository/lists.ts +++ b/src/db/repository/lists.ts @@ -5,6 +5,7 @@ import { randomUUID } from '@/src/lib/uuid'; import { truncate } from '@/src/lib/validation'; import { whenSettingsHydrated } from '@/src/stores/useSettingsStore'; import { LOCAL_INBOX_ID, pickInboxId, planInboxRepair } from '@/src/services/syncRules'; +import { requestSync } from '@/src/services/syncTrigger'; import { writeOutboxEntries, writeOutboxEntry } from './outbox'; /** @@ -93,6 +94,8 @@ export async function repairInbox(): Promise { await writeOutboxEntries(tx, plan.ops); await tx.delete(lists).where(eq(lists.id, LOCAL_INBOX_ID)); }); + // After the commit: the repaired entries go out with the next sync + requestSync(); console.warn( `[inbox] repaired: ${plan.movedTaskIds.length} task(s) moved, ` + @@ -135,7 +138,7 @@ export async function createList(name: string, color?: string, icon?: string) { icon: icon ?? null, position: maxPosition + 1, isInbox: false, - }).catch(() => {}); + }).then(requestSync).catch(() => {}); return id; } @@ -148,7 +151,7 @@ export async function updateList(id: string, data: { name?: string; color?: stri .set({ ...sanitized, updatedAt: new Date() }) .where(eq(lists.id, id)); - writeOutboxEntry('list', id, 'update', { id, ...sanitized }).catch(() => {}); + writeOutboxEntry('list', id, 'update', { id, ...sanitized }).then(requestSync).catch(() => {}); } export async function reorderLists(updates: { id: string; position: number }[]) { @@ -161,5 +164,5 @@ export async function reorderLists(updates: { id: string; position: number }[]) export async function deleteList(id: string) { await db.delete(lists).where(eq(lists.id, id)); - writeOutboxEntry('list', id, 'delete', { id }).catch(() => {}); + writeOutboxEntry('list', id, 'delete', { id }).then(requestSync).catch(() => {}); } diff --git a/src/db/repository/tags.ts b/src/db/repository/tags.ts index 00edcd6..12b2f42 100644 --- a/src/db/repository/tags.ts +++ b/src/db/repository/tags.ts @@ -3,6 +3,7 @@ import { db } from '../client'; import { tags, taskTags } from '../schema'; import { randomUUID } from '@/src/lib/uuid'; import { truncate } from '@/src/lib/validation'; +import { requestSync } from '@/src/services/syncTrigger'; import { writeOutboxEntry } from './outbox'; export async function getAllTags() { @@ -20,20 +21,20 @@ export async function createTag(name: string, color: string) { updatedAt: now, }); - writeOutboxEntry('tag', id, 'create', { id, name, color }).catch(() => {}); + writeOutboxEntry('tag', id, 'create', { id, name, color }).then(requestSync).catch(() => {}); return id; } export async function updateTag(id: string, name: string, color: string) { await db.update(tags).set({ name: truncate(name, 100), color, updatedAt: new Date() }).where(eq(tags.id, id)); - writeOutboxEntry('tag', id, 'update', { id, name, color }).catch(() => {}); + writeOutboxEntry('tag', id, 'update', { id, name, color }).then(requestSync).catch(() => {}); } export async function deleteTag(id: string) { await db.delete(taskTags).where(eq(taskTags.tagId, id)); await db.delete(tags).where(eq(tags.id, id)); - writeOutboxEntry('tag', id, 'delete', { id }).catch(() => {}); + writeOutboxEntry('tag', id, 'delete', { id }).then(requestSync).catch(() => {}); } export async function getTagsForTask(taskId: string) { @@ -54,7 +55,7 @@ export async function setTagsForTask(taskId: string, tagIds: string[]) { } // Send individual taskTag create operations (server expects entityId=taskId, data.tagId) for (const tagId of tagIds) { - writeOutboxEntry('taskTag', taskId, 'create', { tagId }).catch(() => {}); + writeOutboxEntry('taskTag', taskId, 'create', { tagId }).then(requestSync).catch(() => {}); } } diff --git a/src/db/repository/tasks.ts b/src/db/repository/tasks.ts index 8d9ceec..bf0e06e 100644 --- a/src/db/repository/tasks.ts +++ b/src/db/repository/tasks.ts @@ -11,6 +11,7 @@ import { useSettingsStore } from '@/src/stores/useSettingsStore'; import { syncWidgetData } from '@/src/services/widgetSync'; import { clamp, truncate } from '@/src/lib/validation'; import { RECURRENCE_OPTIONS } from '@/src/lib/recurrence'; +import { requestSync } from '@/src/services/syncTrigger'; import { writeOutboxEntry } from './outbox'; export type { TaskFilters } from '@/src/shared/types'; @@ -183,7 +184,7 @@ export async function createTask(data: { listId: data.listId, parentId: data.parentId ?? null, recurrence: sanitizedRecurrence, - }).catch(() => {}); + }).then(requestSync).catch(() => {}); syncWidgetData().catch(() => {}); @@ -263,7 +264,7 @@ export async function updateTask( listId: task.listId, parentId: task.parentId, recurrence: task.recurrence, - }).catch(() => {}); + }).then(requestSync).catch(() => {}); } syncWidgetData().catch(() => {}); @@ -334,7 +335,7 @@ export async function deleteTask(id: string) { // Delete subtasks first const subtasks = await getSubtasks(id); for (const sub of subtasks) { - writeOutboxEntry('task', sub.id, 'delete', { id: sub.id }).catch(() => {}); + writeOutboxEntry('task', sub.id, 'delete', { id: sub.id }).then(requestSync).catch(() => {}); await db.delete(taskTags).where(eq(taskTags.taskId, sub.id)); await db.delete(tasks).where(eq(tasks.id, sub.id)); } @@ -342,7 +343,7 @@ export async function deleteTask(id: string) { await db.delete(tasks).where(eq(tasks.id, id)); // Sync outbox - writeOutboxEntry('task', id, 'delete', { id }).catch(() => {}); + writeOutboxEntry('task', id, 'delete', { id }).then(requestSync).catch(() => {}); syncWidgetData().catch(() => {}); } diff --git a/src/services/syncClient.ts b/src/services/syncClient.ts index 4230ad9..4500c70 100644 --- a/src/services/syncClient.ts +++ b/src/services/syncClient.ts @@ -23,6 +23,12 @@ import { sendInBatches, type PostResponse, } from '@/src/services/syncRules'; +import { + createSyncScheduler, + type RequestTracker, + type RunOutcome, + type SyncRun, +} from '@/src/services/syncSchedule'; const SYNC_API_BASE = 'https://liste.lacompagniemaximus.com'; const INBOX_ID = '00000000-0000-0000-0000-000000000001'; @@ -59,10 +65,16 @@ async function getAuthHeaders(): Promise> { /** * POST one batch of operations to the server sync endpoint. Retry-After is - * read in seconds; the body is parsed only on a 2xx. + * read in seconds; the body is parsed only on a 2xx. Every request and every + * 429 is reported to the scheduler (#178). */ -async function postBatch(batch: SyncOperation[], headers: Record): Promise { +async function postBatch( + batch: SyncOperation[], + headers: Record, + tracker: RequestTracker, +): Promise { try { + tracker.request(); const res = await fetch(`${SYNC_API_BASE}/api/sync`, { method: 'POST', headers, @@ -70,7 +82,9 @@ async function postBatch(batch: SyncOperation[], headers: Record }); if (!res.ok) { console.warn(`[sync] push failed with status ${res.status}`); - return { status: res.status, retryAfter: parseRetryAfter(res.headers.get('Retry-After')), body: null }; + const failed = { status: res.status, retryAfter: parseRetryAfter(res.headers.get('Retry-After')), body: null }; + if (res.status === 429) tracker.rateLimited(failed.retryAfter); + return failed; } const body = await res.json().catch(() => null); return { status: res.status, retryAfter: null, body }; @@ -85,14 +99,15 @@ function sleep(ms: number): Promise { } /** - * Push unsynced outbox entries to the server, oldest first, MAX_PUSH_BATCHES - * batches at most. Marks the entries the server holds (applied or duplicate) - * and the refusals classifyOutbox drops; the other refusals are replayed by - * the next push (#151). + * Push unsynced outbox entries to the server, oldest first, as many batches + * as the scheduler allows (run.pushBatches, MAX_PUSH_BATCHES at most, #178). + * Marks the entries the server holds (applied or duplicate) and the refusals + * classifyOutbox drops; the other refusals are replayed by the next push + * (#151). `more` is true when the budget left entries unsent. */ -export async function pushChanges(): Promise { +export async function pushChanges(run: SyncRun): Promise { const headers = await getAuthHeaders(); - if (!headers['Authorization']) return; + if (!headers['Authorization']) return {}; const unsynced = await db .select() @@ -101,7 +116,7 @@ export async function pushChanges(): Promise { // Creation order: replayed refusals go before the entries that replace them .orderBy(asc(syncOutbox.createdAt)); - if (unsynced.length === 0) return; + if (unsynced.length === 0) return {}; const operations: SyncOperation[] = unsynced.map((entry) => { const data = JSON.parse(entry.payload); @@ -114,11 +129,12 @@ export async function pushChanges(): Promise { }; }); - const { results } = await sendInBatches(operations, { + const maxBatches = Math.max(0, Math.min(run.pushBatches, MAX_PUSH_BATCHES)); + const { results, ok } = await sendInBatches(operations, { size: BATCH_SIZE, - maxBatches: MAX_PUSH_BATCHES, + maxBatches, retryOn429: false, - post: (batch) => postBatch(batch, headers), + post: (batch) => postBatch(batch, headers, run), sleep, }); @@ -135,21 +151,25 @@ export async function pushChanges(): Promise { // Refresh widget after a push that synced entries syncWidgetData().catch(() => {}); } + return { more: ok && operations.length > maxBatches * BATCH_SIZE }; } /** - * Pull changes from the server since the last sync timestamp. + * Pull changes from the server since the last sync timestamp. The GET and a + * 429 are reported to the scheduler (#178). */ -export async function pullChanges(since: string): Promise { +export async function pullChanges(since: string, tracker: RequestTracker): Promise { const headers = await getAuthHeaders(); if (!headers['Authorization']) return; try { const url = `${SYNC_API_BASE}/api/sync?since=${encodeURIComponent(since)}`; + tracker.request(); const res = await fetch(url, { method: 'GET', headers }); if (!res.ok) { console.warn(`[sync] pull failed with status ${res.status}`); + if (res.status === 429) tracker.rateLimited(parseRetryAfter(res.headers.get('Retry-After'))); return; } @@ -284,22 +304,49 @@ async function applyTaskTagChange(id: string, action: string, payload: Record { +async function fullSync(run: SyncRun): Promise { const { syncEnabled } = useSettingsStore.getState(); - if (!syncEnabled) return; + if (!syncEnabled) return {}; try { - await pushChanges(); + const outcome = await pushChanges(run); + // A 429 on the push: nothing more until its Retry-After + if (run.isSuspended()) return outcome; const since = useSettingsStore.getState().lastSyncAt ?? SYNC_EPOCH; - await pullChanges(since); + await pullChanges(since, run); + return outcome; } catch (err) { console.warn('[sync] fullSync error:', err); + return {}; } } +// One scheduler per process: launch, the 30 s interval, the return to the +// foreground, local writes and the Settings button all go through it. +const scheduler = createSyncScheduler({ + now: () => Date.now(), + setTimer: (fn, ms) => setTimeout(fn, ms), + canRun: () => useSettingsStore.getState().syncEnabled, + run: async (run) => { + const outcome = await fullSync(run); + await cleanOutbox().catch(() => {}); + return outcome; + }, +}); + +/** + * Ask the scheduler for a sync (push then pull). Resolves when the sync that + * serves the request has ended; it may wait for the request budget or the + * Retry-After of a 429. + */ +export function scheduleSync(): Promise { + return scheduler.request(); +} + /** * First-time sync: merge all local data to server. * Creates an Inbox on the server, remaps the local hardcoded Inbox ID, @@ -307,6 +354,15 @@ export async function fullSync(): Promise { * pulls the whole account from SYNC_EPOCH. */ export async function initialMerge(): Promise { + await scheduler.beginInitialSync(); + try { + await mergeLocalData(); + } finally { + scheduler.endInitialSync(); + } +} + +async function mergeLocalData(): Promise { const headers = await getAuthHeaders(); if (!headers['Authorization']) return; @@ -388,7 +444,7 @@ export async function initialMerge(): Promise { size: BATCH_SIZE, maxBatches: Infinity, retryOn429: true, - post: (batch) => postBatch(batch, headers), + post: (batch) => postBatch(batch, headers, scheduler.tracker), sleep, }); if (!ok) { @@ -419,13 +475,22 @@ export async function initialMerge(): Promise { // lastSyncAt is set to the epoch first, so that a failed pull is replayed // from the epoch by the next fullSync. useSettingsStore.getState().setLastSyncAt(SYNC_EPOCH); - await pullChanges(SYNC_EPOCH); + await pullChanges(SYNC_EPOCH, scheduler.tracker); } /** * First-time sync: discard local data and pull everything from server. */ export async function initialReset(): Promise { + await scheduler.beginInitialSync(); + try { + await resetFromServer(); + } finally { + scheduler.endInitialSync(); + } +} + +async function resetFromServer(): Promise { const headers = await getAuthHeaders(); if (!headers['Authorization']) return; @@ -437,7 +502,7 @@ export async function initialReset(): Promise { await db.delete(syncOutbox); // 2. Pull everything from server - await pullChanges(SYNC_EPOCH); + await pullChanges(SYNC_EPOCH, scheduler.tracker); // 3. An account without Inbox (the server never creates one for a new // account): create it under a new UUID and push it. Not the fixed local diff --git a/src/services/syncRules.ts b/src/services/syncRules.ts index 8e65ff6..3209a08 100644 --- a/src/services/syncRules.ts +++ b/src/services/syncRules.ts @@ -194,9 +194,10 @@ export function tagUpdatePayload(tag: TagRow): Payload { /** Operations per POST /api/sync (the server accepts 200 at most). */ export const BATCH_SIZE = 50; /** - * Batches sent by one pushChanges. The `sync` rate limit (10 requests per - * minute and per account, GET and POST together) is the budget of a whole - * fullSync: 8 POST batches leave room for its pull. + * Upper bound of the batches sent by one pushChanges. The actual count comes + * from the request budget of the scheduler (syncSchedule.ts, #178), always + * lower: the `sync` rate limit (10 requests per minute and per account, GET + * and POST together) is shared by every device of the account. */ export const MAX_PUSH_BATCHES = 8; /** Refused operations kept in the outbox for a replay, the most recent first. */ diff --git a/src/services/syncSchedule.ts b/src/services/syncSchedule.ts new file mode 100644 index 0000000..e71fc4a --- /dev/null +++ b/src/services/syncSchedule.ts @@ -0,0 +1,188 @@ +// Sync scheduler (#178): one sync at a time, a sliding budget of real HTTP +// requests, the Retry-After of a 429 and the first-sync state. Pure and +// import-free, like syncRules.ts, so that tests/syncSchedule.test.mjs loads +// it through node's type stripping (zero-import guard in smoke.test.cjs). +// The clock and the timers are injected; syncClient.ts wires the real ones. + +/** + * Real HTTP requests (each POST batch and each GET) a device sends per + * BUDGET_WINDOW_MS. The server allows 10 per minute and per account, every + * device together (web/src/lib/rateLimit.ts): 6 leave room for a second + * device and the companion (decision of Max, 2026-11-02). + */ +export const REQUEST_BUDGET = 6; +/** Length of the sliding budget window, in ms. */ +export const BUDGET_WINDOW_MS = 60_000; +/** Suspension after a 429 without a readable Retry-After, in seconds. */ +export const DEFAULT_RETRY_AFTER_S = 60; +/** Upper bound of a Retry-After, in seconds: a bogus header never stops sync for good. */ +export const MAX_RETRY_AFTER_S = 600; + +/** What a code path that sends requests to the sync server reports. */ +export interface RequestTracker { + /** Count one HTTP request, just before it is sent. */ + request(): void; + /** The server answered 429: no request until Retry-After (seconds, null when unreadable). */ + rateLimited(retryAfterS: number | null): void; +} + +/** Handed to one run of the scheduler. */ +export interface SyncRun extends RequestTracker { + /** + * POST batches this run may send: the remaining budget minus one place for + * the GET of the pull. The rest of the queue goes to the next run. + */ + readonly pushBatches: number; + /** True once a 429 suspended the scheduler: the run sends nothing more. */ + isSuspended(): boolean; +} + +export interface RunOutcome { + /** The push left entries unsent (budget): the scheduler runs again when the budget allows. */ + more?: boolean; +} + +export interface SchedulerDeps { + now(): number; + setTimer(fn: () => void, ms: number): unknown; + /** One sync (push then pull). Its errors are swallowed by the scheduler. */ + run(ctx: SyncRun): Promise; + /** + * Checked before each run: false drops the pending requests (sync off, and + * later other guards such as the account check of #165). + */ + canRun?(): boolean; +} + +export interface SyncScheduler { + /** + * Ask for a sync. Resolves when the run that serves this request ends, or + * at once when the guard drops it. A request during a run gives exactly one + * more run, after it. + */ + request(): Promise; + /** Tracker for the requests sent outside a run (initialMerge, initialReset). */ + tracker: RequestTracker; + /** + * Enter the first-sync state: no run starts until endInitialSync, the + * requests made meanwhile wait for its end. Resolves once the run in flight, + * if any, has ended. + */ + beginInitialSync(): Promise; + endInitialSync(): void; +} + +export function createSyncScheduler(deps: SchedulerDeps): SyncScheduler { + // Send times of the requests still inside the window, oldest first + let sent: number[] = []; + let suspendedUntil = 0; + let running = false; + let pending = false; + let initial = 0; + let timerArmed = false; + let waiters: (() => void)[] = []; + let idleWaiters: (() => void)[] = []; + + function remaining(now: number): number { + sent = sent.filter((t) => t > now - BUDGET_WINDOW_MS); + return REQUEST_BUDGET - sent.length; + } + + function arm(ms: number) { + timerArmed = true; + deps.setTimer(() => { + timerArmed = false; + pump(); + }, Math.max(0, ms)); + } + + function settle(list: (() => void)[]) { + for (const resolve of list) resolve(); + } + + const tracker: RequestTracker = { + request() { + sent.push(deps.now()); + }, + rateLimited(retryAfterS) { + const s = retryAfterS == null ? DEFAULT_RETRY_AFTER_S : Math.min(Math.max(retryAfterS, 0), MAX_RETRY_AFTER_S); + suspendedUntil = Math.max(suspendedUntil, deps.now() + s * 1000); + }, + }; + + function pump() { + if (running || initial > 0 || timerArmed || !pending) return; + if (deps.canRun && !deps.canRun()) { + pending = false; + const dropped = waiters; + waiters = []; + settle(dropped); + return; + } + const now = deps.now(); + if (now < suspendedUntil) { + arm(suspendedUntil - now); + return; + } + const left = remaining(now); + if (left < 1) { + // The oldest request leaves the window first + arm(sent[0] + BUDGET_WINDOW_MS - now); + return; + } + start(left); + } + + function start(left: number) { + running = true; + pending = false; + const served = waiters; + waiters = []; + const startedAt = deps.now(); + const ctx: SyncRun = { + pushBatches: left - 1, + request: tracker.request, + rateLimited: tracker.rateLimited, + isSuspended: () => deps.now() < suspendedUntil, + }; + let outcome: RunOutcome | void = undefined; + Promise.resolve() + .then(() => deps.run(ctx)) + .then( + (o) => { + outcome = o; + }, + () => {}, + ) + .then(() => { + running = false; + // Unsent queue, or a 429 in this run: go on once budget or Retry-After allow + if ((outcome && outcome.more) || suspendedUntil > startedAt) pending = true; + settle(served); + const idle = idleWaiters; + idleWaiters = []; + settle(idle); + pump(); + }); + } + + return { + request() { + return new Promise((resolve) => { + waiters.push(resolve); + pending = true; + pump(); + }); + }, + tracker, + beginInitialSync() { + initial++; + if (!running) return Promise.resolve(); + return new Promise((resolve) => idleWaiters.push(resolve)); + }, + endInitialSync() { + initial = Math.max(0, initial - 1); + pump(); + }, + }; +} diff --git a/src/services/syncTrigger.ts b/src/services/syncTrigger.ts new file mode 100644 index 0000000..5fa8c29 --- /dev/null +++ b/src/services/syncTrigger.ts @@ -0,0 +1,38 @@ +// Sync on write (#178). The repositories (lists, tasks, tags) call +// requestSync() after a local write that reached the outbox; the single +// subscriber, registered by app/_layout.tsx while sync is on, hands it to the +// scheduler. Import-free: the repositories load it without any sync or DB +// module, and without a subscriber (headless widget handler, sync off) a +// request does nothing. outbox.ts never calls it, so the outbox writes of the +// sync itself (keepLocal, initialReset) trigger nothing. + +/** Writes closer than this make one sync, sent this long after the last one. */ +export const SYNC_DEBOUNCE_MS = 2000; + +let subscriber: (() => void) | null = null; +let timer: ReturnType | null = null; + +/** Register the single subscriber, or remove it with null (pending request dropped). */ +export function setSyncSubscriber(fn: (() => void) | null): void { + subscriber = fn; + if (!fn && timer) { + clearTimeout(timer); + timer = null; + } +} + +/** Ask for a sync after a local write, debounced by SYNC_DEBOUNCE_MS. */ +export function requestSync(): void { + if (!subscriber) return; + if (timer) clearTimeout(timer); + timer = setTimeout(() => { + timer = null; + const fn = subscriber; + if (!fn) return; + try { + fn(); + } catch { + // The scheduler logs its own failures + } + }, SYNC_DEBOUNCE_MS); +} diff --git a/tests/smoke.test.cjs b/tests/smoke.test.cjs index 9c50960..b51ac94 100644 --- a/tests/smoke.test.cjs +++ b/tests/smoke.test.cjs @@ -181,6 +181,70 @@ check('syncRules.ts stays import-free (protects type-stripping test path)', () = ); }); +// The sync scheduler and the sync-on-write trigger (#178) are executed by +// tests/syncSchedule.test.mjs through node's type stripping, and the +// repositories load syncTrigger.ts: both stay free of any import (no DB, no +// sync module, no dynamic import either). +check('syncSchedule.ts and syncTrigger.ts stay import-free (#178)', () => { + for (const file of ['src/services/syncSchedule.ts', 'src/services/syncTrigger.ts']) { + assert.deepEqual(staticImportsOf(file), [], `${file} must have zero imports`); + const src = fs.readFileSync(path.join(__dirname, '..', file), 'utf8'); + assert.ok(!/\bimport\s*\(|\brequire\s*\(|^\s*import\s/m.test(src), `${file} must not import anything`); + } +}); + +// Wiring of the scheduler (#178) in files node cannot load: the repositories +// request a sync after each outbox write, the sync's own outbox writes never +// do, and every sync goes through the scheduler. +check('sync on write and every sync go through the scheduler (#178)', () => { + const read = (rel) => fs.readFileSync(path.join(__dirname, '..', rel), 'utf8'); + for (const rel of ['src/db/repository/lists.ts', 'src/db/repository/tasks.ts', 'src/db/repository/tags.ts']) { + const src = read(rel); + assert.match(src, /^import \{ requestSync \} from '@\/src\/services\/syncTrigger';$/m, `${rel} must import requestSync`); + // Every single outbox write is followed by a sync request, once written + const writes = src.match(/writeOutboxEntry\([^;]*?;/g) || []; + assert.ok(writes.length > 0, `${rel} writes no outbox entry`); + for (const w of writes) { + assert.match(w, /\)\.then\(requestSync\)\.catch\(\(\) => \{\}\);$/, `${rel}: ${w.slice(0, 60)}... must request a sync after the write`); + } + } + // repairInbox requests a sync after its transaction is committed + const lists = read('src/db/repository/lists.ts'); + const repair = lists.slice(lists.indexOf('export async function repairInbox('), lists.indexOf('function chunks(')); + const tx = repair.indexOf('await db.transaction('); + const req = repair.indexOf('requestSync();'); + assert.ok(tx >= 0 && req > repair.indexOf('\n });', tx), 'repairInbox must call requestSync() after its transaction'); + // The sync's own outbox writes (keepLocal, initialReset) never trigger a sync + for (const rel of ['src/db/repository/outbox.ts', 'src/services/syncClient.ts']) { + assert.ok(!/requestSync|syncTrigger/.test(read(rel)), `${rel} must not request a sync`); + } + // _layout.tsx: launch, interval, foreground and writes through the scheduler + const layout = read('app/_layout.tsx'); + assert.ok(!/\bfullSync\b|pushChanges|pullChanges/.test(layout), '_layout.tsx must not call fullSync directly'); + assert.match(layout, /const SYNC_INTERVAL_MS = 30 \* 1000;/); + assert.match(layout, /setInterval\(\(\) => \{\s*if \(AppState\.currentState !== 'active'\) return;\s*prepareInbox\(\)\.then\(\(\) => scheduleSync\(\)\)/); + assert.match(layout, /setSyncSubscriber\(\(\) => \{\s*scheduleSync\(\)/); + assert.match(layout, /setSyncSubscriber\(null\);/); + // Settings: « Synchroniser maintenant » through the scheduler + const settings = read('app/(tabs)/settings.tsx'); + assert.ok(!/\bfullSync\b/.test(settings), 'settings.tsx must not call fullSync directly'); + assert.match(settings, /await scheduleSync\(\);/); + // syncClient.ts: fullSync is private, every request and 429 is reported + const client = read('src/services/syncClient.ts'); + assert.ok(!/export async function fullSync/.test(client), 'fullSync must stay private to the scheduler'); + assert.match(client, /tracker\.request\(\);\s*const res = await fetch\(`\$\{SYNC_API_BASE\}\/api\/sync`, \{/, 'postBatch must count its request'); + assert.match(client, /tracker\.request\(\);\s*const res = await fetch\(url, \{ method: 'GET', headers \}\);/, 'pullChanges must count its request'); + assert.equal((client.match(/if \(res\.status === 429\) tracker\.rateLimited\(/g) || []).length, 2, 'push and pull must report a 429'); + assert.match(client, /if \(run\.isSuspended\(\)\) return outcome;\s*const since/, 'no pull after a 429 on the push'); + for (const name of ['initialMerge', 'initialReset']) { + const start = client.indexOf(`export async function ${name}(`); + assert.ok(start >= 0, `${name} not found`); + const body = client.slice(start, client.indexOf('\n}\n', start)); + assert.match(body, /await scheduler\.beginInitialSync\(\);\s*try \{[^]*\} finally \{\s*scheduler\.endInitialSync\(\);/, `${name} must hold the first-sync state`); + } + assert.equal((client.match(/pullChanges\(SYNC_EPOCH, scheduler\.tracker\)/g) || []).length, 2, 'the first-sync pulls are counted'); +}); + // Tags must not go through keepLocal: the server's tag updated_at is its // created_at (no updatedAt column), so a local rename would always look newer // (PR #157 review). syncClient.ts cannot load under node, hence a source check. @@ -195,9 +259,10 @@ check('applyTagChange never keeps a local tag (no keepLocal)', () => { // The push bounds of #151 are executed by tests/syncRules.test.mjs, but the // options each caller passes to sendInBatches live in syncClient.ts, which -// node cannot load. Lock them by source: pushChanges sends 8 batches at most -// and never waits on a 429 (the rate limit is the budget of a fullSync), -// initialMerge sends every batch and waits for the Retry-After. +// node cannot load. Lock them by source: pushChanges sends the batches the +// scheduler allows, 8 at most, and never waits on a 429 (the scheduler is +// suspended instead, #178), initialMerge sends every batch and waits for the +// Retry-After. check('syncClient.ts passes the #151 push bounds to sendInBatches', () => { const src = fs.readFileSync(path.join(__dirname, '..', 'src/services/syncClient.ts'), 'utf8'); const body = (name) => { @@ -212,10 +277,13 @@ check('syncClient.ts passes the #151 push bounds to sendInBatches', () => { return m[0]; }; const push = call('pushChanges'); - assert.match(push, /maxBatches: MAX_PUSH_BATCHES,/); + // #178: the scheduler's budget, MAX_PUSH_BATCHES as a ceiling + assert.match(body('pushChanges'), /const maxBatches = Math\.max\(0, Math\.min\(run\.pushBatches, MAX_PUSH_BATCHES\)\);/); + assert.match(push, /\n\s*maxBatches,\n/); assert.match(push, /retryOn429: false,/); assert.match(push, /size: BATCH_SIZE,/); const merge = call('initialMerge'); + assert.match(body('initialMerge'), /await mergeLocalData\(\);/); assert.match(merge, /maxBatches: Infinity,/); assert.match(merge, /retryOn429: true,/); assert.match(merge, /size: BATCH_SIZE,/); @@ -262,14 +330,15 @@ check('syncClient.ts wires the #149-#151 sync rules', () => { assert.match(tag, /pulledTagValues\(id, payload, local\)/); assert.ok(!/\bkeepLocal\b|writeOutboxEntry|updated_at/.test(tag), 'applyTagChange must never keep a local tag'); // #150: lastSyncAt goes back to SYNC_EPOCH before the full pull, never after - const merge = fn('initialMerge'); + const merge = fn('mergeLocalData'); const stamp = merge.indexOf('setLastSyncAt(SYNC_EPOCH)'); - const pull = merge.indexOf('await pullChanges(SYNC_EPOCH)'); + const pull = merge.indexOf('await pullChanges(SYNC_EPOCH, scheduler.tracker)'); assert.ok(stamp >= 0 && pull >= 0 && stamp < pull, 'initialMerge: setLastSyncAt(SYNC_EPOCH) then await pullChanges(SYNC_EPOCH)'); assert.ok(!/setLastSyncAt\(new Date\(/.test(merge), 'initialMerge must not stamp the device time'); // #151: the push marks the batches that succeeded even when a later one failed const push = fn('pushChanges'); - assert.match(push, /const \{ results \} = await sendInBatches\(/); + // #178: `ok` only tells whether the budget left entries unsent, after the marking + assert.match(push, /const \{ results, ok \} = await sendInBatches\(/); const between = push.slice(push.indexOf('await sendInBatches('), push.indexOf('classifyOutbox(unsynced, results,')); assert.ok(!/\breturn\b|results\.length|\bok\b/.test(between), 'pushChanges must classify the results of every successful batch'); assert.match(push, /\.where\(inArray\(syncOutbox\.id, markIds\)\);\s*\/\/[^\n]*\s*syncWidgetData\(\)/); @@ -354,8 +423,10 @@ check('lists.ts and _layout.tsx wire the #152 Inbox rules', () => { assert.ok(r >= 0 && e > r, '_layout.tsx must call repairInbox() before ensureInbox()'); assert.match(layout.slice(r, e), /\.catch\(/, 'a failed repair must not stop the startup'); assert.match(layout, /if \(!inboxSetup\) \{\s*inboxSetup = repairInbox\(\)/, 'the Inbox setup runs once per process'); - assert.match(layout, /prepareInbox\(\)\.then\(\(\) => fullSync\(\)\)/, 'the first sync must wait for the Inbox setup'); - assert.ok(!/\n\s*fullSync\(\)\.then\(\(\) => cleanOutbox\(\)\)\.catch\(\(\) => \{\}\);\n\n\s*\/\/ 2-minute/.test(layout), 'no ungated initial sync'); + // #178: the first sync and the sync on write wait for the Inbox setup + assert.match(layout, /prepareInbox\(\)\.then\(\(\) => \{\s*if \(!active\) return;\s*setSyncSubscriber\([^]*?return scheduleSync\(\);/, 'the first sync must wait for the Inbox setup'); + const content = layout.slice(layout.indexOf('function AppContent(')); + assert.equal((content.match(/scheduleSync\(\)/g) || []).length, (content.match(/prepareInbox\(\)\.then\(/g) || []).length + 1, 'no ungated sync'); // initialReset on an account without Inbox pushes a new one, never the fixed id const client = read('src/services/syncClient.ts'); const reset = client.slice(client.indexOf('export async function initialReset('), client.indexOf('export async function cleanOutbox(')); diff --git a/tests/syncSchedule.test.mjs b/tests/syncSchedule.test.mjs new file mode 100644 index 0000000..0a3af67 --- /dev/null +++ b/tests/syncSchedule.test.mjs @@ -0,0 +1,338 @@ +// Execution tests for the sync scheduler and the sync-on-write trigger (#178). +// Runs on plain node via the built-in test runner + native TS type-stripping: +// +// node --test tests/syncSchedule.test.mjs +// +// syncSchedule.ts and syncTrigger.ts stay import-free so that node loads them +// (zero-import guards in smoke.test.cjs). The scheduler gets a fake clock; +// the trigger runs on node's mocked timers. + +import { test, mock } from 'node:test'; +import assert from 'node:assert/strict'; +import { + BUDGET_WINDOW_MS, + DEFAULT_RETRY_AFTER_S, + REQUEST_BUDGET, + createSyncScheduler, +} from '../src/services/syncSchedule.ts'; +import { SYNC_DEBOUNCE_MS, requestSync, setSyncSubscriber } from '../src/services/syncTrigger.ts'; + +// Fake clock: timers fire in time order when the clock advances. +function fakeClock() { + let now = 0; + let timers = []; + return { + now: () => now, + setTimer: (fn, ms) => { + timers.push({ at: now + ms, fn }); + }, + pending: () => timers.length, + async advance(ms) { + const end = now + ms; + for (;;) { + await flush(); + timers.sort((a, b) => a.at - b.at); + const next = timers[0]; + if (!next || next.at > end) break; + timers.shift(); + now = next.at; + next.fn(); + } + now = end; + await flush(); + }, + }; +} + +async function flush() { + for (let i = 0; i < 20; i++) await Promise.resolve(); +} + +// A server stand-in: a queue of POST batches, each run pushes up to +// ctx.pushBatches of them then pulls once. Records every request time. +function fakeServer(clock, { batches = 0, status = () => 200, duration = 0 } = {}) { + const state = { queue: batches, requests: [], runs: 0, active: 0, maxActive: 0, starts: [] }; + state.run = async (ctx) => { + state.runs++; + state.starts.push(clock.now()); + state.active++; + state.maxActive = Math.max(state.maxActive, state.active); + try { + if (duration) await new Promise((resolve) => clock.setTimer(resolve, duration)); + let sent = 0; + while (state.queue > 0 && sent < ctx.pushBatches) { + ctx.request(); + state.requests.push(clock.now()); + sent++; + const s = status('POST'); + if (s === 429) { + ctx.rateLimited(20); + return { more: true }; + } + state.queue--; + } + if (ctx.isSuspended()) return { more: state.queue > 0 }; + ctx.request(); + state.requests.push(clock.now()); + const s = status('GET'); + if (s === 429) ctx.rateLimited(20); + return { more: state.queue > 0 }; + } finally { + state.active--; + } + }; + return state; +} + +function maxInAnyWindow(times) { + let max = 0; + for (const t of times) { + const n = times.filter((u) => u >= t && u < t + BUDGET_WINDOW_MS).length; + max = Math.max(max, n); + } + return max; +} + +test('a burst of 10 requestSync() in 2 s gives a single sync', () => { + mock.timers.enable({ apis: ['setTimeout'] }); + try { + let syncs = 0; + setSyncSubscriber(() => { + syncs++; + }); + for (let i = 0; i < 10; i++) { + requestSync(); + mock.timers.tick(200); + } + assert.equal(syncs, 0, 'nothing before the debounce delay'); + mock.timers.tick(SYNC_DEBOUNCE_MS); + assert.equal(syncs, 1); + mock.timers.tick(10 * SYNC_DEBOUNCE_MS); + assert.equal(syncs, 1); + } finally { + setSyncSubscriber(null); + mock.timers.reset(); + } +}); + +test('requestSync without a subscriber does nothing (headless widget, sync off)', () => { + mock.timers.enable({ apis: ['setTimeout'] }); + try { + let syncs = 0; + requestSync(); + setSyncSubscriber(() => { + syncs++; + }); + mock.timers.tick(10 * SYNC_DEBOUNCE_MS); + assert.equal(syncs, 0, 'a request made before the subscription is not kept'); + requestSync(); + setSyncSubscriber(null); + mock.timers.tick(10 * SYNC_DEBOUNCE_MS); + assert.equal(syncs, 0, 'removing the subscriber drops the pending request'); + } finally { + setSyncSubscriber(null); + mock.timers.reset(); + } +}); + +test('never two syncs at once; a request during a sync gives exactly one more run', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { duration: 1000 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.request(); + await flush(); + assert.equal(server.runs, 1); + // Three requests while the first run is in flight + s.request(); + s.request(); + s.request(); + await clock.advance(500); + assert.equal(server.runs, 1, 'no second run while the first one is in flight'); + await clock.advance(10_000); + assert.equal(server.runs, 2, 'exactly one relaunch'); + assert.equal(server.maxActive, 1); + await clock.advance(120_000); + assert.equal(server.runs, 2, 'no run without a request'); +}); + +test('request() resolves when the run that serves it ends', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { duration: 1000 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + let first = false; + let second = false; + s.request().then(() => (first = true)); + await flush(); + s.request().then(() => (second = true)); + await clock.advance(1000); + assert.equal(first, true); + assert.equal(second, false, 'a request made during a run waits for the next one'); + await clock.advance(1000); + assert.equal(second, true); +}); + +test('at most REQUEST_BUDGET requests in any 60 s window; 9 batches spread over several syncs', async () => { + assert.equal(REQUEST_BUDGET, 6); + const clock = fakeClock(); + const server = fakeServer(clock, { batches: 9 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.request(); + await clock.advance(1000); + assert.equal(server.runs, 1); + assert.equal(server.queue, 4, 'the first sync sends 5 batches and keeps a place for its GET'); + // Requests keep coming every 5 s (writes, interval) + for (let i = 0; i < 60; i++) { + s.request(); + await clock.advance(5000); + } + assert.equal(server.queue, 0, 'the rest of the queue left with later syncs'); + assert.ok(server.runs >= 2); + assert.ok(maxInAnyWindow(server.requests) <= REQUEST_BUDGET, `max ${maxInAnyWindow(server.requests)} in a window`); +}); + +test('an unsent queue is resumed without a new request once the budget allows', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { batches: 9 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.request(); + await clock.advance(BUDGET_WINDOW_MS - 1); + assert.equal(server.runs, 1, 'the second run waits for the window'); + await clock.advance(2); + assert.equal(server.runs, 2); + assert.equal(server.queue, 0); + assert.ok(maxInAnyWindow(server.requests) <= REQUEST_BUDGET); +}); + +test('after a 429 with Retry-After: 20, no request before 20 s', async () => { + const clock = fakeClock(); + let first = true; + const server = fakeServer(clock, { + batches: 2, + status: () => { + if (first) { + first = false; + return 429; + } + return 200; + }, + }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.request(); + await flush(); + assert.deepEqual(server.requests, [0], 'the run stops at the 429, no pull after it'); + for (let t = 1000; t < 20_000; t += 1000) { + s.request(); + await clock.advance(1000); + } + assert.ok(server.requests.every((t) => t === 0 || t >= 20_000), `requests at ${server.requests}`); + await clock.advance(2000); + assert.ok(server.requests.some((t) => t >= 20_000), 'the scheduler resumes after Retry-After'); + assert.equal(server.queue, 0); +}); + +test('a 429 without a readable Retry-After suspends for the default delay', async () => { + const clock = fakeClock(); + let starts = 0; + const s = createSyncScheduler({ + now: clock.now, + setTimer: clock.setTimer, + run: async (ctx) => { + starts++; + ctx.request(); + ctx.rateLimited(null); + }, + }); + s.request(); + await clock.advance(DEFAULT_RETRY_AFTER_S * 1000 - 1); + assert.equal(starts, 1); + await clock.advance(1); + assert.equal(starts, 2); +}); + +test('a 429 reported outside a run (initial sync) also suspends the scheduler', async () => { + const clock = fakeClock(); + const server = fakeServer(clock); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.tracker.request(); + s.tracker.rateLimited(20); + s.request(); + await clock.advance(19_999); + assert.equal(server.runs, 0); + await clock.advance(1); + assert.equal(server.runs, 1); +}); + +test('requests sent outside a run (initial sync) count against the budget', async () => { + const clock = fakeClock(); + const server = fakeServer(clock); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + for (let i = 0; i < REQUEST_BUDGET; i++) s.tracker.request(); + s.request(); + await clock.advance(BUDGET_WINDOW_MS - 1); + assert.equal(server.runs, 0); + await clock.advance(1); + assert.equal(server.runs, 1); +}); + +test('a request during the first-sync state runs after its end, not before', async () => { + const clock = fakeClock(); + const server = fakeServer(clock); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + await s.beginInitialSync(); + let done = false; + s.request().then(() => (done = true)); + await clock.advance(5 * BUDGET_WINDOW_MS); + assert.equal(server.runs, 0, 'no sync during initialMerge / initialReset'); + assert.equal(done, false); + s.endInitialSync(); + await flush(); + assert.equal(server.runs, 1); + assert.equal(done, true); +}); + +test('beginInitialSync waits for the run in flight', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { duration: 1000 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.request(); + await flush(); + let entered = false; + s.beginInitialSync().then(() => (entered = true)); + await flush(); + assert.equal(entered, false); + await clock.advance(1000); + assert.equal(entered, true); + s.endInitialSync(); +}); + +test('the guard drops requests and resolves them', async () => { + const clock = fakeClock(); + const server = fakeServer(clock); + let allowed = false; + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run, canRun: () => allowed }); + let done = false; + s.request().then(() => (done = true)); + await clock.advance(BUDGET_WINDOW_MS); + assert.equal(server.runs, 0); + assert.equal(done, true); + allowed = true; + s.request(); + await flush(); + assert.equal(server.runs, 1); +}); + +test('a failing run releases the scheduler', async () => { + const clock = fakeClock(); + let runs = 0; + const s = createSyncScheduler({ + now: clock.now, + setTimer: clock.setTimer, + run: async () => { + runs++; + throw new Error('boom'); + }, + }); + await s.request(); + await s.request(); + assert.equal(runs, 2); +}); -- 2.52.0 From 38bcf8b8937230e2e1bb5fd25d9709787ec46c2c Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 21:06:10 -0500 Subject: [PATCH 03/18] fix(sync): no merge across accounts, sync off until the first-sync choice MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #165 A device holding another account's data (dataOwnerId, persisted, kept at sign-out) only offers « Charger ce compte » (initialReset) or « Annuler » (sign-out, data untouched), at sign-in and on « Synchroniser ». The rule lives in syncRules.ts (firstSyncChoice). Sync stays off until initialMerge or initialReset has succeeded, and the scheduler refuses every sync while the local data belong to another account (canSync): the outbox of the old account is never pushed under the new one. The sync's own outbox writes (kept rows, the Inbox of initialReset) no longer depend on syncEnabled, and the token getter follows the session, so that the first sync runs with sync still off. Sign-out pushes the outbox first (10 s at most, in the first-sync state of the scheduler, one request reserved outside its budget) and warns with the number of changes still unsent. Co-Authored-By: Claude Opus 5.5 --- app/(tabs)/settings.tsx | 200 ++++++++++++++++++++------------- app/_layout.tsx | 8 +- src/db/repository/outbox.ts | 14 +++ src/i18n/en.json | 7 +- src/i18n/fr.json | 7 +- src/services/syncClient.ts | 70 +++++++++--- src/services/syncRules.ts | 34 ++++++ src/services/syncSchedule.ts | 42 ++++++- src/stores/useSettingsStore.ts | 7 ++ tests/smoke.test.cjs | 85 +++++++++++++- tests/syncRules.test.mjs | 44 ++++++++ tests/syncSchedule.test.mjs | 91 +++++++++++++++ 12 files changed, 505 insertions(+), 104 deletions(-) diff --git a/app/(tabs)/settings.tsx b/app/(tabs)/settings.tsx index 7ea22e1..3644515 100644 --- a/app/(tabs)/settings.tsx +++ b/app/(tabs)/settings.tsx @@ -12,7 +12,9 @@ import { redirectUri, postSignOutRedirectUri } from '@/src/lib/logtoConfig'; import { getAllTags, createTag, updateTag, deleteTag } from '@/src/db/repository/tags'; import { initCalendar } from '@/src/services/calendar'; import { syncWidgetData } from '@/src/services/widgetSync'; -import { scheduleSync, initialMerge, initialReset } from '@/src/services/syncClient'; +import { scheduleSync, initialMerge, initialReset, pushBeforeSignOut } from '@/src/services/syncClient'; +import { firstSyncChoice } from '@/src/services/syncRules'; +import { getInboxId } from '@/src/db/repository/lists'; import i18n from '@/src/i18n'; import FeedbackModal from '@/src/components/FeedbackModal'; @@ -104,54 +106,109 @@ export default function SettingsScreen() { ]); }; + // First sync (#165): sync stays off until initialMerge or initialReset has + // succeeded. Switched on before the choice, it would push the outbox left + // by another account under the account just signed in. + const runFirstSync = async (kind: 'merge' | 'reset') => { + const accountId = useSettingsStore.getState().userId; + if (!accountId) return; + setIsSyncing(true); + try { + if (kind === 'merge') { + await initialMerge(accountId); + } else { + await initialReset(accountId); + } + setSyncEnabled(true); + Alert.alert(t('sync.firstSyncTitle'), t(kind === 'merge' ? 'sync.mergeDone' : 'sync.resetDone')); + } catch { + Alert.alert(t('sync.syncError')); + } finally { + setIsSyncing(false); + } + }; + + // Sign out of Logto and forget the account. Local data and dataOwnerId stay + // on the device: nothing is pushed nor deleted here. + const finishSignOut = async () => { + try { + await logtoSignOut(postSignOutRedirectUri); + } catch { + // Sign-out may fail if session expired, that's OK + } + setSyncEnabled(false); + setUserId(null); + setLastSyncAt(null); + }; + + // The first-sync choice, at sign-in and on « Synchroniser » before the + // first sync. A device holding another account's data only offers to load + // the signed-in account; « Annuler » signs out (#165). + const offerFirstSync = async () => { + const { dataOwnerId, userId: signedInId } = useSettingsStore.getState(); + if (!signedInId) return; + const localInboxId = await getInboxId(); + const choice = firstSyncChoice({ dataOwnerId, signedInId, localInboxId }); + + if (choice === 'reset-only') { + Alert.alert( + t('sync.firstSyncTitle'), + t('sync.accountSwitchMessage'), + [ + { + text: t('common.cancel'), + style: 'cancel', + onPress: () => { + finishSignOut(); + }, + }, + { + text: t('sync.loadAccount'), + style: 'destructive', + onPress: () => { + runFirstSync('reset'); + }, + }, + ], + { cancelable: false }, + ); + return; + } + + Alert.alert( + t('sync.firstSyncTitle'), + t('sync.firstSyncMessage'), + [ + { + text: t('sync.mergeLocal'), + onPress: () => { + runFirstSync('merge'); + }, + }, + { + text: t('sync.resetFromServer'), + style: 'destructive', + onPress: () => { + runFirstSync('reset'); + }, + }, + ], + ); + }; + const handleSignIn = async () => { try { await logtoSignIn({ redirectUri }); const claims = await getIdTokenClaims(); setUserId(claims.sub); - setSyncEnabled(true); - - // First sync: show merge/reset choice - Alert.alert( - t('sync.firstSyncTitle'), - t('sync.firstSyncMessage'), - [ - { - text: t('sync.mergeLocal'), - onPress: async () => { - setIsSyncing(true); - try { - await initialMerge(); - Alert.alert(t('sync.firstSyncTitle'), t('sync.mergeDone')); - } catch { - Alert.alert(t('sync.syncError')); - } finally { - setIsSyncing(false); - } - }, - }, - { - text: t('sync.resetFromServer'), - style: 'destructive', - onPress: async () => { - setIsSyncing(true); - try { - await initialReset(); - Alert.alert(t('sync.firstSyncTitle'), t('sync.resetDone')); - } catch { - Alert.alert(t('sync.syncError')); - } finally { - setIsSyncing(false); - } - }, - }, - ], - ); + await offerFirstSync(); } catch (err) { console.warn('[auth] sign-in error:', err); } }; + // Sign-out pushes the pending changes to the account first (#165). Those + // still unsent (offline) are counted, and the user may cancel. const handleSignOut = () => { Alert.alert(t('sync.signOutConfirm'), '', [ { text: t('common.cancel'), style: 'cancel' }, @@ -159,57 +216,38 @@ export default function SettingsScreen() { text: t('sync.signOut'), style: 'destructive', onPress: async () => { + setIsSyncing(true); + let unsent = 0; try { - await logtoSignOut(postSignOutRedirectUri); + unsent = await pushBeforeSignOut(); } catch { - // Sign-out may fail if session expired, that's OK + // Counted as nothing unsent: the push logs its own errors + } finally { + setIsSyncing(false); } - setSyncEnabled(false); - setUserId(null); - setLastSyncAt(null); + if (unsent > 0) { + Alert.alert(t('sync.unsentWarning', { count: unsent }), '', [ + { text: t('common.cancel'), style: 'cancel' }, + { + text: t('sync.signOutAnyway'), + style: 'destructive', + onPress: () => { + finishSignOut(); + }, + }, + ]); + return; + } + await finishSignOut(); }, }, ]); }; const handleSyncNow = async () => { - // If never synced before, show first-sync choice - if (!lastSyncAt) { - Alert.alert( - t('sync.firstSyncTitle'), - t('sync.firstSyncMessage'), - [ - { - text: t('sync.mergeLocal'), - onPress: async () => { - setIsSyncing(true); - try { - await initialMerge(); - Alert.alert(t('sync.firstSyncTitle'), t('sync.mergeDone')); - } catch { - Alert.alert(t('sync.syncError')); - } finally { - setIsSyncing(false); - } - }, - }, - { - text: t('sync.resetFromServer'), - style: 'destructive', - onPress: async () => { - setIsSyncing(true); - try { - await initialReset(); - Alert.alert(t('sync.firstSyncTitle'), t('sync.resetDone')); - } catch { - Alert.alert(t('sync.syncError')); - } finally { - setIsSyncing(false); - } - }, - }, - ], - ); + // First sync not done yet (sync still off): offer the choice + if (!syncEnabled || !lastSyncAt) { + await offerFirstSync(); return; } diff --git a/app/_layout.tsx b/app/_layout.tsx index f0bbc74..b7ac5fb 100644 --- a/app/_layout.tsx +++ b/app/_layout.tsx @@ -114,15 +114,17 @@ function AppContent() { const appState = useRef(AppState.currentState); const { getAccessToken, isAuthenticated } = useLogto(); - // Register the token getter for syncClient when authenticated + // Register the token getter for syncClient when authenticated, sync on or + // off: the first sync (initialMerge, initialReset) runs before sync is + // switched on (#165). Scheduled syncs stay behind canSync (syncEnabled). useEffect(() => { - if (isAuthenticated && syncEnabled) { + if (isAuthenticated) { setTokenGetter(getAccessToken); } else { clearTokenGetter(); } return () => clearTokenGetter(); - }, [isAuthenticated, syncEnabled, getAccessToken]); + }, [isAuthenticated, getAccessToken]); // Sync (#178): on launch, every 30 s in the foreground, on return from // background and after a local write, always through the scheduler (one diff --git a/src/db/repository/outbox.ts b/src/db/repository/outbox.ts index 162f84f..d00303b 100644 --- a/src/db/repository/outbox.ts +++ b/src/db/repository/outbox.ts @@ -18,7 +18,21 @@ export async function writeOutboxEntry( ): Promise { const { syncEnabled } = useSettingsStore.getState(); if (!syncEnabled) return; + await queueOutboxEntry(entityType, entityId, action, payload); +} +/** + * Write an entry to the sync outbox whatever the setting: for the sync's own + * writes (a newer local row kept by the pull, the Inbox created by + * initialReset). The first sync runs while sync is still off (#165), and + * these entries must reach the server once it is switched on. + */ +export async function queueOutboxEntry( + entityType: EntityType, + entityId: string, + action: Action, + payload: Record +): Promise { await db.insert(syncOutbox).values({ id: randomUUID(), entityType, diff --git a/src/i18n/en.json b/src/i18n/en.json index 93df87d..413bbad 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -167,7 +167,12 @@ "merging": "Merging...", "mergeDone": "Tasks merged successfully!", "resetDone": "Data synced from server.", - "syncError": "Sync error" + "syncError": "Sync error", + "accountSwitchMessage": "This phone holds the data of another account. They stay on that other account; they will be removed from the phone to load the data of this account. What was created on this phone since signing out will be removed too.", + "loadAccount": "Load this account", + "unsentWarning_one": "{{count}} change has not been sent yet. It will be lost if you switch accounts.", + "unsentWarning_other": "{{count}} changes have not been sent yet. They will be lost if you switch accounts.", + "signOutAnyway": "Sign out anyway" }, "widget": { "title": "Simpl-Liste", diff --git a/src/i18n/fr.json b/src/i18n/fr.json index ac6d78e..8295ead 100644 --- a/src/i18n/fr.json +++ b/src/i18n/fr.json @@ -167,7 +167,12 @@ "merging": "Fusion en cours...", "mergeDone": "Tâches fusionnées avec succès !", "resetDone": "Données synchronisées depuis le serveur.", - "syncError": "Erreur de synchronisation" + "syncError": "Erreur de synchronisation", + "accountSwitchMessage": "Ce téléphone contient les données d'un autre compte. Elles restent sur cet autre compte ; elles vont être retirées du téléphone pour charger celles de ce compte. Ce qui a été créé sur ce téléphone depuis la déconnexion sera aussi retiré.", + "loadAccount": "Charger ce compte", + "unsentWarning_one": "{{count}} modification n'est pas encore envoyée. Elle sera perdue si vous changez de compte.", + "unsentWarning_other": "{{count}} modifications ne sont pas encore envoyées. Elles seront perdues si vous changez de compte.", + "signOutAnyway": "Se déconnecter quand même" }, "widget": { "title": "Simpl-Liste", diff --git a/src/services/syncClient.ts b/src/services/syncClient.ts index 4500c70..c2df178 100644 --- a/src/services/syncClient.ts +++ b/src/services/syncClient.ts @@ -5,7 +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 { writeOutboxEntry } from '@/src/db/repository/outbox'; +import { queueOutboxEntry } from '@/src/db/repository/outbox'; import { SYNC_EPOCH, keepLocal, @@ -24,6 +24,7 @@ import { type PostResponse, } from '@/src/services/syncRules'; import { + canSync, createSyncScheduler, type RequestTracker, type RunOutcome, @@ -227,7 +228,7 @@ async function applyListChange(id: string, action: string, payload: Record { } // One scheduler per process: launch, the 30 s interval, the return to the -// foreground, local writes and the Settings button all go through it. +// foreground, local writes and the Settings button all go through it. No run +// while sync is off or the local data belong to another account (#165). const scheduler = createSyncScheduler({ now: () => Date.now(), setTimer: (fn, ms) => setTimeout(fn, ms), - canRun: () => useSettingsStore.getState().syncEnabled, + canRun: () => canSync(useSettingsStore.getState()), run: async (run) => { const outcome = await fullSync(run); await cleanOutbox().catch(() => {}); @@ -347,16 +349,52 @@ export function scheduleSync(): Promise { return scheduler.request(); } +/** Wait for the sign-out push, in ms (#165). */ +const SIGN_OUT_PUSH_TIMEOUT_MS = 10_000; + +/** + * Last push before sign-out (#165): the pending outbox goes to the account + * still signed in. Held in the first-sync state of the scheduler, so never + * alongside a sync, with a request reserved outside its budget. Waits + * SIGN_OUT_PUSH_TIMEOUT_MS at most (a push still in flight goes on, the + * first-sync state ends with it). Pushes nothing when the scheduler could + * not run (sync off, data of another account). Returns the number of outbox + * entries still unsent. + */ +export async function pushBeforeSignOut(): Promise { + if (canSync(useSettingsStore.getState())) { + const push = (async () => { + await scheduler.beginInitialSync(); + try { + await pushChanges(scheduler.reserve()); + } catch (err) { + console.warn('[sync] sign-out push error:', err); + } finally { + scheduler.endInitialSync(); + } + })(); + await Promise.race([push, sleep(SIGN_OUT_PUSH_TIMEOUT_MS)]); + } + const unsent = await db + .select({ id: syncOutbox.id }) + .from(syncOutbox) + .where(isNull(syncOutbox.syncedAt)); + return unsent.length; +} + /** * First-time sync: merge all local data to server. * Creates an Inbox on the server, remaps the local hardcoded Inbox ID, * then pushes all lists, tasks, tags, and task-tag relations, and finally - * pulls the whole account from SYNC_EPOCH. + * pulls the whole account from SYNC_EPOCH. Runs while sync is still off + * (#165): `accountId` (the signed-in `sub`) becomes the owner of the local + * data once done. Throws when it could not run, so that sync stays off. */ -export async function initialMerge(): Promise { +export async function initialMerge(accountId: string): Promise { await scheduler.beginInitialSync(); try { await mergeLocalData(); + useSettingsStore.getState().setDataOwnerId(accountId); } finally { scheduler.endInitialSync(); } @@ -364,7 +402,7 @@ export async function initialMerge(): Promise { async function mergeLocalData(): Promise { const headers = await getAuthHeaders(); - if (!headers['Authorization']) return; + if (!headers['Authorization']) throw new Error('Not signed in'); const operations: SyncOperation[] = []; @@ -479,12 +517,17 @@ async function mergeLocalData(): Promise { } /** - * First-time sync: discard local data and pull everything from server. + * First-time sync: discard local data and pull everything from server. Also + * « Charger ce compte » on a device holding another account's data (#165): + * the outbox of that account is deleted with the rest. Runs while sync is + * still off: `accountId` (the signed-in `sub`) becomes the owner of the local + * data once done. Throws when it could not run, so that sync stays off. */ -export async function initialReset(): Promise { +export async function initialReset(accountId: string): Promise { await scheduler.beginInitialSync(); try { await resetFromServer(); + useSettingsStore.getState().setDataOwnerId(accountId); } finally { scheduler.endInitialSync(); } @@ -492,14 +535,15 @@ export async function initialReset(): Promise { async function resetFromServer(): Promise { const headers = await getAuthHeaders(); - if (!headers['Authorization']) return; + if (!headers['Authorization']) throw new Error('Not signed in'); - // 1. Delete all local data + // 1. Delete all local data: the device holds nobody's data any more await db.delete(taskTags); await db.delete(tasks); await db.delete(tags); await db.delete(lists); await db.delete(syncOutbox); + useSettingsStore.getState().setDataOwnerId(null); // 2. Pull everything from server await pullChanges(SYNC_EPOCH, scheduler.tracker); @@ -514,7 +558,7 @@ async function resetFromServer(): Promise { const now = new Date(); const inbox = { id, name: 'Inbox', color: null, icon: null, position: 0, isInbox: true }; await db.insert(lists).values({ ...inbox, createdAt: now, updatedAt: now }); - await writeOutboxEntry('list', id, 'create', inbox); + await queueOutboxEntry('list', id, 'create', inbox); } } diff --git a/src/services/syncRules.ts b/src/services/syncRules.ts index 3209a08..a90bf22 100644 --- a/src/services/syncRules.ts +++ b/src/services/syncRules.ts @@ -561,3 +561,37 @@ export function planInboxRepair( return { inboxId, movedTaskIds: moved.map((t) => t.id), ops, rewrites, discardIds }; } + +// --------------------------------------------------------------------------- +// First sync after a sign-in: no merge across accounts (#165) +// --------------------------------------------------------------------------- + +/** + * Choice offered by the first sync: `merge-or-reset` (Fusionner / Remplacer) + * or `reset-only` (« Charger ce compte » alone, which empties the device). + */ +export type FirstSyncChoice = 'merge-or-reset' | 'reset-only'; + +export interface FirstSyncInput { + /** Account the local data come from (settings store), null when unknown. */ + dataOwnerId: string | null; + /** `sub` of the account just signed in. */ + signedInId: string; + /** Id of the local Inbox (pickInboxId), null when there is none. */ + localInboxId: string | null; +} + +/** + * The server refuses every local row of another account (ids taken, lists + * not owned), so a device holding another account's data only offers to load + * the new one: nothing passes from one account to the other (decision of Max, + * 2026-10-25). A known owner decides alone. An unknown owner (device signed + * out before #165) is told by the Inbox: the fixed id means the device has + * never synced, a server id means it has, under an account that may be + * another one, so it is treated as one. + */ +export function firstSyncChoice({ dataOwnerId, signedInId, localInboxId }: FirstSyncInput): FirstSyncChoice { + if (dataOwnerId !== null) return dataOwnerId === signedInId ? 'merge-or-reset' : 'reset-only'; + if (localInboxId === null || localInboxId === LOCAL_INBOX_ID) return 'merge-or-reset'; + return 'reset-only'; +} diff --git a/src/services/syncSchedule.ts b/src/services/syncSchedule.ts index e71fc4a..a5eef92 100644 --- a/src/services/syncSchedule.ts +++ b/src/services/syncSchedule.ts @@ -48,12 +48,33 @@ export interface SchedulerDeps { /** One sync (push then pull). Its errors are swallowed by the scheduler. */ run(ctx: SyncRun): Promise; /** - * Checked before each run: false drops the pending requests (sync off, and - * later other guards such as the account check of #165). + * Checked before each run: false drops the pending requests (canSync: sync + * off, or local data of another account, #165). */ canRun?(): boolean; } +/** Settings read by canSync (#165). */ +export interface SyncGuardState { + syncEnabled: boolean; + /** Account the local data come from, null when unknown. */ + dataOwnerId: string | null; + /** `sub` of the signed-in account. */ + userId: string | null; +} + +/** + * True when a scheduled sync may run: sync on, and no local data of another + * account (#165). A known owner other than the signed-in account blocks every + * sync: its outbox would be pushed under the wrong account. An unknown owner + * (device synced before #165) does not block: sync is only switched on once + * the first-sync choice has succeeded. + */ +export function canSync(state: SyncGuardState): boolean { + if (!state.syncEnabled) return false; + return state.dataOwnerId === null || state.dataOwnerId === state.userId; +} + export interface SyncScheduler { /** * Ask for a sync. Resolves when the run that serves this request ends, or @@ -70,6 +91,14 @@ export interface SyncScheduler { */ beginInitialSync(): Promise; endInitialSync(): void; + /** + * Run for the push before sign-out (#165), to call inside the first-sync + * state: its request is reserved outside the budget. It may send the + * remaining budget, and at least one POST even when the budget is spent; + * none while a 429 suspends the scheduler. Its requests count in the budget + * of the next runs. + */ + reserve(): SyncRun; } export function createSyncScheduler(deps: SchedulerDeps): SyncScheduler { @@ -184,5 +213,14 @@ export function createSyncScheduler(deps: SchedulerDeps): SyncScheduler { initial = Math.max(0, initial - 1); pump(); }, + reserve() { + const now = deps.now(); + return { + pushBatches: now < suspendedUntil ? 0 : Math.max(1, remaining(now)), + request: tracker.request, + rateLimited: tracker.rateLimited, + isSuspended: () => deps.now() < suspendedUntil, + }; + }, }; } diff --git a/src/stores/useSettingsStore.ts b/src/stores/useSettingsStore.ts index 4270e24..4124395 100644 --- a/src/stores/useSettingsStore.ts +++ b/src/stores/useSettingsStore.ts @@ -15,6 +15,10 @@ interface SettingsState { syncEnabled: boolean; lastSyncAt: string | null; // ISO timestamp userId: string | null; + // Account the local data come from (#165): set by initialMerge and + // initialReset once done, kept at sign-out, null when the app empties the + // device or before any sync (also on a device synced before #165). + dataOwnerId: string | null; setTheme: (theme: ThemeMode) => void; setLocale: (locale: 'fr' | 'en') => void; setNotificationsEnabled: (enabled: boolean) => void; @@ -24,6 +28,7 @@ interface SettingsState { setSyncEnabled: (enabled: boolean) => void; setLastSyncAt: (timestamp: string | null) => void; setUserId: (userId: string | null) => void; + setDataOwnerId: (dataOwnerId: string | null) => void; } // Error of a failed settings load, and who waits for it (whenSettingsHydrated) @@ -42,6 +47,7 @@ export const useSettingsStore = create()( syncEnabled: false, lastSyncAt: null, userId: null, + dataOwnerId: null, setTheme: (theme) => set({ theme }), setLocale: (locale) => set({ locale }), setNotificationsEnabled: (notificationsEnabled) => set({ notificationsEnabled }), @@ -51,6 +57,7 @@ export const useSettingsStore = create()( setSyncEnabled: (syncEnabled) => set({ syncEnabled }), setLastSyncAt: (lastSyncAt) => set({ lastSyncAt }), setUserId: (userId) => set({ userId }), + setDataOwnerId: (dataOwnerId) => set({ dataOwnerId }), }), { name: 'simpl-liste-settings', diff --git a/tests/smoke.test.cjs b/tests/smoke.test.cjs index b51ac94..6f7004f 100644 --- a/tests/smoke.test.cjs +++ b/tests/smoke.test.cjs @@ -245,6 +245,84 @@ check('sync on write and every sync go through the scheduler (#178)', () => { assert.equal((client.match(/pullChanges\(SYNC_EPOCH, scheduler\.tracker\)/g) || []).length, 2, 'the first-sync pulls are counted'); }); +// No merge across accounts (#165). firstSyncChoice and canSync are executed +// by tests/syncRules.test.mjs and tests/syncSchedule.test.mjs; this check +// locks their wiring in files node cannot load: sync stays off until the +// first-sync choice has succeeded, the owner of the local data is recorded, +// « Annuler » touches no data, and sign-out pushes first. +check('account switch: sync off until the choice, owner recorded, sign-out pushes first (#165)', () => { + const read = (rel) => fs.readFileSync(path.join(__dirname, '..', rel), 'utf8'); + const body = (src, head) => { + const start = src.indexOf(head); + assert.ok(start >= 0, `${head} not found`); + const end = src.indexOf('\n };\n', start); + return src.slice(start, end < 0 ? undefined : end); + }; + const settings = read('app/(tabs)/settings.tsx'); + // setSyncEnabled(true) only once, after a successful initialMerge / initialReset + assert.equal((settings.match(/setSyncEnabled\(true\)/g) || []).length, 1, 'one setSyncEnabled(true), in runFirstSync'); + const run = body(settings, 'const runFirstSync = async ('); + assert.match(run, /await initialMerge\(accountId\);\s*\} else \{\s*await initialReset\(accountId\);\s*\}\s*setSyncEnabled\(true\);/, 'sync on only after the first sync succeeded'); + const signIn = body(settings, 'const handleSignIn = async ('); + assert.ok(!/setSyncEnabled/.test(signIn), 'handleSignIn must not switch sync on before the choice'); + assert.match(signIn, /setUserId\(claims\.sub\);\s*await offerFirstSync\(\);/); + const syncNow = body(settings, 'const handleSyncNow = async ('); + assert.match(syncNow, /if \(!syncEnabled \|\| !lastSyncAt\) \{\s*await offerFirstSync\(\);\s*return;/); + // Both sites go through firstSyncChoice, fed by the persisted owner + const offer = body(settings, 'const offerFirstSync = async ('); + assert.match(offer, /const \{ dataOwnerId, userId: signedInId \} = useSettingsStore\.getState\(\);/); + assert.match(offer, /firstSyncChoice\(\{ dataOwnerId, signedInId, localInboxId \}\)/); + const onlyStart = offer.indexOf("if (choice === 'reset-only')"); + assert.ok(onlyStart >= 0, 'reset-only branch not found'); + const only = offer.slice(onlyStart, offer.indexOf('return;', onlyStart)); + assert.ok(!/initialMerge|runFirstSync\('merge'\)/.test(only), 'reset-only offers no merge'); + assert.match(only, /text: t\('common\.cancel'\),\s*style: 'cancel',\s*onPress: \(\) => \{\s*finishSignOut\(\);/, '« Annuler » signs out'); + assert.match(only, /text: t\('sync\.loadAccount'\),[^]*?runFirstSync\('reset'\);/, '« Charger ce compte » goes through initialReset'); + // « Annuler » touches no data: neither push, nor reset, nor database + const finish = body(settings, 'const finishSignOut = async ('); + assert.ok(!/initialReset|initialMerge|pushBeforeSignOut|setDataOwnerId|\bdb\b|delete/.test(finish), 'finishSignOut must touch no data'); + // Sign-out pushes first, then counts what is left + const signOut = body(settings, 'const handleSignOut = ('); + assert.match(signOut, /unsent = await pushBeforeSignOut\(\);[^]*if \(unsent > 0\) \{\s*Alert\.alert\(t\('sync\.unsentWarning', \{ count: unsent \}\)/); + assert.ok(signOut.indexOf('pushBeforeSignOut()') < signOut.indexOf('await finishSignOut();'), 'push before the sign-out'); + + const client = read('src/services/syncClient.ts'); + // The scheduler's guard reads the owner of the data + assert.match(client, /canRun: \(\) => canSync\(useSettingsStore\.getState\(\)\),/); + const fnBody = (name) => { + const start = client.indexOf(`export async function ${name}(`); + assert.ok(start >= 0, `${name} not found`); + return client.slice(start, client.indexOf('\n}\n', start)); + }; + // The owner is recorded once the first sync is done, cleared with the data + assert.match(fnBody('initialMerge'), /await mergeLocalData\(\);\s*useSettingsStore\.getState\(\)\.setDataOwnerId\(accountId\);/); + assert.match(fnBody('initialReset'), /await resetFromServer\(\);\s*useSettingsStore\.getState\(\)\.setDataOwnerId\(accountId\);/); + const reset = client.slice(client.indexOf('async function resetFromServer(')); + assert.match(reset, /await db\.delete\(syncOutbox\);\s*useSettingsStore\.getState\(\)\.setDataOwnerId\(null\);/, 'the outbox of the other account is deleted, owner cleared'); + // Neither first sync runs silently without a session: sync would stay off + for (const name of ['mergeLocalData', 'resetFromServer']) { + const start = client.indexOf(`async function ${name}(`); + assert.match(client.slice(start, start + 300), /if \(!headers\['Authorization'\]\) throw new Error\(/, `${name} must throw without a session`); + } + // Sign-out push: guarded, in the first-sync state, reserved run, bounded + const push = fnBody('pushBeforeSignOut'); + assert.match(client, /const SIGN_OUT_PUSH_TIMEOUT_MS = 10_000;/); + assert.match(push, /if \(canSync\(useSettingsStore\.getState\(\)\)\) \{/); + assert.match(push, /await scheduler\.beginInitialSync\(\);\s*try \{\s*await pushChanges\(scheduler\.reserve\(\)\);[^]*\} finally \{\s*scheduler\.endInitialSync\(\);/); + assert.match(push, /await Promise\.race\(\[push, sleep\(SIGN_OUT_PUSH_TIMEOUT_MS\)\]\);/); + assert.match(push, /\.where\(isNull\(syncOutbox\.syncedAt\)\);\s*return unsent\.length;/); + assert.ok(!/pullChanges|fullSync/.test(push), 'the sign-out push does not pull'); + + // dataOwnerId is persisted with the settings and never cleared at sign-out + const store = read('src/stores/useSettingsStore.ts'); + assert.match(store, /dataOwnerId: null,/); + assert.ok(!/partialize/.test(store), 'every setting is persisted, dataOwnerId included'); + + // The token getter follows the session, not syncEnabled: the first sync runs sync off + const layout = read('app/_layout.tsx'); + assert.match(layout, /if \(isAuthenticated\) \{\s*setTokenGetter\(getAccessToken\);/); +}); + // Tags must not go through keepLocal: the server's tag updated_at is its // created_at (no updatedAt column), so a local rename would always look newer // (PR #157 review). syncClient.ts cannot load under node, hence a source check. @@ -320,7 +398,7 @@ check('syncClient.ts wires the #149-#151 sync rules', () => { const body = fn(name); assert.match( body, - new RegExp(`if \\(keepLocal\\(local, payload, since\\)\\) \\{\\s*(//[^\\n]*\\s*)?await writeOutboxEntry\\('${type}', id, 'update', ${snapshot}\\(local\\)\\);\\s*return;\\s*\\}`), + new RegExp(`if \\(keepLocal\\(local, payload, since\\)\\) \\{\\s*(//[^\\n]*\\s*)?await queueOutboxEntry\\('${type}', id, 'update', ${snapshot}\\(local\\)\\);\\s*return;\\s*\\}`), `${name}: a kept row must be re-queued, then left untouched` ); assert.match(body, new RegExp(`${values}\\(id, payload, local\\)`), `${name} must pass the local row`); @@ -328,7 +406,7 @@ check('syncClient.ts wires the #149-#151 sync rules', () => { // Tags always take the server version (decision of Max, PR #157) const tag = fn('applyTagChange'); assert.match(tag, /pulledTagValues\(id, payload, local\)/); - assert.ok(!/\bkeepLocal\b|writeOutboxEntry|updated_at/.test(tag), 'applyTagChange must never keep a local tag'); + assert.ok(!/\bkeepLocal\b|writeOutboxEntry|queueOutboxEntry|updated_at/.test(tag), 'applyTagChange must never keep a local tag'); // #150: lastSyncAt goes back to SYNC_EPOCH before the full pull, never after const merge = fn('mergeLocalData'); const stamp = merge.indexOf('setLastSyncAt(SYNC_EPOCH)'); @@ -432,7 +510,8 @@ check('lists.ts and _layout.tsx wire the #152 Inbox rules', () => { const reset = client.slice(client.indexOf('export async function initialReset('), client.indexOf('export async function cleanOutbox(')); assert.ok(!/ensureInbox/.test(reset), 'initialReset must not fall back to the fixed Inbox'); assert.match(reset, /if \(!hasInbox\) \{\s*(\/\/[^\n]*\s*)*const id = randomUUID\(\);/); - assert.match(reset, /await writeOutboxEntry\('list', id, 'create', inbox\);/); + // #165: written whatever syncEnabled, since initialReset runs before sync is on + assert.match(reset, /await queueOutboxEntry\('list', id, 'create', inbox\);/); assert.match(reset, /const inbox = \{[^}]*isInbox: true \}/); // Callers await the Inbox read from the database assert.match(read('app/(tabs)/index.tsx'), /await getInboxId\(\)/); diff --git a/tests/syncRules.test.mjs b/tests/syncRules.test.mjs index af7e60c..7dcad55 100644 --- a/tests/syncRules.test.mjs +++ b/tests/syncRules.test.mjs @@ -33,6 +33,7 @@ import { LOCAL_INBOX_ID, pickInboxId, planInboxRepair, + firstSyncChoice, } from '../src/services/syncRules.ts'; const ID = '11111111-1111-4111-8111-111111111111'; @@ -845,3 +846,46 @@ test('planInboxRepair: the repaired outbox of a split device is pushed without a assert.deepEqual(server.state.tasks.get(T4), { listId: SERVER_INBOX, deleted: true }); assert.deepEqual([...server.state.links], [`${T1}:${TAG_A}`]); }); + +// --------------------------------------------------------------------------- +// firstSyncChoice: no merge across accounts (#165) +// --------------------------------------------------------------------------- + +const ACCOUNT_A = 'logto-sub-account-a'; +const ACCOUNT_B = 'logto-sub-account-b'; +const SERVER_INBOX_ID = '33333333-3333-4333-8333-333333333333'; + +test('firstSyncChoice: table of the first-sync choice', () => { + const rows = [ + // [case, dataOwnerId, signedInId, localInboxId, expected] + ['never synced, fixed Inbox', null, ACCOUNT_B, LOCAL_INBOX_ID, 'merge-or-reset'], + ['never synced, no Inbox yet', null, ACCOUNT_B, null, 'merge-or-reset'], + ['same account', ACCOUNT_A, ACCOUNT_A, SERVER_INBOX_ID, 'merge-or-reset'], + ['other account', ACCOUNT_A, ACCOUNT_B, SERVER_INBOX_ID, 'reset-only'], + ['unknown owner, fixed Inbox', null, ACCOUNT_A, LOCAL_INBOX_ID, 'merge-or-reset'], + ['unknown owner, server Inbox', null, ACCOUNT_A, SERVER_INBOX_ID, 'reset-only'], + ]; + for (const [name, dataOwnerId, signedInId, localInboxId, expected] of rows) { + assert.equal(firstSyncChoice({ dataOwnerId, signedInId, localInboxId }), expected, name); + } +}); + +// Regression (#165): sign-out resets userId to null but keeps dataOwnerId. +// A device holding A's data, signed in to B, only offers to load B, whatever +// its Inbox says: comparing to the userId of before the sign-in (null) would +// offer the merge again. +test('firstSyncChoice: data of A, signed in to B gives reset-only (regression)', () => { + const afterSignOut = { dataOwnerId: ACCOUNT_A, userId: null }; + for (const localInboxId of [SERVER_INBOX_ID, LOCAL_INBOX_ID, null]) { + assert.equal( + firstSyncChoice({ dataOwnerId: afterSignOut.dataOwnerId, signedInId: ACCOUNT_B, localInboxId }), + 'reset-only', + String(localInboxId), + ); + } + // Back to A: the choice is offered again + assert.equal( + firstSyncChoice({ dataOwnerId: afterSignOut.dataOwnerId, signedInId: ACCOUNT_A, localInboxId: SERVER_INBOX_ID }), + 'merge-or-reset', + ); +}); diff --git a/tests/syncSchedule.test.mjs b/tests/syncSchedule.test.mjs index 0a3af67..3e4dc11 100644 --- a/tests/syncSchedule.test.mjs +++ b/tests/syncSchedule.test.mjs @@ -13,6 +13,7 @@ import { BUDGET_WINDOW_MS, DEFAULT_RETRY_AFTER_S, REQUEST_BUDGET, + canSync, createSyncScheduler, } from '../src/services/syncSchedule.ts'; import { SYNC_DEBOUNCE_MS, requestSync, setSyncSubscriber } from '../src/services/syncTrigger.ts'; @@ -336,3 +337,93 @@ test('a failing run releases the scheduler', async () => { await s.request(); assert.equal(runs, 2); }); + +// --- Account guard and sign-out push (#165) --- + +const A = 'logto-sub-account-a'; +const B = 'logto-sub-account-b'; + +test('canSync: sync on, and local data of the signed-in account or of an unknown owner', () => { + assert.equal(canSync({ syncEnabled: true, dataOwnerId: A, userId: A }), true); + assert.equal(canSync({ syncEnabled: true, dataOwnerId: null, userId: A }), true, 'device synced before #165'); + assert.equal(canSync({ syncEnabled: true, dataOwnerId: A, userId: B }), false, 'data of another account'); + assert.equal(canSync({ syncEnabled: true, dataOwnerId: A, userId: null }), false, 'signed out'); + assert.equal(canSync({ syncEnabled: false, dataOwnerId: A, userId: A }), false, 'sync off'); + assert.equal(canSync({ syncEnabled: false, dataOwnerId: null, userId: null }), false); +}); + +test('data owner other than the signed-in account: the scheduler refuses every sync', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { batches: 3 }); + // Even with sync on: the guard reads the owner, not only syncEnabled + const settings = { syncEnabled: true, dataOwnerId: A, userId: B }; + const s = createSyncScheduler({ + now: clock.now, + setTimer: clock.setTimer, + run: server.run, + canRun: () => canSync(settings), + }); + for (let i = 0; i < 5; i++) s.request(); + await clock.advance(5 * BUDGET_WINDOW_MS); + assert.equal(server.runs, 0); + assert.deepEqual(server.requests, [], 'not one request sent under the other account'); + // « Charger ce compte » done: B owns the data + settings.dataOwnerId = B; + s.request(); + await flush(); + assert.equal(server.runs, 1); +}); + +test('reserve: the sign-out push gets one request outside a spent budget', async () => { + const clock = fakeClock(); + const server = fakeServer(clock); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + assert.equal(s.reserve().pushBatches, REQUEST_BUDGET, 'the whole budget when nothing was sent'); + for (let i = 0; i < REQUEST_BUDGET; i++) s.tracker.request(); + const run = s.reserve(); + assert.equal(run.pushBatches, 1, 'one request outside the spent budget'); + // Its request counts in the budget of the next runs + run.request(); + s.request(); + await clock.advance(BUDGET_WINDOW_MS - 1); + assert.equal(server.runs, 0); + await clock.advance(1); + assert.equal(server.runs, 1); +}); + +test('reserve: nothing while a 429 suspends the scheduler', async () => { + const clock = fakeClock(); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: async () => {} }); + s.tracker.rateLimited(20); + const run = s.reserve(); + assert.equal(run.pushBatches, 0); + assert.equal(run.isSuspended(), true); + await clock.advance(20_000); + assert.equal(s.reserve().pushBatches, REQUEST_BUDGET, 'the budget once the Retry-After has passed'); + assert.equal(run.isSuspended(), false); +}); + +test('the sign-out push never runs alongside a sync, and a sync waits for its end', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { duration: 1000 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.request(); + await flush(); + assert.equal(server.runs, 1); + // pushBeforeSignOut: first-sync state, then a reserved run + let pushing = false; + s.beginInitialSync().then(() => { + pushing = true; + }); + await flush(); + assert.equal(pushing, false, 'waits for the sync in flight'); + await clock.advance(1000); + assert.equal(pushing, true); + assert.equal(server.active, 0, 'no sync during the sign-out push'); + s.request(); + await clock.advance(BUDGET_WINDOW_MS); + assert.equal(server.runs, 1, 'no sync before the push ends'); + s.endInitialSync(); + await flush(); + assert.equal(server.runs, 2); +}); -- 2.52.0 From 7c4292a8bc89344e9247f4aa38cd68132daf7ce2 Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 21:10:55 -0500 Subject: [PATCH 04/18] docs(review): account rule of #165 and the sync's own outbox writes Refs #165 Co-Authored-By: Claude Opus 5.5 --- REVIEW.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/REVIEW.md b/REVIEW.md index 5fb156c..801e8bc 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -110,9 +110,10 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm - 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` - `task create` écrit `completed` et `completedAt` ; une tâche terminée sans date reçoit la date du serveur, une tâche non terminée n'a pas de date (#146). — `web/src/lib/syncData.ts`, `web/src/app/api/sync/route.ts` - `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` +- 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 -- 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 (`writeOutboxEntry`, action `update`). Jamais une étiquette : le serveur n'a pas d'`updatedAt` sur les étiquettes et renvoie `updated_at` = `created_at`, donc un renommage hors connexion d'étiquette est perdu (check smoke « applyTagChange never keeps a local tag »). — `src/services/syncRules.ts` (`keepLocal`), `src/services/syncClient.ts`, #149 +- 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 : le serveur n'a pas d'`updatedAt` sur les étiquettes et renvoie `updated_at` = `created_at`, donc un renommage hors connexion d'étiquette est perdu (check smoke « applyTagChange never keeps a local tag »). — `src/services/syncRules.ts` (`keepLocal`), `src/services/syncClient.ts`, #149 - 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`) - Une suppression serveur s'applique toujours, même sur une ligne locale plus récente : le protocole n'a pas de restauration. — `src/services/syncClient.ts`, #149 - `src/services/syncRules.ts` reste sans import, pour que `tests/syncRules.test.mjs` le charge par le type stripping de Node (check smoke `syncRules.ts stays import-free`). `src/services/syncSchedule.ts` et `src/services/syncTrigger.ts` suivent la même règle pour `tests/syncSchedule.test.mjs` (check smoke `syncSchedule.ts and syncTrigger.ts stay import-free`). — `tests/smoke.test.cjs`, `tests/syncRules.test.mjs`, `tests/syncSchedule.test.mjs`, #149, #178 @@ -133,7 +134,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm ### Vie privée -- L'app n'appelle que quatre hôtes : `liste.lacompagniemaximus.com` (sync, seulement si la sync est activée et la session ouverte), `auth.lacompagniemaximus.com` (Logto), `feedback.lacompagniemaximus.com` (rétroaction envoyée par l'utilisateur) et `git.lacompagniemaximus.com` (vérification des mises à jour, sans authentification). Un hôte ajouté se justifie dans la PR. — `src/services/syncClient.ts`, `src/lib/logtoConfig.ts`, `src/services/feedback.ts`, `app/(tabs)/settings.tsx` +- L'app n'appelle que quatre hôtes : `liste.lacompagniemaximus.com` (sync, seulement la session ouverte, et la sync activée ou la première sync choisie par l'utilisateur), `auth.lacompagniemaximus.com` (Logto), `feedback.lacompagniemaximus.com` (rétroaction envoyée par l'utilisateur) et `git.lacompagniemaximus.com` (vérification des mises à jour, sans authentification). Un hôte ajouté se justifie dans la PR. — `src/services/syncClient.ts`, `src/lib/logtoConfig.ts`, `src/services/feedback.ts`, `app/(tabs)/settings.tsx` - Le Feedback Hub reçoit le texte saisi (2000 caractères au plus), un `user_id` facultatif et un contexte limité à la liste blanche `CONTEXT_KEYS` (page, langue, thème, viewport, user-agent, horodatage). Une clé ajoutée élargit ce qui part (Loi 25) ; le module reste sans import, pour que `tests/feedback.test.mjs` le charge. — `src/services/feedback.ts`, `tests/feedback.test.mjs`, PR #101 - Calendrier, notifications et export `.ics` restent sur l'appareil. — `src/services/{calendar,notifications,icsExport}.ts` -- 2.52.0 From 99cc2fc1c4d1da4cc1260bb1c0af9a700467e68e Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 21:16:47 -0500 Subject: [PATCH 05/18] feat(web): show, add and remove task tags and filter by tag in the companion - web/src/lib/taskQueries.ts: list task query (existing filters + tags), subtasks, loadTaskTags (one query, live tags of the account only) and the account tags, shared by the list page and GET /api/lists/[id]/tasks. - ?tags= validated by zod (at most 20 UUIDs, count checked first); the tag filter joins sl_tags on the account and deleted_at IS NULL; 400 on a malformed value. - TaskItem: tag pills on tasks and subtasks; the detail view adds an existing tag and removes one through the task-tag API. - Sidebar: a click on a tag filters the current view by ?tags=, a second click removes it; FilterBar shows the active tag filter. - FR/EN strings. Refs #179 Refs #168 Co-Authored-By: Claude Opus 5.5 --- web/src/app/(app)/lists/[id]/page.tsx | 87 ++++------ web/src/app/api/lists/[id]/tasks/route.ts | 80 +++------ web/src/components/FilterBar.tsx | 28 +++- web/src/components/Sidebar.tsx | 69 ++++++-- web/src/components/TaskItem.tsx | 110 ++++++++++++- web/src/components/TaskList.tsx | 12 +- web/src/i18n/en.json | 14 +- web/src/i18n/fr.json | 14 +- web/src/lib/taskQueries.test.ts | 188 ++++++++++++++++++++++ web/src/lib/taskQueries.ts | 123 ++++++++++++++ web/src/lib/types.ts | 7 + web/src/lib/validators.test.ts | 40 ++++- web/src/lib/validators.ts | 20 +++ 13 files changed, 648 insertions(+), 144 deletions(-) create mode 100644 web/src/lib/taskQueries.test.ts create mode 100644 web/src/lib/taskQueries.ts diff --git a/web/src/app/(app)/lists/[id]/page.tsx b/web/src/app/(app)/lists/[id]/page.tsx index d4e93de..b4b2713 100644 --- a/web/src/app/(app)/lists/[id]/page.tsx +++ b/web/src/app/(app)/lists/[id]/page.tsx @@ -3,11 +3,17 @@ export const dynamic = "force-dynamic"; import { notFound, redirect } from "next/navigation"; import { getAuthenticatedUser } from "@/lib/auth"; import { db } from "@/db/client"; -import { slLists, slTasks } from "@/db/schema"; -import { eq, and, isNull, asc, desc } from "drizzle-orm"; +import { slLists } from "@/db/schema"; +import { eq, and, isNull } from "drizzle-orm"; import { TaskList } from "@/components/TaskList"; import type { Task } from "@/lib/types"; -import type { SQL } from "drizzle-orm"; +import { parseTagFilter } from "@/lib/validators"; +import { + queryListTasks, + loadSubtasks, + loadTaskTags, + loadAccountTags, +} from "@/lib/taskQueries"; export default async function ListPage({ params, @@ -37,70 +43,31 @@ export default async function ListPage({ if (!list) notFound(); - // Build conditions - const conditions: SQL[] = [ - eq(slTasks.listId, listId), - eq(slTasks.userId, userId), - isNull(slTasks.deletedAt), - isNull(slTasks.parentId), - ]; - const completed = typeof search.completed === "string" ? search.completed : undefined; - if (completed === "true" || completed === "false") { - conditions.push(eq(slTasks.completed, completed === "true")); - } + // A malformed ?tags= in the address bar shows the list unfiltered (the API + // answers 400 to the same value). + const tagFilter = parseTagFilter(typeof search.tags === "string" ? search.tags : undefined); - const sortBy = (typeof search.sortBy === "string" ? search.sortBy : "position") as string; - const sortOrder = (typeof search.sortOrder === "string" ? search.sortOrder : "asc") as string; + const tasks = await queryListTasks(userId, listId, { + completed: completed === "true" || completed === "false" ? completed === "true" : undefined, + tagIds: tagFilter.ok ? tagFilter.tagIds : null, + sortBy: typeof search.sortBy === "string" ? search.sortBy : "position", + sortOrder: typeof search.sortOrder === "string" ? search.sortOrder : "asc", + }); - const sortColumn = - sortBy === "priority" - ? slTasks.priority - : sortBy === "dueDate" - ? slTasks.dueDate - : sortBy === "createdAt" - ? slTasks.createdAt - : sortBy === "title" - ? slTasks.title - : slTasks.position; - - const orderFn = sortOrder === "desc" ? desc : asc; - - const tasks = await db - .select() - .from(slTasks) - .where(and(...conditions)) - .orderBy(orderFn(sortColumn)); - - // Fetch subtasks for all parent tasks - const parentIds = tasks.map((t) => t.id); - const subtasksMap: Record = {}; - - if (parentIds.length > 0) { - const allSubtasks = await db - .select() - .from(slTasks) - .where( - and( - eq(slTasks.userId, userId), - isNull(slTasks.deletedAt) - ) - ) - .orderBy(asc(slTasks.position)); - - const parentIdSet = new Set(parentIds); - for (const sub of allSubtasks) { - if (sub.parentId && parentIdSet.has(sub.parentId)) { - if (!subtasksMap[sub.parentId]) subtasksMap[sub.parentId] = []; - subtasksMap[sub.parentId].push(sub as Task); - } - } - } + const subtasksMap = await loadSubtasks(userId, tasks.map((t) => t.id)); + const subtaskIds = Object.values(subtasksMap).flat().map((s) => s.id); + const [tagsMap, accountTags] = await Promise.all([ + loadTaskTags(userId, [...tasks.map((t) => t.id), ...subtaskIds]), + loadAccountTags(userId), + ]); return ( } + tagsMap={tagsMap} + accountTags={accountTags} listId={listId} listName={list.name} /> diff --git a/web/src/app/api/lists/[id]/tasks/route.ts b/web/src/app/api/lists/[id]/tasks/route.ts index af319e4..290f003 100644 --- a/web/src/app/api/lists/[id]/tasks/route.ts +++ b/web/src/app/api/lists/[id]/tasks/route.ts @@ -1,9 +1,11 @@ import { NextRequest, NextResponse } from 'next/server'; import { db } from '@/db/client'; -import { slTasks, slLists, slTaskTags } from '@/db/schema'; -import { eq, and, isNull, asc, desc, inArray, SQL } from 'drizzle-orm'; +import { slLists } from '@/db/schema'; +import { eq, and } from 'drizzle-orm'; import { requireAuth } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { parseTagFilter } from '@/lib/validators'; +import { queryListTasks } from '@/lib/taskQueries'; export async function GET( request: NextRequest, @@ -16,6 +18,15 @@ export async function GET( const { id: listId } = await params; + const url = request.nextUrl; + const completed = url.searchParams.get('completed'); + const priority = url.searchParams.get('priority'); + const dueDate = url.searchParams.get('dueDate'); + const tagFilter = parseTagFilter(url.searchParams.get('tags')); + if (!tagFilter.ok) { + return NextResponse.json({ error: 'Invalid tags' }, { status: 400 }); + } + // Verify list belongs to user const [list] = await db .select({ id: slLists.id }) @@ -26,63 +37,14 @@ export async function GET( return NextResponse.json({ error: 'List not found' }, { status: 404 }); } - const url = request.nextUrl; - const completed = url.searchParams.get('completed'); - const priority = url.searchParams.get('priority'); - const dueDate = url.searchParams.get('dueDate'); - const tags = url.searchParams.get('tags'); - const sortBy = url.searchParams.get('sortBy') || 'position'; - const sortOrder = url.searchParams.get('sortOrder') || 'asc'; - - const conditions: SQL[] = [ - eq(slTasks.listId, listId), - eq(slTasks.userId, auth.userId), - isNull(slTasks.deletedAt), - isNull(slTasks.parentId), - ]; - - if (completed !== null) { - conditions.push(eq(slTasks.completed, completed === 'true')); - } - if (priority !== null) { - conditions.push(eq(slTasks.priority, parseInt(priority, 10))); - } - - // Build query - const query = db - .select() - .from(slTasks) - .where(and(...conditions)); - - // Sort - const sortColumn = sortBy === 'priority' ? slTasks.priority - : sortBy === 'dueDate' ? slTasks.dueDate - : sortBy === 'createdAt' ? slTasks.createdAt - : sortBy === 'title' ? slTasks.title - : slTasks.position; - - const orderFn = sortOrder === 'desc' ? desc : asc; - const tasks = await query.orderBy(orderFn(sortColumn)); - - // Filter by tags if specified (post-query since it's a join table) - if (tags) { - const tagIds = tags.split(','); - const taskTagRows = await db - .select({ taskId: slTaskTags.taskId }) - .from(slTaskTags) - .where(inArray(slTaskTags.tagId, tagIds)); - - const taskIdsWithTags = new Set(taskTagRows.map((r) => r.taskId)); - return NextResponse.json(tasks.filter((t) => taskIdsWithTags.has(t.id))); - } - - // Filter by dueDate if specified (before/on that date) - if (dueDate) { - const cutoff = new Date(dueDate); - return NextResponse.json( - tasks.filter((t) => t.dueDate && t.dueDate <= cutoff) - ); - } + const tasks = await queryListTasks(auth.userId, listId, { + completed: completed !== null ? completed === 'true' : undefined, + priority: priority !== null ? parseInt(priority, 10) : undefined, + dueBefore: dueDate ? new Date(dueDate) : undefined, + tagIds: tagFilter.tagIds, + sortBy: url.searchParams.get('sortBy') || 'position', + sortOrder: url.searchParams.get('sortOrder') || 'asc', + }); return NextResponse.json(tasks); } diff --git a/web/src/components/FilterBar.tsx b/web/src/components/FilterBar.tsx index 77debd8..3e03891 100644 --- a/web/src/components/FilterBar.tsx +++ b/web/src/components/FilterBar.tsx @@ -1,10 +1,15 @@ "use client"; import { useRouter, useSearchParams, usePathname } from "next/navigation"; -import { Filter, ArrowUpDown } from "lucide-react"; +import { Filter, ArrowUpDown, Tag, X } from "lucide-react"; import { useTranslation } from "react-i18next"; +import type { TagPill } from "@/lib/types"; -export function FilterBar() { +interface FilterBarProps { + accountTags?: TagPill[]; +} + +export function FilterBar({ accountTags = [] }: FilterBarProps) { const { t } = useTranslation(); const router = useRouter(); const pathname = usePathname(); @@ -27,6 +32,11 @@ export function FilterBar() { const completed = searchParams.get("completed") ?? ""; const sortBy = searchParams.get("sortBy") ?? "position"; const sortOrder = searchParams.get("sortOrder") ?? "asc"; + // Tag filter set from the sidebar (one tag at a time, as on mobile). + const tagFilterId = searchParams.get("tags") ?? ""; + const tagFilter = accountTags.find((tag) => tag.id === tagFilterId); + // A filter on a tag that no longer exists still shows, so it can be removed. + const tagFilterName = tagFilter?.name ?? t("filter.unknownTag"); const updateParam = (key: string, value: string) => { const params = new URLSearchParams(searchParams.toString()); @@ -80,6 +90,20 @@ export function FilterBar() { {sortOrder === "asc" ? "↑" : "↓"} + + {/* Active tag filter */} + {tagFilterId && ( + + )} ); } diff --git a/web/src/components/Sidebar.tsx b/web/src/components/Sidebar.tsx index 4bae51c..fbf1aa8 100644 --- a/web/src/components/Sidebar.tsx +++ b/web/src/components/Sidebar.tsx @@ -1,8 +1,8 @@ "use client"; -import { useState } from "react"; +import { Suspense, useState } from "react"; import Link from "next/link"; -import { usePathname, useRouter } from "next/navigation"; +import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { Inbox, Plus, @@ -16,6 +16,56 @@ import { import { useTranslation } from "react-i18next"; import type { List as ListType, Tag as TagType } from "@/lib/types"; +// Sidebar tags: a click filters the current view by `?tags=` (one tag at +// a time, as in src/components/FilterMenu.tsx of the app); a second click on +// the active tag removes the filter. +function SidebarTags({ tags, onNavigate }: { tags: TagType[]; onNavigate: () => void }) { + const { t } = useTranslation(); + const pathname = usePathname(); + const router = useRouter(); + const searchParams = useSearchParams(); + const activeTagId = searchParams.get("tags"); + + const toggleTag = (tagId: string) => { + const params = new URLSearchParams(searchParams.toString()); + if (activeTagId === tagId) { + params.delete("tags"); + } else { + params.set("tags", tagId); + } + const query = params.toString(); + router.push(query ? `${pathname}?${query}` : pathname); + onNavigate(); + }; + + return ( + <> + {tags.map((tag) => { + const isActive = activeTagId === tag.id; + const label = isActive + ? t("filter.clearTag", { name: tag.name }) + : t("sidebar.filterByTag", { name: tag.name }); + return ( + + ); + })} + + ); +} + interface SidebarProps { lists: ListType[]; tags: TagType[]; @@ -122,16 +172,11 @@ export function Sidebar({ lists, tags }: SidebarProps) { )} {t("sidebar.tags")} - {tagsExpanded && - tags.map((tag) => ( -
- - {tag.name} -
- ))} + {tagsExpanded && ( + + setMobileOpen(false)} /> + + )} diff --git a/web/src/components/TaskItem.tsx b/web/src/components/TaskItem.tsx index e4bac37..c5619f4 100644 --- a/web/src/components/TaskItem.tsx +++ b/web/src/components/TaskItem.tsx @@ -10,9 +10,10 @@ import { Repeat, Check, Search, + X, } from "lucide-react"; import { useTranslation } from "react-i18next"; -import type { Task } from "@/lib/types"; +import type { Task, TagPill } from "@/lib/types"; import { TaskForm } from "./TaskForm"; const PRIORITY_COLORS: Record = { @@ -31,13 +32,40 @@ function formatDate(dateStr: string | Date | null): string { }); } +// Tag pill: the tag name on its color, for tasks and subtasks alike. +function TagChip({ tag, onRemove, removeLabel }: { tag: TagPill; onRemove?: () => void; removeLabel?: string }) { + return ( + + {tag.name} + {onRemove && ( + + )} + + ); +} + interface TaskItemProps { task: Task; subtasks?: Task[]; depth?: number; + // Tags of this task and of its subtasks, by task id. + tagsMap?: Record; + // Live tags of the account, offered in the detail view. + accountTags?: TagPill[]; } -export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) { +export function TaskItem({ task, subtasks = [], depth = 0, tagsMap = {}, accountTags = [] }: TaskItemProps) { const { t } = useTranslation(); const router = useRouter(); const [expanded, setExpanded] = useState(false); @@ -52,6 +80,11 @@ export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) { const [recurrence, setRecurrence] = useState(task.recurrence || ""); const [showSubtaskForm, setShowSubtaskForm] = useState(false); const [saving, setSaving] = useState(false); + const [tagBusy, setTagBusy] = useState(false); + + const taskTags = tagsMap[task.id] ?? []; + const assignedIds = new Set(taskTags.map((tag) => tag.id)); + const availableTags = accountTags.filter((tag) => !assignedIds.has(tag.id)); const PRIORITY_LABELS: Record = { 0: t("priority.none"), @@ -113,6 +146,33 @@ export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) { } }; + // Add or remove an existing tag through the task-tag API, then reload. + const addTag = async (tagId: string) => { + if (!tagId || tagBusy) return; + setTagBusy(true); + try { + await fetch(`/api/tasks/${task.id}/tags`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ tagIds: [tagId] }), + }); + router.refresh(); + } finally { + setTagBusy(false); + } + }; + + const removeTag = async (tagId: string) => { + if (tagBusy) return; + setTagBusy(true); + try { + await fetch(`/api/tasks/${task.id}/tags/${tagId}`, { method: "DELETE" }); + router.refresh(); + } finally { + setTagBusy(false); + } + }; + const deleteTask = async () => { await fetch(`/api/tasks/${task.id}`, { method: "DELETE" }); router.refresh(); @@ -168,6 +228,13 @@ export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) { {/* Badges */} + {taskTags.length > 0 && ( + + {taskTags.map((tag) => ( + + ))} + + )} {task.dueDate && ( @@ -274,6 +341,37 @@ export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) { {t("task.recurrenceLabel", { value: RECURRENCE_LABELS[task.recurrence] || task.recurrence })} )} + {/* Tags: remove an assigned tag, add an existing one */} +
+ {t("tag.label")} + {taskTags.length === 0 && ( + {t("tag.none")} + )} + {taskTags.map((tag) => ( + removeTag(tag.id)} + removeLabel={t("tag.remove", { name: tag.name })} + /> + ))} + {availableTags.length > 0 && ( + + )} +
); diff --git a/web/src/components/TaskList.tsx b/web/src/components/TaskList.tsx index 310d5e7..cd135ff 100644 --- a/web/src/components/TaskList.tsx +++ b/web/src/components/TaskList.tsx @@ -1,6 +1,6 @@ "use client"; -import type { Task } from "@/lib/types"; +import type { Task, TagPill } from "@/lib/types"; import { TaskItem } from "./TaskItem"; import { TaskForm } from "./TaskForm"; import { FilterBar } from "./FilterBar"; @@ -12,11 +12,15 @@ import { useTranslation } from "react-i18next"; interface TaskListProps { tasks: Task[]; subtasksMap: Record; + // Tags of every task and subtask shown, by task id. + tagsMap: Record; + // Live tags of the account, for the tag picker and the active filter. + accountTags: TagPill[]; listId: string; listName: string; } -export function TaskList({ tasks, subtasksMap, listId, listName }: TaskListProps) { +export function TaskList({ tasks, subtasksMap, tagsMap, accountTags, listId, listName }: TaskListProps) { const { t } = useTranslation(); const router = useRouter(); const [refreshing, setRefreshing] = useState(false); @@ -44,7 +48,7 @@ export function TaskList({ tasks, subtasksMap, listId, listName }: TaskListProps - + @@ -66,6 +70,8 @@ export function TaskList({ tasks, subtasksMap, listId, listName }: TaskListProps key={task.id} task={task} subtasks={subtasksMap[task.id] || []} + tagsMap={tagsMap} + accountTags={accountTags} /> ))} diff --git a/web/src/i18n/en.json b/web/src/i18n/en.json index 857b386..2fb5887 100644 --- a/web/src/i18n/en.json +++ b/web/src/i18n/en.json @@ -12,7 +12,8 @@ "lists": "Lists", "tags": "Tags", "newList": "New list", - "newListPlaceholder": "List name..." + "newListPlaceholder": "List name...", + "filterByTag": "Filter by {{name}}" }, "task": { "add": "Add a task", @@ -32,6 +33,12 @@ "dueDate": "Due: {{value}}", "recurrenceLabel": "Recurrence: {{value}}" }, + "tag": { + "label": "Tags:", + "none": "None", + "add": "+ Tag", + "remove": "Remove tag {{name}}" + }, "priority": { "none": "None", "noneExplicit": "No priority", @@ -49,7 +56,10 @@ "filter": { "all": "All", "active": "Active", - "completed": "Completed" + "completed": "Completed", + "tag": "Tag: {{name}}", + "clearTag": "Remove filter {{name}}", + "unknownTag": "not found" }, "sort": { "position": "Position", diff --git a/web/src/i18n/fr.json b/web/src/i18n/fr.json index 4e659c0..6cfebff 100644 --- a/web/src/i18n/fr.json +++ b/web/src/i18n/fr.json @@ -12,7 +12,8 @@ "lists": "Listes", "tags": "Étiquettes", "newList": "Nouvelle liste", - "newListPlaceholder": "Nom de la liste..." + "newListPlaceholder": "Nom de la liste...", + "filterByTag": "Filtrer par {{name}}" }, "task": { "add": "Ajouter une tâche", @@ -32,6 +33,12 @@ "dueDate": "Échéance : {{value}}", "recurrenceLabel": "Récurrence : {{value}}" }, + "tag": { + "label": "Étiquettes :", + "none": "Aucune", + "add": "+ Étiquette", + "remove": "Retirer l'étiquette {{name}}" + }, "priority": { "none": "Aucune", "noneExplicit": "Aucune priorité", @@ -49,7 +56,10 @@ "filter": { "all": "Toutes", "active": "Actives", - "completed": "Complétées" + "completed": "Complétées", + "tag": "Étiquette : {{name}}", + "clearTag": "Retirer le filtre {{name}}", + "unknownTag": "introuvable" }, "sort": { "position": "Position", diff --git a/web/src/lib/taskQueries.test.ts b/web/src/lib/taskQueries.test.ts new file mode 100644 index 0000000..fc85fc0 --- /dev/null +++ b/web/src/lib/taskQueries.test.ts @@ -0,0 +1,188 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { randomUUID as u } from 'node:crypto'; +import { describe, it, expect, beforeAll, vi } from 'vitest'; +import type { PGlite } from 'electric-sql-pglite'; + +// Task reads of the list page and of GET /api/lists/[id]/tasks (#179), against +// an in-memory Postgres (PGlite) with the companion migrations, as in +// web/src/app/api/sync/route.test.ts. Auth and rate limiting are stubbed. + +const h = await vi.hoisted(async () => { + const { PGlite } = await import('electric-sql-pglite'); + return { pg: new PGlite() as PGlite, userId: '' }; +}); + +vi.mock('@/db/client', async () => { + const { drizzle } = await import('drizzle-orm/pglite'); + const schema = await import('@/db/schema'); + return { db: drizzle(h.pg, { schema }) }; +}); + +vi.mock('@/lib/auth', () => ({ getAuthenticatedUser: async () => null })); +vi.mock('@/lib/api', async (importOriginal) => ({ + ...(await importOriginal()), + requireAuth: async () => ({ userId: h.userId }), +})); +vi.mock('@/lib/rateLimit', () => ({ rateLimit: () => null })); + +const { loadTaskTags, queryListTasks, loadSubtasks } = await import('./taskQueries'); +const { GET } = await import('@/app/api/lists/[id]/tasks/route'); +const { NextRequest } = await import('next/server'); + +beforeAll(async () => { + const dir = path.join(__dirname, '../db/migrations'); + for (const f of fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) { + for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) { + if (stmt.trim()) await h.pg.exec(stmt); + } + } +}); + +async function exec(sql: string, params: unknown[]) { + await h.pg.query(sql, params); +} + +// One account: a list, three tasks (one with a subtask), and tags. +async function seedAccount() { + const a = { + userId: `user-${u()}`, list: u(), + t1: u(), t2: u(), t3: u(), sub: u(), + red: u(), blue: u(), gone: u(), + }; + await exec('INSERT INTO sl_lists (id, user_id, name) VALUES ($1, $2, $3)', [a.list, a.userId, 'L']); + for (const [id, title, pos] of [[a.t1, 't1', 0], [a.t2, 't2', 1], [a.t3, 't3', 2]] as const) { + await exec('INSERT INTO sl_tasks (id, user_id, title, list_id, position) VALUES ($1, $2, $3, $4, $5)', [id, a.userId, title, a.list, pos]); + } + await exec('INSERT INTO sl_tasks (id, user_id, title, list_id, parent_id) VALUES ($1, $2, $3, $4, $5)', [a.sub, a.userId, 'sub', a.list, a.t1]); + await exec('INSERT INTO sl_tags (id, user_id, name, color) VALUES ($1, $2, $3, $4)', [a.red, a.userId, 'red', '#E57373']); + await exec('INSERT INTO sl_tags (id, user_id, name, color) VALUES ($1, $2, $3, $4)', [a.blue, a.userId, 'blue', '#4A90A4']); + await exec('INSERT INTO sl_tags (id, user_id, name, deleted_at) VALUES ($1, $2, $3, now())', [a.gone, a.userId, 'gone']); + const links: [string, string][] = [[a.t1, a.red], [a.t1, a.blue], [a.t2, a.blue], [a.t3, a.gone], [a.sub, a.red]]; + for (const [taskId, tagId] of links) { + await exec('INSERT INTO sl_task_tags (task_id, tag_id) VALUES ($1, $2)', [taskId, tagId]); + } + return a; +} + +// A tag of another account linked to a task of `a`: rows the sync can never +// produce (it checks the tag owner), but the reads must not trust that. +async function foreignTagOn(taskId: string) { + const other = { userId: `user-${u()}`, tag: u() }; + await exec('INSERT INTO sl_tags (id, user_id, name) VALUES ($1, $2, $3)', [other.tag, other.userId, 'foreign']); + await exec('INSERT INTO sl_task_tags (task_id, tag_id) VALUES ($1, $2)', [taskId, other.tag]); + return other; +} + +async function getTasks(userId: string, listId: string, query: string) { + h.userId = userId; + const req = new NextRequest(`http://localhost/api/lists/${listId}/tasks${query}`); + return GET(req, { params: Promise.resolve({ id: listId }) }); +} + +describe('loadTaskTags', () => { + it('loads the tags of N tasks in a single query', async () => { + const a = await seedAccount(); + const spy = vi.spyOn(h.pg, 'query'); + const map = await loadTaskTags(a.userId, [a.t1, a.t2, a.t3, a.sub]); + expect(spy).toHaveBeenCalledTimes(1); + spy.mockRestore(); + expect(map[a.t1].map((t) => t.name)).toEqual(['blue', 'red']); + expect(map[a.t2]).toEqual([{ id: a.blue, name: 'blue', color: '#4A90A4' }]); + expect(map[a.sub].map((t) => t.id)).toEqual([a.red]); + }); + + it('runs no query for no task', async () => { + const spy = vi.spyOn(h.pg, 'query'); + expect(await loadTaskTags('user-x', [])).toEqual({}); + expect(spy).not.toHaveBeenCalled(); + spy.mockRestore(); + }); + + it('never returns a deleted tag', async () => { + const a = await seedAccount(); + const map = await loadTaskTags(a.userId, [a.t1, a.t2, a.t3]); + expect(map[a.t3]).toBeUndefined(); + expect(Object.values(map).flat().some((t) => t.id === a.gone)).toBe(false); + }); + + it('never returns a tag of another account', async () => { + const a = await seedAccount(); + const other = await foreignTagOn(a.t2); + const map = await loadTaskTags(a.userId, [a.t1, a.t2]); + expect(map[a.t2].map((t) => t.id)).toEqual([a.blue]); + // Nor are the tags of `a` returned to the other account. + expect(await loadTaskTags(other.userId, [a.t1, a.t2])).toEqual({ [a.t2]: [{ id: other.tag, name: 'foreign', color: '#4A90A4' }] }); + }); +}); + +describe('queryListTasks', () => { + it('filters by a live tag of the account', async () => { + const a = await seedAccount(); + expect((await queryListTasks(a.userId, a.list, { tagIds: [a.red] })).map((t) => t.id)).toEqual([a.t1]); + expect((await queryListTasks(a.userId, a.list, { tagIds: [a.blue] })).map((t) => t.id)).toEqual([a.t1, a.t2]); + }); + + it('matches nothing on a deleted tag', async () => { + const a = await seedAccount(); + expect(await queryListTasks(a.userId, a.list, { tagIds: [a.gone] })).toEqual([]); + }); + + it('returns every top-level task without a tag filter', async () => { + const a = await seedAccount(); + expect((await queryListTasks(a.userId, a.list, { tagIds: null })).map((t) => t.id)).toEqual([a.t1, a.t2, a.t3]); + }); +}); + +describe('loadSubtasks', () => { + it('groups the live subtasks of the account by parent', async () => { + const a = await seedAccount(); + const map = await loadSubtasks(a.userId, [a.t1, a.t2]); + expect(Object.keys(map)).toEqual([a.t1]); + expect(map[a.t1].map((t) => t.id)).toEqual([a.sub]); + expect(await loadSubtasks(`user-${u()}`, [a.t1])).toEqual({}); + }); +}); + +describe('GET /api/lists/[id]/tasks?tags=', () => { + it('filters by a tag of the account', async () => { + const a = await seedAccount(); + const res = await getTasks(a.userId, a.list, `?tags=${a.red}`); + expect(res.status).toBe(200); + expect((await res.json() as { id: string }[]).map((t) => t.id)).toEqual([a.t1]); + }); + + it('returns an empty list for a tag of another account', async () => { + const a = await seedAccount(); + const other = await foreignTagOn(a.t2); + const res = await getTasks(a.userId, a.list, `?tags=${other.tag}`); + expect(res.status).toBe(200); + expect(await res.json()).toEqual([]); + }); + + it('answers 400 to a malformed id', async () => { + const a = await seedAccount(); + const res = await getTasks(a.userId, a.list, '?tags=pas-un-uuid'); + expect(res.status).toBe(400); + }); + + it('answers 400 to 21 ids and 200 to 20', async () => { + const a = await seedAccount(); + const ids = (n: number) => Array.from({ length: n }, () => u()).join(','); + expect((await getTasks(a.userId, a.list, `?tags=${ids(21)}`)).status).toBe(400); + expect((await getTasks(a.userId, a.list, `?tags=${ids(20)}`)).status).toBe(200); + }); + + it('keeps the other filters with a tag filter', async () => { + const a = await seedAccount(); + await exec('UPDATE sl_tasks SET completed = true WHERE id = $1', [a.t1]); + const res = await getTasks(a.userId, a.list, `?tags=${a.blue}&completed=false`); + expect((await res.json() as { id: string }[]).map((t) => t.id)).toEqual([a.t2]); + }); + + it('still answers 404 for a list of another account', async () => { + const a = await seedAccount(); + const res = await getTasks(`user-${u()}`, a.list, ''); + expect(res.status).toBe(404); + }); +}); diff --git a/web/src/lib/taskQueries.ts b/web/src/lib/taskQueries.ts new file mode 100644 index 0000000..a6d9bd6 --- /dev/null +++ b/web/src/lib/taskQueries.ts @@ -0,0 +1,123 @@ +// Task reads shared by the list page (web/src/app/(app)/lists/[id]/page.tsx) +// and GET /api/lists/[id]/tasks (#179). Every query is scoped to the account: +// tasks by sl_tasks.user_id, tags by sl_tags.user_id and deleted_at IS NULL. + +import { db } from '@/db/client'; +import { slTasks, slTags, slTaskTags } from '@/db/schema'; +import { eq, and, isNull, asc, desc, inArray, lte, type SQL } from 'drizzle-orm'; +import type { TagPill } from './types'; + +export interface ListTaskFilters { + completed?: boolean; + priority?: number; + // Tasks due on or before this date. + dueBefore?: Date; + // Tasks carrying at least one of these tags (ids already validated). + tagIds?: string[] | null; + sortBy?: string; + sortOrder?: string; +} + +export type TaskTagPill = TagPill; + +function sortColumn(sortBy: string | undefined) { + switch (sortBy) { + case 'priority': return slTasks.priority; + case 'dueDate': return slTasks.dueDate; + case 'createdAt': return slTasks.createdAt; + case 'title': return slTasks.title; + default: return slTasks.position; + } +} + +// Top-level tasks of a list, filtered and sorted. The caller has checked that +// the list belongs to the account. +export async function queryListTasks(userId: string, listId: string, filters: ListTaskFilters = {}) { + const conditions: SQL[] = [ + eq(slTasks.listId, listId), + eq(slTasks.userId, userId), + isNull(slTasks.deletedAt), + isNull(slTasks.parentId), + ]; + + if (filters.completed !== undefined) { + conditions.push(eq(slTasks.completed, filters.completed)); + } + if (filters.priority !== undefined && Number.isInteger(filters.priority)) { + conditions.push(eq(slTasks.priority, filters.priority)); + } + if (filters.dueBefore && !Number.isNaN(filters.dueBefore.getTime())) { + conditions.push(lte(slTasks.dueDate, filters.dueBefore)); + } + if (filters.tagIds && filters.tagIds.length > 0) { + // Only a live tag of this account can select a task: an id from another + // account, or a deleted tag, matches nothing. + const tagged = db + .select({ taskId: slTaskTags.taskId }) + .from(slTaskTags) + .innerJoin(slTags, eq(slTags.id, slTaskTags.tagId)) + .where(and( + inArray(slTaskTags.tagId, filters.tagIds), + eq(slTags.userId, userId), + isNull(slTags.deletedAt), + )); + conditions.push(inArray(slTasks.id, tagged)); + } + + const orderFn = filters.sortOrder === 'desc' ? desc : asc; + return db + .select() + .from(slTasks) + .where(and(...conditions)) + .orderBy(orderFn(sortColumn(filters.sortBy))); +} + +// Live subtasks of the given parents, grouped by parent id. +export async function loadSubtasks(userId: string, parentIds: string[]) { + const map: Record = {}; + if (parentIds.length === 0) return map; + const rows = await db + .select() + .from(slTasks) + .where(and( + eq(slTasks.userId, userId), + isNull(slTasks.deletedAt), + inArray(slTasks.parentId, parentIds), + )) + .orderBy(asc(slTasks.position)); + for (const row of rows) { + if (!row.parentId) continue; + (map[row.parentId] ??= []).push(row); + } + return map; +} + +// Tags of the given tasks, grouped by task id, in one query. Deleted tags and +// tags of another account never appear. +export async function loadTaskTags(userId: string, taskIds: string[]) { + const map: Record = {}; + if (taskIds.length === 0) return map; + const rows = await db + .select({ taskId: slTaskTags.taskId, id: slTags.id, name: slTags.name, color: slTags.color }) + .from(slTaskTags) + .innerJoin(slTags, eq(slTags.id, slTaskTags.tagId)) + .where(and( + inArray(slTaskTags.taskId, taskIds), + eq(slTags.userId, userId), + isNull(slTags.deletedAt), + )) + .orderBy(asc(slTags.name)); + for (const { taskId, ...tag } of rows) { + (map[taskId] ??= []).push(tag); + } + return map; +} + +// Live tags of the account, by name (tag picker of a task). +export async function loadAccountTags(userId: string): Promise { + return db + .select({ id: slTags.id, name: slTags.name, color: slTags.color }) + .from(slTags) + .where(and(eq(slTags.userId, userId), isNull(slTags.deletedAt))) + .orderBy(asc(slTags.name)); +} diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index c44b140..d0a079e 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -39,3 +39,10 @@ export interface Tag { createdAt: Date | string; deletedAt: Date | string | null; } + +// A tag as shown on a task (pill) and in the tag picker. +export interface TagPill { + id: string; + name: string; + color: string; +} diff --git a/web/src/lib/validators.test.ts b/web/src/lib/validators.test.ts index 1bad621..7352680 100644 --- a/web/src/lib/validators.test.ts +++ b/web/src/lib/validators.test.ts @@ -1,6 +1,6 @@ import { randomUUID as u } from 'node:crypto'; import { describe, it, expect } from 'vitest'; -import { syncPushSchema, reorderSchema, assignTagsSchema, SYNC_MAX_OPERATIONS } from './validators'; +import { syncPushSchema, reorderSchema, assignTagsSchema, SYNC_MAX_OPERATIONS, tagFilterSchema, parseTagFilter, TAG_FILTER_MAX } from './validators'; // Length bounds checked before the elements (#147). @@ -81,3 +81,41 @@ describe('assignTagsSchema', () => { expect(assignTagsSchema.safeParse({ tagIds: Array.from({ length: 100 }, () => u()) }).success).toBe(true); }); }); + +describe('tagFilterSchema / parseTagFilter (#179)', () => { + it('bounds the filter at 20 tags', () => { + expect(TAG_FILTER_MAX).toBe(20); + }); + + it('accepts 20 ids and refuses 21 with a single issue', () => { + expect(tagFilterSchema.safeParse(Array.from({ length: 20 }, () => u())).success).toBe(true); + const r = tagFilterSchema.safeParse(Array.from({ length: 21 }, () => u())); + expect(r.success).toBe(false); + expect(r.error!.issues).toHaveLength(1); + expect(r.error!.issues[0].code).toBe('too_big'); + }); + + it('checks the count before the ids: 10000 invalid ids give one issue', () => { + const r = tagFilterSchema.safeParse(Array.from({ length: 10_000 }, () => 'x')); + expect(r.success).toBe(false); + expect(r.error!.issues).toHaveLength(1); + }); + + it('treats an absent or empty value as no filter', () => { + expect(parseTagFilter(null)).toEqual({ ok: true, tagIds: null }); + expect(parseTagFilter(undefined)).toEqual({ ok: true, tagIds: null }); + expect(parseTagFilter('')).toEqual({ ok: true, tagIds: null }); + }); + + it('splits comma-separated ids', () => { + const a = u(); + const b = u(); + expect(parseTagFilter(`${a},${b}`)).toEqual({ ok: true, tagIds: [a, b] }); + }); + + it('refuses a malformed id, an empty element and 21 ids', () => { + expect(parseTagFilter('pas-un-uuid').ok).toBe(false); + expect(parseTagFilter(`${u()},`).ok).toBe(false); + expect(parseTagFilter(Array.from({ length: 21 }, () => u()).join(',')).ok).toBe(false); + }); +}); diff --git a/web/src/lib/validators.ts b/web/src/lib/validators.ts index 02f148b..aab19b0 100644 --- a/web/src/lib/validators.ts +++ b/web/src/lib/validators.ts @@ -60,6 +60,26 @@ export const assignTagsSchema = z.object({ tagIds: z.array(z.unknown()).min(1).max(100).pipe(z.array(z.string().uuid())), }).strict(); +// Tag filter of GET /api/lists/[id]/tasks and of the list page (`?tags=a,b`). +// Same bound-first pattern: the count is checked before each id is parsed. +export const TAG_FILTER_MAX = 20; + +export const tagFilterSchema = z + .array(z.unknown()) + .min(1) + .max(TAG_FILTER_MAX) + .pipe(z.array(z.string().uuid())); + +// `?tags=` absent or empty: no filter (null). Otherwise the comma-separated +// ids, validated by tagFilterSchema. +export function parseTagFilter( + raw: string | null | undefined, +): { ok: true; tagIds: string[] | null } | { ok: false } { + if (raw === null || raw === undefined || raw === '') return { ok: true, tagIds: null }; + const r = tagFilterSchema.safeParse(raw.split(',')); + return r.success ? { ok: true, tagIds: r.data } : { ok: false }; +} + // Sync // Maximum operations in one POST /api/sync. The app sends batches of 50 -- 2.52.0 From d98b3e5bff4838c7fb14fefb2b4b93e4d1648ba3 Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 21:19:43 -0500 Subject: [PATCH 06/18] fix(web): check the task owner in loadTaskTags too A link joins two owned rows: REVIEW.md asks for the ownership check on both sides, so loadTaskTags also joins sl_tasks on the account (still one query). Refs #179 Co-Authored-By: Claude Opus 5.5 --- web/src/lib/taskQueries.test.ts | 5 +++-- web/src/lib/taskQueries.ts | 7 +++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/web/src/lib/taskQueries.test.ts b/web/src/lib/taskQueries.test.ts index fc85fc0..342091e 100644 --- a/web/src/lib/taskQueries.test.ts +++ b/web/src/lib/taskQueries.test.ts @@ -111,8 +111,9 @@ describe('loadTaskTags', () => { const other = await foreignTagOn(a.t2); const map = await loadTaskTags(a.userId, [a.t1, a.t2]); expect(map[a.t2].map((t) => t.id)).toEqual([a.blue]); - // Nor are the tags of `a` returned to the other account. - expect(await loadTaskTags(other.userId, [a.t1, a.t2])).toEqual({ [a.t2]: [{ id: other.tag, name: 'foreign', color: '#4A90A4' }] }); + // The task side is checked too: the other account gets nothing for tasks + // of `a`, its own tag included. + expect(await loadTaskTags(other.userId, [a.t1, a.t2])).toEqual({}); }); }); diff --git a/web/src/lib/taskQueries.ts b/web/src/lib/taskQueries.ts index a6d9bd6..3021535 100644 --- a/web/src/lib/taskQueries.ts +++ b/web/src/lib/taskQueries.ts @@ -92,8 +92,9 @@ export async function loadSubtasks(userId: string, parentIds: string[]) { return map; } -// Tags of the given tasks, grouped by task id, in one query. Deleted tags and -// tags of another account never appear. +// Tags of the given tasks, grouped by task id, in one query. Ownership is +// checked on both sides of the link: deleted tags, tags of another account and +// tasks of another account never appear. export async function loadTaskTags(userId: string, taskIds: string[]) { const map: Record = {}; if (taskIds.length === 0) return map; @@ -101,8 +102,10 @@ export async function loadTaskTags(userId: string, taskIds: string[]) { .select({ taskId: slTaskTags.taskId, id: slTags.id, name: slTags.name, color: slTags.color }) .from(slTaskTags) .innerJoin(slTags, eq(slTags.id, slTaskTags.tagId)) + .innerJoin(slTasks, eq(slTasks.id, slTaskTags.taskId)) .where(and( inArray(slTaskTags.taskId, taskIds), + eq(slTasks.userId, userId), eq(slTags.userId, userId), isNull(slTags.deletedAt), )) -- 2.52.0 From 55d05046ee43f7289096f30d52a58b33156f19ac Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 21:26:08 -0500 Subject: [PATCH 07/18] fix(sync): propagate tag link removals both ways and refuse foreign ids App: setTagsForTask diffs with the local links and writes one taskTag delete per removed link and one create per added link; addTagToTask and removeTagFromTask write their entry and request a sync. The pull aligns the links of every pulled task on the set the server sent, by direct writes on task_tags in one transaction, sparing links with an unsent taskTag entry (pure rule alignedTagIds in syncRules.ts). Server: every link add or removal (REST routes and the taskTag case of POST /api/sync) moves sl_tasks.updatedAt, so GET /api/sync sends the task with its whole set of links. Task and tag creates in POST /api/sync refuse an id taken by another account (assertIdNotTaken) instead of answering applied without writing. Refs #180 Refs #168 Co-Authored-By: Claude Opus 5.5 --- src/db/repository/tags.ts | 30 ++-- src/services/syncClient.ts | 91 +++++++++--- src/services/syncRules.ts | 63 +++++++++ tests/smoke.test.cjs | 41 ++++++ tests/syncRules.test.mjs | 56 ++++++++ web/src/app/api/sync/route.test.ts | 129 +++++++++++++++++- web/src/app/api/sync/route.ts | 29 ++-- .../app/api/tasks/[id]/tags/[tagId]/route.ts | 14 +- web/src/app/api/tasks/[id]/tags/route.ts | 17 ++- 9 files changed, 428 insertions(+), 42 deletions(-) diff --git a/src/db/repository/tags.ts b/src/db/repository/tags.ts index 12b2f42..419ec51 100644 --- a/src/db/repository/tags.ts +++ b/src/db/repository/tags.ts @@ -1,9 +1,10 @@ -import { eq, and } from 'drizzle-orm'; +import { eq, and, inArray } from 'drizzle-orm'; import { db } from '../client'; import { tags, taskTags } from '../schema'; import { randomUUID } from '@/src/lib/uuid'; import { truncate } from '@/src/lib/validation'; import { requestSync } from '@/src/services/syncTrigger'; +import { tagLinkDiff } from '@/src/services/syncRules'; import { writeOutboxEntry } from './outbox'; export async function getAllTags() { @@ -47,24 +48,37 @@ export async function getTagsForTask(taskId: string) { } export async function setTagsForTask(taskId: string, tagIds: string[]) { - await db.delete(taskTags).where(eq(taskTags.taskId, taskId)); - if (tagIds.length > 0) { - await db.insert(taskTags).values( - tagIds.map((tagId) => ({ taskId, tagId })) - ); + const current = await db + .select({ tagId: taskTags.tagId }) + .from(taskTags) + .where(eq(taskTags.taskId, taskId)); + const { added, removed } = tagLinkDiff(current.map((r) => r.tagId), tagIds); + if (removed.length > 0) { + await db + .delete(taskTags) + .where(and(eq(taskTags.taskId, taskId), inArray(taskTags.tagId, removed))); } - // Send individual taskTag create operations (server expects entityId=taskId, data.tagId) - for (const tagId of tagIds) { + if (added.length > 0) { + await db.insert(taskTags).values(added.map((tagId) => ({ taskId, tagId }))).onConflictDoNothing(); + } + // One taskTag operation per changed link (server expects entityId=taskId, + // data.tagId): a removal must reach the server too (#180) + for (const tagId of removed) { + writeOutboxEntry('taskTag', taskId, 'delete', { tagId }).then(requestSync).catch(() => {}); + } + for (const tagId of added) { writeOutboxEntry('taskTag', taskId, 'create', { tagId }).then(requestSync).catch(() => {}); } } export async function addTagToTask(taskId: string, tagId: string) { await db.insert(taskTags).values({ taskId, tagId }).onConflictDoNothing(); + writeOutboxEntry('taskTag', taskId, 'create', { tagId }).then(requestSync).catch(() => {}); } export async function removeTagFromTask(taskId: string, tagId: string) { await db .delete(taskTags) .where(and(eq(taskTags.taskId, taskId), eq(taskTags.tagId, tagId))); + writeOutboxEntry('taskTag', taskId, 'delete', { tagId }).then(requestSync).catch(() => {}); } diff --git a/src/services/syncClient.ts b/src/services/syncClient.ts index c2df178..8ce63eb 100644 --- a/src/services/syncClient.ts +++ b/src/services/syncClient.ts @@ -1,4 +1,4 @@ -import { asc, eq, inArray, isNull, not } from 'drizzle-orm'; +import { and, asc, eq, inArray, isNull, not } from 'drizzle-orm'; import { db } from '@/src/db/client'; import { syncOutbox, lists, tasks, tags, taskTags } from '@/src/db/schema'; import { useSettingsStore } from '@/src/stores/useSettingsStore'; @@ -21,6 +21,8 @@ import { isSynced, parseRetryAfter, sendInBatches, + pendingTagIdsByTask, + alignedTagIds, type PostResponse, } from '@/src/services/syncRules'; import { @@ -177,7 +179,16 @@ export async function pullChanges(since: string, tracker: RequestTracker): Promi const data: SyncPullResponse = await res.json(); let appliedChanges = 0; + // Links are not applied one by one: the server sends the whole set of + // links of every task it sends, aligned once all rows are in (#180) + const pulledTaskIds = new Set(); + const serverLinks = new Map>(); for (const change of data.changes) { + if (change.entity_type === 'task_tag') { + collectServerLink(serverLinks, change.payload); + continue; + } + if (change.entity_type === 'task' && change.action !== 'delete') pulledTaskIds.add(change.entity_id); try { await applyChange(change, since); appliedChanges++; @@ -185,6 +196,11 @@ export async function pullChanges(since: string, tracker: RequestTracker): Promi console.warn(`[sync] failed to apply change for ${change.entity_type}/${change.entity_id}:`, err); } } + try { + if (await alignTaskTags(pulledTaskIds, serverLinks)) appliedChanges++; + } catch (err) { + console.warn('[sync] failed to align task tags:', err); + } // Update last sync timestamp if (data.sync_token) { @@ -213,9 +229,7 @@ async function applyChange(change: SyncPullChange, since: string): Promise case 'tag': await applyTagChange(entity_id, action, payload); break; - case 'task_tag': - await applyTaskTagChange(entity_id, action, payload); - break; + // task_tag changes are aligned per task by pullChanges (alignTaskTags) } } @@ -285,23 +299,66 @@ async function applyTagChange(id: string, action: string, payload: Record) { - const taskId = payload.task_id as string; - const tagId = payload.tag_id as string; +function collectServerLink(serverLinks: Map>, payload: Record) { + const taskId = payload.task_id; + const tagId = payload.tag_id; + if (typeof taskId !== 'string' || typeof tagId !== 'string') return; + const set = serverLinks.get(taskId) ?? new Set(); + set.add(tagId); + serverLinks.set(taskId, set); +} - if (action === 'delete') { - await db - .delete(taskTags) - .where(eq(taskTags.taskId, taskId)); - return; +/** + * Align the links of each pulled task on the set the server sent (#180), so + * that a link removed on the web disappears from the app. Links with an + * unsent taskTag entry keep their local state (alignedTagIds). Direct writes + * on task_tags in one transaction: never the tags.ts helpers nor the outbox, + * which would send each received change back and request another sync. + * Returns true when a link was written. + */ +async function alignTaskTags(taskIds: Set, serverLinks: Map>): Promise { + if (taskIds.size === 0) return false; + + const pendingRows = await db + .select({ entityType: syncOutbox.entityType, entityId: syncOutbox.entityId, payload: syncOutbox.payload }) + .from(syncOutbox) + .where(and(isNull(syncOutbox.syncedAt), eq(syncOutbox.entityType, 'taskTag'))); + const pending = pendingTagIdsByTask(pendingRows); + // Whole tables, filtered here: no bound-variable limit on large pulls + const localTaskIds = new Set((await db.select({ id: tasks.id }).from(tasks)).map((r) => r.id)); + const localTagIds = new Set((await db.select({ id: tags.id }).from(tags)).map((r) => r.id)); + const localLinks = new Map>(); + for (const { taskId, tagId } of await db.select().from(taskTags)) { + const set = localLinks.get(taskId) ?? new Set(); + set.add(tagId); + localLinks.set(taskId, set); } - // Upsert: insert if not exists - try { - await db.insert(taskTags).values({ taskId, tagId }).onConflictDoNothing(); - } catch { - // Ignore constraint errors + const removals: { taskId: string; tagId: string }[] = []; + const additions: { taskId: string; tagId: string }[] = []; + for (const taskId of taskIds) { + if (!localTaskIds.has(taskId)) continue; + const local = localLinks.get(taskId) ?? new Set(); + const keep = alignedTagIds(serverLinks.get(taskId) ?? [], local, pending.get(taskId) ?? []); + for (const tagId of local) { + if (!keep.has(tagId)) removals.push({ taskId, tagId }); + } + for (const tagId of keep) { + // A link to a tag the device does not hold (deleted) is not written + if (!local.has(tagId) && localTagIds.has(tagId)) additions.push({ taskId, tagId }); + } } + if (removals.length === 0 && additions.length === 0) return false; + + await db.transaction(async (tx) => { + for (const { taskId, tagId } of removals) { + await tx.delete(taskTags).where(and(eq(taskTags.taskId, taskId), eq(taskTags.tagId, tagId))); + } + for (const link of additions) { + await tx.insert(taskTags).values(link).onConflictDoNothing(); + } + }); + return true; } /** diff --git a/src/services/syncRules.ts b/src/services/syncRules.ts index a90bf22..63d9f96 100644 --- a/src/services/syncRules.ts +++ b/src/services/syncRules.ts @@ -595,3 +595,66 @@ export function firstSyncChoice({ dataOwnerId, signedInId, localInboxId }: First if (localInboxId === null || localInboxId === LOCAL_INBOX_ID) return 'merge-or-reset'; return 'reset-only'; } + +// --------------------------------------------------------------------------- +// Task-tag links: removals both ways (#180) +// --------------------------------------------------------------------------- + +/** + * Links a tag edit changes: the tags of `next` absent from `current` are + * added, those of `current` absent from `next` are removed. setTagsForTask + * writes one taskTag create per added tag and one taskTag delete per removed + * one, so that a removal made on the phone reaches the server. + */ +export function tagLinkDiff(current: string[], next: string[]): { added: string[]; removed: string[] } { + const before = new Set(current); + const after = new Set(next); + return { + added: [...after].filter((id) => !before.has(id)), + removed: [...before].filter((id) => !after.has(id)), + }; +} + +/** Outbox row fields read by pendingTagIdsByTask (unsynced entries only). */ +export interface PendingLinkEntry { + entityType: string; + entityId: string; + payload: string; +} + +/** + * Tags of each task that have an unsent taskTag entry, create or delete + * alike: the pull leaves those links as they are locally. + */ +export function pendingTagIdsByTask(entries: PendingLinkEntry[]): Map> { + const out = new Map>(); + for (const entry of entries) { + if (entry.entityType !== 'taskTag') continue; + const tagId = parsePayload(entry.payload)?.tagId; + if (typeof tagId !== 'string') continue; + const set = out.get(entry.entityId) ?? new Set(); + set.add(tagId); + out.set(entry.entityId, set); + } + return out; +} + +/** + * Tags a pulled task keeps locally. The server sends the whole set of links + * of every task it sends (GET /api/sync), and moves the task's updatedAt on + * each link change: the local links are aligned on that set, except the + * links with an unsent taskTag entry, which keep their local state (a link + * added or removed on the phone and not pushed yet is not undone). + */ +export function alignedTagIds(server: Iterable, local: Iterable, pending: Iterable): Set { + const localSet = new Set(local); + const pendingSet = new Set(pending); + const keep = new Set(); + for (const id of server) { + if (!pendingSet.has(id)) keep.add(id); + } + for (const id of pendingSet) { + if (localSet.has(id)) keep.add(id); + } + return keep; +} diff --git a/tests/smoke.test.cjs b/tests/smoke.test.cjs index 6f7004f..41a134b 100644 --- a/tests/smoke.test.cjs +++ b/tests/smoke.test.cjs @@ -422,6 +422,47 @@ check('syncClient.ts wires the #149-#151 sync rules', () => { assert.match(push, /\.where\(inArray\(syncOutbox\.id, markIds\)\);\s*\/\/[^\n]*\s*syncWidgetData\(\)/); }); +// Tag links both ways (#180). The rules are executed by tests/syncRules.test.mjs; +// this check locks their wiring in files node cannot load: the tag helpers +// write a taskTag entry per changed link, and the pull aligns the links by +// direct writes, never through the helpers or the outbox. +check('tag links: removals written by the app, pull aligned without the outbox (#180)', () => { + const read = (rel) => fs.readFileSync(path.join(__dirname, '..', rel), 'utf8'); + const tags = read('src/db/repository/tags.ts'); + const fnOf = (src, name) => { + const start = src.indexOf(`export async function ${name}(`); + assert.ok(start >= 0, `${name} not found`); + const end = src.indexOf('\n}\n', start); + return src.slice(start, end); + }; + const set = fnOf(tags, 'setTagsForTask'); + assert.match(set, /tagLinkDiff\(/, 'setTagsForTask must diff with the local links'); + assert.match(set, /for \(const tagId of removed\) \{\s*writeOutboxEntry\('taskTag', taskId, 'delete', \{ tagId \}\)/); + assert.match(set, /for \(const tagId of added\) \{\s*writeOutboxEntry\('taskTag', taskId, 'create', \{ tagId \}\)/); + assert.ok(!/db\.delete\(taskTags\)\.where\(eq\(taskTags\.taskId, taskId\)\)/.test(set), 'setTagsForTask must not wipe every link'); + assert.match(fnOf(tags, 'addTagToTask'), /writeOutboxEntry\('taskTag', taskId, 'create', \{ tagId \}\)\.then\(requestSync\)/); + assert.match(fnOf(tags, 'removeTagFromTask'), /writeOutboxEntry\('taskTag', taskId, 'delete', \{ tagId \}\)\.then\(requestSync\)/); + + const client = read('src/services/syncClient.ts'); + const start = client.indexOf('async function alignTaskTags('); + assert.ok(start >= 0, 'alignTaskTags not found'); + const align = client.slice(start, client.indexOf('\n}\n', start)); + for (const banned of ['setTagsForTask', 'addTagToTask', 'removeTagFromTask', 'writeOutboxEntry', 'queueOutboxEntry', 'requestSync']) { + assert.ok(!align.includes(banned), `alignTaskTags must not call ${banned}`); + } + assert.match(align, /alignedTagIds\(/, 'alignTaskTags must use the pure rule'); + assert.match(align, /pendingTagIdsByTask\(/, 'alignTaskTags must spare links with an unsent entry'); + assert.match(align, /isNull\(syncOutbox\.syncedAt\)/, 'only unsent entries are pending'); + assert.match(align, /await db\.transaction\(async \(tx\) => \{[^]*tx\.delete\(taskTags\)[^]*tx\.insert\(taskTags\)/, 'links written directly, in one transaction'); + assert.ok(!/from '@\/src\/db\/repository\/tags'/.test(client), 'syncClient.ts must not import the tag helpers'); + // The pull collects the links and aligns every pulled task once + const pull = client.slice(client.indexOf('export async function pullChanges('), client.indexOf('\nasync function applyChange(')); + assert.match(pull, /if \(change\.entity_type === 'task_tag'\) \{\s*collectServerLink\(serverLinks, change\.payload\);\s*continue;\s*\}/); + assert.match(pull, /pulledTaskIds\.add\(change\.entity_id\)/); + assert.match(pull, /await alignTaskTags\(pulledTaskIds, serverLinks\)/); + assert.ok(!/applyTaskTagChange/.test(client), 'links are no longer applied one by one'); +}); + // 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 7dcad55..338a3d4 100644 --- a/tests/syncRules.test.mjs +++ b/tests/syncRules.test.mjs @@ -11,6 +11,9 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { SYNC_EPOCH, + tagLinkDiff, + pendingTagIdsByTask, + alignedTagIds, pulledListValues, pulledTaskValues, pulledTagValues, @@ -889,3 +892,56 @@ test('firstSyncChoice: data of A, signed in to B gives reset-only (regression)', 'merge-or-reset', ); }); + +// --------------------------------------------------------------------------- +// Task-tag links: removals both ways (#180) +// --------------------------------------------------------------------------- + +const sorted = (set) => [...set].sort(); + +test('alignedTagIds: server {a}, local {a, b}, nothing pending -> keep {a} (web removal arrives)', () => { + assert.deepEqual(sorted(alignedTagIds(['a'], ['a', 'b'], [])), ['a']); +}); + +test('alignedTagIds: local {a, b} with create b pending -> keep {a, b}', () => { + assert.deepEqual(sorted(alignedTagIds(['a'], ['a', 'b'], ['b'])), ['a', 'b']); +}); + +test('alignedTagIds: server {a, b}, delete b pending -> keep {a} (phone removal not undone)', () => { + // The phone removed b: it is absent locally and has a pending entry + assert.deepEqual(sorted(alignedTagIds(['a', 'b'], ['a'], ['b'])), ['a']); +}); + +test('alignedTagIds: server links absent locally are added, empty server set clears', () => { + assert.deepEqual(sorted(alignedTagIds(['a', 'c'], ['a'], [])), ['a', 'c']); + assert.deepEqual(sorted(alignedTagIds([], ['a', 'b'], [])), []); +}); + +test('pendingTagIdsByTask: groups taskTag entries by task, create and delete alike', () => { + const pending = pendingTagIdsByTask([ + { entityType: 'taskTag', entityId: 't1', payload: JSON.stringify({ tagId: 'a' }) }, + { entityType: 'taskTag', entityId: 't1', payload: JSON.stringify({ tagId: 'b' }) }, + { entityType: 'taskTag', entityId: 't2', payload: JSON.stringify({ tagId: 'c' }) }, + { entityType: 'task', entityId: 't1', payload: JSON.stringify({ tagId: 'x' }) }, + { entityType: 'taskTag', entityId: 't3', payload: 'not json' }, + { entityType: 'taskTag', entityId: 't3', payload: JSON.stringify({}) }, + ]); + assert.deepEqual(sorted(pending.get('t1')), ['a', 'b']); + assert.deepEqual(sorted(pending.get('t2')), ['c']); + assert.equal(pending.has('t3'), false); +}); + +test('tagLinkDiff: a removed tag is listed (setTagsForTask writes a taskTag delete)', () => { + assert.deepEqual(tagLinkDiff(['a', 'b'], ['a']), { added: [], removed: ['b'] }); + assert.deepEqual(tagLinkDiff(['a'], ['a', 'c']), { added: ['c'], removed: [] }); + assert.deepEqual(tagLinkDiff(['a', 'b'], ['b', 'c']), { added: ['c'], removed: ['a'] }); + assert.deepEqual(tagLinkDiff(['a'], ['a']), { added: [], removed: [] }); +}); + +test('phone removal then pull: the delete entry keeps the link removed until pushed', () => { + // setTagsForTask(['a']) on a task linked to {a, b}: b is removed locally + const { removed } = tagLinkDiff(['a', 'b'], ['a']); + const pending = pendingTagIdsByTask(removed.map((tagId) => ({ entityType: 'taskTag', entityId: 't', payload: JSON.stringify({ tagId }) }))); + // A pull still carrying b on the server side does not bring it back + assert.deepEqual(sorted(alignedTagIds(['a', 'b'], ['a'], pending.get('t'))), ['a']); +}); diff --git a/web/src/app/api/sync/route.test.ts b/web/src/app/api/sync/route.test.ts index 5baa212..0871538 100644 --- a/web/src/app/api/sync/route.test.ts +++ b/web/src/app/api/sync/route.test.ts @@ -43,7 +43,10 @@ vi.mock('@/lib/idempotency', async (importOriginal) => { }; }); -const { POST } = await import('./route'); +const { GET, POST } = await import('./route'); +const { POST: postTaskTags } = await import('../tasks/[id]/tags/route'); +const { DELETE: deleteTaskTag } = await import('../tasks/[id]/tags/[tagId]/route'); +const { NextRequest } = await import('next/server'); type Op = [entityType: string, action: string, entityId: string, data?: Record]; @@ -680,3 +683,127 @@ describe('POST /api/sync: open pages notified over WebSocket (#177)', () => { expect(calls).toEqual([]); }); }); + +describe('task-tag links move the task\'s updatedAt (#180)', () => { + const OLD = '2020-01-01T00:00:00.000Z'; + + // Put the task back in the past, so that any write that moves it shows. + async function age(taskId: string) { + await h.pg.query('update sl_tasks set updated_at=$1 where id=$2', [OLD, taskId]); + } + + async function updatedAt(taskId: string): Promise { + const r = await row<{ t: Date }>('select updated_at t from sl_tasks where id=$1', [taskId]); + return new Date(r!.t).toISOString(); + } + + // GET /api/sync since OLD + 1 s, as the account: the task and its links. + async function pulled(userId: string, taskId: string) { + h.userId = userId; + const since = new Date(new Date(OLD).getTime() + 1000).toISOString(); + const res = await GET(new NextRequest(`http://localhost/api/sync?since=${encodeURIComponent(since)}`)); + expect(res.status).toBe(200); + const { changes } = await res.json() as { changes: { entity_type: string; entity_id: string; payload: Record }[] }; + return { + task: changes.some((c) => c.entity_type === 'task' && c.entity_id === taskId), + tags: changes + .filter((c) => c.entity_type === 'task_tag' && c.payload.task_id === taskId) + .map((c) => c.payload.tag_id as string) + .sort(), + }; + } + + async function newTag(userId: string): Promise { + const id = u(); + expect(await push(userId, [['tag', 'create', id, { name: `t-${id.slice(0, 4)}`, color: '#4A90A4' }]])).toEqual(['applied']); + return id; + } + + it('POST /api/sync taskTag create and delete move updatedAt; the pull sends the whole set', async () => { + const { B } = await seed(); + const extra = await newTag(B.userId); + + await age(B.task); + expect(await push(B.userId, [['taskTag', 'create', B.task, { tagId: extra }]])).toEqual(['applied']); + expect(await updatedAt(B.task)).not.toBe(OLD); + expect(await pulled(B.userId, B.task)).toEqual({ task: true, tags: [B.tag, extra].sort() }); + + await age(B.task); + expect(await push(B.userId, [['taskTag', 'delete', B.task, { tagId: B.tag }]])).toEqual(['applied']); + expect(await updatedAt(B.task)).not.toBe(OLD); + expect(await pulled(B.userId, B.task)).toEqual({ task: true, tags: [extra] }); + + // Last link removed: the task still comes, with an empty set + await age(B.task); + expect(await push(B.userId, [['taskTag', 'delete', B.task, { tagId: extra }]])).toEqual(['applied']); + expect(await pulled(B.userId, B.task)).toEqual({ task: true, tags: [] }); + }); + + it('REST add and remove of a link move updatedAt; the pull sends the whole set', async () => { + const { B } = await seed(); + const extra = await newTag(B.userId); + h.userId = B.userId; + + await age(B.task); + const added = await postTaskTags( + new Request('http://localhost', { method: 'POST', body: JSON.stringify({ tagIds: [extra] }) }), + { params: Promise.resolve({ id: B.task }) }, + ); + expect(added.status).toBe(201); + expect(await updatedAt(B.task)).not.toBe(OLD); + expect(await pulled(B.userId, B.task)).toEqual({ task: true, tags: [B.tag, extra].sort() }); + + await age(B.task); + h.userId = B.userId; + const removed = await deleteTaskTag( + new Request('http://localhost', { method: 'DELETE' }), + { params: Promise.resolve({ id: B.task, tagId: B.tag }) }, + ); + expect(removed.status).toBe(200); + expect(await updatedAt(B.task)).not.toBe(OLD); + expect(await pulled(B.userId, B.task)).toEqual({ task: true, tags: [extra] }); + }); + + it('a refused link change leaves another account\'s task untouched', async () => { + const { A, B } = await seed(); + await age(A.task); + expect(await push(B.userId, [['taskTag', 'delete', A.task, { tagId: A.tag }]])).toEqual(['skipped']); + h.userId = B.userId; + const res = await deleteTaskTag( + new Request('http://localhost', { method: 'DELETE' }), + { params: Promise.resolve({ id: A.task, tagId: A.tag }) }, + ); + expect(res.status).toBe(404); + expect(await updatedAt(A.task)).toBe(OLD); + }); +}); + +describe('POST /api/sync: task and tag creation with an id taken by another account (#180)', () => { + it('refuses a task create on another account\'s task id, without notification', async () => { + const { A, B } = await seed(); + h.notified.length = 0; + const [result] = await pushResults(B.userId, [['task', 'create', A.task, { title: 'stolen', listId: B.list }]]); + expect(result.status).toBe('skipped'); + expect(result.error).toBeDefined(); + expect(h.notified).toEqual([]); + expect(await row('select user_id, title from sl_tasks where id=$1', [A.task])).toEqual({ user_id: A.userId, title: 'A task' }); + }); + + it('refuses a tag create on another account\'s tag id, without notification', async () => { + const { A, B } = await seed(); + h.notified.length = 0; + const [result] = await pushResults(B.userId, [['tag', 'create', A.tag, { name: 'stolen', color: '#4A90A4' }]]); + expect(result.status).toBe('skipped'); + expect(result.error).toBeDefined(); + expect(h.notified).toEqual([]); + expect(await row('select user_id, name from sl_tags where id=$1', [A.tag])).toEqual({ user_id: A.userId, name: 'a-tag' }); + }); + + it('still applies a create pushed again on the caller\'s own ids (initialMerge)', async () => { + const { B } = await seed(); + expect(await push(B.userId, [ + ['task', 'create', B.task, { title: 'B task', listId: B.list }], + ['tag', 'create', B.tag, { name: 'b-tag', color: '#8BA889' }], + ])).toEqual(['applied', 'applied']); + }); +}); diff --git a/web/src/app/api/sync/route.ts b/web/src/app/api/sync/route.ts index 2972174..87a8396 100644 --- a/web/src/app/api/sync/route.ts +++ b/web/src/app/api/sync/route.ts @@ -282,6 +282,9 @@ async function processOperation(op: SyncOperation, userId: string, ctx: RequestC case 'task': { if (action === 'create') { const d = taskCreateData.parse(data); + // An id of another account would hit onConflictDoNothing and answer + // `applied` without creating anything (#180) + await assertIdNotTaken(slTasks, entityId, 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). @@ -322,6 +325,7 @@ async function processOperation(op: SyncOperation, userId: string, ctx: RequestC case 'tag': { if (action === 'create') { const d = tagCreateData.parse(data); + await assertIdNotTaken(slTags, entityId, userId); await db.insert(slTags).values({ id: entityId, userId, @@ -349,14 +353,23 @@ async function processOperation(op: SyncOperation, userId: string, ctx: RequestC const { tagId } = taskTagData.parse(data); await verifyOwnership(slTasks, entityId, userId); await verifyTagOwnership(tagId, userId); - if (action === 'create') { - await db.insert(slTaskTags) - .values({ taskId: entityId, tagId }) - .onConflictDoNothing(); - } else if (action === 'delete') { - await db.delete(slTaskTags) - .where(and(eq(slTaskTags.taskId, entityId), eq(slTaskTags.tagId, tagId))); - } + // A link change moves the task's updatedAt: GET /api/sync then sends + // the task with the whole set of its links (#180) + await db.transaction(async (tx) => { + if (action === 'create') { + await tx.insert(slTaskTags) + .values({ taskId: entityId, tagId }) + .onConflictDoNothing(); + } else if (action === 'delete') { + await tx.delete(slTaskTags) + .where(and(eq(slTaskTags.taskId, entityId), eq(slTaskTags.tagId, tagId))); + } else { + return; + } + await tx.update(slTasks) + .set({ updatedAt: now }) + .where(and(eq(slTasks.id, entityId), eq(slTasks.userId, userId))); + }); break; } } diff --git a/web/src/app/api/tasks/[id]/tags/[tagId]/route.ts b/web/src/app/api/tasks/[id]/tags/[tagId]/route.ts index 6d64375..1ac6468 100644 --- a/web/src/app/api/tasks/[id]/tags/[tagId]/route.ts +++ b/web/src/app/api/tasks/[id]/tags/[tagId]/route.ts @@ -27,9 +27,17 @@ export async function DELETE( return NextResponse.json({ error: 'Task not found' }, { status: 404 }); } - await db - .delete(slTaskTags) - .where(and(eq(slTaskTags.taskId, taskId), eq(slTaskTags.tagId, tagId))); + // Remove the link and move the task's updatedAt: GET /api/sync then sends + // the task with the whole set of its links, without this one (#180) + await db.transaction(async (tx) => { + await tx + .delete(slTaskTags) + .where(and(eq(slTaskTags.taskId, taskId), eq(slTaskTags.tagId, tagId))); + await tx + .update(slTasks) + .set({ updatedAt: new Date() }) + .where(and(eq(slTasks.id, taskId), eq(slTasks.userId, auth.userId))); + }); notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }); diff --git a/web/src/app/api/tasks/[id]/tags/route.ts b/web/src/app/api/tasks/[id]/tags/route.ts index 4389920..1a08289 100644 --- a/web/src/app/api/tasks/[id]/tags/route.ts +++ b/web/src/app/api/tasks/[id]/tags/route.ts @@ -41,11 +41,18 @@ export async function POST( return NextResponse.json({ error: 'Some tags not found' }, { status: 404 }); } - // Insert (ignore conflicts) - await db - .insert(slTaskTags) - .values(body.data.tagIds.map((tagId) => ({ taskId, tagId }))) - .onConflictDoNothing(); + // Insert (ignore conflicts), and move the task's updatedAt: GET /api/sync + // then sends the task with the whole set of its links (#180) + await db.transaction(async (tx) => { + await tx + .insert(slTaskTags) + .values(body.data.tagIds.map((tagId) => ({ taskId, tagId }))) + .onConflictDoNothing(); + await tx + .update(slTasks) + .set({ updatedAt: new Date() }) + .where(and(eq(slTasks.id, taskId), eq(slTasks.userId, auth.userId))); + }); notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }, { status: 201 }); -- 2.52.0 From bb233c8b5915a488c98e7c70361085010117b199 Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 21:33:14 -0500 Subject: [PATCH 08/18] fix(sync): add updated_at to sl_tags so tag renames and deletions reach the app Migration 0003 adds sl_tags.updated_at (default now(), backfilled from created_at). Every tag write moves it (PUT/DELETE /api/tags/[id], tag update/delete in POST /api/sync), and GET /api/sync pulls tags on updatedAt >= since. Deleting a tag removes its links and moves the touched tasks' updatedAt in the same transaction, so the app realigns their links on the next pull. The user_id ALTERs drizzle-kit re-emitted from the stale 0000 snapshot are dropped from 0003 (0001 applied them); the new snapshot is current. Refs #181 Refs #168 Co-Authored-By: Claude Opus 5.5 --- REVIEW.md | 5 +- web/src/app/api/sync/route.test.ts | 116 +++++ web/src/app/api/sync/route.ts | 28 +- web/src/app/api/tags/[id]/route.ts | 31 +- web/src/db/migrations/0003_tag_updated_at.sql | 6 + web/src/db/migrations/meta/0003_snapshot.json | 417 ++++++++++++++++++ web/src/db/migrations/meta/_journal.json | 7 + web/src/db/schema.ts | 1 + 8 files changed, 593 insertions(+), 18 deletions(-) create mode 100644 web/src/db/migrations/0003_tag_updated_at.sql create mode 100644 web/src/db/migrations/meta/0003_snapshot.json diff --git a/REVIEW.md b/REVIEW.md index 801e8bc..936bb6c 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -113,7 +113,8 @@ 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 -- 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 : le serveur n'a pas d'`updatedAt` sur les étiquettes et renvoie `updated_at` = `created_at`, donc un renommage hors connexion d'étiquette est perdu (check smoke « applyTagChange never keeps a local tag »). — `src/services/syncRules.ts` (`keepLocal`), `src/services/syncClient.ts`, #149 +- 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. — `web/src/db/schema.ts`, `web/src/app/api/sync/route.ts`, `web/src/app/api/tags/[id]/route.ts`, `web/src/app/api/sync/route.test.ts`, #181 - 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`) - Une suppression serveur s'applique toujours, même sur une ligne locale plus récente : le protocole n'a pas de restauration. — `src/services/syncClient.ts`, #149 - `src/services/syncRules.ts` reste sans import, pour que `tests/syncRules.test.mjs` le charge par le type stripping de Node (check smoke `syncRules.ts stays import-free`). `src/services/syncSchedule.ts` et `src/services/syncTrigger.ts` suivent la même règle pour `tests/syncSchedule.test.mjs` (check smoke `syncSchedule.ts and syncTrigger.ts stay import-free`). — `tests/smoke.test.cjs`, `tests/syncRules.test.mjs`, `tests/syncSchedule.test.mjs`, #149, #178 @@ -202,7 +203,7 @@ npm run build - **Tests verts, build cassé.** Le smoke test ne charge ni Babel ni Metro : seul l'export Expo prouve le bundle (PR #118). — `STATE.md` (2026-09-25) - **Le Bearer ouvre le middleware.** Une route d'API qui oublie `requireAuth()` n'est pas protégée par le middleware dès que la requête porte un `Bearer`, même invalide. Lire le début de chaque route ajoutée. — `web/src/middleware.ts` - **`...data` dans un `.set()`.** Jusqu'à #142, le code de sync recopiait `data` dans les mises à jour, et un client pouvait écrire `userId`. Une PR qui touche `processOperation` passe `data` par un schéma de `syncData.ts` avant tout `.set()` ou `.values()`, et un `...d` n'y est acceptable que sur la sortie d'un de ces schémas. — `web/src/app/api/sync/route.ts`, #142 -- **Le serveur n'a pas d'`updatedAt` sur les étiquettes.** `createdAt` sert de date de changement au pull : une étiquette renommée n'est pas renvoyée à l'app. — revue de la PR #58, `web/src/app/api/sync/route.ts` +- **Une écriture d'étiquette sans `updatedAt`.** Jusqu'à #181, le serveur n'avait pas d'`updatedAt` sur les étiquettes et le pull les tirait sur `createdAt` : un renommage ou une suppression n'arrivait pas à l'app (revue de la PR #58). Toute écriture ajoutée sur `sl_tags` avance `updatedAt`, sinon elle reste invisible au pull. — `web/src/app/api/sync/route.ts`, `web/src/app/api/tags/[id]/route.ts`, #181 - **Tests de route dépendants de l'ordre.** Chaque test de `web/src/app/api/sync/route.test.ts` crée ses deux comptes neufs par `seed()` et ne lit ni ne modifie jamais les lignes d'un autre test : un test qui suppose l'état laissé par un autre passe dans un ordre et tombe dans un autre, que le mélange permanent finit par tirer. — `web/src/app/api/sync/route.test.ts`, `web/vitest.config.mts`, #148 - **Polling, pas de requêtes vivantes.** Les écrans relisent SQLite toutes les 500 ms ; un état global de tâches ajouté contourne cette convention. — `CLAUDE.md` « Conventions » - **Widget headless.** `widgetState.ts` reste léger (pas de DB, de drizzle ni de date-fns), le smoke test verrouille son graphe d'import ; un import ajouté rallonge le cold start de chaque tap. — `CLAUDE.md` « Widget Android » diff --git a/web/src/app/api/sync/route.test.ts b/web/src/app/api/sync/route.test.ts index 0871538..1ccbe3a 100644 --- a/web/src/app/api/sync/route.test.ts +++ b/web/src/app/api/sync/route.test.ts @@ -46,6 +46,7 @@ vi.mock('@/lib/idempotency', async (importOriginal) => { const { GET, POST } = await import('./route'); const { POST: postTaskTags } = await import('../tasks/[id]/tags/route'); const { DELETE: deleteTaskTag } = await import('../tasks/[id]/tags/[tagId]/route'); +const { PUT: putTag, DELETE: deleteTag } = await import('../tags/[id]/route'); const { NextRequest } = await import('next/server'); type Op = [entityType: string, action: string, entityId: string, data?: Record]; @@ -807,3 +808,118 @@ describe('POST /api/sync: task and tag creation with an id taken by another acco ])).toEqual(['applied', 'applied']); }); }); + +describe('tags carry an updatedAt that the pull follows (#181)', () => { + const OLD = '2020-01-01T00:00:00.000Z'; + const SINCE = new Date(new Date(OLD).getTime() + 1000).toISOString(); + + // Put the tag and the account's tasks back in the past: only what a write + // moves afterwards comes back in a pull since SINCE. + async function age(userId: string, tagId: string) { + await h.pg.query('update sl_tags set created_at=$1, updated_at=$1 where id=$2', [OLD, tagId]); + await h.pg.query('update sl_tasks set updated_at=$1 where user_id=$2', [OLD, userId]); + } + + type Change = { entity_type: string; entity_id: string; action: string; payload: Record; updated_at: string }; + + async function pull(userId: string): Promise { + h.userId = userId; + const res = await GET(new NextRequest(`http://localhost/api/sync?since=${encodeURIComponent(SINCE)}`)); + expect(res.status).toBe(200); + return (await res.json() as { changes: Change[] }).changes; + } + + function tagChange(changes: Change[], tagId: string) { + return changes.find((c) => c.entity_type === 'tag' && c.entity_id === tagId); + } + + function taskIds(changes: Change[]) { + return changes.filter((c) => c.entity_type === 'task').map((c) => c.entity_id).sort(); + } + + it('the migration backfills updated_at = created_at on existing tags', async () => { + const { PGlite } = await import('electric-sql-pglite'); + const pg = new PGlite(); + const dir = path.join(__dirname, '../../../db/migrations'); + const files = fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort(); + const last = files.findIndex((f) => f.startsWith('0003_')); + expect(last).toBeGreaterThan(0); + const apply = async (f: string) => { + for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) { + if (stmt.trim()) await pg.exec(stmt); + } + }; + for (const f of files.slice(0, last)) await apply(f); + const id = u(); + await pg.query('insert into sl_tags (id, user_id, name, created_at) values ($1, $2, $3, $4)', [id, 'user-old', 'old', OLD]); + await apply(files[last]); + const r = (await pg.query<{ c: Date; u: Date }>('select created_at c, updated_at u from sl_tags where id=$1', [id])).rows[0]; + expect(new Date(r.u).toISOString()).toBe(OLD); + expect(new Date(r.c).toISOString()).toBe(OLD); + await pg.close(); + }); + + it('an untouched tag created before since is not pulled', async () => { + const { B } = await seed(); + await age(B.userId, B.tag); + expect(tagChange(await pull(B.userId), B.tag)).toBeUndefined(); + }); + + it('POST /api/sync tag update: the pull sends the new name, updated_at after the creation', async () => { + const { B } = await seed(); + await age(B.userId, B.tag); + expect(await push(B.userId, [['tag', 'update', B.tag, { name: 'renamed', color: '#4DB6AC' }]])).toEqual(['applied']); + const c = tagChange(await pull(B.userId), B.tag); + expect(c).toMatchObject({ action: 'update', payload: { name: 'renamed', color: '#4DB6AC', created_at: OLD } }); + expect(c!.updated_at > SINCE).toBe(true); + expect(c!.payload.updated_at).toBe(c!.updated_at); + }); + + it('PUT /api/tags/[id]: the pull sends the new name', async () => { + const { B } = await seed(); + await age(B.userId, B.tag); + h.userId = B.userId; + const res = await putTag( + new Request('http://localhost', { method: 'PUT', body: JSON.stringify({ name: 'renamed-web' }) }), + { params: Promise.resolve({ id: B.tag }) }, + ); + expect(res.status).toBe(200); + expect(tagChange(await pull(B.userId), B.tag)).toMatchObject({ action: 'update', payload: { name: 'renamed-web' } }); + }); + + it('POST /api/sync tag delete: the pull sends delete, the links are gone, the touched tasks come back', async () => { + const { B } = await seed(); + // B.tag on B.task (seed) and on B.sub; B.parent stays without it + expect(await push(B.userId, [['taskTag', 'create', B.sub, { tagId: B.tag }]])).toEqual(['applied']); + await age(B.userId, B.tag); + expect(await push(B.userId, [['tag', 'delete', B.tag, { id: B.tag }]])).toEqual(['applied']); + const changes = await pull(B.userId); + expect(tagChange(changes, B.tag)?.action).toBe('delete'); + expect(await row('select count(*)::int c from sl_task_tags where tag_id=$1', [B.tag])).toEqual({ c: 0 }); + expect(taskIds(changes)).toEqual([B.task, B.sub].sort()); + expect(changes.filter((c) => c.entity_type === 'task_tag' && c.payload.tag_id === B.tag)).toEqual([]); + }); + + it('DELETE /api/tags/[id]: the pull sends delete, the links are gone, the touched tasks come back', async () => { + const { B } = await seed(); + await age(B.userId, B.tag); + h.userId = B.userId; + const res = await deleteTag(new Request('http://localhost', { method: 'DELETE' }), { params: Promise.resolve({ id: B.tag }) }); + expect(res.status).toBe(200); + const changes = await pull(B.userId); + expect(tagChange(changes, B.tag)?.action).toBe('delete'); + expect(await row('select count(*)::int c from sl_task_tags where tag_id=$1', [B.tag])).toEqual({ c: 0 }); + expect(taskIds(changes)).toEqual([B.task]); + }); + + it('DELETE /api/tags/[id] on another account\'s tag: 404, its tag, links and tasks untouched', async () => { + const { A, B } = await seed(); + await age(A.userId, A.tag); + h.userId = B.userId; + const res = await deleteTag(new Request('http://localhost', { method: 'DELETE' }), { params: Promise.resolve({ id: A.tag }) }); + expect(res.status).toBe(404); + expect(await row('select deleted_at from sl_tags where id=$1', [A.tag])).toEqual({ deleted_at: null }); + expect(await row('select count(*)::int c from sl_task_tags where tag_id=$1', [A.tag])).toEqual({ c: 1 }); + expect(taskIds(await pull(A.userId))).toEqual([]); + }); +}); diff --git a/web/src/app/api/sync/route.ts b/web/src/app/api/sync/route.ts index 87a8396..e61fe6a 100644 --- a/web/src/app/api/sync/route.ts +++ b/web/src/app/api/sync/route.ts @@ -49,7 +49,7 @@ export async function GET(request: NextRequest) { db .select() .from(slTags) - .where(and(eq(slTags.userId, auth.userId), gte(slTags.createdAt, sinceDate))), + .where(and(eq(slTags.userId, auth.userId), gte(slTags.updatedAt, sinceDate))), ]); // Get task-tag relations for the affected tasks @@ -121,9 +121,9 @@ export async function GET(request: NextRequest) { name: tag.name, color: tag.color, created_at: tag.createdAt.toISOString(), - updated_at: tag.createdAt.toISOString(), + updated_at: tag.updatedAt.toISOString(), }, - updated_at: tag.createdAt.toISOString(), + updated_at: tag.updatedAt.toISOString(), }); } @@ -335,16 +335,28 @@ async function processOperation(op: SyncOperation, userId: string, ctx: RequestC } else if (action === 'update') { const d = tagUpdateData.parse(data); await verifyTagOwnership(entityId, userId); - // Tags have no updatedAt: skip when nothing is left to write + // Nothing left to write: no change, so updatedAt does not move either if (d.name === undefined && d.color === undefined) break; await db.update(slTags) - .set(d) + .set({ ...d, updatedAt: now }) .where(and(eq(slTags.id, entityId), eq(slTags.userId, userId))); } else if (action === 'delete') { await verifyTagOwnership(entityId, userId); - await db.update(slTags) - .set({ deletedAt: now }) - .where(and(eq(slTags.id, entityId), eq(slTags.userId, userId))); + // Same transaction as DELETE /api/tags/[id] (#181): the tag's + // updatedAt brings the delete to the pull, and the tasks that lose a + // link come back in it too, so the app aligns their links. + await db.transaction(async (tx) => { + await tx.update(slTags) + .set({ deletedAt: now, updatedAt: now }) + .where(and(eq(slTags.id, entityId), eq(slTags.userId, userId))); + await tx.update(slTasks) + .set({ updatedAt: now }) + .where(and( + eq(slTasks.userId, userId), + inArray(slTasks.id, tx.select({ id: slTaskTags.taskId }).from(slTaskTags).where(eq(slTaskTags.tagId, entityId))), + )); + await tx.delete(slTaskTags).where(eq(slTaskTags.tagId, entityId)); + }); } break; } diff --git a/web/src/app/api/tags/[id]/route.ts b/web/src/app/api/tags/[id]/route.ts index dfa7af5..8ca7bcc 100644 --- a/web/src/app/api/tags/[id]/route.ts +++ b/web/src/app/api/tags/[id]/route.ts @@ -1,7 +1,7 @@ import { NextResponse } from 'next/server'; import { db } from '@/db/client'; -import { slTags } from '@/db/schema'; -import { eq, and } from 'drizzle-orm'; +import { slTags, slTasks, slTaskTags } from '@/db/schema'; +import { eq, and, inArray } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; import { notifyUserChanged } from '@/lib/ws'; @@ -22,7 +22,7 @@ export async function PUT( const [updated] = await db .update(slTags) - .set(body.data) + .set({ ...body.data, updatedAt: new Date() }) .where(and(eq(slTags.id, id), eq(slTags.userId, auth.userId))) .returning(); @@ -45,11 +45,26 @@ export async function DELETE( const { id } = await params; - const [deleted] = await db - .update(slTags) - .set({ deletedAt: new Date() }) - .where(and(eq(slTags.id, id), eq(slTags.userId, auth.userId))) - .returning(); + // Same transaction as POST /api/sync tag delete (#181): the tag's updatedAt + // brings the delete to the app's pull, and the tasks that lose a link come + // back in it too, so the app aligns their links. + const now = new Date(); + const deleted = await db.transaction(async (tx) => { + const [tag] = await tx + .update(slTags) + .set({ deletedAt: now, updatedAt: now }) + .where(and(eq(slTags.id, id), eq(slTags.userId, auth.userId))) + .returning({ id: slTags.id }); + if (!tag) return null; + await tx.update(slTasks) + .set({ updatedAt: now }) + .where(and( + eq(slTasks.userId, auth.userId), + inArray(slTasks.id, tx.select({ id: slTaskTags.taskId }).from(slTaskTags).where(eq(slTaskTags.tagId, id))), + )); + await tx.delete(slTaskTags).where(eq(slTaskTags.tagId, id)); + return tag; + }); if (!deleted) { return NextResponse.json({ error: 'Not found' }, { status: 404 }); diff --git a/web/src/db/migrations/0003_tag_updated_at.sql b/web/src/db/migrations/0003_tag_updated_at.sql new file mode 100644 index 0000000..5ae0e1d --- /dev/null +++ b/web/src/db/migrations/0003_tag_updated_at.sql @@ -0,0 +1,6 @@ +-- Tags get an updatedAt so that GET /api/sync pulls renames, colour changes +-- and deletions (#181). The user_id ALTERs that drizzle-kit re-emitted from +-- the stale 0000 snapshot were dropped: 0001 already applied them. +ALTER TABLE "sl_tags" ADD COLUMN "updated_at" timestamp with time zone DEFAULT now() NOT NULL;--> statement-breakpoint +-- Existing tags: their last known change is their creation. +UPDATE "sl_tags" SET "updated_at" = "created_at"; diff --git a/web/src/db/migrations/meta/0003_snapshot.json b/web/src/db/migrations/meta/0003_snapshot.json new file mode 100644 index 0000000..a80a8b5 --- /dev/null +++ b/web/src/db/migrations/meta/0003_snapshot.json @@ -0,0 +1,417 @@ +{ + "id": "f15d185b-4478-4cdf-91b9-e281f16fdb3f", + "prevId": "a1bf2951-6318-42a2-adbb-758a703deb0b", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.sl_lists": { + "name": "sl_lists", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "is_inbox": { + "name": "is_inbox", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_sl_lists_user": { + "name": "idx_sl_lists_user", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sl_tags": { + "name": "sl_tags", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'#4A90A4'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_sl_tags_user": { + "name": "idx_sl_tags_user", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sl_task_tags": { + "name": "sl_task_tags", + "schema": "", + "columns": { + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tag_id": { + "name": "tag_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "sl_task_tags_task_id_sl_tasks_id_fk": { + "name": "sl_task_tags_task_id_sl_tasks_id_fk", + "tableFrom": "sl_task_tags", + "tableTo": "sl_tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sl_task_tags_tag_id_sl_tags_id_fk": { + "name": "sl_task_tags_tag_id_sl_tags_id_fk", + "tableFrom": "sl_task_tags", + "tableTo": "sl_tags", + "columnsFrom": [ + "tag_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "sl_task_tags_task_id_tag_id_pk": { + "name": "sl_task_tags_task_id_tag_id_pk", + "columns": [ + "task_id", + "tag_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sl_tasks": { + "name": "sl_tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "completed": { + "name": "completed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "priority": { + "name": "priority", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "due_date": { + "name": "due_date", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "list_id": { + "name": "list_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "parent_id": { + "name": "parent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "recurrence": { + "name": "recurrence", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_sl_tasks_user": { + "name": "idx_sl_tasks_user", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_sl_tasks_list": { + "name": "idx_sl_tasks_list", + "columns": [ + { + "expression": "list_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_sl_tasks_parent": { + "name": "idx_sl_tasks_parent", + "columns": [ + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sl_tasks_list_id_sl_lists_id_fk": { + "name": "sl_tasks_list_id_sl_lists_id_fk", + "tableFrom": "sl_tasks", + "tableTo": "sl_lists", + "columnsFrom": [ + "list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/web/src/db/migrations/meta/_journal.json b/web/src/db/migrations/meta/_journal.json index 5fd5c09..f21ecc8 100644 --- a/web/src/db/migrations/meta/_journal.json +++ b/web/src/db/migrations/meta/_journal.json @@ -22,6 +22,13 @@ "when": 1775649600000, "tag": "0002_cleanup_duplicate_inboxes", "breakpoints": true + }, + { + "idx": 3, + "version": "7", + "when": 1793673039382, + "tag": "0003_tag_updated_at", + "breakpoints": true } ] } \ No newline at end of file diff --git a/web/src/db/schema.ts b/web/src/db/schema.ts index 02fedc7..7eec89e 100644 --- a/web/src/db/schema.ts +++ b/web/src/db/schema.ts @@ -43,6 +43,7 @@ export const slTags = pgTable('sl_tags', { name: text('name').notNull(), color: text('color').notNull().default('#4A90A4'), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(), deletedAt: timestamp('deleted_at', { withTimezone: true }), }, (table) => [ index('idx_sl_tags_user').on(table.userId), -- 2.52.0 From acaad3ba6a6b6755dbe1aaf1e5c0dae3357e171b Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 21:38:09 -0500 Subject: [PATCH 09/18] test(sync): give the migration backfill test room to boot its own PGlite Refs #181 Co-Authored-By: Claude Opus 5.5 --- web/src/app/api/sync/route.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/src/app/api/sync/route.test.ts b/web/src/app/api/sync/route.test.ts index 1ccbe3a..7ed54a1 100644 --- a/web/src/app/api/sync/route.test.ts +++ b/web/src/app/api/sync/route.test.ts @@ -857,7 +857,7 @@ describe('tags carry an updatedAt that the pull follows (#181)', () => { expect(new Date(r.u).toISOString()).toBe(OLD); expect(new Date(r.c).toISOString()).toBe(OLD); await pg.close(); - }); + }, 30_000); // a second PGlite instance boots in seconds, over the 5 s default it('an untouched tag created before since is not pulled', async () => { const { B } = await seed(); -- 2.52.0 From 83cf32a5618bfe76917f4b199aa2639e1feb0c33 Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 21:43:49 -0500 Subject: [PATCH 10/18] feat(web): create, rename, recolor and delete tags in the companion The sidebar's Tags section gets a "Manage tags" mode, on par with the app's Settings: create a tag (name + color from the app palette), rename it, change its color, delete it after a confirmation. A deleted tag leaves the sidebar at once; when it was the active filter, ?tags= leaves the URL. router.refresh() reloads the server data so the task detail view offers new tags without a reload. The logic (palette, name check, list after deletion, URL after the active filter's tag is deleted) lives in the pure helper web/src/lib/tagEditing.ts, covered by vitest; the JSX is not tested. No API route and no dependency change. Refs #182 Refs #168 Co-Authored-By: Claude Opus 5.5 --- web/src/components/Sidebar.tsx | 31 +++- web/src/components/TagManager.tsx | 259 ++++++++++++++++++++++++++++++ web/src/i18n/en.json | 19 ++- web/src/i18n/fr.json | 19 ++- web/src/lib/tagEditing.test.ts | 86 ++++++++++ web/src/lib/tagEditing.ts | 57 +++++++ 6 files changed, 468 insertions(+), 3 deletions(-) create mode 100644 web/src/components/TagManager.tsx create mode 100644 web/src/lib/tagEditing.test.ts create mode 100644 web/src/lib/tagEditing.ts diff --git a/web/src/components/Sidebar.tsx b/web/src/components/Sidebar.tsx index fbf1aa8..c31f649 100644 --- a/web/src/components/Sidebar.tsx +++ b/web/src/components/Sidebar.tsx @@ -12,9 +12,12 @@ import { ChevronDown, ChevronRight, LogOut, + Settings2, } from "lucide-react"; import { useTranslation } from "react-i18next"; import type { List as ListType, Tag as TagType } from "@/lib/types"; +import { removeTagFromList } from "@/lib/tagEditing"; +import { TagManager } from "./TagManager"; // Sidebar tags: a click filters the current view by `?tags=` (one tag at // a time, as in src/components/FilterMenu.tsx of the app); a second click on @@ -79,6 +82,15 @@ export function Sidebar({ lists, tags }: SidebarProps) { const [showNewList, setShowNewList] = useState(false); const [newListName, setNewListName] = useState(""); const [tagsExpanded, setTagsExpanded] = useState(false); + const [managingTags, setManagingTags] = useState(false); + // Tags shown in the sidebar: the server's, minus a tag just deleted until + // router.refresh() brings the new list (#182). Reset when the props change. + const [serverTags, setServerTags] = useState(tags); + const [shownTags, setShownTags] = useState(tags); + if (tags !== serverTags) { + setServerTags(tags); + setShownTags(tags); + } const handleCreateList = async () => { const name = newListName.trim(); @@ -174,7 +186,24 @@ export function Sidebar({ lists, tags }: SidebarProps) { {tagsExpanded && ( - setMobileOpen(false)} /> + {managingTags ? ( + setShownTags((cur) => removeTagFromList(cur, id))} + onClose={() => setManagingTags(false)} + /> + ) : ( + <> + setMobileOpen(false)} /> + + + )} )} diff --git a/web/src/components/TagManager.tsx b/web/src/components/TagManager.tsx new file mode 100644 index 0000000..e66faad --- /dev/null +++ b/web/src/components/TagManager.tsx @@ -0,0 +1,259 @@ +"use client"; + +import { useState } from "react"; +import { usePathname, useRouter, useSearchParams } from "next/navigation"; +import { Check, Pencil, Plus, Trash2, X } from "lucide-react"; +import { useTranslation } from "react-i18next"; +import type { Tag as TagType } from "@/lib/types"; +import { + TAG_COLORS, + DEFAULT_TAG_COLOR, + validateTagName, + urlAfterTagDelete, +} from "@/lib/tagEditing"; + +// Tag management of the companion (#182), as in the app's Settings +// (app/(tabs)/settings.tsx): create, rename, recolor, delete with a +// confirmation. Logic lives in web/src/lib/tagEditing.ts (tested); this JSX +// is not covered by tests. + +type Editing = { mode: "new" } | { mode: "edit"; id: string } | null; + +function TagForm({ + initialName, + initialColor, + onSubmit, + onCancel, +}: { + initialName: string; + initialColor: string; + onSubmit: (name: string, color: string) => Promise; + onCancel: () => void; +}) { + const { t } = useTranslation(); + const [name, setName] = useState(initialName); + const [color, setColor] = useState(initialColor); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const submit = async () => { + if (busy) return; + const check = validateTagName(name); + if (!check.ok) { + setError(t(check.reason === "empty" ? "tag.nameRequired" : "tag.nameTooLong")); + return; + } + setBusy(true); + setError(null); + let ok = false; + try { + ok = await onSubmit(check.name, color); + } catch { + ok = false; + } + setBusy(false); + if (!ok) setError(t("tag.saveError")); + }; + + return ( +
+ { + setName(e.target.value); + setError(null); + }} + onKeyDown={(e) => { + if (e.key === "Enter") submit(); + if (e.key === "Escape") onCancel(); + }} + placeholder={t("tag.namePlaceholder")} + aria-label={t("tag.name")} + aria-invalid={error ? true : undefined} + className="w-full px-2 py-1 text-sm border border-border-light dark:border-border-dark rounded bg-transparent focus:outline-none focus:border-bleu" + /> +
+ {TAG_COLORS.map((c) => ( + + ))} +
+ {error && ( +

+ {error} +

+ )} +
+ + +
+
+ ); +} + +export function TagManager({ + tags, + onDeleted, + onClose, +}: { + tags: TagType[]; + // Called once the API has deleted the tag, so the sidebar drops it at once. + onDeleted: (tagId: string) => void; + onClose: () => void; +}) { + const { t } = useTranslation(); + const router = useRouter(); + const pathname = usePathname(); + const searchParams = useSearchParams(); + const [editing, setEditing] = useState(null); + const [deleteError, setDeleteError] = useState(null); + const [busyId, setBusyId] = useState(null); + + const createTag = async (name: string, color: string) => { + const res = await fetch("/api/tags", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ name, color }), + }); + if (!res.ok) return false; + setEditing(null); + // Reloads the server data: the task detail view offers the new tag. + router.refresh(); + return true; + }; + + const updateTag = async (id: string, name: string, color: string) => { + const res = await fetch(`/api/tags/${id}`, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ name, color }), + }); + if (!res.ok) return false; + setEditing(null); + router.refresh(); + return true; + }; + + const deleteTag = async (tag: TagType) => { + if (busyId) return; + if (!window.confirm(t("tag.deleteConfirm", { name: tag.name }))) return; + setBusyId(tag.id); + setDeleteError(null); + try { + const res = await fetch(`/api/tags/${tag.id}`, { method: "DELETE" }); + if (!res.ok) { + setDeleteError(t("tag.deleteError")); + return; + } + onDeleted(tag.id); + if (editing?.mode === "edit" && editing.id === tag.id) setEditing(null); + const next = urlAfterTagDelete(pathname, searchParams.toString(), tag.id); + if (next !== null) router.replace(next); + router.refresh(); + } catch { + setDeleteError(t("tag.deleteError")); + } finally { + setBusyId(null); + } + }; + + return ( +
+ {tags.length === 0 && editing?.mode !== "new" && ( +

{t("tag.noTags")}

+ )} + {tags.map((tag) => + editing?.mode === "edit" && editing.id === tag.id ? ( + updateTag(tag.id, name, color)} + onCancel={() => setEditing(null)} + /> + ) : ( +
+ + {tag.name} + + +
+ ), + )} + {deleteError && ( +

+ {deleteError} +

+ )} + {editing?.mode === "new" ? ( + setEditing(null)} + /> + ) : ( + + )} + +
+ ); +} diff --git a/web/src/i18n/en.json b/web/src/i18n/en.json index 2fb5887..3ae55e7 100644 --- a/web/src/i18n/en.json +++ b/web/src/i18n/en.json @@ -37,7 +37,24 @@ "label": "Tags:", "none": "None", "add": "+ Tag", - "remove": "Remove tag {{name}}" + "remove": "Remove tag {{name}}", + "manage": "Manage tags", + "doneManaging": "Done", + "newTag": "New tag", + "noTags": "No tags", + "name": "Tag name", + "namePlaceholder": "Tag name...", + "nameRequired": "The name cannot be empty.", + "nameTooLong": "The name cannot exceed 100 characters.", + "color": "Tag color", + "colorOption": "Color {{color}}", + "save": "Save", + "cancel": "Cancel", + "edit": "Edit tag {{name}}", + "delete": "Delete tag {{name}}", + "deleteConfirm": "Are you sure you want to delete the tag \"{{name}}\"? It will be removed from all your tasks.", + "saveError": "The tag could not be saved.", + "deleteError": "The tag could not be deleted." }, "priority": { "none": "None", diff --git a/web/src/i18n/fr.json b/web/src/i18n/fr.json index 6cfebff..d3adf1a 100644 --- a/web/src/i18n/fr.json +++ b/web/src/i18n/fr.json @@ -37,7 +37,24 @@ "label": "Étiquettes :", "none": "Aucune", "add": "+ Étiquette", - "remove": "Retirer l'étiquette {{name}}" + "remove": "Retirer l'étiquette {{name}}", + "manage": "Gérer les étiquettes", + "doneManaging": "Terminer", + "newTag": "Nouvelle étiquette", + "noTags": "Aucune étiquette", + "name": "Nom de l'étiquette", + "namePlaceholder": "Nom de l'étiquette...", + "nameRequired": "Le nom ne peut pas être vide.", + "nameTooLong": "Le nom ne peut pas dépasser 100 caractères.", + "color": "Couleur de l'étiquette", + "colorOption": "Couleur {{color}}", + "save": "Enregistrer", + "cancel": "Annuler", + "edit": "Modifier l'étiquette {{name}}", + "delete": "Supprimer l'étiquette {{name}}", + "deleteConfirm": "Voulez-vous vraiment supprimer l'étiquette « {{name}} » ? Elle sera retirée de toutes vos tâches.", + "saveError": "L'étiquette n'a pas pu être enregistrée.", + "deleteError": "L'étiquette n'a pas pu être supprimée." }, "priority": { "none": "Aucune", diff --git a/web/src/lib/tagEditing.test.ts b/web/src/lib/tagEditing.test.ts new file mode 100644 index 0000000..6272afa --- /dev/null +++ b/web/src/lib/tagEditing.test.ts @@ -0,0 +1,86 @@ +import { describe, it, expect } from 'vitest'; +import { + TAG_COLORS, + DEFAULT_TAG_COLOR, + TAG_NAME_MAX, + validateTagName, + removeTagFromList, + urlAfterTagDelete, +} from './tagEditing'; + +const A = '11111111-1111-4111-8111-111111111111'; +const B = '22222222-2222-4222-8222-222222222222'; + +describe('TAG_COLORS', () => { + it('is the app palette, the first color by default', () => { + expect([...TAG_COLORS]).toEqual(['#4A90A4', '#C17767', '#8BA889', '#D4A574', '#7B68EE', '#E57373', '#4DB6AC']); + expect(DEFAULT_TAG_COLOR).toBe('#4A90A4'); + }); +}); + +describe('validateTagName', () => { + it('refuses an empty name', () => { + expect(validateTagName('')).toEqual({ ok: false, reason: 'empty' }); + }); + + it('refuses a name made of spaces', () => { + expect(validateTagName(' ')).toEqual({ ok: false, reason: 'empty' }); + expect(validateTagName('\t \n')).toEqual({ ok: false, reason: 'empty' }); + }); + + it('accepts and trims a real name', () => { + expect(validateTagName(' Courses ')).toEqual({ ok: true, name: 'Courses' }); + expect(validateTagName('x')).toEqual({ ok: true, name: 'x' }); + }); + + it('accepts the API bound and refuses one character more', () => { + expect(validateTagName('a'.repeat(TAG_NAME_MAX))).toEqual({ ok: true, name: 'a'.repeat(TAG_NAME_MAX) }); + expect(validateTagName('a'.repeat(TAG_NAME_MAX + 1))).toEqual({ ok: false, reason: 'tooLong' }); + // Surrounding spaces do not count against the bound. + expect(validateTagName(` ${'a'.repeat(TAG_NAME_MAX)} `).ok).toBe(true); + }); +}); + +describe('removeTagFromList', () => { + const tags = [ + { id: A, name: 'Alpha', color: '#4A90A4' }, + { id: B, name: 'Beta', color: '#C17767' }, + ]; + + it('removes the deleted tag and keeps the order of the others', () => { + expect(removeTagFromList(tags, A)).toEqual([tags[1]]); + expect(removeTagFromList(tags, B)).toEqual([tags[0]]); + }); + + it('leaves the list as it was for an unknown id, without mutating it', () => { + expect(removeTagFromList(tags, 'other')).toEqual(tags); + removeTagFromList(tags, A); + expect(tags).toHaveLength(2); + }); +}); + +describe('urlAfterTagDelete', () => { + it('drops ?tags= when the deleted tag is the active filter', () => { + expect(urlAfterTagDelete('/lists/x', `?tags=${A}`, A)).toBe('/lists/x'); + expect(urlAfterTagDelete('/lists/x', `tags=${A}`, A)).toBe('/lists/x'); + }); + + it('keeps the other parameters', () => { + expect(urlAfterTagDelete('/lists/x', `?completed=false&tags=${A}&sortBy=title`, A)).toBe( + '/lists/x?completed=false&sortBy=title', + ); + }); + + it('keeps the other tags of a multi-tag filter', () => { + expect(urlAfterTagDelete('/lists/x', `?tags=${A},${B}`, A)).toBe(`/lists/x?tags=${encodeURIComponent(B)}`); + }); + + it('leaves the URL unchanged when another tag is the filter', () => { + expect(urlAfterTagDelete('/lists/x', `?tags=${B}`, A)).toBeNull(); + }); + + it('leaves the URL unchanged without a tag filter', () => { + expect(urlAfterTagDelete('/lists/x', '', A)).toBeNull(); + expect(urlAfterTagDelete('/lists/x', '?completed=true', A)).toBeNull(); + }); +}); diff --git a/web/src/lib/tagEditing.ts b/web/src/lib/tagEditing.ts new file mode 100644 index 0000000..92943bd --- /dev/null +++ b/web/src/lib/tagEditing.ts @@ -0,0 +1,57 @@ +// Pure helpers of the companion tag manager (#182), kept out of the JSX so +// vitest covers them without a DOM: the palette, the name check, the list +// after a deletion and the URL after the active filter's tag is deleted. + +// Same palette as the app's tag modal (app/(tabs)/settings.tsx, TAG_COLORS). +export const TAG_COLORS = [ + '#4A90A4', + '#C17767', + '#8BA889', + '#D4A574', + '#7B68EE', + '#E57373', + '#4DB6AC', +] as const; + +export const DEFAULT_TAG_COLOR = TAG_COLORS[0]; + +// Same bound as createTagSchema / updateTagSchema in validators.ts. +export const TAG_NAME_MAX = 100; + +export type TagNameCheck = + | { ok: true; name: string } + | { ok: false; reason: 'empty' | 'tooLong' }; + +// The name sent to the API: trimmed, neither empty nor made of spaces, at +// most TAG_NAME_MAX characters once trimmed. +export function validateTagName(raw: string): TagNameCheck { + const name = raw.trim(); + if (name.length === 0) return { ok: false, reason: 'empty' }; + if (name.length > TAG_NAME_MAX) return { ok: false, reason: 'tooLong' }; + return { ok: true, name }; +} + +// The tag list once `tagId` is deleted; the other tags keep their order. +export function removeTagFromList(tags: readonly T[], tagId: string): T[] { + return tags.filter((tag) => tag.id !== tagId); +} + +// The URL to show once `tagId` is deleted. `search` is the current query +// string, with or without its leading `?`. When the deleted tag is in the +// `?tags=` filter, it leaves it, and `tags` goes away once empty; the other +// parameters stay. Returns null when the URL does not change. +export function urlAfterTagDelete(pathname: string, search: string, tagId: string): string | null { + const params = new URLSearchParams(search.startsWith('?') ? search.slice(1) : search); + const raw = params.get('tags'); + if (raw === null) return null; + const ids = raw.split(','); + if (!ids.includes(tagId)) return null; + const rest = ids.filter((id) => id !== tagId && id !== ''); + if (rest.length > 0) { + params.set('tags', rest.join(',')); + } else { + params.delete('tags'); + } + const query = params.toString(); + return query ? `${pathname}?${query}` : pathname; +} -- 2.52.0 From 589c01955afc89728b7a7be86f924f2d6eceb6d6 Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 3 Nov 2026 20:01:42 -0500 Subject: [PATCH 11/18] fix(sync): start a run only with room for one POST and the GET Review of PR #184: when the budget freed up one place at a time (requests spread by network latency), every place went to a pull-only run with pushBatches = 0, so a queued backlog was never sent while the device spent 6 GETs a minute. The scheduler now waits for two free places. Tests: a fake server with 300 ms per request (9-batch queue empties within 4 min, no run without a POST place), the 600 s Retry-After bound, and source guards for the `more` signal of pushChanges and the budget of initialMerge. Refs #178 Co-Authored-By: Claude Opus 5.5 --- src/services/syncSchedule.ts | 11 +++++++---- tests/smoke.test.cjs | 5 +++++ tests/syncSchedule.test.mjs | 38 ++++++++++++++++++++++++++++++++++-- 3 files changed, 48 insertions(+), 6 deletions(-) diff --git a/src/services/syncSchedule.ts b/src/services/syncSchedule.ts index e71fc4a..9e11b6a 100644 --- a/src/services/syncSchedule.ts +++ b/src/services/syncSchedule.ts @@ -30,7 +30,7 @@ export interface RequestTracker { export interface SyncRun extends RequestTracker { /** * POST batches this run may send: the remaining budget minus one place for - * the GET of the pull. The rest of the queue goes to the next run. + * the GET of the pull, at least 1. The rest of the queue goes to the next run. */ readonly pushBatches: number; /** True once a 429 suspended the scheduler: the run sends nothing more. */ @@ -125,9 +125,12 @@ export function createSyncScheduler(deps: SchedulerDeps): SyncScheduler { return; } const left = remaining(now); - if (left < 1) { - // The oldest request leaves the window first - arm(sent[0] + BUDGET_WINDOW_MS - now); + if (left < 2) { + // A run needs a place for one POST and one for the GET. Starting with a + // single place would only pull, and a queue whose places free up one by + // one would never be sent (review of PR #184). Wait until the second + // oldest request in the window leaves it. + arm(sent[sent.length - REQUEST_BUDGET + 1] + BUDGET_WINDOW_MS - now); return; } start(left); diff --git a/tests/smoke.test.cjs b/tests/smoke.test.cjs index b51ac94..76096f2 100644 --- a/tests/smoke.test.cjs +++ b/tests/smoke.test.cjs @@ -243,6 +243,11 @@ check('sync on write and every sync go through the scheduler (#178)', () => { assert.match(body, /await scheduler\.beginInitialSync\(\);\s*try \{[^]*\} finally \{\s*scheduler\.endInitialSync\(\);/, `${name} must hold the first-sync state`); } assert.equal((client.match(/pullChanges\(SYNC_EPOCH, scheduler\.tracker\)/g) || []).length, 2, 'the first-sync pulls are counted'); + // Review of PR #184: initialMerge's POST batches count against the budget, + // and pushChanges tells the scheduler when the budget left entries unsent + const merge = client.slice(client.indexOf('async function mergeLocalData('), client.indexOf('export async function initialReset(')); + assert.match(merge, /post: \(batch\) => postBatch\(batch, headers, scheduler\.tracker\),/, 'initialMerge must count its POST batches'); + assert.match(client, /return \{ more: ok && operations\.length > maxBatches \* BATCH_SIZE \};\n\}/, 'pushChanges must report an unsent queue'); }); // Tags must not go through keepLocal: the server's tag updated_at is its diff --git a/tests/syncSchedule.test.mjs b/tests/syncSchedule.test.mjs index 0a3af67..1d78954 100644 --- a/tests/syncSchedule.test.mjs +++ b/tests/syncSchedule.test.mjs @@ -12,6 +12,7 @@ import assert from 'node:assert/strict'; import { BUDGET_WINDOW_MS, DEFAULT_RETRY_AFTER_S, + MAX_RETRY_AFTER_S, REQUEST_BUDGET, createSyncScheduler, } from '../src/services/syncSchedule.ts'; @@ -50,11 +51,15 @@ async function flush() { // A server stand-in: a queue of POST batches, each run pushes up to // ctx.pushBatches of them then pulls once. Records every request time. -function fakeServer(clock, { batches = 0, status = () => 200, duration = 0 } = {}) { - const state = { queue: batches, requests: [], runs: 0, active: 0, maxActive: 0, starts: [] }; +// `latency` is the response time of each request: the requests of one run +// are then spread in time, as on a real network (review of PR #184). +function fakeServer(clock, { batches = 0, status = () => 200, duration = 0, latency = 0 } = {}) { + const state = { queue: batches, requests: [], runs: 0, active: 0, maxActive: 0, starts: [], emptyPushRuns: 0 }; + const respond = () => (latency ? new Promise((resolve) => clock.setTimer(resolve, latency)) : undefined); state.run = async (ctx) => { state.runs++; state.starts.push(clock.now()); + if (state.queue > 0 && ctx.pushBatches < 1) state.emptyPushRuns++; state.active++; state.maxActive = Math.max(state.maxActive, state.active); try { @@ -64,6 +69,7 @@ function fakeServer(clock, { batches = 0, status = () => 200, duration = 0 } = { ctx.request(); state.requests.push(clock.now()); sent++; + await respond(); const s = status('POST'); if (s === 429) { ctx.rateLimited(20); @@ -74,6 +80,7 @@ function fakeServer(clock, { batches = 0, status = () => 200, duration = 0 } = { if (ctx.isSuspended()) return { more: state.queue > 0 }; ctx.request(); state.requests.push(clock.now()); + await respond(); const s = status('GET'); if (s === 429) ctx.rateLimited(20); return { more: state.queue > 0 }; @@ -203,6 +210,21 @@ test('an unsent queue is resumed without a new request once the budget allows', assert.ok(maxInAnyWindow(server.requests) <= REQUEST_BUDGET); }); +test('with 300 ms per request, a 9-batch queue empties in bounded time and no run starts without a POST place', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { batches: 9, latency: 300 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.request(); + // The 30 s foreground interval keeps asking + for (let t = 0; t < 4 * BUDGET_WINDOW_MS; t += 30_000) { + await clock.advance(30_000); + s.request(); + } + assert.equal(server.queue, 0, `${server.queue} batch(es) still queued after 4 min (${server.runs} runs)`); + assert.equal(server.emptyPushRuns, 0, 'a run started with pushBatches = 0 while the queue was not empty'); + assert.ok(maxInAnyWindow(server.requests) <= REQUEST_BUDGET, `max ${maxInAnyWindow(server.requests)} in a window`); +}); + test('after a 429 with Retry-After: 20, no request before 20 s', async () => { const clock = fakeClock(); let first = true; @@ -249,6 +271,18 @@ test('a 429 without a readable Retry-After suspends for the default delay', asyn assert.equal(starts, 2); }); +test('a huge Retry-After is bounded to MAX_RETRY_AFTER_S', async () => { + const clock = fakeClock(); + const server = fakeServer(clock); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.tracker.rateLimited(100_000); + s.request(); + await clock.advance(MAX_RETRY_AFTER_S * 1000 - 1); + assert.equal(server.runs, 0); + await clock.advance(1); + assert.equal(server.runs, 1, 'the scheduler resumes after MAX_RETRY_AFTER_S'); +}); + test('a 429 reported outside a run (initial sync) also suspends the scheduler', async () => { const clock = fakeClock(); const server = fakeServer(clock); -- 2.52.0 From dc479e36186ac9a6aee580a026073123d56a41d1 Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 3 Nov 2026 20:02:20 -0500 Subject: [PATCH 12/18] test(sync): pin the two-place rule of the scheduler A single free place with a queued backlog starts no run until a second place frees up; the condition alone was not pinned by the latency test. Refs #178 Co-Authored-By: Claude Opus 5.5 --- tests/syncSchedule.test.mjs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/syncSchedule.test.mjs b/tests/syncSchedule.test.mjs index 1d78954..14e91df 100644 --- a/tests/syncSchedule.test.mjs +++ b/tests/syncSchedule.test.mjs @@ -225,6 +225,22 @@ test('with 300 ms per request, a 9-batch queue empties in bounded time and no ru assert.ok(maxInAnyWindow(server.requests) <= REQUEST_BUDGET, `max ${maxInAnyWindow(server.requests)} in a window`); }); +test('with a single free place, no run starts until a second one frees up', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { batches: 1 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.tracker.request(); + await clock.advance(1000); + for (let i = 1; i < REQUEST_BUDGET - 1; i++) s.tracker.request(); + s.request(); + await clock.advance(BUDGET_WINDOW_MS - 1001); + assert.equal(server.runs, 0, 'one place left: a run would only pull'); + await clock.advance(1); + assert.equal(server.runs, 1, 'the run starts once the oldest request leaves the window'); + assert.equal(server.emptyPushRuns, 0); + assert.equal(server.queue, 0); +}); + test('after a 429 with Retry-After: 20, no request before 20 s', async () => { const clock = fakeClock(); let first = true; -- 2.52.0 From cc591ba85e5185657ebba1e6862bac834ada4ff2 Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 3 Nov 2026 20:41:32 -0500 Subject: [PATCH 13/18] fix(web): close a socket whose send throws Review of PR #183: the socket was dropped from the client set but left open, outside the heartbeat, so its page was never notified again. terminate() closes it and the page reconnects through onclose. Refs #177 Co-Authored-By: Claude Opus 5.5 --- web/src/lib/ws.test.ts | 4 +++- web/src/lib/ws.ts | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/web/src/lib/ws.test.ts b/web/src/lib/ws.test.ts index c310b71..ab0b2f7 100644 --- a/web/src/lib/ws.test.ts +++ b/web/src/lib/ws.test.ts @@ -12,6 +12,7 @@ type FakeSocket = EventEmitter & { userId: string; readyState: number; send: ReturnType; + terminate: ReturnType; }; const OPEN = 1; // WebSocket.OPEN @@ -22,7 +23,7 @@ const g = globalThis as unknown as { }; function fakeSocket(userId: string): FakeSocket { - return Object.assign(new EventEmitter(), { userId, readyState: OPEN, send: vi.fn() }); + return Object.assign(new EventEmitter(), { userId, readyState: OPEN, send: vi.fn(), terminate: vi.fn() }); } async function freshModule() { @@ -106,6 +107,7 @@ describe('notifyUserChanged', () => { ws.notifyUserChanged('user-a'); expect(() => vi.advanceTimersByTime(ws.NOTIFY_DEBOUNCE_MS)).not.toThrow(); expect(ws.getActiveConnections()).toBe(0); + expect(a.terminate).toHaveBeenCalledTimes(1); }); }); diff --git a/web/src/lib/ws.ts b/web/src/lib/ws.ts index a454e77..14734e3 100644 --- a/web/src/lib/ws.ts +++ b/web/src/lib/ws.ts @@ -171,7 +171,10 @@ export function broadcastToUser(userId: string, message: WsMessage) { try { ws.send(payload); } catch { + // Close it too: left open, it would escape the heartbeat and the page + // would never be notified again (its onclose reconnects it). clients.delete(ws); + ws.terminate(); } } } -- 2.52.0 From fd509fbfac3374a21b169e8092f20a5756b9a89d Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 3 Nov 2026 20:42:15 -0500 Subject: [PATCH 14/18] test(web): pin dueDate with a tag filter and a non-integer priority Review of PR #186: both behaviour changes of the shared task query were untested; removing either condition left the suite green. Refs #179 Co-Authored-By: Claude Opus 5.5 --- web/src/lib/taskQueries.test.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/web/src/lib/taskQueries.test.ts b/web/src/lib/taskQueries.test.ts index 342091e..16bfa8f 100644 --- a/web/src/lib/taskQueries.test.ts +++ b/web/src/lib/taskQueries.test.ts @@ -181,6 +181,22 @@ describe('GET /api/lists/[id]/tasks?tags=', () => { expect((await res.json() as { id: string }[]).map((t) => t.id)).toEqual([a.t2]); }); + it('applies dueDate with a tag filter', async () => { + const a = await seedAccount(); + await exec('UPDATE sl_tasks SET due_date = $1 WHERE id = $2', ['2026-01-10T00:00:00Z', a.t1]); + // t2 (blue too) has no due date: excluded by the dueDate filter + const res = await getTasks(a.userId, a.list, `?tags=${a.blue}&dueDate=2026-02-01T00:00:00Z`); + expect(res.status).toBe(200); + expect((await res.json() as { id: string }[]).map((t) => t.id)).toEqual([a.t1]); + }); + + it('ignores a non-integer priority instead of failing', async () => { + const a = await seedAccount(); + const res = await getTasks(a.userId, a.list, '?priority=abc'); + expect(res.status).toBe(200); + expect((await res.json() as { id: string }[]).map((t) => t.id)).toEqual([a.t1, a.t2, a.t3]); + }); + it('still answers 404 for a list of another account', async () => { const a = await seedAccount(); const res = await getTasks(`user-${u()}`, a.list, ''); -- 2.52.0 From 706f91d234976e2eb2b16828eb620843c09d8233 Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 3 Nov 2026 20:42:41 -0500 Subject: [PATCH 15/18] test(sync): let the setTagsForTask wipe guard match across lines Review of PR #187: the regex did not allow the line break between .delete(taskTags) and .where(...), so the guard could never fail. Refs #180 Co-Authored-By: Claude Opus 5.5 --- tests/smoke.test.cjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/smoke.test.cjs b/tests/smoke.test.cjs index 89603c8..39fe31e 100644 --- a/tests/smoke.test.cjs +++ b/tests/smoke.test.cjs @@ -444,7 +444,7 @@ check('tag links: removals written by the app, pull aligned without the outbox ( assert.match(set, /tagLinkDiff\(/, 'setTagsForTask must diff with the local links'); assert.match(set, /for \(const tagId of removed\) \{\s*writeOutboxEntry\('taskTag', taskId, 'delete', \{ tagId \}\)/); assert.match(set, /for \(const tagId of added\) \{\s*writeOutboxEntry\('taskTag', taskId, 'create', \{ tagId \}\)/); - assert.ok(!/db\.delete\(taskTags\)\.where\(eq\(taskTags\.taskId, taskId\)\)/.test(set), 'setTagsForTask must not wipe every link'); + assert.ok(!/db\s*\.delete\(taskTags\)\s*\.where\(eq\(taskTags\.taskId, taskId\)\)/.test(set), 'setTagsForTask must not wipe every link'); assert.match(fnOf(tags, 'addTagToTask'), /writeOutboxEntry\('taskTag', taskId, 'create', \{ tagId \}\)\.then\(requestSync\)/); assert.match(fnOf(tags, 'removeTagFromTask'), /writeOutboxEntry\('taskTag', taskId, 'delete', \{ tagId \}\)\.then\(requestSync\)/); -- 2.52.0 From 0317d152666b835f1d6f591f71f1a905d06aea96 Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 3 Nov 2026 21:12:24 -0500 Subject: [PATCH 16/18] fix(sync): queue the user's writes made during the first sync MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Decision of Max at /pr-brief 185 (2026-11-03): a change made during the few seconds of « Fusionner » (or « Charger ce compte ») must reach the server. initialMerge and initialReset run while sync is still off, so writeOutboxEntry dropped such a write. The outbox now also queues while a first sync runs, and the merge points the pending entries that name the fixed local Inbox at the server Inbox (remapInboxEntry), otherwise the server refuses them. Refs #165 Co-Authored-By: Claude Opus 5.5 --- src/db/repository/outbox.ts | 20 +++++++++++++++----- src/services/syncClient.ts | 13 ++++++++++++- src/services/syncRules.ts | 31 +++++++++++++++++++++++++++++++ tests/smoke.test.cjs | 23 ++++++++++++++++++++++- tests/syncRules.test.mjs | 27 +++++++++++++++++++++++++++ 5 files changed, 107 insertions(+), 7 deletions(-) diff --git a/src/db/repository/outbox.ts b/src/db/repository/outbox.ts index d00303b..69588cb 100644 --- a/src/db/repository/outbox.ts +++ b/src/db/repository/outbox.ts @@ -6,9 +6,18 @@ import { useSettingsStore } from '@/src/stores/useSettingsStore'; type EntityType = 'task' | 'list' | 'tag' | 'taskTag'; type Action = 'create' | 'update' | 'delete'; +// Set by initialMerge / initialReset while they run (#165). They run while +// sync is still off; a write the user makes meanwhile is queued all the same, +// so that it reaches the server once sync is switched on. +let firstSyncInProgress = false; + +export function setFirstSyncInProgress(on: boolean): void { + firstSyncInProgress = on; +} + /** - * Write an entry to the sync outbox if sync is enabled. - * The entry id serves as the idempotency key. + * Write an entry to the sync outbox if sync is enabled, or while the first + * sync runs. The entry id serves as the idempotency key. */ export async function writeOutboxEntry( entityType: EntityType, @@ -17,7 +26,7 @@ export async function writeOutboxEntry( payload: Record ): Promise { const { syncEnabled } = useSettingsStore.getState(); - if (!syncEnabled) return; + if (!syncEnabled && !firstSyncInProgress) return; await queueOutboxEntry(entityType, entityId, action, payload); } @@ -50,7 +59,8 @@ const INSERT_CHUNK = 100; type Executor = Pick; /** - * Write several entries with an explicit createdAt if sync is enabled: the + * Write several entries with an explicit createdAt if sync is enabled (or + * while the first sync runs): the * push sends in createdAt order, writeOutboxEntry dates entries by the clock * and two writes in the same millisecond tie. Used by the Inbox repair (#152). */ @@ -65,7 +75,7 @@ export async function writeOutboxEntries( }[] ): Promise { const { syncEnabled } = useSettingsStore.getState(); - if (!syncEnabled || entries.length === 0) return; + if ((!syncEnabled && !firstSyncInProgress) || entries.length === 0) return; const rows = entries.map((e) => ({ id: randomUUID(), diff --git a/src/services/syncClient.ts b/src/services/syncClient.ts index c2df178..cf37c3c 100644 --- a/src/services/syncClient.ts +++ b/src/services/syncClient.ts @@ -5,7 +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 { queueOutboxEntry } from '@/src/db/repository/outbox'; +import { queueOutboxEntry, setFirstSyncInProgress } from '@/src/db/repository/outbox'; import { SYNC_EPOCH, keepLocal, @@ -21,6 +21,7 @@ import { isSynced, parseRetryAfter, sendInBatches, + remapInboxEntry, type PostResponse, } from '@/src/services/syncRules'; import { @@ -392,10 +393,12 @@ export async function pushBeforeSignOut(): Promise { */ export async function initialMerge(accountId: string): Promise { await scheduler.beginInitialSync(); + setFirstSyncInProgress(true); try { await mergeLocalData(); useSettingsStore.getState().setDataOwnerId(accountId); } finally { + setFirstSyncInProgress(false); scheduler.endInitialSync(); } } @@ -499,6 +502,12 @@ async function mergeLocalData(): Promise { if (localInbox) { // Update all tasks pointing to the old inbox await db.update(tasks).set({ listId: serverInboxId }).where(eq(tasks.listId, INBOX_ID)); + // Writes made during the merge still name the fixed local Inbox (#165) + const pending = await db.select().from(syncOutbox).where(isNull(syncOutbox.syncedAt)); + for (const entry of pending) { + const remapped = remapInboxEntry(entry, serverInboxId); + if (remapped) await db.update(syncOutbox).set(remapped).where(eq(syncOutbox.id, entry.id)); + } // Delete old inbox and insert with new ID await db.delete(lists).where(eq(lists.id, INBOX_ID)); await db.insert(lists).values({ @@ -525,10 +534,12 @@ async function mergeLocalData(): Promise { */ export async function initialReset(accountId: string): Promise { await scheduler.beginInitialSync(); + setFirstSyncInProgress(true); try { await resetFromServer(); useSettingsStore.getState().setDataOwnerId(accountId); } finally { + setFirstSyncInProgress(false); scheduler.endInitialSync(); } } diff --git a/src/services/syncRules.ts b/src/services/syncRules.ts index a90bf22..3b0c340 100644 --- a/src/services/syncRules.ts +++ b/src/services/syncRules.ts @@ -595,3 +595,34 @@ export function firstSyncChoice({ dataOwnerId, signedInId, localInboxId }: First if (localInboxId === null || localInboxId === LOCAL_INBOX_ID) return 'merge-or-reset'; return 'reset-only'; } + +/** + * A pending outbox entry that names the fixed local Inbox, rewritten under the + * server Inbox id that initialMerge gives it (#165): a task created or moved + * in the Inbox during « Fusionner », or an update of the Inbox itself. Null + * when the entry does not name the local Inbox (or cannot be read). + */ +export function remapInboxEntry( + entry: { entityType: string; entityId: string; payload: string }, + inboxId: string, +): { entityId: string; payload: string } | null { + let data: Record; + try { + data = JSON.parse(entry.payload); + } catch { + return null; + } + if (!data || typeof data !== 'object') return null; + let entityId = entry.entityId; + let changed = false; + if (entry.entityType === 'list' && entityId === LOCAL_INBOX_ID) { + entityId = inboxId; + if (data.id === LOCAL_INBOX_ID) data.id = inboxId; + changed = true; + } + if (entry.entityType === 'task' && data.listId === LOCAL_INBOX_ID) { + data.listId = inboxId; + changed = true; + } + return changed ? { entityId, payload: JSON.stringify(data) } : null; +} diff --git a/tests/smoke.test.cjs b/tests/smoke.test.cjs index 201baca..710cf84 100644 --- a/tests/smoke.test.cjs +++ b/tests/smoke.test.cjs @@ -240,7 +240,7 @@ check('sync on write and every sync go through the scheduler (#178)', () => { const start = client.indexOf(`export async function ${name}(`); assert.ok(start >= 0, `${name} not found`); const body = client.slice(start, client.indexOf('\n}\n', start)); - assert.match(body, /await scheduler\.beginInitialSync\(\);\s*try \{[^]*\} finally \{\s*scheduler\.endInitialSync\(\);/, `${name} must hold the first-sync state`); + assert.match(body, /await scheduler\.beginInitialSync\(\);\s*(?:setFirstSyncInProgress\(true\);\s*)?try \{[^]*\} finally \{\s*(?:setFirstSyncInProgress\(false\);\s*)?scheduler\.endInitialSync\(\);/, `${name} must hold the first-sync state`); } assert.equal((client.match(/pullChanges\(SYNC_EPOCH, scheduler\.tracker\)/g) || []).length, 2, 'the first-sync pulls are counted'); // Review of PR #184: initialMerge's POST batches count against the budget, @@ -250,6 +250,27 @@ check('sync on write and every sync go through the scheduler (#178)', () => { assert.match(client, /return \{ more: ok && operations\.length > maxBatches \* BATCH_SIZE \};\n\}/, 'pushChanges must report an unsent queue'); }); +// A write made during « Fusionner » or « Charger ce compte » (sync still off) +// is queued, and the merge points the pending entries at the server Inbox +// (/pr-brief 185, Max 2026-11-03). remapInboxEntry is executed by +// tests/syncRules.test.mjs; this check locks its wiring. +check('writes made during the first sync are queued and follow the server Inbox (#165)', () => { + const read = (rel) => fs.readFileSync(path.join(__dirname, '..', rel), 'utf8'); + const outbox = read('src/db/repository/outbox.ts'); + assert.equal((outbox.match(/if \(!syncEnabled && !firstSyncInProgress\) return;/g) || []).length, 1, 'writeOutboxEntry queues during the first sync'); + assert.match(outbox, /if \(\(!syncEnabled && !firstSyncInProgress\) \|\| entries\.length === 0\) return;/, 'writeOutboxEntries queues during the first sync'); + const client = read('src/services/syncClient.ts'); + for (const [name, inner] of [['initialMerge', 'mergeLocalData'], ['initialReset', 'resetFromServer']]) { + const start = client.indexOf(`export async function ${name}(`); + const body = client.slice(start, client.indexOf('\n}\n', start)); + assert.match(body, new RegExp(`await scheduler\\.beginInitialSync\\(\\);\\s*setFirstSyncInProgress\\(true\\);\\s*try \\{\\s*await ${inner}\\(\\);[^]*\\} finally \\{\\s*setFirstSyncInProgress\\(false\\);\\s*scheduler\\.endInitialSync\\(\\);`), `${name} must queue the user's writes while it runs`); + } + const merge = client.slice(client.indexOf('async function mergeLocalData('), client.indexOf('export async function initialReset(')); + const remap = merge.indexOf('await db.update(tasks).set({ listId: serverInboxId }).where(eq(tasks.listId, INBOX_ID));'); + const pending = merge.indexOf('remapInboxEntry(entry, serverInboxId)'); + assert.ok(remap >= 0 && pending > remap, 'the pending entries follow the server Inbox after the local remap'); +}); + // No merge across accounts (#165). firstSyncChoice and canSync are executed // by tests/syncRules.test.mjs and tests/syncSchedule.test.mjs; this check // locks their wiring in files node cannot load: sync stays off until the diff --git a/tests/syncRules.test.mjs b/tests/syncRules.test.mjs index 7dcad55..b6eae4b 100644 --- a/tests/syncRules.test.mjs +++ b/tests/syncRules.test.mjs @@ -34,6 +34,7 @@ import { pickInboxId, planInboxRepair, firstSyncChoice, + remapInboxEntry, } from '../src/services/syncRules.ts'; const ID = '11111111-1111-4111-8111-111111111111'; @@ -889,3 +890,29 @@ test('firstSyncChoice: data of A, signed in to B gives reset-only (regression)', 'merge-or-reset', ); }); + +// remapInboxEntry: writes made during « Fusionner » (/pr-brief 185, Max +// 2026-11-03) still name the fixed local Inbox, which the merge replaces by a +// server id; the pending entries follow it. +test('remapInboxEntry: a task created in the local Inbox during the merge moves to the server Inbox', () => { + const entry = { entityType: 'task', entityId: ID, payload: JSON.stringify({ id: ID, title: 't', listId: LOCAL_INBOX_ID }) }; + const out = remapInboxEntry(entry, LIST_ID); + assert.equal(out.entityId, ID); + assert.deepEqual(JSON.parse(out.payload), { id: ID, title: 't', listId: LIST_ID }); +}); + +test('remapInboxEntry: an update of the local Inbox itself takes the server id', () => { + const entry = { entityType: 'list', entityId: LOCAL_INBOX_ID, payload: JSON.stringify({ id: LOCAL_INBOX_ID, name: 'Boite' }) }; + const out = remapInboxEntry(entry, LIST_ID); + assert.equal(out.entityId, LIST_ID); + assert.deepEqual(JSON.parse(out.payload), { id: LIST_ID, name: 'Boite' }); +}); + +test('remapInboxEntry: entries that do not name the local Inbox are left alone', () => { + const other = '33333333-3333-4333-8333-333333333333'; + assert.equal(remapInboxEntry({ entityType: 'task', entityId: ID, payload: JSON.stringify({ id: ID, listId: other }) }, LIST_ID), null); + assert.equal(remapInboxEntry({ entityType: 'task', entityId: ID, payload: JSON.stringify({ id: ID, title: 'x' }) }, LIST_ID), null); + assert.equal(remapInboxEntry({ entityType: 'list', entityId: other, payload: JSON.stringify({ id: other }) }, LIST_ID), null); + 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); +}); -- 2.52.0 From 532b628887cee71ed2cb832b04e564a2dc557605 Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 3 Nov 2026 21:12:51 -0500 Subject: [PATCH 17/18] test(sync): pin the write-back of remapped outbox entries Refs #165 Co-Authored-By: Claude Opus 5.5 --- tests/smoke.test.cjs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/smoke.test.cjs b/tests/smoke.test.cjs index 710cf84..1f6a3c9 100644 --- a/tests/smoke.test.cjs +++ b/tests/smoke.test.cjs @@ -269,6 +269,8 @@ check('writes made during the first sync are queued and follow the server Inbox const remap = merge.indexOf('await db.update(tasks).set({ listId: serverInboxId }).where(eq(tasks.listId, INBOX_ID));'); const pending = merge.indexOf('remapInboxEntry(entry, serverInboxId)'); assert.ok(remap >= 0 && pending > remap, 'the pending entries follow the server Inbox after the local remap'); + assert.match(merge, /const remapped = remapInboxEntry\(entry, serverInboxId\);\s*if \(remapped\) await db\.update\(syncOutbox\)\.set\(remapped\)\.where\(eq\(syncOutbox\.id, entry\.id\)\);/, 'the remapped entry is written back'); + assert.match(merge, /const pending = await db\.select\(\)\.from\(syncOutbox\)\.where\(isNull\(syncOutbox\.syncedAt\)\);\s*for \(const entry of pending\) \{/, 'every unsent entry is remapped'); }); // No merge across accounts (#165). firstSyncChoice and canSync are executed -- 2.52.0 From 48218bdf6f31de1f7ca5a9cef29a4c534c27f241 Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 3 Nov 2026 21:20:25 -0500 Subject: [PATCH 18/18] docs(review): the outbox also queues during a first sync Review of PR #185: the Sync rule said writeOutboxEntry writes only while sync is on. Fixed at the top of the stack so the reviewed links keep their heads. Refs #165 Co-Authored-By: Claude Opus 5.5 --- REVIEW.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/REVIEW.md b/REVIEW.md index 936bb6c..9fa0538 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -105,7 +105,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm ### Sync -- 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` +- 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, ou pendant une première sync (`initialMerge`, `initialReset` : drapeau `setFirstSyncInProgress`, #165) ; 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`). 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` - `task create` écrit `completed` et `completedAt` ; une tâche terminée sans date reçoit la date du serveur, une tâche non terminée n'a pas de date (#146). — `web/src/lib/syncData.ts`, `web/src/app/api/sync/route.ts` -- 2.52.0