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

fix: consolidate code quality maintenance paths

[._.]/ Adam Eivy881f68d5f7b0
diff --git a/server/lib/editorial/repetition.js b/server/lib/editorial/repetition.js
index d1fcd1042f..37c82a3303 100644
--- a/server/lib/editorial/repetition.js
+++ b/server/lib/editorial/repetition.js
@@ -28,8 +28,6 @@ const STOPWORDS = new Set([
'now', 'said', 'like', 'back', 'get', 'got',
]);
-const isEchoCandidate = (lower) => lower.length >= 5 && !STOPWORDS.has(lower);
-
/**
* Distinctive words repeated within a window of `windowWords` tokens. Returns
* one finding per repeated word (the SECOND occurrence — the echo — anchored),
diff --git a/server/routes/scaffoldIOS.js b/server/routes/scaffoldIOS.js
index 5c3faa8f14..f3244b6345 100644
--- a/server/routes/scaffoldIOS.js
+++ b/server/routes/scaffoldIOS.js
@@ -1,11 +1,10 @@
-import { writeFile } from 'fs/promises';
+import { chmod, writeFile } from 'fs/promises';
import { join } from 'path';
-import { exec } from '../lib/childProcess.js';
-import { promisify } from 'util';
import { ensureDir, ensureDirs } from '../lib/fileUtils.js';
-import { XCODE_TEAM_ID, XCODE_BUNDLE_PREFIX, toBundleId, toTargetName } from '../services/xcodeScripts.js';
-
-const execAsync = promisify(exec);
+import {
+ XCODE_TEAM_ID, XCODE_BUNDLE_PREFIX, XCODE_ENV_EXAMPLE,
+ generateDeployScript, toBundleId, toTargetName,
+} from '../services/xcodeScripts.js';
export async function scaffoldIOS(repoPath, name, dirName, addStep) {
const bundleId = toBundleId(name);
@@ -148,168 +147,11 @@ final class ${targetName}Tests: XCTestCase {
}
`);
- // .env.example
- await writeFile(join(repoPath, '.env.example'), `TEAM_ID=${teamId}
-APPSTORE_API_KEY_ID=YOUR_KEY_ID
-APPSTORE_ISSUER_ID=YOUR_ISSUER_ID
-APPSTORE_API_PRIVATE_KEY_PATH=~/Library/Mobile Documents/com~apple~CloudDocs/AppDev/AuthKey_XXXXXXXXXX.p8
-`);
-
- // deploy.sh (TestFlight local deploy)
- const deployScript = `#!/bin/bash
-set -euo pipefail
-
-# ${name} - Local TestFlight Deploy
-# Usage: ./deploy.sh [--skip-tests]
-
-SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
-cd "$SCRIPT_DIR"
-
-# Load environment
-if [ -f .env ]; then
- set -a
- source .env
- set +a
-else
- echo "❌ .env file not found. Copy .env.example to .env and fill in values."
- exit 1
-fi
-
-KEY_PATH="$APPSTORE_API_PRIVATE_KEY_PATH"
-
-if [ ! -f "$KEY_PATH" ]; then
- echo "❌ API key not found at: $KEY_PATH"
- exit 1
-fi
-
-# Ensure altool can find the key
-mkdir -p ~/.private_keys
-KEY_FILENAME="AuthKey_\${APPSTORE_API_KEY_ID}.p8"
-if [ ! -f ~/.private_keys/"$KEY_FILENAME" ]; then
- ln -sf "$KEY_PATH" ~/.private_keys/"$KEY_FILENAME"
- echo "🔑 Symlinked API key to ~/.private_keys/"
-fi
-
-PROJECT="${targetName}.xcodeproj"
-SCHEME="${targetName}"
-BUILD_DIR="$SCRIPT_DIR/build"
-ARCHIVE_PATH="$BUILD_DIR/$SCHEME.xcarchive"
-EXPORT_PATH="$BUILD_DIR/export"
-
-# Auto-increment build number
-CURRENT_BUILD=$(grep CURRENT_PROJECT_VERSION project.yml | head -1 | awk '{print $2}')
-NEW_BUILD=$((CURRENT_BUILD + 1))
-echo "📦 Build number: $CURRENT_BUILD → $NEW_BUILD"
-/usr/bin/sed -i '' "s/CURRENT_PROJECT_VERSION: \${CURRENT_BUILD}/CURRENT_PROJECT_VERSION: \${NEW_BUILD}/" project.yml
-
-# Regenerate Xcode project
-echo "⚙️ Regenerating Xcode project..."
-xcodegen generate
-
-# Run tests (unless skipped)
-if [ "\${1:-}" != "--skip-tests" ]; then
- echo "🧪 Running tests..."
- DESTINATION=$(
- if xcrun simctl list devices available | grep -q "iPhone 16"; then
- echo "platform=iOS Simulator,name=iPhone 16"
- elif xcrun simctl list devices available | grep -q "iPhone 15"; then
- echo "platform=iOS Simulator,name=iPhone 15"
- else
- echo "platform=iOS Simulator,name=iPhone 14"
- fi
- )
- xcodebuild test \\
- -project "$PROJECT" \\
- -scheme "$SCHEME" \\
- -only-testing:${targetName}Tests \\
- -destination "$DESTINATION" \\
- -configuration Debug \\
- CODE_SIGNING_ALLOWED=NO \\
- -quiet
- echo "✅ Tests passed"
-fi
-
-# Clean build directory
-rm -rf "$BUILD_DIR"
-
-# Archive
-echo "📦 Archiving..."
-xcodebuild archive \\
- -project "$PROJECT" \\
- -scheme "$SCHEME" \\
- -configuration Release \\
- -destination 'generic/platform=iOS' \\
- -archivePath "$ARCHIVE_PATH" \\
- CODE_SIGNING_ALLOWED=NO \\
- CODE_SIGN_IDENTITY="" \\
- CODE_SIGNING_REQUIRED=NO \\
- -quiet
-
-echo "✅ Archive complete"
-
-# Create exportOptions.plist
-cat > "$BUILD_DIR/exportOptions.plist" <<EOF
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
- "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>method</key><string>app-store-connect</string>
- <key>teamID</key><string>$TEAM_ID</string>
- <key>signingStyle</key><string>automatic</string>
-</dict>
-</plist>
-EOF
-
-# Export IPA
-echo "📤 Exporting IPA..."
-xcodebuild -exportArchive \\
- -archivePath "$ARCHIVE_PATH" \\
- -exportOptionsPlist "$BUILD_DIR/exportOptions.plist" \\
- -exportPath "$EXPORT_PATH" \\
- -allowProvisioningUpdates \\
- -authenticationKeyPath "$KEY_PATH" \\
- -authenticationKeyID "$APPSTORE_API_KEY_ID" \\
- -authenticationKeyIssuerID "$APPSTORE_ISSUER_ID" \\
- -quiet
-
-echo "✅ IPA exported"
-
-# Upload to TestFlight
-IPA_PATH="$EXPORT_PATH/$SCHEME.ipa"
-if [ ! -f "$IPA_PATH" ]; then
- echo "❌ IPA not found at $IPA_PATH"
- ls -la "$EXPORT_PATH/"
- exit 1
-fi
-
-echo "🚀 Uploading to TestFlight..."
-xcrun altool --upload-app \\
- --file "$IPA_PATH" \\
- --type ios \\
- --apiKey "$APPSTORE_API_KEY_ID" \\
- --apiIssuer "$APPSTORE_ISSUER_ID"
-
-UPLOAD_EXIT=$?
-if [ $UPLOAD_EXIT -ne 0 ]; then
- echo "❌ Upload failed with exit code $UPLOAD_EXIT"
- exit $UPLOAD_EXIT
-fi
-
-echo "✅ Upload complete! Build $NEW_BUILD submitted to TestFlight."
-
-# Commit the build number bump
-git add project.yml "$PROJECT/project.pbxproj"
-git commit -m "build: bump to build $NEW_BUILD"
-echo "📝 Committed build number bump"
-
-# Clean up
-rm -rf "$BUILD_DIR"
-echo "🧹 Cleaned build artifacts"
-`;
- await writeFile(join(repoPath, 'deploy.sh'), deployScript);
- // Make deploy.sh executable
- await execAsync(`chmod +x "${join(repoPath, 'deploy.sh')}"`);
+ // Shared Xcode deployment assets
+ await writeFile(join(repoPath, '.env.example'), XCODE_ENV_EXAMPLE);
+ const deployPath = join(repoPath, 'deploy.sh');
+ await writeFile(deployPath, generateDeployScript(targetName, bundleId));
+ if (process.platform !== 'win32') await chmod(deployPath, 0o755);
// CLAUDE.md
await writeFile(join(repoPath, 'CLAUDE.md'), `# ${name}
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 08e6ac26fc..2e3c310df5 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -2126,10 +2126,6 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
const taskSections = [];
const contractSections = [];
- // Alias preserving the original single-list flow below: task-block pushes go
- // to `taskSections`, then `sections` is repointed at `contractSections` for
- // the operating-contract blocks.
- let sections = taskSections;
// --- Task block --------------------------------------------------------
// cwd is set by the spawner and the agent knows its own id from the
@@ -2138,35 +2134,30 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
// suppressed in buildTaskBlock since cwd already reveals it. Shared with the
// full path via buildTaskBlock.
const taskBlock = buildTaskBlock(task, { screenshotsAsList: true });
- sections.push(taskBlock.description);
- if (taskBlock.targetApp) sections.push(taskBlock.targetApp);
+ taskSections.push(taskBlock.description);
+ if (taskBlock.targetApp) taskSections.push(taskBlock.targetApp);
// The task's prompt payload + human note as one block (#4153), so the split is
// invisible here and a legacy `metadata.context`-as-prompt still renders.
const context = taskContextBlock(task);
if (context) {
- sections.push(context.includes('\n')
+ taskSections.push(context.includes('\n')
? `### Context\n\n${context.trimEnd()}`
: `### Context\n${context}`);
}
- if (taskBlock.screenshots) sections.push(taskBlock.screenshots);
- if (taskBlock.attachments) sections.push(taskBlock.attachments);
-
- // Everything below is the PortOS operating contract (not task content) —
- // route it to `contractSections` so the split path can lift it into the
- // system prompt.
- sections = contractSections;
+ if (taskBlock.screenshots) taskSections.push(taskBlock.screenshots);
+ if (taskBlock.attachments) taskSections.push(taskBlock.attachments);
// --- Unattended run ----------------------------------------------------
// First contract section, and unconditional: the light path is the one that
// actually stalled on an approval gate, and "no human will answer you" is not
// something the agent can infer from CLAUDE.md or its cwd.
- sections.push(UNATTENDED_RUN_RULE);
+ contractSections.push(UNATTENDED_RUN_RULE);
// --- Worktree ----------------------------------------------------------
if (worktreeInfo) {
- sections.push([
+ contractSections.push([
'## Git Worktree',
`- **Branch**: \`${worktreeInfo.branchName}\`${isWorktreeOnExistingBranch ? ' *(pre-existing PR branch)*' : ''}`,
`- **Path**: \`${worktreeInfo.worktreePath}\``,
@@ -2184,7 +2175,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
const pipelineCtx = task.metadata?.pipeline;
if (pipelineCtx?.previousStageAgentId) {
const prevOutput = join(AGENTS_DIR, pipelineCtx.previousStageAgentId, 'output.txt');
- sections.push([
+ contractSections.push([
'## Pipeline Context',
`Stage ${pipelineCtx.currentStage + 1} of ${pipelineCtx.stages.length}: "${pipelineCtx.stages[pipelineCtx.currentStage]?.name}"`,
`Previous stage: "${pipelineCtx.stages[pipelineCtx.currentStage - 1]?.name}"`,
@@ -2196,7 +2187,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
// --- JIRA --------------------------------------------------------------
if (task.metadata?.jiraTicketId) {
- sections.push([
+ contractSections.push([
'## JIRA',
`- **Ticket**: ${task.metadata.jiraTicketId} (${task.metadata.jiraTicketUrl})`,
task.metadata.jiraBranch ? `- **Branch**: \`${task.metadata.jiraBranch}\` — commit here; do NOT switch branches.` : null,
@@ -2213,7 +2204,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
// path above and never reaches the other two, so a fix applied only there is
// no fix at all for anything a subscription-quota job can run.
if (noCodeOutput) {
- sections.push(buildActionOutputCompletionSection({
+ contractSections.push(buildActionOutputCompletionSection({
isTui,
sentinelPath: resolveSentinelPath(worktreeInfo, workspaceDir, agentId),
}));
@@ -2221,24 +2212,24 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
// Reasoning-only task: the sentinel payload (shape set by the task-type
// output hook) is the sole output; the worktree is discarded on exit. Wins
// over the isTui / CLI push-and-PR completion workflows below.
- sections.push(buildProgrammaticOutputCompletionSection(resolveSentinelPath(worktreeInfo, workspaceDir, agentId)));
+ contractSections.push(buildProgrammaticOutputCompletionSection(resolveSentinelPath(worktreeInfo, workspaceDir, agentId)));
} else if (claimFlow) {
- sections.push(buildClaimFlowCompletionSection({
+ contractSections.push(buildClaimFlowCompletionSection({
isTui,
sentinelPath: resolveSentinelPath(worktreeInfo, workspaceDir, agentId),
}));
} else if (isReadOnly) {
- sections.push(buildReadOnlyCompletionSection({
+ contractSections.push(buildReadOnlyCompletionSection({
isTui,
sentinelPath: resolveSentinelPath(worktreeInfo, workspaceDir, agentId),
}));
} else if (isReviewLoopFollowUp) {
- sections.push(buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: false, localAgentLoopBody, forgeCli: resolvedForgeCli }));
+ contractSections.push(buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: false, localAgentLoopBody, forgeCli: resolvedForgeCli }));
if (isTui) {
const sentinelPath = resolveSentinelPath(worktreeInfo, workspaceDir, agentId);
const branchName = worktreeInfo?.branchName || task.metadata?.reviewLoopPRBranch || null;
const sentinelTail = branchName ? ` ## Branch\n ${branchName}` : ' ## Branch\n <branch name>';
- sections.push([
+ contractSections.push([
'## Completion Handoff',
'When finished with the follow-up steps above, write the completion sentinel to signal PortOS that you are done:',
'',
@@ -2246,7 +2237,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
].join('\n'));
}
} else if (isTui) {
- sections.push(buildTuiCompletionSection({
+ contractSections.push(buildTuiCompletionSection({
willOpenPR, prCompletion, simplifyEnabled, slashdoFree: tuiSlashdoFree, ownsPrWorkflow,
sentinelPath: resolveSentinelPath(worktreeInfo, workspaceDir, agentId),
branchName: worktreeInfo?.branchName || null,
@@ -2256,7 +2247,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
forgeCli: resolvedForgeCli
}));
} else {
- sections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion, hasSlashdo, ownsPrWorkflow, simplifyEnabled, leavePrOpen: leavesPrForHuman(task), reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies, forgeCli: resolvedForgeCli }));
+ contractSections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion, hasSlashdo, ownsPrWorkflow, simplifyEnabled, leavePrOpen: leavesPrForHuman(task), reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies, forgeCli: resolvedForgeCli }));
}
// The manual workflow's step 4 points here — it must follow the completion
@@ -2264,7 +2255,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
// so a dangling "step 4" cross-reference and an orphaned Review Loop section
// are both unrepresentable.
if (ownsPrWorkflow) {
- sections.push(buildInlineReviewLoopSection({
+ contractSections.push(buildInlineReviewLoopSection({
taskId: task.id,
branchName: worktreeInfo?.branchName || null,
runsReviewLoop: inlineSection === 'review-loop',
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index 8c16c800b5..0761362510 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -167,59 +167,6 @@ function mergeObjectLWW(local, remote, timestampField = 'updatedAt') {
return { merged: local, changed: false };
}
-/**
- * Deep merge for derived files (longevity, chronotype) where timestamps
- * are unreliable (regenerated on derivation). Merges nested marker objects
- * as unions, keeps non-default scalar values, and uses LWW as final tiebreaker.
- */
-function mergeDeepUnion(local, remote, timestampField = 'derivedAt') {
- if (!local) return { merged: remote, changed: true };
- if (!remote) return { merged: local, changed: false };
-
- const merged = { ...local };
- let changed = false;
-
- for (const [key, remoteVal] of Object.entries(remote)) {
- const localVal = local[key];
-
- // Skip timestamp fields — set after merge
- if (key === timestampField) continue;
-
- // Nested objects (markers): union keys, local wins per-key conflicts
- if (isPlainObject(remoteVal) && isPlainObject(localVal)) {
- const mergedObj = { ...localVal };
- for (const [k, v] of Object.entries(remoteVal)) {
- if (!(k in mergedObj)) {
- mergedObj[k] = v;
- changed = true;
- }
- }
- merged[key] = mergedObj;
- continue;
- }
-
- // Missing locally — take remote
- if (localVal === undefined || localVal === null) {
- merged[key] = remoteVal;
- changed = true;
- continue;
- }
-
- // Remote has non-default value, local has default — take remote
- if (localVal === 0 && remoteVal !== 0) {
- merged[key] = remoteVal;
- changed = true;
- }
- }
-
- // Use the newer timestamp
- const localTs = local[timestampField] || '';
- const remoteTs = remote[timestampField] || '';
- merged[timestampField] = remoteTs > localTs ? remoteTs : localTs;
-
- return { merged, changed };
-}
-
// --- Category: Goals ---
async function getGoalsSnapshot() {
diff --git a/server/services/googleAuth.js b/server/services/googleAuth.js
index 9554e8512f..3dcb875284 100644
--- a/server/services/googleAuth.js
+++ b/server/services/googleAuth.js
@@ -48,6 +48,19 @@ async function saveTokens(tokens) {
console.log('📅 Google OAuth tokens saved');
}
+async function persistRefreshedTokens(newTokens) {
+ const existing = (await getTokens()) || {};
+ await saveTokens({ ...existing, ...newTokens });
+ console.log('📅 Google OAuth tokens refreshed');
+}
+
+function attachTokenPersistence(client) {
+ client.on('tokens', (newTokens) => {
+ persistRefreshedTokens(newTokens)
+ .catch((err) => console.error(`❌ Failed to persist refreshed Google OAuth tokens: ${err.message}`));
+ });
+}
+
export async function clearAuth() {
await ensureAuthDir();
await writeFile(TOKENS_FILE, '{}').catch(() => {});
@@ -90,12 +103,7 @@ export async function handleCallback(code) {
oAuth2Client = client;
oAuth2Client.setCredentials(tokens);
- // Attach refresh listener so refreshed tokens are persisted
- oAuth2Client.on('tokens', async (newTokens) => {
- const existing = (await getTokens()) || {};
- await saveTokens({ ...existing, ...newTokens });
- console.log('📅 Google OAuth tokens refreshed');
- });
+ attachTokenPersistence(oAuth2Client);
console.log('📅 Google OAuth callback processed, tokens stored');
return { success: true };
@@ -112,12 +120,7 @@ export async function getAuthenticatedClient() {
oAuth2Client = createOAuth2Client(credentials);
oAuth2Client.setCredentials(tokens);
- // Listen for token refresh
- oAuth2Client.on('tokens', async (newTokens) => {
- const existing = (await getTokens()) || {};
- await saveTokens({ ...existing, ...newTokens });
- console.log('📅 Google OAuth tokens refreshed');
- });
+ attachTokenPersistence(oAuth2Client);
}
return oAuth2Client;
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 127d03c1e7..4b901ac7f0 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -1397,17 +1397,24 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// internally-created resize/still-clip temp files. Clean them up explicitly
// before either throw so a missing ffmpeg or a failed still-encode doesn't
// leak every resized temp file for the request into os.tmpdir().
- const cleanupResizeTempFiles = async () => {
- if (resizedSrcTempPath) await unlink(resizedSrcTempPath).catch(() => {});
- if (resizedLastTempPath) await unlink(resizedLastTempPath).catch(() => {});
- for (const p of resizedKeyframeTempPaths) await unlink(p).catch(() => {});
- for (const p of icReferenceTempPaths) await unlink(p).catch(() => {});
+ const cleanupTempFiles = ({ includeUploads = false, includeUntrackedAudio = false } = {}) => {
+ const paths = [
+ resizedSrcTempPath,
+ resizedLastTempPath,
+ ...resizedKeyframeTempPaths,
+ ...icReferenceTempPaths,
+ ...(includeUploads ? [uploadedTempPath, ...uploadedTempPaths] : []),
+ ...(includeUntrackedAudio && audioFilePath && !uploadedTempPaths.includes(audioFilePath)
+ ? [audioFilePath]
+ : []),
+ ];
+ return Promise.all(paths.filter(Boolean).map((path) => unlink(path).catch(() => {})));
};
if (isIcLoraMode(mode) && icLoraSpecForMode(mode)?.referenceKind === 'image'
&& Array.isArray(icReferencePaths) && icReferencePaths.length) {
const stillFfmpeg = ffmpeg || await findFfmpeg();
if (!stillFfmpeg) {
- await cleanupResizeTempFiles();
+ await cleanupTempFiles();
throw new ServerError(
'ffmpeg is required to prepare still references for Ingredients mode — install it (brew install ffmpeg) and retry.',
{ status: 400, code: 'IC_LORA_STILL_NEEDS_FFMPEG' },
@@ -1434,9 +1441,9 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// Unlike the resizeImage fallback (which degrades to the original), there is
// no usable degradation here — a still handed straight to the pipeline fails
// deep inside the VAE reshape. Fail loudly with the ffmpeg reason.
- // cleanupResizeTempFiles() also unlinks clipPaths (already pushed into
+ // cleanupTempFiles() also unlinks clipPaths (already pushed into
// icReferenceTempPaths above), plus any earlier resize temp files.
- await cleanupResizeTempFiles();
+ await cleanupTempFiles();
throw new ServerError(
`Failed to prepare Ingredients reference ${basename(icReferencePaths[failedAt])}: ${encodes[failedAt].error.message}`,
{ status: 400, code: 'IC_LORA_STILL_PREP_FAILED' },
@@ -1537,15 +1544,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
console.log(`❌ Video generation buildArgs error [${jobId.slice(0, 8)}]: ${reason}`);
broadcastSse(job, { type: 'error', error: reason });
videoGenEvents.emit('failed', { generationId: jobId, error: reason });
- if (resizedSrcTempPath) unlink(resizedSrcTempPath).catch(() => {});
- if (resizedLastTempPath) unlink(resizedLastTempPath).catch(() => {});
- for (const p of resizedKeyframeTempPaths) unlink(p).catch(() => {});
- for (const p of icReferenceTempPaths) unlink(p).catch(() => {});
- if (uploadedTempPath) unlink(uploadedTempPath).catch(() => {});
- for (const p of uploadedTempPaths) unlink(p).catch(() => {});
- if (audioFilePath && !uploadedTempPaths.includes(audioFilePath)) {
- unlink(audioFilePath).catch(() => {});
- }
+ void cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });
closeJobAfterDelay(jobs, jobId);
throw err;
}
@@ -1553,12 +1552,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
const heavyClaim = await claimHeavyLocalJob({ kind: 'local video generation', id: jobId });
if (!heavyClaim.ok) {
jobs.delete(jobId);
- if (resizedSrcTempPath) await unlink(resizedSrcTempPath).catch(() => {});
- if (resizedLastTempPath) await unlink(resizedLastTempPath).catch(() => {});
- await Promise.all(resizedKeyframeTempPaths.map((path) => unlink(path).catch(() => {})));
- await Promise.all(icReferenceTempPaths.map((path) => unlink(path).catch(() => {})));
- if (uploadedTempPath) await unlink(uploadedTempPath).catch(() => {});
- await Promise.all(uploadedTempPaths.map((path) => unlink(path).catch(() => {})));
+ await cleanupTempFiles({ includeUploads: true });
throw new ServerError(heavyClaim.message, { status: 409, code: 'HEAVY_LOCAL_JOB_BUSY', context: { holder: heavyClaim.holder } });
}
const releaseHeavyClaim = () => heavyClaim.release()
@@ -1751,18 +1745,9 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// Spawn failed, so proc.on('close') will never fire — clean up every
// temp file we own here, including the multipart upload, otherwise
// ENOENT/permission errors leak files in os.tmpdir().
- if (resizedSrcTempPath) unlink(resizedSrcTempPath).catch(() => {});
- if (resizedLastTempPath) unlink(resizedLastTempPath).catch(() => {});
- for (const p of resizedKeyframeTempPaths) unlink(p).catch(() => {});
- for (const p of icReferenceTempPaths) unlink(p).catch(() => {});
- if (uploadedTempPath) unlink(uploadedTempPath).catch(() => {});
- for (const p of uploadedTempPaths) unlink(p).catch(() => {});
- // Defensive: a direct caller (bypassing the route) may pass audioFilePath
- // without also threading it through uploadedTempPaths. Unlink it here too —
- // double-unlink on the route's path is harmless (catch swallows ENOENT).
- if (audioFilePath && !uploadedTempPaths.includes(audioFilePath)) {
- unlink(audioFilePath).catch(() => {});
- }
+ // Defensive cleanup includes audio passed directly without the route's
+ // uploadedTempPaths tracking. Duplicate unlinks remain harmless.
+ void cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });
closeJobAfterDelay(jobs, jobId);
});
@@ -1846,23 +1831,9 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// Cleanup the resized temp images if we made them. Track via flags rather
// than a path-prefix check — tmpdir() can return a symlinked path
// (macOS /var → /private/var) so startsWith() can silently miss.
- if (resizedSrcTempPath) await unlink(resizedSrcTempPath).catch(() => {});
- if (resizedLastTempPath) await unlink(resizedLastTempPath).catch(() => {});
- for (const p of resizedKeyframeTempPaths) await unlink(p).catch(() => {});
- // The throwaway still→clip encodes for an image-kind IC reference. The
- // ORIGINAL stills are gallery files (or route-staged uploads) and are NOT
- // ours to remove — only these temp clips.
- for (const p of icReferenceTempPaths) await unlink(p).catch(() => {});
- // Cleanup the original multipart upload temp file too — without this,
- // every i2v request leaves a file in os.tmpdir() forever.
- if (uploadedTempPath) await unlink(uploadedTempPath).catch(() => {});
- for (const p of uploadedTempPaths) await unlink(p).catch(() => {});
- // Defensive: catch audioFilePath too in case a direct caller passed it
- // without threading through uploadedTempPaths. Skip when the route
- // already covered it (extraUploadedTempPaths.push(audioFilePath)).
- if (audioFilePath && !uploadedTempPaths.includes(audioFilePath)) {
- await unlink(audioFilePath).catch(() => {});
- }
+ // Cleanup internally generated resize/reference files, route-staged
+ // uploads, and direct-call audio through the same ownership-aware helper.
+ await cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });
// A PortOS-fired SIGKILL (completion-teardown watchdog OR idle-stall
// deadline) is a SUCCESS when the output file is already on disk and