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([brain-bucket-chip-reorder]): persist a reorder atomically, not via N racing PUTs
[._.]/ Adam Eivya4adab713bb6
diff --git a/client/src/components/brain/tabs/LinksTab.jsx b/client/src/components/brain/tabs/LinksTab.jsxindex 4c70476ce0..ed83453ebb 100644--- a/client/src/components/brain/tabs/LinksTab.jsx+++ b/client/src/components/brain/tabs/LinksTab.jsx@@ -187,8 +187,9 @@ export default function LinksTab({ onRefresh }) {// Reposition a chip within (or into) a bucket at a specific index — the// intra-bucket reorder the bucket board's "append on assign" path can't do.- // Renumbers the destination bucket densely and PATCHes only the chips that- // actually moved.+ // Renumbers the destination bucket densely and persists the whole batch in+ // one atomic call: N concurrent single-link PUTs would race the shared links+ // store and silently lose-update some chips' bucketOrder.const handleMoveLinkToIndex = async (link, bucketId, targetIndex) => {const { renumbered, changed } = reorderLinksInBucket(links, link, bucketId, targetIndex);if (changed.length === 0) return;@@ -198,11 +199,8 @@ export default function LinksTab({ onRefresh }) {const r = byId.get(l.id);return r ? { ...l, bucketId: r.bucketId, bucketOrder: r.bucketOrder } : l;}));- const results = await Promise.all(changed.map(r =>- api.updateBrainLink(r.id, { bucketId: r.bucketId, bucketOrder: r.bucketOrder }, { silent: true })- .catch(() => null)- ));- if (results.some(r => r === null)) {+ const ok = await api.reorderBrainLinks(changed, { silent: true }).catch(() => null);+ if (!ok) {toast.error('Failed to reorder links');fetchLinks(); // revert optimistic change on failure}diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.jsindex 861d2c3f65..2ba0b5bf4b 100644--- a/client/src/services/apiBrain.js+++ b/client/src/services/apiBrain.js@@ -161,6 +161,14 @@ export const updateBrainLink = (id, data, options = {}) => request(`/brain/linksbody: JSON.stringify(data),...options});+// Batch reorder: apply a whole drag gesture's { id, bucketId, bucketOrder }+// changes in one atomic server write (avoids N concurrent PUTs racing the+// shared links store).+export const reorderBrainLinks = (updates, options = {}) => request('/brain/links/reorder', {+ method: 'POST',+ body: JSON.stringify({ updates }),+ ...options+});export const deleteBrainLink = (id) => request(`/brain/links/${id}`, { method: 'DELETE' });export const cloneBrainLink = (id) => request(`/brain/links/${id}/clone`, { method: 'POST' });export const pullBrainLink = (id) => request(`/brain/links/${id}/pull`, { method: 'POST' });diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex 818ffc2405..dd1fd6f4d0 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -431,6 +431,18 @@ export const bucketReorderSchema = z.object({ids: z.array(z.string().uuid()).min(1)});+// Batch link reorder (POST /api/brain/links/reorder) — applies a dense+// bucketOrder renumbering for one drag gesture in a single atomic write, so a+// multi-chip reorder can't lose-update the shared links store the way N+// concurrent single-record PUTs can.+export const linkReorderSchema = z.object({+ updates: z.array(z.object({+ id: z.string().min(1),+ bucketId: z.string().min(1).nullable(),+ bucketOrder: z.number().int()+ })).min(1)+});+// =============================================================================// SYNC SCHEMAS// =============================================================================diff --git a/server/lib/brainValidation.test.js b/server/lib/brainValidation.test.jsindex 4251e07067..7b4123e8cd 100644--- a/server/lib/brainValidation.test.js+++ b/server/lib/brainValidation.test.js@@ -27,6 +27,7 @@ import {linkRecordSchema,linkInputSchema,linkUpdateInputSchema,+ linkReorderSchema,linksQuerySchema,bucketInputSchema,bucketUpdateInputSchema,@@ -614,6 +615,34 @@ describe('brainValidation.js', () => {});});+ describe('linkReorderSchema', () => {+ it('should accept a batch of { id, bucketId, bucketOrder }', () => {+ const result = linkReorderSchema.safeParse({+ updates: [+ { id: 'l1', bucketId: 'b1', bucketOrder: 0 },+ { id: 'l2', bucketId: 'b1', bucketOrder: 1 }+ ]+ });+ expect(result.success).toBe(true);+ });++ it('should accept a null bucketId (ungrouped landing)', () => {+ expect(linkReorderSchema.safeParse({ updates: [{ id: 'l1', bucketId: null, bucketOrder: 0 }] }).success).toBe(true);+ });++ it('should reject an empty batch', () => {+ expect(linkReorderSchema.safeParse({ updates: [] }).success).toBe(false);+ });++ it('should reject a non-integer bucketOrder', () => {+ expect(linkReorderSchema.safeParse({ updates: [{ id: 'l1', bucketId: 'b1', bucketOrder: 1.5 }] }).success).toBe(false);+ });++ it('should reject an entry missing its id', () => {+ expect(linkReorderSchema.safeParse({ updates: [{ bucketId: 'b1', bucketOrder: 0 }] }).success).toBe(false);+ });+ });+describe('brainSyncQuerySchema', () => {it('should accept valid query with defaults', () => {const result = brainSyncQuerySchema.safeParse({});diff --git a/server/routes/brain.js b/server/routes/brain.jsindex 54a8896052..1699cdb3ac 100644--- a/server/routes/brain.js+++ b/server/routes/brain.js@@ -29,6 +29,7 @@ import {settingsUpdateInputSchema,linkInputSchema,linkUpdateInputSchema,+ linkReorderSchema,linksQuerySchema,bucketInputSchema,bucketUpdateInputSchema,@@ -530,6 +531,19 @@ router.get('/links', asyncHandler(async (req, res) => {res.json({ links, total, limit, offset });}));+/**+ * POST /api/brain/links/reorder+ * Apply a batch of { id, bucketId, bucketOrder } updates for one drag gesture+ * in a single atomic write — N concurrent single-link PUTs against the shared+ * links store can lose-update each other. Mirrors POST /buckets/reorder.+ * (Registered before /links/:id so "reorder" isn't captured as an :id.)+ */+router.post('/links/reorder', asyncHandler(async (req, res) => {+ const { updates } = validateRequest(linkReorderSchema, req.body);+ const links = await brainService.reorderLinks(updates);+ res.json({ links });+}));+/*** GET /api/brain/links/:id* Get a single link by IDdiff --git a/server/routes/brain.test.js b/server/routes/brain.test.jsindex 74283735f3..9d48646cd3 100644--- a/server/routes/brain.test.js+++ b/server/routes/brain.test.js@@ -60,6 +60,7 @@ vi.mock('../services/brain.js', () => ({getLinkByUrl: vi.fn(),createLink: vi.fn(),updateLink: vi.fn(),+ reorderLinks: vi.fn(),deleteLink: vi.fn(),// BucketsgetBuckets: vi.fn(),@@ -1245,6 +1246,38 @@ describe('Brain Routes', () => {});});+ describe('POST /api/brain/links/reorder', () => {+ it('applies the whole batch in one atomic reorderLinks call', async () => {+ const updates = [+ { id: 'l2', bucketId: 'b1', bucketOrder: 0 },+ { id: 'l1', bucketId: 'b1', bucketOrder: 1 }+ ];+ brainService.reorderLinks.mockResolvedValue(updates.map(u => ({ ...u, url: 'x' })));+ const res = await request(app).post('/api/brain/links/reorder').send({ updates });+ expect(res.status).toBe(200);+ // One atomic call (not N concurrent updateLink PUTs).+ expect(brainService.reorderLinks).toHaveBeenCalledTimes(1);+ expect(brainService.reorderLinks).toHaveBeenCalledWith(updates);+ expect(brainService.updateLink).not.toHaveBeenCalled();+ expect(res.body.links).toHaveLength(2);+ });++ it('rejects an empty or malformed batch', async () => {+ const res = await request(app).post('/api/brain/links/reorder').send({ updates: [] });+ expect(res.status).toBe(400);+ expect(brainService.reorderLinks).not.toHaveBeenCalled();+ });++ it('is matched before /links/:id so "reorder" is not treated as an id', async () => {+ brainService.reorderLinks.mockResolvedValue([]);+ const res = await request(app)+ .post('/api/brain/links/reorder')+ .send({ updates: [{ id: 'l1', bucketId: 'b1', bucketOrder: 0 }] });+ expect(res.status).toBe(200);+ expect(brainService.reorderLinks).toHaveBeenCalledTimes(1);+ });+ });+describe('PUT /api/brain/buckets/:id', () => {it('updates an existing bucket', async () => {brainService.getBucketById.mockResolvedValue({ id: 'b1', name: 'Old' });diff --git a/server/services/brain.js b/server/services/brain.jsindex 16959559aa..36ee6f73be 100644--- a/server/services/brain.js+++ b/server/services/brain.js@@ -698,6 +698,7 @@ export const getLinkById = storage.getLinkById;export const getLinkByUrl = storage.getLinkByUrl;export const createLink = storage.createLink;export const updateLink = storage.updateLink;+export const reorderLinks = storage.reorderLinks;export const deleteLink = storage.deleteLink;export const getBuckets = storage.getBuckets;export const getBucketById = storage.getBucketById;diff --git a/server/services/brain.test.js b/server/services/brain.test.jsindex 8b999f9c79..1cbe15bd7a 100644--- a/server/services/brain.test.js+++ b/server/services/brain.test.js@@ -50,6 +50,7 @@ vi.mock('./brainStorage.js', () => {getLinkByUrl: vi.fn(),createLink: vi.fn(),updateLink: vi.fn(),+ reorderLinks: vi.fn(),deleteLink: vi.fn(),getBuckets: vi.fn(),getBucketById: vi.fn(),diff --git a/server/services/brainStorage.js b/server/services/brainStorage.jsindex 723da50b18..daff93a4e1 100644--- a/server/services/brainStorage.js+++ b/server/services/brainStorage.js@@ -236,6 +236,46 @@ export async function update(type, id, updates) {return { id, ...record };}+/**+ * Apply many record updates to one store in a single load-modify-save.+ *+ * A batch like a chip reorder must NOT fan out into N concurrent single-record+ * `update()` calls: `update()` is a read-modify-save over the whole shared JSON+ * file, so concurrent calls on a cold cache read overlapping baselines and the+ * last save wins — silently dropping the other records' changes. Collapsing the+ * batch into one load-modify-save (one file write) makes the whole reorder+ * atomic. `updates` is an array of { id, ...fields }; unknown ids are skipped.+ * Returns the updated records.+ */+export async function updateMany(type, updates) {+ const data = await loadJsonStore(type);+ const applied = [];+ for (const { id, ...fields } of updates) {+ const existing = data.records[id];+ if (!existing) continue;+ const record = {+ ...existing,+ ...fields,+ // Preserve immutable fields, exactly as update() does.+ originInstanceId: existing.originInstanceId,+ createdAt: existing.createdAt,+ updatedAt: now()+ };+ data.records[id] = record;+ applied.push({ id, record });+ }+ if (applied.length === 0) return [];++ await saveJsonStore(type, data);+ for (const { id, record } of applied) {+ brainEvents.emit(`${type}:upserted`, { id, record: { id, ...record } });+ await brainSyncLog.appendChange('update', type, id, record, record.originInstanceId)+ .catch(err => console.error(`⚠️ Sync log append failed for update ${type}/${id}: ${err.message}`));+ }+ console.log(`🧠 Updated ${applied.length} ${type} records in one batch`);+ return applied.map(({ id, record }) => ({ id, ...record }));+}+/*** Delete a record*/@@ -562,6 +602,9 @@ export const getLinks = (filters) => filters ? query('links', filters) : getAll(export const getLinkById = (id) => getById('links', id);export const createLink = (data) => create('links', data);export const updateLink = (id, data) => update('links', id, data);+// Batch reorder: one atomic load-modify-save so a multi-chip drag can't+// lose-update the shared links store the way N concurrent updateLink calls can.+export const reorderLinks = (updates) => updateMany('links', updates);export const deleteLink = (id) => remove('links', id);/**