Merge branch 'issue-181-tag-updated-at' into issue-182-web-tag-crud

This commit is contained in:
le king fu 2026-11-03 21:13:20 -05:00
commit 99d2323a93
5 changed files with 109 additions and 7 deletions

View file

@ -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<string, unknown>
): Promise<void> {
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<typeof db, 'insert'>;
/**
* 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<void> {
const { syncEnabled } = useSettingsStore.getState();
if (!syncEnabled || entries.length === 0) return;
if ((!syncEnabled && !firstSyncInProgress) || entries.length === 0) return;
const rows = entries.map((e) => ({
id: randomUUID(),

View file

@ -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,
@ -23,6 +23,7 @@ import {
sendInBatches,
pendingTagIdsByTask,
alignedTagIds,
remapInboxEntry,
type PostResponse,
} from '@/src/services/syncRules';
import {
@ -449,10 +450,12 @@ export async function pushBeforeSignOut(): Promise<number> {
*/
export async function initialMerge(accountId: string): Promise<void> {
await scheduler.beginInitialSync();
setFirstSyncInProgress(true);
try {
await mergeLocalData();
useSettingsStore.getState().setDataOwnerId(accountId);
} finally {
setFirstSyncInProgress(false);
scheduler.endInitialSync();
}
}
@ -556,6 +559,12 @@ async function mergeLocalData(): Promise<void> {
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({
@ -582,10 +591,12 @@ async function mergeLocalData(): Promise<void> {
*/
export async function initialReset(accountId: string): Promise<void> {
await scheduler.beginInitialSync();
setFirstSyncInProgress(true);
try {
await resetFromServer();
useSettingsStore.getState().setDataOwnerId(accountId);
} finally {
setFirstSyncInProgress(false);
scheduler.endInitialSync();
}
}

View file

@ -658,3 +658,34 @@ export function alignedTagIds(server: Iterable<string>, local: Iterable<string>,
}
return keep;
}
/**
* 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<string, unknown>;
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;
}

View file

@ -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,29 @@ 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');
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
// 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

View file

@ -37,6 +37,7 @@ import {
pickInboxId,
planInboxRepair,
firstSyncChoice,
remapInboxEntry,
} from '../src/services/syncRules.ts';
const ID = '11111111-1111-4111-8111-111111111111';
@ -945,3 +946,29 @@ test('phone removal then pull: the delete entry keeps the link removed until pus
// 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']);
});
// 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);
});