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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: dedupe finalizeCanceled and drop dead imports after the finalizer extraction (#6830)
[._.]/ Adam Eivy4648223ce0ac
diff --git a/server/lib/README.md b/server/lib/README.mdindex 52f3f8351a..02768be1d6 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -584,7 +584,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `services/promptRunner.js`'s fallback mark-and-pick. || `staleWhileRevalidate.js` | `createStaleWhileRevalidate({ ttlMs, failureBackoffMs?, isComplete?, partialTtlMs? })` → `read(key, produce, { wait })` / `clear(key?)` — TTL cache that serves a STALE value immediately and revalidates behind the caller, for readings too slow to block on (10-20s CLI/PTY spawns). `wait`: `'fresh'` bypasses and blocks, `'cached'` (default) blocks only on a cold cache, `'never'` returns the `PENDING` symbol on a cold cache for UIs that render "still reading" and poll. Failures keep the last good value and back off; a cold cache whose producer failed throws rather than promising a reading that isn't coming. Used by `providerUsage.js` (TUI scrapes) and `claudeCodeUsage.js`. || `staticImportGraph.js` | Static ES-module import scanning for structural test guards. `staticImportSpecifiers(file)` → every specifier a file statically imports (verbatim, source order); `staticImportClosure(entry)` → `{files, packages}` for the whole reachable graph; `buildStaticImportGraph(rootDir)` → `Map<relPath, relPath[]>` of one directory's internal static edges (recurses into subdirectories, skips `.test.js`); `listModuleFiles(rootDir)` → every non-test `.js` under a directory, keyed by `/`-separated relative path (the same walk the graph builder uses, shared so a layering guard cannot drift from it); `findImportCycles(graph)` → each cycle rendered as `a.js -> b.js -> a.js` (depth-first, so WHICH rings it names depends on where the walk enters a component — fine for an "is this empty?" assertion, unusable as a baseline); `findImportCycleComponents(graph)` → the cyclic strongly-connected components as sorted member lists, traversal-order invariant and therefore baselineable (#5693); `specifierMatchesPackage(spec, pkg)` matches a package or any subpath; `toModuleKey(relPath)` is the one graph-key mint — always `/`-separated, because the keys are built two ways (entry-name concatenation vs `path.relative`) and Windows spells the second one with `\`, which silently dropped every edge into a subdirectory module and made the acyclicity guards pass vacuously there (#5909). Static imports only — `await import()` is deferred and can't create a load-time cycle or drag a native dep into an init graph. Shared by `serviceImportCycles.test.js` (the tree-wide cycle ratchet), `agentImportCycles.test.js` and `twinImportCycles.test.js` (per-cluster acyclicity) and `spriteAnimationTracks.test.js` (the request-validation graph reaches no sharp/ffmpeg). |-| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. `createJobFailureFinalizer({ jobs, activeJobs, activeSlots, label, events, failedPayload? })` — the shared job-failure finalizer (idempotency guard w/ `force` escape hatch, slot-owner clear, SSE error frame, `failed` event, `closeJobAfterDelay`) behind all six media-generation backends (`imageGen/{agy,codex,grok}.js`, `videoGen/{grok,fal,reactor}.js`). |+| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. `createJobFailureFinalizer({ jobs, activeJobs, activeSlots, label, events, failedPayload? })` — the shared job-failure finalizer (idempotency guard w/ `force` escape hatch, slot-owner clear, SSE error frame, `failed` event, `closeJobAfterDelay`, plus a `.canceled(job, jobId, slotOwner?)` convenience) behind all six media-generation backends (`imageGen/{agy,codex,grok}.js`, `videoGen/{grok,fal,reactor}.js`). || `streamAttachment.js` | `streamAttachment(res,stream,{filename,contentType,failure,label})` — pipe a readable to a response as a file download. Sets the attachment headers plus `X-Content-Type-Options:nosniff`, and owns the teardown every attachment route needs: a pre-stream failure drops the download headers and returns `failure` via `sendErrorResponse`, a mid-stream failure destroys the socket (the envelope no-ops once headers are sent), and a client disconnect calls `stream.abort?.()` so an upstream child process is torn down. Shared by `routes/imageTo3d.js` (GLB, full-mesh) and `routes/backup.js` (snapshot tarball). || `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). || `streamingSpawn.js` | `runStreamingCommand(cmd, args, onLine, {timeoutMs?, cwd?, env?, splitRe?})` — run one command to completion and forward its stdout/stderr LINES to a hook, resolving `{ success, error? }`. Never rejects (spawn error, non-zero exit, and timeout all resolve as `success: false`) because every caller is an install/setup flow running outside the Express request lifecycle, and the `onLine` hook is guarded for the same reason. A failure carries the last ~1KB of streamed output, so `brew upgrade ollama` exiting 1 with "Error: ollama not installed" surfaces that string instead of "exited with code 1". Shared by `services/localLlm.js`'s package-manager installs and `services/localRuntimeSetup.js`'s one-click daemon setup. `splitRe` is forwarded to the line readers — pass `/[\r\n]+/` for a downloader whose progress bar redraws one line with a bare `\r`, or the stream goes silent for the whole download. `isCancelled` is polled once a second and SIGKILLs the child when it turns true (resolving `{success:false, error:'cancelled'}`) — required for a command that can run for hours while the caller holds a lock until it settles; a throwing predicate is logged and read as "not cancelled" rather than crashing the process from a timer callback. `bufferedSpawn.js` is the sibling for run-and-collect; use this one when live output IS the progress. |diff --git a/server/lib/sseUtils.js b/server/lib/sseUtils.jsindex 284742bd04..4cad454374 100644--- a/server/lib/sseUtils.js+++ b/server/lib/sseUtils.js@@ -111,22 +111,31 @@ export const closeJobAfterDelay = (jobs, jobId, delay = SSE_CLEANUP_DELAY_MS, ex// It defaults to the video shape (`{ generationId, error }`); the image// backends override it to add the `mode` field their event bus carries// (read by `imageGenQuota.js`'s per-provider outcome recorder).+//+// The returned function also carries a `.canceled(job, jobId, slotOwner?)`+// convenience — `fal.js` and `reactor.js` each defined an identical+// `finalizeCanceled = (job, jobId) => finalize(job, jobId, null, 'Canceled',+// { force: true })` wrapper; this puts that one place instead of two.export const createJobFailureFinalizer = ({jobs, activeJobs, activeSlots, label, events,failedPayload = (jobId, reason) => ({ generationId: jobId, error: reason }),-}) => (job, jobId, slotOwner, reason, { force = false } = {}) => {- // Idempotent except under `force` — spawn failures fire 'error' AND a- // follow-up 'close', so both paths reach this finalizer, and a caller- // whose success path can throw AFTER stamping 'complete' passes `force`- // to still deliver a terminal 'failed' for that window.- if (!force && (job.status === 'error' || job.status === 'complete')) return;- if (slotOwner == null || activeSlots.get(jobId) === slotOwner) activeSlots.delete(jobId);- job.status = 'error';- activeJobs.delete(jobId);- console.log(`❌ ${label} failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);- broadcastSse(job, { type: 'error', error: reason });- events.emit('failed', failedPayload(jobId, reason));- closeJobAfterDelay(jobs, jobId);+}) => {+ const finalize = (job, jobId, slotOwner, reason, { force = false } = {}) => {+ // Idempotent except under `force` — spawn failures fire 'error' AND a+ // follow-up 'close', so both paths reach this finalizer, and a caller+ // whose success path can throw AFTER stamping 'complete' passes `force`+ // to still deliver a terminal 'failed' for that window.+ if (!force && (job.status === 'error' || job.status === 'complete')) return;+ if (slotOwner == null || activeSlots.get(jobId) === slotOwner) activeSlots.delete(jobId);+ job.status = 'error';+ activeJobs.delete(jobId);+ console.log(`❌ ${label} failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);+ broadcastSse(job, { type: 'error', error: reason });+ events.emit('failed', failedPayload(jobId, reason));+ closeJobAfterDelay(jobs, jobId);+ };+ finalize.canceled = (job, jobId, slotOwner = null) => finalize(job, jobId, slotOwner, 'Canceled', { force: true });+ return finalize;};// ---------------------------------------------------------------------------diff --git a/server/lib/sseUtils.test.js b/server/lib/sseUtils.test.jsindex 0a7e4f92ed..4512b56c64 100644--- a/server/lib/sseUtils.test.js+++ b/server/lib/sseUtils.test.js@@ -286,6 +286,32 @@ describe('createJobFailureFinalizer', () => {expect(events.emit).toHaveBeenCalledWith('failed', { mode: 'grok', generationId: 'j1', error: 'boom' });});++ it('.canceled forces a "Canceled" failure past the idempotency guard (fal.js/reactor.js cancel path)', () => {+ const { activeSlots, events, finalize } = setup();+ const job = { clients: [], status: 'running' };+ activeSlots.set('j1', { some: 'request-entry' });++ finalize.canceled(job, 'j1');++ expect(job.status).toBe('error');+ expect(activeSlots.has('j1')).toBe(false);+ expect(events.emit).toHaveBeenCalledWith('failed', { generationId: 'j1', error: 'Canceled' });+ });++ it('.canceled accepts an optional slotOwner for a backend that does track one', () => {+ const { activeSlots, finalize } = setup();+ const owner = { pid: 1 };+ const otherOwner = { pid: 2 };+ const job = { clients: [], status: 'running' };+ activeSlots.set('j1', otherOwner);++ finalize.canceled(job, 'j1', owner);++ // A cancel from a stale owner must not evict a newer run's slot, same+ // guard as the base finalizer.+ expect(activeSlots.get('j1')).toBe(otherOwner);+ });});describe('createSseRunner', () => {diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.jsindex f9f56b7dde..47c89e9207 100644--- a/server/services/imageGen/agy.js+++ b/server/services/imageGen/agy.js@@ -402,11 +402,8 @@ async function runAgy(job, jobId, bin, args, {closeJobAfterDelay(jobs, jobId);} catch (err) {removeScratch();- // finalizeJobFailure is a no-op once job.status === 'complete' — but the- // success path above stamps 'complete' BEFORE its own broadcastSse/- // event-emit tail, so a throw from there still needs a terminal- // 'failed' delivered. Force past the idempotency guard (matches- // videoGen/grok.js's post-exit catch, fa3796650).+ // force: true — 'complete' is already stamped above; see+ // createJobFailureFinalizer's doc comment in sseUtils.js.finalizeJobFailure(job, jobId, proc, `Agy post-exit handler failed: ${err?.message || err}`, { force: true });}});diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex fb02d34860..f4e4c362df 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -450,11 +450,8 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleimageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.CODEX, generationId: jobId, path: `/data/images/${filename}`, filename });closeJobAfterDelay(jobs, jobId);} catch (err) {- // finalizeJobFailure is a no-op once job.status === 'complete' — but the- // success path above stamps 'complete' BEFORE its own broadcastSse/- // event-emit tail, so a throw from there still needs a terminal- // 'failed' delivered. Force past the idempotency guard (matches- // videoGen/grok.js's post-exit catch, fa3796650).+ // force: true — 'complete' is already stamped above; see+ // createJobFailureFinalizer's doc comment in sseUtils.js.finalizeJobFailure(job, jobId, proc, `Codex post-exit handler failed: ${err?.message || err}`, { force: true });}});diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.jsindex 7e6d4f4db8..67b2eb7ac6 100644--- a/server/services/imageGen/codex.test.js+++ b/server/services/imageGen/codex.test.js@@ -579,7 +579,7 @@ describe('codex provider — image harvest', () => {// configurable in ESM. macOS/Linux are the platforms PortOS actually// runs on; this regression-locks the fix where it matters.const itPosix = process.platform === 'win32' ? it.skip : it;- itPosix('routes async errors in the close handler through finalizeError (no unhandled rejections)', async () => {+ itPosix('routes async errors in the close handler through finalizeJobFailure (no unhandled rejections)', async () => {const sessionId = '11111111-1111-4111-8111-111111111111';const codexDir = join(TEST_HOME, '.codex', 'generated_images', sessionId);await mkdir(codexDir, { recursive: true });diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.jsindex d199b05997..533d20ef81 100644--- a/server/services/imageGen/grok.js+++ b/server/services/imageGen/grok.js@@ -431,11 +431,8 @@ async function runGrok(job, jobId, bin, args, {closeJobAfterDelay(jobs, jobId);} catch (err) {removeScratch();- // finalizeJobFailure is a no-op once job.status === 'complete' — but the- // success path above stamps 'complete' BEFORE its own broadcastSse/- // event-emit tail, so a throw from there still needs a terminal- // 'failed' delivered. Force past the idempotency guard (matches- // videoGen/grok.js's post-exit catch, fa3796650).+ // force: true — 'complete' is already stamped above; see+ // createJobFailureFinalizer's doc comment in sseUtils.js.finalizeJobFailure(job, jobId, proc, `Grok post-exit handler failed: ${err?.message || err}`, { force: true });}});diff --git a/server/services/videoGen/fal.js b/server/services/videoGen/fal.jsindex ca6f225c2b..9c1d125892 100644--- a/server/services/videoGen/fal.js+++ b/server/services/videoGen/fal.js@@ -23,7 +23,7 @@ import { ensureDir, PATHS } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';import { detectImageFormat } from '../../lib/mimeTypes.js';-import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';+import { attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';import { videoGenEvents } from './events.js';import { finalizeGeneratedVideo, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';import { mutateVideoHistory } from './history.js';@@ -277,8 +277,6 @@ async function runFalVideo(job, jobId, { apiKey, modelId, prompt, negativePrompt}}-const finalizeCanceled = (job, jobId) => finalizeJobFailure(job, jobId, null, 'Canceled', { force: true });-const finalizeJobFailure = createJobFailureFinalizer({jobs,activeJobs,@@ -286,6 +284,7 @@ const finalizeJobFailure = createJobFailureFinalizer({label: 'fal video generation',events: videoGenEvents,});+const finalizeCanceled = finalizeJobFailure.canceled;// Test-only handles.export const _internals = {diff --git a/server/services/videoGen/grok.js b/server/services/videoGen/grok.jsindex 2a3ddd2a7d..32eebaaef0 100644--- a/server/services/videoGen/grok.js+++ b/server/services/videoGen/grok.js@@ -28,7 +28,7 @@ import { tmpdir } from 'os';import { randomUUID } from 'crypto';import { ensureDir, PATHS, copyFileGuarded, unlinkGuarded, rmGuarded } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';-import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';+import { attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';import { killWithEscalation } from '../../lib/killWithEscalation.js';import { killProcessTree, prepareCliSpawn } from '../../lib/bufferedSpawn.js';import { ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../../lib/grok.js';diff --git a/server/services/videoGen/reactor.js b/server/services/videoGen/reactor.jsindex b397af6a1e..72b88253ab 100644--- a/server/services/videoGen/reactor.js+++ b/server/services/videoGen/reactor.js@@ -6,7 +6,7 @@ import { join } from 'path';import { ensureDir, PATHS } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';-import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';+import { attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';import { videoGenEvents } from './events.js';import { finalizeGeneratedVideo, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';import { mutateVideoHistory } from './history.js';@@ -329,8 +329,6 @@ async function runReactorVideo(job, jobId, {}}-const finalizeCanceled = (job, jobId) => finalizeJobFailure(job, jobId, null, 'Canceled', { force: true });-const finalizeJobFailure = createJobFailureFinalizer({jobs,activeJobs,@@ -338,6 +336,7 @@ const finalizeJobFailure = createJobFailureFinalizer({label: 'reactor video generation',events: videoGenEvents,});+const finalizeCanceled = finalizeJobFailure.canceled;// Test-only handles.export const _internals = { validateRequest: validateReactorRequest };