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

Merge remote-tracking branch 'origin/main' into claim/issue-2534

[._.]/ Adam Eivyc77286ef4403
diff --cc .changelog/NEXT.md
index 0601d7b40a,ed8e19cf2e..769404e7f8
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@@ -7,7 -14,10 +14,11 @@@
## Changed
- - **[issue-2534] Unify service errors on `ServerError` and delete the duplicated `mapServiceError` copies.** Routes now speak one error model. A single `createServiceErrorMapper(statusMap, buildContext?)` factory in `server/lib/errorHandler.js` replaces the nine near-identical local `mapServiceError` bodies that had accreted across the pipeline / builder / media routers (`pipeline/shared.js`, `storyBuilder.js`, `universeBuilder.js`, `importer.js`, `dashboardLayouts.js`, `conflictJournal.js`, `mediaSketches.js`, `mediaCollections.js`, `mediaAnnotations.js`) — each now just wires its own domain `code → status` map (and optional diagnostic-context builder) through the shared factory. Separately, the CoS agent service functions that returned result-shaped `{ error }` payloads (`getAgentPrompt`, `deleteAgent`, `submitAgentFeedback`, `sendBtwToAgent`) now throw `ServerError` with an explicit `status`/`code`, so `cosAgentRoutes.js` no longer string-matches `result.error === 'Agent not found'` to guess 404-vs-400 — the errors bubble straight to the centralized middleware and every route returns the same `{ error, code, timestamp, context? }` envelope. No client-visible behavior change (the same statuses/codes are preserved). Pure architecture refactor. The ~370-line `dequeueNextTask` scheduler is now a thin orchestrator that threads a shared `ctx` through five `spawnDequeuePriorityN(ctx)` tier helpers (mirroring `evaluateTasks`), with the pure per-cycle capacity tracker (`createDequeueCapacity`) and mission/idle tier-eligibility predicates extracted to a new `server/services/cosDequeue.js` — so the scheduler and its unit tests exercise the *same* guards instead of a local replica. The ~1090-line `cosAgents.js` is split into focused siblings — `cosAgentIndex.js` (date-bucket index / migration / prune / archive layout), `cosAgentLifecycle.js` (register / complete / output / terminate / pause / kill / BTW / zombie cleanup), `cosAgentFeedback.js` (feedback capture + classifier), `cosAgentArchive.js` (state-eviction sweeps) — with `cosAgents.js` kept as a thin barrel so every existing import path is unchanged. Pure mechanical refactor: no behavior change.
++- **[issue-2534] Unify service errors on `ServerError` and delete the duplicated `mapServiceError` copies.** Routes now speak one error model. A single `createServiceErrorMapper(statusMap, buildContext?)` factory in `server/lib/errorHandler.js` replaces the nine near-identical local `mapServiceError` bodies that had accreted across the pipeline / builder / media routers (`pipeline/shared.js`, `storyBuilder.js`, `universeBuilder.js`, `importer.js`, `dashboardLayouts.js`, `conflictJournal.js`, `mediaSketches.js`, `mediaCollections.js`, `mediaAnnotations.js`) — each now just wires its own domain `code → status` map (and optional diagnostic-context builder) through the shared factory. Separately, the CoS agent service functions that returned result-shaped `{ error }` payloads (`getAgentPrompt`, `deleteAgent`, `submitAgentFeedback`, `sendBtwToAgent`) now throw `ServerError` with an explicit `status`/`code`, so `cosAgentRoutes.js` no longer string-matches `result.error === 'Agent not found'` to guess 404-vs-400 — the errors bubble straight to the centralized middleware and every route returns the same `{ error, code, timestamp, context? }` envelope. No client-visible behavior change (the same statuses/codes are preserved). Pure architecture refactor.
+ - **[issue-2591] Responsive City HUD + City settings on the shared Drawer.** The CyberCity HUD now adapts to the viewport instead of stacking every desktop panel on top of the 3D scene at phone width. A new `useCityViewport` hook brackets the window into desktop (≥1024, unchanged cockpit), compact (640–1023) and phone (<640); below desktop the HUD collapses to a small clock/health chip, a status chip and a bottom dock of 44×44 launchers, keeping ≥70% of the scene unobscured on load. Secondary surfaces (vitals, attention, timeline, activity, map, filter, legend) open as ONE mutually-exclusive disclosure sheet driven by a `cityPane` URL param, so only one shows at a time and the open one is deep-linkable, reload-safe and restored by browser back/forward (the desktop Intel pane's active tab reads the same param). City settings moved off the bespoke bottom-right scroller onto the shared tabbed `Drawer` (`size="sm"`, Performance/Audio/Visual/Explore, active tab deep-linked via `useDrawerTab`'s `cityTab` param, `TabPills` mobile dropdown), preserving the `/city/settings` route.
+
+ - **[issue-2550] Add direct unit tests for `telegramClient`, the telegram service, and `errorHandler.asyncHandler`.** Three previously under-covered modules gain colocated `*.test.js` suites, all driven with an injected/mock `fetch` (no network): `server/lib/telegramClient.test.js` now covers the poll loop (getUpdates dispatch to matching/non-matching `onText` + `message`/`callback_query` listeners, offset advance, `stopPolling` abort, and non-ok retry via fake timers) and the `apiCall` methods (`getMe`/`sendMessage` happy path, `reply_markup` string→object parse, non-ok throw); a new `server/services/telegram.test.js` exercises the token-bucket rate limiter (30-message cap then `Rate limit exceeded`) and unauthorized-chat rejection (message/command/callback_query paths) through `init()` with all deps mocked; and `server/lib/errorHandler.test.js` adds `asyncHandler` coverage (thrown ServerError → status+body+emit, plain Error → 500 normalization, success no-op, and the no-io path). Test-only change — no runtime behavior change.
+ - **[issue-2530] Decompose `cos.js` `dequeueNextTask` and split `cosAgents.js` into focused modules.** The ~370-line `dequeueNextTask` scheduler is now a thin orchestrator that threads a shared `ctx` through five `spawnDequeuePriorityN(ctx)` tier helpers (mirroring `evaluateTasks`), with the pure per-cycle capacity tracker (`createDequeueCapacity`) and mission/idle tier-eligibility predicates extracted to a new `server/services/cosDequeue.js` — so the scheduler and its unit tests exercise the *same* guards instead of a local replica. The ~1090-line `cosAgents.js` is split into focused siblings — `cosAgentIndex.js` (date-bucket index / migration / prune / archive layout), `cosAgentLifecycle.js` (register / complete / output / terminate / pause / kill / BTW / zombie cleanup), `cosAgentFeedback.js` (feedback capture + classifier), `cosAgentArchive.js` (state-eviction sweeps) — with `cosAgents.js` kept as a thin barrel so every existing import path is unchanged. Pure mechanical refactor: no behavior change.
- **[issue-2533] Thin the apps-list route and split the imageGen setup routes into their own module.** The `GET /api/apps` handler's ~80 lines of inline PM2 enrichment (one read per `pm2Home`, absent-vs-empty status classification, ecosystem-config process backfill, port derivation) moved into a new `server/services/appListEnrichment.js` (`enrichAppsWithPm2Status(apps)`), so the route just fetches the raw records and responds; the pure port/status helpers (`deriveUiPort`/`deriveAppPorts`/`computeOverallStatus`) live there too and are re-exported from `routes/apps/shared.js` so the detail/lifecycle routes keep one shared implementation. The `/api/image-gen/setup/*` handlers (python probe/venv bootstrap, FLUX.2 install/status, HuggingFace-token store, pip installer) split out of the large `routes/imageGen.js` render router into `routes/imageGenSetup.js`, with the setup-check cache and pip allowlist relocated to `services/imageGen/setup.js`. Pure mechanical refactor — no behavior change.
- **[issue-2531] Split the pipeline `issues.js` and `visualStages.js` monoliths along CRUD/stage/sync seams.** The ~1470-line `server/services/pipeline/issues.js` is now a thin barrel over `issuesShared.js` (store facade + per-series write queue + record sanitizers + `renumberInline`), `issueCrud.js` (create/read/list/update/delete + numbering/reassign), `issueStages.js` (per-stage merge/history/restore), and `issueSync.js` (peer-sync LWW merge + tombstone GC). The ~1760-line `visualStages.js` is now a thin barrel over `visualStageHelpers.js` (shared style/prompt composers + image-gen enqueue plumbing), `covers.js` (comic + volume front/back covers), `comicPages.js` (comic page renders + panel prompt refine), and `storyboards.js` (scene/shot renders + scene refine). Pure mechanical refactor — no behavior change; the single-tail-per-series write serialization (`queueSeriesIssuesWrite`) and the store's `queueTypeIndexWrite` merge snapshot are preserved, and every existing `from './issues.js'` / `from './visualStages.js'` import path still resolves through the barrels.
diff --cc server/lib/errorHandler.test.js
index 6446744b08,cbb21b005e..041b183ff3
--- a/server/lib/errorHandler.test.js
+++ b/server/lib/errorHandler.test.js
@@@ -5,9 -5,23 +5,24 @@@ import
emitErrorEvent,
errorEvents,
errorMiddleware,
- createServiceErrorMapper
++ createServiceErrorMapper,
+ asyncHandler
} from './errorHandler.js';
+ // Build a fake Express req/res pair. `res.status()` and `res.json()` are
+ // chainable (they return `res`) to mirror Express, and `req.app.get('io')`
+ // resolves to whatever io stub the test supplies (or null for the no-io path).
+ function makeReqRes(io) {
+ const res = { status: vi.fn(() => res), json: vi.fn(() => res) };
+ const req = { method: 'GET', originalUrl: '/api/thing', app: { get: vi.fn(() => io) } };
+ return { req, res };
+ }
+
+ // asyncHandler wires the rejection handling onto a `.catch()` microtask and the
+ // returned middleware does not itself return that promise — so flush the
+ // microtask queue before asserting the response/emit happened.
+ const flushMicrotasks = () => new Promise((r) => setImmediate(r));
+
describe('errorHandler.js', () => {
describe('ServerError', () => {
it('should create error with default options', () => {
@@@ -233,44 -247,97 +248,138 @@@
});
});
+ describe('createServiceErrorMapper', () => {
+ const STATUS = { SVC_NOT_FOUND: 404, SVC_VALIDATION: 400 };
+
+ it('maps a recognized code to a ServerError with the mapped status', () => {
+ const map = createServiceErrorMapper(STATUS);
+ const mapped = map(Object.assign(new Error('missing'), { code: 'SVC_NOT_FOUND' }));
+ expect(mapped).toBeInstanceOf(ServerError);
+ expect(mapped.status).toBe(404);
+ expect(mapped.code).toBe('SVC_NOT_FOUND');
+ expect(mapped.message).toBe('missing');
+ });
+
+ it('passes an unrecognized error through untouched', () => {
+ const map = createServiceErrorMapper(STATUS);
+ const original = Object.assign(new Error('boom'), { code: 'SOMETHING_ELSE' });
+ expect(map(original)).toBe(original);
+ });
+
+ it('passes a code-less error through untouched', () => {
+ const map = createServiceErrorMapper(STATUS);
+ const original = new Error('plain');
+ expect(map(original)).toBe(original);
+ });
+
+ it('attaches a non-empty buildContext result as context', () => {
+ const map = createServiceErrorMapper(STATUS, (err) => ({ blockingSeries: err.blockingSeries }));
+ const mapped = map(Object.assign(new Error('busy'), { code: 'SVC_VALIDATION', blockingSeries: ['s1'] }));
+ expect(mapped.context).toEqual({ blockingSeries: ['s1'] });
+ });
+
+ it('omits context when buildContext returns undefined or an empty object', () => {
+ const map = createServiceErrorMapper(STATUS, () => undefined);
+ const mapped = map(Object.assign(new Error('x'), { code: 'SVC_VALIDATION' }));
+ expect(mapped.context).toEqual({});
+
+ const mapEmpty = createServiceErrorMapper(STATUS, () => ({}));
+ const mappedEmpty = mapEmpty(Object.assign(new Error('y'), { code: 'SVC_VALIDATION' }));
+ expect(mappedEmpty.context).toEqual({});
+ });
+ });
++
+ describe('asyncHandler', () => {
+ // `errorEvents` is a Node EventEmitter: emitting 'error' with zero listeners
+ // re-throws the argument (the classic footgun). Production always has
+ // subscribers (autoFixer / socket.js); keep a noop attached so emitErrorEvent
+ // doesn't throw out of asyncHandler's catch during these tests.
+ // Cleanup lives in afterEach (not test bodies) so a failing assertion can't
+ // leak the noop listener, any test-registered listener, or the console.error
+ // spy into sibling tests.
+ let noopErrorListener;
+ let errorSpy;
+ let testListeners;
+ // Register an errorEvents 'error' listener that this describe will remove.
+ const trackListener = (fn) => { testListeners.push(fn); errorEvents.on('error', fn); };
+
+ beforeEach(() => {
+ testListeners = [];
+ noopErrorListener = () => {};
+ errorEvents.on('error', noopErrorListener);
+ errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+ afterEach(() => {
+ errorEvents.off('error', noopErrorListener);
+ for (const fn of testListeners) errorEvents.off('error', fn);
+ errorSpy.mockRestore();
+ });
+
+ it('catches a thrown ServerError, emits, and responds with status + body', async () => {
+ const io = { emit: vi.fn() };
+ const { req, res } = makeReqRes(io);
+ const events = [];
+ trackListener((err, ctx) => events.push({ err, ctx }));
+
+ const handler = asyncHandler(async () => {
+ throw new ServerError('nope', { status: 403, code: 'FORBIDDEN', context: { detail: 'x' } });
+ });
+ await handler(req, res, vi.fn());
+ await flushMicrotasks();
+
+ expect(res.status).toHaveBeenCalledWith(403);
+ const body = res.json.mock.calls[0][0];
+ expect(body.error).toBe('nope');
+ expect(body.code).toBe('FORBIDDEN');
+ expect(body.timestamp).toBeDefined();
+ expect(body.context).toEqual({ detail: 'x' });
+ // Both channels fire: the process-local errorEvents emitter and the io broadcast.
+ expect(events).toHaveLength(1);
+ expect(io.emit).toHaveBeenCalledWith(
+ 'error:occurred',
+ expect.objectContaining({ code: 'FORBIDDEN', status: 403, message: 'nope' })
+ );
+ });
+
+ it('normalizes a plain thrown Error to a 500 INTERNAL_ERROR response', async () => {
+ const io = { emit: vi.fn() };
+ const { req, res } = makeReqRes(io);
+
+ const handler = asyncHandler(async () => {
+ throw new Error('kaboom');
+ });
+ await handler(req, res, vi.fn());
+ await flushMicrotasks();
+
+ expect(res.status).toHaveBeenCalledWith(500);
+ const body = res.json.mock.calls[0][0];
+ expect(body.code).toBe('INTERNAL_ERROR');
+ expect(body.error).toBe('kaboom');
+ });
+
+ it('does not touch res when the wrapped handler resolves successfully', async () => {
+ const { req, res } = makeReqRes({ emit: vi.fn() });
+
+ const handler = asyncHandler(async () => 'ok');
+ await handler(req, res, vi.fn());
+ await flushMicrotasks();
+
+ expect(res.status).not.toHaveBeenCalled();
+ expect(res.json).not.toHaveBeenCalled();
+ });
+
+ it('still responds when no io is registered on the app', async () => {
+ const { req, res } = makeReqRes(null);
+
+ const handler = asyncHandler(async () => {
+ throw new ServerError('missing', { status: 404 });
+ });
+ await handler(req, res, vi.fn());
+ await flushMicrotasks();
+
+ expect(res.status).toHaveBeenCalledWith(404);
+ // status→code derivation still runs even without an io channel.
+ expect(res.json.mock.calls[0][0].code).toBe('NOT_FOUND');
+ });
+ });
});