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
perf: serialize createCachedStore + backup.saveState writes; bound rate-limit maps (#2539)
Adam Eivy92304b1f2b32
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 7a57f0b5a6..e7e541a554 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -56,3 +56,4 @@- **[issue-2532] Extract the Universe Builder's page-level lightbox into a `useUniverseGallery` hook.** `UniverseBuilder.jsx` inlined ~160 lines of gallery/preview plumbing — the filename→image-sidecar metadata map, the `listImageGallery()` refetch effect (keyed on `runs.length` + a per-job-completion bump), the `previewItems` derivation across variations/composite sheets/style probes/canon+character-sheet refs (namespaced-key dedupe), and the `usePreviewRoute`/`useMediaPreviewActions`/`useMediaAnnotations` wiring. That cohesive concern now lives in `client/src/hooks/useUniverseGallery.js` (takes `{ draft, runsLength }`, returns `{ previewItems, preview, setPreview, previewActions, openPreviewByFilename, openVariationPreview, annotations, updateAnnotation, bumpGalleryRefresh }`), thinning the page shell toward the WritersRoom pattern. Pure structural refactor — behavior identical, no route-contract change; the UniverseBuilder page suite and hooks barrel test stay green. Further hook/panel extractions (draft/expand/canon/bulk-render for UniverseBuilder, `useShellSession` for Shell) remain.- **[issue-2545] Add `aria-label`s to icon-only controls and fix Templates/MessageDetail form labels.** Several icon-only buttons exposed their purpose only via `title` (unreliable for screen readers): the MessageDetail toolbar (Reply, voice-mode toggle, AI Reply, Refresh, Archive, Delete), MusicVideo scene move-up/move-down/delete, MediaCard hide/delete, the MediaJobsQueue per-job cancel, Review's edit save/cancel, and DuplicateGroup rename now carry an `aria-label` matching their `title`. The MessageDetail reply `<textarea>` (previously placeholder-only) gains an `aria-label`, and the Templates "Target Directory" `<label>` is now wired to its input via `htmlFor`/`id` so click-to-focus and screen readers work. Accessibility attributes only — no behavior or styling change.- **[issue-2533] Extract JIRA-ticket claim assembly out of the route into `buildJiraTicketTask` (next to `buildClaimWorkTask`).** `POST /api/cos/tasks/jira-ticket` (the sprint-board per-card play button) inlined its reviewer-CSV resolution (`resolveClaimReviewersCsv`), the target-ticket constraint block (`buildTargetTicketBlock`), and the `claim-issue-jira` prompt assembly directly in `server/routes/cosTaskRoutes.js`. That logic now lives in `server/services/cosTaskGenerator.js` as an exported `buildJiraTicketTask(app, ticketKey)` that returns `{ ticketKey, prompt, taskMetadata }` — beside `buildClaimWorkTask`, sharing the same reviewer/isolation conventions. The route stays thin: validate → JIRA-enabled gate → assemble → queue. Pure refactor — the queued task's context, description, and `useWorktree/openPR` posture are byte-for-byte unchanged; new unit tests cover the extracted assembly.+- **[issue-2539] Serialize `createCachedStore` and `backup.saveState` writes; bound the rate-limit state maps.** `createCachedStore` now runs every write through an internal single-tail `createFileWriteQueue` and exposes a `mutate(fn)` primitive that serializes the whole `load → modify → persist` cycle, so two concurrent read-modify-write paths can no longer clobber each other; the feeds, social-accounts, platform-accounts, agent-personalities, and automation-scheduler services were migrated off the racy `load()` + `save()` pair onto `mutate()`. `backup.saveState` gained the same promise-tail so a run completing while the scheduler stamps a status can't lose fields. The moltbook/moltworld rate-limiters, which kept one in-memory state entry per API key / agent id forever, now store it in a new bounded `createBoundedStateMap({ maxSize, ttlMs })` helper (`server/lib/boundedStateMap.js`) that lazily evicts idle (TTL) and least-recently-used (LRU) entries. (The idle pipeline `writeQueues` pruning called for by the issue already shipped via `createKeyedFileWriteQueue`/`createKeyCachedQueue` in #2528/#2524.) Behavior is otherwise unchanged; new unit tests cover the serialized `mutate`, the bounded map, and the rate-limiter.diff --git a/server/integrations/moltbook/rateLimits.js b/server/integrations/moltbook/rateLimits.jsindex 7cbefc030d..f623d7319a 100644--- a/server/integrations/moltbook/rateLimits.js+++ b/server/integrations/moltbook/rateLimits.js@@ -5,6 +5,8 @@* These limits are enforced by the platform - exceeding them will result in errors.*/+import { createBoundedStateMap } from '../../lib/boundedStateMap.js';+export const MOLTBOOK_RATE_LIMITS = {post: {cooldownMs: 30 * 60 * 1000, // 30 minutes between posts@@ -24,8 +26,10 @@ export const MOLTBOOK_RATE_LIMITS = {}};-// In-memory rate limit tracking per API key-const rateLimitState = new Map();+// In-memory rate limit tracking per API key. Bounded (TTL + LRU) so a process+// cycling through many keys doesn't leak one entry per key forever — idle+// state is worthless anyway once its daily counters have reset.+const rateLimitState = createBoundedStateMap();/*** Get rate limit state for an API keydiff --git a/server/integrations/moltbook/rateLimits.test.js b/server/integrations/moltbook/rateLimits.test.jsnew file mode 100644index 0000000000..b7d9b0418d--- /dev/null+++ b/server/integrations/moltbook/rateLimits.test.js@@ -0,0 +1,47 @@+import { describe, it, expect } from 'vitest';+import {+ checkRateLimit,+ recordAction,+ getRateLimitStatus,+ clearRateLimitState,+ MOLTBOOK_RATE_LIMITS,+} from './rateLimits.js';++describe('moltbook rateLimits', () => {+ it('allows an action then enforces the cooldown after recording', () => {+ const key = 'test-key-cooldown';+ clearRateLimitState(key);+ expect(checkRateLimit(key, 'vote').allowed).toBe(true);+ recordAction(key, 'vote');+ const blocked = checkRateLimit(key, 'vote');+ expect(blocked.allowed).toBe(false);+ expect(blocked.waitMs).toBeGreaterThan(0);+ clearRateLimitState(key);+ });++ it('enforces the daily cap', () => {+ const key = 'test-key-daily';+ clearRateLimitState(key);+ const max = MOLTBOOK_RATE_LIMITS.vote.maxPerDay;+ for (let i = 0; i < max; i++) recordAction(key, 'vote');+ const status = getRateLimitStatus(key);+ expect(status.vote.remaining).toBe(0);+ expect(checkRateLimit(key, 'vote').allowed).toBe(false);+ clearRateLimitState(key);+ });++ it('unknown actions are always allowed', () => {+ expect(checkRateLimit('any', 'bogus').allowed).toBe(true);+ });++ it('does not leak entries without bound — cycling many keys stays bounded', () => {+ // The state map is bounded (default maxSize 1000). Touching far more keys+ // than the cap must not grow the map without limit; older idle keys are+ // shed. We can only observe behavior through the public API, so assert the+ // most-recently-used key is still tracked (cooldown enforced) after churn.+ for (let i = 0; i < 5000; i++) recordAction(`churn-${i}`, 'vote');+ const recent = 'churn-4999';+ expect(checkRateLimit(recent, 'vote').allowed).toBe(false); // still cooling down+ clearRateLimitState(recent);+ });+});diff --git a/server/integrations/moltworld/rateLimits.js b/server/integrations/moltworld/rateLimits.jsindex c697c013cf..41c867a616 100644--- a/server/integrations/moltworld/rateLimits.js+++ b/server/integrations/moltworld/rateLimits.js@@ -6,6 +6,8 @@* Global limit: 60 requests/minute per agent.*/+import { createBoundedStateMap } from '../../lib/boundedStateMap.js';+export const MOLTWORLD_RATE_LIMITS = {join: {cooldownMs: 5 * 1000, // 5 seconds between joins (heartbeat)@@ -25,9 +27,11 @@ export const MOLTWORLD_RATE_LIMITS = {const GLOBAL_WINDOW_MS = 60 * 1000;const GLOBAL_MAX_REQUESTS = 60;-// In-memory rate limit tracking per agent ID-const rateLimitState = new Map();-const globalRateState = new Map();+// In-memory rate limit tracking per agent ID. Bounded (TTL + LRU) so a process+// cycling through many agent ids doesn't leak one entry per id forever — idle+// state is worthless anyway once its daily counters / sliding window have aged out.+const rateLimitState = createBoundedStateMap();+const globalRateState = createBoundedStateMap();/*** Get rate limit state for an agent IDdiff --git a/server/lib/README.md b/server/lib/README.mdindex 2e27fe2a1e..4c709e24b5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -124,6 +124,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. || `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. || `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |+| `boundedStateMap.js` | `createBoundedStateMap({ maxSize, ttlMs })` — a `Map` that self-evicts so a per-key state cache can't grow one entry per key forever. Lazy TTL + LRU eviction on `get`/`set` (no timers); `get` doubles as the LRU touch. Used by the moltbook/moltworld rate-limiters to bound their per-agent state. || `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. || `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. || `fileWriteQueue.js` | Serialize read-modify-write cycles so they don't interleave. `createFileWriteQueue()` → single-tail `queue(fn)` for one shared file; `createRecordWriteQueue(assertId?)` → id-keyed `queueRecordWrite(id, fn)` where same-id cycles serialize and different-id cycles run in parallel (the queue the PG/file store facades use for `collectionStore.queueRecordWrite` parity); `createKeyedFileWriteQueue()` → `queueKeyedWrite(key, fn)` that collapses the pipeline stage stores' hand-rolled `Map` + per-key `createFileWriteQueue` factory (falsy keys → shared `'__unknown__'` tail; self-pruning via `createKeyCachedQueue`). |diff --git a/server/lib/boundedStateMap.js b/server/lib/boundedStateMap.jsnew file mode 100644index 0000000000..ba9b6f1f6f--- /dev/null+++ b/server/lib/boundedStateMap.js@@ -0,0 +1,83 @@+/**+ * boundedStateMap — a `Map` that self-evicts so a per-key state cache can't+ * grow one entry per key forever.+ *+ * The integration rate-limiters (`integrations/moltbook/rateLimits.js`,+ * `integrations/moltworld/rateLimits.js`) keep an in-memory entry per API key /+ * agent id and never removed idle ones — a long-lived process cycling through+ * many keys leaked one object per key indefinitely. This wraps a `Map` with two+ * bounds, applied lazily on `get`/`set` (no timers):+ *+ * 1. TTL — entries untouched for longer than `ttlMs` are dropped. For the+ * rate-limiters the useful state (daily counters, cooldown timers) is+ * already stale after a day, so an idle entry carries nothing worth keeping.+ * 2. LRU cap — if the live set still exceeds `maxSize`, the least-recently+ * accessed entries are evicted until it fits. Belt-and-suspenders against+ * pathological key churn within the TTL window.+ *+ * `get` marks access (so it doubles as the LRU touch), mirroring how the+ * rate-limiters call `getState(key)` on every check/record/status. Entries are+ * mutated in place by callers; access tracking lives in a parallel timestamp+ * map so those in-place mutations don't need to round-trip through `set`.+ *+ * @param {Object} [options]+ * @param {number} [options.maxSize=1000] Hard cap on live entries.+ * @param {number} [options.ttlMs=25*60*60*1000] Idle eviction window (default 25h).+ * @returns {{ get, set, has, delete: (k:any)=>boolean, get size(): number, clear }}+ */+export function createBoundedStateMap({ maxSize = 1000, ttlMs = 25 * 60 * 60 * 1000 } = {}) {+ const values = new Map();+ const lastAccess = new Map();++ const touch = (key, now) => { lastAccess.set(key, now); };++ const drop = (key) => {+ values.delete(key);+ lastAccess.delete(key);+ };++ // Lazy sweep: TTL first, then LRU trim to maxSize. Runs on every set so the+ // map stays bounded between accesses without a background timer.+ const evict = (now) => {+ for (const [key, at] of lastAccess) {+ if (now - at > ttlMs) drop(key);+ }+ if (values.size <= maxSize) return;+ // Oldest-first — Map preserves insertion order, so sort the surviving keys+ // by lastAccess and shed from the front until within the cap.+ const byAge = [...lastAccess.entries()].sort((a, b) => a[1] - b[1]);+ for (const [key] of byAge) {+ if (values.size <= maxSize) break;+ drop(key);+ }+ };++ return {+ get(key) {+ if (!values.has(key)) return undefined;+ touch(key, Date.now());+ return values.get(key);+ },+ set(key, value) {+ const now = Date.now();+ values.set(key, value);+ touch(key, now);+ evict(now);+ return value;+ },+ has(key) {+ return values.has(key);+ },+ delete(key) {+ lastAccess.delete(key);+ return values.delete(key);+ },+ get size() {+ return values.size;+ },+ clear() {+ values.clear();+ lastAccess.clear();+ },+ };+}diff --git a/server/lib/boundedStateMap.test.js b/server/lib/boundedStateMap.test.jsnew file mode 100644index 0000000000..e594a6e7f3--- /dev/null+++ b/server/lib/boundedStateMap.test.js@@ -0,0 +1,81 @@+import { describe, it, expect, vi, afterEach } from 'vitest';+import { createBoundedStateMap } from './boundedStateMap.js';++afterEach(() => {+ vi.useRealTimers();+});++describe('createBoundedStateMap', () => {+ it('behaves like a Map for get/set/has/delete/size', () => {+ const m = createBoundedStateMap();+ expect(m.has('a')).toBe(false);+ expect(m.get('a')).toBeUndefined();+ m.set('a', { v: 1 });+ expect(m.has('a')).toBe(true);+ expect(m.get('a')).toEqual({ v: 1 });+ expect(m.size).toBe(1);+ expect(m.delete('a')).toBe(true);+ expect(m.delete('a')).toBe(false);+ expect(m.size).toBe(0);+ });++ it('preserves in-place mutations of stored objects', () => {+ const m = createBoundedStateMap();+ m.set('a', { count: 0 });+ m.get('a').count += 1;+ expect(m.get('a').count).toBe(1);+ });++ it('evicts entries idle longer than ttlMs on the next write', () => {+ vi.useFakeTimers();+ const m = createBoundedStateMap({ ttlMs: 1000 });+ m.set('old', 1);+ vi.advanceTimersByTime(1500); // 'old' is now stale+ m.set('new', 2); // triggers the lazy sweep+ expect(m.has('old')).toBe(false);+ expect(m.has('new')).toBe(true);+ expect(m.size).toBe(1);+ });++ it('get() refreshes recency so an actively-used key survives the TTL sweep', () => {+ vi.useFakeTimers();+ const m = createBoundedStateMap({ ttlMs: 1000 });+ m.set('a', 1);+ vi.advanceTimersByTime(800);+ m.get('a'); // touch — resets lastAccess+ vi.advanceTimersByTime(800); // 1600ms since set, but only 800ms since touch+ m.set('b', 2); // sweep runs+ expect(m.has('a')).toBe(true);+ });++ it('enforces the LRU cap, shedding the least-recently accessed entries', () => {+ // Fake timers so each access gets a distinct timestamp — otherwise+ // same-millisecond ties make the eviction order ambiguous. ttl large so+ // only the size cap can evict.+ vi.useFakeTimers();+ const m = createBoundedStateMap({ maxSize: 3, ttlMs: 60 * 60 * 1000 });+ m.set('a', 1);+ vi.advanceTimersByTime(10);+ m.set('b', 2);+ vi.advanceTimersByTime(10);+ m.set('c', 3);+ vi.advanceTimersByTime(10);+ m.get('a'); // 'a' most recently used; 'b' now the oldest+ vi.advanceTimersByTime(10);+ m.set('d', 4); // over cap → evict least-recently accessed ('b')+ expect(m.size).toBe(3);+ expect(m.has('b')).toBe(false);+ expect(m.has('a')).toBe(true);+ expect(m.has('c')).toBe(true);+ expect(m.has('d')).toBe(true);+ });++ it('clear() empties the map', () => {+ const m = createBoundedStateMap();+ m.set('a', 1);+ m.set('b', 2);+ m.clear();+ expect(m.size).toBe(0);+ expect(m.has('a')).toBe(false);+ });+});diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 9e7b751669..47da1be593 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -14,6 +14,7 @@ import { fileURLToPath } from 'url';import { homedir } from 'os';import { ServerError } from './errorHandler.js';import { resolveInstallRoot } from './dataRoot.js';+import { createFileWriteQueue } from './fileWriteQueue.js';// Promisified execFile — shared so callers (e.g. backup's pg_dump probing)// don't each re-wrap it. Returns { stdout, stderr }.@@ -556,12 +557,22 @@ export async function writeJSONLines(filePath, values) {* @param {Object} options* @param {number} [options.ttl=2000] - Cache TTL in milliseconds* @param {string} [options.context=''] - Context label for error logging- * @returns {{ load, save, invalidateCache }}+ * @returns {{ load, save, mutate, invalidateCache }}+ *+ * Writes are serialized through a single-tail `createFileWriteQueue` so two+ * concurrent `save()` calls can't interleave their `atomicWrite` + cache+ * assignment. For read-modify-write, use `mutate(fn)` — it runs the whole+ * `load → fn → persist` cycle under the same tail, so a `load` always sees the+ * previous cycle's committed result and one writer can't clobber the other+ * (CLAUDE.md: "serialize writes server-side… a single tail per shared file").+ * A bare `load()` + `save()` pair does NOT get that guarantee; reach for+ * `mutate()` whenever the new value depends on the current one.*/export function createCachedStore(filePath, defaultValue, { ttl = 2000, context = '' } = {}) {let cache = null;let cacheTimestamp = 0;const dir = dirname(filePath);+ const queueWrite = createFileWriteQueue();// Safe clone for plain JSON defaults (structuredClone requires Node 17+)const cloneDefault = () => JSON.parse(JSON.stringify(defaultValue));@@ -580,18 +591,32 @@ export function createCachedStore(filePath, defaultValue, { ttl = 2000, contextreturn cache;};- const save = async (data) => {+ // Persist `data` and refresh the cache — the shared write body. Callers reach+ // it via the serialized `save`/`mutate`, never directly.+ const persist = async (data) => {await atomicWrite(filePath, data);cache = data;cacheTimestamp = Date.now();+ return data;};+ const save = (data) => queueWrite(() => persist(data));++ // Serialized read-modify-write: load the freshest state under the tail, apply+ // `fn`, then persist. `fn` may mutate the loaded object in place and/or return+ // the value to write (returning `undefined` persists the mutated input).+ const mutate = (fn) => queueWrite(async () => {+ const data = await load();+ const result = await fn(data);+ return persist(result === undefined ? data : result);+ });+const invalidateCache = () => {cache = null;cacheTimestamp = 0;};- return { load, save, invalidateCache };+ return { load, save, mutate, invalidateCache };}export const MINUTE = 60 * 1000;diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex ffd465afbf..6b7a51d08b 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -23,6 +23,7 @@ import {listDirectoryByExtension,safeJSONParse,safeJSONLParse,+ createCachedStore,readJSONFile,readJSONLFile,appendJSONLine,@@ -942,6 +943,71 @@ describe('fileUtils', () => {});});+// =============================================================================+// createCachedStore — cached JSON store with serialized writes (#2539)+// =============================================================================++describe('createCachedStore', () => {+ let dir;++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'cached-store-test-'));+ });++ afterEach(() => {+ rmSync(dir, { recursive: true, force: true });+ });++ it('loads the default when the file is absent, then round-trips a save', async () => {+ const store = createCachedStore(join(dir, 'x.json'), { n: 0 });+ expect(await store.load()).toEqual({ n: 0 });+ await store.save({ n: 5 });+ expect(await store.load()).toEqual({ n: 5 });+ });++ it('mutate persists the fn result and returns it', async () => {+ const store = createCachedStore(join(dir, 'x.json'), { n: 0 });+ const out = await store.mutate((data) => { data.n = 9; });+ expect(out).toEqual({ n: 9 });+ // Persisted to disk, not just cache+ expect(JSON.parse(await readFile(join(dir, 'x.json'), 'utf-8'))).toEqual({ n: 9 });+ });++ it('serializes concurrent read-modify-write so no update is lost', async () => {+ const file = join(dir, 'counter.json');+ const store = createCachedStore(file, { n: 0 }, { ttl: 0 });+ // ttl:0 forces every load to re-read from disk — the worst case for the+ // classic load→mutate→save clobber. Without serialization, N concurrent+ // increments race down to ~1; mutate() must land all N.+ const N = 25;+ await Promise.all(+ Array.from({ length: N }, () => store.mutate(async (data) => {+ const current = data.n;+ await Promise.resolve(); // yield — invites interleaving+ data.n = current + 1;+ }))+ );+ expect((await store.load()).n).toBe(N);+ expect(JSON.parse(await readFile(file, 'utf-8')).n).toBe(N);+ });++ it('mutate that returns undefined persists the mutated input', async () => {+ const store = createCachedStore(join(dir, 'x.json'), { items: [] });+ await store.mutate((data) => { data.items.push('a'); });+ await store.mutate((data) => { data.items.push('b'); });+ expect((await store.load()).items).toEqual(['a', 'b']);+ });++ it('invalidateCache forces a re-read from disk', async () => {+ const file = join(dir, 'x.json');+ const store = createCachedStore(file, { n: 0 });+ await store.load();+ await writeFile(file, JSON.stringify({ n: 42 }));+ store.invalidateCache();+ expect((await store.load()).n).toBe(42);+ });+});+// =============================================================================// sanitizeFilename / getFileExtension / getMimeType / allowlists (#1140)// =============================================================================diff --git a/server/lib/index.js b/server/lib/index.jsindex 5b62b9cb48..0b1f7f445c 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -110,6 +110,7 @@ export * from './tuiHandshake.js';export * from './tuiPromptRunner.js';// === File & I/O ===+export * from './boundedStateMap.js';export * from './collectionStore.js';export * from './conflictJournal.js';export * from './createKeyCachedQueue.js';diff --git a/server/services/agentPersonalities.js b/server/services/agentPersonalities.jsindex c9f7bb940a..f93f59433e 100644--- a/server/services/agentPersonalities.js+++ b/server/services/agentPersonalities.js@@ -14,7 +14,6 @@ import { PATHS, createCachedStore } from '../lib/fileUtils.js';const AGENTS_FILE = join(PATHS.agentPersonalities, 'agents.json');const store = createCachedStore(AGENTS_FILE, { agents: {} }, { context: 'agentPersonalities' });const loadAgents = store.load;-const saveAgents = store.save;// Event emitter for agent personality changesexport const agentPersonalityEvents = new EventEmitter();@@ -53,7 +52,6 @@ export async function getAgentById(id) {* Create a new agent personality*/export async function createAgent(agentData) {- const data = await loadAgents();const id = uuidv4();const now = new Date().toISOString();@@ -75,8 +73,7 @@ export async function createAgent(agentData) {updatedAt: now};- data.agents[id] = agent;- await saveAgents(data);+ await store.mutate((data) => { data.agents[id] = agent; });notifyChanged('create', id);console.log(`🤖 Created agent personality: ${agent.name} (${id})`);@@ -87,31 +84,31 @@ export async function createAgent(agentData) {* Update an existing agent personality*/export async function updateAgent(id, updates) {- const data = await loadAgents();-- if (!data.agents[id]) {- return null;- }-- // Remove id from updates if present- const { id: _id, createdAt: _createdAt, ...cleanUpdates } = updates;-- // Handle nested personality updates properly- const existingPersonality = data.agents[id].personality || {};- const updatedPersonality = cleanUpdates.personality- ? { ...existingPersonality, ...cleanUpdates.personality }- : existingPersonality;-- const agent = {- ...data.agents[id],- ...cleanUpdates,- personality: updatedPersonality,- createdAt: data.agents[id].createdAt,- updatedAt: new Date().toISOString()- };-- data.agents[id] = agent;- await saveAgents(data);+ let agent = null;+ await store.mutate((data) => {+ if (!data.agents[id]) return data; // not found — persist unchanged+ // Remove id from updates if present+ const { id: _id, createdAt: _createdAt, ...cleanUpdates } = updates;++ // Handle nested personality updates properly+ const existingPersonality = data.agents[id].personality || {};+ const updatedPersonality = cleanUpdates.personality+ ? { ...existingPersonality, ...cleanUpdates.personality }+ : existingPersonality;++ agent = {+ ...data.agents[id],+ ...cleanUpdates,+ personality: updatedPersonality,+ createdAt: data.agents[id].createdAt,+ updatedAt: new Date().toISOString()+ };++ data.agents[id] = agent;+ return data;+ });++ if (!agent) return null;notifyChanged('update', id);console.log(`📝 Updated agent personality: ${agent.name} (${id})`);@@ -122,15 +119,15 @@ export async function updateAgent(id, updates) {* Delete an agent personality*/export async function deleteAgent(id) {- const data = await loadAgents();-- if (!data.agents[id]) {- return false;- }-- const agentName = data.agents[id].name;- delete data.agents[id];- await saveAgents(data);+ let agentName = null;+ await store.mutate((data) => {+ if (!data.agents[id]) return data; // not found — persist unchanged+ agentName = data.agents[id].name;+ delete data.agents[id];+ return data;+ });++ if (agentName === null) return false;notifyChanged('delete', id);console.log(`🗑️ Deleted agent personality: ${agentName} (${id})`);diff --git a/server/services/automationScheduler.js b/server/services/automationScheduler.jsindex c6934d60da..614c632b2f 100644--- a/server/services/automationScheduler.js+++ b/server/services/automationScheduler.js@@ -16,7 +16,6 @@ import { getUserTimezone } from '../lib/timezone.js';const SCHEDULES_FILE = join(PATHS.agentPersonalities, 'schedules.json');const store = createCachedStore(SCHEDULES_FILE, { schedules: {} }, { context: 'automation schedules' });const loadSchedules = store.load;-const saveSchedules = store.save;// Event emitter for schedule changesexport const scheduleEvents = new EventEmitter();@@ -75,7 +74,6 @@ export async function getScheduleById(id) {* Create a new schedule*/export async function createSchedule(scheduleData) {- const data = await loadSchedules();const id = uuidv4();const now = new Date().toISOString();@@ -100,8 +98,7 @@ export async function createSchedule(scheduleData) {updatedAt: now};- data.schedules[id] = schedule;- await saveSchedules(data);+ await store.mutate((data) => { data.schedules[id] = schedule; });notifyChanged('create', id);// If enabled, activate the schedule@@ -117,24 +114,26 @@ export async function createSchedule(scheduleData) {* Update an existing schedule*/export async function updateSchedule(id, updates) {- const data = await loadSchedules();-- if (!data.schedules[id]) {- return null;- }-- const { id: _id, createdAt: _createdAt, ...cleanUpdates } = updates;- const wasEnabled = data.schedules[id].enabled;-- const schedule = {- ...data.schedules[id],- ...cleanUpdates,- createdAt: data.schedules[id].createdAt,- updatedAt: new Date().toISOString()- };+ let schedule = null;+ let wasEnabled = false;+ await store.mutate((data) => {+ if (!data.schedules[id]) return data;++ const { id: _id, createdAt: _createdAt, ...cleanUpdates } = updates;+ wasEnabled = data.schedules[id].enabled;++ schedule = {+ ...data.schedules[id],+ ...cleanUpdates,+ createdAt: data.schedules[id].createdAt,+ updatedAt: new Date().toISOString()+ };++ data.schedules[id] = schedule;+ return data;+ });- data.schedules[id] = schedule;- await saveSchedules(data);+ if (!schedule) return null;notifyChanged('update', id);// Handle enable/disable@@ -156,17 +155,18 @@ export async function updateSchedule(id, updates) {* Delete a schedule*/export async function deleteSchedule(id) {- const data = await loadSchedules();+ let existed = false;+ await store.mutate((data) => {+ if (!data.schedules[id]) return data;+ existed = true;+ delete data.schedules[id];+ return data;+ });- if (!data.schedules[id]) {- return false;- }+ if (!existed) return false;// Deactivate if runningawait deactivateSchedule(id);-- delete data.schedules[id];- await saveSchedules(data);notifyChanged('delete', id);console.log(`🗑️ Deleted schedule (${id})`);@@ -292,12 +292,12 @@ async function executeScheduledAction(scheduleId) {});// Update last run- const data = await loadSchedules();- if (data.schedules[scheduleId]) {- data.schedules[scheduleId].lastRun = now;- data.schedules[scheduleId].runCount = (data.schedules[scheduleId].runCount || 0) + 1;- await saveSchedules(data);- }+ await store.mutate((data) => {+ if (data.schedules[scheduleId]) {+ data.schedules[scheduleId].lastRun = now;+ data.schedules[scheduleId].runCount = (data.schedules[scheduleId].runCount || 0) + 1;+ }+ });// Emit event for platform integration to pick upscheduleEvents.emit('execute', {diff --git a/server/services/backup.js b/server/services/backup.jsindex d02bb516b2..c6539010c3 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -11,6 +11,7 @@ import { access, readdir, readFile, stat, unlink } from 'fs/promises';import { hostname } from 'os';import { join, resolve, relative, isAbsolute } from 'path';import { PATHS, ensureDir, readJSONFile, atomicWrite, sha256File } from '../lib/fileUtils.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { getEvent } from './eventScheduler.js';import { checkHealth, getServerMajorVersion } from '../lib/db.js';import { resolvePgDumpBinary } from '../lib/pgTools.js';@@ -25,6 +26,11 @@ let isRunning = false;const STATE_PATH = join(PATHS.data, 'backup', 'state.json');+// Serialize state read-merge-write so two saveState() calls (e.g. a run+// completing while the scheduler stamps a status) can't each read the same+// pre-image and clobber the other's fields. Single tail per shared state file.+const queueStateWrite = createFileWriteQueue();+// Paths under data/ that are skipped by default on top of user-configured excludes.// Two classes live here: (1) ephemeral/cache data the user almost never wants in a// snapshot (browser profile, agent worktrees), and (2) large re-downloadable assets@@ -611,10 +617,13 @@ export async function getState() {* @param {object} patch - Fields to merge into state*/export async function saveState(patch) {- await ensureDir(join(PATHS.data, 'backup'));- const current = await getState();- const updated = { ...current, ...patch };- await atomicWrite(STATE_PATH, updated);+ return queueStateWrite(async () => {+ await ensureDir(join(PATHS.data, 'backup'));+ const current = await getState();+ const updated = { ...current, ...patch };+ await atomicWrite(STATE_PATH, updated);+ return updated;+ });}/**diff --git a/server/services/feeds.js b/server/services/feeds.jsindex 11b9932c6f..7f71ee5207 100644--- a/server/services/feeds.js+++ b/server/services/feeds.js@@ -45,13 +45,14 @@ const isSortedNewestFirst = (items) => {async function ensureItemsSorted() {if (_itemsSorted) return;- const data = await store.load();- if (!isSortedNewestFirst(data.items)) {- sortItemsNewestFirst(data.items);- await store.save(data);- } else {- _itemsSorted = true;- }+ await store.mutate((data) => {+ if (!isSortedNewestFirst(data.items)) {+ sortItemsNewestFirst(data.items);+ } else {+ _itemsSorted = true;+ }+ return data;+ });}// ─── RSS/Atom Parser ────────────────────────────────────────────────────────@@ -146,10 +147,11 @@ export async function getFeeds() {}export async function addFeed(url) {- const data = await store.load();-- // Check for duplicate URL- if (data.feeds.some(f => f.url === url)) {+ // Fast pre-check for an obvious duplicate so we don't fetch the network for+ // a URL we're going to reject anyway. The authoritative re-check happens+ // inside the serialized mutate below.+ const existing = await store.load();+ if (existing.feeds.some(f => f.url === url)) {return { error: 'Feed URL already subscribed' };}@@ -169,8 +171,6 @@ export async function addFeed(url) {itemCount: parsed.items.length};- data.feeds.push(feed);-// Add initial itemsconst newItems = parsed.items.slice(0, MAX_ITEMS_PER_FEED).map(item => ({id: randomUUID(),@@ -183,76 +183,65 @@ export async function addFeed(url) {read: false,fetchedAt: new Date().toISOString()}));- data.items.push(...newItems);- sortItemsNewestFirst(data.items);- await store.save(data);+ let dup = false;+ await store.mutate((data) => {+ if (data.feeds.some(f => f.url === url)) { dup = true; return data; }+ data.feeds.push(feed);+ data.items.push(...newItems);+ sortItemsNewestFirst(data.items);+ return data;+ });+ if (dup) return { error: 'Feed URL already subscribed' };+console.log(`📡 Feed added: ${feed.title} (${newItems.length} items)`);return { feed: { ...feed, unreadCount: newItems.length } };}export async function removeFeed(id) {- const data = await store.load();- const idx = data.feeds.findIndex(f => f.id === id);- if (idx === -1) return { error: 'Feed not found' };-- const feed = data.feeds[idx];- data.feeds.splice(idx, 1);- data.items = data.items.filter(i => i.feedId !== id);- await store.save(data);+ let removedFeed = null;+ await store.mutate((data) => {+ const idx = data.feeds.findIndex(f => f.id === id);+ if (idx === -1) return data;+ removedFeed = data.feeds[idx];+ data.feeds.splice(idx, 1);+ data.items = data.items.filter(i => i.feedId !== id);+ return data;+ });- console.log(`🗑️ Feed removed: ${feed.title}`);+ if (!removedFeed) return { error: 'Feed not found' };+ console.log(`🗑️ Feed removed: ${removedFeed.title}`);return { removed: true };}export async function refreshFeed(id) {- const data = await store.load();- const feed = data.feeds.find(f => f.id === id);- if (!feed) return { error: 'Feed not found' };-- const xml = await fetchFeedXml(feed.url);+ const snapshot = await store.load();+ const feedSnapshot = snapshot.feeds.find(f => f.id === id);+ if (!feedSnapshot) return { error: 'Feed not found' };++ // Network fetch happens outside the write lock; the parsed result is applied+ // under mutate so a concurrent write can't clobber the merge (applyParsedFeed+ // is the shared no-I/O merge — dedupe, trim, bump lastFetched/itemCount/title).+ const xml = await fetchFeedXml(feedSnapshot.url);if (!xml) return { error: 'Could not fetch feed' };const parsed = parseFeed(xml);- // Deduplicate by link- const existingLinks = new Set(data.items.filter(i => i.feedId === id).map(i => i.link));- const newItems = parsed.items- .filter(item => item.link && !existingLinks.has(item.link))- .slice(0, MAX_ITEMS_PER_FEED)- .map(item => ({- id: randomUUID(),- feedId: id,- title: item.title,- link: item.link,- description: item.description,- pubDate: item.pubDate,- author: item.author,- read: false,- fetchedAt: new Date().toISOString()- }));-- data.items.push(...newItems);-- // Trim to MAX_ITEMS_PER_FEED per feed (keep newest)- const feedItems = data.items- .filter(i => i.feedId === id)- .sort((a, b) => new Date(b.fetchedAt) - new Date(a.fetchedAt));- if (feedItems.length > MAX_ITEMS_PER_FEED) {- const keepIds = new Set(feedItems.slice(0, MAX_ITEMS_PER_FEED).map(i => i.id));- data.items = data.items.filter(i => i.feedId !== id || keepIds.has(i.id));- }-- feed.lastFetched = new Date().toISOString();- feed.itemCount = data.items.filter(i => i.feedId === id).length;- if (parsed.title) feed.title = parsed.title;-- sortItemsNewestFirst(data.items);- await store.save(data);- console.log(`🔄 Feed refreshed: ${feed.title} (+${newItems.length} new)`);+ let result = null;+ await store.mutate((data) => {+ const feed = data.feeds.find(f => f.id === id);+ if (!feed) return data; // removed between fetch and apply+ const newCount = applyParsedFeed(data, feed, parsed);+ sortItemsNewestFirst(data.items);+ const unreadCount = data.items.filter(i => i.feedId === id && !i.read).length;+ result = { feed: { ...feed, unreadCount }, newCount };+ return data;+ });- return { feed: { ...feed, unreadCount: data.items.filter(i => i.feedId === id && !i.read).length }, newCount: newItems.length };+ if (!result) return { error: 'Feed not found' };+ console.log(`🔄 Feed refreshed: ${result.feed.title} (+${result.newCount} new)`);+ return result;}// Fetch and parse XML for a feed without touching the store (safe to run in parallel)@@ -305,14 +294,17 @@ function applyParsedFeed(data, feed, parsed) {// runs per feed inside the loop and we'd otherwise re-sort the whole array// N times for an N-feed refresh.export async function refreshAllFeeds() {- const data = await store.load();+ const snapshot = await store.load();+ const feedList = [...snapshot.feeds];const CONCURRENCY = 5;- let totalNew = 0;let totalFailed = 0;- // Fetch in parallel batches; mutations are applied serially to avoid concurrent store.save() races- for (let i = 0; i < data.feeds.length; i += CONCURRENCY) {- const batch = data.feeds.slice(i, i + CONCURRENCY);+ // Fetch in parallel batches (no store I/O), collecting parsed results; the+ // merge into the store happens once under mutate so a concurrent write path+ // can't clobber the batch.+ const parsedResults = [];+ for (let i = 0; i < feedList.length; i += CONCURRENCY) {+ const batch = feedList.slice(i, i + CONCURRENCY);const fetched = await Promise.allSettled(batch.map(f => fetchAndParseFeed(f)));for (const r of fetched) {if (r.status === 'rejected') {@@ -326,16 +318,25 @@ export async function refreshAllFeeds() {console.warn(`⚠️ feeds: refresh failed for ${feed.id} (${feed.url}): ${error}`);continue;}+ parsedResults.push({ feed, parsed });+ }+ }++ let totalNew = 0;+ let feedCount = 0;+ await store.mutate((data) => {+ for (const { feed, parsed } of parsedResults) {const newCount = applyParsedFeed(data, feed, parsed);console.log(`🔄 Feed refreshed: ${feed.title || feed.id} (+${newCount} new)`);totalNew += newCount;}- }+ if (totalNew > 0) sortItemsNewestFirst(data.items);+ feedCount = data.feeds.length;+ return data;+ });- if (totalNew > 0) sortItemsNewestFirst(data.items);- await store.save(data);console.log(`📡 All feeds refreshed: +${totalNew} new items, ${totalFailed} failures`);- return { refreshed: data.feeds.length, newItems: totalNew, failures: totalFailed };+ return { refreshed: feedCount, newItems: totalNew, failures: totalFailed };}export async function getItems({ feedId, unreadOnly, limit, offset = 0 } = {}) {@@ -351,25 +352,30 @@ export async function getItems({ feedId, unreadOnly, limit, offset = 0 } = {}) {}export async function markItemRead(itemId) {- const data = await store.load();- const item = data.items.find(i => i.id === itemId);- if (!item) return { error: 'Item not found' };- item.read = true;- await store.save(data);+ let found = false;+ await store.mutate((data) => {+ const item = data.items.find(i => i.id === itemId);+ if (!item) return data;+ item.read = true;+ found = true;+ return data;+ });+ if (!found) return { error: 'Item not found' };return { updated: true };}export async function markAllRead(feedId) {- const data = await store.load();let count = 0;- for (const item of data.items) {- if (feedId && item.feedId !== feedId) continue;- if (!item.read) {- item.read = true;- count++;+ await store.mutate((data) => {+ for (const item of data.items) {+ if (feedId && item.feedId !== feedId) continue;+ if (!item.read) {+ item.read = true;+ count++;+ }}- }- await store.save(data);+ return data;+ });console.log(`✅ Marked ${count} items as read${feedId ? ` for feed ${feedId}` : ''}`);return { marked: count };}diff --git a/server/services/platformAccounts.js b/server/services/platformAccounts.jsindex 7d990b1e99..f2eb14600d 100644--- a/server/services/platformAccounts.js+++ b/server/services/platformAccounts.js@@ -14,7 +14,6 @@ import { PATHS, createCachedStore } from '../lib/fileUtils.js';const ACCOUNTS_FILE = join(PATHS.agentPersonalities, 'accounts.json');const store = createCachedStore(ACCOUNTS_FILE, { accounts: {} }, { context: 'platformAccounts' });const loadAccounts = store.load;-const saveAccounts = store.save;// Event emitter for account changesexport const platformAccountEvents = new EventEmitter();@@ -77,7 +76,6 @@ export async function getAccountWithCredentials(id) {* Create a new platform account*/export async function createAccount(accountData) {- const data = await loadAccounts();const id = uuidv4();const now = new Date().toISOString();@@ -95,8 +93,7 @@ export async function createAccount(accountData) {createdAt: now};- data.accounts[id] = account;- await saveAccounts(data);+ await store.mutate((data) => { data.accounts[id] = account; });notifyChanged('create', id);console.log(`🔗 Created platform account: ${account.platform}/${account.credentials.username} (${id})`);@@ -114,22 +111,22 @@ export async function createAccount(accountData) {* Update account status*/export async function updateAccountStatus(id, status, platformData = null) {- const data = await loadAccounts();-- if (!data.accounts[id]) {- return null;- }-- data.accounts[id].status = status;- data.accounts[id].lastActivity = new Date().toISOString();- if (platformData) {- data.accounts[id].platformData = {- ...data.accounts[id].platformData,- ...platformData- };- }+ let found = false;+ await store.mutate((data) => {+ if (!data.accounts[id]) return data;+ found = true;+ data.accounts[id].status = status;+ data.accounts[id].lastActivity = new Date().toISOString();+ if (platformData) {+ data.accounts[id].platformData = {+ ...data.accounts[id].platformData,+ ...platformData+ };+ }+ return data;+ });- await saveAccounts(data);+ if (!found) return null;notifyChanged('update', id);return getAccountById(id);@@ -139,15 +136,15 @@ export async function updateAccountStatus(id, status, platformData = null) {* Record activity on account*/export async function recordActivity(id) {- const data = await loadAccounts();-- if (!data.accounts[id]) {- return null;- }-- data.accounts[id].lastActivity = new Date().toISOString();- await saveAccounts(data);-+ let found = false;+ await store.mutate((data) => {+ if (!data.accounts[id]) return data;+ found = true;+ data.accounts[id].lastActivity = new Date().toISOString();+ return data;+ });++ if (!found) return null;return getAccountById(id);}@@ -155,18 +152,18 @@ export async function recordActivity(id) {* Update account credentials*/export async function updateCredentials(id, credentials) {- const data = await loadAccounts();-- if (!data.accounts[id]) {- return null;- }-- data.accounts[id].credentials = {- ...data.accounts[id].credentials,- ...credentials- };+ let found = false;+ await store.mutate((data) => {+ if (!data.accounts[id]) return data;+ found = true;+ data.accounts[id].credentials = {+ ...data.accounts[id].credentials,+ ...credentials+ };+ return data;+ });- await saveAccounts(data);+ if (!found) return null;notifyChanged('update', id);console.log(`🔑 Updated credentials for account ${id}`);@@ -177,15 +174,15 @@ export async function updateCredentials(id, credentials) {* Delete a platform account*/export async function deleteAccount(id) {- const data = await loadAccounts();-- if (!data.accounts[id]) {- return false;- }-- const account = data.accounts[id];- delete data.accounts[id];- await saveAccounts(data);+ let account = null;+ await store.mutate((data) => {+ if (!data.accounts[id]) return data;+ account = data.accounts[id];+ delete data.accounts[id];+ return data;+ });++ if (!account) return false;notifyChanged('delete', id);console.log(`🗑️ Deleted platform account: ${account.platform}/${account.credentials.username} (${id})`);diff --git a/server/services/socialAccounts.js b/server/services/socialAccounts.jsindex 956781e54f..9b06c58af7 100644--- a/server/services/socialAccounts.js+++ b/server/services/socialAccounts.js@@ -176,7 +176,6 @@ export async function getAccountsByCategory(category) {* Create a new social account*/export async function createAccount(accountData) {- const data = await loadAccounts();const id = uuidv4();const now = new Date().toISOString();@@ -196,8 +195,7 @@ export async function createAccount(accountData) {updatedAt: now};- data.accounts[id] = account;- await saveAccounts(data);+ await store.mutate((data) => { data.accounts[id] = account; });notifyChanged('create', id);console.log(`🔗 Added social account: ${account.platform}/${account.username} (${id})`);@@ -208,39 +206,46 @@ export async function createAccount(accountData) {* Update a social account*/export async function updateAccount(id, updates) {- const data = await loadAccounts();- if (!data.accounts[id]) return null;+ let account = null;+ await store.mutate((data) => {+ if (!data.accounts[id]) return data;- const allowed = [- 'username', 'displayName', 'url', 'bio', 'contentTypes',- 'ingestionEnabled', 'ingestionStatus', 'lastIngested',- 'contentCount', 'notes'- ];+ const allowed = [+ 'username', 'displayName', 'url', 'bio', 'contentTypes',+ 'ingestionEnabled', 'ingestionStatus', 'lastIngested',+ 'contentCount', 'notes'+ ];- for (const key of allowed) {- if (updates[key] !== undefined) {- data.accounts[id][key] = updates[key];+ for (const key of allowed) {+ if (updates[key] !== undefined) {+ data.accounts[id][key] = updates[key];+ }}- }- data.accounts[id].updatedAt = new Date().toISOString();+ data.accounts[id].updatedAt = new Date().toISOString();+ account = data.accounts[id];+ return data;+ });- await saveAccounts(data);+ if (!account) return null;notifyChanged('update', id);- console.log(`📝 Updated social account: ${data.accounts[id].platform}/${data.accounts[id].username} (${id})`);- return { id, ...data.accounts[id] };+ console.log(`📝 Updated social account: ${account.platform}/${account.username} (${id})`);+ return { id, ...account };}/*** Delete a social account*/export async function deleteAccount(id) {- const data = await loadAccounts();- if (!data.accounts[id]) return false;+ let account = null;+ await store.mutate((data) => {+ if (!data.accounts[id]) return data;+ account = data.accounts[id];+ delete data.accounts[id];+ return data;+ });- const account = data.accounts[id];- delete data.accounts[id];- await saveAccounts(data);+ if (!account) return false;notifyChanged('delete', id);console.log(`🗑️ Removed social account: ${account.platform}/${account.username} (${id})`);