fix(sync): read the app inbox from the database and repair split devices #164

Merged
maximus merged 2 commits from issue-152-inbox-server-id into master 2026-10-26 00:59:29 +00:00
13 changed files with 1024 additions and 25 deletions

View file

@ -51,7 +51,8 @@ export default function InboxScreen() {
const loadTasks = useCallback(async () => {
if (isDraggingRef.current) return;
const result = await getTasksByList(getInboxId(), {
const inboxId = await getInboxId();
const result = await getTasksByList(inboxId, {
sortBy, sortOrder, filterPriority, filterTag, filterCompleted, filterDueDate,
});
const withTags = await Promise.all(

View file

@ -11,7 +11,7 @@ import { KeyboardProvider } from 'react-native-keyboard-controller';
import { LogtoProvider, useLogto } from '@logto/rn';
import { db } from '@/src/db/client';
import migrations from '@/src/db/migrations/migrations';
import { ensureInbox } from '@/src/db/repository/lists';
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';
@ -49,6 +49,22 @@ const SimplDarkTheme = {
},
};
// Inbox setup, once per process: repair a device split between the fixed
// and the server Inbox, then ensureInbox, which no longer recreates the fixed
// one next to a server Inbox (#152). Memoized because AppContent's first sync
// waits for it, and a child's effects run before its parent's: a push during
// the repair would replay the entries it rewrites.
let inboxSetup: Promise<void> | null = null;
function prepareInbox(): Promise<void> {
if (!inboxSetup) {
inboxSetup = repairInbox()
.catch((err) => console.warn('[inbox] repair failed:', err))
.then(() => ensureInbox())
.then(() => {});
}
return inboxSetup;
}
export default function RootLayout() {
const [fontsLoaded, fontError] = useFonts({
Inter_400Regular,
@ -66,7 +82,7 @@ export default function RootLayout() {
useEffect(() => {
if (fontsLoaded && migrationsReady) {
ensureInbox().then(async () => {
prepareInbox().then(async () => {
await initNotifications();
syncWidgetData().catch(() => {});
SplashScreen.hideAsync();
@ -107,8 +123,8 @@ function AppContent() {
useEffect(() => {
if (!syncEnabled) return;
// Initial sync
fullSync().then(() => cleanOutbox()).catch(() => {});
// Initial sync, once the Inbox is set up
prepareInbox().then(() => fullSync()).then(() => cleanOutbox()).catch(() => {});
// 2-minute interval
const interval = setInterval(() => {

View file

@ -49,8 +49,9 @@ export default function NewTaskScreen() {
const [priority, setPriority] = useState(0);
const [dueDate, setDueDate] = useState<Date | null>(null);
const [showDatePicker, setShowDatePicker] = useState(false);
const [selectedListId, setSelectedListId] = useState(
isValidUUID(params.listId) ? params.listId : getInboxId()
// The Inbox id is read from the database (#152): null until it is loaded
const [selectedListId, setSelectedListId] = useState<string | null>(
isValidUUID(params.listId) ? params.listId : null
);
const [lists, setLists] = useState<{ id: string; name: string; color: string | null; icon: string | null; isInbox: boolean }[]>([]);
const [recurrence, setRecurrence] = useState<string | null>(null);
@ -63,11 +64,14 @@ export default function NewTaskScreen() {
useEffect(() => {
getAllLists().then(setLists);
getAllTags().then(setAvailableTags);
if (!isValidUUID(params.listId)) {
getInboxId().then((id) => setSelectedListId((current) => current ?? id));
}
}, []);
const handleSave = async () => {
if (saving) return;
if (!title.trim()) return;
if (!title.trim() || !selectedListId) return;
setSaving(true);
try {
const taskId = await createTask({
@ -88,7 +92,7 @@ export default function NewTaskScreen() {
} catch {
// FK constraint or other DB error — fallback to inbox
setSaving(false);
setSelectedListId(getInboxId());
setSelectedListId(await getInboxId());
}
};

View file

@ -4,7 +4,7 @@
"version": "1.6.6",
"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",
"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",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",

View file

@ -1,18 +1,24 @@
import { eq } from 'drizzle-orm';
import { asc, desc, eq, inArray, isNull } from 'drizzle-orm';
import { db } from '../client';
import { lists } from '../schema';
import { lists, syncOutbox, taskTags, tasks } from '../schema';
import { randomUUID } from '@/src/lib/uuid';
import { truncate } from '@/src/lib/validation';
import { writeOutboxEntry } from './outbox';
const INBOX_ID = '00000000-0000-0000-0000-000000000001';
import { whenSettingsHydrated } from '@/src/stores/useSettingsStore';
import { LOCAL_INBOX_ID, pickInboxId, planInboxRepair } from '@/src/services/syncRules';
import { writeOutboxEntries, writeOutboxEntry } from './outbox';
/**
* Create the fixed local Inbox when the device has no Inbox at all (never
* synced, or a server without Inbox). Never alongside a server Inbox: that
* split is what repairInbox undoes (#152). Not written to the outbox, the
* first sync remaps it.
*/
export async function ensureInbox() {
const existing = await db.select().from(lists).where(eq(lists.id, INBOX_ID));
if (existing.length === 0) {
const inboxes = await db.select({ id: lists.id }).from(lists).where(eq(lists.isInbox, true));
if (inboxes.length === 0) {
const now = new Date();
await db.insert(lists).values({
id: INBOX_ID,
id: LOCAL_INBOX_ID,
name: 'Inbox',
isInbox: true,
position: 0,
@ -20,11 +26,85 @@ export async function ensureInbox() {
updatedAt: now,
});
}
return INBOX_ID;
return getInboxId();
}
export function getInboxId() {
return INBOX_ID;
/**
* Id of the app Inbox, read from the database: the server Inbox after the
* first sync, the fixed local one before (#152).
*/
export async function getInboxId(): Promise<string> {
return pickInboxId(await getInboxes()) ?? LOCAL_INBOX_ID;
}
// Local Inbox lists, the most recent first: the server picks its active
// Inbox the same way (resolveTaskListId), and every Inbox has position 0.
function getInboxes() {
return db
.select({ id: lists.id, isInbox: lists.isInbox })
.from(lists)
.where(eq(lists.isInbox, true))
.orderBy(desc(lists.createdAt), desc(lists.id));
}
/**
* Repair a device that has both the fixed Inbox and a server Inbox (#152):
* moves the tasks of the fixed Inbox to the server one and queues them, fixes
* the pending outbox entries that point at the fixed id, then deletes the
* fixed Inbox without an outbox entry (the server never had it). The
* decisions live in planInboxRepair; a repaired device plans nothing.
*/
export async function repairInbox(): Promise<void> {
// The repair queues its ops only when sync is on: never decide that from
// the default value of a store not yet loaded, the fixed Inbox would be
// deleted without its tasks ever reaching the server.
await whenSettingsHydrated();
const inboxes = await getInboxes();
const moved = await db.select().from(tasks).where(eq(tasks.listId, LOCAL_INBOX_ID));
const movedTags = [];
for (const ids of chunks(moved.map((t) => t.id))) {
movedTags.push(...(await db.select().from(taskTags).where(inArray(taskTags.taskId, ids))));
}
// Creation order: planInboxRepair reads the last action on a task tag
const pending = await db
.select()
.from(syncOutbox)
.where(isNull(syncOutbox.syncedAt))
.orderBy(asc(syncOutbox.createdAt));
const now = new Date();
const plan = planInboxRepair(inboxes, moved, movedTags, pending, now);
if (!plan) return;
await db.transaction(async (tx) => {
if (plan.movedTaskIds.length > 0) {
await tx
.update(tasks)
.set({ listId: plan.inboxId, updatedAt: now })
.where(eq(tasks.listId, LOCAL_INBOX_ID));
}
for (const { id, payload } of plan.rewrites) {
await tx.update(syncOutbox).set({ payload }).where(eq(syncOutbox.id, id));
}
for (const ids of chunks(plan.discardIds)) {
await tx.delete(syncOutbox).where(inArray(syncOutbox.id, ids));
}
await writeOutboxEntries(tx, plan.ops);
await tx.delete(lists).where(eq(lists.id, LOCAL_INBOX_ID));
});
console.warn(
`[inbox] repaired: ${plan.movedTaskIds.length} task(s) moved, ` +
`${plan.rewrites.length} pending entr(ies) rewritten, ${plan.discardIds.length} discarded`
);
}
// Slices of an id list for inArray: SQLite binds 999 variables at most.
function chunks(ids: string[], size = 500): string[][] {
const out: string[][] = [];
for (let i = 0; i < ids.length; i += size) out.push(ids.slice(i, i + size));
return out;
}
export async function getAllLists() {

View file

@ -29,3 +29,41 @@ export async function writeOutboxEntry(
syncedAt: null,
});
}
const INSERT_CHUNK = 100;
/** Database or transaction the entries are written with. */
type Executor = Pick<typeof db, 'insert'>;
/**
* Write several entries with an explicit createdAt if sync is enabled: 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).
*/
export async function writeOutboxEntries(
executor: Executor,
entries: {
entityType: EntityType;
entityId: string;
action: Action;
payload: Record<string, unknown>;
createdAt: string;
}[]
): Promise<void> {
const { syncEnabled } = useSettingsStore.getState();
if (!syncEnabled || entries.length === 0) return;
const rows = entries.map((e) => ({
id: randomUUID(),
entityType: e.entityType,
entityId: e.entityId,
action: e.action,
payload: JSON.stringify(e.payload),
createdAt: e.createdAt,
syncedAt: null,
}));
// Chunked: 7 bound variables per row, under SQLite's 999 per statement
for (let i = 0; i < rows.length; i += INSERT_CHUNK) {
await executor.insert(syncOutbox).values(rows.slice(i, i + INSERT_CHUNK));
}
}

55
src/lib/hydration.ts Normal file
View file

@ -0,0 +1,55 @@
// Bounded wait for a persisted store to finish loading.
//
// This module MUST stay import-free and use only erasable TypeScript syntax:
// tests/hydration.test.mjs loads it with Node's native type stripping. The
// smoke test locks the zero-import rule.
/** Upper bound of the wait for the persisted settings, in milliseconds. */
export const HYDRATION_TIMEOUT_MS = 5000;
/** What waitForHydration reads from a persisted store. */
export interface HydrationSource {
hasHydrated: () => boolean;
/** Error of a failed load, null when there is none (yet). */
error: () => unknown;
/** Called once the load succeeds; returns an unsubscribe function. */
onFinish: (cb: () => void) => () => void;
/** Called when the load fails; returns an unsubscribe function. */
onError: (cb: (error: unknown) => void) => () => void;
}
export interface Timers {
setTimeout: (cb: () => void, ms: number) => unknown;
clearTimeout: (handle: unknown) => void;
}
/**
* Resolves once the store has loaded, rejects when its load failed or after
* timeoutMs. zustand's persist never finishes a failed load (a storage that
* throws, or corrupted JSON): onFinishHydration is never called and
* hasHydrated stays false, so an unbounded wait would hang forever (#152,
* review of PR #164).
*/
export function waitForHydration(source: HydrationSource, timeoutMs: number, timers: Timers): Promise<void> {
if (source.hasHydrated()) return Promise.resolve();
const failed = source.error();
if (failed != null) return Promise.reject(failed);
return new Promise((resolve, reject) => {
let done = false;
const settle = (fn: () => void) => {
if (done) return;
done = true;
offFinish();
offError();
timers.clearTimeout(timer);
fn();
};
const offFinish = source.onFinish(() => settle(resolve));
const offError = source.onError((error) => settle(() => reject(error)));
const timer = timers.setTimeout(
() => settle(() => reject(new Error(`settings not loaded after ${timeoutMs} ms`))),
timeoutMs
);
});
}

View file

@ -439,13 +439,17 @@ export async function initialReset(): Promise<void> {
// 2. Pull everything from server
await pullChanges(SYNC_EPOCH);
// 3. Ensure we have a local inbox (the server may have created one)
// 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
// id, unknown to the server: every task sent there would be refused (#152).
const serverLists = await db.select().from(lists);
const hasInbox = serverLists.some((l) => l.isInbox);
if (!hasInbox) {
// Import ensureInbox dynamically to avoid circular deps
const { ensureInbox } = await import('@/src/db/repository/lists');
await ensureInbox();
const id = randomUUID();
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);
}
}

View file

@ -416,3 +416,147 @@ export async function sendInBatches<T>(
}
return { ok: true, results };
}
// ---------------------------------------------------------------------------
// Inbox: fixed local id before the first sync, server id after (#152)
// ---------------------------------------------------------------------------
/**
* Id of the Inbox created on a device that has never synced. The server never
* knows it: initialMerge remaps it to a server UUID, initialReset pulls the
* server Inbox under its own id.
*/
export const LOCAL_INBOX_ID = '00000000-0000-0000-0000-000000000001';
interface InboxCandidate {
id: string;
isInbox: boolean;
}
/**
* The Inbox of the app: the first isInbox list other than the fixed one, else
* the fixed one, else null. Lists deleted on the server are removed locally
* by the pull, so a local isInbox list is active.
*/
export function pickInboxId(lists: InboxCandidate[]): string | null {
const inboxes = lists.filter((l) => l.isInbox);
const server = inboxes.find((l) => l.id !== LOCAL_INBOX_ID);
if (server) return server.id;
return inboxes.length > 0 ? LOCAL_INBOX_ID : null;
}
/** Outbox row fields read by planInboxRepair (unsynced entries only). */
export interface RepairOutboxEntry {
id: string;
entityType: string;
entityId: string;
action: string;
payload: string;
}
/** Outbox entry written by the repair, with an explicit createdAt. */
export interface RepairOp {
entityType: 'task' | 'taskTag';
entityId: string;
action: 'create' | 'update' | 'delete';
payload: Payload;
createdAt: string;
}
export interface InboxRepair {
/** The real Inbox, which receives the tasks of the fixed one. */
inboxId: string;
/** Tasks (subtasks included) whose listId moves to inboxId. */
movedTaskIds: string[];
/** Outbox entries to add, dated from now in push order. */
ops: RepairOp[];
/** Unsynced entries whose payload.listId was the fixed id, rewritten. */
rewrites: { id: string; payload: string }[];
/** Unsynced entries to delete: those of moved tasks and of the fixed list. */
discardIds: string[];
}
function parsePayload(raw: string): Payload | null {
try {
const payload: unknown = JSON.parse(raw);
return payload && typeof payload === 'object' ? (payload as Payload) : null;
} catch {
return null;
}
}
/**
* Plan the repair of a device split between the fixed Inbox and a server
* Inbox (ensureInbox recreated the fixed id after the first sync, before
* #152). Null when there is nothing to repair: no fixed Inbox, or no other
* Inbox. Once applied (tasks moved, fixed list deleted), the plan is null.
*
* A moved task (listId = fixed id, subtasks included) may be unknown to the
* server (its create was refused, and dropped by an app older than #151) or
* known under another list (its move was refused). Its pending task and
* taskTag entries are discarded, and it is queued again from its local
* state: a full create, then an update with the same fields, then a taskTag
* create per current tag and a taskTag delete per pending tag removal. The
* create applies on an unknown task and does nothing on a known one
* (onConflictDoNothing); the update moves a known task. Every op comes after
* the create, so none is refused for an unknown task. The ops are dated
* now + 1 ms each: the push sends in createdAt order.
*
* Other pending entries that carry the fixed listId (a task deleted since)
* keep their id, since the server does not remember a refused key, and their
* date, with the listId rewritten: replayed first, the create applies. List
* entries of the fixed Inbox are discarded: the server never had it.
*/
export function planInboxRepair(
lists: InboxCandidate[],
taskRows: TaskRow[],
taskTagRows: { taskId: string; tagId: string }[],
outbox: RepairOutboxEntry[],
now: Date | number,
): InboxRepair | null {
const hasFixed = lists.some((l) => l.isInbox && l.id === LOCAL_INBOX_ID);
const inboxId = pickInboxId(lists);
if (!hasFixed || inboxId === null || inboxId === LOCAL_INBOX_ID) return null;
const moved = taskRows.filter((t) => t.listId === LOCAL_INBOX_ID);
const movedIds = new Set(moved.map((t) => t.id));
const rewrites: { id: string; payload: string }[] = [];
const discardIds: string[] = [];
// Tags removed from a moved task while its entries were pending
const removedTags = new Map<string, string[]>();
for (const entry of outbox) {
const payload = parsePayload(entry.payload);
if (entry.entityType === 'list' && entry.entityId === LOCAL_INBOX_ID) {
discardIds.push(entry.id);
} else if ((entry.entityType === 'task' || entry.entityType === 'taskTag') && movedIds.has(entry.entityId)) {
discardIds.push(entry.id);
const tagId = payload?.tagId;
if (entry.entityType === 'taskTag' && typeof tagId === 'string') {
// Entries come in creation order: the last action on a tag wins
const without = (removedTags.get(entry.entityId) ?? []).filter((id) => id !== tagId);
removedTags.set(entry.entityId, entry.action === 'delete' ? [...without, tagId] : without);
}
} else if (payload && payload.listId === LOCAL_INBOX_ID) {
rewrites.push({ id: entry.id, payload: JSON.stringify({ ...payload, listId: inboxId }) });
}
}
const nowMs = new Date(now).getTime();
const ops: RepairOp[] = [];
const push = (entityType: RepairOp['entityType'], entityId: string, action: RepairOp['action'], payload: Payload) => {
ops.push({ entityType, entityId, action, payload, createdAt: new Date(nowMs + ops.length).toISOString() });
};
for (const task of moved) {
const payload = taskUpdatePayload({ ...task, listId: inboxId });
push('task', task.id, 'create', payload);
push('task', task.id, 'update', payload);
const current = taskTagRows.filter((tt) => tt.taskId === task.id).map((tt) => tt.tagId);
for (const tagId of current) push('taskTag', task.id, 'create', { tagId });
for (const tagId of removedTags.get(task.id) ?? []) {
if (!current.includes(tagId)) push('taskTag', task.id, 'delete', { tagId });
}
}
return { inboxId, movedTaskIds: moved.map((t) => t.id), ops, rewrites, discardIds };
}

View file

@ -1,6 +1,7 @@
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { HYDRATION_TIMEOUT_MS, waitForHydration } from '@/src/lib/hydration';
type ThemeMode = 'light' | 'dark' | 'system';
@ -25,6 +26,10 @@ interface SettingsState {
setUserId: (userId: string | null) => void;
}
// Error of a failed settings load, and who waits for it (whenSettingsHydrated)
let hydrationError: unknown = null;
const hydrationErrorListeners = new Set<(error: unknown) => void>();
export const useSettingsStore = create<SettingsState>()(
persist(
(set) => ({
@ -50,6 +55,35 @@ export const useSettingsStore = create<SettingsState>()(
{
name: 'simpl-liste-settings',
storage: createJSONStorage(() => AsyncStorage),
// A failed load is never finished by persist: record it for
// whenSettingsHydrated, which would otherwise wait for nothing.
onRehydrateStorage: () => (_state, error) => {
if (error == null) return;
hydrationError = error;
hydrationErrorListeners.forEach((cb) => cb(error));
},
}
)
);
/**
* Resolves once the persisted settings are loaded from AsyncStorage, rejects
* when the load failed or after HYDRATION_TIMEOUT_MS. Before the load,
* syncEnabled reads as its default false: a startup write that depends on it
* waits for this, and is skipped when it rejects (#152).
*/
export function whenSettingsHydrated(): Promise<void> {
return waitForHydration(
{
hasHydrated: () => useSettingsStore.persist.hasHydrated(),
error: () => hydrationError,
onFinish: (cb) => useSettingsStore.persist.onFinishHydration(cb),
onError: (cb) => {
hydrationErrorListeners.add(cb);
return () => hydrationErrorListeners.delete(cb);
},
},
HYDRATION_TIMEOUT_MS,
{ setTimeout, clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>) }
);
}

185
tests/hydration.test.mjs Normal file
View file

@ -0,0 +1,185 @@
// Execution tests for the bounded wait on the persisted settings (#152,
// review of PR #164). Runs on plain node via the built-in test runner +
// native TS type-stripping:
//
// node --test tests/hydration.test.mjs
//
// The unit tests drive waitForHydration with a fake source and fake timers.
// The last tests run it against the zustand persist middleware of the repo,
// with the same onRehydrateStorage hook as src/stores/useSettingsStore.ts
// (locked by the smoke test), to pin the failure mode it guards against.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createStore } from 'zustand/vanilla';
import { persist, createJSONStorage } from 'zustand/middleware';
import { HYDRATION_TIMEOUT_MS, waitForHydration } from '../src/lib/hydration.ts';
function fakeSource({ hydrated = false, error = null } = {}) {
const finish = new Set();
const errors = new Set();
return {
finish,
errors,
source: {
hasHydrated: () => hydrated,
error: () => error,
onFinish: (cb) => {
finish.add(cb);
return () => finish.delete(cb);
},
onError: (cb) => {
errors.add(cb);
return () => errors.delete(cb);
},
},
};
}
function fakeTimers() {
const pending = new Map();
let next = 1;
return {
pending,
fire: () => [...pending.values()].forEach((t) => t.cb()),
timers: {
setTimeout: (cb, ms) => {
const id = next++;
pending.set(id, { cb, ms });
return id;
},
clearTimeout: (id) => pending.delete(id),
},
};
}
// Settled state of a promise after the microtask queue drains
async function state(promise) {
let s = 'pending';
promise.then(() => (s = 'resolved'), (e) => (s = `rejected: ${e && e.message ? e.message : e}`));
await new Promise((r) => setImmediate(r));
return s;
}
test('HYDRATION_TIMEOUT_MS is a few seconds', () => {
assert.equal(HYDRATION_TIMEOUT_MS, 5000);
});
test('waitForHydration: an already loaded store resolves at once, without a timer', async () => {
const { source } = fakeSource({ hydrated: true });
const t = fakeTimers();
assert.equal(await state(waitForHydration(source, 5000, t.timers)), 'resolved');
assert.equal(t.pending.size, 0);
});
test('waitForHydration: a load that already failed rejects at once', async () => {
const { source } = fakeSource({ error: new Error('bad json') });
const t = fakeTimers();
assert.equal(await state(waitForHydration(source, 5000, t.timers)), 'rejected: bad json');
assert.equal(t.pending.size, 0);
});
test('waitForHydration: waits for the load, then resolves and clears its timer and listeners', async () => {
const f = fakeSource();
const t = fakeTimers();
const p = waitForHydration(f.source, 5000, t.timers);
assert.equal(await state(p), 'pending');
assert.equal(t.pending.size, 1);
assert.equal([...t.pending.values()][0].ms, 5000);
[...f.finish].forEach((cb) => cb());
assert.equal(await state(p), 'resolved');
assert.equal(t.pending.size, 0);
assert.equal(f.finish.size, 0);
assert.equal(f.errors.size, 0);
});
test('waitForHydration: a load that fails later rejects with its error', async () => {
const f = fakeSource();
const t = fakeTimers();
const p = waitForHydration(f.source, 5000, t.timers);
[...f.errors].forEach((cb) => cb(new Error('storage down')));
assert.equal(await state(p), 'rejected: storage down');
assert.equal(t.pending.size, 0);
assert.equal(f.finish.size, 0);
});
test('waitForHydration: a load that never ends rejects at the timeout', async () => {
const f = fakeSource();
const t = fakeTimers();
const p = waitForHydration(f.source, 5000, t.timers);
t.fire();
assert.equal(await state(p), 'rejected: settings not loaded after 5000 ms');
assert.equal(f.finish.size, 0);
assert.equal(f.errors.size, 0);
});
test('waitForHydration: settles once, a late finish after the timeout changes nothing', async () => {
const f = fakeSource();
const t = fakeTimers();
const finishers = () => [...f.finish];
const p = waitForHydration(f.source, 5000, t.timers);
const late = finishers();
t.fire();
late.forEach((cb) => cb());
assert.match(await state(p), /^rejected/);
});
// --- Against the zustand persist middleware of the repo ---
function settingsStore(raw) {
let error = null;
const errorListeners = new Set();
const store = createStore()(
persist(() => ({ syncEnabled: false }), {
name: 'simpl-liste-settings',
storage: createJSONStorage(() => ({
getItem: async () => raw,
setItem: async () => {},
removeItem: async () => {},
})),
// Same hook as useSettingsStore.ts
onRehydrateStorage: () => (_state, e) => {
if (e == null) return;
error = e;
errorListeners.forEach((cb) => cb(e));
},
}),
);
const source = {
hasHydrated: () => store.persist.hasHydrated(),
error: () => error,
onFinish: (cb) => store.persist.onFinishHydration(cb),
onError: (cb) => {
errorListeners.add(cb);
return () => errorListeners.delete(cb);
},
};
return { store, source };
}
const realTimers = { setTimeout, clearTimeout };
test('zustand persist never finishes a load of corrupted JSON (the hang of the review)', async () => {
const { store } = settingsStore('{not json');
let finished = false;
store.persist.onFinishHydration(() => (finished = true));
await new Promise((r) => setTimeout(r, 50));
assert.equal(store.persist.hasHydrated(), false);
assert.equal(finished, false);
});
test('waitForHydration rejects on corrupted settings, whether it starts before or after the failure', async () => {
const early = settingsStore('{not json');
const p = waitForHydration(early.source, 1000, realTimers);
await assert.rejects(p);
const late = settingsStore('{not json');
await new Promise((r) => setTimeout(r, 20));
await assert.rejects(waitForHydration(late.source, 1000, realTimers));
});
test('waitForHydration resolves on valid settings, with the stored syncEnabled', async () => {
const { store, source } = settingsStore(JSON.stringify({ state: { syncEnabled: true }, version: 0 }));
await waitForHydration(source, 1000, realTimers);
assert.equal(store.getState().syncEnabled, true);
});

View file

@ -275,6 +275,101 @@ check('syncClient.ts wires the #149-#151 sync rules', () => {
assert.match(push, /\.where\(inArray\(syncOutbox\.id, markIds\)\);\s*\/\/[^\n]*\s*syncWidgetData\(\)/);
});
// 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
// under node) must feed it the load error and the timeout.
check('hydration.ts stays import-free and useSettingsStore.ts bounds its wait', () => {
assert.deepEqual(staticImportsOf('src/lib/hydration.ts'), [], 'hydration.ts must have zero imports');
const src = fs.readFileSync(path.join(__dirname, '..', 'src/stores/useSettingsStore.ts'), 'utf8');
// persist never finishes a failed load: the hook records the error
assert.match(
src,
/onRehydrateStorage: \(\) => \(_state, error\) => \{\s*if \(error == null\) return;\s*hydrationError = error;\s*hydrationErrorListeners\.forEach\(\(cb\) => cb\(error\)\);\s*\}/
);
const start = src.indexOf('export function whenSettingsHydrated(');
assert.ok(start >= 0, 'whenSettingsHydrated not found');
const body = src.slice(start);
assert.match(body, /^[^]*?\{\s*return waitForHydration\(/, 'whenSettingsHydrated must return waitForHydration(...)');
for (const piece of [
'hasHydrated: () => useSettingsStore.persist.hasHydrated()',
'error: () => hydrationError',
'onFinish: (cb) => useSettingsStore.persist.onFinishHydration(cb)',
'hydrationErrorListeners.add(cb)',
'HYDRATION_TIMEOUT_MS,',
]) {
assert.ok(body.includes(piece), `whenSettingsHydrated misses ${piece}`);
}
});
// Wiring of the Inbox repair (#152) in lists.ts and app/_layout.tsx, which
// node cannot load: planInboxRepair and pickInboxId are executed by
// tests/syncRules.test.mjs, this check locks how they are called.
check('lists.ts and _layout.tsx wire the #152 Inbox rules', () => {
const read = (rel) => fs.readFileSync(path.join(__dirname, '..', rel), 'utf8');
const lists = read('src/db/repository/lists.ts');
const fn = (name) => {
const m = new RegExp(`\\nexport async function ${name}\\(`).exec(lists);
assert.ok(m, `${name} not found in lists.ts`);
const rest = lists.slice(m.index + 1);
const end = rest.search(/\nexport (async )?function /);
return end < 0 ? rest : rest.slice(0, end);
};
assert.ok(!/INBOX_ID = /.test(lists), 'lists.ts must take the fixed id from syncRules (LOCAL_INBOX_ID)');
// getInboxId reads the database, never returns the constant alone
assert.match(fn('getInboxId'), /return pickInboxId\(await getInboxes\(\)\) \?\? LOCAL_INBOX_ID;/);
// ensureInbox creates the fixed id only when no Inbox exists at all
const ensure = fn('ensureInbox');
assert.match(ensure, /\.where\(eq\(lists\.isInbox, true\)\)/);
assert.ok(!/eq\(lists\.id, LOCAL_INBOX_ID\)/.test(ensure), 'ensureInbox must not test the fixed id alone');
assert.ok(!/writeOutboxEntr/.test(ensure), 'the fixed Inbox never reaches the outbox');
// repairInbox applies the whole plan in one transaction, fixed list last
const repair = fn('repairInbox');
assert.match(repair, /planInboxRepair\(inboxes, moved, movedTags, pending, now\)/);
assert.match(repair, /\.where\(isNull\(syncOutbox\.syncedAt\)\)\s*\.orderBy\(asc\(syncOutbox\.createdAt\)\)/);
// Same Inbox order as the server: the most recent first
assert.match(lists, /\.where\(eq\(lists\.isInbox, true\)\)\s*\.orderBy\(desc\(lists\.createdAt\), desc\(lists\.id\)\)/);
const tx = repair.slice(repair.indexOf('db.transaction('));
assert.ok(repair.indexOf('db.transaction(') > 0, 'repairInbox must use a transaction');
for (const step of [
'.set({ listId: plan.inboxId, updatedAt: now })',
'plan.rewrites',
'for (const ids of chunks(plan.discardIds))',
'writeOutboxEntries(tx, plan.ops)',
'tx.delete(lists).where(eq(lists.id, LOCAL_INBOX_ID))',
]) {
assert.ok(tx.includes(step), `repairInbox transaction misses ${step}`);
}
assert.ok(
tx.indexOf('writeOutboxEntries(tx, plan.ops)') < tx.indexOf('tx.delete(lists)'),
'the fixed Inbox is deleted after its tasks are queued'
);
// The repair waits for the persisted settings (syncEnabled) before planning
assert.match(repair, /^[^]*?await whenSettingsHydrated\(\);[^]*planInboxRepair\(/);
// Startup: repair before ensureInbox, a failed repair does not block launch,
// and the first sync waits for both
const layout = read('app/_layout.tsx');
const r = layout.indexOf('repairInbox()');
const e = layout.indexOf('ensureInbox()');
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');
// 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('));
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\);/);
assert.match(reset, /const inbox = \{[^}]*isInbox: true \}/);
// Callers await the Inbox read from the database
assert.match(read('app/(tabs)/index.tsx'), /await getInboxId\(\)/);
const newTask = read('app/task/new.tsx');
assert.ok(!/useState\([^)]*getInboxId\(\)/.test(newTask), 'new.tsx must not read the Inbox synchronously');
assert.match(newTask, /getInboxId\(\)\.then\(\(id\) => setSelectedListId\(\(current\) => current \?\? id\)\)/);
});
// --- Build toolchain guards ---
// A blanket `npm audit fix` (PR #118) once rewrote hundreds of lock entries:
// babel-preset-expo and @expo/metro-config lost their root hoisting and a

View file

@ -30,6 +30,9 @@ import {
isSynced,
classifyOutbox,
sendInBatches,
LOCAL_INBOX_ID,
pickInboxId,
planInboxRepair,
} from '../src/services/syncRules.ts';
const ID = '11111111-1111-4111-8111-111111111111';
@ -502,3 +505,343 @@ test('sendInBatches: maxBatches 8 sends 8 batches at most', async () => {
assert.equal(t.calls.length, 8);
assert.equal(r.results.length, 400);
});
// ---------------------------------------------------------------------------
// Inbox repair (#152)
// ---------------------------------------------------------------------------
const SERVER_INBOX = '33333333-3333-4333-8333-333333333333';
const OTHER_LIST = '44444444-4444-4444-8444-444444444444';
const TAG_A = '55555555-5555-4555-8555-55555555555a';
const TAG_B = '55555555-5555-4555-8555-55555555555b';
const REPAIR_NOW = new Date('2026-10-25T12:00:00.000Z');
const listRow = (id, isInbox) => ({ id, isInbox });
const fixedInbox = listRow(LOCAL_INBOX_ID, true);
const serverInbox = listRow(SERVER_INBOX, true);
const otherList = listRow(OTHER_LIST, false);
const taskRow = (id, listId, over = {}) => ({
id,
title: `task ${id.slice(-1)}`,
notes: null,
completed: false,
completedAt: null,
priority: 0,
dueDate: null,
listId,
parentId: null,
position: 0,
recurrence: null,
calendarEventId: null,
createdAt: LOCAL_CREATED,
updatedAt: LOCAL_CREATED,
...over,
});
let outboxSeq = 0;
const outboxRow = (id, entityType, entityId, action, payload) => ({
id,
entityType,
entityId,
action,
payload: typeof payload === 'string' ? payload : JSON.stringify(payload),
// Pending entries predate the repair, in creation order
createdAt: new Date(Date.parse('2026-10-01T00:00:00.000Z') + outboxSeq++ * 1000).toISOString(),
});
const T1 = 'aaaaaaaa-0000-4000-8000-000000000001';
const T2 = 'aaaaaaaa-0000-4000-8000-000000000002';
const T3 = 'aaaaaaaa-0000-4000-8000-000000000003';
const T4 = 'aaaaaaaa-0000-4000-8000-000000000004';
const plan = (lists, tasks, outbox = [], taskTags = []) => planInboxRepair(lists, tasks, taskTags, outbox, REPAIR_NOW);
test('LOCAL_INBOX_ID is the fixed id of the local Inbox', () => {
assert.equal(LOCAL_INBOX_ID, '00000000-0000-0000-0000-000000000001');
});
test('pickInboxId: no Inbox gives null', () => {
assert.equal(pickInboxId([]), null);
assert.equal(pickInboxId([otherList]), null);
});
test('pickInboxId: the fixed Inbox alone is the Inbox', () => {
assert.equal(pickInboxId([fixedInbox, otherList]), LOCAL_INBOX_ID);
});
test('pickInboxId: the server Inbox alone is the Inbox', () => {
assert.equal(pickInboxId([otherList, serverInbox]), SERVER_INBOX);
});
test('pickInboxId: with both, the server Inbox wins whatever the order', () => {
assert.equal(pickInboxId([fixedInbox, serverInbox]), SERVER_INBOX);
assert.equal(pickInboxId([serverInbox, fixedInbox]), SERVER_INBOX);
});
test('pickInboxId: among several server Inboxes, the first given wins (caller orders)', () => {
assert.equal(pickInboxId([listRow(OTHER_LIST, true), serverInbox]), OTHER_LIST);
});
test('pickInboxId: a list that is not an Inbox is never picked', () => {
assert.equal(pickInboxId([listRow(OTHER_LIST, false), fixedInbox]), LOCAL_INBOX_ID);
});
test('planInboxRepair: nothing to repair without the fixed Inbox and another Inbox', () => {
const tasks = [taskRow(T1, LOCAL_INBOX_ID)];
assert.equal(plan([], tasks), null);
assert.equal(plan([fixedInbox, otherList], tasks), null);
assert.equal(plan([serverInbox, otherList], [taskRow(T1, SERVER_INBOX)]), null);
});
test('planInboxRepair: the fixed id that is not flagged isInbox is not a split', () => {
assert.equal(plan([listRow(LOCAL_INBOX_ID, false), serverInbox], []), null);
});
test('planInboxRepair: split device moves every task under the fixed id, subtasks included', () => {
const tasks = [
taskRow(T1, LOCAL_INBOX_ID),
taskRow(T2, LOCAL_INBOX_ID, { parentId: T1 }),
taskRow(T3, OTHER_LIST),
taskRow(T4, SERVER_INBOX),
];
const p = plan([fixedInbox, serverInbox, otherList], tasks);
assert.equal(p.inboxId, SERVER_INBOX);
assert.deepEqual(p.movedTaskIds, [T1, T2]);
});
test('planInboxRepair: each moved task gets a full create then an update, then its tags', () => {
const tasks = [
taskRow(T1, LOCAL_INBOX_ID, {
title: 'Lait',
notes: 'deux litres',
completed: true,
completedAt: new Date('2026-10-24T09:00:00.000Z'),
priority: 2,
dueDate: new Date('2026-10-26T00:00:00.000Z'),
position: 3,
recurrence: 'weekly',
calendarEventId: 'cal-1',
}),
taskRow(T2, LOCAL_INBOX_ID, { parentId: T1 }),
];
const taskTags = [{ taskId: T1, tagId: TAG_A }, { taskId: T3, tagId: TAG_B }];
const p = plan([fixedInbox, serverInbox], tasks, [], taskTags);
assert.deepEqual(
p.ops.map((o) => [o.entityType, o.entityId, o.action]),
[
['task', T1, 'create'],
['task', T1, 'update'],
['taskTag', T1, 'create'],
['task', T2, 'create'],
['task', T2, 'update'],
],
);
const expected = {
id: T1,
title: 'Lait',
notes: 'deux litres',
completed: true,
completedAt: '2026-10-24T09:00:00.000Z',
priority: 2,
dueDate: '2026-10-26T00:00:00.000Z',
listId: SERVER_INBOX,
parentId: null,
position: 3,
recurrence: 'weekly',
};
assert.deepEqual(p.ops[0].payload, expected);
assert.deepEqual(p.ops[1].payload, expected);
assert.deepEqual(p.ops[2].payload, { tagId: TAG_A });
assert.equal(p.ops[3].payload.parentId, T1);
assert.equal(p.ops[4].payload.listId, SERVER_INBOX);
// The calendar id is local-only, never pushed
assert.equal('calendarEventId' in p.ops[0].payload, false);
});
test('planInboxRepair: op createdAt strictly increase from now, so the push sends the create first', () => {
const tasks = [taskRow(T1, LOCAL_INBOX_ID), taskRow(T2, LOCAL_INBOX_ID)];
const p = plan([fixedInbox, serverInbox], tasks, [], [{ taskId: T1, tagId: TAG_A }]);
const times = p.ops.map((o) => new Date(o.createdAt).getTime());
assert.equal(p.ops[0].createdAt, REPAIR_NOW.toISOString());
for (let i = 1; i < times.length; i++) assert.ok(times[i] > times[i - 1], `op ${i} not after op ${i - 1}`);
});
test('planInboxRepair: pending entries of a moved task are discarded, its pending tag removals re-queued', () => {
const outbox = [
outboxRow('c1', 'task', T1, 'create', { id: T1, listId: LOCAL_INBOX_ID }),
outboxRow('u1', 'task', T1, 'update', { id: T1, title: 'x' }),
outboxRow('ta', 'taskTag', T1, 'create', { tagId: TAG_A }),
outboxRow('tb', 'taskTag', T1, 'delete', { tagId: TAG_B }),
outboxRow('ta2', 'taskTag', T1, 'delete', { tagId: TAG_A }),
outboxRow('ta3', 'taskTag', T1, 'create', { tagId: TAG_A }),
outboxRow('o3', 'task', T3, 'update', { id: T3, title: 'y', listId: OTHER_LIST }),
];
const p = plan([fixedInbox, serverInbox], [taskRow(T1, LOCAL_INBOX_ID)], outbox, [{ taskId: T1, tagId: TAG_A }]);
assert.deepEqual(p.discardIds, ['c1', 'u1', 'ta', 'tb', 'ta2', 'ta3']);
assert.deepEqual(p.rewrites, []);
assert.deepEqual(
p.ops.map((o) => [o.entityType, o.action, o.payload.tagId ?? null]),
[
['task', 'create', null],
['task', 'update', null],
['taskTag', 'create', TAG_A],
['taskTag', 'delete', TAG_B],
],
);
});
test('planInboxRepair: a tag removed then added back is not re-queued as a removal', () => {
const outbox = [
outboxRow('d', 'taskTag', T1, 'delete', { tagId: TAG_B }),
outboxRow('c', 'taskTag', T1, 'create', { tagId: TAG_B }),
];
// TAG_B is no longer on the task locally (removed by a pull, say): no op for it
const p = plan([fixedInbox, serverInbox], [taskRow(T1, LOCAL_INBOX_ID)], outbox);
assert.deepEqual(p.ops.map((o) => o.entityType), ['task', 'task']);
});
test('planInboxRepair: other pending entries that carry the fixed listId are rewritten to the real Inbox', () => {
const outbox = [
outboxRow('c4', 'task', T4, 'create', { id: T4, title: 'x', listId: LOCAL_INBOX_ID, completed: false }),
outboxRow('d4', 'task', T4, 'delete', { id: T4 }),
outboxRow('o3', 'task', T3, 'update', { id: T3, title: 'y', listId: OTHER_LIST }),
];
const p = plan([fixedInbox, serverInbox], [], outbox);
assert.deepEqual(p.rewrites, [
{ id: 'c4', payload: JSON.stringify({ id: T4, title: 'x', listId: SERVER_INBOX, completed: false }) },
]);
assert.deepEqual(p.discardIds, []);
});
test('planInboxRepair: pending list entries of the fixed Inbox are discarded, the server never had it', () => {
const outbox = [
outboxRow('l1', 'list', LOCAL_INBOX_ID, 'update', { id: LOCAL_INBOX_ID, name: 'Boîte' }),
outboxRow('l2', 'list', OTHER_LIST, 'update', { id: OTHER_LIST, name: 'Courses' }),
outboxRow('l3', 'list', LOCAL_INBOX_ID, 'delete', { id: LOCAL_INBOX_ID }),
];
const p = plan([fixedInbox, serverInbox], [], outbox);
assert.deepEqual(p.discardIds, ['l1', 'l3']);
assert.deepEqual(p.rewrites, []);
});
test('planInboxRepair: an unreadable payload is left alone', () => {
const outbox = [outboxRow('bad', 'task', T4, 'create', '{not json'), outboxRow('nul', 'task', T4, 'create', 'null')];
const p = plan([fixedInbox, serverInbox], [], outbox);
assert.deepEqual(p.rewrites, []);
assert.deepEqual(p.discardIds, []);
});
test('planInboxRepair: a split without tasks or outbox still removes the fixed Inbox', () => {
const p = plan([fixedInbox, serverInbox], []);
assert.equal(p.inboxId, SERVER_INBOX);
assert.deepEqual(p.movedTaskIds, []);
assert.deepEqual(p.ops, []);
});
test('planInboxRepair: idempotent, the repaired state needs no repair', () => {
const lists = [fixedInbox, serverInbox];
const tasks = [taskRow(T1, LOCAL_INBOX_ID)];
const p = plan(lists, tasks);
const repairedTasks = tasks.map((t) => (p.movedTaskIds.includes(t.id) ? { ...t, listId: p.inboxId } : t));
assert.equal(plan(lists.filter((l) => l.id !== LOCAL_INBOX_ID), repairedTasks), null);
});
// Minimal model of POST /api/sync (web/src/app/api/sync/route.ts) for tasks
// and task-tag links: a create on an existing id does nothing, an update, a
// delete or a link on a missing task is refused, a task in an unknown list is
// refused. Refused keys are not remembered.
function fakeServer({ lists, tasks, tags }) {
const state = { lists: new Set(lists), tasks: new Map(tasks), tags: new Set(tags), links: new Set() };
const apply = (e) => {
const d = JSON.parse(e.payload);
if (e.entityType === 'task') {
if (e.action === 'create') {
if (!state.lists.has(d.listId)) throw new Error('unknown list');
if (!state.tasks.has(e.entityId)) state.tasks.set(e.entityId, { listId: d.listId, deleted: false });
return;
}
const t = state.tasks.get(e.entityId);
if (!t) throw new Error('unknown task');
if (e.action === 'delete') t.deleted = true;
else if (d.listId) {
if (!state.lists.has(d.listId)) throw new Error('unknown list');
t.listId = d.listId;
}
return;
}
if (e.entityType === 'taskTag') {
if (!state.tasks.has(e.entityId)) throw new Error('unknown task');
if (!state.tags.has(d.tagId)) throw new Error('unknown tag');
const key = `${e.entityId}:${d.tagId}`;
if (e.action === 'create') state.links.add(key);
else state.links.delete(key);
return;
}
if (e.entityType === 'list') throw new Error('unknown list');
};
const push = (entries) =>
entries.map((e) => {
try {
apply(e);
return { idempotencyKey: e.id, status: 'applied' };
} catch (err) {
return { idempotencyKey: e.id, status: 'skipped', error: err.message };
}
});
return { state, push };
}
// Apply a plan to the pending outbox, as repairInbox does
function repairedOutbox(outbox, p) {
const discard = new Set(p.discardIds);
const rewrite = new Map(p.rewrites.map((r) => [r.id, r.payload]));
const kept = outbox
.filter((e) => !discard.has(e.id))
.map((e) => (rewrite.has(e.id) ? { ...e, payload: rewrite.get(e.id) } : e));
const added = p.ops.map((o, i) => ({
id: `op${i}`,
entityType: o.entityType,
entityId: o.entityId,
action: o.action,
payload: JSON.stringify(o.payload),
createdAt: o.createdAt,
}));
return [...kept, ...added].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
}
test('planInboxRepair: the repaired outbox of a split device is pushed without a single refusal', () => {
// T1: created under the fixed Inbox, its create refused then dropped by an
// app older than #151; edited and tagged since, a tag removed.
// T2: known to the server in OTHER_LIST, moved to the fixed Inbox (refused).
// T4: created under the fixed Inbox, then deleted, both still pending.
const server = fakeServer({ lists: [SERVER_INBOX, OTHER_LIST], tasks: [[T2, { listId: OTHER_LIST, deleted: false }]], tags: [TAG_A, TAG_B] });
const outbox = [
outboxRow('u1', 'task', T1, 'update', { id: T1, title: 'x', listId: LOCAL_INBOX_ID }),
outboxRow('ta', 'taskTag', T1, 'create', { tagId: TAG_A }),
outboxRow('tb', 'taskTag', T1, 'create', { tagId: TAG_B }),
outboxRow('tb2', 'taskTag', T1, 'delete', { tagId: TAG_B }),
outboxRow('u2', 'task', T2, 'update', { id: T2, listId: LOCAL_INBOX_ID }),
outboxRow('c4', 'task', T4, 'create', { id: T4, title: 'z', listId: LOCAL_INBOX_ID }),
outboxRow('d4', 'task', T4, 'delete', { id: T4 }),
outboxRow('l1', 'list', LOCAL_INBOX_ID, 'update', { id: LOCAL_INBOX_ID, name: 'Boîte' }),
];
const tasks = [taskRow(T1, LOCAL_INBOX_ID), taskRow(T2, LOCAL_INBOX_ID)];
const p = plan([fixedInbox, serverInbox, otherList], tasks, outbox, [{ taskId: T1, tagId: TAG_A }]);
const entries = repairedOutbox(outbox, p);
// Without the repair, the same outbox is refused (the guard of this test)
const before = fakeServer({ lists: [SERVER_INBOX, OTHER_LIST], tasks: [[T2, { listId: OTHER_LIST, deleted: false }]], tags: [TAG_A, TAG_B] });
assert.ok(before.push(outbox).some((r) => r.error), 'the unrepaired outbox must hold refusals');
const results = server.push(entries);
assert.deepEqual(results.filter((r) => r.error), []);
const c = classifyOutbox(entries, results, REPAIR_NOW);
assert.equal(c.droppedRefusals, 0);
assert.equal(c.keptRefusals, 0);
assert.equal(c.markIds.length, entries.length);
assert.deepEqual(server.state.tasks.get(T1), { listId: SERVER_INBOX, deleted: false });
assert.deepEqual(server.state.tasks.get(T2), { listId: SERVER_INBOX, deleted: false });
assert.deepEqual(server.state.tasks.get(T4), { listId: SERVER_INBOX, deleted: true });
assert.deepEqual([...server.state.links], [`${T1}:${TAG_A}`]);
});