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: clarify error and lifecycle comment contracts

Adam Eivy4c53c7a22703
diff --git a/server/lib/errorHandler.js b/server/lib/errorHandler.js
index d44c072fe7..f8c501502a 100644
--- a/server/lib/errorHandler.js
+++ b/server/lib/errorHandler.js
@@ -71,26 +71,14 @@ export class ServerError extends Error {
}
}
-/**
- * Wrap async route handlers to catch errors and emit Socket.IO events
- * Also sends error response to client
- */
-/**
- * Translate a Zod safeParse() failure into the standard `Validation failed:`
- * ServerError shape that the rest of PortOS speaks. Pass the result of
- * `schema.safeParse(...)` after confirming `.success === false`.
- */
-/**
- * A thrown value reduced to one bounded, model-safe sentence.
- *
- * Typed capability results carry the failure reason back into a prompt, so the
- * string has to be short and has to exist even when what was thrown is not an
- * Error. Shared rather than re-declared per capability: the cap and the
- * fallback are the contract, not a local detail.
- */
+/** Reduce a thrown value to a bounded string for model-facing failure results. */
export const boundedErrorMessage = (error, fallback = 'Request failed', maxChars = 300) =>
String(error?.message || error || fallback).slice(0, maxChars);
+/**
+ * Throw the standard validation error for a Zod safeParse() result whose
+ * `success` is false.
+ */
export function failValidation(parsed) {
throw new ServerError(
`Validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`,
@@ -177,6 +165,10 @@ const summarizeDetails = (details) => {
return clampLogText(details);
};
+/**
+ * Handle rejected route promises with logging, Socket.IO events and the shared
+ * HTTP error envelope; delegate failures after streaming starts to middleware.
+ */
export function asyncHandler(fn) {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch((err) => {
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 00aeeacc8e..8d5dda3097 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -1585,17 +1585,6 @@ async function runJobLifecycle(job, markDispatched, permit, finalizeLane) {
progressPersistTimer.unref?.();
};
- // Single idempotent terminal sink. All terminal paths (completed, failed,
- // canceled, watchdog) funnel through here. The status check at the top
- // ensures only the first caller wins; any subsequent call (e.g. watchdog
- // fired and then the gen emits 'completed') is a no-op.
- //
- // `job.terminating` (not a closure-local) is the guard so cancelJob — a
- // module-level function — can also see that a terminal transition has begun.
- // It's set synchronously before the async drain below, during which
- // job.status is still 'running'; a cancel arriving in that window must not
- // fire a redundant provider cancel. It's a transient in-memory flag
- // (excluded from persistImpl's serialized field set).
let watchdogTimer;
async function releaseRemoteAudioInputs(disposable) {
if (!disposable || !isRemoteMediaJob(job)) return;
@@ -1635,11 +1624,11 @@ async function runJobLifecycle(job, markDispatched, permit, finalizeLane) {
console.error(`❌ Remote video input cleanup needs recovery for ${job.id}: ${error.message}`);
}
}
+ // All terminal paths compete for one outcome. claimTerminalOutcome sets the
+ // transient job.terminating flag synchronously, so cancelJob also sees the
+ // claim while status is still running during the async progress drain.
async function terminate(state, apply, remoteInputsDisposable = false) {
if (!claimTerminalOutcome(job)) return;
- // setInterval now (was setTimeout) — using clearInterval to match the new
- // API. (Node accepts either clearTimeout or clearInterval on the same
- // Timeout handle, so this is purely stylistic.)
clearInterval(watchdogTimer);
emitter.off?.('activity', onActivity);
emitter.off?.('progress', onActivity);
diff --git a/server/services/sharing/peerSyncPush.js b/server/services/sharing/peerSyncPush.js
index f9b90d0619..100d4e4f83 100644
--- a/server/services/sharing/peerSyncPush.js
+++ b/server/services/sharing/peerSyncPush.js
@@ -506,10 +506,9 @@ async function persistPushDeliveryEvidence(subId, {
// whose content moved) can never be held back by a stale entry.
sub.lastPushedLegacyHash = isNonBlankStr(legacyStrippedPayloadHash) ? legacyStrippedPayloadHash : null;
sub.updatedAt = now;
- // Advance the per-record confirmed-delivery water-mark monotonically — an
- // out-of-order retry must not retract it (mirrors ackDeletesUpTo's
- // never-move-backward guarantee). tombstoneGc reads MIN-of-this across a
- // kind's rows, so a regression here would let a stale tombstone prune.
+ // Keep confirmed delivery monotonic across out-of-order retries, as with
+ // ackDeletesUpTo. tombstoneGc uses the minimum across a kind's rows; moving
+ // this mark backward would unnecessarily retain already-delivered tombstones.
if (Number.isFinite(recordPushAcceptedAtMs) && recordPushAcceptedAtMs > (sub.lastConfirmedPushedAt ?? 0)) {
sub.lastConfirmedPushedAt = recordPushAcceptedAtMs;
}