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

test: cover destructive routes and sharing modules, deflake timing-dependent suites

[._.]/ Adam Eivyb0d5b139d58d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e1e27ff5c7..b2621f90a7 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -25,6 +25,7 @@
- **Loop fallback crash + durability** — provider fallback no longer crashes loop iterations; loops.json writes are atomic and serialized; cos-runner state races, leaked kill timers, and unguarded close handlers fixed; N+1 issue scans eliminated with an uncapped accessor so >1000-issue installs don't miscount; HF repo-size and Telegram check-in caches bounded.
- **Crash-proofing + UI hygiene** — voice socket handlers can't take down the server on settings-read failures; hung deploy scripts time out instead of wedging the deploy lock; buttons get explicit types, list keys stabilized, theme/notification fetches gain abort/unmount guards.
- **Dependency security** — Outlook message refresh no longer crashes on an uninstalled `uuid` import; `@protobufjs/utf8` override unpinned from its own CVE (1.1.1), `ws` 8.21.0 override added, eslint/brace-expansion/jsdom updated; npm audit is clean.
+- **Test quality** — the database-destroy safety guard and sharing identity/watcher modules now have real tests; timing-dependent suites use fake timers; vacuous assertions strengthened; temp dirs cleaned up.
- **A watched TUI run no longer false-times-out after finishing its work** — companion fix to *Live TUI runs are now viewable AND drivable in the Shell page* (above). One-shot AI runs that drive a terminal UI (Claude Code, Codex, etc.) write their completed answer to a response file and then return to an interactive prompt **without exiting**. The runner only auto-completed such a run via output-idle — which is paused while you watch it in the Shell page (so it isn't snapped shut mid-read). With the process never exiting and idle paused, a watched run had no terminus but the 10-minute hard timeout — at which point it was marked **failed**, its already-written result was **discarded**, and a useless fallback retry ran in its place. The runner now watches for the response file as the model's authoritative "done" signal and completes the run the moment it's written — even while you're watching — since once the file exists the task is genuinely finished. A second safety net salvages the file on hard timeout: if the result was written but completion stalled for any other reason, the run finishes as **success** with that result instead of throwing it away and falling back. So a long editorial pass you keep open in the Shell tab now lands its findings when the model finishes, instead of silently dying at 10 minutes. (`server/lib/tuiPromptRunner.js`)
diff --git a/client/src/lib/healthProvenance.test.js b/client/src/lib/healthProvenance.test.js
index 8adedbf235..68d26621c1 100644
--- a/client/src/lib/healthProvenance.test.js
+++ b/client/src/lib/healthProvenance.test.js
@@ -16,11 +16,17 @@ describe('healthProvenance', () => {
});
it('every level carries label, tone, description, and a what-would-change explainer', () => {
+ const EXPECTED = {
+ 'data-backed': { label: 'Data-backed', tone: 'success' },
+ inferred: { label: 'Inferred', tone: 'accent' },
+ experimental: { label: 'Experimental', tone: 'warning' },
+ speculative: { label: 'Speculative', tone: 'muted' },
+ };
for (const id of PROVENANCE_LEVEL_IDS) {
const meta = PROVENANCE_LEVELS[id];
expect(meta.id).toBe(id);
- expect(meta.label).toBeTruthy();
- expect(['success', 'accent', 'warning', 'muted']).toContain(meta.tone);
+ expect(meta.label).toBe(EXPECTED[id].label);
+ expect(meta.tone).toBe(EXPECTED[id].tone);
expect(meta.description.length).toBeGreaterThan(10);
expect(meta.whatWouldChange.length).toBeGreaterThan(10);
}
diff --git a/server/lib/asyncMutex.test.js b/server/lib/asyncMutex.test.js
index 524579f6c3..e723ffa218 100644
--- a/server/lib/asyncMutex.test.js
+++ b/server/lib/asyncMutex.test.js
@@ -1,19 +1,25 @@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi, afterEach } from 'vitest';
import { createMutex } from './asyncMutex.js';
describe('asyncMutex.js', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
describe('createMutex', () => {
- it('should serialize concurrent operations', async () => {
+ it('serializes concurrent operations — deterministic with fake timers', async () => {
+ vi.useFakeTimers();
const withLock = createMutex();
const results = [];
- // Start multiple operations concurrently
+ // First op awaits a 20ms delay before pushing.
const p1 = withLock(async () => {
- await new Promise(r => setTimeout(r, 20));
+ await vi.advanceTimersByTimeAsync(20);
results.push('first');
return 'first';
});
+ // p2 and p3 are already queued behind p1.
const p2 = withLock(async () => {
results.push('second');
return 'second';
@@ -26,7 +32,7 @@ describe('asyncMutex.js', () => {
await Promise.all([p1, p2, p3]);
- // Operations should complete in order despite first one being slow
+ // Operations must complete in order despite p1 being slower.
expect(results).toEqual(['first', 'second', 'third']);
});
@@ -77,7 +83,7 @@ describe('asyncMutex.js', () => {
expect(result).toBe('sync result');
});
- it('should handle rapid sequential calls', async () => {
+ it('serializes rapid sequential calls — counter reaches 10 without races', async () => {
const withLock = createMutex();
let counter = 0;
@@ -85,26 +91,29 @@ describe('asyncMutex.js', () => {
for (let i = 0; i < 10; i++) {
promises.push(withLock(async () => {
const current = counter;
- await new Promise(r => setTimeout(r, 1));
+ // Microtask yield — gives the event loop a chance to interleave.
+ // Without serialization, concurrent readers would see the same
+ // `current` and the final counter would be less than 10.
+ await Promise.resolve();
counter = current + 1;
}));
}
await Promise.all(promises);
- // Without serialization, counter would likely be less than 10
- // due to race conditions
expect(counter).toBe(10);
});
- it('should create independent mutexes', async () => {
+ it('creates independent mutexes — separate queues run concurrently', async () => {
+ vi.useFakeTimers();
const withLock1 = createMutex();
const withLock2 = createMutex();
const results = [];
- // Both locks should run concurrently
+ // lock1's single op awaits a 20ms delay, lock2's op is instant.
+ // Because the mutexes are independent, lock2 must finish first.
const p1 = withLock1(async () => {
- await new Promise(r => setTimeout(r, 20));
+ await vi.advanceTimersByTimeAsync(20);
results.push('lock1');
});
@@ -114,7 +123,7 @@ describe('asyncMutex.js', () => {
await Promise.all([p1, p2]);
- // lock2 should finish first since locks are independent
+ // lock2 finishes first — independent queues don't block each other.
expect(results[0]).toBe('lock2');
expect(results[1]).toBe('lock1');
});
diff --git a/server/lib/fetchWithTimeout.test.js b/server/lib/fetchWithTimeout.test.js
index 4e7d94a4e1..80afa5e6cf 100644
--- a/server/lib/fetchWithTimeout.test.js
+++ b/server/lib/fetchWithTimeout.test.js
@@ -34,12 +34,32 @@ describe('fetchWithTimeout', () => {
}
});
- it('clears timeout on success', async () => {
- const clearSpy = vi.spyOn(global, 'clearTimeout');
- vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }));
-
- await fetchWithTimeout('http://example.com');
- expect(clearSpy).toHaveBeenCalled();
+ it('clears timeout on success — no pending timer remains', async () => {
+ // Use fake timers so we can observe that no timer is left pending after
+ // a successful fetch. If clearTimeout were NOT called, advanceTimersByTime
+ // would later fire the abort, which would error on an already-resolved fetch.
+ vi.useFakeTimers();
+ try {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, status: 200 }));
+ const clearSpy = vi.spyOn(global, 'clearTimeout');
+
+ const result = await fetchWithTimeout('http://example.com', {}, 5000);
+
+ expect(result.status).toBe(200);
+ // clearTimeout must have been called with a non-null handle.
+ // Under fake timers the handle is an object, not a number; the important
+ // thing is it was called (not skipped) and not with null/undefined.
+ expect(clearSpy).toHaveBeenCalledTimes(1);
+ const [handle] = clearSpy.mock.calls[0];
+ expect(handle).not.toBeNull();
+ expect(handle).not.toBeUndefined();
+
+ // Advance past the original timeout — if the abort timer were still
+ // pending this would cause an unhandled abort on a resolved promise.
+ vi.advanceTimersByTime(6000);
+ } finally {
+ vi.useRealTimers();
+ }
});
it('forwards options to fetch', async () => {
diff --git a/server/lib/universePromptRenderers.test.js b/server/lib/universePromptRenderers.test.js
index 3ec02f2c0e..d75125e46f 100644
--- a/server/lib/universePromptRenderers.test.js
+++ b/server/lib/universePromptRenderers.test.js
@@ -79,7 +79,7 @@ describe('renderEntitiesSummary', () => {
});
// Descriptor body length stays bounded; trailing ellipsis present.
const match = out.match(/Mira \(([^)]+)\)/);
- expect(match).toBeTruthy();
+ expect(match, 'renderEntitiesSummary should produce a "Mira (...)" descriptor').not.toBeNull();
expect(match[1].length).toBeLessThanOrEqual(ENTITIES_SUMMARY_DESCRIPTOR_MAX);
expect(match[1]).toMatch(/…$/);
});
diff --git a/server/routes/database.test.js b/server/routes/database.test.js
new file mode 100644
index 0000000000..264d38f287
--- /dev/null
+++ b/server/routes/database.test.js
@@ -0,0 +1,201 @@
+/**
+ * Tests for POST /api/database/destroy (and the adjacent validation paths).
+ *
+ * Strategy: mock child_process.execFile — which is what runCmd() wraps — so
+ * we can control every shell invocation without touching the real filesystem
+ * or running actual Docker/psql commands.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+
+// resolveBashBinary and the db.sh path are resolved at module load — mock
+// the dependencies before the route is imported.
+vi.mock('../lib/bashResolver.js', () => ({
+ resolveBashBinary: vi.fn(() => 'bash'),
+}));
+
+vi.mock('../lib/pgTools.js', () => ({
+ resolvePgDumpBinary: vi.fn(async () => ({ binary: 'pg_dump', satisfies: true })),
+}));
+
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, root: '/fake/root' },
+ };
+});
+
+vi.mock('../lib/db.js', () => ({
+ checkHealth: vi.fn(async () => ({ healthy: true })),
+ query: vi.fn(async () => ({ rows: [] })),
+}));
+
+// Mock child_process.execFile at the module level.
+vi.mock('child_process', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ execFile: vi.fn(),
+ };
+});
+
+import { execFile } from 'child_process';
+import databaseRoutes from './database.js';
+
+// Helper: make execFile call the callback with controlled output
+function mockExecFile(responses) {
+ // responses: array of { exitCode, stdout, stderr } in call order.
+ // Any call beyond the list resolves with exitCode=0.
+ let callIndex = 0;
+ execFile.mockImplementation((_cmd, _args, _opts, callback) => {
+ const resp = responses[callIndex++] ?? { exitCode: 0, stdout: '', stderr: '' };
+ if (resp.exitCode !== 0) {
+ const err = Object.assign(new Error(resp.stderr || 'error'), { code: resp.exitCode });
+ callback(err, resp.stdout || '', resp.stderr || '');
+ } else {
+ callback(null, resp.stdout || '', resp.stderr || '');
+ }
+ // Return a dummy handle (execFile should return a ChildProcess)
+ return { pid: 0 };
+ });
+}
+
+function makeApp() {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/database', databaseRoutes);
+ app.use((err, _req, res, _next) => {
+ res.status(err.status ?? 500).json({ error: err.message, code: err.code });
+ });
+ return app;
+}
+
+describe('POST /api/database/destroy', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('input validation', () => {
+ it('returns 400 when backend is missing', async () => {
+ const app = makeApp();
+ const res = await request(app).post('/api/database/destroy').send({});
+ expect(res.status).toBe(400);
+ expect(res.body.error).toMatch(/backend/i);
+ });
+
+ it('returns 400 when backend is an unknown value', async () => {
+ const app = makeApp();
+ const res = await request(app)
+ .post('/api/database/destroy')
+ .send({ backend: 'mysql' });
+ expect(res.status).toBe(400);
+ expect(res.body.error).toMatch(/docker.*native|native.*docker/i);
+ });
+
+ it('returns 400 when backend is null', async () => {
+ const app = makeApp();
+ const res = await request(app)
+ .post('/api/database/destroy')
+ .send({ backend: null });
+ expect(res.status).toBe(400);
+ });
+ });
+
+ describe('active-backend safety guard', () => {
+ it('returns 400 when the requested backend matches the active backend (docker)', async () => {
+ // First execFile call is runDbScript(['status']) → returns "Current mode: docker"
+ mockExecFile([
+ { exitCode: 0, stdout: 'Current mode: docker\nSome other output', stderr: '' },
+ ]);
+
+ const app = makeApp();
+ const res = await request(app)
+ .post('/api/database/destroy')
+ .send({ backend: 'docker' });
+
+ expect(res.status).toBe(400);
+ expect(res.body.error).toMatch(/active/i);
+ });
+
+ it('returns 400 when the requested backend matches the active backend (native)', async () => {
+ mockExecFile([
+ { exitCode: 0, stdout: 'Current mode: native', stderr: '' },
+ ]);
+
+ const app = makeApp();
+ const res = await request(app)
+ .post('/api/database/destroy')
+ .send({ backend: 'native' });
+
+ expect(res.status).toBe(400);
+ expect(res.body.error).toMatch(/active/i);
+ });
+ });
+
+ describe('docker destroy path', () => {
+ it('invokes docker stop, rm, and volume rm commands when destroying non-active docker backend', async () => {
+ // Call order:
+ // 0: runDbScript(['status']) → mode is "native" (so docker is the non-active backend)
+ // 1: docker compose stop db
+ // 2: docker compose rm -f db
+ // 3: docker volume rm -f portos_portos-pgdata (first volume attempt)
+ // 4: docker volume rm -f portos-pgdata (alternate volume attempt)
+ mockExecFile([
+ { exitCode: 0, stdout: 'Current mode: native', stderr: '' },
+ { exitCode: 0, stdout: '', stderr: '' }, // compose stop
+ { exitCode: 0, stdout: '', stderr: '' }, // compose rm
+ { exitCode: 0, stdout: '', stderr: '' }, // volume rm primary
+ { exitCode: 0, stdout: '', stderr: '' }, // volume rm alternate
+ ]);
+
+ const app = makeApp();
+ const res = await request(app)
+ .post('/api/database/destroy')
+ .send({ backend: 'docker' });
+
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+
+ // Verify the first call was the status probe
+ const statusCall = execFile.mock.calls[0];
+ expect(statusCall[1]).toContain('status'); // db.sh status arg
+
+ // Verify one of the calls used 'docker' as the command with compose/volume args
+ const dockerCalls = execFile.mock.calls.filter(c => c[0] === 'docker');
+ expect(dockerCalls.length).toBeGreaterThanOrEqual(3);
+
+ const volumeRmCall = dockerCalls.find(
+ c => c[1].includes('volume') && c[1].includes('rm')
+ );
+ expect(volumeRmCall).toBeDefined();
+ });
+ });
+
+ describe('native destroy path', () => {
+ it('invokes psql DROP DATABASE when destroying the non-active native backend', async () => {
+ // Call order:
+ // 0: runDbScript(['status']) → mode is "docker" (so native is non-active)
+ // 1: psql DROP DATABASE …
+ mockExecFile([
+ { exitCode: 0, stdout: 'Current mode: docker', stderr: '' },
+ { exitCode: 0, stdout: 'DROP DATABASE', stderr: '' },
+ ]);
+
+ const app = makeApp();
+ const res = await request(app)
+ .post('/api/database/destroy')
+ .send({ backend: 'native' });
+
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+
+ // Verify a psql call was made
+ const psqlCall = execFile.mock.calls.find(c => c[0] === 'psql');
+ expect(psqlCall).toBeDefined();
+ // The args should contain a DROP DATABASE statement
+ expect(psqlCall[1].join(' ')).toMatch(/DROP DATABASE/i);
+ });
+ });
+});
diff --git a/server/routes/tools.test.js b/server/routes/tools.test.js
index b794e9b771..5064a555ea 100644
--- a/server/routes/tools.test.js
+++ b/server/routes/tools.test.js
@@ -49,6 +49,18 @@ describe('Tools Routes', () => {
expect(response.status).toBe(200);
expect(response.body).toHaveLength(1);
+ expect(response.body[0].id).toBe('sd-api');
+ expect(response.body[0].enabled).toBe(true);
+ expect(toolsService.getEnabledTools).toHaveBeenCalledTimes(1);
+ });
+
+ it('returns an empty array when no tools are enabled', async () => {
+ toolsService.getEnabledTools.mockResolvedValue([]);
+
+ const response = await request(app).get('/api/tools/enabled');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual([]);
});
});
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
index 8180a5d9ca..81d3078d7a 100644
--- a/server/services/localLlm.test.js
+++ b/server/services/localLlm.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import os from 'os';
import path from 'path';
import fs from 'fs';
@@ -61,6 +61,13 @@ beforeEach(async () => {
svc = await import('./localLlm.js');
});
+afterEach(() => {
+ if (state.root) {
+ fs.rmSync(state.root, { recursive: true, force: true });
+ state.root = '';
+ }
+});
+
describe('localLlm', () => {
describe('getBackend', () => {
it('defaults to ollama when .env has no marker', () => {
diff --git a/server/services/sharing/annotationIdentity.test.js b/server/services/sharing/annotationIdentity.test.js
new file mode 100644
index 0000000000..89ffc5ba80
--- /dev/null
+++ b/server/services/sharing/annotationIdentity.test.js
@@ -0,0 +1,191 @@
+/**
+ * Tests for server/services/sharing/annotationIdentity.js
+ *
+ * The module memoizes a display-name read (30s TTL), invalidates on
+ * settings:updated events, and falls back to os.userInfo().username.
+ * We stub getSettings and os.userInfo to drive the caching paths.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// --- mock settings.js before the module is imported -----------------------
+
+const settingsEventEmitter = vi.hoisted(() => {
+ // A minimal EventEmitter stub so `settingsEvents.on(...)` can be called.
+ const listeners = {};
+ return {
+ on(event, fn) { (listeners[event] ||= []).push(fn); },
+ emit(event, ...args) { (listeners[event] || []).forEach(fn => fn(...args)); },
+ _listeners: listeners,
+ };
+});
+
+vi.mock('../settings.js', () => ({
+ getSettings: vi.fn(),
+ settingsEvents: settingsEventEmitter,
+}));
+
+// mock os — override userInfo so the fallback is deterministic
+vi.mock('os', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, userInfo: vi.fn(() => ({ username: 'os-user' })) };
+});
+
+import { getSettings } from '../settings.js';
+import * as osModule from 'os';
+import {
+ resolveGlobalDisplayName,
+ invalidateGlobalDisplayNameCache,
+ resolveBucketSourceName,
+} from './annotationIdentity.js';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.useRealTimers();
+ // Always reset cache between tests so state doesn't bleed.
+ invalidateGlobalDisplayNameCache();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('annotationIdentity — resolveGlobalDisplayName', () => {
+ it('returns sharingDisplayName from settings when set', async () => {
+ getSettings.mockResolvedValue({ sharingDisplayName: 'Alice' });
+
+ const name = await resolveGlobalDisplayName();
+
+ expect(name).toBe('Alice');
+ });
+
+ it('falls back to os.userInfo().username when sharingDisplayName is absent', async () => {
+ getSettings.mockResolvedValue({});
+ osModule.userInfo.mockReturnValue({ username: 'bob' });
+
+ const name = await resolveGlobalDisplayName();
+
+ expect(name).toBe('bob');
+ });
+
+ it('falls back to os.userInfo().username when sharingDisplayName is whitespace', async () => {
+ getSettings.mockResolvedValue({ sharingDisplayName: ' ' });
+ osModule.userInfo.mockReturnValue({ username: 'carol' });
+
+ const name = await resolveGlobalDisplayName();
+
+ expect(name).toBe('carol');
+ });
+
+ it('falls back to "unknown" when settings and os.userInfo both fail', async () => {
+ getSettings.mockResolvedValue({});
+ osModule.userInfo.mockReturnValue({ username: '' });
+
+ const name = await resolveGlobalDisplayName();
+
+ expect(name).toBe('unknown');
+ });
+
+ it('returns the cached value within the TTL without re-reading settings', async () => {
+ vi.useFakeTimers();
+ getSettings.mockResolvedValue({ sharingDisplayName: 'Cached' });
+
+ const first = await resolveGlobalDisplayName();
+ expect(first).toBe('Cached');
+ expect(getSettings).toHaveBeenCalledTimes(1);
+
+ // Advance by less than the 30s TTL
+ vi.advanceTimersByTime(15_000);
+
+ // Second call must use the cache
+ const second = await resolveGlobalDisplayName();
+ expect(second).toBe('Cached');
+ expect(getSettings).toHaveBeenCalledTimes(1); // NOT called again
+ });
+
+ it('re-reads settings after the TTL expires', async () => {
+ vi.useFakeTimers();
+ getSettings
+ .mockResolvedValueOnce({ sharingDisplayName: 'First' })
+ .mockResolvedValueOnce({ sharingDisplayName: 'Second' });
+
+ const first = await resolveGlobalDisplayName();
+ expect(first).toBe('First');
+
+ // Advance past the 30s TTL
+ vi.setSystemTime(Date.now() + 31_000);
+
+ const second = await resolveGlobalDisplayName();
+ expect(second).toBe('Second');
+ expect(getSettings).toHaveBeenCalledTimes(2);
+ });
+
+ it('invalidateGlobalDisplayNameCache() forces a re-read on next call', async () => {
+ getSettings
+ .mockResolvedValueOnce({ sharingDisplayName: 'BeforeInvalidate' })
+ .mockResolvedValueOnce({ sharingDisplayName: 'AfterInvalidate' });
+
+ const first = await resolveGlobalDisplayName();
+ expect(first).toBe('BeforeInvalidate');
+ expect(getSettings).toHaveBeenCalledTimes(1);
+
+ invalidateGlobalDisplayNameCache();
+
+ const second = await resolveGlobalDisplayName();
+ expect(second).toBe('AfterInvalidate');
+ expect(getSettings).toHaveBeenCalledTimes(2);
+ });
+
+ it('settings:updated event invalidates the cache', async () => {
+ getSettings
+ .mockResolvedValueOnce({ sharingDisplayName: 'BeforeEvent' })
+ .mockResolvedValueOnce({ sharingDisplayName: 'AfterEvent' });
+
+ // First read populates the cache.
+ const first = await resolveGlobalDisplayName();
+ expect(first).toBe('BeforeEvent');
+
+ // Simulate a settings save event — should invalidate the cache.
+ settingsEventEmitter.emit('settings:updated');
+
+ // Next read must go to settings again.
+ const second = await resolveGlobalDisplayName();
+ expect(second).toBe('AfterEvent');
+ expect(getSettings).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not cache when settings read fails (prevents pinning OS fallback)', async () => {
+ // First call: settings unreadable → returns OS username, does NOT cache.
+ getSettings
+ .mockRejectedValueOnce(new Error('disk error'))
+ .mockResolvedValueOnce({ sharingDisplayName: 'Recovered' });
+ osModule.userInfo.mockReturnValue({ username: 'fallback-user' });
+
+ const first = await resolveGlobalDisplayName();
+ expect(first).toBe('fallback-user');
+
+ // Second call: settings now readable → should fetch again (not return cached fallback).
+ const second = await resolveGlobalDisplayName();
+ expect(second).toBe('Recovered');
+ expect(getSettings).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe('annotationIdentity — resolveBucketSourceName', () => {
+ it('returns bucket displayNameOverride when set', async () => {
+ const name = await resolveBucketSourceName({ displayNameOverride: 'BucketAlias' });
+ expect(name).toBe('BucketAlias');
+ expect(getSettings).not.toHaveBeenCalled();
+ });
+
+ it('falls through to global display name when override is absent', async () => {
+ getSettings.mockResolvedValue({ sharingDisplayName: 'Global' });
+ const name = await resolveBucketSourceName({});
+ expect(name).toBe('Global');
+ });
+
+ it('handles a null bucket by falling through to global name', async () => {
+ getSettings.mockResolvedValue({ sharingDisplayName: 'Global' });
+ const name = await resolveBucketSourceName(null);
+ expect(name).toBe('Global');
+ });
+});
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index fd0419352e..820eacef3e 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -13,14 +13,17 @@ import { tmpdir } from 'os';
import { PATHS } from '../../lib/fileUtils.js';
import { RECORD_KIND_SCHEMA_CATEGORIES, PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';
-vi.mock('../instances.js', async () => {
- return {
- UNKNOWN_INSTANCE_ID: 'unknown',
- DEFAULT_SYNC_CATEGORIES: {},
- getInstanceId: vi.fn(),
- getPeers: vi.fn(),
- };
-});
+// instances.js mock: aligns with mockNoPeers() contract (getPeers → [], getInstanceId
+// → 'test-instance' by default) while keeping vi.fn() wrappers so per-test
+// overrides via vi.mocked(getPeers).mockResolvedValue([...]) still work.
+// A plain mockNoPeers() call would return static functions that vi.mocked()
+// cannot spy on — so we construct vi.fn() variants here and match the same defaults.
+vi.mock('../instances.js', () => ({
+ UNKNOWN_INSTANCE_ID: 'unknown',
+ DEFAULT_SYNC_CATEGORIES: {},
+ getInstanceId: vi.fn().mockResolvedValue('test-instance'),
+ getPeers: vi.fn().mockResolvedValue([]),
+}));
vi.mock('../universeBuilder.js', async () => ({
getUniverse: vi.fn(),
diff --git a/server/services/sharing/watcher.js b/server/services/sharing/watcher.js
index 5d33bb30e6..04b16af19e 100644
--- a/server/services/sharing/watcher.js
+++ b/server/services/sharing/watcher.js
@@ -167,3 +167,10 @@ export async function shutdownAllWatchers() {
export function listAttachedWatchers() {
return [...watchers.keys()];
}
+
+/**
+ * Exported for unit testing only — exposes the coalescing queue so the
+ * flood-then-assert pattern can be tested without a real chokidar watcher.
+ * @internal
+ */
+export { queueBacklog as __queueBacklogForTests, backlogQueues as __backlogQueuesForTests };
diff --git a/server/services/sharing/watcher.test.js b/server/services/sharing/watcher.test.js
new file mode 100644
index 0000000000..e5d3571727
--- /dev/null
+++ b/server/services/sharing/watcher.test.js
@@ -0,0 +1,163 @@
+/**
+ * Tests for queueBacklog coalescing in server/services/sharing/watcher.js
+ *
+ * The coalescing contract: a flood of concurrent queueBacklog(bucketId) calls
+ * must collapse to at most one in-flight scan + one queued follow-up. When the
+ * in-flight finishes, the queued run executes. All calls that arrive while a
+ * scan is running share the same queued Promise, so processBacklog is never
+ * called more than twice regardless of flood size.
+ *
+ * Testing strategy: mock importer.processBacklog with a controlled promise so
+ * we can pause and resume the in-flight scan and count calls precisely.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// Mock chokidar so attaching a watcher doesn't require real fs events.
+vi.mock('chokidar', () => ({
+ watch: vi.fn(() => ({
+ on: vi.fn().mockReturnThis(),
+ close: vi.fn().mockResolvedValue(undefined),
+ })),
+}));
+
+// Mock all the collaborators watcher.js pulls in.
+vi.mock('./importer.js', () => ({
+ processManifest: vi.fn().mockResolvedValue(undefined),
+ processBacklog: vi.fn(),
+ handleUnshare: vi.fn().mockResolvedValue(undefined),
+ sharingEvents: { emit: vi.fn(), on: vi.fn() },
+}));
+
+vi.mock('./buckets.js', () => ({
+ getBucket: vi.fn(),
+ listBuckets: vi.fn().mockResolvedValue([]),
+ ensureBucketLayout: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock('./manifest.js', () => ({
+ isManifestPruning: vi.fn().mockReturnValue(false),
+ pruneBucketManifests: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock('../instances.js', () => ({
+ getInstanceId: vi.fn().mockResolvedValue('test-instance'),
+ getPeers: vi.fn().mockResolvedValue([]),
+}));
+
+import { processBacklog } from './importer.js';
+import {
+ __queueBacklogForTests as queueBacklog,
+ __backlogQueuesForTests as backlogQueues,
+} from './watcher.js';
+
+// Helper: create a deferred Promise so we can control when processBacklog resolves.
+function deferred() {
+ let resolve, reject;
+ const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
+ return { promise, resolve, reject };
+}
+
+describe('watcher — queueBacklog coalescing', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Clear any residual queue state from other tests.
+ backlogQueues.clear();
+ });
+
+ afterEach(() => {
+ backlogQueues.clear();
+ });
+
+ it('calls processBacklog once when there is no in-flight scan', async () => {
+ processBacklog.mockResolvedValue(undefined);
+
+ await queueBacklog('bucket-1');
+
+ expect(processBacklog).toHaveBeenCalledTimes(1);
+ expect(processBacklog).toHaveBeenCalledWith('bucket-1');
+ // Queue slot is cleaned up after the run.
+ expect(backlogQueues.has('bucket-1')).toBe(false);
+ });
+
+ it('coalesces a flood of calls to at most two processBacklog invocations', async () => {
+ // First scan is in-flight — hold it with a deferred.
+ const d = deferred();
+ processBacklog.mockReturnValueOnce(d.promise).mockResolvedValue(undefined);
+
+ // Fire the first call (in-flight).
+ const p1 = queueBacklog('bucket-flood');
+ // Fire many more calls while the first scan is still running.
+ const p2 = queueBacklog('bucket-flood');
+ const p3 = queueBacklog('bucket-flood');
+ const p4 = queueBacklog('bucket-flood');
+ const p5 = queueBacklog('bucket-flood');
+
+ // While in-flight, processBacklog should have been called exactly once.
+ expect(processBacklog).toHaveBeenCalledTimes(1);
+
+ // Release the first scan.
+ d.resolve();
+ await Promise.all([p1, p2, p3, p4, p5]);
+
+ // After the in-flight scan completes, exactly one queued follow-up should
+ // have fired — total calls is 2 (in-flight + one queued).
+ expect(processBacklog).toHaveBeenCalledTimes(2);
+ // Queue is fully drained.
+ expect(backlogQueues.has('bucket-flood')).toBe(false);
+ });
+
+ it('all queued calls receive the same Promise (coalescing, not duplication)', async () => {
+ const d = deferred();
+ processBacklog.mockReturnValueOnce(d.promise).mockResolvedValue(undefined);
+
+ // Start first in-flight call.
+ queueBacklog('bucket-coalesce');
+ // All subsequent calls while in-flight must return the SAME Promise.
+ const q1 = queueBacklog('bucket-coalesce');
+ const q2 = queueBacklog('bucket-coalesce');
+ const q3 = queueBacklog('bucket-coalesce');
+
+ // q1, q2, q3 are the queued promises — they must be the same reference.
+ expect(q1).toBe(q2);
+ expect(q2).toBe(q3);
+
+ d.resolve();
+ await Promise.all([q1, q2, q3]);
+ });
+
+ it('uses separate queue slots for different bucket ids', async () => {
+ processBacklog.mockResolvedValue(undefined);
+
+ await Promise.all([
+ queueBacklog('bucket-A'),
+ queueBacklog('bucket-B'),
+ ]);
+
+ // Each bucket is handled independently.
+ expect(processBacklog).toHaveBeenCalledWith('bucket-A');
+ expect(processBacklog).toHaveBeenCalledWith('bucket-B');
+ // Both queue slots are cleaned up.
+ expect(backlogQueues.has('bucket-A')).toBe(false);
+ expect(backlogQueues.has('bucket-B')).toBe(false);
+ });
+
+ it('continues to accept new scans after the queue drains', async () => {
+ processBacklog.mockResolvedValue(undefined);
+
+ await queueBacklog('bucket-seq');
+ expect(processBacklog).toHaveBeenCalledTimes(1);
+ expect(backlogQueues.has('bucket-seq')).toBe(false);
+
+ // A second call after draining should start a fresh in-flight scan.
+ await queueBacklog('bucket-seq');
+ expect(processBacklog).toHaveBeenCalledTimes(2);
+ });
+
+ it('swallows processBacklog errors without unhandled rejection', async () => {
+ processBacklog.mockRejectedValue(new Error('scan failed'));
+
+ // Should not throw — errors are caught inside queueBacklog.
+ await expect(queueBacklog('bucket-err')).resolves.toBeUndefined();
+ expect(backlogQueues.has('bucket-err')).toBe(false);
+ });
+});
diff --git a/server/services/songs.test.js b/server/services/songs.test.js
index 9494da1a60..2407610a94 100644
--- a/server/services/songs.test.js
+++ b/server/services/songs.test.js
@@ -1,5 +1,5 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-import { existsSync, unlinkSync } from 'fs';
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { existsSync, unlinkSync, rmSync } from 'fs';
import { join } from 'path';
// The service captures STATE_PATH at module-load time, so the scratch dir must
@@ -32,17 +32,22 @@ describe('songs service', () => {
if (existsSync(STATE_FILE)) unlinkSync(STATE_FILE);
});
+ afterAll(() => {
+ rmSync(scratch.dir, { recursive: true, force: true });
+ });
+
it('seeds the 500 Miles example on first read and persists it', async () => {
const songs = await svc.listSongs();
expect(songs.length).toBeGreaterThan(0);
- const seed = songs.find((s) => s.title === '500 Miles');
- expect(seed).toBeTruthy();
+ const seed = songs.find((s) => s.id === 'seed-500-miles');
+ expect(seed).not.toBeNull();
+ expect(seed.title).toBe('500 Miles');
expect(seed.artist).toBe('Peter, Paul and Mary');
expect(seed.rhythmShapeId).toBe('slow-4-4');
// Persisted, so a re-read returns the same seed (no re-seed churn).
expect(existsSync(STATE_FILE)).toBe(true);
const again = await svc.listSongs();
- expect(again.find((s) => s.title === '500 Miles')).toBeTruthy();
+ expect(again.find((s) => s.id === 'seed-500-miles')).toBeDefined();
});
it('creates a song with a generated id, newest-first', async () => {
@@ -476,4 +481,10 @@ describe('songs service', () => {
const patched = await svc.updateSong(song.id, { partnerSongIds: [song.id, 'song-other'] });
expect(patched.partnerSongIds).toEqual(['song-other']); // self dropped
});
+
+ it('getSong returns null for a non-existent id', async () => {
+ await svc.listSongs(); // ensure seeded
+ const missing = await svc.getSong('song-does-not-exist-xyz');
+ expect(missing).toBeNull();
+ });
});