Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: serialize media annotation merges (#4915)
[._.]/ Adam Eivy291f3ec55594
diff --git a/server/services/mediaAnnotations.js b/server/services/mediaAnnotations.jsindex 8959b7428a..b6c75b75e2 100644--- a/server/services/mediaAnnotations.js+++ b/server/services/mediaAnnotations.js@@ -7,6 +7,7 @@import { join } from 'path';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { isValidKey } from '../lib/mediaItemKey.js';import { getInstanceId, UNKNOWN_INSTANCE_ID } from './instances.js';import { resolveLocalAuthorName } from './sharing/annotationIdentity.js';@@ -19,6 +20,7 @@ const makeErr = (message, code) => Object.assign(new Error(message), { code });export const NOTE_MAX_LENGTH = 2000;const DEFAULT_STATE = { annotations: {} };+const queueWrite = createFileWriteQueue();export { isValidKey };@@ -172,14 +174,15 @@ export async function mergePeerAnnotations(payload) {// one — without this guard, every such peer would alias into the same// sentinel bucket and clobber each other on every merge.if (!peerInstanceId || peerInstanceId === UNKNOWN_INSTANCE_ID) return { changed: [], projections: new Map() };- const localInstanceId = await getInstanceId().catch(() => null);- if (peerInstanceId === localInstanceId) return { changed: [], projections: new Map() };- const incoming = payload.annotations && typeof payload.annotations === 'object'- ? payload.annotations : {};- const all = await readAll();- const changed = [];- const clampUpdatedAtTo = Date.now();- for (const [key, rawEntry] of Object.entries(incoming)) {+ return queueWrite(async () => {+ const localInstanceId = await getInstanceId().catch(() => null);+ if (peerInstanceId === localInstanceId) return { changed: [], projections: new Map() };+ const incoming = payload.annotations && typeof payload.annotations === 'object'+ ? payload.annotations : {};+ const all = await readAll();+ const changed = [];+ const clampUpdatedAtTo = Date.now();+ for (const [key, rawEntry] of Object.entries(incoming)) {if (!isValidKey(key)) continue;// A malformed payload (missing/invalid updatedAt) must be ignored entirely// rather than falling through to the tombstone branch — `sanitize` returns@@ -213,15 +216,16 @@ export async function mergePeerAnnotations(payload) {if (!all[key]) all[key] = { authors: {} };all[key].authors[peerInstanceId] = sane;changed.push(key);- }- if (changed.length > 0) {- await atomicWrite(STATE_PATH, { annotations: all });- }- const projections = new Map();- for (const key of changed) {- projections.set(key, projectForLocal(all[key]?.authors, localInstanceId));- }- return { changed, projections };+ }+ if (changed.length > 0) {+ await atomicWrite(STATE_PATH, { annotations: all });+ }+ const projections = new Map();+ for (const key of changed) {+ projections.set(key, projectForLocal(all[key]?.authors, localInstanceId));+ }+ return { changed, projections };+ });}@@ -257,14 +261,15 @@ export async function setAnnotation(key, patch) {throw makeErr(`note exceeds max length (${NOTE_MAX_LENGTH})`, ERR_VALIDATION);}- const [all, localInstanceId, authorName] = await Promise.all([- readAll(),- getInstanceId(),- resolveLocalAuthorName().catch(() => ''),- ]);- if (!localInstanceId || localInstanceId === UNKNOWN_INSTANCE_ID) {- throw makeErr('Local instance identity not initialized', ERR_VALIDATION);- }+ return queueWrite(async () => {+ const [all, localInstanceId, authorName] = await Promise.all([+ readAll(),+ getInstanceId(),+ resolveLocalAuthorName().catch(() => ''),+ ]);+ if (!localInstanceId || localInstanceId === UNKNOWN_INSTANCE_ID) {+ throw makeErr('Local instance identity not initialized', ERR_VALIDATION);+ }const priorAuthors = all[key]?.authors ?? {};const priorOwn = priorAuthors[localInstanceId] ?? { starred: false, note: '', updatedAt: null };@@ -285,8 +290,9 @@ export async function setAnnotation(key, patch) {const next = { ...all };if (Object.keys(nextAuthors).length === 0) delete next[key];else next[key] = { authors: nextAuthors };- await atomicWrite(STATE_PATH, { annotations: next });- emitLocalChange(key);+ await atomicWrite(STATE_PATH, { annotations: next });+ emitLocalChange(key);- return projectForLocal(next[key]?.authors, localInstanceId);+ return projectForLocal(next[key]?.authors, localInstanceId);+ });}diff --git a/server/services/mediaAnnotations.test.js b/server/services/mediaAnnotations.test.jsindex 41a508ae3a..f01827a2ed 100644--- a/server/services/mediaAnnotations.test.js+++ b/server/services/mediaAnnotations.test.js@@ -2,12 +2,16 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import { posixPath as toPosix } from '../lib/testHelper.js';const fileStore = new Map();+let writeDelay = 0;vi.mock('../lib/fileUtils.js', () => ({tryReadFile: vi.fn().mockResolvedValue(null),PATHS: { data: '/mock/data' },ensureDir: vi.fn().mockResolvedValue(undefined),- atomicWrite: vi.fn(async (path, data) => { fileStore.set(toPosix(path), data); }),+ atomicWrite: vi.fn(async (path, data) => {+ if (writeDelay) await new Promise((resolve) => setTimeout(resolve, writeDelay));+ fileStore.set(toPosix(path), data);+ }),readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(toPosix(path)) ? fileStore.get(toPosix(path)) : fallback)),}));@@ -28,6 +32,25 @@ const STATE_PATH = '/mock/data/media-annotations.json';describe('mediaAnnotations service (multi-author)', () => {beforeEach(() => {fileStore.clear();+ writeDelay = 0;+ });++ it('serializes concurrent local and peer read-modify-write cycles', async () => {+ writeDelay = 5;+ await Promise.all([+ svc.setAnnotation('image:local.png', { starred: true }),+ svc.mergePeerAnnotations({+ instanceId: 'peer-1',+ authorName: 'Peer',+ annotations: {+ 'image:peer.png': { starred: true, note: 'kept', updatedAt: '2026-01-01T00:00:00.000Z' },+ },+ }),+ ]);+ expect(Object.keys(fileStore.get(STATE_PATH).annotations)).toEqual([+ 'image:local.png',+ 'image:peer.png',+ ]);});it('listAnnotations returns {} for fresh state', async () => {