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

refactor: better-audit residue bundle — formatters, feeds sort, error codes, magic numbers

[._.]/ Adam Eivy21291a0a9acd
diff --git a/DONE.md b/DONE.md
index 7ada8a2cb9..0a36476ac6 100644
--- a/DONE.md
+++ b/DONE.md
@@ -11,6 +11,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
### 2026-05-19
- **[characterdetaileditor-listrow-row-draft-hook] Extract `ListRow`'s multi-column row-draft state into a shared `useRowDraft` hook.** `client/src/components/universe/CharacterDetailEditor.jsx`'s `ListRow` carried 19 lines of inline `useState({})` draft buffer + `draftFor`/`setDraft`/`commit` triple, with the load-bearing sibling-draft "ride-along" merge (`{...row, ...drafts, [col]: v}`) that keeps a fast A-blur → B-blur sequence from losing column A when the parent hasn't re-rendered yet. Lifted into new `client/src/hooks/useRowDraft.js` — the row-level analogue of `useFieldDraft` (single-field draft+blur). Hook signature is `useRowDraft(row, onChange)` returning `{ draftFor, setDraft, commit }`; preserves the ride-along merge verbatim and coerces `null`/`undefined` persisted columns to `''` so inputs stay controlled. `ListRow` collapses to a single hook call. 9 new vitest cases cover persisted/empty fallback, draft buffering without firing onChange, commit no-op when value equals persisted, commit no-op when no draft set, null-as-empty equivalence, the ride-along race-protection invariant (committing column B with a pending column-A draft ships both in one onChange), and that commit clears only the committed column from the drafts map. All 112 client tests pass.
+- **Better-audit residue refactor bundle.** Shipped four PLAN.md items from the Better-audit residue section as one PR — three landed as scoped fixes, one was rescoped after the underlying premise eroded. (1) `[medium-client-4-components-still-redefine]` — added `formatTimecode` (M:SS.ss for video timecodes), `formatDurationSec` (M:SS for seconds, `'—'` fallback), and `formatDateShort` (short-month date, `'—'` fallback) to `client/src/utils/formatters.js`; migrated `VideoTimelineEditor.jsx`, `VideoTimeline.jsx`, and `ImportTab.jsx` off their local re-definitions. `MortalLoomTab.jsx` (also named in PLAN) already imported `formatBytes` from the shared module, so no change there. (2) `[medium-perf-feeds-js-getitems-303-319-full-sort]` — `server/services/feeds.js` now maintains the newest-first sort invariant on writes (`addFeed`, `refreshFeed`, `applyParsedFeed` end-of-batch in `refreshAllFeeds`); `getItems` drops the per-call sort. New `ensureItemsSorted()` runs once on first read after server boot to normalize legacy disk data, with an `isSortedNewestFirst()` guard so an already-sorted file isn't re-saved on every restart. (3) `[medium-code-magic-numbers-in-cos-js-166-357]` — replaced the brittle `err.message.startsWith('unknown piper voice:')` check in `routes/voice.js` and the `err.message.includes('not initialized')` check in `services/visionTest.js` with typed error codes. `services/voice/tts.js` now throws `new ServerError(\`unknown piper voice: …\`, { status: 400, code: 'UNKNOWN_VOICE' })`; `services/providers.js` consolidated its nine `if (!aiToolkitInstance) throw new Error(…)` duplicates into a single `requireToolkit()` helper that throws `new ServerError('AI Toolkit not initialized', { status: 503, code: 'AI_TOOLKIT_NOT_INITIALIZED' })`. Both new ServerErrors bubble through `asyncHandler` automatically — the voice.js try/catch around `synthesize` dropped entirely (~10 LOC + 1 narrative comment). visionTest.js's error path now surfaces a more accurate "AI provider service is still initializing" message when the toolkit isn't warmed (previously it masqueraded as "provider not found", sending the user looking for the wrong root cause). Named time constants extracted in `cos.js` (`CD_RECOVERY_BOOT_TIMEOUT_MS = 60_000`, `POST_STARTUP_QUEUE_DELAY_MS = 30_000`, `RECENT_COMPLETION_GRACE_MS = 60_000`) and `lmStudioManager.js` (`DEFAULT_REQUEST_TIMEOUT_MS = 30_000`, `AVAILABILITY_PROBE_TIMEOUT_MS = 5_000`). (4) `[low-client-extract-shared-usepopoverposition-hook]` — **skipped, premise eroded.** The original PLAN flagged 4 components (`AddToCollectionMenu`, `BulkTargetPicker`, `ThemeSwitcher`, `VisualStylePicker`) but `VisualStylePicker` no longer exists in the codebase and `AddToCollectionMenu`/`BulkTargetPicker` no longer use the portal-positioning pattern. Today only `ThemeSwitcher` and `CollectionPickerShell` match the shape; the abstraction isn't worth the indirection at 2 callers. PLAN.md entry rewritten to reflect current state — extract when a 3rd caller lands. Updated `voice.test.js` to mock `ServerError` directly (drops the legacy back-compat test, asserts `code: 'UNKNOWN_VOICE'` on the body); loosened `visionTest.integration.test.js`'s "non-existent provider" assertion to accept either the "not found" branch (toolkit warmed) or "still initializing" branch (toolkit not yet wired in the test context). One `/simplify` follow-up deferred to PLAN.md as `[extract-requiretoolkit-pattern-to-runner-js]` — `runner.js` has 13 more sites of the same inlined `if (!aiToolkitInstance)` check that should adopt the new `requireToolkit()` helper. All 5703 server tests + 103 client tests pass.
- **[clear-pending-sheet-slot-on-entry-delete] Prune `_latestPendingByCharacter` on character / universe delete.** The in-process slot map that supersede-checks character reference-sheet renders previously persisted entries for the full Node process lifetime — even after the character or its universe was deleted. Extracted the Map + its `claim`/`get`/`release` helpers into `server/services/universeCharacterSheetSlot.js` (standalone module so `universeBuilder.js` can clear slots without a `universeCharacterSheet.js → universeBuilder.js` import cycle) and added two delete-path helpers: `clearPendingSheetSlot(universeId, entryId)` (unconditional single-character drop) and `clearPendingSheetSlotsForUniverse(universeId)` (walks the map once, drops every `${universeId}:` prefix). `universeCharacterSheet.js` now consumes `claimPendingSheetSlot` / `getPendingSheetSlot` / `releasePendingSheetSlot` instead of inline `_latestPendingByCharacter.set/.get/.delete` — behavior is unchanged, the supersede-aware contract still holds. Wired into two paths: (a) `deleteUniverse` calls `clearPendingSheetSlotsForUniverse(id)` after the file-write queue releases, alongside the existing `unlinkCollectionsForUniverse` cascade; (b) `updateUniverse` computes a `prevIds`/`nextIds` diff against `cur.characters` vs `mergedRecord.characters` INSIDE the write queue (so the diff sees the freshest persisted state) and calls `clearPendingSheetSlot(id, removedId)` for each dropped id after the queue returns. The in-flight render path is unaffected — if a render's character is deleted mid-flight the slot becomes empty, `onSheetComplete` treats itself as superseded, saves the file on disk, and skips stamping a now-orphaned `referenceSheetImageRef` pointer (the `updateUniverse` mutator inside `onSheetComplete` is also a no-op since the character record is gone). Coverage: 11 new tests in `universeCharacterSheetSlot.test.js` covering claim/get/release contracts, unconditional vs conditional drop, prefix-anchored universe sweep (with explicit anti-collision case proving `u-a` doesn't match `u-ab`), falsy-id no-ops; 3 new integration tests in `universeBuilder.test.js#"pending sheet slot cleanup"` covering character-drop via PATCH, character-preserve when the patch keeps them, and universe-delete clearing only that universe's slots. All 5703 server tests + 14 reused `universeCharacterSheet.test.js` cases pass.
- **[purge-reference-sheet-image-ref-on-sheet-delete] Active-purge `character.referenceSheetImageRef` on sheet delete.** Shipped both the sheet-delete route the original PLAN entry was gated on AND the eager purge it needed. New `purgeReferenceSheetFromAllUniverses(filename)` helper in `server/services/universeCanon.js` mirrors `purgeImageRefFromAllUniverses` but targets the single-string sheet pointer; uses `updateUniverse`'s mutator form because `referenceSheetImageRef` is in `SERVER_OWNED_CHARACTER_FIELDS` and a literal-object PATCH would be guarded against clobbering the pointer. New `deleteCharacterReferenceSheet(universeId, entryId)` in `server/services/universeCharacterSheet.js` reads the character's current pointer, re-validates via `assertSafeFilename` as defense-in-depth, unlinks the PNG from `PATHS.imageRefs` (ENOENT is benign — surfaced via `fileDeleted: false`), then calls the purge to clear every matching pointer across all universes. Mirrors the renderer's lock guard (`UNIVERSE_CANON_LOCKED` 409) so locked characters' sheets stay delete-protected. New `DELETE /api/universe-builder/:id/characters/:entryId/reference-sheet` route. Client: `deleteCharacterReferenceSheet` helper in `apiUniverseBuilder.js` (silent option), trash button in `CharacterReferenceSheetPanel.jsx` (only rendered when a sheet exists + not in-flight) with inline `[Cancel] [Delete sheet]` confirm row per the user's confirmation-UX preference, `onSheetDeleted` callback wired through `characterExtensions` in `CanonCard.jsx` → `UniverseCanonSection.jsx` (`handleSheetDeleted` mirrors `handleSheetCompleted`'s `latestUniverseRef` read so a parallel edit during the DELETE isn't clobbered). Coverage: 3 new tests in `universeCanon.test.js` for `purgeReferenceSheetFromAllUniverses` + 2 backfill tests for the previously-untested `purgeImageRefFromAllUniverses`; new `universeCharacterSheetDelete.test.js` with 8 tests covering happy path, ENOENT benign, non-ENOENT propagation, no-pointer no-op, 404 character, 409 locked, traversal-rejection, and cross-universe purge. All 5710 server tests + 103 client tests pass; client build clean.
- **[per-field-locks-arc-and-stage-granularity] Per-field arc locks + per-stage issue locks.** Follow-on to per-season locks (`[per-season-and-per-field-locks-extend-arc-lock]`). Two layered ratchets, both enforced server-side and surfaced in the UI. (1) **Per-field arc locks** — `series.locked.arcFields` carries an opt-in sub-map (`{ logline, summary, themes, protagonistArc, shape }`); new `mergeArcWithLocks(currentArc, nextArc, lockedFields)` helper in `arcPlanner.js` rewrites the incoming arc to preserve locked field values verbatim from the existing arc, called from `commitSeasonsWithRemap` so both auto-resolve (via `resolveVerifyIssues`) and the `/series/:id/arc/generate?commit=true` path honor the lock; new `ARC_LOCKABLE_FIELDS = ['logline','summary','protagonistArc','themes','shape']` export in `pipeline/series.js` is mirrored as the Zod schema in `seriesLockedSchema`. Arc Canvas read view now renders a small `FieldLockToggle` icon (subtle 4×4 inline button, Lock/Unlock-with-spinner) next to each field that's currently displayed — logline paragraph, story-shape badge, themes chip row, summary `<summary>`, protagonistArc `<summary>` — toggling PATCHes through `updatePipelineSeries({ locked: { ...series.locked, arcFields: nextFields } })` with optimistic update + toast. (2) **Per-stage issue locks** — every `issue.stages.{id}` (text + visual + audio) carries `locked: boolean` (default `false`, strict-true coercion so `locked: 'yes'` typos can't accidentally freeze the stage). New `assertStageUnlocked(issue, stageId)` helper in `pipeline/issues.js` throws `ServerError({ status: 400, code: 'PIPELINE_STAGE_LOCKED' })` and is called from every regeneration entry point: `textStages.generateStage`, `visualStages.enqueueComicCoverLike` / `enqueueVisualComicPage` / `enqueueVisualImage` / `enqueueStoryboardSceneVideo` / `enqueueStoryboardShotStartFrame` / `refineComicPanelPrompt` / `refineStoryboardScenePrompt`, `episodeVideo.startEpisodeVideoForIssue` (fresh-start branch only; reuse of existing `cdProjectId` is still permitted), `arcPlanner.generateComicCoverConcepts` (`commit: true` path), and the four route-level audio/extract paths (`/audio/extract-lines`, `/audio/lines/:n/render`, `/storyboards/extract-scenes`, `/comicPages/extract-pages`). The text-stage gate runs *before* `updateStage({ status: 'generating' })` so a locked stage doesn't get stuck at "generating" only to be reset. `PipelineIssue.jsx` (a) gates the per-tab `<Lock>` indicator on per-stage `locked` first (then falls back to the ambient arc/season-wide lock); (b) adds a Lock/Unlock toggle button to the action bar that targets the currently-active stage and PATCHes `{ stages: { [stageId]: { locked: next } } }` via `updatePipelineIssue`; (c) the lock-banner under the TabPills strip prefers the per-stage message when the active tab is locked. Coverage: 11 new tests — 4 in `issues.test.js` (default `locked: false` on every stage, PATCH round-trip, non-boolean coerce-to-false, `assertStageUnlocked` throw/no-op), 1 in `textStages.test.js` (refuse + leave status untouched on locked stage), 6 in `arcPlanner.test.js` (`mergeArcWithLocks` per-field preservation, empty/null/undefined locks pass through, no-current-arc passthrough, null/undefined next no-op, unknown lock keys ignored, full `commitSeasonsWithRemap` round-trip with locked logline + themes). All 5689 server tests + 103 client tests pass.
diff --git a/PLAN.md b/PLAN.md
index f7502e337c..d29a0dc31d 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -126,10 +126,8 @@ _Nothing currently parked — pick the next item from the Backlog._
- [x] [high-code-server-services-cos-js-3113-remove-node] ~~**[HIGH][CODE]** `server/services/cos.js:3113` — remove `NODE_ENV !== 'test' && VITEST !== 'true'` init guard (test hack in prod boot path).~~ **Shipped 2026-05-17** — `init()` is now exported and called explicitly from `server/index.js` (alongside the other `*.init()` calls); module-level auto-init removed entirely so the test guard is no longer needed.
- [ ] [high-tests-create-test-files-for-server-services] **[HIGH][TESTS]** Create test files for `server/services/clinvar.js` and `server/services/telegramBridge.js`.
- [ ] [high-tests-add-coverage-for-server-services-shell] **[HIGH][TESTS]** Add coverage for `server/services/shell.js` and `server/services/feeds.js` — both have exported functions but no sibling test. Shell drives all terminal sessions; feeds manages subscriptions. (New — surfaced 2026-05-16 replan.)
-- [ ] [medium-client-4-components-still-redefine] **[MEDIUM][CLIENT]** 4 components still redefine `formatBytes`/`formatTime`/`formatDuration`/`timeAgo`/`formatDate` locally: `VideoTimelineEditor.jsx`, `VideoTimeline.jsx`, `MortalLoomTab.jsx`, `ImportTab.jsx`.
-- [ ] [medium-perf-feeds-js-getitems-303-319-full-sort] **[MEDIUM][PERF]** `feeds.js#getItems` (303–319) — full-sort-then-paginate on every request. Pre-sort once at write time or maintain a per-feed index.
-- [ ] [medium-code-magic-numbers-in-cos-js-166-357] **[MEDIUM][CODE]** Magic numbers in `cos.js:166,357`, `lmStudioManager.js:66`; brittle `err.message.startsWith('unknown piper voice:')` in `routes/voice.js:160` and `err.message.includes('not initialized')` in `services/visionTest.js:124`.
-- [ ] [low-client-extract-shared-usepopoverposition-hook] **[LOW][CLIENT]** Extract shared `usePopoverPosition` hook — portal-with-fixed-positioning duplicated across 4 components (`AddToCollectionMenu`, `BulkTargetPicker`, `ThemeSwitcher`, `VisualStylePicker`) with near-identical rAF-coalesced scroll/resize listeners + `useLayoutEffect` measurement.
+- [ ] [low-client-extract-shared-usepopoverposition-hook] **[LOW][CLIENT]** Extract shared `usePopoverPosition` hook — **premise eroded; revisit when a 3rd caller lands.** Original PLAN flagged 4 components but `VisualStylePicker` no longer exists and `AddToCollectionMenu` / `BulkTargetPicker` no longer use portal positioning. Today the pattern lives in exactly two components (`client/src/components/ThemeSwitcher.jsx` and `client/src/components/media/CollectionPickerShell.jsx`) — both implement portal-with-fixed-positioning + `useLayoutEffect` measurement + rAF-coalesced scroll/resize listeners. With only 2 callers the abstraction isn't worth the indirection; extract when a third surface needs the same shape.
+- [ ] [extract-requiretoolkit-pattern-to-runner-js] **[MEDIUM][CODE]** Extend the `requireToolkit()` pattern from `server/services/providers.js` to `server/services/runner.js` — 13 sites of `if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized')` still inlined there (lines 27, 144, 218, 332, 343 + others). Surfaced by /simplify during the better-audit residue refactor bundle; left out of that PR to keep scope tight. Should reuse the same `ServerError({ status: 503, code: 'AI_TOOLKIT_NOT_INITIALIZED' })` shape providers.js now throws.
### Pipeline — deferred
diff --git a/client/src/components/brain/tabs/ImportTab.jsx b/client/src/components/brain/tabs/ImportTab.jsx
index 1ebf5060da..352c9f8d64 100644
--- a/client/src/components/brain/tabs/ImportTab.jsx
+++ b/client/src/components/brain/tabs/ImportTab.jsx
@@ -13,7 +13,7 @@ import {Upload,
import * as api from '../../../services/api';
import toast from '../../ui/Toast';
import BrailleSpinner from '../../BrailleSpinner';
-import { formatBytes } from '../../../utils/formatters';
+import { formatBytes, formatDateShort } from '../../../utils/formatters';
// Sources we plan to support. Only `available` ones are clickable.
const SOURCES = [
@@ -53,13 +53,6 @@ const STEPS = [
{ id: 'done', label: 'Done' }
];
-const formatDate = (iso) => {
- if (!iso) return '—';
- const d = new Date(iso);
- if (Number.isNaN(d.getTime())) return '—';
- return d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
-};
-
export default function ImportTab() {
const navigate = useNavigate();
const [source, setSource] = useState(null);
@@ -428,8 +421,8 @@ function StepPreview({ preview, fileMeta, onNext, onBack }) {
<Stat label="Messages" value={summary.totalMessages.toLocaleString()} />
<Stat label="Total chars" value={summary.totalChars.toLocaleString()} />
<Stat label="Custom GPTs" value={summary.gizmoCount.toString()} />
- <Stat label="Earliest" value={formatDate(summary.earliest)} />
- <Stat label="Latest" value={formatDate(summary.latest)} />
+ <Stat label="Earliest" value={formatDateShort(summary.earliest)} />
+ <Stat label="Latest" value={formatDateShort(summary.latest)} />
</div>
<div className="border border-port-border rounded">
@@ -441,7 +434,7 @@ function StepPreview({ preview, fileMeta, onNext, onBack }) {
<li key={c.id || c.title} className="px-3 py-2 flex items-center justify-between gap-2">
<span className="text-sm text-white truncate">{c.title}</span>
<span className="text-xs text-gray-500 flex-shrink-0">
- {c.messageCount} msg · {formatDate(c.createTime)}
+ {c.messageCount} msg · {formatDateShort(c.createTime)}
</span>
</li>
))}
diff --git a/client/src/hooks/useRowDraft.test.js b/client/src/hooks/useRowDraft.test.jsx
similarity index 100%
rename from client/src/hooks/useRowDraft.test.js
rename to client/src/hooks/useRowDraft.test.jsx
diff --git a/client/src/pages/VideoTimeline.jsx b/client/src/pages/VideoTimeline.jsx
index a6545c2751..e3ed53b464 100644
--- a/client/src/pages/VideoTimeline.jsx
+++ b/client/src/pages/VideoTimeline.jsx
@@ -3,13 +3,7 @@ import { useNavigate } from 'react-router-dom';
import { Plus, Film, Trash2, Clock } from 'lucide-react';
import toast from '../components/ui/Toast';
import * as api from '../services/api';
-
-const formatDuration = (sec) => {
- if (!sec || !Number.isFinite(sec)) return '—';
- const m = Math.floor(sec / 60);
- const s = Math.floor(sec % 60);
- return `${m}:${String(s).padStart(2, '0')}`;
-};
+import { formatDurationSec } from '../utils/formatters';
export default function VideoTimeline() {
const navigate = useNavigate();
@@ -142,7 +136,7 @@ export default function VideoTimeline() {
</div>
<div className="flex items-center gap-3 text-xs text-gray-400">
<span className="flex items-center gap-1"><Film className="w-3 h-3" />{(project.clips || []).length} clips</span>
- <span className="flex items-center gap-1"><Clock className="w-3 h-3" />{formatDuration(totalSec)}</span>
+ <span className="flex items-center gap-1"><Clock className="w-3 h-3" />{formatDurationSec(totalSec)}</span>
</div>
</div>
</div>
diff --git a/client/src/pages/VideoTimelineEditor.jsx b/client/src/pages/VideoTimelineEditor.jsx
index ecf597aede..29843ce141 100644
--- a/client/src/pages/VideoTimelineEditor.jsx
+++ b/client/src/pages/VideoTimelineEditor.jsx
@@ -19,6 +19,7 @@ import {
} from 'lucide-react';
import toast from '../components/ui/Toast';
import * as api from '../services/api';
+import { formatTimecode } from '../utils/formatters';
// Map project-time t (every clip contributes its trimmed duration) to the
// (clipIndex, withinClipSec) pair the preview <video> element needs. The
@@ -38,13 +39,6 @@ const findClipAt = (clips, t) => {
const totalDuration = (clips) => clips.reduce((s, c) => s + Math.max(0, c.outSec - c.inSec), 0);
-const formatTime = (sec) => {
- if (!Number.isFinite(sec) || sec < 0) return '0:00.00';
- const m = Math.floor(sec / 60);
- const s = sec - m * 60;
- return `${m}:${s.toFixed(2).padStart(5, '0')}`;
-};
-
// Draggable+sortable timeline block. Snaps the trimmed duration to a width
// derived from `pxPerSec` so longer clips visibly take more horizontal space.
function TimelineBlock({ clip, clipMeta, isSelected, isMissing, pxPerSec, onSelect, onRemove }) {
@@ -506,7 +500,7 @@ export default function VideoTimelineEditor() {
}}
className="bg-transparent text-white font-medium text-lg focus:outline-none focus:bg-port-card focus:px-2 rounded transition-all"
/>
- <span className="text-xs text-gray-500">{clips.length} clips · {formatTime(total)}</span>
+ <span className="text-xs text-gray-500">{clips.length} clips · {formatTimecode(total)}</span>
</div>
<div className="flex items-center gap-2">
<button
@@ -592,7 +586,7 @@ export default function VideoTimelineEditor() {
disabled={clips.length === 0}
/>
<span className="font-mono text-[11px] tabular-nums">
- {formatTime(t)} / {formatTime(total)}
+ {formatTimecode(t)} / {formatTimecode(total)}
</span>
<label className="flex items-center gap-1 ml-2">
<span>zoom</span>
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index 6be950c7d9..644030edb3 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -147,6 +147,40 @@ export function formatDateTime(value) {
return _dateTimeFormatter.format(date);
}
+/**
+ * Format a number of seconds as M:SS (e.g. 75 → "1:15"). For coarse durations
+ * like a stitched video's runtime. Returns `'—'` for missing/invalid input.
+ */
+export function formatDurationSec(seconds) {
+ if (!seconds || !Number.isFinite(seconds)) return '—';
+ const m = Math.floor(seconds / 60);
+ const s = Math.floor(seconds % 60);
+ return `${m}:${String(s).padStart(2, '0')}`;
+}
+
+/**
+ * Format a number of seconds as M:SS.ss for video-editor timecodes
+ * (e.g. 95.42 → "1:35.42"). Negative or non-finite inputs render as "0:00.00".
+ */
+export function formatTimecode(seconds) {
+ if (!Number.isFinite(seconds) || seconds < 0) return '0:00.00';
+ const m = Math.floor(seconds / 60);
+ const s = seconds - m * 60;
+ return `${m}:${s.toFixed(2).padStart(5, '0')}`;
+}
+
+/**
+ * Format a date with a short month label (e.g., "Mar 5, 2026"). Returns
+ * `'—'` for missing/invalid input — pair with `formatDate` (long month, null
+ * fallback) depending on the surrounding UI.
+ */
+export function formatDateShort(value) {
+ if (!value) return '—';
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) return '—';
+ return date.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
+}
+
/**
* Format a duration in milliseconds as a human-readable string
* @param {number} ms - Duration in milliseconds
diff --git a/server/routes/voice.js b/server/routes/voice.js
index a038183964..b6c13ddd0a 100644
--- a/server/routes/voice.js
+++ b/server/routes/voice.js
@@ -163,19 +163,10 @@ router.post('/test', asyncHandler(async (req, res) => {
}
const voice = (req.body?.voice || '').toString().trim() || undefined;
const engine = validEngine((req.body?.engine || '').toString().trim());
- // synthesize() throws "unknown piper voice: X" when a client supplies a
- // voice id that isn't in the curated catalog — that's user input, not a
- // server failure, so map to 400 instead of asyncHandler's default 500.
- let wav; let latencyMs;
- try {
- ({ wav, latencyMs } = await synthesize(text, { voice, engine }));
- } catch (err) {
- // String check couples to synthesize() internals; also accept err.code for future typed errors
- if (err?.code === 'UNKNOWN_VOICE' || err?.message?.startsWith('unknown piper voice:')) {
- return res.status(400).json({ error: err.message });
- }
- throw err;
- }
+ // synthesize() throws a ServerError(`status: 400, code: 'UNKNOWN_VOICE'`)
+ // when the client supplies a voice id that isn't in the curated catalog;
+ // asyncHandler maps the ServerError status, so no inline try/catch needed.
+ const { wav, latencyMs } = await synthesize(text, { voice, engine });
res.setHeader('Content-Type', 'audio/wav');
res.setHeader('X-TTS-Latency-Ms', String(latencyMs));
res.send(wav);
diff --git a/server/routes/voice.test.js b/server/routes/voice.test.js
index da269f6b60..91a66d8965 100644
--- a/server/routes/voice.test.js
+++ b/server/routes/voice.test.js
@@ -38,6 +38,7 @@ import * as config from '../services/voice/config.js';
import * as health from '../services/voice/health.js';
import * as bootstrap from '../services/voice/bootstrap.js';
import * as tts from '../services/voice/tts.js';
+import { ServerError } from '../lib/errorHandler.js';
import * as piperVoices from '../services/voice/piper-voices.js';
import * as proactiveSpeech from '../services/voice/proactiveSpeech.js';
import voiceRoutes from './voice.js';
@@ -210,23 +211,25 @@ describe('Voice Routes', () => {
expect(res.headers['x-tts-latency-ms']).toBe('123');
});
- it('maps err.code === "UNKNOWN_VOICE" from synthesize() to a 400 response', async () => {
- const err = Object.assign(new Error('voice id not in catalog'), { code: 'UNKNOWN_VOICE' });
- tts.synthesize.mockRejectedValue(err);
+ it('maps ServerError UNKNOWN_VOICE from synthesize() to a 400 response', async () => {
+ tts.synthesize.mockRejectedValue(new ServerError('voice id not in catalog', {
+ status: 400,
+ code: 'UNKNOWN_VOICE',
+ }));
const res = await request(buildApp())
.post('/api/voice/test')
.send({ text: 'hello', voice: 'nonexistent', engine: 'piper' });
expect(res.status).toBe(400);
expect(res.body.error).toBe('voice id not in catalog');
+ expect(res.body.code).toBe('UNKNOWN_VOICE');
});
- it('still maps the legacy "unknown piper voice:" message to 400 (back-compat)', async () => {
- tts.synthesize.mockRejectedValue(new Error('unknown piper voice: nonexistent'));
+ it('lets unrelated synth errors bubble to asyncHandler (500)', async () => {
+ tts.synthesize.mockRejectedValue(new Error('synth crashed'));
const res = await request(buildApp())
.post('/api/voice/test')
- .send({ text: 'hello', voice: 'nonexistent', engine: 'piper' });
- expect(res.status).toBe(400);
- expect(res.body.error).toMatch(/unknown piper voice/);
+ .send({ text: 'hello', voice: 'whatever', engine: 'piper' });
+ expect(res.status).toBe(500);
});
});
diff --git a/server/services/cos.js b/server/services/cos.js
index 4de133aed0..fc7de197c3 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -51,6 +51,15 @@ export { generateReport, getReport, getTodayReport, listReports, listBriefings,
const AGENT_ARCHIVE_RETENTION_DAYS = 90;
const RESUME_DEQUEUE_DELAY_MS = 500;
+// CD recovery normally resolves in <100ms; hold start() at most this long so
+// a stuck recovery doesn't block daemon boot indefinitely.
+const CD_RECOVERY_BOOT_TIMEOUT_MS = 60_000;
+// Initial idle-review queue kicks off after start() — far enough back that
+// a fresh install isn't overwhelmed but close enough to not stall users.
+const POST_STARTUP_QUEUE_DELAY_MS = 30_000;
+// A task whose agent reported completed within this window is treated as
+// "recently completed" and protected from resetOrphanedTasks's reaper.
+const RECENT_COMPLETION_GRACE_MS = 60_000;
// First non-empty line of a string. Used by addTask dedup: stored descriptions
// are flattened to a single line by generateTasksMarkdown, so the comparison
@@ -218,7 +227,7 @@ export async function start() {
const { cdRecoveryDone } = await import('./creativeDirector/recovery.js');
await Promise.race([
cdRecoveryDone,
- new Promise((resolve) => setTimeout(resolve, 60000)),
+ new Promise((resolve) => setTimeout(resolve, CD_RECOVERY_BOOT_TIMEOUT_MS)),
]);
// Then reset any orphaned in_progress tasks (no running agent)
@@ -359,7 +368,7 @@ export async function start() {
await queueEligibleImprovementTasks(state, cosTaskData);
setImmediate(() => dequeueNextTask());
}).catch(err => emitLog('warn', `Post-startup improvement queuing failed: ${err.message}`));
- }, 30000);
+ }, POST_STARTUP_QUEUE_DELAY_MS);
return { success: true };
}
@@ -562,7 +571,7 @@ async function resetOrphanedTasks() {
const recentlyCompletedTaskIds = new Set(
Object.values(state.agents)
.filter(a => a.status === 'completed' && a.completedAt &&
- (Date.now() - new Date(a.completedAt).getTime()) < 60000)
+ (Date.now() - new Date(a.completedAt).getTime()) < RECENT_COMPLETION_GRACE_MS)
.map(a => a.taskId)
);
diff --git a/server/services/feeds.js b/server/services/feeds.js
index e6e8c7b4e0..1a549fe499 100644
--- a/server/services/feeds.js
+++ b/server/services/feeds.js
@@ -22,6 +22,39 @@ const FETCH_TIMEOUT_MS = 15000;
const DEFAULT_DATA = { feeds: [], items: [] };
const store = createCachedStore(FEEDS_FILE, DEFAULT_DATA, { context: 'feeds' });
+// Compare items newest-first by pubDate (or fetchedAt fallback). Both writes
+// and the legacy normalization pass use this so getItems can skip the sort.
+const itemSortKey = (item) => Date.parse(item.pubDate || item.fetchedAt) || 0;
+const compareItemsNewestFirst = (a, b) => itemSortKey(b) - itemSortKey(a);
+
+// Sort runs on writes only; getItems trusts the invariant. Legacy unsorted
+// state on disk gets normalized once on first read (see ensureItemsSorted).
+// The invariant assumes this module owns all writes to feeds.json — out-of-band
+// edits while the process is running won't retrigger normalization.
+let _itemsSorted = false;
+const sortItemsNewestFirst = (items) => {
+ items.sort(compareItemsNewestFirst);
+ _itemsSorted = true;
+};
+
+const isSortedNewestFirst = (items) => {
+ for (let i = 1; i < items.length; i++) {
+ if (compareItemsNewestFirst(items[i - 1], items[i]) > 0) return false;
+ }
+ return true;
+};
+
+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;
+ }
+}
+
// ─── RSS/Atom Parser ────────────────────────────────────────────────────────
/**
@@ -152,6 +185,7 @@ export async function addFeed(url) {
fetchedAt: new Date().toISOString()
}));
data.items.push(...newItems);
+ sortItemsNewestFirst(data.items);
await store.save(data);
console.log(`📡 Feed added: ${feed.title} (${newItems.length} items)`);
@@ -215,6 +249,7 @@ export async function refreshFeed(id) {
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)`);
@@ -267,6 +302,9 @@ function applyParsedFeed(data, feed, parsed) {
return newItems.length;
}
+// refreshAllFeeds defers sort to a single end-of-batch pass — applyParsedFeed
+// 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 CONCURRENCY = 5;
@@ -295,25 +333,20 @@ export async function refreshAllFeeds() {
}
}
+ 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 };
}
export async function getItems({ feedId, unreadOnly, limit, offset = 0 } = {}) {
+ await ensureItemsSorted();
const data = await store.load();
let items = data.items;
if (feedId) items = items.filter(i => i.feedId === feedId);
if (unreadOnly) items = items.filter(i => !i.read);
- // Sort newest first by pubDate or fetchedAt
- items.sort((a, b) => {
- const da = new Date(a.pubDate || a.fetchedAt);
- const db = new Date(b.pubDate || b.fetchedAt);
- return db - da;
- });
-
if (limit != null) return items.slice(offset, offset + limit);
return items.slice(offset);
}
diff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.js
index c5f737dab0..fe815e4fdf 100644
--- a/server/services/lmStudioManager.js
+++ b/server/services/lmStudioManager.js
@@ -9,11 +9,15 @@ import { cosEvents } from './cosEvents.js'
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'
const AVAILABILITY_CACHE_TTL_MS = 30_000
+const DEFAULT_REQUEST_TIMEOUT_MS = 30_000
+// Availability probe is short — if the local server is down we'd rather fail
+// fast and degrade to "no LM Studio" than block 30s on every cold check.
+const AVAILABILITY_PROBE_TIMEOUT_MS = 5_000
// Default LM Studio configuration
const DEFAULT_CONFIG = {
baseUrl: (process.env.LM_STUDIO_URL || 'http://localhost:1234').replace(/\/+$/, '').replace(/\/v1$/, ''),
- timeout: 30000,
+ timeout: DEFAULT_REQUEST_TIMEOUT_MS,
defaultThinkingModel: 'gpt-oss-20b'
}
@@ -69,7 +73,7 @@ async function checkLMStudioAvailable() {
}
try {
- await lmStudioRequest('/v1/models', { timeout: 5000 })
+ await lmStudioRequest('/v1/models', { timeout: AVAILABILITY_PROBE_TIMEOUT_MS })
isAvailable = true
status.lastSuccessAt = now
status.consecutiveErrors = 0
diff --git a/server/services/providers.js b/server/services/providers.js
index 87df09926a..0fa721f73e 100644
--- a/server/services/providers.js
+++ b/server/services/providers.js
@@ -3,6 +3,8 @@
* Re-exports toolkit provider service functions
*/
+import { ServerError } from '../lib/errorHandler.js';
+
// This will be initialized by server/index.js and set via setAIToolkit()
let aiToolkitInstance = null;
@@ -10,47 +12,50 @@ export function setAIToolkit(toolkit) {
aiToolkitInstance = toolkit;
}
+// Centralized typed-error so callers can gate on `err.code === 'AI_TOOLKIT_NOT_INITIALIZED'`
+// instead of string-matching the message; status 503 (service-unavailable)
+// because the toolkit warms at boot and a not-initialized state means the
+// service hasn't finished starting.
+function requireToolkit() {
+ if (aiToolkitInstance) return aiToolkitInstance;
+ throw new ServerError('AI Toolkit not initialized', {
+ status: 503,
+ code: 'AI_TOOLKIT_NOT_INITIALIZED',
+ });
+}
+
export async function getAllProviders() {
- if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized');
- return aiToolkitInstance.services.providers.getAllProviders();
+ return requireToolkit().services.providers.getAllProviders();
}
export async function getProviderById(id) {
- if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized');
- return aiToolkitInstance.services.providers.getProviderById(id);
+ return requireToolkit().services.providers.getProviderById(id);
}
export async function getActiveProvider() {
- if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized');
- return aiToolkitInstance.services.providers.getActiveProvider();
+ return requireToolkit().services.providers.getActiveProvider();
}
export async function setActiveProvider(id) {
- if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized');
- return aiToolkitInstance.services.providers.setActiveProvider(id);
+ return requireToolkit().services.providers.setActiveProvider(id);
}
export async function createProvider(data) {
- if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized');
- return aiToolkitInstance.services.providers.createProvider(data);
+ return requireToolkit().services.providers.createProvider(data);
}
export async function updateProvider(id, data) {
- if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized');
- return aiToolkitInstance.services.providers.updateProvider(id, data);
+ return requireToolkit().services.providers.updateProvider(id, data);
}
export async function deleteProvider(id) {
- if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized');
- return aiToolkitInstance.services.providers.deleteProvider(id);
+ return requireToolkit().services.providers.deleteProvider(id);
}
export async function testProvider(id) {
- if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized');
- return aiToolkitInstance.services.providers.testProvider(id);
+ return requireToolkit().services.providers.testProvider(id);
}
export async function refreshProviderModels(id) {
- if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized');
- return aiToolkitInstance.services.providers.refreshProviderModels(id);
+ return requireToolkit().services.providers.refreshProviderModels(id);
}
diff --git a/server/services/visionTest.integration.test.js b/server/services/visionTest.integration.test.js
index c0da10929e..42023edf60 100644
--- a/server/services/visionTest.integration.test.js
+++ b/server/services/visionTest.integration.test.js
@@ -203,7 +203,11 @@ describe('Vision Integration Tests', () => {
});
expect(result.success).toBe(false);
- expect(result.error).toContain('not found');
+ // Either the toolkit isn't initialized in this test context (boot-race
+ // path) or the provider really is missing — both surface as a graceful
+ // string error.
+ expect(typeof result.error).toBe('string');
+ expect(result.error).toMatch(/not found|still initializing/);
});
it('should gracefully handle non-existent image', async () => {
diff --git a/server/services/visionTest.js b/server/services/visionTest.js
index aa202496ac..252695bef6 100644
--- a/server/services/visionTest.js
+++ b/server/services/visionTest.js
@@ -113,14 +113,19 @@ async function callVisionAPI({ endpoint, apiKey, model, imageDataUrl, prompt, ti
export async function testVision({ imagePath, prompt, expectedContent, providerId = 'lmstudio', model }) {
const startTime = Date.now();
- // Get provider configuration
+ // Get provider configuration. The AI toolkit warms at server boot, so an
+ // AI_TOOLKIT_NOT_INITIALIZED code only fires from a vision test that races
+ // boot — surface the boot state directly rather than masquerading as "not
+ // found", which would send the user looking for the wrong root cause.
let provider;
try {
provider = await getProviderById(providerId);
} catch (err) {
return {
success: false,
- error: err.message.includes('not initialized') ? `Provider '${providerId}' not found` : err.message,
+ error: err.code === 'AI_TOOLKIT_NOT_INITIALIZED'
+ ? 'AI provider service is still initializing — try again in a moment'
+ : err.message,
duration: Date.now() - startTime
};
}
diff --git a/server/services/voice/tts.js b/server/services/voice/tts.js
index daa227622b..5c80830fbb 100644
--- a/server/services/voice/tts.js
+++ b/server/services/voice/tts.js
@@ -4,6 +4,7 @@ import { getVoiceConfig, piperVoiceTildePath } from './config.js';
import { synthesizeKokoro, listKokoroVoices } from './tts-kokoro.js';
import { synthesizePiper, listPiperVoices } from './tts-piper.js';
import { findPiperVoice } from './piper-voices.js';
+import { ServerError } from '../../lib/errorHandler.js';
// Single source of truth for the supported TTS engine names. Imported by
// routes/voice.js, routes/pipeline.js, and services/pipeline/audio.js so a
@@ -43,7 +44,12 @@ export const synthesize = async (text, opts = {}) => {
// otherwise `voice` would change but `voicePath` would remain the
// previous config value, silently synthesizing the wrong voice.
const catalog = findPiperVoice(opts.voice);
- if (!catalog) throw new Error(`unknown piper voice: ${opts.voice}`);
+ if (!catalog) {
+ throw new ServerError(`unknown piper voice: ${opts.voice}`, {
+ status: 400,
+ code: 'UNKNOWN_VOICE',
+ });
+ }
ttsCfg = {
...cfg.tts,
piper: {