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([issue-1956]): extract shared SIGTERM→SIGKILL kill-escalation helper for spawn-based jobs

[._.]/ Adam Eivy539c3b3dcaaf
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8af667c9a4..4c1e70cd1f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -117,3 +117,5 @@
- **[issue-1876] Consolidated four private XML-entity decoders into a shared `server/lib/xmlEntities.js`** — `decodeXmlEntities`/`decodeEntities`/inline `stripHtml` had drifted into near-identical copies across `appleHealthXmlParser.js`, `claudeChangelog.js`, `pinterestFeed.js`, `feeds.js`, and `messageGmailSync.js`, so an entity-handling fix had to be applied in up to five places. The most complete implementation (named + decimal `&#NN;` + hex `&#xNN;` via a single double-decode-safe pass, out-of-range-tolerant) is promoted to a shared, barrel-registered helper that also takes an optional extra-named-entity map (`{ nbsp: ' ', zwnj: '' }`) for the mail-specific entities Gmail's HTML-to-text needs; every call site now imports it. Behavior-preserving (each site's existing tests pass on the shared single-pass decoder); covered by a new `xmlEntities.test.js`. (#1876)
- **[issue-1847] Added tests for four sync-critical pure modules that shipped without one** — `server/lib/lwwTimestamp.js` (the last-writer-wins polarity behind every cross-instance merge), `server/lib/pgTimestamp.js` (`mirrorTimestamp`'s TIMESTAMPTZ bind-safety guards), `server/lib/agentGuard/index.js` (`agentGuardEnv`'s PATH-prepend + `PORTOS_REAL_PM2` pm2-kill shim), and the previously-untested `providerSchema`/`validate` exports of `server/lib/aiToolkit/validation.js`. Coverage hits the real branch points: `parseTsMs` non-string/unparseable returns, `compareNewerWins`/`compareEarlierWins` tie + unparseable-side + ISO-vs-non-ISO + antisymmetry; `mirrorTimestamp` calendar-rollover normalization, year-0000 rejection, ±expanded-year rejection, 0001/9999 bounds; `agentGuardEnv` guard-dir-first PATH order, `Path` fallback, real-pm2 resolution, plus the `bin/pm2` bash shim's actual block behavior (spawns the shim with a stub real-pm2 to assert `pm2 kill`/`startup`/`unstartup` and `delete/stop/restart all` are blocked case-insensitively while scoped/read-only commands pass through, and the no-pm2-found 127 path); `providerSchema` endpoint `''`/`null`→undefined coercion, id slug regex + 80-char max, `numCtx` 512–1048576 bounds, and `validate`'s `{path, message}` error shape. Tests only. (#1847)
- **[self-improvement] CoS's auto-approved error-investigation tasks now require human review, matching the rest of the codebase's error-driven task creators** — two task creators auto-approved an unsupervised agent to start editing code from thin diagnostic evidence: `autoFixer.js`'s `createAutoFixTask` (triggered by `severity: 'critical'` or `canAutoFix`, covering bare `uncaughtException`/`unhandledRejection` — no repro steps, no live process state, since the process already crashed) and `agentManagement.js`'s orphan-retry investigation task (triggered after repeated agent-orphaning, an infra/process-flakiness signal rather than a diagnosed code bug). Every other error-driven task creator (`createAIProviderInvestigationTask`, `handleErrorRecovery`, `agentErrorAnalysis.js`'s `createInvestigationTask`) already required approval first; these two were the outliers, and both shipped with zero test coverage for this branch. CoS's own `learning.json` history bears this out — this task class runs rarely and has a materially worse success rate than the reviewed-first paths. Flipped both to `approvalRequired: true` and added coverage for the previously-untested branches (approval flag, trigger conditions, skip paths, dedupe).
+
+- **[issue-1956] Extracted a shared SIGTERM→grace→SIGKILL kill-escalation helper for spawn-based jobs** — the identical "SIGTERM, then after 8s escalate to SIGKILL if the tracked child hasn't exited" cancel block was copy-pasted across seven job-cancel paths (`musicVideo/render.js`, `videoTimeline/local.js`, `imageGen/local.js`, `imageGen/codex.js`, `videoGen/local.js`, `loraTraining/index.js`, `trackYoutubeImport.js`). It now lives in one place — `killWithEscalation(proc, { label, stillRunning, delayMs=8000 })` (`server/lib/killWithEscalation.js`) — which preserves each site's exact guard (`job.process === proc` / `activeProcess === proc` / `activeProcs.get(id) === proc`), its exit check (`exitCode === null && signalCode === null`), and its emoji-prefixed single-line warning, while wrapping the out-of-request-lifecycle `setTimeout` callback in try/catch and unref'ing the timer (codex passes `delayMs: 5000`). Behavior-preserving consolidation; covered by a new `killWithEscalation.test.js`. (#1956)
diff --git a/server/lib/README.md b/server/lib/README.md
index 548f17f679..15ff86dbc3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -143,6 +143,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — pure GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. |
| `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. |
| `gitRemote.js` | `getOriginInfo`, `parseGitRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — classifies the local `origin` remote vs the upstream atomantic/PortOS repo. Used by the update flow to detect forks. |
+| `killWithEscalation.js` | `killWithEscalation(proc, {label, stillRunning, delayMs=8000})` — shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs. Sends SIGTERM, then escalates to SIGKILL after `delayMs` only when `stillRunning()` holds and the child hasn't exited (`exitCode===null && signalCode===null`). The timer is unref'd and the callback is try/catch-wrapped (runs outside the request lifecycle). Converges musicVideo/render, videoTimeline, imageGen local+codex, videoGen, loraTraining, and the yt-dlp track import cancel paths. |
| `processEnv.js` | `stripDebugMallocEnv(env)` — drop macOS `Malloc*` debug env vars before spawning a child. Pinokio-launched PortOS exports `MallocStackLogging`/`MallocScribble`/etc. that flood Python subprocess stderr with `can't turn off malloc stack logging` lines; route every Node→Python spawn through this. No-op on Linux/Windows. |
| `pythonSetup.js` | Python venv / runner setup helpers. |
| `ytdlp.js` | `findYtDlp()` — cached discovery of the `yt-dlp` binary on PATH, mirrors `findFfmpeg()` in `ffmpeg.js`. Used by the track YouTube-import job. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 1d0c0b011d..2ae68402aa 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -133,6 +133,7 @@ export * from './gitArgs.js';
export * from './gitForge.js';
export * from './gitOutputParsers.js';
export * from './gitRemote.js';
+export * from './killWithEscalation.js';
export * from './openFolder.js';
export * from './processEnv.js';
export * from './pythonSetup.js';
diff --git a/server/lib/killWithEscalation.js b/server/lib/killWithEscalation.js
new file mode 100644
index 0000000000..de7f9518fd
--- /dev/null
+++ b/server/lib/killWithEscalation.js
@@ -0,0 +1,47 @@
+/**
+ * Shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs.
+ *
+ * Every spawn-based job service (musicVideo/render, videoTimeline/local,
+ * imageGen/local, imageGen/codex, videoGen/local, loraTraining, the yt-dlp
+ * track import) cancels an in-flight child the same way: SIGTERM first, then
+ * escalate to SIGKILL after a grace window IFF the tracked process is still the
+ * one we spawned and hasn't exited yet. This helper is that single convention
+ * so new job services converge here instead of re-copying the block by hand.
+ *
+ * Semantics preserved verbatim from the pre-existing call sites:
+ * - `proc.kill('SIGTERM')` is sent synchronously.
+ * - After `delayMs`, escalate to SIGKILL only when BOTH the caller's
+ * `stillRunning()` guard holds (e.g. `job.process === proc`, so a replaced
+ * or already-cleared handle is left alone) AND the child hasn't exited
+ * (`proc.exitCode === null && proc.signalCode === null` — `proc.killed` is
+ * set the moment `kill()` is called and does NOT mean the child exited).
+ *
+ * The escalation runs in a `setTimeout` OUTSIDE the Express request lifecycle,
+ * so the callback is wrapped in try/catch (an uncaught throw there would crash
+ * the Node process — there is no `next(err)` to bubble to). The timer is
+ * `unref()`'d so a pending escalation can't hold the event loop open.
+ *
+ * @param {import('child_process').ChildProcess} proc - the child to terminate.
+ * @param {object} opts
+ * @param {string} opts.label - per-site label for the warning log (e.g.
+ * `music-video render`, `image child`, `yt-dlp import`).
+ * @param {() => boolean} opts.stillRunning - predicate reproducing the caller's
+ * guard; escalation is skipped when it returns false.
+ * @param {number} [opts.delayMs=8000] - grace window before SIGKILL.
+ * @returns {NodeJS.Timeout} the escalation timer (already unref'd).
+ */
+export function killWithEscalation(proc, { label, stillRunning, delayMs = 8000 }) {
+ proc.kill('SIGTERM');
+ const timer = setTimeout(() => {
+ try {
+ if (stillRunning() && proc.exitCode === null && proc.signalCode === null) {
+ console.log(`⚠️ ${label} didn't exit on SIGTERM — escalating to SIGKILL`);
+ proc.kill('SIGKILL');
+ }
+ } catch (err) {
+ console.error(`❌ ${label} SIGKILL escalation failed: ${err.message}`);
+ }
+ }, delayMs);
+ timer.unref?.();
+ return timer;
+}
diff --git a/server/lib/killWithEscalation.test.js b/server/lib/killWithEscalation.test.js
new file mode 100644
index 0000000000..cfdc04ff76
--- /dev/null
+++ b/server/lib/killWithEscalation.test.js
@@ -0,0 +1,106 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { killWithEscalation } from './killWithEscalation.js';
+
+// A minimal ChildProcess stand-in: exitCode/signalCode default to null (still
+// running); kill() records the signal and, for SIGTERM/SIGKILL, flips the
+// matching field so the escalation guard reflects a real exit.
+const makeProc = () => {
+ const proc = {
+ exitCode: null,
+ signalCode: null,
+ kill: vi.fn((sig) => {
+ if (sig === 'SIGKILL') proc.signalCode = 'SIGKILL';
+ return true;
+ }),
+ };
+ return proc;
+};
+
+describe('killWithEscalation', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+ afterEach(() => {
+ vi.runOnlyPendingTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it('sends SIGTERM synchronously', () => {
+ const proc = makeProc();
+ killWithEscalation(proc, { label: 'test job', stillRunning: () => true });
+ expect(proc.kill).toHaveBeenCalledTimes(1);
+ expect(proc.kill).toHaveBeenCalledWith('SIGTERM');
+ });
+
+ it('escalates to SIGKILL after the default 8s grace when still running', () => {
+ const proc = makeProc();
+ killWithEscalation(proc, { label: 'test job', stillRunning: () => true });
+ // Not yet past the grace window.
+ vi.advanceTimersByTime(7999);
+ expect(proc.kill).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(1);
+ expect(proc.kill).toHaveBeenCalledTimes(2);
+ expect(proc.kill).toHaveBeenLastCalledWith('SIGKILL');
+ expect(console.log).toHaveBeenCalledWith(
+ expect.stringContaining("test job didn't exit on SIGTERM"),
+ );
+ });
+
+ it('honors a custom delayMs', () => {
+ const proc = makeProc();
+ killWithEscalation(proc, { label: 'codex child', delayMs: 5000, stillRunning: () => true });
+ vi.advanceTimersByTime(4999);
+ expect(proc.kill).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(1);
+ expect(proc.kill).toHaveBeenLastCalledWith('SIGKILL');
+ });
+
+ it('does NOT escalate when the process already exited (exitCode set)', () => {
+ const proc = makeProc();
+ killWithEscalation(proc, { label: 'test job', stillRunning: () => true });
+ proc.exitCode = 0; // child exited on SIGTERM
+ vi.advanceTimersByTime(8000);
+ expect(proc.kill).toHaveBeenCalledTimes(1); // SIGTERM only
+ expect(proc.kill).not.toHaveBeenCalledWith('SIGKILL');
+ });
+
+ it('does NOT escalate when the process already exited via signal', () => {
+ const proc = makeProc();
+ killWithEscalation(proc, { label: 'test job', stillRunning: () => true });
+ proc.signalCode = 'SIGTERM'; // terminated by the SIGTERM
+ vi.advanceTimersByTime(8000);
+ expect(proc.kill).toHaveBeenCalledTimes(1);
+ });
+
+ it('does NOT escalate when stillRunning() returns false (handle replaced/cleared)', () => {
+ const proc = makeProc();
+ let running = true;
+ killWithEscalation(proc, { label: 'test job', stillRunning: () => running });
+ running = false; // e.g. job.process was reassigned or cleared on close
+ vi.advanceTimersByTime(8000);
+ expect(proc.kill).toHaveBeenCalledTimes(1);
+ expect(proc.kill).not.toHaveBeenCalledWith('SIGKILL');
+ });
+
+ it('swallows a throw from the escalation callback (runs outside request lifecycle)', () => {
+ const proc = makeProc();
+ proc.kill = vi.fn((sig) => {
+ if (sig === 'SIGKILL') throw new Error('boom');
+ return true;
+ });
+ killWithEscalation(proc, { label: 'test job', stillRunning: () => true });
+ // Advancing must not throw out of the fake-timer flush.
+ expect(() => vi.advanceTimersByTime(8000)).not.toThrow();
+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('SIGKILL escalation failed'));
+ });
+
+ it('unref()s the escalation timer so it cannot hold the event loop open', () => {
+ const proc = makeProc();
+ const timer = killWithEscalation(proc, { label: 'test job', stillRunning: () => true });
+ // Node timers expose unref(); assert we returned a timer handle.
+ expect(timer).toBeDefined();
+ });
+});
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index e86bf43696..b506fe7e11 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -31,6 +31,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { IMAGE_GEN_MODE } from './modes.js';
// 20 minutes — built-in `image_gen` typically returns in 30–90s, but with the
@@ -68,15 +69,8 @@ export const getActiveJob = () => {
export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);
-const sigtermWithEscalation = (id, proc) => {
- proc.kill('SIGTERM');
- setTimeout(() => {
- if (activeProcs.get(id) === proc && proc.exitCode === null && proc.signalCode === null) {
- console.log(`⚠️ codex child didn't exit on SIGTERM — escalating to SIGKILL`);
- proc.kill('SIGKILL');
- }
- }, 5000);
-};
+const sigtermWithEscalation = (id, proc) =>
+ killWithEscalation(proc, { label: 'codex child', delayMs: 5000, stillRunning: () => activeProcs.get(id) === proc });
// Cancel one specific codex render. jobId is required — with parallel codex
// renders an "anonymous cancel" is genuinely destructive (would nuke every
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 3384aa1719..4aa110f73c 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -28,6 +28,7 @@ import { resolveFlux2Python, FLUX2_VENV_DEFAULT } from '../../lib/pythonSetup.js
import { hfTokenEnv } from '../../lib/hfToken.js';
import { extractGatedRepo } from '../../lib/hfErrors.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
+import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { IMAGE_GEN_MODE } from './modes.js';
import { computePixelDelta } from './regen.js';
@@ -57,20 +58,12 @@ export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);
export const cancel = () => {
if (!activeProcess) return false;
const proc = activeProcess;
- proc.kill('SIGTERM');
// KEEP activeProcess + activeJob set until proc.on('close') clears them.
// Otherwise BUSY immediately allows a new generation while the SIGTERM'd
// mflux child is still running, and we lose the handle for a follow-up
- // SIGKILL. Escalate after 8s if the child ignored SIGTERM.
- setTimeout(() => {
- // proc.killed is set the moment proc.kill() is called; it does NOT mean
- // the child has exited. Check exitCode (null until 'close' fires) so the
- // SIGKILL escalation actually triggers when mflux ignores SIGTERM.
- if (activeProcess === proc && proc.exitCode === null && proc.signalCode === null) {
- console.log(`⚠️ image child didn't exit on SIGTERM — escalating to SIGKILL`);
- proc.kill('SIGKILL');
- }
- }, 8000);
+ // SIGKILL. The `activeProcess === proc` guard escalates only when this is
+ // still the tracked child (mflux can ignore SIGTERM mid-tensor-op).
+ killWithEscalation(proc, { label: 'image child', stillRunning: () => activeProcess === proc });
return true;
};
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index eb01656ab6..c6a29699b3 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -24,6 +24,7 @@ import { v4 as uuidv4 } from '../../lib/uuid.js';
import { hfTokenEnv } from '../../lib/hfToken.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { spawnDetached, reapDetached, reattachDetached, isReattachable } from '../../lib/detachedSpawn.js';
+import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { getImageModels } from '../../lib/mediaModels.js';
import { resolveFlux2Python, isFlux2VenvHealthy } from '../../lib/pythonSetup.js';
import { getSettings } from '../settings.js';
@@ -98,15 +99,9 @@ const STALL_TICK_MS = 30_000;
export const cancel = (jobId) => {
if (!activeProcess || (jobId && activeJobId !== jobId)) return false;
const proc = activeProcess;
- proc.kill('SIGTERM');
// Keep activeProcess set until 'close' clears it — the trainer may spend
// a few seconds writing its cancel checkpoint. Escalate after 8s.
- setTimeout(() => {
- if (activeProcess === proc && proc.exitCode === null && proc.signalCode === null) {
- console.log('⚠️ training child ignored SIGTERM — escalating to SIGKILL');
- proc.kill('SIGKILL');
- }
- }, 8000).unref?.();
+ killWithEscalation(proc, { label: 'training child', stillRunning: () => activeProcess === proc });
return true;
};
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index 54fa1552f1..a49726dfb8 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -30,6 +30,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
import { findFfmpeg, safeUnder, generateThumbnail, probeVideoDuration } from '../../lib/ffmpeg.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
+import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { loadHistory, saveHistory } from '../videoGen/local.js';
import { getTrack } from '../tracks/index.js';
import { getProject, updateProject } from './projects.js';
@@ -75,13 +76,7 @@ export function cancelRender(jobId) {
const job = jobs.get(jobId);
if (!job || !job.process) return false;
const proc = job.process;
- proc.kill('SIGTERM');
- setTimeout(() => {
- if (job.process === proc && proc.exitCode === null && proc.signalCode === null) {
- console.log(`⚠️ music-video render didn't exit on SIGTERM — escalating to SIGKILL`);
- proc.kill('SIGKILL');
- }
- }, 8000);
+ killWithEscalation(proc, { label: 'music-video render', stillRunning: () => job.process === proc });
return true;
}
diff --git a/server/services/trackYoutubeImport.js b/server/services/trackYoutubeImport.js
index ffc6b84b5c..c4dac6217a 100644
--- a/server/services/trackYoutubeImport.js
+++ b/server/services/trackYoutubeImport.js
@@ -24,6 +24,7 @@ import { findFfmpeg, probeVideoDuration } from '../lib/ffmpeg.js';
import { findYtDlp } from '../lib/ytdlp.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';
import { safeChildProcessEnv } from '../lib/processEnv.js';
+import { killWithEscalation } from '../lib/killWithEscalation.js';
import { importUploadedTrack, MUSIC_UPLOAD_MAX_BYTES } from './pipeline/musicLibrary.js';
import { createTrack, DURATION_MAX_SEC } from './tracks/index.js';
@@ -52,13 +53,7 @@ export function cancelYoutubeImport(jobId) {
const job = importJobs.get(jobId);
if (!job || !job.process) return false;
const proc = job.process;
- proc.kill('SIGTERM');
- setTimeout(() => {
- if (job.process === proc && proc.exitCode === null && proc.signalCode === null) {
- console.log(`⚠️ yt-dlp import didn't exit on SIGTERM — escalating to SIGKILL`);
- proc.kill('SIGKILL');
- }
- }, 8000);
+ killWithEscalation(proc, { label: 'yt-dlp import', stillRunning: () => job.process === proc });
return true;
}
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 3143258410..d6bac16edc 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -19,6 +19,7 @@ import { randomUUID } from 'crypto';
import { promisify } from 'util';
import { ensureDir, PATHS, UUID_RE } from '../../lib/fileUtils.js';
import { spawnDetached } from '../../lib/detachedSpawn.js';
+import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { ServerError } from '../../lib/errorHandler.js';
import { videoGenEvents } from './events.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
@@ -111,20 +112,12 @@ export const cancel = () => {
if (activeChain) activeChain.stopped = true;
if (!activeProcess) return !!activeChain;
const proc = activeProcess;
- proc.kill('SIGTERM');
// KEEP activeProcess set until proc.on('close') clears it. Without this,
// the BUSY guard immediately allows a new generation while the SIGTERM'd
// child is still running (mlx_video can ignore SIGTERM mid-tensor-op),
- // and we'd lose the handle for a follow-up SIGKILL. Escalate after 8s.
- setTimeout(() => {
- // proc.killed is set the moment proc.kill() is called; it does NOT mean
- // the child has exited. Check exitCode (null until 'close' fires) so the
- // SIGKILL escalation actually triggers when mlx_video ignores SIGTERM.
- if (activeProcess === proc && proc.exitCode === null && proc.signalCode === null) {
- console.log(`⚠️ video child didn't exit on SIGTERM — escalating to SIGKILL`);
- proc.kill('SIGKILL');
- }
- }, 8000);
+ // and we'd lose the handle for a follow-up SIGKILL. The `activeProcess ===
+ // proc` guard escalates only when this is still the tracked child.
+ killWithEscalation(proc, { label: 'video child', stillRunning: () => activeProcess === proc });
return true;
};
diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.js
index d9cc997929..7d3d931e64 100644
--- a/server/services/videoTimeline/local.js
+++ b/server/services/videoTimeline/local.js
@@ -23,6 +23,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
import { findFfmpeg, findFfprobe, safeUnder, generateThumbnail } from '../../lib/ffmpeg.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
+import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { loadHistory, saveHistory } from '../videoGen/local.js';
const PROJECTS_FILE = join(PATHS.data, 'video-projects.json');
@@ -323,13 +324,7 @@ export function cancelRender(jobId) {
const job = jobs.get(jobId);
if (!job || !job.process) return false;
const proc = job.process;
- proc.kill('SIGTERM');
- setTimeout(() => {
- if (job.process === proc && proc.exitCode === null && proc.signalCode === null) {
- console.log(`⚠️ ffmpeg render didn't exit on SIGTERM — escalating to SIGKILL`);
- proc.kill('SIGKILL');
- }
- }, 8000);
+ killWithEscalation(proc, { label: 'ffmpeg render', stillRunning: () => job.process === proc });
return true;
}