Skip to content

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

fix(media): sync annotations across shared buckets with per-author attribution

[._.]/ Adam Eivy5da80617265f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ba3a152053..be8959ef07 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -12,4 +12,6 @@
## Fixed
+- **Media annotations now sync across PortOS instances via shared Drive buckets, with per-author attribution.** Previously, a note or star added on one machine was invisible to peers sharing the same Drive bucket — `data/media-annotations.json` lived purely client-local. Storage is now per-author: each instance owns its own `instanceId` sub-entry under each `<kind>:<ref>` key (`{ authors: { [instanceId]: { authorName, starred, note, updatedAt } } }`), so my notes never clobber yours and vice versa. A new manifest kind (`media-annotations`) carries each instance's annotation snapshot into every auto-merge bucket via a stable filename (`annotations-<instanceId>.json`), debounced 2s after the last local edit. The export is per-bucket scoped to assets actually present in that bucket, so a private annotation can't leak into an unrelated share. On import, peer records merge per-author by `updatedAt` LWW and re-broadcast `media:annotation:updated` so open clients refresh without a reload. Stars are also per-author — "my favorites" remains my view, not a tug-of-war. The lightbox now shows my note in the editable textarea and "Notes from others" as labeled read-only blocks below (with the peer's display name + their star). Migration `012-attribute-existing-annotations.js` rewraps existing notes under the local instance's id on first run.
+
## Removed
diff --git a/PLAN.md b/PLAN.md
index 04dbb710b6..98ba00ae70 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -259,3 +259,7 @@ Skeleton landed in `server/services/pipeline/` + `client/src/pages/Pipeline*.jsx
- [ ] **Teach `request()` in `client/src/services/apiCore.js` about FormData.** Two helpers today bypass `request()` because it hard-codes `Content-Type: application/json`: `apiHealth.js#uploadAppleHealthXml` and `apiPipeline.js#uploadPipelineMusicTrack`. Each re-implements the error-shape extraction (`{ error, code, status }`) inline. Fix: in `request()`, when `body instanceof FormData`, omit the `Content-Type` header so the browser sets `multipart/form-data; boundary=...` automatically. Both call sites then collapse to a single `request()` call. Surfaced from the /simplify pass on Phase 4c.
- [ ] **Per-panel/scene image progress in the Pipeline UI.** Right now ComicPages and Storyboards record `jobId` but don't subscribe to the media-job SSE for live preview. Tie into the existing per-job progress hook so each panel shows live render thumbnails.
- [ ] **Bulk reassign helper to collapse N+1 writes in `deleteSeason`.** `server/services/pipeline/seasons.js#deleteSeason` reassigns each child issue via `issuesSvc.updateIssue(..., { skipRenumber: true })` in a loop, then runs one final `recomputeIssueNumbersForSeries`. Each `updateIssue` still calls `writeState` on `pipeline-issues.json`, so a 50-issue volume = 51 sequential `atomicWrite` calls. Add `issuesSvc.bulkReassignSeason(seriesId, fromSeasonId, toSeasonId)` that does one `readState` + N in-memory mutations + one `writeState` + one renumber. Surfaced from /simplify on the volume-ordered numbering fix (2026-05-16).
+- [ ] **`useMediaAnnotations.getCardProps(key)` helper.** The 4 gallery pages (`VideoGen.jsx`, `ImageGen.jsx`, `MediaCollectionDetail.jsx`, `MediaHistory.jsx`) repeat `starred={!!annotations[key]?.starred} hasNote={!!annotations[key]?.anyNote}` at 6 sites total. A single `getCardProps(key) → { starred, hasNote, onToggleStar }` helper on the hook collapses each site to `{...getCardProps(item.key)}` and removes the `anyNote` vs `note` foot-gun this PR had to chase across 4 files. Surfaced from /simplify on the multi-author annotations PR (2026-05-16).
+- [ ] **Cache `resolveGlobalDisplayName()` settings read.** Every annotation write reads `data/settings.json` to resolve `sharingDisplayName`. Cheap, but called per PATCH (sharing export is debounced 2s, but `setAnnotation()` is not). Either memoize for ~30s in `server/services/sharing/annotationIdentity.js`, or invalidate on a `settings:updated` event. Surfaced from /simplify on the multi-author annotations PR (2026-05-16).
+- [ ] **Shallow-equal guard in `useMediaAnnotations` socket handler.** A peer's debounced annotation flush re-broadcasts even when their record's contents are byte-identical. The client's `onUpdate` always calls `setAnnotations`, re-rendering every gallery card. Add a JSON-equal short-circuit before the setState. Theoretical until observed; speculative micro-opt. Surfaced from /simplify on the multi-author annotations PR (2026-05-16).
+- [ ] **Hoist identity lookup out of `liftLegacyEntry` loop in `mediaAnnotations.js#readAll()`.** Post-migration-012 the `for (...) await liftLegacyEntry` loop is a microtask penalty per entry with no real I/O. Pre-migration it does `getInstanceId() + resolveLocalAuthorName()` per legacy entry serially. Make `liftLegacyEntry` synchronous and pass `localInstanceId, defaultAuthorName` in once. Surfaced from /simplify on the multi-author annotations PR (2026-05-16).
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsx
index 514cf0656f..0d9646fa68 100644
--- a/client/src/components/media/MediaLightbox.jsx
+++ b/client/src/components/media/MediaLightbox.jsx
@@ -252,6 +252,31 @@ export default function MediaLightbox({
);
}
+function PeerNotes({ others }) {
+ if (!Array.isArray(others) || others.length === 0) return null;
+ return (
+ <div>
+ <div className="mb-1">
+ <span className="text-gray-500 uppercase tracking-wide text-xs">Notes from others</span>
+ </div>
+ <ul className="space-y-2">
+ {others.map((o) => (
+ <li key={o.instanceId} className="rounded border border-port-border bg-port-bg/50 p-2">
+ <div className="flex items-center justify-between text-[10px] text-gray-500 mb-1">
+ <span className="flex items-center gap-1.5 text-gray-300">
+ {o.starred && <Star className="w-3 h-3 fill-current text-port-warning" />}
+ <span>{o.authorName || 'Unknown'}</span>
+ </span>
+ <span>{o.updatedAt ? new Date(o.updatedAt).toLocaleDateString() : ''}</span>
+ </div>
+ {o.note && <p className="text-gray-200 whitespace-pre-wrap text-xs">{o.note}</p>}
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
+
function SettingsPane({
item, meta, isVideo,
onClose, onRemix, onSendToVideo, onContinue, onClean,
@@ -358,7 +383,7 @@ function SettingsPane({
{onAnnotationChange && (
<div>
<div className="flex items-center justify-between mb-1">
- <span className="text-gray-500 uppercase tracking-wide">Notes</span>
+ <span className="text-gray-500 uppercase tracking-wide">My note</span>
<div className="flex items-center gap-2 text-[10px] text-gray-500">
{saveStatus === 'pending' && <span>Saving…</span>}
{saveStatus === 'saved' && <span className="text-port-success">Saved</span>}
@@ -377,6 +402,8 @@ function SettingsPane({
</div>
)}
+ <PeerNotes others={annotation?.others} />
+
{item.negativePrompt && (
<div>
<div className="flex items-center justify-between mb-1">
diff --git a/client/src/hooks/useMediaAnnotations.js b/client/src/hooks/useMediaAnnotations.js
index 3444b3144d..20c77dc7ca 100644
--- a/client/src/hooks/useMediaAnnotations.js
+++ b/client/src/hooks/useMediaAnnotations.js
@@ -3,36 +3,56 @@ import { listMediaAnnotations, setMediaAnnotation } from '../services/api';
import socket from '../services/socket';
import toast from '../components/ui/Toast';
-// Loads the full media-annotation map once and exposes optimistic-update
-// helpers. Shared by every gallery surface (MediaHistory, ImageGen, VideoGen,
-// MediaCollectionDetail) so favorites stay in sync across pages and the same
-// optimistic-update / revert behavior lives in one place.
-//
-// Returns:
-// annotations — { [key]: { starred, note, updatedAt } }
-// toggleStar(item) — flips starred for item.key (optimistic + revert on error)
-// updateAnnotation(key, patch) — generic partial update used by the lightbox note editor
+// Per-entry: `own`/`others` from the server, plus back-compat aliases
+// (`starred`/`note`/`updatedAt` = local author) and `anyNote` for the
+// card-level "has notes" indicator (true when any author has a note).
+function enrich(entry) {
+ if (!entry || typeof entry !== 'object') return null;
+ const own = entry.own || null;
+ const others = Array.isArray(entry.others) ? entry.others : [];
+ return {
+ own,
+ others,
+ starred: !!own?.starred,
+ note: own?.note ?? '',
+ updatedAt: own?.updatedAt ?? null,
+ anyStarred: !!own?.starred || others.some((o) => o.starred),
+ anyNote: !!(own?.note) || others.some((o) => o.note),
+ };
+}
+
+function enrichAll(raw) {
+ const out = {};
+ for (const [key, entry] of Object.entries(raw || {})) {
+ const e = enrich(entry);
+ if (e) out[key] = e;
+ }
+ return out;
+}
+
export function useMediaAnnotations() {
const [annotations, setAnnotations] = useState({});
useEffect(() => {
let cancelled = false;
listMediaAnnotations().then(
- (res) => { if (!cancelled) setAnnotations(res?.annotations || {}); },
+ (res) => { if (!cancelled) setAnnotations(enrichAll(res?.annotations)); },
() => { /* fallback to empty map — non-fatal */ },
);
return () => { cancelled = true; };
}, []);
- // Mirror server broadcasts so a note/star toggle in one view (or browser tab)
- // shows up in every other open consumer. Originator also receives this; the
- // server entry is authoritative and overrides the optimistic merge.
+ // Mirror server broadcasts so a note/star toggle in one view (or browser tab,
+ // or a peer's machine via the sharing pipeline) shows up in every other open
+ // consumer. The originator also receives this; the server entry is
+ // authoritative and overrides the optimistic merge.
useEffect(() => {
const onUpdate = ({ key, entry }) => {
if (!key) return;
setAnnotations((prev) => {
const next = { ...prev };
- if (entry) next[key] = entry;
+ const enriched = enrich(entry);
+ if (enriched) next[key] = enriched;
else delete next[key];
return next;
});
@@ -42,18 +62,25 @@ export function useMediaAnnotations() {
}, []);
const updateAnnotation = useCallback(async (key, patch) => {
- // Snapshot prior state for revert; build optimistic next state.
let prior;
setAnnotations((prev) => {
prior = prev[key];
- const merged = {
- starred: 'starred' in patch ? patch.starred : (prior?.starred ?? false),
- note: 'note' in patch ? patch.note : (prior?.note ?? ''),
+ const priorOwn = prior?.own ?? null;
+ const mergedOwn = {
+ authorName: priorOwn?.authorName ?? '',
+ starred: 'starred' in patch ? patch.starred : (priorOwn?.starred ?? false),
+ note: 'note' in patch ? patch.note : (priorOwn?.note ?? ''),
updatedAt: new Date().toISOString(),
};
+ const others = prior?.others ?? [];
+ const ownEmpty = !mergedOwn.starred && !mergedOwn.note;
+ const nextEntry = enrich({
+ own: ownEmpty ? null : mergedOwn,
+ others,
+ });
const next = { ...prev };
- if (!merged.starred && !merged.note) delete next[key];
- else next[key] = merged;
+ if (!nextEntry || (!nextEntry.own && nextEntry.others.length === 0)) delete next[key];
+ else next[key] = nextEntry;
return next;
});
const res = await setMediaAnnotation(key, patch).catch((err) => {
@@ -75,7 +102,7 @@ export function useMediaAnnotations() {
const toggleStar = useCallback((item) => {
if (!item?.key) return;
setAnnotations((prev) => {
- updateAnnotation(item.key, { starred: !prev[item.key]?.starred });
+ updateAnnotation(item.key, { starred: !prev[item.key]?.own?.starred });
return prev;
});
}, [updateAnnotation]);
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 5f2a04ff75..110efb726f 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -1164,7 +1164,7 @@ export default function ImageGen() {
onDelete={() => handleDelete(img.filename)}
onToggleHidden={() => handleToggleHidden(item)}
starred={!!annotations[item.key]?.starred}
- hasNote={!!annotations[item.key]?.note}
+ hasNote={!!annotations[item.key]?.anyNote}
onToggleStar={toggleStar}
/>
);
@@ -1198,7 +1198,7 @@ export default function ImageGen() {
onDelete={() => handleDelete(img.filename)}
onToggleHidden={() => handleToggleHidden(item)}
starred={!!annotations[item.key]?.starred}
- hasNote={!!annotations[item.key]?.note}
+ hasNote={!!annotations[item.key]?.anyNote}
onToggleStar={toggleStar}
/>
);
diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsx
index 9e6400d27c..7112804897 100644
--- a/client/src/pages/MediaCollectionDetail.jsx
+++ b/client/src/pages/MediaCollectionDetail.jsx
@@ -462,7 +462,7 @@ export default function MediaCollectionDetail() {
hideActions={selectMode}
selected={isSelected}
starred={!!annotations[key]?.starred}
- hasNote={!!annotations[key]?.note}
+ hasNote={!!annotations[key]?.anyNote}
onToggleStar={!selectMode ? toggleStar : undefined}
/>
{!selectMode && !isUnsorted && (
diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsx
index 7e85545e66..daaec4e92c 100644
--- a/client/src/pages/MediaHistory.jsx
+++ b/client/src/pages/MediaHistory.jsx
@@ -303,7 +303,7 @@ export default function MediaHistory() {
disabled={stitchMode && it.kind !== 'video'}
hideActions={stitchMode}
starred={!!annotations[it.key]?.starred}
- hasNote={!!annotations[it.key]?.note}
+ hasNote={!!annotations[it.key]?.anyNote}
onToggleStar={!stitchMode ? toggleStar : undefined}
/>
);
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index cec3cb1f49..9f9ea6ed6c 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -1329,7 +1329,7 @@ export default function VideoGen() {
onDelete={() => handleDeleteHistory(v)}
onToggleHidden={() => handleToggleHistoryHidden(v)}
starred={!!annotations[item.key]?.starred}
- hasNote={!!annotations[item.key]?.note}
+ hasNote={!!annotations[item.key]?.anyNote}
onToggleStar={toggleStar}
/>
);
@@ -1362,7 +1362,7 @@ export default function VideoGen() {
onDelete={() => handleDeleteHistory(v)}
onToggleHidden={() => handleToggleHistoryHidden(v)}
starred={!!annotations[item.key]?.starred}
- hasNote={!!annotations[item.key]?.note}
+ hasNote={!!annotations[item.key]?.anyNote}
onToggleStar={toggleStar}
/>
);
diff --git a/scripts/migrations/012-attribute-existing-annotations.js b/scripts/migrations/012-attribute-existing-annotations.js
new file mode 100644
index 0000000000..b9077c6c4b
--- /dev/null
+++ b/scripts/migrations/012-attribute-existing-annotations.js
@@ -0,0 +1,75 @@
+/**
+ * Rewrap data/media-annotations.json into the multi-author shape.
+ *
+ * Before: `{ annotations: { [key]: { starred, note, updatedAt } } }`
+ * After: `{ annotations: { [key]: { authors: { [instanceId]: { authorName, starred, note, updatedAt } } } } }`
+ *
+ * Every existing entry is attributed to the local instance — the user wrote
+ * those notes here, so they should stay editable in their own textarea and
+ * (once exported) appear attributed on peers' machines. Idempotent: any entry
+ * that already has an `authors` field is left alone.
+ *
+ * Reads identity from data/instances.json (self.instanceId / self.name).
+ * Falls back to a deterministic placeholder if instances.json is missing —
+ * the multi-author service still works with a `'unknown'` author entry, and
+ * the placeholder gets overwritten the first time the user edits the note
+ * (setAnnotation always stamps with the real instanceId).
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+
+async function readJsonOr(path, fallback) {
+ if (!existsSync(path)) return fallback;
+ const raw = await readFile(path, 'utf8').catch(() => null);
+ if (!raw) return fallback;
+ return JSON.parse(raw);
+}
+
+export default {
+ async up({ rootDir }) {
+ const annotationsPath = join(rootDir, 'data', 'media-annotations.json');
+ if (!existsSync(annotationsPath)) {
+ return { changed: false, reason: 'no-annotations-file' };
+ }
+ const state = await readJsonOr(annotationsPath, { annotations: {} });
+ const entries = state?.annotations && typeof state.annotations === 'object'
+ ? state.annotations
+ : {};
+
+ const instancesPath = join(rootDir, 'data', 'instances.json');
+ const instances = await readJsonOr(instancesPath, { self: null });
+ const instanceId = instances?.self?.instanceId || 'unknown';
+ const authorName = instances?.self?.name || '';
+
+ let migrated = 0;
+ let alreadyCurrent = 0;
+ const next = {};
+ for (const [key, entry] of Object.entries(entries)) {
+ if (!entry || typeof entry !== 'object') continue;
+ if (entry.authors && typeof entry.authors === 'object') {
+ next[key] = entry;
+ alreadyCurrent += 1;
+ continue;
+ }
+ const starred = entry.starred === true;
+ const note = typeof entry.note === 'string' ? entry.note : '';
+ if (!starred && !note) continue;
+ const updatedAt = typeof entry.updatedAt === 'string' ? entry.updatedAt : new Date().toISOString();
+ next[key] = {
+ authors: {
+ [instanceId]: { authorName, starred, note, updatedAt },
+ },
+ };
+ migrated += 1;
+ }
+
+ if (migrated === 0) {
+ return { changed: false, alreadyCurrent };
+ }
+ await writeFile(annotationsPath, JSON.stringify({ annotations: next }, null, 2));
+ console.log(`📝 migration 012: attributed ${migrated} annotation(s) to instanceId=${instanceId} (already-multi-author=${alreadyCurrent})`);
+ return { changed: true, migrated, alreadyCurrent };
+ },
+};
diff --git a/server/routes/mediaAnnotations.js b/server/routes/mediaAnnotations.js
index f1b530ef69..1f55a82103 100644
--- a/server/routes/mediaAnnotations.js
+++ b/server/routes/mediaAnnotations.js
@@ -1,7 +1,10 @@
/**
- * GET /api/media/annotations → { [key]: { starred, note, updatedAt } }
- * PATCH /api/media/annotations/:key → updated entry or null (if pruned)
- * body: { starred?: boolean, note?: string }
+ * GET /api/media/annotations
+ * → { [key]: { own: { authorName, starred, note, updatedAt } | null,
+ * others: [{ instanceId, authorName, starred, note, updatedAt }] } }
+ * PATCH /api/media/annotations/:key
+ * body: { starred?: boolean, note?: string } — writes the local-author entry
+ * → { key, entry: { own, others } }
*
* Key shape: `<kind>:<ref>` where kind ∈ {image, video} and ref has no `:`.
* Matches the convention enforced by mediaCollections.js and produced by the
@@ -39,12 +42,13 @@ router.patch('/:key', asyncHandler(async (req, res) => {
const body = validateRequest(patchSchema, req.body ?? {});
// Express decodes the path param, but the key still has to round-trip through
// svc validation so a hand-rolled curl can't sneak past.
- const updated = await svc.setAnnotation(req.params.key, body).catch((err) => { throw mapServiceError(err); });
+ const entry = await svc.setAnnotation(req.params.key, body).catch((err) => { throw mapServiceError(err); });
// Broadcast so every other open view (History, Collections, Pipeline, other
- // browser tabs) reflects the change without a manual refresh. `entry` is null
- // when the annotation was pruned (both starred=false and note='').
- req.app.get('io')?.emit('media:annotation:updated', { key: req.params.key, entry: updated });
- res.json({ key: req.params.key, entry: updated });
+ // browser tabs) reflects the change without a manual refresh. Payload mirrors
+ // the GET shape: `entry` is `{ own, others }` (with own=null when the local
+ // author cleared their entry but peer notes remain).
+ req.app.get('io')?.emit('media:annotation:updated', { key: req.params.key, entry });
+ res.json({ key: req.params.key, entry });
}));
export default router;
diff --git a/server/services/mediaAnnotations.js b/server/services/mediaAnnotations.js
index 84164e7838..4c8a964037 100644
--- a/server/services/mediaAnnotations.js
+++ b/server/services/mediaAnnotations.js
@@ -1,18 +1,15 @@
/**
- * Media Annotations
- *
- * Per-item star + free-text note, keyed by the same `<kind>:<ref>` convention
- * used by mediaCollections.js and the client-side normalize.js (`item.key`).
- * Persisted to data/media-annotations.json as a single
- * `{ annotations: { [key]: { starred, note, updatedAt } } }` document.
- *
- * Decoupled from the generation pipeline records (media-jobs.json,
- * video-history.json) so annotations survive pruning/archival of jobs.
+ * Per-author star + free-text note, keyed by `<kind>:<ref>`. Each PortOS
+ * instance only ever writes its own `instanceId` sub-entry; peer notes arrive
+ * via sharing/annotationsSync.js and merge in per-author LWW. Decoupled from
+ * media-jobs.json so annotations survive job pruning.
*/
import { join } from 'path';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';
import { isValidKey } from '../lib/mediaItemKey.js';
+import { getInstanceId } from './instances.js';
+import { resolveLocalAuthorName } from './sharing/annotationIdentity.js';
const STATE_PATH = join(PATHS.data, 'media-annotations.json');
@@ -25,7 +22,19 @@ const DEFAULT_STATE = { annotations: {} };
export { isValidKey };
-const sanitizeEntry = (raw) => {
+// Indirection avoids a circular import on sharing/annotationsSync.js.
+const localChangeListeners = new Set();
+export function onLocalAnnotationChange(fn) {
+ localChangeListeners.add(fn);
+ return () => localChangeListeners.delete(fn);
+}
+function emitLocalChange(key) {
+ for (const fn of localChangeListeners) {
+ try { fn(key); } catch (err) { console.error(`⚠️ mediaAnnotations: listener failed: ${err.message}`); }
+ }
+}
+
+function sanitizeAuthorEntry(raw) {
if (!raw || typeof raw !== 'object') return null;
const starred = raw.starred === true;
const note = typeof raw.note === 'string' ? raw.note.slice(0, NOTE_MAX_LENGTH) : '';
@@ -33,10 +42,28 @@ const sanitizeEntry = (raw) => {
const updatedAt = typeof raw.updatedAt === 'string' && !Number.isNaN(Date.parse(raw.updatedAt))
? raw.updatedAt
: new Date().toISOString();
- return { starred, note, updatedAt };
-};
+ const authorName = typeof raw.authorName === 'string' && raw.authorName.trim()
+ ? raw.authorName.trim().slice(0, 120)
+ : '';
+ return { authorName, starred, note, updatedAt };
+}
-const readAll = async () => {
+// Safety net for a stale install: migration 012 rewrites the file once, but a
+// hand-edited or pre-012 file still parses correctly here.
+async function liftLegacyEntry(rawEntry) {
+ const isLegacy = rawEntry
+ && typeof rawEntry === 'object'
+ && !rawEntry.authors
+ && ('starred' in rawEntry || 'note' in rawEntry);
+ if (!isLegacy) return rawEntry;
+ const author = sanitizeAuthorEntry(rawEntry);
+ if (!author) return null;
+ const instanceId = await getInstanceId().catch(() => 'unknown');
+ const authorName = author.authorName || await resolveLocalAuthorName().catch(() => '');
+ return { authors: { [instanceId]: { ...author, authorName } } };
+}
+
+async function readAll() {
await ensureDir(PATHS.data);
const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false });
const annotations = raw && typeof raw.annotations === 'object' && raw.annotations !== null
@@ -45,25 +72,112 @@ const readAll = async () => {
const out = {};
for (const [key, value] of Object.entries(annotations)) {
if (!isValidKey(key)) continue;
- const s = sanitizeEntry(value);
- if (s) out[key] = s;
+ const lifted = await liftLegacyEntry(value);
+ if (!lifted || !lifted.authors || typeof lifted.authors !== 'object') continue;
+ const authors = {};
+ for (const [instanceId, sub] of Object.entries(lifted.authors)) {
+ if (typeof instanceId !== 'string' || !instanceId) continue;
+ const sane = sanitizeAuthorEntry(sub);
+ if (sane) authors[instanceId] = sane;
+ }
+ if (Object.keys(authors).length > 0) out[key] = { authors };
}
return out;
-};
+}
+
+function projectForLocal(authorsMap, localInstanceId) {
+ if (!authorsMap || typeof authorsMap !== 'object') return { own: null, others: [] };
+ const own = authorsMap[localInstanceId] ?? null;
+ const others = Object.entries(authorsMap)
+ .filter(([id]) => id !== localInstanceId)
+ .map(([instanceId, entry]) => ({ instanceId, ...entry }))
+ .sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));
+ return { own, others };
+}
export async function listAnnotations() {
- return await readAll();
+ const [all, localInstanceId] = await Promise.all([
+ readAll(),
+ getInstanceId().catch(() => 'unknown'),
+ ]);
+ const out = {};
+ for (const [key, { authors }] of Object.entries(all)) {
+ out[key] = projectForLocal(authors, localInstanceId);
+ }
+ return out;
+}
+
+/** Used by sharing/annotationsSync.js to project just the local-author entries for export. */
+export async function listLocalAuthorAnnotations() {
+ const [all, localInstanceId] = await Promise.all([
+ readAll(),
+ getInstanceId().catch(() => 'unknown'),
+ ]);
+ const out = {};
+ for (const [key, { authors }] of Object.entries(all)) {
+ const entry = authors[localInstanceId];
+ if (entry) out[key] = entry;
+ }
+ return out;
}
/**
- * Partial merge with prune-on-empty.
+ * Per-author LWW: a peer payload only ever rewrites its own `instanceId`
+ * sub-entry, never another author's. Returns the changed keys AND the
+ * post-merge `{ own, others }` projection for each — so callers can broadcast
+ * without paying for a second readAll() per key.
+ *
+ * `payload` shape: `{ instanceId, authorName, annotations: { [key]: { starred, note, updatedAt } } }`.
+ */
+export async function mergePeerAnnotations(payload) {
+ if (!payload || typeof payload !== 'object') return { changed: [], projections: new Map() };
+ const peerInstanceId = typeof payload.instanceId === 'string' ? payload.instanceId : null;
+ if (!peerInstanceId) 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 = [];
+ for (const [key, rawEntry] of Object.entries(incoming)) {
+ if (!isValidKey(key)) continue;
+ const sane = sanitizeAuthorEntry({ ...rawEntry, authorName: rawEntry?.authorName || payload.authorName });
+ const prior = all[key]?.authors?.[peerInstanceId] ?? null;
+ if (!sane) {
+ if (prior) {
+ delete all[key].authors[peerInstanceId];
+ if (Object.keys(all[key].authors).length === 0) delete all[key];
+ changed.push(key);
+ }
+ continue;
+ }
+ if (prior && (prior.updatedAt || '') >= sane.updatedAt) continue;
+ 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 };
+}
+
+
+
+/**
+ * Partial merge with prune-on-empty — writes the local-instance author entry.
*
* Patch may include `starred` (boolean) and/or `note` (string). Fields not in
- * the patch keep their prior value. If the merged entry ends up with
- * `starred:false` AND an empty `note`, the entry is removed entirely to keep
- * the file lean.
+ * the patch keep their prior value (the local author's prior value, not any
+ * peer's). If the merged entry ends up with `starred:false` AND an empty
+ * `note`, the local-author entry is removed; if no authors remain on the key,
+ * the whole key is removed.
*
- * Returns the merged entry, or `null` if it was pruned.
+ * Returns the post-write projection `{ own, others }` for this key.
*/
export async function setAnnotation(key, patch) {
if (!isValidKey(key)) throw makeErr(`Invalid key: ${key}`, ERR_VALIDATION);
@@ -85,21 +199,36 @@ export async function setAnnotation(key, patch) {
throw makeErr(`note exceeds max length (${NOTE_MAX_LENGTH})`, ERR_VALIDATION);
}
- const all = await readAll();
- const prior = all[key] ?? { starred: false, note: '', updatedAt: null };
+ const [all, localInstanceId, authorName] = await Promise.all([
+ readAll(),
+ getInstanceId(),
+ resolveLocalAuthorName().catch(() => ''),
+ ]);
+ if (!localInstanceId || localInstanceId === 'unknown') {
+ throw makeErr('Local instance identity not initialized', ERR_VALIDATION);
+ }
+
+ const priorAuthors = all[key]?.authors ?? {};
+ const priorOwn = priorAuthors[localInstanceId] ?? { starred: false, note: '', updatedAt: null };
const merged = {
- starred: hasStarred ? patch.starred : prior.starred,
- note: hasNote ? patch.note : prior.note,
+ authorName: authorName || priorOwn.authorName || '',
+ starred: hasStarred ? patch.starred : priorOwn.starred,
+ note: hasNote ? patch.note : priorOwn.note,
updatedAt: new Date().toISOString(),
};
- const next = { ...all };
+ const nextAuthors = { ...priorAuthors };
if (!merged.starred && !merged.note) {
- delete next[key];
- await atomicWrite(STATE_PATH, { annotations: next });
- return null;
+ delete nextAuthors[localInstanceId];
+ } else {
+ nextAuthors[localInstanceId] = merged;
}
- next[key] = merged;
+
+ const next = { ...all };
+ if (Object.keys(nextAuthors).length === 0) delete next[key];
+ else next[key] = { authors: nextAuthors };
await atomicWrite(STATE_PATH, { annotations: next });
- return merged;
+ emitLocalChange(key);
+
+ return projectForLocal(next[key]?.authors, localInstanceId);
}
diff --git a/server/services/mediaAnnotations.test.js b/server/services/mediaAnnotations.test.js
index 418bf23eca..424aa719d8 100644
--- a/server/services/mediaAnnotations.test.js
+++ b/server/services/mediaAnnotations.test.js
@@ -9,9 +9,20 @@ vi.mock('../lib/fileUtils.js', () => ({
readJSONFile: vi.fn(async (path, fallback) => fileStore.has(path) ? fileStore.get(path) : fallback),
}));
+// Stable identity for tests — bypass the disk-backed instances service.
+const LOCAL_INSTANCE = 'local-instance-id';
+vi.mock('./instances.js', () => ({
+ getInstanceId: vi.fn(async () => LOCAL_INSTANCE),
+}));
+vi.mock('./sharing/annotationIdentity.js', () => ({
+ resolveLocalAuthorName: vi.fn(async () => 'Local User'),
+}));
+
const svc = await import('./mediaAnnotations.js');
-describe('mediaAnnotations service', () => {
+const STATE_PATH = '/mock/data/media-annotations.json';
+
+describe('mediaAnnotations service (multi-author)', () => {
beforeEach(() => {
fileStore.clear();
});
@@ -20,36 +31,126 @@ describe('mediaAnnotations service', () => {
expect(await svc.listAnnotations()).toEqual({});
});
- it('setAnnotation persists a starred entry', async () => {
+ it('setAnnotation writes local author entry and returns { own, others }', async () => {
const r = await svc.setAnnotation('image:foo.png', { starred: true });
- expect(r.starred).toBe(true);
- expect(r.note).toBe('');
- expect(typeof r.updatedAt).toBe('string');
+ expect(r.own).toMatchObject({ starred: true, note: '', authorName: 'Local User' });
+ expect(r.others).toEqual([]);
const all = await svc.listAnnotations();
- expect(all['image:foo.png'].starred).toBe(true);
- });
-
- it('setAnnotation persists a note-only entry', async () => {
- const r = await svc.setAnnotation('video:abc-1', { note: 'reshoot at 24fps' });
- expect(r.starred).toBe(false);
- expect(r.note).toBe('reshoot at 24fps');
+ expect(all['image:foo.png'].own.starred).toBe(true);
});
- it('setAnnotation partial-merges (note keeps prior starred)', async () => {
+ it('setAnnotation partial-merges within the local author entry', async () => {
await svc.setAnnotation('image:a.png', { starred: true });
const r = await svc.setAnnotation('image:a.png', { note: 'looks great' });
- expect(r.starred).toBe(true);
- expect(r.note).toBe('looks great');
+ expect(r.own.starred).toBe(true);
+ expect(r.own.note).toBe('looks great');
});
- it('setAnnotation prunes when both fields become empty', async () => {
+ it('setAnnotation prunes the local author entry when both fields empty', async () => {
await svc.setAnnotation('image:a.png', { starred: true, note: 'hi' });
const r = await svc.setAnnotation('image:a.png', { starred: false, note: '' });
- expect(r).toBeNull();
+ expect(r.own).toBeNull();
+ expect(r.others).toEqual([]);
const all = await svc.listAnnotations();
expect(all['image:a.png']).toBeUndefined();
});
+ it('setAnnotation preserves peer authors when local entry is pruned', async () => {
+ fileStore.set(STATE_PATH, {
+ annotations: {
+ 'image:a.png': {
+ authors: {
+ 'peer-1': { authorName: 'Peer', starred: true, note: 'keep me', updatedAt: '2026-01-01T00:00:00.000Z' },
+ [LOCAL_INSTANCE]: { authorName: 'Local User', starred: true, note: '', updatedAt: '2026-01-02T00:00:00.000Z' },
+ },
+ },
+ },
+ });
+ const r = await svc.setAnnotation('image:a.png', { starred: false });
+ expect(r.own).toBeNull();
+ expect(r.others).toHaveLength(1);
+ expect(r.others[0]).toMatchObject({ instanceId: 'peer-1', note: 'keep me' });
+ });
+
+ it('mergePeerAnnotations applies a peer record without touching local', async () => {
+ await svc.setAnnotation('image:a.png', { note: 'my note' });
+ const result = await svc.mergePeerAnnotations({
+ instanceId: 'peer-1',
+ authorName: 'Sam',
+ annotations: {
+ 'image:a.png': { starred: true, note: 'peer note', updatedAt: '2099-01-01T00:00:00.000Z' },
+ },
+ });
+ expect(result.changed).toEqual(['image:a.png']);
+ const all = await svc.listAnnotations();
+ expect(all['image:a.png'].own.note).toBe('my note');
+ expect(all['image:a.png'].others[0]).toMatchObject({ authorName: 'Sam', starred: true, note: 'peer note' });
+ });
+
+ it('mergePeerAnnotations is per-author LWW (older payload ignored)', async () => {
+ fileStore.set(STATE_PATH, {
+ annotations: {
+ 'image:a.png': {
+ authors: {
+ 'peer-1': { authorName: 'Sam', starred: true, note: 'newer', updatedAt: '2026-02-01T00:00:00.000Z' },
+ },
+ },
+ },
+ });
+ await svc.mergePeerAnnotations({
+ instanceId: 'peer-1',
+ authorName: 'Sam',
+ annotations: {
+ 'image:a.png': { starred: false, note: 'older', updatedAt: '2026-01-01T00:00:00.000Z' },
+ },
+ });
+ const all = await svc.listAnnotations();
+ expect(all['image:a.png'].others[0].note).toBe('newer');
+ });
+
+ it('mergePeerAnnotations refuses to write under local instanceId', async () => {
+ const result = await svc.mergePeerAnnotations({
+ instanceId: LOCAL_INSTANCE,
+ authorName: 'Spoofed',
+ annotations: {
+ 'image:a.png': { starred: true, note: 'spoofed', updatedAt: '2099-01-01T00:00:00.000Z' },
+ },
+ });
+ expect(result.changed).toEqual([]);
+ });
+
+ it('legacy single-author entries are lifted into the local author bucket on read', async () => {
+ fileStore.set(STATE_PATH, {
+ annotations: {
+ 'image:legacy.png': { starred: true, note: 'old note', updatedAt: '2025-01-01T00:00:00.000Z' },
+ },
+ });
+ const all = await svc.listAnnotations();
+ expect(all['image:legacy.png'].own).toMatchObject({ starred: true, note: 'old note' });
+ expect(all['image:legacy.png'].others).toEqual([]);
+ });
+
+ it('listLocalAuthorAnnotations returns only the local-instance entries', async () => {
+ fileStore.set(STATE_PATH, {
+ annotations: {
+ 'image:mine.png': {
+ authors: {
+ [LOCAL_INSTANCE]: { authorName: 'Local User', starred: true, note: '', updatedAt: '2026-01-01T00:00:00.000Z' },
+ 'peer-1': { authorName: 'Sam', starred: false, note: 'peer', updatedAt: '2026-01-02T00:00:00.000Z' },
+ },
+ },
+ 'image:peers-only.png': {
+ authors: {
+ 'peer-1': { authorName: 'Sam', starred: true, note: '', updatedAt: '2026-01-03T00:00:00.000Z' },
+ },
+ },
+ },
+ });
+ const mine = await svc.listLocalAuthorAnnotations();
+ expect(Object.keys(mine)).toEqual(['image:mine.png']);
+ expect(mine['image:mine.png'].starred).toBe(true);
+ });
+
it('setAnnotation rejects invalid key (no colon)', async () => {
await expect(svc.setAnnotation('foo.png', { starred: true }))
.rejects.toMatchObject({ code: svc.ERR_VALIDATION });
@@ -82,12 +183,22 @@ describe('mediaAnnotations service', () => {
});
it('listAnnotations filters out invalid keys and entries from disk', async () => {
- fileStore.set('/mock/data/media-annotations.json', {
+ fileStore.set(STATE_PATH, {
annotations: {
- 'image:good.png': { starred: true, note: '', updatedAt: '2026-01-01T00:00:00.000Z' },
- 'badkey': { starred: true },
- 'audio:foo.mp3': { starred: true },
- 'image:empty.png': { starred: false, note: '' },
+ 'image:good.png': {
+ authors: {
+ [LOCAL_INSTANCE]: { authorName: 'Local User', starred: true, note: '', updatedAt: '2026-01-01T00:00:00.000Z' },
+ },
+ },
+ 'badkey': {
+ authors: { [LOCAL_INSTANCE]: { starred: true } },
+ },
+ 'audio:foo.mp3': {
+ authors: { [LOCAL_INSTANCE]: { starred: true } },
+ },
+ 'image:empty.png': {
+ authors: { [LOCAL_INSTANCE]: { starred: false, note: '' } },
+ },
},
});
const all = await svc.listAnnotations();
diff --git a/server/services/sharing/annotationIdentity.js b/server/services/sharing/annotationIdentity.js
new file mode 100644
index 0000000000..3a4beef5e9
--- /dev/null
+++ b/server/services/sharing/annotationIdentity.js
@@ -0,0 +1,25 @@
+/**
+ * Single source of truth for the "who am I when sharing?" display name.
+ *
+ * `resolveGlobalDisplayName` returns settings.sharingDisplayName → OS user.
+ * `resolveLocalAuthorName` is the alias used by mediaAnnotations — annotation
+ * entries stamp the *global* name (no per-bucket override) so the name is
+ * consistent across every bucket the note flows into.
+ *
+ * exporter.js#resolveSourceName layers a per-bucket `displayNameOverride`
+ * short-circuit on top of this for manifest envelopes.
+ */
+
+import * as os from 'os';
+import { getSettings } from '../settings.js';
+import { isStr } from '../../lib/storyBible.js';
+
+export async function resolveGlobalDisplayName() {
+ const settings = await getSettings().catch(() => ({}));
+ if (isStr(settings?.sharingDisplayName) && settings.sharingDisplayName.trim()) {
+ return settings.sharingDisplayName.trim();
+ }
+ return os.userInfo().username || 'unknown';
+}
+
+export const resolveLocalAuthorName = resolveGlobalDisplayName;
diff --git a/server/services/sharing/annotationsSync.js b/server/services/sharing/annotationsSync.js
new file mode 100644
index 0000000000..069444ddcd
--- /dev/null
+++ b/server/services/sharing/annotationsSync.js
@@ -0,0 +1,121 @@
+/**
+ * Outgoing annotation manifest writer. One file per (bucket, instance),
+ * rewritten on a 2s debounce after any local annotation change. Inbox-mode
+ * buckets are skipped (not a fit for constant pings). Per-bucket scoping: an
+ * annotation is only written into a bucket that already has the underlying
+ * asset, so a private note can't leak into an unrelated share.
+ */
+
+import { join } from 'path';
+import { readdir } from 'fs/promises';
+import { existsSync } from 'fs';
+import { ensureDir, atomicWrite } from '../../lib/fileUtils.js';
+import { listBuckets } from './buckets.js';
+import { buildManifest, writeManifest, annotationManifestFilename } from './manifest.js';
+import { getProducedByVersion } from './version.js';
+import { getInstanceId } from '../instances.js';
+import { resolveLocalAuthorName } from './annotationIdentity.js';
+import { onLocalAnnotationChange, listLocalAuthorAnnotations } from '../mediaAnnotations.js';
+
+const DEBOUNCE_MS = 2000;
+let pendingTimer = null;
+let installed = false;
+
+async function listBucketAssetKeys(bucketPath) {
+ const keys = new Set();
+ for (const [subdir, kind] of [['images', 'image'], ['videos', 'video']]) {
+ const dir = join(bucketPath, 'assets', subdir);
+ if (!existsSync(dir)) continue;
+ const files = await readdir(dir).catch(() => []);
+ for (const f of files) {
+ if (f.endsWith('.metadata.json')) continue;
+ keys.add(`${kind}:${f}`);
+ }
+ }
+ return keys;
+}
+
+async function exportAnnotationsToBucket(bucket, localAnnotations, senderInstanceId, sourceName) {
+ if (bucket.mode !== 'auto-merge') return { skipped: true, reason: 'not-auto-merge' };
+ const assetKeys = await listBucketAssetKeys(bucket.path);
+ if (assetKeys.size === 0) return { skipped: true, reason: 'no-bucket-assets' };
+ const filtered = {};
+ for (const [key, entry] of Object.entries(localAnnotations)) {
+ if (assetKeys.has(key)) filtered[key] = entry;
+ }
+ const recordDir = join(bucket.path, 'records', 'media-annotations');
+ await ensureDir(recordDir);
+ const recordId = senderInstanceId;
+ const recordPath = join(recordDir, `${recordId}.json`);
+ const record = {
+ id: recordId,
+ instanceId: senderInstanceId,
+ authorName: sourceName,
+ updatedAt: new Date().toISOString(),
+ annotations: filtered,
+ };
+ // Always write the record even when filtered is empty — an empty payload is
+ // how we signal "I deleted all my notes on assets in this bucket" to peers.
+ await atomicWrite(recordPath, record);
+ const manifest = buildManifestForAnnotations({
+ senderInstanceId,
+ sourceName,
+ bucket,
+ recordId,
+ });
+ const filename = await writeManifest(bucket.path, manifest);
+ return { skipped: false, filename, entryCount: Object.keys(filtered).length };
+}
+
+function buildManifestForAnnotations({ senderInstanceId, sourceName, bucket, recordId }) {
+ return buildManifest({
+ kind: 'media-annotations',
+ senderInstanceId,
+ source: sourceName,
+ sourceBio: null,
+ recordIds: [recordId],
+ assetRefs: [],
+ bucketId: bucket.id,
+ bucketName: bucket.name,
+ producedByVersion: getProducedByVersion(),
+ });
+}
+
+async function flushAll() {
+ pendingTimer = null;
+ const [buckets, senderInstanceId, sourceName, localAnnotations] = await Promise.all([
+ listBuckets().catch(() => []),
+ getInstanceId().catch(() => null),
+ resolveLocalAuthorName().catch(() => 'unknown'),
+ listLocalAuthorAnnotations().catch(() => ({})),
+ ]);
+ if (!senderInstanceId || senderInstanceId === 'unknown') return;
+ const autoMerge = buckets.filter((b) => b.mode === 'auto-merge');
+ if (autoMerge.length === 0) return;
+ await Promise.all(autoMerge.map(async (bucket) => {
+ const res = await exportAnnotationsToBucket(bucket, localAnnotations, senderInstanceId, sourceName).catch((err) => {
+ console.error(`⚠️ sharing.annotations: export to bucket=${bucket.name} failed: ${err.message}`);
+ return null;
+ });
+ if (res && !res.skipped) {
+ console.log(`📤 sharing.annotations: bucket=${bucket.name} wrote ${res.entryCount} annotation(s) (${res.filename})`);
+ }
+ }));
+}
+
+function scheduleFlush() {
+ if (pendingTimer) return;
+ pendingTimer = setTimeout(() => {
+ flushAll().catch((err) => {
+ console.error(`⚠️ sharing.annotations: flushAll failed: ${err.message}`);
+ });
+ }, DEBOUNCE_MS);
+ pendingTimer.unref?.();
+}
+
+/** Install the local-annotation-change listener. Idempotent. Called once on boot. */
+export function initAnnotationsSync() {
+ if (installed) return;
+ installed = true;
+ onLocalAnnotationChange(() => scheduleFlush());
+}
diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.js
index 84b0dcea32..da178fe5de 100644
--- a/server/services/sharing/exporter.js
+++ b/server/services/sharing/exporter.js
@@ -28,16 +28,12 @@ import { getInstanceId } from '../instances.js';
import { getSettings } from '../settings.js';
import { getProducedByVersion } from './version.js';
import { isStr } from '../../lib/storyBible.js';
-import * as os from 'os';
+import { resolveGlobalDisplayName } from './annotationIdentity.js';
-/** Resolve the bucket-effective display name (per-bucket override → instance setting → OS user). */
+/** Resolve the bucket-effective display name (per-bucket override → global identity). */
async function resolveSourceName(bucket) {
if (bucket.displayNameOverride) return bucket.displayNameOverride;
- const settings = await getSettings().catch(() => ({}));
- if (isStr(settings?.sharingDisplayName) && settings.sharingDisplayName.trim()) {
- return settings.sharingDisplayName.trim();
- }
- return os.userInfo().username || 'unknown';
+ return resolveGlobalDisplayName();
}
/**
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index 361c41eeb6..65d2670240 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -33,6 +33,7 @@ import { insertUniverseWithId, updateUniverse, getUniverse } from '../universeBu
import { findOrCreateCollectionByName, addItem as addCollectionItem, ERR_DUPLICATE as COLLECTION_ERR_DUPLICATE } from '../mediaCollections.js';
import { adoptImportedSubscription, withReexportSuppressed } from './subscriptions.js';
import { getInstanceId } from '../instances.js';
+import { mergePeerAnnotations } from '../mediaAnnotations.js';
import { isStr } from '../../lib/storyBible.js';
const UNKNOWN_INSTANCE_ID = 'unknown';
@@ -160,6 +161,26 @@ async function copyAssetsLocally(bucketPath, assetRefs) {
return { copied, available, missing };
}
+async function processAnnotationManifest(bucket, manifest) {
+ const recordId = (manifest.recordIds || [])[0] || manifest.senderInstanceId;
+ if (!recordId) return { applied: 0, missing: true, reason: 'no-record-id' };
+ const recordPath = join(bucket.path, 'records', 'media-annotations', `${recordId}.json`);
+ const record = await readJSONFile(recordPath, null, { logError: false });
+ if (!record) return { applied: 0, missing: true, reason: 'record-not-synced' };
+ // record.instanceId is the source-of-truth for the author; fall back to the
+ // manifest envelope for older records that omit it.
+ const payload = {
+ instanceId: record.instanceId || manifest.senderInstanceId,
+ authorName: record.authorName || manifest.source,
+ annotations: record.annotations || {},
+ };
+ const { changed, projections } = await mergePeerAnnotations(payload);
+ for (const key of changed) {
+ sharingEvents.emit('annotation-updated', { key, entry: projections.get(key) });
+ }
+ return { applied: changed.length, changedKeys: changed };
+}
+
/** Merge bucket-bundled media-job records into local data/media-jobs.json. */
async function mergeMediaJobRecords(bucketPath, recordIds) {
const mediaDir = join(bucketPath, 'records', 'media');
@@ -424,6 +445,16 @@ export async function processManifest(bucketId, manifestFilename) {
console.log(`⚠️ sharing: bucket=${bucket.name} manifest=${manifest.id} schemaVersion=${remoteVersion} > local=${SHARING_SCHEMA_VERSION} — refusing import (peer producedBy=${manifest.producedByVersion || 'unknown'})`);
return { skipped: true, reason: 'incompatible-version', remoteVersion, localVersion: SHARING_SCHEMA_VERSION };
}
+ // Annotation manifests bypass the records/assets/applyMerge pipeline — they
+ // carry a per-instance annotation snapshot at records/media-annotations/<id>.json
+ // that merges author-by-author into data/media-annotations.json.
+ if (manifest.kind === 'media-annotations') {
+ const outcome = await processAnnotationManifest(bucket, manifest);
+ await markProcessed(bucketId, manifestFilename, manifest.id);
+ sharingEvents.emit('manifest-processed', { bucketId, manifestId: manifest.id, manifestFilename, outcome });
+ console.log(`📥 sharing: bucket=${bucket.name} manifest=${manifest.id} kind=media-annotations applied=${outcome.applied}`);
+ return { processed: true, manifest, outcome };
+ }
const { records, missing: missingRecords } = await readReferencedRecords(bucket.path, manifest);
// Always copy assets + media-job records ahead of the merge so canon and
diff --git a/server/services/sharing/index.js b/server/services/sharing/index.js
index beaeb90de6..f1868f0581 100644
--- a/server/services/sharing/index.js
+++ b/server/services/sharing/index.js
@@ -12,6 +12,7 @@ import { join } from 'path';
import { attachAllWatchers, attachWatcher, detachWatcher, shutdownAllWatchers, listAttachedWatchers } from './watcher.js';
import { sharingEvents } from './importer.js';
import { installSubscriptionListener } from './subscriptions.js';
+import { initAnnotationsSync } from './annotationsSync.js';
export { sharingEvents } from './importer.js';
export { attachWatcher, detachWatcher, listAttachedWatchers };
@@ -50,9 +51,16 @@ export async function initSharing({ io: socketIo } = {}) {
sharingEvents.on('unshared', (payload) => {
io.emit('sharing:unshared', payload);
});
+ // Peer-driven annotation merges re-use the same `media:annotation:updated`
+ // socket event the local PATCH route emits, so open UI consumers handle
+ // both transports through the same listener.
+ sharingEvents.on('annotation-updated', (payload) => {
+ io.emit('media:annotation:updated', payload);
+ });
}
installSubscriptionListener();
+ initAnnotationsSync();
const result = await attachAllWatchers();
console.log(`📡 sharing: initialized, watchers attached for ${result.attached} bucket(s)`);
return result;
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 039dd20f4d..7d6ab81c9c 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -646,4 +646,76 @@ describe('sharing round-trip', () => {
expect(replay.skipped).toBe(true);
expect(replay.reason).toBe('already-processed');
});
+
+ it('annotation manifest round-trip: peer record merges into local annotations without touching pipeline records', async () => {
+ const { sharingEvents } = await import('./importer.js');
+ const { SHARING_SCHEMA_VERSION } = await import('./version.js');
+ const mediaAnnotations = await import('../mediaAnnotations.js');
+ const bucket = await buckets.createBucket({ name: 'AnnotationsBucket', path: tempBucket, mode: 'auto-merge' });
+
+ // Stage a bucket asset so peer annotations have a corresponding key.
+ mkdirSync(join(tempBucket, 'assets', 'images'), { recursive: true });
+ writeFileSync(join(tempBucket, 'assets', 'images', 'fakeasset.png'), 'PNGSTUB');
+
+ // Hand-write a peer's annotation record + manifest. Bypasses the exporter
+ // (which would stamp the LOCAL instance id and short-circuit as
+ // self-authored on import). simulateRemoteSender is conceptually the same
+ // trick the other tests use.
+ const recordDir = join(tempBucket, 'records', 'media-annotations');
+ mkdirSync(recordDir, { recursive: true });
+ const peerRecord = {
+ id: 'peer-on-other-machine',
+ instanceId: 'peer-on-other-machine',
+ authorName: 'Sam',
+ updatedAt: '2099-01-01T00:00:00.000Z',
+ annotations: {
+ 'image:fakeasset.png': { starred: true, note: 'great shot', updatedAt: '2099-01-01T00:00:00.000Z' },
+ },
+ };
+ writeFileSync(join(recordDir, 'peer-on-other-machine.json'), JSON.stringify(peerRecord));
+
+ const peerManifest = {
+ id: 'mfst-annotations-peer',
+ schemaVersion: SHARING_SCHEMA_VERSION,
+ sharingSchemaVersion: SHARING_SCHEMA_VERSION,
+ producedByVersion: '1.0.0',
+ createdAt: '2099-01-01T00:00:00.000Z',
+ kind: 'media-annotations',
+ senderInstanceId: 'peer-on-other-machine',
+ source: 'Sam',
+ sourceBio: null,
+ bucketId: bucket.id,
+ bucketName: bucket.name,
+ recordIds: ['peer-on-other-machine'],
+ assetRefs: [],
+ note: null,
+ };
+ const filename = `annotations-peer-on-other-machine.json`;
+ mkdirSync(join(tempBucket, 'manifests'), { recursive: true });
+ writeFileSync(join(tempBucket, 'manifests', filename), JSON.stringify(peerManifest));
+
+ const events = [];
+ const onUpdate = (p) => events.push(p);
+ sharingEvents.on('annotation-updated', onUpdate);
+
+ const result = await importer.processManifest(bucket.id, filename);
+ sharingEvents.off('annotation-updated', onUpdate);
+
+ expect(result.processed).toBe(true);
+ expect(result.outcome.applied).toBe(1);
+ expect(events).toHaveLength(1);
+ expect(events[0].key).toBe('image:fakeasset.png');
+ expect(events[0].entry.others[0]).toMatchObject({ authorName: 'Sam', starred: true, note: 'great shot' });
+
+ // The peer record lives under their instanceId in local annotations; our
+ // own author entry (would-be empty in a fresh fixture) is untouched.
+ const local = await mediaAnnotations.listAnnotations();
+ expect(local['image:fakeasset.png'].own).toBeNull();
+ expect(local['image:fakeasset.png'].others[0]).toMatchObject({ authorName: 'Sam', starred: true, note: 'great shot' });
+
+ // Cursor was advanced — replay is a no-op.
+ const replay = await importer.processManifest(bucket.id, filename);
+ expect(replay.skipped).toBe(true);
+ expect(replay.reason).toBe('already-processed');
+ });
});
diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.js
index 8084ff0945..f262de69f2 100644
--- a/server/services/sharing/manifest.js
+++ b/server/services/sharing/manifest.js
@@ -21,7 +21,15 @@ import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils
import { SHARING_SCHEMA_VERSION, getProducedByVersion } from './version.js';
import { isStr } from '../../lib/storyBible.js';
-export const MANIFEST_KIND = Object.freeze(['series', 'universe', 'media']);
+export const MANIFEST_KIND = Object.freeze(['series', 'universe', 'media', 'media-annotations']);
+
+/** Deterministic filename for an instance's annotation manifest in a bucket.
+ * One file per (bucket, instanceId) — re-exports overwrite in place so peers
+ * see updates via chokidar `change` events, same pattern as subscriptions. */
+export function annotationManifestFilename(senderInstanceId) {
+ const safeId = String(senderInstanceId || 'unknown').replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 80);
+ return `annotations-${safeId}.json`;
+}
/** @deprecated Use SHARING_SCHEMA_VERSION from ./version.js. Kept exported for back-compat. */
export const MANIFEST_SCHEMA_VERSION = SHARING_SCHEMA_VERSION;
@@ -187,6 +195,9 @@ export function subscriptionFilename({ recordKind, recordId }) {
}
export function manifestFilename(manifest) {
+ if (manifest.kind === 'media-annotations') {
+ return annotationManifestFilename(manifest.senderInstanceId);
+ }
if (manifest.subscription?.recordKind && manifest.subscription?.recordId) {
return subscriptionFilename(manifest.subscription);
}
@@ -292,7 +303,7 @@ export async function pruneBucketManifests(bucket, opts = {}) {
const manifestsDir = join(bucket.path, 'manifests');
const entries = await readdir(manifestsDir).catch(() => []);
const candidates = entries
- .filter((f) => f.endsWith('.json') && !f.startsWith('sub-'))
+ .filter((f) => f.endsWith('.json') && !f.startsWith('sub-') && !f.startsWith('annotations-'))
.sort();
// Fast path: if the total candidate count is at or below the cap, no read
// of any manifest is necessary — owned count cannot exceed total.