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

perf: lazy-load tabbed-page bodies, scope per-series issue reads, batch serial I/O

[._.]/ Adam Eivy06271646645b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 185cd0e5c7..b5f9eefc8e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,12 @@
# Unreleased
+## Performance
+
+- **Tabbed pages now lazy-load their tab bodies, and `/apps` + `/ambient` moved out of the eager entry bundle.** Digital Twin (17 tabs), MeatSpace (11 tabs), and Brain (10 tabs) previously imported *every* tab component up front, so opening any one tab downloaded a single 240–450 kB chunk's worth of all of them. Each tab body is now a `React.lazy` chunk behind a `<Suspense>` boundary, so a user who views 1–2 tabs no longer pays for the other 15. `Apps` and `Ambient` were the only two non-index pages still imported statically into the entry chunk — they're now `lazyWithReload` like every other route, shrinking the initial bundle (~109 → ~95 kB gzip). The Vite vendor split also gained named `vendor-three` / `vendor-charts` / `vendor-term` groups so the big 3D/charting/terminal libs land in stable, single shared chunks instead of an opaque `OrbitControls-*.js`. (`client/src/App.jsx`, `client/src/pages/DigitalTwin.jsx`, `client/src/pages/MeatSpace.jsx`, `client/src/pages/Brain.jsx`, `client/vite.config.js`)
+- **Pipeline series views read only their own issues instead of scanning the whole table.** `listIssuesForSeries` and `listIssues({ seriesId })` loaded *every* issue in the install, sanitized each, then filtered in JS — wasteful in the autopilot/editorial hot loops that call them per series. They now route through a new indexed `WHERE series_id = $1` query (`idx_issues_series`) on the PostgreSQL backend, with a matching JS-filtered path on the dev/test file backend. (`server/services/pipeline/issues.js`, `server/services/pipeline/issuesStore/{db,store}.js`)
+- **Removed avoidable per-render and per-frame work in the client.** `ArcCanvas` rebuilt + re-sorted its season→issue buckets (`Set`/`Map`/`sort`) on every render; it's now a `useMemo` keyed on `[seasons, issues]`. `VideoGen` re-filtered the full installed-LoRA list on every keystroke; those two filters are memoized. The CyberCity sky's `useFrame` loop allocated a fresh `THREE.Vector3` every frame (~60/sec) for the sun direction — it now reuses a module-scoped scratch vector. (`client/src/components/pipeline/ArcCanvas.jsx`, `client/src/pages/VideoGen.jsx`, `client/src/components/city/CitySky.jsx`)
+- **Collapsed serial awaits and an N+1 insert into batched I/O.** The `/api/apps/:id` detail endpoint read each PM2 process status one-at-a-time → now `Promise.all`. `dataSync`'s meatspace snapshot and the media-collections ephemeral/refused-parent lookups did serial independent reads → now concurrent. `memoryDB.updateMemory` inserted one `memory_links` row per related id in a loop → now a single multi-row `INSERT`. (`server/routes/apps.js`, `server/services/dataSync.js`, `server/services/memoryDB.js`)
+
## Navigation
- **Messages moved out of Brain into its own top-level "Comms" section.** The four Messages pages (Inbox, Drafts, Sync, Config) were buried as loose children inside the Brain group, mixed in with notes/feeds/links. They now live under a dedicated **Comms** sidebar section (between Chief of Staff and Create, alphabetically), with clean labels — so messaging is a first-class destination rather than a Brain sub-item. The page routes are unchanged (`/messages/*`), so existing links, ⌘K, and voice ("messages" / "comms") still resolve; only the sidebar grouping and the nav-manifest section moved. (`client/src/components/Layout.jsx`, `server/lib/navManifest.js`)
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 35b26758d4..8545bf99b2 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -5,10 +5,13 @@ import { getSettings, updateSettings, getSelfInstance } from './services/api';
import BrailleSpinner from './components/BrailleSpinner';
import { CatalogTypesProvider } from './hooks/useCatalogTypes.jsx';
import Dashboard from './pages/Dashboard';
-import Apps from './pages/Apps';
-import Ambient from './pages/Ambient';
import { lazyWithReload } from './utils/lazyWithReload';
+// Neither /apps nor /ambient is the landing route, so keep them out of the eager
+// entry chunk — lazy-load them like every other non-index page.
+const Apps = lazyWithReload(() => import('./pages/Apps'));
+const Ambient = lazyWithReload(() => import('./pages/Ambient'));
+
// Lazy load heavier pages for code splitting
// DevTools pages are large (~2300 lines total) so lazy load them
const AIProviders = lazyWithReload(() => import('./pages/AIProviders'));
diff --git a/client/src/components/city/CitySky.jsx b/client/src/components/city/CitySky.jsx
index 429ef723f5..a20fc035fa 100644
--- a/client/src/components/city/CitySky.jsx
+++ b/client/src/components/city/CitySky.jsx
@@ -112,6 +112,10 @@ const lerpColor = (target, a, b, t) => {
// sky bands (zenith, midSky) are tinted toward the active theme accent so the sky
// tracks the theme; horizon haze + sun colors stay physical/untinted. The accent is
// in the cache key so a theme switch re-derives instead of serving a stale tint.
+// Reused scratch vector for the per-frame sun direction — avoids allocating a
+// fresh THREE.Vector3 every frame (~60/sec) inside the useFrame loop below.
+const sunDirScratch = new THREE.Vector3();
+
const presetColors = {};
const getPresetColors = (name, skyTheme, accent) => {
const cacheKey = `${skyTheme}:${name}:${accent}`;
@@ -269,7 +273,7 @@ export default function CitySky({ settings }) {
// Compute sun position from current hour on the arc
const bodyPos = getArcPosition(currentHourRef.current);
- const bodyDir = new THREE.Vector3(...bodyPos).normalize();
+ const bodyDir = sunDirScratch.set(bodyPos[0], bodyPos[1], bodyPos[2]).normalize();
// Lerp sky dome colors
lerpColor(skyMaterial.uniforms.uZenith.value, skyMaterial.uniforms.uZenith.value, preset.zenith, lerpFactor);
diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsx
index c2587d20ed..d8b35e95a1 100644
--- a/client/src/components/pipeline/ArcCanvas.jsx
+++ b/client/src/components/pipeline/ArcCanvas.jsx
@@ -259,18 +259,23 @@ function CoverArt({ record, label, className = '', placeholderClassName = '' })
export default function ArcCanvas({ series, issues, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {
const seasons = useMemo(() => series.seasons || [], [series.seasons]);
const [activeSeasonId, setActiveSeasonId] = useState(seasons[0]?.id || null);
- // Stale seasonIds (e.g. after a verify-resolve season rewrite) bucket under
- // null so they show as ungrouped instead of vanishing into an un-iterated key.
- const validSeasonIds = new Set(seasons.map((s) => s.id));
- const issuesBySeason = new Map();
- for (const iss of issues) {
- const key = iss.seasonId && validSeasonIds.has(iss.seasonId) ? iss.seasonId : null;
- if (!issuesBySeason.has(key)) issuesBySeason.set(key, []);
- issuesBySeason.get(key).push(iss);
- }
- for (const list of issuesBySeason.values()) {
- list.sort((a, b) => (a.arcPosition ?? 9999) - (b.arcPosition ?? 9999) || (a.number || 0) - (b.number || 0));
- }
+ // Bucket + sort issues by season once per (seasons, issues) change rather than
+ // on every render. Stale seasonIds (e.g. after a verify-resolve season rewrite)
+ // bucket under null so they show as ungrouped instead of vanishing into an
+ // un-iterated key.
+ const issuesBySeason = useMemo(() => {
+ const validSeasonIds = new Set(seasons.map((s) => s.id));
+ const map = new Map();
+ for (const iss of issues) {
+ const key = iss.seasonId && validSeasonIds.has(iss.seasonId) ? iss.seasonId : null;
+ if (!map.has(key)) map.set(key, []);
+ map.get(key).push(iss);
+ }
+ for (const list of map.values()) {
+ list.sort((a, b) => (a.arcPosition ?? 9999) - (b.arcPosition ?? 9999) || (a.number || 0) - (b.number || 0));
+ }
+ return map;
+ }, [seasons, issues]);
const ungroupedIssues = issuesBySeason.get(null) || [];
const activeSeason = seasons.find((s) => s.id === activeSeasonId) || seasons[0] || null;
diff --git a/client/src/pages/Brain.jsx b/client/src/pages/Brain.jsx
index 6f381c90ae..0214c8c9ca 100644
--- a/client/src/pages/Brain.jsx
+++ b/client/src/pages/Brain.jsx
@@ -11,19 +11,18 @@ import { sameJsonShape } from '../lib/sameJsonShape';
import { TABS, FULL_BLEED_TAB_IDS } from '../components/brain/constants';
import { timeAgo } from '../utils/formatters';
-import InboxTab from '../components/brain/tabs/InboxTab';
-import LinksTab from '../components/brain/tabs/LinksTab';
-import MemoryTab from '../components/brain/tabs/MemoryTab';
-import DigestTab from '../components/brain/tabs/DigestTab';
-import FeedsTab from '../components/brain/tabs/FeedsTab';
-import TrustTab from '../components/brain/tabs/TrustTab';
-import NotesTab from '../components/brain/tabs/NotesTab';
-import DailyLogTab from '../components/brain/tabs/DailyLogTab';
-import ConfigTab from '../components/brain/tabs/ConfigTab';
-import ImportTab from '../components/brain/tabs/ImportTab';
-
-// BrainGraph uses the three.js stack — lazy-load so it's not bundled until the
-// graph tab is actually opened.
+// Lazy-load tab bodies so opening one tab doesn't pull in all ten. BrainGraph in
+// particular drags in the three.js stack, so it must stay out of the eager set.
+const InboxTab = lazy(() => import('../components/brain/tabs/InboxTab'));
+const LinksTab = lazy(() => import('../components/brain/tabs/LinksTab'));
+const MemoryTab = lazy(() => import('../components/brain/tabs/MemoryTab'));
+const DigestTab = lazy(() => import('../components/brain/tabs/DigestTab'));
+const FeedsTab = lazy(() => import('../components/brain/tabs/FeedsTab'));
+const TrustTab = lazy(() => import('../components/brain/tabs/TrustTab'));
+const NotesTab = lazy(() => import('../components/brain/tabs/NotesTab'));
+const DailyLogTab = lazy(() => import('../components/brain/tabs/DailyLogTab'));
+const ConfigTab = lazy(() => import('../components/brain/tabs/ConfigTab'));
+const ImportTab = lazy(() => import('../components/brain/tabs/ImportTab'));
const BrainGraph = lazy(() => import('../components/brain/tabs/BrainGraph'));
export default function Brain() {
@@ -69,7 +68,7 @@ export default function Brain() {
case 'daily-log':
return <DailyLogTab />;
case 'graph':
- return <Suspense fallback={<div className="flex items-center justify-center h-64"><BrailleSpinner text="Loading" /></div>}><BrainGraph /></Suspense>;
+ return <BrainGraph />;
case 'digest':
return <DigestTab onRefresh={refetch} />;
case 'feeds':
@@ -136,7 +135,9 @@ export default function Brain() {
{/* Tab content — full-bleed tabs own their own scroll and fill height;
document-style tabs scroll inside a padded wrapper. */}
<div className={`flex-1 min-h-0 ${fullBleed ? 'overflow-hidden' : 'overflow-auto p-3 sm:p-4'}`}>
- {renderTabContent()}
+ <Suspense fallback={<div className="flex items-center justify-center h-64"><BrailleSpinner text="Loading" /></div>}>
+ {renderTabContent()}
+ </Suspense>
</div>
</div>
);
diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsx
index 7e4eea9e0a..db628cd5dd 100644
--- a/client/src/pages/DigitalTwin.jsx
+++ b/client/src/pages/DigitalTwin.jsx
@@ -1,4 +1,4 @@
-import { useCallback } from 'react';
+import { useCallback, lazy, Suspense } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import * as api from '../services/api';
import { Heart } from 'lucide-react';
@@ -9,23 +9,25 @@ import { sameJsonShape } from '../lib/sameJsonShape';
import { TABS, getHealthColor, getHealthLabel } from '../components/digital-twin/constants';
-import OverviewTab from '../components/digital-twin/tabs/OverviewTab';
-import DocumentsTab from '../components/digital-twin/tabs/DocumentsTab';
-import TestTab from '../components/digital-twin/tabs/TestTab';
-import EnrichTab from '../components/digital-twin/tabs/EnrichTab';
-import TasteTab from '../components/digital-twin/tabs/TasteTab';
-import AccountsTab from '../components/digital-twin/tabs/AccountsTab';
-import InterviewTab from '../components/digital-twin/tabs/InterviewTab';
-import VoiceStyleTab from '../components/digital-twin/tabs/VoiceStyleTab';
-import AppearanceTab from '../components/digital-twin/tabs/AppearanceTab';
-import IdentityTab from '../components/digital-twin/tabs/IdentityTab';
-import PersonasTab from '../components/digital-twin/tabs/PersonasTab';
-import GoalsTab from '../components/digital-twin/tabs/GoalsTab';
-import AutobiographyTab from '../components/digital-twin/tabs/AutobiographyTab';
-import ImportTab from '../components/digital-twin/tabs/ImportTab';
-import ExportTab from '../components/digital-twin/tabs/ExportTab';
-import LegacyExportTab from '../components/digital-twin/tabs/LegacyExportTab';
-import TimeCapsuleTab from '../components/digital-twin/tabs/TimeCapsuleTab';
+// Lazy-load tab bodies so opening any one tab doesn't pull in all 17 — a user
+// typically views 1–2 of them. The page itself is already a lazy route chunk.
+const OverviewTab = lazy(() => import('../components/digital-twin/tabs/OverviewTab'));
+const DocumentsTab = lazy(() => import('../components/digital-twin/tabs/DocumentsTab'));
+const TestTab = lazy(() => import('../components/digital-twin/tabs/TestTab'));
+const EnrichTab = lazy(() => import('../components/digital-twin/tabs/EnrichTab'));
+const TasteTab = lazy(() => import('../components/digital-twin/tabs/TasteTab'));
+const AccountsTab = lazy(() => import('../components/digital-twin/tabs/AccountsTab'));
+const InterviewTab = lazy(() => import('../components/digital-twin/tabs/InterviewTab'));
+const VoiceStyleTab = lazy(() => import('../components/digital-twin/tabs/VoiceStyleTab'));
+const AppearanceTab = lazy(() => import('../components/digital-twin/tabs/AppearanceTab'));
+const IdentityTab = lazy(() => import('../components/digital-twin/tabs/IdentityTab'));
+const PersonasTab = lazy(() => import('../components/digital-twin/tabs/PersonasTab'));
+const GoalsTab = lazy(() => import('../components/digital-twin/tabs/GoalsTab'));
+const AutobiographyTab = lazy(() => import('../components/digital-twin/tabs/AutobiographyTab'));
+const ImportTab = lazy(() => import('../components/digital-twin/tabs/ImportTab'));
+const ExportTab = lazy(() => import('../components/digital-twin/tabs/ExportTab'));
+const LegacyExportTab = lazy(() => import('../components/digital-twin/tabs/LegacyExportTab'));
+const TimeCapsuleTab = lazy(() => import('../components/digital-twin/tabs/TimeCapsuleTab'));
export default function DigitalTwin() {
const { tab } = useParams();
@@ -145,7 +147,9 @@ export default function DigitalTwin() {
{/* Tab content */}
<div className="flex-1 overflow-auto p-4">
- {renderTabContent()}
+ <Suspense fallback={<div className="flex justify-center py-12"><BrailleSpinner text="Loading" /></div>}>
+ {renderTabContent()}
+ </Suspense>
</div>
</div>
);
diff --git a/client/src/pages/MeatSpace.jsx b/client/src/pages/MeatSpace.jsx
index a8900226b9..da4c8957a6 100644
--- a/client/src/pages/MeatSpace.jsx
+++ b/client/src/pages/MeatSpace.jsx
@@ -1,3 +1,4 @@
+import { lazy, Suspense } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Skull } from 'lucide-react';
@@ -5,18 +6,21 @@ import { TABS } from '../components/meatspace/constants';
import MortalLoomBanner from '../components/MortalLoomBanner';
import PageHeader from '../components/PageHeader';
import TabPills from '../components/ui/TabPills';
+import BrailleSpinner from '../components/BrailleSpinner';
-import OverviewTab from '../components/meatspace/tabs/OverviewTab';
-import AgeTab from '../components/meatspace/tabs/AgeTab';
-import AlcoholTab from '../components/meatspace/tabs/AlcoholTab';
-import BloodTab from '../components/meatspace/tabs/BloodTab';
-import BodyTab from '../components/meatspace/tabs/BodyTab';
-import ExportTab from '../components/meatspace/tabs/ExportTab';
-import GenomeTab from '../components/meatspace/tabs/GenomeTab';
-import HealthTab from '../components/meatspace/tabs/HealthTab';
-import SettingsTab from '../components/meatspace/tabs/SettingsTab';
-import LifestyleTab from '../components/meatspace/tabs/LifestyleTab';
-import NicotineTab from '../components/meatspace/tabs/NicotineTab';
+// Lazy-load tab bodies so opening one tab doesn't pull in all eleven (GenomeTab
+// in particular is heavy). The page itself is already a lazy route chunk.
+const OverviewTab = lazy(() => import('../components/meatspace/tabs/OverviewTab'));
+const AgeTab = lazy(() => import('../components/meatspace/tabs/AgeTab'));
+const AlcoholTab = lazy(() => import('../components/meatspace/tabs/AlcoholTab'));
+const BloodTab = lazy(() => import('../components/meatspace/tabs/BloodTab'));
+const BodyTab = lazy(() => import('../components/meatspace/tabs/BodyTab'));
+const ExportTab = lazy(() => import('../components/meatspace/tabs/ExportTab'));
+const GenomeTab = lazy(() => import('../components/meatspace/tabs/GenomeTab'));
+const HealthTab = lazy(() => import('../components/meatspace/tabs/HealthTab'));
+const SettingsTab = lazy(() => import('../components/meatspace/tabs/SettingsTab'));
+const LifestyleTab = lazy(() => import('../components/meatspace/tabs/LifestyleTab'));
+const NicotineTab = lazy(() => import('../components/meatspace/tabs/NicotineTab'));
export default function MeatSpace() {
const { tab } = useParams();
@@ -80,7 +84,9 @@ export default function MeatSpace() {
{/* Tab content */}
<div className="flex-1 overflow-auto p-6 print:overflow-visible print:p-0">
- {renderTabContent()}
+ <Suspense fallback={<div className="flex justify-center py-12"><BrailleSpinner text="Loading" /></div>}>
+ {renderTabContent()}
+ </Suspense>
</div>
</div>
);
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 575408ecd4..06dae930e6 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -766,9 +766,12 @@ export default function VideoGen() {
// transformer (the route only checks file-exists + ltx2) and fail the render.
// Video LoRAs always carry an explicit `ltx-video` family (HF import sets it),
// so an exact-match filter here is the correct strict mode.
- const videoLoras = loraFamily
- ? availableLoras.filter((l) => (l.loraCompatKey || l.runnerFamily) === loraFamily)
- : [];
+ const videoLoras = useMemo(
+ () => (loraFamily
+ ? availableLoras.filter((l) => (l.loraCompatKey || l.runnerFamily) === loraFamily)
+ : []),
+ [availableLoras, loraFamily],
+ );
// Installed LTX-video LoRAs regardless of the selected model's runtime. When
// the user picks an LTX-2.x model whose runtime can't fuse LoRAs (a quantized
@@ -777,8 +780,11 @@ export default function VideoGen() {
// unavailable and point at the models that CAN run it. The `/ltx-?2/i` scope
// matches the server's LTX-2.x capability family (see isMlxVideoLtxLoraCapable)
// so the hint never fires for a non-LTX-2.x model where the advice wouldn't apply.
- const installedVideoLoras = availableLoras.filter(
- (l) => (l.loraCompatKey || l.runnerFamily) === VIDEO_LORA_FAMILIES.LTX_VIDEO,
+ const installedVideoLoras = useMemo(
+ () => availableLoras.filter(
+ (l) => (l.loraCompatKey || l.runnerFamily) === VIDEO_LORA_FAMILIES.LTX_VIDEO,
+ ),
+ [availableLoras],
);
// Gated on the quantized-mlx_video case specifically (runtime mlx_video +
// loraFamily null = a quantized LTX-2.x model) so the hint copy's "quantized
diff --git a/client/vite.config.js b/client/vite.config.js
index e72d488745..c81ddde7bd 100644
--- a/client/vite.config.js
+++ b/client/vite.config.js
@@ -93,6 +93,15 @@ export default defineConfig(({ mode }) => {
{ name: 'vendor-dnd', test: /[\\/]node_modules[\\/]@dnd-kit[\\/]/ },
// Icon library (largest dependency)
{ name: 'vendor-icons', test: /[\\/]node_modules[\\/]lucide-react[\\/]/ },
+ // 3D stack — only pulled into lazy 3D pages (CyberCity, avatars,
+ // BrainGraph). Naming it gives the ~1 MB chunk a stable identity
+ // instead of an opaque `OrbitControls-*.js` and guarantees a single
+ // shared chunk across all 3D consumers.
+ { name: 'vendor-three', test: /[\\/]node_modules[\\/](three|@react-three|three-fenestra)[\\/]/ },
+ // Charting (recharts) — lazy chart pages only
+ { name: 'vendor-charts', test: /[\\/]node_modules[\\/](recharts|d3-[^\\/]+|victory-[^\\/]+)[\\/]/ },
+ // Terminal emulator (xterm) — Shell page only
+ { name: 'vendor-term', test: /[\\/]node_modules[\\/]@xterm[\\/]/ },
]
}
}
diff --git a/server/routes/apps.js b/server/routes/apps.js
index 5d4d4e2c25..e9c21c2d24 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -173,8 +173,15 @@ router.get('/:id', loadApp, asyncHandler(async (req, res) => {
// status object). A failed read is genuinely unknown, not "not running" —
// mark `degraded` so the detail UI can offer refresh-to-retry rather than a
// misleading Start. Mirrors the list endpoint's `degraded`.
- for (const processName of app.pm2ProcessNames || []) {
- const status = await pm2Service.getAppStatusStrict(processName, app.pm2Home);
+ // Read each process's PM2 status in parallel — a detail view of a
+ // multi-process app would otherwise serialize one IPC round-trip per process.
+ const reads = await Promise.all(
+ (app.pm2ProcessNames || []).map(async (processName) => ({
+ processName,
+ status: await pm2Service.getAppStatusStrict(processName, app.pm2Home),
+ })),
+ );
+ for (const { processName, status } of reads) {
if (status === null) {
degraded = true;
statuses[processName] = { name: processName, status: 'unknown', pm2_env: null };
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index 81455484bc..b867a7165e 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -328,11 +328,14 @@ async function applyCharacterRemote(remoteData) {
// --- Category: Meatspace ---
async function getMeatspaceSnapshot() {
+ const filenames = Object.keys(MEATSPACE_FILES);
+ // The files are independent — read them in parallel rather than one-at-a-time
+ // (this snapshot runs on every ~60s sync poll).
+ const contents = await Promise.all(
+ filenames.map((filename) => readJSONFile(join(MEATSPACE_DIR, filename), null)),
+ );
const result = {};
- for (const [filename] of Object.entries(MEATSPACE_FILES)) {
- const filePath = join(MEATSPACE_DIR, filename);
- result[filename] = await readJSONFile(filePath, null);
- }
+ filenames.forEach((filename, i) => { result[filename] = contents[i]; });
return { data: result, checksum: computeChecksum(result) };
}
@@ -512,15 +515,16 @@ async function getMediaCollectionsSnapshot({ exclude } = {}) {
// item refs for records the user explicitly opted out of sync. Tombstoned
// ephemeral parents also drop their collection (sender wouldn't bundle them
// anyway, but the snapshot path is independent).
+ // Independent reads — fetch the universe and series lists concurrently.
+ const [allUniversesForEphemeral, allSeriesForEphemeral] = await Promise.all([
+ listUniverses({ includeDeleted: true }).catch(() => []),
+ listSeries({ includeDeleted: true }).catch(() => []),
+ ]);
const ephemeralUniverseIds = new Set(
- (await listUniverses({ includeDeleted: true }).catch(() => []))
- .filter((u) => u?.ephemeral === true)
- .map((u) => u.id),
+ allUniversesForEphemeral.filter((u) => u?.ephemeral === true).map((u) => u.id),
);
const ephemeralSeriesIds = new Set(
- (await listSeries({ includeDeleted: true }).catch(() => []))
- .filter((s) => s?.ephemeral === true)
- .map((s) => s.id),
+ allSeriesForEphemeral.filter((s) => s?.ephemeral === true).map((s) => s.id),
);
// Exclude collections the requesting peer already receives per-record via
// the push pipeline (its INBOUND coverage). Keyed on the collection's own
@@ -566,8 +570,10 @@ async function applyMediaCollectionsRemote(remoteData, source) {
// the parent live could otherwise ship a newer collection snapshot
// with the old parent id and re-link the collection to our tombstone,
// undoing the cleanup.
- const allUniverses = await listUniverses({ includeDeleted: true }).catch(() => []);
- const allSeries = await listSeries({ includeDeleted: true }).catch(() => []);
+ const [allUniverses, allSeries] = await Promise.all([
+ listUniverses({ includeDeleted: true }).catch(() => []),
+ listSeries({ includeDeleted: true }).catch(() => []),
+ ]);
const refusedUniverseIds = new Set(
allUniverses.filter((u) => u?.ephemeral === true || u?.deleted === true).map((u) => u.id),
);
diff --git a/server/services/memoryDB.js b/server/services/memoryDB.js
index 5d815ffbfd..30352d82e4 100644
--- a/server/services/memoryDB.js
+++ b/server/services/memoryDB.js
@@ -316,10 +316,15 @@ export async function updateMemory(id, updates) {
if (updates.relatedMemories) {
await client.query('DELETE FROM memory_links WHERE source_id = $1', [id]);
- for (const relId of updates.relatedMemories) {
+ if (updates.relatedMemories.length > 0) {
+ // One multi-row INSERT instead of N round-trips. $1 is source_id;
+ // each related id binds to $2, $3, … as its own VALUES row.
+ const valuesSql = updates.relatedMemories
+ .map((_, i) => `($1, $${i + 2})`)
+ .join(', ');
await client.query(
- 'INSERT INTO memory_links (source_id, target_id) VALUES ($1, $2) ON CONFLICT DO NOTHING',
- [id, relId]
+ `INSERT INTO memory_links (source_id, target_id) VALUES ${valuesSql} ON CONFLICT DO NOTHING`,
+ [id, ...updates.relatedMemories]
);
}
// Bump updated_at so link changes appear in sync and timeline
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index ba3ac1d2b0..08ff4f4146 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -606,6 +606,13 @@ async function readState() {
return { issues: await store().loadAll() };
}
+// Series-scoped read — uses the indexed `idx_issues_series` query (PG) so a
+// per-series scan doesn't load + sanitize every issue in the install. Callers
+// that already filter by seriesId in JS should source from here instead.
+async function readStateForSeries(seriesId) {
+ return { issues: await store().loadAllForSeries(seriesId) };
+}
+
async function saveIssueNow(issue) {
await store().saveOneNow(issue.id, issue);
return issue;
@@ -623,7 +630,10 @@ export async function listIssues({
withHistory = true,
includeDeleted = false,
} = {}) {
- const { issues } = await readState();
+ // Scope the read to one series when filtering by it — avoids loading every
+ // issue in the install just to discard the rest (the `seriesId.localeCompare`
+ // tiebreak below is a no-op within a single series).
+ const { issues } = seriesId ? await readStateForSeries(seriesId) : await readState();
const live = includeDeleted ? issues : issues.filter((i) => !i.deleted);
const filtered = seriesId ? live.filter((i) => i.seriesId === seriesId) : live;
const sorted = [...filtered].sort((a, b) => {
@@ -698,10 +708,9 @@ export async function listAllIssues({ includeDeleted = false, withHistory = true
* @param {boolean} [options.withHistory=true] - false strips per-stage run history
*/
export async function listIssuesForSeries(seriesId, { includeDeleted = false, withHistory = true } = {}) {
- const { issues } = await readState();
+ const { issues } = await readStateForSeries(seriesId);
const live = includeDeleted ? issues : issues.filter((i) => !i.deleted);
- const filtered = live.filter((i) => i.seriesId === seriesId);
- const sorted = [...filtered].sort((a, b) => (a.number || 0) - (b.number || 0));
+ const sorted = [...live].sort((a, b) => (a.number || 0) - (b.number || 0));
return withHistory ? sorted : sorted.map(stripRunHistoryFromIssue);
}
diff --git a/server/services/pipeline/issuesStore/db.js b/server/services/pipeline/issuesStore/db.js
index 2d4da45549..07fa5e8fee 100644
--- a/server/services/pipeline/issuesStore/db.js
+++ b/server/services/pipeline/issuesStore/db.js
@@ -35,6 +35,17 @@ export async function listRaw() {
return rows.map((r) => r.data);
}
+/**
+ * Raw `data` JSONB for one series only — uses the `idx_issues_series
+ * (series_id, number)` index instead of scanning + sanitizing the whole table.
+ * Returns live/ephemeral/tombstones (the service applies the `deleted` filter),
+ * matching `listRaw`'s contract but scoped.
+ */
+export async function listRawBySeries(seriesId) {
+ const { rows } = await query(`SELECT data FROM pipeline_issues WHERE series_id = $1`, [seriesId]);
+ return rows.map((r) => r.data);
+}
+
/**
* Upsert one record. `data` is written verbatim (lossless); the typed mirror
* columns are bind-sanitized so a hand-edited/legacy record can't make the
diff --git a/server/services/pipeline/issuesStore/store.js b/server/services/pipeline/issuesStore/store.js
index f9b405230e..1112f28938 100644
--- a/server/services/pipeline/issuesStore/store.js
+++ b/server/services/pipeline/issuesStore/store.js
@@ -59,6 +59,13 @@ function makeFileBackend(dir, sanitizeRecord) {
const records = await Promise.all(ids.map((id) => cs.loadOneRaw(id)));
return records.filter((r) => r != null);
},
+ // No per-series index in the file backend — filter the full set in JS. The
+ // PG backend below uses an indexed WHERE; this keeps the facade uniform.
+ listRawBySeries: async (seriesId) => {
+ const ids = await cs.listIds();
+ const records = await Promise.all(ids.map((id) => cs.loadOneRaw(id)));
+ return records.filter((r) => r != null && r.seriesId === seriesId);
+ },
writeRaw: (id, record) => cs.saveOneNow(id, record),
deleteRaw: (id) => cs.deleteOneNow(id),
verify: () => cs.verifySchemaVersion(),
@@ -74,6 +81,7 @@ function makePgBackend(db, sanitizeRecord) {
},
listIds: db.listIds,
listRaw: db.listRaw,
+ listRawBySeries: db.listRawBySeries,
writeRaw: db.writeRaw,
deleteRaw: db.deleteRaw,
verify: async () => ({ ok: true, type: 'pipelineIssues', onDisk: null, expected: null,
@@ -148,6 +156,10 @@ function createFacade({ dir, sanitizeRecord }) {
const raw = await (await getBackend()).listRaw();
return raw.map((r) => sanitizer(r)).filter((r) => r != null);
},
+ loadAllForSeries: async (seriesId) => {
+ const raw = await (await getBackend()).listRawBySeries(seriesId);
+ return raw.map((r) => sanitizer(r)).filter((r) => r != null);
+ },
saveOneNow,
deleteOneNow,
diff --git a/server/services/pipeline/issuesStore/store.test.js b/server/services/pipeline/issuesStore/store.test.js
index df066fc720..1e8e0b5f13 100644
--- a/server/services/pipeline/issuesStore/store.test.js
+++ b/server/services/pipeline/issuesStore/store.test.js
@@ -46,6 +46,18 @@ describe('pipeline issues store facade — file backend', () => {
expect((await s.loadAll()).map((r) => r.id).sort()).toEqual(['iss-1', 'iss-2']);
});
+ it('loadAllForSeries returns only the requested series, sanitized', async () => {
+ const s = getIssuesStore(passthroughSanitize);
+ await s.saveOneNow('iss-1', { id: 'iss-1', seriesId: 'ser-1', title: 'One' });
+ await s.saveOneNow('iss-2', { id: 'iss-2', seriesId: 'ser-2', title: 'Two' });
+ await s.saveOneNow('iss-3', { id: 'iss-3', seriesId: 'ser-1', title: 'Three' });
+ const ser1 = await s.loadAllForSeries('ser-1');
+ expect(ser1.map((r) => r.id).sort()).toEqual(['iss-1', 'iss-3']);
+ expect(ser1.every((r) => r._sanitized === true)).toBe(true);
+ expect((await s.loadAllForSeries('ser-2')).map((r) => r.id)).toEqual(['iss-2']);
+ expect(await s.loadAllForSeries('ser-missing')).toEqual([]);
+ });
+
it('deleteOne removes the record', async () => {
const s = getIssuesStore(passthroughSanitize);
await s.saveOneNow('iss-1', { id: 'iss-1', seriesId: 'ser-1', title: 'X' });