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

record how long each image/video render took and show it on the media cards

[._.]/ Adam Eivy12201127dcce
diff --git a/client/src/components/media/MediaCard.jsx b/client/src/components/media/MediaCard.jsx
index cd93f1ad40..4de658227c 100644
--- a/client/src/components/media/MediaCard.jsx
+++ b/client/src/components/media/MediaCard.jsx
@@ -1,10 +1,11 @@
import { memo, useState } from 'react';
-import { Trash2, Download, Film, Image as ImageIcon, Sparkles, Eye, EyeOff, Maximize2, Wand2, Star, MessageSquare, Pencil, Box } from 'lucide-react';
+import { Trash2, Download, Film, Image as ImageIcon, Sparkles, Eye, EyeOff, Maximize2, Wand2, Star, MessageSquare, Pencil, Box, Timer } from 'lucide-react';
import MediaImage from '../MediaImage';
import AddToCollectionMenu from './AddToCollectionMenu';
import PinToMoodBoardMenu from './PinToMoodBoardMenu';
import InlineConfirmRow from '../ui/InlineConfirmRow';
import { loraDisplayName } from './normalize';
+import { formatDurationMs } from '../../utils/formatters';
// Single card used everywhere a generated image/video appears in a grid:
// the Image Gen page's recent gallery, the Video Gen page's recent renders,
@@ -118,6 +119,17 @@ function MediaCard({
{item.numFrames && <span className="px-1.5 py-0.5 bg-port-border text-gray-400 rounded">{item.numFrames}f</span>}
{item.fps && <span className="px-1.5 py-0.5 bg-port-border text-gray-400 rounded">{item.fps}fps</span>}
{item.seed != null && <span className="px-1.5 py-0.5 bg-port-border text-gray-400 rounded">seed {item.seed}</span>}
+ {/* How long this render took, once the queue picked it up (see the
+ renderMs contract in normalize.js). Absent renders no chip at all,
+ rather than a placeholder, so the row stays scannable. */}
+ {item.renderMs != null && (
+ <span
+ title="Render time — measured from when the queue started this job, so it excludes queue wait"
+ className="px-1.5 py-0.5 bg-port-border text-gray-400 rounded inline-flex items-center gap-0.5"
+ >
+ <Timer className="w-2.5 h-2.5" aria-hidden="true" />{formatDurationMs(item.renderMs)}
+ </span>
+ )}
</div>
{Array.isArray(item.loraNames) && item.loraNames.length > 0 && (
<div className="flex flex-wrap items-center gap-1 text-[9px]" title={item.loraNames.map(loraDisplayName).join(', ')}>
diff --git a/client/src/components/media/MediaCard.test.jsx b/client/src/components/media/MediaCard.test.jsx
index b17dafcaaf..bcb6c458b6 100644
--- a/client/src/components/media/MediaCard.test.jsx
+++ b/client/src/components/media/MediaCard.test.jsx
@@ -170,3 +170,20 @@ describe('MediaCard', () => {
expect(screen.queryByRole('button', { name: 'Send to 3D' })).toBeNull();
});
});
+
+// Render duration (#5878) — the card is where a user compares "which of these
+// backends is actually fast". The chip must be humanized, not raw ms, and must
+// disappear entirely for a record that was never timed rather than rendering a
+// placeholder or a misleading "0s".
+describe('MediaCard render-time chip', () => {
+ it('humanizes renderMs', () => {
+ render(<MediaCard item={{ ...imageItem, renderMs: 92_000 }} />);
+ expect(screen.getByText('1m 32s')).toBeInTheDocument();
+ expect(screen.queryByText('92000')).not.toBeInTheDocument();
+ });
+
+ it('renders no chip when the record carries no render time', () => {
+ const { container } = render(<MediaCard item={{ ...imageItem, renderMs: null }} />);
+ expect(container.querySelector('[title^="Render time"]')).toBeNull();
+ });
+});
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsx
index 677094e032..3ade673035 100644
--- a/client/src/components/media/MediaLightbox.jsx
+++ b/client/src/components/media/MediaLightbox.jsx
@@ -16,7 +16,7 @@ import { i2vReferenceModeLabel } from '../../lib/videoReferenceModes';
import useFocusTrap from '../../hooks/useFocusTrap.js';
import { copyToClipboard } from '../../lib/clipboard';
import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';
-import { formatDateTime, formatDateNumeric } from '../../utils/formatters';
+import { formatDateTime, formatDateNumeric, formatDurationMs } from '../../utils/formatters';
// Intentionally NOT migrated to <ui/Modal> or <components/Drawer>. The
// prev/next buttons sit as viewport-edge siblings of the card (not children
@@ -286,6 +286,9 @@ export default function MediaLightbox({
['Reference', item.raw?.i2vReferenceMode ? i2vReferenceModeLabel(item.raw.i2vReferenceMode) : null],
['Image strength', item.raw?.imageStrength],
['Created', item.createdAt && formatDateTime(item.createdAt)],
+ // Wall-clock the render itself took, excluding queue wait (see the renderMs
+ // contract in normalize.js). Absent drops the row via the null-filter below.
+ ['Render time', item.renderMs != null ? formatDurationMs(item.renderMs) : null],
].filter(([, v]) => v != null && v !== '');
const cardClasses = fullScreen
diff --git a/client/src/components/media/MediaLightbox.test.jsx b/client/src/components/media/MediaLightbox.test.jsx
index b242a1497e..4bda49664f 100644
--- a/client/src/components/media/MediaLightbox.test.jsx
+++ b/client/src/components/media/MediaLightbox.test.jsx
@@ -247,3 +247,20 @@ describe('MediaLightbox — local image execution provenance', () => {
expect(screen.getByText('Unknown (invalid runner marker)')).toBeTruthy();
});
});
+
+// Render duration (#5878) — the detail panel is where the number is read
+// deliberately ("why did this one take four minutes?"), so it needs both the
+// humanized value and the row label, and must not invent a row for a record
+// that carries no timing.
+describe('MediaLightbox render-time row', () => {
+ it('shows a humanized render time beside its label', () => {
+ render(<MediaLightbox item={{ ...imageItem, renderMs: 254_000 }} onClose={() => {}} />);
+ const label = screen.getByText('Render time');
+ expect(label.nextElementSibling).toHaveTextContent('4m 14s');
+ });
+
+ it('omits the row entirely when the record was never timed', () => {
+ render(<MediaLightbox item={{ ...imageItem, renderMs: null }} onClose={() => {}} />);
+ expect(screen.queryByText('Render time')).toBeNull();
+ });
+});
diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.js
index f93a1049e0..e0dc1ad547 100644
--- a/client/src/components/media/normalize.js
+++ b/client/src/components/media/normalize.js
@@ -59,6 +59,12 @@ export function normalizeImage(i) {
entryName: i.entryName || null,
entryLabel: i.entryLabel || null,
createdAt: i.createdAt,
+ // How long the render itself took, in ms — stamped server-side by
+ // lib/renderTiming.js from the moment the media-job queue ingested the job,
+ // so it excludes queue wait. Absent on records from a path that never
+ // observed a start instant (uploads, downloads, extracted frames, older
+ // renders), which the cards render as "no render time" rather than 0.
+ renderMs: typeof i.renderMs === 'number' ? i.renderMs : null,
hidden: !!i.hidden,
extractedFromVideoId: i.extractedFromVideoId || null,
extractedFromVideoFilename: i.extractedFromVideoFilename || null,
@@ -116,6 +122,8 @@ export function normalizeVideo(v) {
upscaledFrom: v.upscaledFrom,
loraNames,
createdAt: v.createdAt,
+ // Same contract as normalizeImage's renderMs above.
+ renderMs: typeof v.renderMs === 'number' ? v.renderMs : null,
hidden: !!v.hidden,
raw: v,
};
diff --git a/client/src/components/media/normalize.test.js b/client/src/components/media/normalize.test.js
index 2e3c55413b..e71fd03e4a 100644
--- a/client/src/components/media/normalize.test.js
+++ b/client/src/components/media/normalize.test.js
@@ -307,3 +307,26 @@ describe('getRenderConfigForItem - video', () => {
});
});
// @vitest-environment node
+
+// Render duration (#5878). The card and lightbox read `item.renderMs`, so a
+// normalizer that drops it silently removes the display with no test failure
+// anywhere else — and a non-numeric sidecar value must land as `null` rather
+// than being passed through to `formatDurationMs`.
+describe('render duration normalization', () => {
+ it('lifts a numeric renderMs off image and video records', () => {
+ expect(normalizeImage({ filename: 'a.png', renderMs: 42_000 }).renderMs).toBe(42_000);
+ expect(normalizeVideo({ id: 'v1', filename: 'a.mp4', renderMs: 42_000 }).renderMs).toBe(42_000);
+ });
+
+ it('reports null — not 0, not the raw value — when the record was never timed', () => {
+ for (const raw of [{}, { renderMs: null }, { renderMs: '42000' }]) {
+ expect(normalizeImage({ filename: 'a.png', ...raw }).renderMs).toBeNull();
+ expect(normalizeVideo({ id: 'v1', filename: 'a.mp4', ...raw }).renderMs).toBeNull();
+ }
+ });
+
+ it('keeps renderMs out of the requeue config — it describes the past render, not the next one', () => {
+ const image = normalizeImage({ filename: 'a.png', modelId: 'flux', mode: 'local', renderMs: 42_000 });
+ expect(getRenderConfigForItem(image)).not.toHaveProperty('renderMs');
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 68911cfb33..c0836c053b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -408,6 +408,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `markdownText.js` | `stripMarkdownEmphasis(text)` — unwrap `**bold**` / `~~struck~~` / `` `code` `` / `[text](url)` and drop HTML comments, keeping the words. For strings handed to something that can't read markdown (a model's text encoder, a slug builder, TTS); leftover lone `*_~` become spaces so an unbalanced marker can't fuse two words. Does not collapse whitespace — callers that need that normalize themselves. |
| `renderSlot.js` | Render-slot helpers for `(proof\|final)Image` per stage. |
| `renderTargets.js` | Render-target alphabet (#3231): `RENDER_TARGET`/`RENDER_TARGETS` name every creative surface that enqueues renders (universe-bible, sprite-reference, music-video, …) — the keys into `settings.renderDefaults` — plus the `RENDER_TARGET_BACKEND_AUTO` fall-through sentinel. Dependency-free leaf; resolved per surface by `services/imageGen/cloudProviderConfig.js#resolveRenderTargetConfig`. |
+| `renderTiming.js` | `renderTimingFields(startedAtMs, nowMs?)` → the `{ renderMs, renderStartedAt, renderCompletedAt }` spread every image/video backend stamps on the record it persists, measuring ingestion → finished artifact (not queue wait). Returns `{}` when no start instant was observed, so absence stays the explicit unknown sentinel for the history cards and `services/videoGen/eta.js`. `omitRenderTiming(record)` is the inverse, for a DERIVED record built by spreading its source (an image variant) that must not inherit a duration it never took. |
| `telegramClient.js` | Telegram bot client. |
| `tempPathGuard.js` | Throwaway-path guard for destructive test fixtures. `isTempPath(target)` — true only for an absolute path that is a STRICT descendant of `os.tmpdir()` **after symlinks are resolved** (`os.tmpdir()` itself is refused, or `destroyGitSandbox(tmpdir())` would wipe every process's scratch; a `..` segment is refused rather than lexically collapsed; macOS `/var/folders/...` and `/private/var/folders/...` both pass). `assertTempPath(target, operation)` throws otherwise and returns `target` so it can wrap an argument inline. Use it before any fixture `git init` / `git config` / `rm -rf`: `spawn` silently substitutes `process.cwd()` for a missing cwd, which is how a test run once set `core.bare = true` on a real checkout (#4554). |
| `vaultCrypto.js` | Privacy Center PII Vault field-level encryption (issue #2140). AES-256-GCM `encryptValue`/`decryptValue` (`v1:<iv>:<tag>:<ct>` format, per-value 12-byte IV), `ensureVaultKey()` self-heal (generates `PRIVACY_VAULT_KEY` into the install root's `.env` on first write, replacing any invalid line; never logs the value), key resolution that falls back to reading `.env` so decrypt/status survive a server restart, `isVaultKeyConfigured()`, and the per-type `maskValue(type, plaintext)` display masking (last-4 / domain-visible / street-masked). Plaintext must never be logged by callers. |
diff --git a/server/lib/index.js b/server/lib/index.js
index f87a18b527..02de8e0740 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -382,6 +382,7 @@ export * from './planIds.js';
export * from './markdownText.js';
export * from './renderSlot.js';
export * from './renderTargets.js';
+export * from './renderTiming.js';
export * from './generationModes.js';
export * from './spriteVocabulary.js';
export * from './spriteChromaKey.js';
diff --git a/server/lib/renderTiming.js b/server/lib/renderTiming.js
new file mode 100644
index 0000000000..5999b14e90
--- /dev/null
+++ b/server/lib/renderTiming.js
@@ -0,0 +1,64 @@
+/**
+ * Render timing — the wall-clock a media render actually took.
+ *
+ * Every image/video backend stamps the same three fields on the record it
+ * persists (an image sidecar, a video-history row) so the Create section's
+ * history/preview cards can show "how long did this take" without re-deriving
+ * it from unrelated timestamps.
+ *
+ * The window measured is INGESTION → finished artifact: it starts when the
+ * media-job queue handed the job to the generator (not when the user submitted
+ * it), so a render that sat behind five others in the queue still reports its
+ * own cost. It ends once the deliverable is on disk, including the
+ * thumbnail/faststart tail the user waits through.
+ *
+ * Absence is the explicit "unknown" sentinel: a record with no `renderMs` was
+ * produced by a path that never observed a start instant (or by a build that
+ * predates this), and consumers — the card, videoGen/eta.js's cost model —
+ * skip it rather than treating it as zero. That is why every failure mode here
+ * returns `{}` instead of a defaulted `renderMs: 0`, which would drag every
+ * estimate toward "instant".
+ */
+
+/**
+ * Build the render-timing spread for a completed render.
+ *
+ * @param {number|null|undefined} startedAtMs - Epoch ms captured when the
+ * render began, typically `job.renderStartedAtMs`. Coerced, so a missing or
+ * junk value reports "unknown" rather than throwing.
+ * @param {number} [nowMs=Date.now()] - Completion instant; injectable for tests.
+ * @returns {{renderMs?: number, renderStartedAt?: string, renderCompletedAt?: string}}
+ * The fields to spread into the persisted record, or `{}` when the start
+ * instant is missing/unusable (including a clock that moved backwards).
+ */
+export function renderTimingFields(startedAtMs, nowMs = Date.now()) {
+ const startMs = Number(startedAtMs);
+ if (!Number.isFinite(startMs) || startMs <= 0) return {};
+ // Negated `>= 0` so a NaN span (an unusable `nowMs`) and a negative one — the
+ // clock moved backwards mid-render — both report "unknown" rather than a
+ // measurement the estimator would ingest.
+ const renderMs = nowMs - startMs;
+ if (!(renderMs >= 0)) return {};
+ return {
+ renderMs,
+ renderStartedAt: new Date(startMs).toISOString(),
+ renderCompletedAt: new Date(nowMs).toISOString(),
+ };
+}
+
+/**
+ * Strip the render-timing fields off a record.
+ *
+ * A DERIVED record — an image variant, any post-process built by spreading its
+ * source — inherits the source render's timing, which would make its card claim
+ * a duration it never took. This lives beside `renderTimingFields` so the field
+ * names have one owner: hand-copying them at the strip site means a fourth
+ * field added here silently starts leaking into every derived record.
+ *
+ * @param {object} record
+ * @returns {object} A copy without `renderMs`/`renderStartedAt`/`renderCompletedAt`.
+ */
+export function omitRenderTiming(record) {
+ const { renderMs, renderStartedAt, renderCompletedAt, ...rest } = record;
+ return rest;
+}
diff --git a/server/lib/renderTiming.test.js b/server/lib/renderTiming.test.js
new file mode 100644
index 0000000000..0461d24eff
--- /dev/null
+++ b/server/lib/renderTiming.test.js
@@ -0,0 +1,39 @@
+import { describe, it, expect } from 'vitest';
+import { renderTimingFields } from './renderTiming.js';
+
+// The absent-vs-zero contract is the whole point of this helper: videoGen/eta.js
+// calibrates every future render estimate from persisted `renderMs` samples, so
+// a defaulted `renderMs: 0` for an unmeasured render would drag every estimate
+// toward "instant", and the gallery card would claim a render took no time.
+describe('renderTimingFields', () => {
+ it('reports the measured span', () => {
+ const start = Date.parse('2026-09-02T00:00:00.000Z');
+ expect(renderTimingFields(start, start + 90_000)).toEqual({
+ renderMs: 90_000,
+ renderStartedAt: '2026-09-02T00:00:00.000Z',
+ renderCompletedAt: '2026-09-02T00:01:30.000Z',
+ });
+ });
+
+ it('returns no fields at all when the start instant is missing or unusable', () => {
+ for (const bad of [undefined, null, '', 'not-a-date', NaN, 0, -1]) {
+ expect(renderTimingFields(bad, Date.now())).toEqual({});
+ }
+ });
+
+ // A caller that hands over a junk completion instant gets "unknown", not a
+ // NaN `renderMs` persisted onto the record and fed to the ETA cost model.
+ it('reports nothing when the completion instant is unusable', () => {
+ expect(renderTimingFields(Date.parse('2026-09-02T00:00:00.000Z'), NaN)).toEqual({});
+ });
+
+ it('reports nothing rather than a negative span when the clock moved backwards', () => {
+ const start = Date.parse('2026-09-02T00:01:00.000Z');
+ expect(renderTimingFields(start, start - 5_000)).toEqual({});
+ });
+
+ it('keeps a genuine zero-length measurement distinguishable from an absent one', () => {
+ const start = Date.parse('2026-09-02T00:00:00.000Z');
+ expect(renderTimingFields(start, start).renderMs).toBe(0);
+ });
+});
diff --git a/server/services/federatedMedia/remoteExecutor.js b/server/services/federatedMedia/remoteExecutor.js
index 75494eb4b2..baa2fcc2db 100644
--- a/server/services/federatedMedia/remoteExecutor.js
+++ b/server/services/federatedMedia/remoteExecutor.js
@@ -88,6 +88,8 @@ const isRetryableTransportError = (error) =>
* Where the verified result lands. Called per job so a PATHS proxy stays live.
* @param {(ctx: object) => Promise<object>} config.finalize - Register the downloaded
* result locally; its return value is merged into the `completed` event payload.
+ * Its ctx carries `renderStartedAtMs` (this install's ingestion instant) for
+ * `renderTimingFields` — see the call site for what that span covers.
*/
export function createRemoteMediaExecutor({
kind,
@@ -472,6 +474,13 @@ export function createRemoteMediaExecutor({
peerId: state.peerId,
request,
remoteJob: completed,
+ // Wall-clock render timing (#5878). Measured from THIS install's
+ // ingestion of the job — submission, the peer's own queue wait and
+ // render, download, verification — because that whole span is what the
+ // user waited through here. The peer's internal render time is not on
+ // the wire, and asking for it would be a status payload crossing the
+ // federation boundary.
+ renderStartedAtMs: state.renderStartedAtMs,
...downloaded,
});
return {
@@ -506,6 +515,9 @@ export function createRemoteMediaExecutor({
standingRoute: marker.data.standingRoute === true,
requestController: null,
wake: null,
+ // The instant the media-job queue handed this job to us; `finalize` turns
+ // it into the record's render-timing fields.
+ renderStartedAtMs: Date.now(),
};
activeJobs.set(params.jobId, state);
try {
diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.js
index fa02adfcf6..43189a0840 100644
--- a/server/services/imageGen/agy.js
+++ b/server/services/imageGen/agy.js
@@ -28,6 +28,7 @@ import { atomicWrite, detectImageFormat, ensureDir, PATHS } from '../../lib/file
import { ServerError } from '../../lib/errorHandler.js';
import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
+import { renderTimingFields } from '../../lib/renderTiming.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { buildNoImageReason } from './noImageReason.js';
@@ -218,6 +219,9 @@ export async function generateImage({
cleanC2PA = false,
denoise = false,
}) {
+ // The ingestion instant `renderTimingFields` measures from — the queue calls
+ // generateImage the moment it picks this job up. See lib/renderTiming.js.
+ const renderStartedAtMs = Date.now();
// Re-anchors every path to the approved image roots and caps at agy's
// 3-image ImagePaths ceiling — see inputImages.js.
const inputImages = resolveInputImages({
@@ -263,7 +267,7 @@ export async function generateImage({
...(visualConditioning ? { visualConditioning } : {}),
createdAt: new Date().toISOString(),
};
- const job = { ...meta, clients: [], status: 'running' };
+ const job = { ...meta, clients: [], status: 'running', renderStartedAtMs };
jobs.set(jobId, job);
activeJobs.set(jobId, {
...meta,
@@ -378,7 +382,10 @@ async function runAgy(job, jobId, bin, args, {
return finalizeError(job, jobId, proc, emptyFrame);
}
const sidecar = join(PATHS.images, `${jobId}.metadata.json`);
- await atomicWrite(sidecar, meta).catch(() => {});
+ // `job.renderStartedAtMs` is the queue-ingestion instant generateImage
+ // captured, so the spread measures the render itself — not the time the
+ // job spent queued behind other renders.
+ await atomicWrite(sidecar, { ...meta, ...renderTimingFields(job.renderStartedAtMs) }).catch(() => {});
await autoCleanGeneratedImage({
cleanC2PA,
denoise,
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index 1d4c5c31c8..cf4e1b8519 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -41,6 +41,7 @@ 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 { renderTimingFields } from '../../lib/renderTiming.js';
import { buildCodexStartupArgs, buildEffortArgs, resolveCliEffort } from '../../lib/providerModels.js';
import {
IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT,
@@ -177,6 +178,9 @@ export async function generateImage({
cleanC2PA = false,
denoise = false,
}) {
+ // The ingestion instant `renderTimingFields` measures from — the queue calls
+ // generateImage the moment it picks this job up. See lib/renderTiming.js.
+ const renderStartedAtMs = Date.now();
await ensureDir(PATHS.images);
// Ship the cheap gpt-5.6-luna / low-effort path by default (see modes.js).
@@ -263,7 +267,7 @@ export async function generateImage({
...(visualConditioning ? { visualConditioning } : {}),
createdAt: new Date().toISOString(),
};
- const job = { ...meta, clients: [], status: 'running' };
+ const job = { ...meta, clients: [], status: 'running', renderStartedAtMs };
jobs.set(jobId, job);
console.log(`🎨 Generating image [${jobId.slice(0, 8)}] codex: ${prompt.slice(0, 60)}…`);
@@ -424,7 +428,10 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cle
// (which doesn't expose one) — uniquely identifies the run and is
// useful for traceability even though it doesn't reproduce the output.
const sidecar = join(PATHS.images, `${jobId}.metadata.json`);
- await atomicWrite(sidecar, { ...meta, codexSessionId: sessionId }).catch(() => {});
+ // `job.renderStartedAtMs` is the queue-ingestion instant generateImage
+ // captured, so the spread measures the render itself — not the time the
+ // job spent queued behind other renders.
+ await atomicWrite(sidecar, { ...meta, codexSessionId: sessionId, ...renderTimingFields(job.renderStartedAtMs) }).catch(() => {});
// Cleaners run BEFORE the SSE complete + completed events so subscribers
// see the cleaned bytes. codex output is the highest-value target for
// C2PA stripping because gpt-image is the one provider that embeds
diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.js
index 6c001b9eb2..794bd359b4 100644
--- a/server/services/imageGen/grok.js
+++ b/server/services/imageGen/grok.js
@@ -43,6 +43,7 @@ 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 { renderTimingFields } from '../../lib/renderTiming.js';
import { buildNoImageReason } from './noImageReason.js';
import { rejectDegenerateFrame } from './frameGuard.js';
import { checkFabrication, noFabricationClause } from './fabricationGuard.js';
@@ -216,6 +217,9 @@ export async function generateImage({
cleanC2PA = false,
denoise = false,
}) {
+ // The ingestion instant `renderTimingFields` measures from — the queue calls
+ // generateImage the moment it picks this job up. See lib/renderTiming.js.
+ const renderStartedAtMs = Date.now();
await ensureDir(PATHS.images);
// Re-anchors every path to the allowed input roots (so no caller can point
@@ -273,7 +277,7 @@ export async function generateImage({
...(effectiveRatio ? { aspectRatio: effectiveRatio } : {}),
createdAt: new Date().toISOString(),
};
- const job = { ...meta, clients: [], status: 'running' };
+ const job = { ...meta, clients: [], status: 'running', renderStartedAtMs };
jobs.set(jobId, job);
console.log(`🎨 Generating image [${jobId.slice(0, 8)}] grok: ${prompt.slice(0, 60)}…`);
@@ -412,7 +416,10 @@ async function runGrok(job, jobId, bin, args, {
}
// Sidecar metadata so the gallery can recover prompt/ratio/etc.
const sidecar = join(PATHS.images, `${jobId}.metadata.json`);
- await atomicWrite(sidecar, meta).catch(() => {});
+ // `job.renderStartedAtMs` is the queue-ingestion instant generateImage
+ // captured, so the spread measures the render itself — not the time the
+ // job spent queued behind other renders.
+ await atomicWrite(sidecar, { ...meta, ...renderTimingFields(job.renderStartedAtMs) }).catch(() => {});
// Cleaners run BEFORE the SSE complete + completed events so
// subscribers see the cleaned bytes.
await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: IMAGE_GEN_MODE.GROK });
diff --git a/server/services/imageGen/grok.test.js b/server/services/imageGen/grok.test.js
index 1b6aa473eb..50f61fc96d 100644
--- a/server/services/imageGen/grok.test.js
+++ b/server/services/imageGen/grok.test.js
@@ -283,6 +283,14 @@ describe('grok provider — directed-path harvest', () => {
// Sidecar metadata exists too.
const sidecar = join(FAKE_IMAGES_DIR, `${job.generationId}.metadata.json`);
expect(existsSync(sidecar)).toBe(true);
+ // …and carries this render's own wall-clock cost (#5878), which is what the
+ // gallery card humanizes. The span is bounded by `createdAt`→`now` rather
+ // than asserted against a literal, so this stays a contract test and not a
+ // timing flake.
+ const meta = JSON.parse(await readFile(sidecar, 'utf8'));
+ expect(meta.renderMs).toBeGreaterThanOrEqual(0);
+ expect(Date.parse(meta.renderStartedAt)).toBeLessThanOrEqual(Date.parse(meta.renderCompletedAt));
+ expect(Date.parse(meta.renderCompletedAt) - Date.parse(meta.renderStartedAt)).toBe(meta.renderMs);
});
it('transcodes a staged JPEG to PNG instead of shipping mislabeled bytes', async () => {
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 88d7ff5bda..df6b67632a 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -29,6 +29,7 @@ import { resolveFlux2Python, FLUX2_VENV_DEFAULT } from '../../lib/pythonSetup.js
import { hfChildEnv } from '../hfToken.js';
import { extractGatedRepo, isGatedRepoError } from '../../lib/hfErrors.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
+import { renderTimingFields } from '../../lib/renderTiming.js';
import { createLineReader } from '../../lib/streamLines.js';
import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';
import { prepareLocalMemory, gpuBlockersMessage } from '../localMemory.js';
@@ -532,6 +533,9 @@ export function parseImageExecutionMarker(line) {
}
export async function generateImage({ pythonPath, prompt = '', negativePrompt = '', modelId = LOCAL_IMAGEGEN_DEFAULT_MODEL, width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, referenceImagePaths = [], referenceImageStrengths = [], visualConditioning = null, jobId: providedJobId = null, cleanC2PA = false, denoise = false, regenOf = null, upscaleTo = null, outputTarget = null }) {
+ // The ingestion instant `renderTimingFields` measures from — the queue calls
+ // generateImage the moment it picks this job up. See lib/renderTiming.js.
+ const renderStartedAtMs = Date.now();
// Empty prompt is allowed: img2img / edit / unconditional renders are driven
// by the init image (or run unconditionally), so text isn't required. The
// mflux/diffusers runners accept an empty `--prompt` — the regen pass (#912)
@@ -628,7 +632,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
if (addedTriggerWords.length) {
console.log(`🔤 LoRA trigger words woven [${jobId.slice(0, 8)}]: ${addedTriggerWords.join(', ')}`);
}
- const job = { ...meta, clients: [], status: 'running' };
+ const job = { ...meta, clients: [], status: 'running', renderStartedAtMs };
jobs.set(jobId, job);
// Per-job stepwise output dir under the OS temp dir. mflux writes one PNG
@@ -1010,6 +1014,9 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
// result-fetch, so there's no gallery record to hydrate.
const sidecar = join(outputDir, `${jobId}.metadata.json`);
if (!skipSidecar) {
+ // Render timing is stamped onto `meta` (not spread at the write) so the
+ // sidecar and the `autoCleanGeneratedImage` rewrite below agree on it.
+ Object.assign(meta, renderTimingFields(job.renderStartedAtMs));
await atomicWrite(sidecar, meta).catch(() => {});
// Cleaners run BEFORE the SSE complete + completed events so subscribers
// see the cleaned bytes. Local FLUX renders never carry C2PA chunks so
diff --git a/server/services/imageGen/remote.js b/server/services/imageGen/remote.js
index e434e6467c..24fa0fbd37 100644
--- a/server/services/imageGen/remote.js
+++ b/server/services/imageGen/remote.js
@@ -15,6 +15,7 @@
import { join } from 'node:path';
import { z } from 'zod';
import { PATHS, atomicWrite } from '../../lib/fileUtils.js';
+import { renderTimingFields } from '../../lib/renderTiming.js';
import { FEDERATED_MEDIA_WIRE_VERSION } from '../../lib/federatedMediaWire.js';
import {
federatedMediaImageJobSubmissionBaseSchema,
@@ -62,7 +63,7 @@ const executor = createRemoteMediaExecutor({
// filename is the same shape imageGen/local.js uses, which is what lets the
// gallery, the media index, and the provider-side result guard all agree.
resolveDestination: ({ jobId }) => ({ dir: PATHS.images, filename: `${jobId}.png` }),
- async finalize({ jobId, dir, filename, request, remoteJob, peerId }) {
+ async finalize({ jobId, dir, filename, request, remoteJob, peerId, renderStartedAtMs }) {
// Honest sidecar: only fields this render actually had. Seed is the
// requested one (wire-v1 results carry no rendered seed), so a render that
// did not pin one records null rather than inventing a number the peer
@@ -83,6 +84,7 @@ const executor = createRemoteMediaExecutor({
federatedPeerId: peerId,
federatedJobId: remoteJob.id,
createdAt: new Date().toISOString(),
+ ...renderTimingFields(renderStartedAtMs),
};
await atomicWrite(join(dir, `${jobId}.metadata.json`), meta);
return {
diff --git a/server/services/imageGen/variants.js b/server/services/imageGen/variants.js
index 5ddbfc79ba..9d069a90f0 100644
--- a/server/services/imageGen/variants.js
+++ b/server/services/imageGen/variants.js
@@ -23,6 +23,7 @@ import { join } from 'node:path';
import { ServerError } from '../../lib/errorHandler.js';
import { atomicWrite, PATHS } from '../../lib/fileUtils.js';
import { stripPngC2PAChunk } from '../../lib/imageClean.js';
+import { omitRenderTiming } from '../../lib/renderTiming.js';
import { removeCornerWatermark } from '../../lib/imageWatermark.js';
import { applyLightRegen, computePixelDelta } from './regen.js';
import { listCollections, addItem, ERR_DUPLICATE } from '../mediaCollections.js';
@@ -89,9 +90,17 @@ export async function persistVariant({
const sidecarBase = outFilename.slice(0, -'.png'.length);
const sidecarPath = join(PATHS.images, `${sidecarBase}.metadata.json`);
+ // Every caller builds `variantMeta` by spreading the SOURCE sidecar, which
+ // carries that render's own timing. A variant is a post-process of bytes that
+ // already exist — it never ran a render — so inheriting `renderMs` would make
+ // the gallery card claim a duration this image never took. Stripped here, in
+ // the one place that owns the variant sidecar write, so it holds for every
+ // current and future caller.
+ const untimedVariantMeta = omitRenderTiming(variantMeta);
+
await Promise.all([
writeFile(outPath, data),
- atomicWrite(sidecarPath, variantMeta),
+ atomicWrite(sidecarPath, untimedVariantMeta),
]);
const filedCollections = await autoFileCleanedToSourceCollections(sourceFilename, outFilename).catch((err) => {
@@ -102,7 +111,7 @@ export async function persistVariant({
console.log(`${logLine}${filedCollections.length ? `, filed to ${filedCollections.length} collection(s)` : ''}`);
return {
- ...variantMeta,
+ ...untimedVariantMeta,
filename: outFilename,
path: `/data/images/${outFilename}`,
...(width != null ? { width } : {}),
diff --git a/server/services/videoGen/eta.js b/server/services/videoGen/eta.js
index ca29a59040..e632640d33 100644
--- a/server/services/videoGen/eta.js
+++ b/server/services/videoGen/eta.js
@@ -105,11 +105,38 @@ const speedBucket = (id) => (id == null || id === '' ? DEFAULT_SPEED_BUCKET : St
* the user at render time, and ordinary variance next to the slope difference
* this split exists to capture.
*/
+
+/**
+ * A timed row whose `renderMs` does NOT measure "this model rendering these
+ * work units on this machine", and so must never train the cost model — even
+ * though it carries a `modelId` and a positive `renderMs` and would otherwise
+ * sail through the filter below. Each is a derived record that inherits its
+ * source's model and dials while measuring something else entirely:
+ *
+ * - `upscaledFrom` — the row keeps the source's `steps`/`numFrames` but DOUBLES
+ * width and height (4× the work units), while its duration is an ffmpeg 2×
+ * pass measured in seconds. Large x, tiny y: the single worst sample the
+ * least-squares fit could be handed.
+ * - `federatedPeerId` — rendered on a PEER's hardware, and the span includes
+ * submission, that peer's own queue wait, download and verification. It
+ * describes the federation round-trip, not this machine's throughput.
+ * - `chainedFrom` / `stitchedFrom` — the chain's chunk rows are themselves
+ * timed samples, so the stitched total would double-count them.
+ *
+ * Keyed on the discriminators the rows already carry rather than on a tag the
+ * writers have to remember to set: a future derived-record path is excluded the
+ * moment it stamps one of these, and until then the estimator is the one place
+ * that decides what a valid sample is.
+ */
+const DERIVED_RECORD_KEYS = ['upscaledFrom', 'federatedPeerId', 'chainedFrom', 'stitchedFrom'];
+const isDerivedRecord = (e) => DERIVED_RECORD_KEYS.some((key) => e[key] != null);
+
export const timedRenderSamples = (history, modelId, speedProfileId = null) => {
if (!Array.isArray(history)) return [];
const wantBucket = speedBucket(speedProfileId);
return history
.filter((e) => e && e.modelId === modelId && speedBucket(e.speedProfileId) === wantBucket
+ && !isDerivedRecord(e)
&& Number.isFinite(Number(e.renderMs)) && Number(e.renderMs) > 0)
.map((e) => ({
workUnits: renderWorkUnits(e),
diff --git a/server/services/videoGen/eta.test.js b/server/services/videoGen/eta.test.js
index 61b9c2efa6..98e1c2d4c0 100644
--- a/server/services/videoGen/eta.test.js
+++ b/server/services/videoGen/eta.test.js
@@ -218,3 +218,25 @@ describe('speed-profile sample bucketing', () => {
expect(estimateRenderMs({ history: [quality], ...target, speedProfileId: 'fast' })).toBeNull();
});
});
+
+// Derived history rows (#5878). These inherit their SOURCE's modelId and dials
+// but time something else — an ffmpeg upscale pass, a federated round-trip, a
+// chain total whose chunks are already samples. They carry a positive renderMs,
+// so nothing but this exclusion keeps them out of the least-squares fit.
+describe('timedRenderSamples excludes derived rows', () => {
+ const good = rec({ renderMs: 600_000 });
+
+ it.each([
+ ['an upscale (4x the work units, seconds of ffmpeg)', { upscaledFrom: 'src-id', width: 1536, height: 1024 }],
+ ['a federated render (peer hardware + network round-trip)', { federatedPeerId: 'peer-1' }],
+ ['a chained total (its chunks are already samples)', { chainedFrom: ['a', 'b'] }],
+ ['a hand-stitched clip', { stitchedFrom: ['a', 'b'] }],
+ ])('drops %s', (_label, over) => {
+ const derived = { ...rec({ renderMs: 20_000 }), ...over };
+ expect(timedRenderSamples([good, derived], MODEL)).toHaveLength(1);
+ });
+
+ it('keeps an ordinary local render', () => {
+ expect(timedRenderSamples([good], MODEL)).toHaveLength(1);
+ });
+});
diff --git a/server/services/videoGen/generateVideoHelpers.js b/server/services/videoGen/generateVideoHelpers.js
index e3a04d5eee..cf54a129fd 100644
--- a/server/services/videoGen/generateVideoHelpers.js
+++ b/server/services/videoGen/generateVideoHelpers.js
@@ -12,6 +12,7 @@ import { existsSync, statSync } from 'fs';
import { broadcastSse } from '../../lib/sseUtils.js';
import { generateThumbnail, optimizeForStreaming } from '../../lib/ffmpeg.js';
import { formatBytes } from '../../lib/fileUtils.js';
+import { renderTimingFields } from '../../lib/renderTiming.js';
import { videoGenEvents } from './events.js';
/**
@@ -568,14 +569,7 @@ export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename,
// (a zero-duration sample would drag every estimate toward "instant").
// The window measured is spawn → output finalized, i.e. what the user waits
// through, including the thumbnail/faststart tail above.
- const startMs = Number(startedAtMs);
- const timing = Number.isFinite(startMs) && startMs > 0
- ? {
- renderMs: Date.now() - startMs,
- renderStartedAt: new Date(startMs).toISOString(),
- renderCompletedAt: new Date().toISOString(),
- }
- : {};
+ const timing = renderTimingFields(startedAtMs);
await mutateHistory((history) => {
history.unshift({
...meta,
diff --git a/server/services/videoGen/grok.js b/server/services/videoGen/grok.js
index 19af0d8473..75055b14fd 100644
--- a/server/services/videoGen/grok.js
+++ b/server/services/videoGen/grok.js
@@ -124,6 +124,13 @@ export async function generateVideo({
}) {
await ensureDir(PATHS.videos);
+ // Wall-clock render timing (#5878). finalizeGeneratedVideo reads this off the
+ // job; without it a grok render lands with no `renderMs` at all — the cloud
+ // lane is exactly the one whose cost the user can't guess from hardware.
+ // Measured from here (queue ingestion) rather than from the spawn, which is
+ // what videoGen/spawnWatch.js does for local renders.
+ const renderStartedAtMs = Date.now();
+
if (!prompt?.trim()) {
throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
}
@@ -169,7 +176,7 @@ export async function generateVideo({
createdAt: new Date().toISOString(),
mode: sourceImagePath ? 'image' : 'text',
};
- const job = { ...meta, clients: [], status: 'running' };
+ const job = { ...meta, clients: [], status: 'running', renderStartedAtMs };
jobs.set(jobId, job);
console.log(`🎬 Generating video [${jobId.slice(0, 8)}] grok: ${prompt.slice(0, 60)}…`);
diff --git a/server/services/videoGen/remote.js b/server/services/videoGen/remote.js
index 47390c584f..99bc56063a 100644
--- a/server/services/videoGen/remote.js
+++ b/server/services/videoGen/remote.js
@@ -25,6 +25,7 @@ import { createRemoteMediaExecutor } from '../federatedMedia/remoteExecutor.js';
import { applyRemoteInputAssets, remoteInputAssetsSchema } from '../federatedMedia/inputAssets.js';
import { videoGenEvents } from './events.js';
import { mutateVideoHistory } from './history.js';
+import { renderTimingFields } from '../../lib/renderTiming.js';
const remoteVideoMarkerSchema = z.object({
wireVersion: z.literal(FEDERATED_MEDIA_WIRE_VERSION),
@@ -62,7 +63,7 @@ const executor = createRemoteMediaExecutor({
// `<jobId>.mp4` is videoGen/local.js's own filename shape, which is what the
// provider-side result guard and the local history row both key on.
resolveDestination: ({ jobId }) => ({ dir: PATHS.videos, filename: `${jobId}.mp4` }),
- async finalize({ jobId, path, filename, request, remoteJob, peerId }) {
+ async finalize({ jobId, path, filename, request, remoteJob, peerId, renderStartedAtMs }) {
// Both ffmpeg passes are best-effort by construction (they no-op when
// ffmpeg is absent), exactly as the local finalize path treats them — a
// missing thumbnail must not fail a render that already landed verified.
@@ -88,6 +89,7 @@ const executor = createRemoteMediaExecutor({
federatedPeerId: peerId,
federatedJobId: remoteJob.id,
createdAt: new Date().toISOString(),
+ ...renderTimingFields(renderStartedAtMs),
});
return history;
});
diff --git a/server/services/videoGen/stitchVideos.js b/server/services/videoGen/stitchVideos.js
index 144d7381e5..96c1d5a5bc 100644
--- a/server/services/videoGen/stitchVideos.js
+++ b/server/services/videoGen/stitchVideos.js
@@ -13,8 +13,23 @@ import {
hasAudioStream, buildTrimConcatArgs, bt709TagFilter,
} from '../../lib/ffmpeg.js';
import { safeChildProcessOptions } from '../../lib/processEnv.js';
+import { renderTimingFields } from '../../lib/renderTiming.js';
import { loadHistory, mutateVideoHistory } from './history.js';
+// Wall-clock render timing (#5878) for a CHAINED render's stitched entry. A
+// chain writes its chunk rows `hidden: true`, so this is the only row the user
+// ever sees. Chunks render sequentially, so the honest number is the span from
+// the first chunk's start to now — it includes the inter-chunk trimming and
+// this concat, which summing the chunks' own `renderMs` would drop. A
+// hand-stitched clip is assembled from renders that already existed and gets
+// nothing; so does a chain missing any chunk's start instant, rather than a
+// span measured from a later chunk.
+const chainRenderTiming = (videos, historyKey) => {
+ if (historyKey !== 'chainedFrom') return {};
+ const starts = videos.map((v) => Date.parse(v.renderStartedAt));
+ return starts.every(Number.isFinite) ? renderTimingFields(Math.min(...starts)) : {};
+};
+
// Fold the per-chunk DRAFTDECODE: reports into one claim, or none. Unanimity is
// on the `applied` verdict rather than deep equality: two chunks that both fell
// back agree about the clip's fidelity even if their failure reasons differ.
@@ -199,6 +214,7 @@ export async function stitchVideos(videoIds, opts = {}) {
filename: outFilename,
thumbnail: thumb,
createdAt: new Date().toISOString(),
+ ...chainRenderTiming(videos, historyKey),
[historyKey]: videoIds,
...(Array.isArray(chunkPrompts) ? { chunkPrompts } : {}),
// The stitched clip is the chain's visible history row, so it must carry
diff --git a/server/services/videoGen/upscaleVideo.js b/server/services/videoGen/upscaleVideo.js
index 4ffc767b65..4e5c9e7ccb 100644
--- a/server/services/videoGen/upscaleVideo.js
+++ b/server/services/videoGen/upscaleVideo.js
@@ -8,6 +8,7 @@ import { PATHS, UUID_RE } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { safeUnder, generateThumbnail, upscaleVideo2x } from '../../lib/ffmpeg.js';
import { loadHistory, mutateVideoHistory } from './history.js';
+import { renderTimingFields } from '../../lib/renderTiming.js';
const UPLOADED_HISTORY_ID_RE = /^upload-[a-f0-9]{8}$/i;
@@ -45,6 +46,12 @@ export async function upscaleHistoryItem(historyId) {
// Copy first, then upscale-in-place — keeps the upscaler's atomic-rename
// contract intact and means a mid-process kill leaves the source clip
// untouched.
+ // Wall-clock timing (#5878) for the pass the user actually waits through.
+ // The entry below is built by spreading the SOURCE row, so without this it
+ // would inherit — and display — the original render's duration for work it
+ // never did. Overriding is the fix rather than stripping: an upscale produces
+ // its own gallery card, and the ffmpeg pass is a real cost worth reporting.
+ const renderStartedAtMs = Date.now();
await copyFile(sourcePath, newPath);
console.log(`🔍 Upscaling video [${historyId.slice(0, 8)} → ${newId.slice(0, 8)}]: 2×`);
const result = await upscaleVideo2x(newPath);
@@ -69,6 +76,9 @@ export async function upscaleHistoryItem(historyId) {
// Drop hidden so the upscaled version surfaces in the visible gallery
// even when the source clip was hidden.
hidden: false,
+ // AFTER the `...item` spread above so this pass's own timing replaces the
+ // source render's inherited fields.
+ ...renderTimingFields(renderStartedAtMs),
};
// Serialized append (re-reads inside the mutator) so a concurrent
// download/render write can't drop the upscaled entry.