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

Extract shared bounded concurrency mapper

[._.]/ Adam Eivye3bc796793cb
diff --git a/PLAN.md b/PLAN.md
index 195343cae5..dd4c3583ed 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -6,10 +6,9 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
1. **[ltx2-fflf-skips-last-image-resize-when-both-frames-set]** **ltx2 FFLF skips last-image resize when both start and end frames are provided — CONFIRMED bug (verified 2026-05-30 this replan).** `server/services/videoGen/local.js:573` gates `lastImageWillBeUsed` on `mode === 'fflf' && !sourceImagePath`, so the ltx2 true-FFLF flow (both `sourceImagePath` AND `lastImagePath` set, passed via `--image` + `--last-image` at `buildLtx2Args` ~line 328) skips the `resizeImage` ffmpeg pass for the end frame; `scripts/generate_ltx2.py` `_resolve_keyframes` (~line 313) then passes both paths straight through with no resize/letterbox/pad. The end-frame image reaches `KeyframeInterpolationPipeline.generate_and_save()` at its ORIGINAL dimensions → dimension mismatch / degraded output (the multi-keyframe path already resizes each keyframe at `local.js` ~line 606; the two-keyframe legacy path was missed). Fix: resize the last image in the ltx2 two-keyframe FFLF path the same way multi-keyframes are resized, and correct the stale comment at `local.js` ~line 560 that wrongly assumes only mlx_video/Windows consume `--last-image`. (Was filed UNVERIFIED under blocked; verification this replan confirmed it real and moved it up.)
2. **[media-job-store-progress-on-job-record]** **mediaJobQueue: persist progress/statusMsg on the job record.** `runJob`'s progress handler in `server/services/mediaJobQueue/index.js` (~line 575) only broadcasts to SSE (`broadcastSse`) — it doesn't mutate the job object. So `GET /api/media-jobs/:id` (used by `MediaJobsQueue.jsx` and any other non-SSE consumer) always reports 0 progress for in-flight jobs. SSE-attached pages don't see this (lastPayload replay), but list-view hydration does. Add `job.progress` + `job.statusMsg` updates inside the dispatcher's `progress` handler. Cross-cutting across image/video/codex paths.
-3. **[shared-bounded-concurrency-mapper]** **Extract a generic `mapWithConcurrency(items, n, fn)` to `server/lib/` and reuse it.** The worker-pool idiom (cursor + N workers draining a shared array, order-preserving result) is now hand-rolled in THREE places (verified 2026-05-30): `embedBatch` in `server/services/embeddings.js` (~line 158), the mapper in `server/services/catalogExtraction.js` (~line 317), and another in `server/routes/imageVideoModels.js`. A pure `server/lib/` helper would collapse all three onto one tested mechanism (barrel + README row per the maintenance rule).
-4. **[video-resume-restore-keyframes]** **VideoGen resume: restore keyframes from the active job.** `ACTIVE_JOB_PARAM_FIELDS` in `server/routes/videoGen.js` (~line 739) intentionally omits `keyframes` (gallery filename + frame-index pairs for multi-keyframe FFLF) because the v1 resume effect doesn't repopulate the picker UI for them. A user who reloads mid-render on a keyframe job loses the keyframe-picker state even though every other form field is restored. Whitelist `keyframes` in the route AND wire a `setKeyframes()`-style setter in `client/src/pages/VideoGen.jsx`'s resume effect (~line 507). Independent of the SSE re-attach.
-5. **[chrome-canary-followups]** **Hardening for the custom-Chrome-binary feature — remaining low/medium items.** _High-severity (a)–(f) are now DONE (verified 2026-05-30): (a) `browser/server.js` (~line 46) derives `macAppBundle` from `chromePath` on macOS; (b) both `spawn()` calls (~lines 221, 236) have `.on('error', …)` listeners; (d) both `loadConfig`s try/catch `JSON.parse`; (e) `setup-browser.js#loadConfig` warns + returns null and `applyCanaryToConfig` skips the save on unreadable config; (f) top-level `runCanarySetup()` is `.catch()`-wrapped. (c) headless-flag flip is tracked in `[setup-browser-canary-headless]` (now in Backlog with a decision)._ **Remaining low/medium:** (g) idempotency guard only checks `chromePath` — decliners + `macAppBundle`-only users get re-prompted every update; (h) `PORTOS_USE_CANARY` only matches literal `0/false/1/true` — `no/off/yes/on/True` fall through both branches; (i) `spawnSync(install.cmd, …, { stdio: 'inherit' })` for brew/winget can hang on a sudo prompt under non-TTY + `PORTOS_USE_CANARY=1`; (j) `cachedConfig` in `browserService.js` is stale relative to setup-browser's direct write (GET /api/browser/config returns pre-update values until process restart); (k) `saveConfig` uses bare `writeFileSync` — switch to the canonical `atomicWrite` (`server/lib/fileUtils.js`); (l) `spawnSync` status check treats `status: null` (spawn-failure/signal) like a non-zero exit and never logs `result.error`; (m) `optionalPath` Zod schema has no `.app`/`.exe` sanity check; (n) `launchBrowser`'s reuse-existing-Chrome early-return fires BEFORE `headlessMode` is set (wrong /health mode after a PM2 restart that reuses Chrome); (o) `detectCanary` on macOS only checks `/Applications/...` and misses per-user `~/Applications` installs.
-6. **[ref-watch-phosphene-teacache-extend-a2v-denoise]** **TeaCache through Extend + A2V Stage-1 denoise loops.** From `reference-watch` review of phosphene (commits `ea98aad8` + `17be2a79`, 2026-05-28). PortOS's `scripts/generate_ltx2.py` invokes `ExtendPipeline.extend_from_video(...)` (~line 378) and `AudioToVideoPipeline.generate_and_save(...)` (~line 417) directly without passing a TeaCache controller, so the slowest two modes in the panel run full denoise. Phosphene reuses the existing Stage-1 calibration (`ti2vid_two_stages._build_teacache_controller(n_steps, thresh=0.5)`) by monkey-patching `guided_denoise_loop` on the `ltx_pipelines_mlx.retake` and `ltx_pipelines_mlx.a2vid_two_stage` modules, gating activation on a per-call module-level config dict, set before the pipeline call and cleared in `finally`. Predicted ~1.2× on extend at default threshold (up to ~3× at 1.5); similar for A2V Stage 1. Fix: install both monkey-patches at the top of `generate_ltx2.py`, wire `_EXTEND_TC_CONFIG` / `_A2V_TC_CONFIG` from the helper's `run_extend`/`run_a2v` paths, and add a `--no-teacache` CLI flag (default-on). **Decision (resolved 2026-05-30): land independently** against today's pin — the calibration helper `_build_teacache_controller` already exists at the current pin, so there's no need to couple this to the risky rename in `[ref-watch-phosphene-bump-ltx2-pin-v0148]`. Scope: small/medium.
+3. **[video-resume-restore-keyframes]** **VideoGen resume: restore keyframes from the active job.** `ACTIVE_JOB_PARAM_FIELDS` in `server/routes/videoGen.js` (~line 739) intentionally omits `keyframes` (gallery filename + frame-index pairs for multi-keyframe FFLF) because the v1 resume effect doesn't repopulate the picker UI for them. A user who reloads mid-render on a keyframe job loses the keyframe-picker state even though every other form field is restored. Whitelist `keyframes` in the route AND wire a `setKeyframes()`-style setter in `client/src/pages/VideoGen.jsx`'s resume effect (~line 507). Independent of the SSE re-attach.
+4. **[chrome-canary-followups]** **Hardening for the custom-Chrome-binary feature — remaining low/medium items.** _High-severity (a)–(f) are now DONE (verified 2026-05-30): (a) `browser/server.js` (~line 46) derives `macAppBundle` from `chromePath` on macOS; (b) both `spawn()` calls (~lines 221, 236) have `.on('error', …)` listeners; (d) both `loadConfig`s try/catch `JSON.parse`; (e) `setup-browser.js#loadConfig` warns + returns null and `applyCanaryToConfig` skips the save on unreadable config; (f) top-level `runCanarySetup()` is `.catch()`-wrapped. (c) headless-flag flip is tracked in `[setup-browser-canary-headless]` (now in Backlog with a decision)._ **Remaining low/medium:** (g) idempotency guard only checks `chromePath` — decliners + `macAppBundle`-only users get re-prompted every update; (h) `PORTOS_USE_CANARY` only matches literal `0/false/1/true` — `no/off/yes/on/True` fall through both branches; (i) `spawnSync(install.cmd, …, { stdio: 'inherit' })` for brew/winget can hang on a sudo prompt under non-TTY + `PORTOS_USE_CANARY=1`; (j) `cachedConfig` in `browserService.js` is stale relative to setup-browser's direct write (GET /api/browser/config returns pre-update values until process restart); (k) `saveConfig` uses bare `writeFileSync` — switch to the canonical `atomicWrite` (`server/lib/fileUtils.js`); (l) `spawnSync` status check treats `status: null` (spawn-failure/signal) like a non-zero exit and never logs `result.error`; (m) `optionalPath` Zod schema has no `.app`/`.exe` sanity check; (n) `launchBrowser`'s reuse-existing-Chrome early-return fires BEFORE `headlessMode` is set (wrong /health mode after a PM2 restart that reuses Chrome); (o) `detectCanary` on macOS only checks `/Applications/...` and misses per-user `~/Applications` installs.
+5. **[ref-watch-phosphene-teacache-extend-a2v-denoise]** **TeaCache through Extend + A2V Stage-1 denoise loops.** From `reference-watch` review of phosphene (commits `ea98aad8` + `17be2a79`, 2026-05-28). PortOS's `scripts/generate_ltx2.py` invokes `ExtendPipeline.extend_from_video(...)` (~line 378) and `AudioToVideoPipeline.generate_and_save(...)` (~line 417) directly without passing a TeaCache controller, so the slowest two modes in the panel run full denoise. Phosphene reuses the existing Stage-1 calibration (`ti2vid_two_stages._build_teacache_controller(n_steps, thresh=0.5)`) by monkey-patching `guided_denoise_loop` on the `ltx_pipelines_mlx.retake` and `ltx_pipelines_mlx.a2vid_two_stage` modules, gating activation on a per-call module-level config dict, set before the pipeline call and cleared in `finally`. Predicted ~1.2× on extend at default threshold (up to ~3× at 1.5); similar for A2V Stage 1. Fix: install both monkey-patches at the top of `generate_ltx2.py`, wire `_EXTEND_TC_CONFIG` / `_A2V_TC_CONFIG` from the helper's `run_extend`/`run_a2v` paths, and add a `--no-teacache` CLI flag (default-on). **Decision (resolved 2026-05-30): land independently** against today's pin — the calibration helper `_build_teacache_controller` already exists at the current pin, so there's no need to couple this to the risky rename in `[ref-watch-phosphene-bump-ltx2-pin-v0148]`. Scope: small/medium.
## Backlog
diff --git a/server/lib/README.md b/server/lib/README.md
index a8690e2791..6bb14404dd 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -186,6 +186,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `asyncMutex.js` | Promise-based async mutex. |
| `errorHandler.js` | `ServerError` + `asyncHandler` middleware. |
+| `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. |
| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |
| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others). |
| `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 12021920a0..e5da568906 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -153,6 +153,7 @@ export * from './timezone.js';
// === General utilities ===
export * from './asyncMutex.js';
export * from './errorHandler.js';
+export * from './mapWithConcurrency.js';
export * from './objects.js';
export * from './sseUtils.js';
export * from './uuid.js';
diff --git a/server/lib/mapWithConcurrency.js b/server/lib/mapWithConcurrency.js
new file mode 100644
index 0000000000..ceb418be08
--- /dev/null
+++ b/server/lib/mapWithConcurrency.js
@@ -0,0 +1,29 @@
+/**
+ * Map items with a bounded number of in-flight async operations while
+ * preserving input order in the returned array.
+ */
+export async function mapWithConcurrency(items, concurrency, fn) {
+ if (!Array.isArray(items)) {
+ throw new TypeError('mapWithConcurrency: items must be an array');
+ }
+ if (typeof fn !== 'function') {
+ throw new TypeError('mapWithConcurrency: fn must be a function');
+ }
+
+ const requestedConcurrency = Number(concurrency);
+ const normalizedConcurrency = Number.isFinite(requestedConcurrency)
+ ? Math.max(1, Math.floor(requestedConcurrency))
+ : 1;
+ const workerCount = Math.min(items.length, normalizedConcurrency);
+ const results = new Array(items.length);
+ let cursor = 0;
+
+ await Promise.all(Array.from({ length: workerCount }, async () => {
+ while (cursor < items.length) {
+ const i = cursor++;
+ results[i] = await fn(items[i], i);
+ }
+ }));
+
+ return results;
+}
diff --git a/server/lib/mapWithConcurrency.test.js b/server/lib/mapWithConcurrency.test.js
new file mode 100644
index 0000000000..e22bad127a
--- /dev/null
+++ b/server/lib/mapWithConcurrency.test.js
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+import { mapWithConcurrency } from './mapWithConcurrency.js';
+
+describe('mapWithConcurrency', () => {
+ it('preserves input order while limiting in-flight work', async () => {
+ let active = 0;
+ let maxActive = 0;
+
+ const out = await mapWithConcurrency([30, 10, 20, 5], 2, async (delay, index) => {
+ active += 1;
+ maxActive = Math.max(maxActive, active);
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ active -= 1;
+ return `${index}:${delay}`;
+ });
+
+ expect(out).toEqual(['0:30', '1:10', '2:20', '3:5']);
+ expect(maxActive).toBeLessThanOrEqual(2);
+ });
+
+ it('normalizes invalid concurrency to one worker', async () => {
+ let active = 0;
+ let maxActive = 0;
+
+ const out = await mapWithConcurrency([1, 2, 3], 0, async (item) => {
+ active += 1;
+ maxActive = Math.max(maxActive, active);
+ await Promise.resolve();
+ active -= 1;
+ return item * 2;
+ });
+
+ expect(out).toEqual([2, 4, 6]);
+ expect(maxActive).toBe(1);
+ });
+
+ it('returns an empty array without invoking the mapper', async () => {
+ let calls = 0;
+
+ const out = await mapWithConcurrency([], 4, async () => {
+ calls += 1;
+ });
+
+ expect(out).toEqual([]);
+ expect(calls).toBe(0);
+ });
+
+ it('rejects when a mapped item rejects', async () => {
+ await expect(mapWithConcurrency(['ok', 'bad'], 2, async (item) => {
+ if (item === 'bad') throw new Error('boom');
+ return item;
+ })).rejects.toThrow('boom');
+ });
+});
diff --git a/server/routes/imageVideoModels.js b/server/routes/imageVideoModels.js
index 0ebf5b1ac2..5d4d315390 100644
--- a/server/routes/imageVideoModels.js
+++ b/server/routes/imageVideoModels.js
@@ -16,6 +16,7 @@ import { join } from 'path';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { PATHS, formatBytes, dirSize } from '../lib/fileUtils.js';
import { loadMediaModels } from '../lib/mediaModels.js';
+import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';
const router = Router();
const HF_DEFAULT_HUB = join(homedir(), '.cache', 'huggingface', 'hub');
@@ -46,22 +47,6 @@ const buildAppModels = () => {
};
const APP_MODELS = buildAppModels();
-// Bound concurrent dirSize calls — each one spawns a `du` (or PowerShell)
-// child, and a hub with 50+ models would otherwise create a process storm
-// that stalls the API.
-async function mapWithConcurrency(items, concurrency, fn) {
- const results = new Array(items.length);
- let next = 0;
- await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, async () => {
- while (true) {
- const i = next++;
- if (i >= items.length) return;
- results[i] = await fn(items[i], i);
- }
- }));
- return results;
-}
-
router.get('/', asyncHandler(async (_req, res) => {
const hubDir = HF_HUB_DIR();
diff --git a/server/services/catalogExtraction.js b/server/services/catalogExtraction.js
index 9185a90718..39229d38c7 100644
--- a/server/services/catalogExtraction.js
+++ b/server/services/catalogExtraction.js
@@ -22,6 +22,7 @@ import { extractBible } from '../lib/bibleExtractor.js';
import { runStagedLLM } from '../lib/stageRunner.js';
import { BIBLE_KINDS, BIBLE_FIELD, BIBLE_LIMITS } from '../lib/storyBible.js';
import { CATALOG_TYPES } from '../lib/catalogTypes.js';
+import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';
import { catalogEvents } from './catalogEvents.js';
import { getScrap, listChildScraps, listIngredientsForRef } from './catalogDB.js';
@@ -317,23 +318,6 @@ export function dedupDrafts(drafts = []) {
return merged;
}
-// Map over an array with a bounded number of in-flight promises. Preserves
-// input order in the result. Used so a heavily-chunked scrap doesn't fan out
-// dozens of concurrent LLM extraction passes at once.
-async function mapWithConcurrency(items, concurrency, fn) {
- const results = new Array(items.length);
- let cursor = 0;
- const worker = async () => {
- while (cursor < items.length) {
- const i = cursor++;
- results[i] = await fn(items[i], i);
- }
- };
- const workers = Array.from({ length: Math.min(concurrency, items.length) }, worker);
- await Promise.all(workers);
- return results;
-}
-
// How many child-chunk extractions run concurrently. Bounded so a long paste
// (up to CATALOG_CHUNK_MAX_CHARS-sized chunks × maxChunks) doesn't slam the
// provider with dozens of parallel LLM calls.
diff --git a/server/services/embeddings.js b/server/services/embeddings.js
index 851b6d45d5..08c284555e 100644
--- a/server/services/embeddings.js
+++ b/server/services/embeddings.js
@@ -14,6 +14,7 @@
import { getSettings } from './settings.js';
import * as ollama from './ollamaManager.js';
import * as lmstudio from './lmStudioManager.js';
+import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';
export const EMBEDDING_DIM = 768;
@@ -157,24 +158,14 @@ export async function embedIngredient(ingredient) {
*/
export async function embedBatch(texts, options = {}) {
const concurrency = Math.max(1, options.concurrency || 4);
- const results = new Array(texts.length).fill(null);
-
- let next = 0;
- const worker = async () => {
- while (next < texts.length) {
- const i = next++;
- const out = await embedText(texts[i], options);
- if (out.success) {
- results[i] = { embedding: out.embedding, model: out.model, provider: out.provider };
- } else if (out.skipped) {
- results[i] = null;
- } else {
- console.error(`🧬 embedBatch[${i}] failed: ${out.error}`);
- results[i] = null;
- }
+ return mapWithConcurrency(texts, concurrency, async (text, i) => {
+ const out = await embedText(text, options);
+ if (out.success) {
+ return { embedding: out.embedding, model: out.model, provider: out.provider };
}
- };
-
- await Promise.all(Array.from({ length: concurrency }, worker));
- return results;
+ if (!out.skipped) {
+ console.error(`🧬 embedBatch[${i}] failed: ${out.error}`);
+ }
+ return null;
+ });
}