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 share-bucket registry changes so overlapping edits are not lost (#9771)
[._.]/ Adam Eivy0ce6e3aa5593
diff --git a/server/services/sharing/buckets.js b/server/services/sharing/buckets.jsindex 4305745378..7c238b332c 100644--- a/server/services/sharing/buckets.js+++ b/server/services/sharing/buckets.js@@ -16,6 +16,7 @@ import { access, constants, stat } from 'fs/promises';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';import { SHARING_SCHEMA_VERSION } from './version.js';import { isStr, trimTo } from '../../lib/textUtils.js';+import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';const REGISTRY_PATH = () => join(PATHS.data, 'sharing', 'buckets.json');@@ -30,6 +31,10 @@ export const ERR_NOT_FOUND = 'SHARING_BUCKET_NOT_FOUND';export const ERR_VALIDATION = 'SHARING_BUCKET_VALIDATION';export const ERR_PATH_UNUSABLE = 'SHARING_BUCKET_PATH_UNUSABLE';+// One tail for the whole registry file: every bucket shares it, so a per-id+// queue would still let two snapshots overwrite each other.+const queueRegistryWrite = createFileWriteQueue();+const makeErr = (message, code) => Object.assign(new Error(message), { code });const sanitizeBucket = (raw) => {@@ -192,59 +197,65 @@ export async function createBucket(input = {}) {const path = trimTo(input.path, PATH_MAX);if (!path) throw makeErr('Bucket path is required', ERR_VALIDATION);await assertPathUsable(path);- const state = await readRegistry();- // Reject duplicate paths so two registry entries can't both attempt to- // claim the same on-disk folder (they would fight over bucket.json + the- // watcher would double-fire on every manifest).- if (state.buckets.some((b) => b.path === path)) {- throw makeErr(`A bucket is already registered at: ${path}`, ERR_VALIDATION);- }- const now = new Date().toISOString();- const bucket = sanitizeBucket({- id: `bkt-${randomUUID()}`,- name,- path,- mode: input.mode || 'inbox',- displayNameOverride: input.displayNameOverride || null,- bioOverride: input.bioOverride || null,- createdAt: now,- updatedAt: now,+ return queueRegistryWrite(async () => {+ const state = await readRegistry();+ // Reject duplicate paths so two registry entries can't both attempt to+ // claim the same on-disk folder (they would fight over bucket.json + the+ // watcher would double-fire on every manifest).+ if (state.buckets.some((b) => b.path === path)) {+ throw makeErr(`A bucket is already registered at: ${path}`, ERR_VALIDATION);+ }+ const now = new Date().toISOString();+ const bucket = sanitizeBucket({+ id: `bkt-${randomUUID()}`,+ name,+ path,+ mode: input.mode || 'inbox',+ displayNameOverride: input.displayNameOverride || null,+ bioOverride: input.bioOverride || null,+ createdAt: now,+ updatedAt: now,+ });+ state.buckets.push(bucket);+ // Validate/read the shared identity before publishing the local registration.+ await ensureBucketLayout(bucket);+ await writeRegistry(state);+ return bucket;});- state.buckets.push(bucket);- // Validate/read the shared identity before publishing the local registration.- await ensureBucketLayout(bucket);- await writeRegistry(state);- return bucket;}-export async function updateBucket(id, patch = {}) {- const state = await readRegistry();- const idx = state.buckets.findIndex((b) => b.id === id);- if (idx < 0) throw makeErr(`Bucket not found: ${id}`, ERR_NOT_FOUND);- const cur = state.buckets[idx];- const merged = sanitizeBucket({- ...cur,- ...('name' in patch ? { name: patch.name } : {}),- ...('mode' in patch ? { mode: patch.mode } : {}),- ...('displayNameOverride' in patch ? { displayNameOverride: patch.displayNameOverride } : {}),- ...('bioOverride' in patch ? { bioOverride: patch.bioOverride } : {}),- updatedAt: new Date().toISOString(),+export function updateBucket(id, patch = {}) {+ return queueRegistryWrite(async () => {+ const state = await readRegistry();+ const idx = state.buckets.findIndex((b) => b.id === id);+ if (idx < 0) throw makeErr(`Bucket not found: ${id}`, ERR_NOT_FOUND);+ const cur = state.buckets[idx];+ const merged = sanitizeBucket({+ ...cur,+ ...('name' in patch ? { name: patch.name } : {}),+ ...('mode' in patch ? { mode: patch.mode } : {}),+ ...('displayNameOverride' in patch ? { displayNameOverride: patch.displayNameOverride } : {}),+ ...('bioOverride' in patch ? { bioOverride: patch.bioOverride } : {}),+ updatedAt: new Date().toISOString(),+ });+ if (!merged) throw makeErr('Invalid bucket payload', ERR_VALIDATION);+ // `path` is intentionally NOT patchable — if the user wants to move a+ // bucket, they delete and re-register so the registry can re-validate and+ // re-layout the new path.+ state.buckets[idx] = merged;+ await writeRegistry(state);+ return merged;});- if (!merged) throw makeErr('Invalid bucket payload', ERR_VALIDATION);- // `path` is intentionally NOT patchable — if the user wants to move a- // bucket, they delete and re-register so the registry can re-validate and- // re-layout the new path.- state.buckets[idx] = merged;- await writeRegistry(state);- return merged;}-export async function deleteBucket(id) {- const state = await readRegistry();- const before = state.buckets.length;- state.buckets = state.buckets.filter((b) => b.id !== id);- if (state.buckets.length === before) throw makeErr(`Bucket not found: ${id}`, ERR_NOT_FOUND);- await writeRegistry(state);- return { id };+export function deleteBucket(id) {+ return queueRegistryWrite(async () => {+ const state = await readRegistry();+ const before = state.buckets.length;+ state.buckets = state.buckets.filter((b) => b.id !== id);+ if (state.buckets.length === before) throw makeErr(`Bucket not found: ${id}`, ERR_NOT_FOUND);+ await writeRegistry(state);+ return { id };+ });}diff --git a/server/services/sharing/buckets.test.js b/server/services/sharing/buckets.test.jsindex 21a0634ffe..0d9d7f8661 100644--- a/server/services/sharing/buckets.test.js+++ b/server/services/sharing/buckets.test.js@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach } from 'vitest';-import { mkdtempSync, rmSync } from 'fs';+import { mkdtempSync, rmSync, readFileSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { vi } from 'vitest';@@ -99,6 +99,68 @@ describe('sharing/buckets', () => {}});+ describe('concurrent registry mutations', () => {+ const extraDirs = [];+ const mkDir = () => { const d = mkdtempSync(join(tmpdir(), 'portos-sharing-extra-')); extraDirs.push(d); return d; };+ afterEach(() => { while (extraDirs.length) rmSync(extraDirs.pop(), { recursive: true, force: true }); });++ it('keeps both registrations when two creates at different paths overlap', async () => {+ const [a, b] = await Promise.all([+ buckets.createBucket({ name: 'A', path: mkDir() }),+ buckets.createBucket({ name: 'B', path: mkDir() }),+ ]);+ const ids = (await buckets.listBuckets()).map((x) => x.id).sort();+ expect(ids).toEqual([a.id, b.id].sort());+ });++ it('admits only one bucket when the same path is registered concurrently', async () => {+ const results = await Promise.allSettled([+ buckets.createBucket({ name: 'A', path: bucketTargetDir }),+ buckets.createBucket({ name: 'B', path: bucketTargetDir }),+ ]);+ expect(results.map((r) => r.status).sort()).toEqual(['fulfilled', 'rejected']);+ expect(results.find((r) => r.status === 'rejected').reason.code).toBe(buckets.ERR_VALIDATION);+ expect(await buckets.listBuckets()).toHaveLength(1);+ });++ it('preserves updates to different buckets', async () => {+ const a = await buckets.createBucket({ name: 'A', path: mkDir() });+ const b = await buckets.createBucket({ name: 'B', path: mkDir() });+ await Promise.all([+ buckets.updateBucket(a.id, { name: 'A2' }),+ buckets.updateBucket(b.id, { mode: 'auto-merge' }),+ ]);+ const list = await buckets.listBuckets();+ expect(list.find((x) => x.id === a.id).name).toBe('A2');+ expect(list.find((x) => x.id === b.id).mode).toBe('auto-merge');+ });++ it('does not resurrect a bucket when a rename is queued ahead of its delete, and later renames report not-found', async () => {+ const created = await buckets.createBucket({ name: 'A', path: bucketTargetDir });+ const rename = buckets.updateBucket(created.id, { name: 'Renamed' });+ const remove = buckets.deleteBucket(created.id);+ const lateRename = buckets.updateBucket(created.id, { name: 'Late' });+ await expect(rename).resolves.toMatchObject({ name: 'Renamed' });+ await expect(remove).resolves.toEqual({ id: created.id });+ await expect(lateRename).rejects.toMatchObject({ code: buckets.ERR_NOT_FOUND });+ expect(await buckets.listBuckets()).toEqual([]);+ });++ it('a rejected mutation does not poison later queued work, and an unreadable registry is never overwritten', async () => {+ const failing = buckets.updateBucket('missing', { name: 'X' });+ const ok = buckets.createBucket({ name: 'A', path: bucketTargetDir });+ await expect(failing).rejects.toMatchObject({ code: buckets.ERR_NOT_FOUND });+ await expect(ok).resolves.toMatchObject({ name: 'A' });++ const registry = join(tempRoot, 'sharing', 'buckets.json');+ writeFileSync(registry, '{ not json');+ await expect(buckets.createBucket({ name: 'B', path: mkDir() })).rejects.toBeTruthy();+ expect(readFileSync(registry, 'utf8')).toBe('{ not json');+ writeFileSync(registry, JSON.stringify({ buckets: [] }));+ await expect(buckets.createBucket({ name: 'C', path: mkDir() })).resolves.toMatchObject({ name: 'C' });+ });+ });+describe('bucketRecordsDir / bucketRecordPath', () => {it('joins the per-type records directory under the bucket path', () => {expect(buckets.bucketRecordsDir('/b', 'series')).toBe(join('/b', 'records', 'series'));