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: stream media uploads without file size caps

[._.]/ Adam Eivy49ad027da80f
diff --git a/client/src/components/apps/LaunchVideoPanel.jsx b/client/src/components/apps/LaunchVideoPanel.jsx
index c6146a63e4..b19a8a274f 100644
--- a/client/src/components/apps/LaunchVideoPanel.jsx
+++ b/client/src/components/apps/LaunchVideoPanel.jsx
@@ -15,7 +15,6 @@ import { createAppLaunchVideo, getAppLaunchVideos, getMotionToolkit, publishAppL
import { listPipelineMusicLibrary } from '../../services/apiPipeline';
import { uploadFile } from '../../services/apiMedia';
import { trackAudioUrl } from '../../services/apiTracks';
-import { readFileAsBase64, JSON_UPLOAD_MAX_FILE_SIZE } from '../../utils/fileUpload';
import { formatBytes, formatDateTime, formatDurationSec } from '../../utils/formatters';
import toast from '../ui/Toast';
@@ -96,11 +95,8 @@ function LaunchVideoForm({ appId, onQueued }) {
const VIDEO_TYPES = ['video/mp4', 'video/webm', 'video/quicktime', 'video/x-m4v'];
const kind = VIDEO_TYPES.includes(file.type) ? 'video' : IMAGE_TYPES.includes(file.type) ? 'image' : null;
if (!kind) { toast.error('Choose a PNG, JPEG, WEBP, GIF, MP4, WebM, MOV or M4V file'); return; }
- if (file.size > JSON_UPLOAD_MAX_FILE_SIZE) { toast.error(`File is too large (${formatBytes(file.size)}). Max ${formatBytes(JSON_UPLOAD_MAX_FILE_SIZE)}.`); return; }
setReferenceUploading(true);
- const base64 = await readFileAsBase64(file).catch(() => null);
- if (!base64) { setReferenceUploading(false); toast.error(`Failed to read ${file.name}`); return; }
- const saved = await uploadFile(base64, file.name, { silent: true }).catch(err => { toast.error(err?.message || 'Upload failed'); return null; });
+ const saved = await uploadFile(file, file.name, { silent: true }).catch(err => { toast.error(err?.message || 'Upload failed'); return null; });
setReferenceUploading(false);
if (!saved?.filename) return;
setReference({ kind, source: 'upload', filename: saved.filename, label: file.name, previewUrl: null });
diff --git a/client/src/components/codeAnimation/CodeAnimationPreview.jsx b/client/src/components/codeAnimation/CodeAnimationPreview.jsx
index cdb8f5bdf6..222ee61388 100644
--- a/client/src/components/codeAnimation/CodeAnimationPreview.jsx
+++ b/client/src/components/codeAnimation/CodeAnimationPreview.jsx
@@ -3,7 +3,6 @@ import { Circle, Download, FileCode2, LoaderCircle, Save } from 'lucide-react';
import { Link } from 'react-router';
import toast from '../ui/Toast';
import { uploadGalleryVideo } from '../../services/api';
-import { readFileAsBase64 } from '../../utils/fileUpload';
import { downloadBlob } from '../../lib/downloadBlob';
// Seconds past the film's own duration before a silent recording is abandoned
@@ -180,13 +179,10 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGl
const handleSave = async () => {
if (!video || video.saved || saving) return;
setSaving(true);
- const base64 = await readFileAsBase64(video.blob).catch(() => null);
- const saved = base64
- ? await uploadGalleryVideo(base64, `${fileBase}.webm`, { silent: true }).catch((error) => {
- toast.error(error.message || 'Failed to save the video');
- return null;
- })
- : null;
+ const saved = await uploadGalleryVideo(video.blob, `${fileBase}.webm`, { silent: true }).catch((error) => {
+ toast.error(error.message || 'Failed to save the video');
+ return null;
+ });
setSaving(false);
if (saved?.id) {
setVideo((current) => (current?.blob === video.blob ? { ...current, saved: true } : current));
diff --git a/client/src/components/imageGen/GalleryImagePicker.jsx b/client/src/components/imageGen/GalleryImagePicker.jsx
index 2e62ec8ed8..6acfcc70df 100644
--- a/client/src/components/imageGen/GalleryImagePicker.jsx
+++ b/client/src/components/imageGen/GalleryImagePicker.jsx
@@ -11,7 +11,7 @@
// then selected exactly like a gallery image — the same source-image flow the
// image→3D page feeds to createImageTo3dModel. Hosts get one modal for both
// "reuse an image" and "upload a new one" instead of a separate file `<input>`
-// beside the picker; `maxBytes` narrows the size cap below the wire limit.
+// beside the picker. Uploads have no default file-size limit.
//
// Local gallery only — no external/web search (deliberate, see plan).
@@ -25,7 +25,7 @@ import { listImageGalleryFacets } from '../../services/apiImageVideo';
import { listUniverseNames } from '../../services/apiUniverseBuilder';
import { uploadGalleryImage } from '../../services/apiSystem';
import {
- readFileAsBase64, validateImageFile, JSON_UPLOAD_MAX_FILE_SIZE, UPLOAD_IMAGE_ACCEPT,
+ validateImageFile, UPLOAD_IMAGE_ACCEPT,
} from '../../utils/fileUpload';
import { useGalleryPage } from '../../hooks/useGalleryPage';
import { humanizeCategory } from '../../lib/universeBuilderShared';
@@ -52,7 +52,7 @@ const byLabel = (a, b) => a.label.localeCompare(b.label);
const asText = (value) => (typeof value === 'string' && value.trim() ? value : null);
export default function GalleryImagePicker({
- open, onClose, onSelect, allowUpload = false, maxBytes = JSON_UPLOAD_MAX_FILE_SIZE,
+ open, onClose, onSelect, allowUpload = false, maxBytes = Infinity,
}) {
const [facets, setFacets] = useState({ universes: [], categories: [], kinds: [], collections: [] });
const [uploading, setUploading] = useState(false);
@@ -105,16 +105,12 @@ export default function GalleryImagePicker({
const handleUpload = async (event) => {
const file = event.target.files?.[0];
if (!file) return;
- // Drag-drop and clipboard paste bypass the picker's `accept`, and an
- // oversized body only fails as an opaque 413 — so gate here, not just in the
- // file dialog. `maxBytes` lets a host keep a tighter product cap than the wire limit.
+ // Validate the format as well as the input's accept hint.
const invalid = validateImageFile(file, maxBytes);
if (invalid) { toast.error(invalid); return; }
const session = sessionRef.current;
setUploading(true);
- const base64 = await readFileAsBase64(file).catch(() => null);
- if (!base64) { setUploading(false); toast.error(`Failed to read ${file.name}`); return; }
- const saved = await uploadGalleryImage(base64, { silent: true }).catch((err) => {
+ const saved = await uploadGalleryImage(file, { silent: true }).catch((err) => {
toast.error(err?.message || 'Upload failed');
return null;
});
diff --git a/client/src/components/music/AlbumsManager.jsx b/client/src/components/music/AlbumsManager.jsx
index 2f13aa760c..a0fcd30ec2 100644
--- a/client/src/components/music/AlbumsManager.jsx
+++ b/client/src/components/music/AlbumsManager.jsx
@@ -32,7 +32,6 @@ import {
// Cap cover uploads so the base64 round-trip stays small. Enforced by
// GalleryImagePicker's `maxBytes`.
-const COVER_MAX_BYTES = 12 * 1024 * 1024;
const emptyForm = () => ({
title: '', artistId: '', artist: '', description: '', genre: '', releaseYear: '', coverImageUrl: '', trackIds: [],
@@ -412,7 +411,7 @@ export default function AlbumsManager() {
</div>
</div>
- <GalleryImagePicker open={galleryOpen} onClose={() => setGalleryOpen(false)} onSelect={handleCoverPick} allowUpload maxBytes={COVER_MAX_BYTES} />
+ <GalleryImagePicker open={galleryOpen} onClose={() => setGalleryOpen(false)} onSelect={handleCoverPick} allowUpload />
<AlbumTrackPicker open={trackPickerOpen} tracks={availableTracks} onClose={() => setTrackPickerOpen(false)} onAdd={addTracks} />
</div>
);
diff --git a/client/src/components/persona/PersonaMasterDetail.jsx b/client/src/components/persona/PersonaMasterDetail.jsx
index b078c8ac3d..816d437e4b 100644
--- a/client/src/components/persona/PersonaMasterDetail.jsx
+++ b/client/src/components/persona/PersonaMasterDetail.jsx
@@ -10,7 +10,6 @@ import { useConfirmDelete } from '../../hooks/useConfirmDelete';
import useMediaJobProgress from '../../hooks/useMediaJobProgress';
import { DEFAULT_NEGATIVE_PROMPT } from '../../lib/imageGenDefaults';
-const PERSONA_IMAGE_MAX_BYTES = 12 * 1024 * 1024;
const byName = (a, b) => (a.name || '').localeCompare(b.name || '');
export default function PersonaMasterDetail({
@@ -298,7 +297,7 @@ export default function PersonaMasterDetail({
</div>
</div>
- <GalleryImagePicker open={galleryOpen} onClose={() => setGalleryOpen(false)} onSelect={handleImagePick} allowUpload maxBytes={PERSONA_IMAGE_MAX_BYTES} />
+ <GalleryImagePicker open={galleryOpen} onClose={() => setGalleryOpen(false)} onSelect={handleImagePick} allowUpload />
</div>
);
}
diff --git a/client/src/components/videoGen/GalleryVideoPicker.jsx b/client/src/components/videoGen/GalleryVideoPicker.jsx
index 599a5cb930..b493d48673 100644
--- a/client/src/components/videoGen/GalleryVideoPicker.jsx
+++ b/client/src/components/videoGen/GalleryVideoPicker.jsx
@@ -18,9 +18,7 @@ import MediaCard from '../media/MediaCard';
import { normalizeVideo } from '../media/normalize';
import { listVideoHistory, uploadGalleryVideo } from '../../services/apiImageVideo';
import { uploadFile } from '../../services/apiMedia';
-import { readFileAsBase64, JSON_UPLOAD_MAX_FILE_SIZE } from '../../utils/fileUpload';
import { buildMediaHaystack, tokenizeQuery, matchHaystack } from '../../lib/mediaSearch';
-import { formatBytes } from '../../utils/formatters';
import toast from '../ui/Toast';
const VIDEO_ACCEPT = 'video/mp4,video/webm,video/quicktime,video/x-m4v,.mp4,.webm,.mov,.m4v';
@@ -77,17 +75,10 @@ export default function GalleryVideoPicker({
const handleUpload = async (event) => {
const file = event.target.files?.[0];
if (!file) return;
- if (file.size > JSON_UPLOAD_MAX_FILE_SIZE) {
- toast.error(`Video is too large (${formatBytes(file.size)}). Max ${formatBytes(JSON_UPLOAD_MAX_FILE_SIZE)}.`);
- return;
- }
const session = sessionRef.current;
setUploading(true);
- const base64 = await readFileAsBase64(file).catch(() => null);
- if (sessionRef.current !== session) return;
- if (!base64) { setUploading(false); toast.error(`Failed to read ${file.name}`); return; }
if (uploadToGallery) {
- const entry = await uploadGalleryVideo(base64, file.name, { silent: true }).catch((err) => {
+ const entry = await uploadGalleryVideo(file, file.name, { silent: true }).catch((err) => {
if (sessionRef.current === session) toast.error(err?.message || 'Upload failed');
return null;
});
@@ -98,7 +89,7 @@ export default function GalleryVideoPicker({
onClose?.();
return;
}
- const saved = await uploadFile(base64, file.name, { silent: true }).catch((err) => {
+ const saved = await uploadFile(file, file.name, { silent: true }).catch((err) => {
if (sessionRef.current === session) toast.error(err?.message || 'Upload failed');
return null;
});
diff --git a/client/src/components/videoGen/GalleryVideoPicker.test.jsx b/client/src/components/videoGen/GalleryVideoPicker.test.jsx
index 7aaf854339..8fe4157c7f 100644
--- a/client/src/components/videoGen/GalleryVideoPicker.test.jsx
+++ b/client/src/components/videoGen/GalleryVideoPicker.test.jsx
@@ -66,8 +66,10 @@ describe('GalleryVideoPicker', () => {
await waitFor(() => expect(screen.getByText('a neon chase')).toBeInTheDocument());
// The modal renders through a portal, so query the document, not the container.
const fileInput = document.querySelector('input[type="file"]');
- fireEvent.change(fileInput, { target: { files: [new File(['x'], 'clip.mp4', { type: 'video/mp4' })] } });
- await waitFor(() => expect(uploadGalleryVideo).toHaveBeenCalledWith('ZmFrZQ==', 'clip.mp4', { silent: true }));
+ const largeFile = new File(['x'], 'clip.mp4', { type: 'video/mp4' });
+ Object.defineProperty(largeFile, 'size', { value: 2 ** 32 });
+ fireEvent.change(fileInput, { target: { files: [largeFile] } });
+ await waitFor(() => expect(uploadGalleryVideo).toHaveBeenCalledWith(expect.any(File), 'clip.mp4', { silent: true }));
await waitFor(() => expect(onSelect).toHaveBeenCalledWith(
expect.objectContaining({
kind: 'video',
diff --git a/client/src/hooks/useMusicVideoTakes.js b/client/src/hooks/useMusicVideoTakes.js
index 32dd8b1fd4..ddcdf4c11d 100644
--- a/client/src/hooks/useMusicVideoTakes.js
+++ b/client/src/hooks/useMusicVideoTakes.js
@@ -11,8 +11,7 @@ import {
import { uploadGalleryImage } from '../services/apiSystem.js';
import { uploadGalleryVideo } from '../services/apiImageVideo.js';
import { downloadBlob } from '../lib/downloadBlob.js';
-import { readFileAsBase64, validateImageFile, JSON_UPLOAD_MAX_FILE_SIZE } from '../utils/fileUpload.js';
-import { formatBytes } from '../utils/formatters.js';
+import { validateImageFile } from '../utils/fileUpload.js';
// Mirrors the server's handoff import cap, checked BEFORE uploading so an
// oversized pick can't leave a gallery full of files nothing imported.
@@ -20,12 +19,10 @@ const MAX_HANDOFF_FILES = 200;
// The video formats the gallery video upload can container-sniff.
const HANDOFF_VIDEO_TYPES = new Set(['video/mp4', 'video/quicktime', 'video/webm']);
-// Why a picked file can't be uploaded, or null. Both uploads are one base64
-// JSON body, so both share the wire cap.
+// Why a picked file can't be uploaded, or null.
function handoffFileProblem(file, isVideo) {
- if (!isVideo) return validateImageFile(file, JSON_UPLOAD_MAX_FILE_SIZE);
+ if (!isVideo) return validateImageFile(file, Infinity);
if (!HANDOFF_VIDEO_TYPES.has(file.type)) return `File "${file.name}" is not an MP4, MOV, or WebM video`;
- if (file.size > JSON_UPLOAD_MAX_FILE_SIZE) return `File "${file.name}" exceeds the ${formatBytes(JSON_UPLOAD_MAX_FILE_SIZE)} limit`;
return null;
}
@@ -124,12 +121,10 @@ export default function useMusicVideoTakes({ project, applyScenePatch }) {
const isVideo = typeof file.type === 'string' && file.type.startsWith('video/');
const invalid = handoffFileProblem(file, isVideo);
if (invalid) { failures.push(invalid); continue; }
- const base64 = await readFileAsBase64(file).catch(() => null);
- if (!base64) { failures.push(`Failed to read ${file.name}`); continue; }
- // Sequential on purpose: each upload is a whole file in one JSON body.
+ // Sequential uploads keep disk and decode work bounded.
const saved = await (isVideo
- ? uploadGalleryVideo(base64, file.name, { silent: true })
- : uploadGalleryImage(base64, { silent: true })
+ ? uploadGalleryVideo(file, file.name, { silent: true })
+ : uploadGalleryImage(file, { silent: true })
).catch((err) => { failures.push(`${file.name}: ${err?.message || 'upload failed'}`); return null; });
const assetId = isVideo ? saved?.id : saved?.filename;
if (assetId) items.push({ kind: isVideo ? 'video' : 'image', assetId, originalName: file.name });
diff --git a/client/src/pages/CodeAnimation.jsx b/client/src/pages/CodeAnimation.jsx
index 242511cd97..1d42407c6d 100644
--- a/client/src/pages/CodeAnimation.jsx
+++ b/client/src/pages/CodeAnimation.jsx
@@ -25,7 +25,7 @@ import {
} from '../services/api';
import { copyToClipboard } from '../lib/clipboard';
import { safeReadJsonStorage, safeWriteJsonStorage } from '../lib/safeStorage';
-import { readFileAsBase64, UPLOAD_IMAGE_ACCEPT, validateImageFile } from '../utils/fileUpload';
+import { UPLOAD_IMAGE_ACCEPT, validateImageFile } from '../utils/fileUpload';
import { formatCount, timeAgo } from '../utils/formatters';
const DRAFT_KEY = 'portos.codeAnimation.draft';
@@ -256,12 +256,7 @@ const providerFilter = (provider) => provider.enabled !== false;
// Read + upload one file; toasts and resolves null on failure.
async function uploadOrToast(file) {
- const base64 = await readFileAsBase64(file).catch(() => null);
- if (!base64) {
- toast.error(`Failed to read ${file.name}`);
- return null;
- }
- return uploadFile(base64, file.name, { silent: true }).catch((error) => {
+ return uploadFile(file, file.name, { silent: true }).catch((error) => {
toast.error(error.message || `Failed to upload ${file.name}`);
return null;
});
@@ -413,7 +408,7 @@ export default function CodeAnimation() {
const room = Math.max(0, maxRefs - draft.referenceImages.length);
if (files.length > room) toast.error(`Only ${room} more reference image(s) fit`);
const valid = files.slice(0, room).filter((file) => {
- const invalid = validateImageFile(file);
+ const invalid = validateImageFile(file, Infinity);
if (invalid) toast.error(invalid);
return !invalid;
});
diff --git a/client/src/pages/Uploads.jsx b/client/src/pages/Uploads.jsx
index 02d6be04ec..df543d9021 100644
--- a/client/src/pages/Uploads.jsx
+++ b/client/src/pages/Uploads.jsx
@@ -2,12 +2,11 @@ import { useState, useEffect, useCallback } from 'react';
import { Upload, Trash2, Download, FileText, Image, File, FolderOpen, RefreshCw } from 'lucide-react';
import { useConfirmDelete } from '../hooks/useConfirmDelete';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
-import { formatDateTime, formatBytes } from '../utils/formatters';
+import { formatDateTime } from '../utils/formatters';
import toast from '../components/ui/Toast';
import PageSkeleton from '../components/ui/PageSkeleton';
import FilePickerButton from '../components/ui/FilePickerButton';
import * as api from '../services/api';
-import { JSON_UPLOAD_MAX_FILE_SIZE } from '../utils/fileUpload';
// File type icons based on MIME type
function getFileIcon(mimeType) {
@@ -53,32 +52,7 @@ export default function Uploads() {
const fileArray = Array.from(files);
for (const file of fileArray) {
- if (file.size > JSON_UPLOAD_MAX_FILE_SIZE) {
- toast.error(`File "${file.name}" exceeds the ${formatBytes(JSON_UPLOAD_MAX_FILE_SIZE)} limit`);
- continue;
- }
-
- // Read file as base64
- const base64 = await new Promise((resolve) => {
- const reader = new FileReader();
- reader.onload = (e) => {
- const result = e.target?.result;
- if (typeof result === 'string') {
- resolve(result.split(',')[1]);
- } else {
- resolve(null);
- }
- };
- reader.onerror = () => resolve(null);
- reader.readAsDataURL(file);
- });
-
- if (!base64) {
- toast.error(`Failed to read file "${file.name}"`);
- continue;
- }
-
- const result = await api.uploadFile(base64, file.name, { silent: true }).catch(err => {
+ const result = await api.uploadFile(file, file.name, { silent: true }).catch(err => {
toast.error(`Failed to upload "${file.name}": ${err.message}`);
return null;
});
@@ -213,7 +187,7 @@ export default function Uploads() {
{uploading ? 'Uploading...' : 'Browse Files'}
</FilePickerButton>
<p className="text-gray-500 text-xs mt-4">
- Maximum file size: {formatBytes(JSON_UPLOAD_MAX_FILE_SIZE)}
+ No file size limit
</p>
</div>
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 2caba82282..cb5b85a325 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -29,7 +29,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| File | Purpose |
|---|---|
| `api.js` | Barrel — re-exports every `apiX.js`. |
-| `apiCore.js` | `request()` helper + stable PortOS-app id. Shared error / toast handling. |
+| `apiCore.js` | `request()` and `uploadBody()` (stream File/Blob multipart; legacy base64 JSON) + stable PortOS-app id. Shared error / toast handling. |
| `apiBatch.js` | `fetchByIds(path, ids, options)` — batch-fetch records through a list route's `?ids=a,b,c` filter (dedupe, empty-list short-circuit, `{ items }` envelope unwrap). |
| `socket.js` | Singleton Socket.IO client over relative path (Tailscale-friendly). |
| `appUrls.js` | Compute candidate launch URLs for an app from page context. |
diff --git a/client/src/services/apiCore.js b/client/src/services/apiCore.js
index 1dc7a2b7f7..ad332c48c9 100644
--- a/client/src/services/apiCore.js
+++ b/client/src/services/apiCore.js
@@ -141,3 +141,13 @@ export default {
}),
delete: (endpoint, options) => request(endpoint, { method: 'DELETE', ...options })
};
+
+// File/Blob uploads stream as multipart; retain base64 JSON for older callers.
+export function uploadBody(data, filename) {
+ if (typeof Blob !== 'undefined' && data instanceof Blob) {
+ const body = new FormData();
+ body.append('file', data, filename || data.name || 'upload');
+ return body;
+ }
+ return JSON.stringify({ data, ...(filename ? { filename } : {}) });
+}
diff --git a/client/src/services/apiCore.test.js b/client/src/services/apiCore.test.js
index 2d67dd0950..d494171ac7 100644
--- a/client/src/services/apiCore.test.js
+++ b/client/src/services/apiCore.test.js
@@ -13,7 +13,7 @@ vi.mock('../components/ui/Toast', () => {
});
import toast from '../components/ui/Toast';
-import { throwApiError, request } from './apiCore.js';
+import { throwApiError, request, uploadBody } from './apiCore.js';
const makeResponse = ({ status = 400, ok = false, json = null } = {}) => ({
status,
@@ -105,3 +105,15 @@ describe('request() error path (now delegating to throwApiError)', () => {
expect(toast.error).not.toHaveBeenCalled();
});
});
+
+
+it('streams Blob uploads with a browser boundary and retains legacy JSON callers', async () => {
+ const file = new Blob(['video bytes'], { type: 'video/mp4' });
+ global.fetch.mockResolvedValue({ ok: true, json: async () => ({ filename: 'saved.mp4' }) });
+ await request('/video-gen/upload', { method: 'POST', body: uploadBody(file, 'clip.mp4') });
+ const [, options] = global.fetch.mock.calls[0];
+ expect(options.headers).not.toHaveProperty('Content-Type');
+ expect(options.body.get('file').name).toBe('clip.mp4');
+ expect(await options.body.get('file').text()).toBe('video bytes');
+ expect(JSON.parse(uploadBody('YWJj', 'old.mp4'))).toEqual({ data: 'YWJj', filename: 'old.mp4' });
+});
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 2383c01b78..7b81ee6f93 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -1,4 +1,4 @@
-import { request, API_BASE, throwApiError } from './apiCore.js';
+import { uploadBody, request, API_BASE, throwApiError } from './apiCore.js';
import { filterHardwareCompatibleModels } from '../utils/systemCapabilities.js';
// Image gen — local backend extras (gallery, models, LoRAs, cancel, delete).
@@ -268,7 +268,7 @@ export const getVideoHistoryItem = (id, options = {}) => request(`/video-gen/his
// dir. Returns the history entry; feed it through normalizeVideo to display.
export const uploadGalleryVideo = (base64Data, filename, options = {}) => request('/video-gen/upload', {
method: 'POST',
- body: JSON.stringify({ data: base64Data, ...(filename ? { filename } : {}) }),
+ body: uploadBody(base64Data, filename),
...options,
});
export const deleteVideoHistoryItem = (id, options = {}) => request(`/video-gen/history/${encodeURIComponent(id)}`, { method: 'DELETE', ...options });
diff --git a/client/src/services/apiMedia.js b/client/src/services/apiMedia.js
index e0748473e3..75ee300e65 100644
--- a/client/src/services/apiMedia.js
+++ b/client/src/services/apiMedia.js
@@ -1,4 +1,4 @@
-import { request, API_BASE, throwApiError } from './apiCore.js';
+import { uploadBody, request, API_BASE, throwApiError } from './apiCore.js';
import { formatBytes } from '../utils/formatters.js';
import {
validateImageFile,
@@ -243,7 +243,7 @@ async function uploadAttachmentFile(file, options = {}) {
// Uploads (general file storage)
export const uploadFile = (base64Data, filename, options = {}) => request('/uploads', {
method: 'POST',
- body: JSON.stringify({ data: base64Data, filename }),
+ body: uploadBody(base64Data, filename),
...options
});
export const listUploads = (options = {}) => request('/uploads', options);
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index bb61328f85..6a370dbf91 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -1,4 +1,4 @@
-import { request, API_BASE, throwApiError } from './apiCore.js';
+import { uploadBody, request, API_BASE, throwApiError } from './apiCore.js';
import { downloadBlob } from '../lib/downloadBlob.js';
export const rectifyModelDuplicates = (payload, options = {}) => request('/system-resources/duplicates/rectify', {
@@ -506,7 +506,7 @@ export const generateAvatar = (data, options = {}) => request('/image-gen/avatar
// URL must sync to peers — the `image` asset path only ships `/data/images/<f>`.
export const uploadGalleryImage = (base64Data, options = {}) => request('/image-gen/upload', {
method: 'POST',
- body: JSON.stringify({ data: base64Data }),
+ body: uploadBody(base64Data),
...options,
});
diff --git a/server/lib/README.md b/server/lib/README.md
index 68c85398a3..bd2259edac 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -362,7 +362,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `imageRgba.js` | Sharp-backed RGBA boundary: `decodeRgbaFrame` decodes an image to `{ data, width, height }`, and `encodePng` turns a raw frame into PNG bytes for the caller's destination/hash policy. |
| `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. |
| `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). |
-| `pngMetadata.js` | Bounded PNG `tEXt`/`zTXt`/`iTXt` extraction for Stable Diffusion-compatible provenance plus normalization of prompt, negative prompt, sampler, steps, CFG, seed, size, model, and model hash fields; `GENERATION_METADATA_LIMITS` shares the projection bounds with catalog sync validation. Pure. |
+| `pngMetadata.js` | `extractPngGenerationMetadataFile` seeks past pixel data for bounded disk-file metadata extraction. Bounded PNG `tEXt`/`zTXt`/`iTXt` extraction for Stable Diffusion-compatible provenance plus normalization of prompt, negative prompt, sampler, steps, CFG, seed, size, model, and model hash fields; `GENERATION_METADATA_LIMITS` shares the projection bounds with catalog sync validation. Pure. |
| `threejsModel.js` | Validated declarative procedural-model schema plus deterministic standalone Three.js factory export for the Three.js Models workspace. Also the cross-section gate: `evaluateThreejsFlatness(spec)` counts distinct vertex planes per axis — relative to the mesh's own size, with a rotation-invariant zero-volume check behind it — and treats an `extrude` with no bevel thickness as the two-plane slab it is to report when the majority of identity-priority features are built only from flat parts — a model that reads right head-on and like cardboard when orbited. `buildThreejsFlatnessFeedback(flatness)` turns that into default refinement feedback; `listSpecNames(names)` is the shared capped name-list formatter both gates use in finding messages. Also the material-plausibility gate: `evaluateThreejsMaterialPlausibility(spec)` keys a bounded per-family prior table (metal, wood, plastic, glass, fabric, ceramic, rubber, stone, leather, paper) off tokens in each material's id and reports channels whose values the named substance does not support — metalness 0.9 oak, transmission 1.0 steel — skipping any id that names no family or two, and any channel the material's `type` never forwards to Three.js. Advisory only: it never clamps, because a stylized model may legitimately break every prior. `buildThreejsMaterialFeedback(plausibility)` turns that into default refinement feedback. The same pass emits a `reflective-material-without-environment` note when a spec authors reflective channels (metalness above 0.6, or any transmission/clearcoat/iridescence) while `environment.preset` is `none` — those channels read off an environment, so in that scene their values cannot be judged at all. Attachments are declared in two forms — the original anchor-less `attachmentPartIds` and the anchored `attachments: [{ partId, anchorPartId | anchorSocket, maxOffset }]` — and `resolveThreejsAttachments(articulation)` merges them into one canonical list (an anchored entry wins over a bare id) so every gate reads the same set; `isThreejsAttachmentAnchored(attachment)` is the shared anchored/unanchored predicate and `DEFAULT_ATTACHMENT_MAX_OFFSET` the default tolerance. The spec-level refinement rejects an anchor that does not resolve, one that is the attachment itself, an anchor chain that cycles, and the model root (the sole top-level part) — which carries no relationship to any body part. The spec carries an optional `environment` block (see `threejsModelEnvironment.js`), and `buildThreejsFactorySource()` stamps its render profile onto `root.userData.sculptRuntime.render` and exports it as `renderProfile`, so a consumer wiring their own `WebGLRenderer` reproduces the model instead of a differently tone-mapped approximation. |
| `threejsModelAnimation.js` | `summarizeThreejsAnimation(spec)` — clip inventory *and* playback gate over an already-validated Three.js spec: `{ animated, clipCount, cueCount, sequenceCount, movingPartCount, longestClipSeconds, findings, warningCount, clips }`. The schema proves a declared `animation` block is well *formed* (sequences on real parts, inside their clip, never two on one channel at once, never a cue without motion); this reports what the model *declared* — one entry per clip with its role, duration, sequence and distinct-cue counts — plus the ways a well-formed clip still plays badly: a clip authored against a pose the assembly does not build (`clip-start-pose-mismatch`), a handover between sequences that do not meet (`clip-sequence-jump`), a `loop: true` clip that does not return to where it began, a one-shot `idle`, an unfired cue, a long dead tail, and an articulation graph with no clip at all. Advisory warnings only — a static assembly is a complete answer. `buildThreejsAnimationFeedback(animation)` turns those findings into default refinement feedback. A spec with no `animation` key summarizes as not animated — never as evaluated-and-empty. |
| `threejsModelCoverage.js` | `evaluateThreejsPartCoverage(spec, { family })` — structural assembly gate over an already-validated Three.js spec: flags promised features fused onto the same part set, geometry claimed by no detail, and details nothing was built for (folded minor relief stays a `note`). With a subject family it also warns on a required component the spec never mentions at all — the one check that can fault a spec for what it failed to *promise*. `buildThreejsCoverageFeedback(coverage)` turns the error findings (plus any family gap) into default refinement feedback. |
diff --git a/server/lib/pngMetadata.js b/server/lib/pngMetadata.js
index a140918ee4..64d4b5ddb4 100644
--- a/server/lib/pngMetadata.js
+++ b/server/lib/pngMetadata.js
@@ -5,6 +5,7 @@
// prompt provenance survives as structured application metadata instead of being
// lost with the source bytes.
+import { open } from 'node:fs/promises';
import { inflateSync } from 'node:zlib';
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
@@ -288,3 +289,33 @@ export function extractPngGenerationMetadata(value) {
}
return normalizeGenerationMetadata(result);
}
+
+// Seek past pixel data rather than reading a potentially huge PNG into memory.
+export async function extractPngGenerationMetadataFile(path) {
+ const file = await open(path, 'r');
+ try {
+ const signature = Buffer.alloc(8);
+ await file.read(signature, 0, 8, 0);
+ if (!signature.equals(PNG_SIGNATURE)) return {};
+ const { size } = await file.stat();
+ const chunks = [signature];
+ let offset = 8;
+ for (let count = 0; count < MAX_PNG_CHUNKS && offset + 12 <= size; count++) {
+ const header = Buffer.alloc(8);
+ await file.read(header, 0, 8, offset);
+ const length = header.readUInt32BE(0);
+ const type = header.toString('ascii', 4, 8);
+ if (offset + length + 12 > size) break;
+ if (TEXT_CHUNK_TYPES.has(type) && length <= MAX_TEXT_CHUNK_BYTES) {
+ const chunk = Buffer.alloc(length + 12);
+ await file.read(chunk, 0, chunk.length, offset);
+ chunks.push(chunk);
+ }
+ offset += length + 12;
+ if (type === 'IEND') break;
+ }
+ return extractPngGenerationMetadata(Buffer.concat(chunks));
+ } finally {
+ await file.close();
+ }
+}
diff --git a/server/lib/uploads.js b/server/lib/uploads.js
index 35ab36bcd8..f2f386609f 100644
--- a/server/lib/uploads.js
+++ b/server/lib/uploads.js
@@ -28,12 +28,13 @@ export async function importFileToDir(tempPath, originalName, destDir, { extensi
throw new ServerError('Invalid file type', { status: 400, code: 'INVALID_FILE_TYPE' });
}
await ensureDir(destDir);
- const filename = `${randomUUID().slice(0, 8)}-${sanitizeFilename(originalName)}`;
+ const id = randomUUID();
+ const filename = `${id.slice(0, 8)}-${sanitizeFilename(originalName)}`;
const dest = join(destDir, filename);
await copyFileGuarded(tempPath, dest);
await unlink(tempPath).catch(() => {});
const s = await stat(dest).catch(() => null);
- return { filename, sizeBytes: s?.size ?? 0 };
+ return { id, filename, sizeBytes: s?.size ?? 0 };
}
/**
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 8156473bcb..50275bfd41 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -16,7 +16,7 @@ import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.j
import {
validateRequest, imageEdgeSchema, refineImagePixelCap, PIXEL_CAP_MESSAGE,
} from '../lib/validation.js';
-import { optionalUploadFields } from '../lib/multipart.js';
+import { optionalUploadFields, optionalUpload } from '../lib/multipart.js';
import * as imageGen from '../services/imageGen/index.js';
import { local, IMAGE_GEN_MODE, IMAGE_GEN_MODES } from '../services/imageGen/index.js';
import { resolveCloudProviderConfig } from '../services/imageGen/cloudProviderConfig.js';
@@ -86,7 +86,6 @@ async function enqueueLoggedImage(req, job) {
const MAX_PROMPT_LENGTH = 8000;
const MAX_LORAS = 8;
const MAX_REFERENCE_IMAGES = 10;
-const MAX_IMAGE_UPLOAD_BYTES = 20 * 1024 * 1024;
const updatePromptSchema = z.object({ prompt: z.string().max(MAX_PROMPT_LENGTH) });
const galleryImageFilenameSchema = (label) => z.string().max(256)
.regex(/^[^/\\]+\.(png|jpg|jpeg|webp)$/i, `${label} must be a basename ending in png/jpg/jpeg/webp`);
@@ -260,7 +259,6 @@ const REFERENCE_IMAGE_FIELDS = Array.from({ length: MAX_REFERENCE_IMAGES }, (_,
const IMAGE_UPLOAD_FIELDS = ['initImage', ...REFERENCE_IMAGE_FIELDS];
const imageGenUploads = optionalUploadFields(IMAGE_UPLOAD_FIELDS, {
- limits: { fileSize: MAX_IMAGE_UPLOAD_BYTES },
fileFilter: (_req, file, cb) => cb(null, ACCEPTED_INIT_IMAGE_MIME.has((file.mimetype || '').toLowerCase())),
});
@@ -317,7 +315,7 @@ const avatarSchema = z.object({
// Upload a user-supplied image straight into the gallery (`data/images/`) so it
// rides the existing `image` peer-sync asset path. `data` is base64 (no data:
// URI prefix); the real format is sniffed server-side, so the schema only caps
-// the encoded string length (~16MB decoded ≈ 21.8M base64 chars).
+// the legacy JSON request. Multipart uploads have no size cap.
const uploadImageSchema = z.object({
data: z.string().min(1).max(24 * 1024 * 1024),
});
@@ -689,7 +687,14 @@ router.post('/avatar', asyncHandler(async (req, res) => {
// headshots) get a `/data/images/<f>` URL that the peer-sync `image` asset
// path can transfer — unlike `/api/uploads/<f>`, which is not a pullable
// asset kind and 404s on a peer.
-router.post('/upload', asyncHandler(async (req, res) => {
+router.post('/upload', optionalUpload('file'), asyncHandler(async (req, res) => {
+ if (req.file) {
+ try {
+ return res.json(await local.saveUploadedGalleryImage(null, req.file.path));
+ } finally {
+ await unlinkGuarded(req.file.path).catch(() => {});
+ }
+ }
const { data } = validateRequest(uploadImageSchema, req.body);
res.json(await local.saveUploadedGalleryImage(data));
}));
diff --git a/server/routes/uploads.js b/server/routes/uploads.js
index 8c887cd26e..2fcc7f6f78 100644
--- a/server/routes/uploads.js
+++ b/server/routes/uploads.js
@@ -10,8 +10,9 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import {
pathExists, PATHS, sanitizeFilename, getFileExtension, getMimeType,
EXTENSION_MIME_MAP, isPathInsideDir, saveBase64Upload, serveLocalFile,
- unlinkGuarded,
+ unlinkGuarded, importFileToDir,
} from '../lib/fileUtils.js';
+import { optionalUpload } from '../lib/multipart.js';
import { MAX_BASE64_UPLOAD_BYTES } from '../lib/uploadLimits.js';
import { validateRequest, uploadRequestSchema } from '../lib/validation.js';
@@ -44,8 +45,23 @@ function formatSize(bytes) {
return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
}
-// POST /api/uploads - Upload a file (base64)
-router.post('/', asyncHandler(async (req, res) => {
+// POST /api/uploads - Stream a file, or accept legacy base64 JSON
+router.post('/', optionalUpload('file'), asyncHandler(async (req, res) => {
+ if (req.file) {
+ try {
+ const saved = await importFileToDir(req.file.path, req.file.originalname, UPLOADS_DIR, {
+ extensions: [...UPLOAD_ALLOWED_EXTENSIONS],
+ });
+ return res.json({
+ id: saved.id, filename: saved.filename, originalName: req.file.originalname,
+ path: `/api/uploads/${encodeURIComponent(saved.filename)}`, size: saved.sizeBytes,
+ sizeFormatted: formatSize(saved.sizeBytes), mimeType: getMimeType(getFileExtension(saved.filename)),
+ createdAt: new Date().toISOString(),
+ });
+ } finally {
+ await unlinkGuarded(req.file.path).catch(() => {});
+ }
+ }
const { data, filename } = validateRequest(uploadRequestSchema, req.body);
// Shared pipeline: allowlist → decode → size cap → `<uuid8>-name` → write.
diff --git a/server/routes/uploads.test.js b/server/routes/uploads.test.js
index 1998aea4a6..aba0ed14ab 100644
--- a/server/routes/uploads.test.js
+++ b/server/routes/uploads.test.js
@@ -193,3 +193,24 @@ describe('uploads routes (#4101)', () => {
expect(after.body.totalSizeFormatted).toBe('0 B');
});
});
+
+
+describe('streamed uploads', () => {
+ it('accepts media beyond the JSON ceiling, persists the bytes, and rejects unsupported extensions', async () => {
+ const payload = Buffer.alloc(56 * 1024 * 1024, 7);
+ const multipart = (filename, bytes) => Buffer.concat([
+ Buffer.from(`--upload-test\r\nContent-Disposition: form-data; name="file"; filename="${filename}"\r\nContent-Type: video/mp4\r\n\r\n`),
+ bytes, Buffer.from('\r\n--upload-test--\r\n'),
+ ]);
+ const res = await request(buildApp()).post('/api/uploads')
+ .set('Content-Type', 'multipart/form-data; boundary=upload-test').send(multipart('large.mp4', payload));
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ originalName: 'large.mp4', size: payload.length, mimeType: 'video/mp4' });
+ expect(res.body.id).toMatch(/^[0-9a-f-]{36}$/);
+ expect(readFileSync(join(PATHS.uploads, res.body.filename)).equals(payload)).toBe(true);
+ const bad = await request(buildApp()).post('/api/uploads')
+ .set('Content-Type', 'multipart/form-data; boundary=upload-test').send(multipart('bad.exe', Buffer.from('bad')));
+ expect(bad.status).toBe(400);
+ expect(bad.body.code).toBe('INVALID_FILE_TYPE');
+ });
+});
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 7c5bc41ced..eb67804135 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -13,7 +13,7 @@ import os from 'os';
import { z } from 'zod';
import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
import { createVideoHistoryItemRead, historyRecordIdSchema } from './videoHistoryRead.js';
-import { uploadFields } from '../lib/multipart.js';
+import { uploadFields, optionalUpload } from '../lib/multipart.js';
import {
validateRequest, videoModelTermsSchema,
} from '../lib/validation.js';
@@ -78,7 +78,7 @@ import {
} from '../services/videoGen/modelCache.js';
import { startHfDownloadStream } from '../services/hfDownloadStream.js';
import { openSseStream } from '../lib/sseDownload.js';
-import { saveUploadedGalleryVideo } from '../services/videoUpload.js';
+import { saveUploadedGalleryVideo, saveUploadedGalleryVideoFile } from '../services/videoUpload.js';
import { JSON_BODY_LIMIT_BYTES } from '../lib/uploadLimits.js';
import {
FEDERATED_MEDIA_MAX_VIDEO_FRAMES,
@@ -163,12 +163,10 @@ export const isAudioMime = (mime, filename) => {
// FFLF accepts up to two image uploads (start and end frame); a2v takes one
// audio upload (audioFile); the IC-LoRA remix modes take one reference video
-// upload (icReference). Audio duration is not capped: the 100MB transport cap
-// is a file-size safety bound, so compressed inputs may be much longer than
-// lossless PCM inputs. Per-fieldname mime filtering rejects mismatched parts
+// upload (icReference). Files stream to disk without a file-size cap.
+// Per-fieldname mime filtering rejects mismatched parts
// up-front so a stray .mp4 drag-drop can't get staged under these fields.
const frameImageUpload = uploadFields(['sourceImage', 'lastImage', 'audioFile', 'icReference'], {
- limits: { fileSize: 100 * 1024 * 1024 },
fileFilter: (_req, file, cb) => {
const isImageField = file.fieldname === 'sourceImage' || file.fieldname === 'lastImage';
const isAudioField = file.fieldname === 'audioFile';
@@ -1115,16 +1113,20 @@ router.get('/history/:id', createVideoHistoryItemRead(getHistoryItem));
// POST /api/image-gen/upload. Lands the bytes under PATHS.videos with a
// `source: 'upload'` history entry so the file federates via the peer-sync
// asset manifest (unlike POST /api/uploads → data/uploads/, which does not).
-// The schema's string cap is the JSON body-parser limit itself — anything
-// longer 413s at the parser before this route runs — and the reachable cap
-// is the binary MAX_GALLERY_VIDEO_UPLOAD_BYTES check in the saver, both
-// derived from server/lib/uploadLimits.js so there is one source of truth.
+// Legacy base64 callers retain the JSON transport bounds; multipart files bypass them.
const uploadVideoSchema = z.object({
data: z.string().min(1).max(JSON_BODY_LIMIT_BYTES),
filename: z.string().max(255).optional(),
});
-router.post('/upload', asyncHandler(async (req, res) => {
+router.post('/upload', optionalUpload('file'), asyncHandler(async (req, res) => {
+ if (req.file) {
+ try {
+ return res.json(await saveUploadedGalleryVideoFile(req.file.path, req.file.originalname));
+ } finally {
+ await cleanupMultipartTemp(req.files);
+ }
+ }
const parsed = uploadVideoSchema.safeParse(req.body || {});
if (!parsed.success) failValidation(parsed);
const { data, filename } = parsed.data;
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 807a8f24a1..5bf390063e 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -236,6 +236,7 @@ const pendingUpload = { current: null };
const setPendingUpload = (...files) => { pendingUpload.current = files.flat(); };
vi.mock('../lib/multipart.js', () => ({
+ optionalUpload: () => (_req, _res, next) => next(),
// Bypass the streaming parser. If a test set a pending upload via
// setPendingUpload(), inject it under req.files keyed by fieldname so the
// route exercises the upload-staging path; otherwise pass through.
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 3d27066b5c..26f7f86807 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -14,13 +14,13 @@
import { spawn } from '../../lib/childProcess.js';
import sharp from 'sharp';
-import { readFile, readdir, stat, mkdtemp } from 'fs/promises';
+import { readFile, readdir, stat, mkdtemp, open, rename } from 'fs/promises';
import { existsSync, watch as fsWatch } from 'fs';
import { join, dirname, resolve as resolvePath, sep as PATH_SEP, basename } from 'path';
import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
import { atomicWrite, assertSafeFilename, detectImageFormat, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveImageInputPath, tryReadFile, rmGuarded, unlinkGuarded } from '../../lib/fileUtils.js';
-import { extractPngGenerationMetadata } from '../../lib/pngMetadata.js';
+import { extractPngGenerationMetadata, extractPngGenerationMetadataFile } from '../../lib/pngMetadata.js';
import { ServerError } from '../../lib/errorHandler.js';
import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { rejectDegenerateFrame } from './frameGuard.js';
@@ -1204,16 +1204,6 @@ export async function readImageSidecar(filename) {
return { path: portosSidecar, metadata: {} };
}
-// Cap on uploaded gallery image bytes (decoded). Headshots and similar
-// uploads never need more than a few MB; this is a defense-in-depth ceiling so
-// a hand-crafted request can't write an arbitrarily large file into the
-// gallery dir. The Authors page caps its own headshot upload well below this.
-const MAX_GALLERY_UPLOAD_BYTES = 16 * 1024 * 1024;
-// Cap decoded pixels too: a small compressed payload can still decode to a huge
-// canvas (decompression bomb), so the byte ceiling alone isn't enough. Mirrors
-// the cleaner's guard (lib/imageClean.js MAX_PIXELS) — sharp throws past it.
-const MAX_GALLERY_UPLOAD_PIXELS = 96 * 1000 * 1000;
-
async function refreshImageIndex(filename) {
await import('../mediaAssetIndex/index.js')
.then(m => m.indexImage({ filename }))
@@ -1231,31 +1221,43 @@ async function refreshImageIndex(filename) {
* `deleteImage`, both of which only manage `.png`. Returns the bare gallery
* filename and its `/data/images/` mount path for the caller to store.
*
- * @param {string} base64Data - Raw base64 (no data: URI prefix) image bytes
+ * @param {string|null} base64Data - Legacy raw base64 image bytes
+ * @param {string} [tempPath] - Server-staged multipart file, preferred over base64
* @returns {Promise<{ filename: string, path: string, metadata: object }>}
*/
-export async function saveUploadedGalleryImage(base64Data) {
- const buffer = Buffer.from(base64Data, 'base64');
- if (buffer.length === 0) {
- throw new ServerError('Empty image upload', { status: 400, code: 'VALIDATION_ERROR' });
+export async function saveUploadedGalleryImage(base64Data, tempPath) {
+ const input = tempPath || Buffer.from(base64Data, 'base64');
+ let header = input;
+ if (tempPath) {
+ const file = await open(tempPath, 'r');
+ header = Buffer.alloc(12);
+ await file.read(header, 0, header.length, 0).finally(() => file.close());
}
- if (buffer.length > MAX_GALLERY_UPLOAD_BYTES) {
- throw new ServerError(`Image exceeds maximum size of ${MAX_GALLERY_UPLOAD_BYTES / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });
+ if (!tempPath && input.length === 0) {
+ throw new ServerError('Empty image upload', { status: 400, code: 'VALIDATION_ERROR' });
}
- const detected = detectImageFormat(buffer);
+ const detected = detectImageFormat(header);
if (!detected) {
throw new ServerError('Unsupported image format (expected PNG, JPEG, WebP, or GIF)', { status: 400, code: 'UNSUPPORTED_IMAGE' });
}
// Read Stable Diffusion-compatible PNG text chunks before sharp normalizes
// the image. JPEG/WebP/GIF uploads simply produce an empty projection.
- const metadata = extractPngGenerationMetadata(buffer);
+ const metadata = tempPath
+ ? await extractPngGenerationMetadataFile(tempPath)
+ : extractPngGenerationMetadata(input);
// Normalize to PNG so the gallery's PNG-only list/delete paths manage it.
// `.rotate()` with no args bakes in EXIF orientation before the metadata is
// dropped, so a camera-JPEG portrait isn't saved sideways/upside-down.
- const png = await sharp(buffer, { limitInputPixels: MAX_GALLERY_UPLOAD_PIXELS }).rotate().png().toBuffer();
const filename = `upload-${randomUUID().slice(0, 8)}.png`;
await ensureDir(PATHS.images);
- await atomicWrite(join(PATHS.images, filename), png);
+ const output = join(PATHS.images, filename);
+ const staging = `${output}.tmp`;
+ try {
+ await sharp(input, { limitInputPixels: false }).rotate().png().toFile(staging);
+ await rename(staging, output);
+ } finally {
+ await unlinkGuarded(staging).catch(() => {});
+ }
// The normalized PNG intentionally has no source text chunks. Keep the
// bounded projection in the canonical gallery sidecar so gallery listings,
// media indexing, and later catalog attachments can still recover it.
@@ -1263,7 +1265,7 @@ export async function saveUploadedGalleryImage(base64Data) {
await atomicWrite(join(PATHS.images, filename.replace('.png', '.metadata.json')), metadata);
}
await refreshImageIndex(filename);
- console.log(`📥 Saved uploaded gallery image: ${filename} (${(png.length / 1024).toFixed(0)}KB PNG, from ${detected.mime})`);
+ console.log(`📥 Saved uploaded gallery image: ${filename} (PNG from ${detected.mime})`);
return { filename, path: `/data/images/${filename}`, metadata };
}
diff --git a/server/services/imageGen/saveUploadedGalleryImage.test.js b/server/services/imageGen/saveUploadedGalleryImage.test.js
index d80128f857..f821d353ed 100644
--- a/server/services/imageGen/saveUploadedGalleryImage.test.js
+++ b/server/services/imageGen/saveUploadedGalleryImage.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
-import { mkdtempSync, rmSync, existsSync, readFileSync } from 'fs';
+import { mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import sharp from 'sharp';
@@ -124,9 +124,14 @@ describe('saveUploadedGalleryImage', () => {
).rejects.toMatchObject({ status: 400, code: 'UNSUPPORTED_IMAGE' });
});
- it('rejects an oversized upload with a 400', async () => {
- // 17MB of zero bytes — over the 16MB ceiling, and not a valid image header.
- const huge = Buffer.alloc(17 * 1024 * 1024).toString('base64');
- await expect(saveUploadedGalleryImage(huge)).rejects.toMatchObject({ status: 400, code: 'FILE_TOO_LARGE' });
+ it('accepts a file above the former JSON ceiling and preserves PNG metadata', async () => {
+ const png = await sharp({ create: { width: 2, height: 2, channels: 3, background: 'red' } }).png().toBuffer();
+ const source = addPngText(png, 'parameters', 'A test image\nSteps: 20, Seed: 42');
+ const tempPath = join(tmpRoot, 'large.png');
+ // Trailing padding is legal input for the decoder, without a huge pixel allocation.
+ writeFileSync(tempPath, Buffer.concat([source, Buffer.alloc(56 * 1024 * 1024)]));
+ const saved = await saveUploadedGalleryImage(null, tempPath);
+ expect(saved.metadata.prompt).toBe('A test image');
+ expect(isPng(readFileSync(join(imagesDir, saved.filename)))).toBe(true);
});
});
diff --git a/server/services/videoUpload.js b/server/services/videoUpload.js
index 7b2daf24f2..5f1a77d9f4 100644
--- a/server/services/videoUpload.js
+++ b/server/services/videoUpload.js
@@ -19,18 +19,18 @@
* from the stem resolves identically on the sender and on every peer.
*/
+import { open, stat, rename } from 'fs/promises';
import { join } from 'path';
import { randomUUID } from 'crypto';
import { ServerError } from '../lib/errorHandler.js';
-import { PATHS, ensureDir, atomicWrite, unlinkGuarded } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, atomicWrite, unlinkGuarded, copyFileGuarded } from '../lib/fileUtils.js';
import { MAX_BASE64_UPLOAD_BYTES } from '../lib/uploadLimits.js';
import { generateThumbnail, probeVideoDuration } from '../lib/ffmpeg.js';
import { mutateVideoHistory } from './videoGen/history.js';
import { videoGenEvents } from './videoGen/events.js';
-// The largest raw file that fits the JSON body-parser limit once
-// base64-encoded — the single source of truth in uploadLimits.js, mirrored
-// client-side as JSON_UPLOAD_MAX_FILE_SIZE (the cap the picker enforces).
+// Compatibility export for the separate remote browser-download path.
+// User uploads stream to disk without this legacy JSON transport bound.
export const MAX_GALLERY_VIDEO_UPLOAD_BYTES = MAX_BASE64_UPLOAD_BYTES;
// Container sniff — extension comes from the BYTES, not the client filename.
@@ -73,10 +73,30 @@ export async function saveUploadedGalleryVideoBuffer(buffer, originalName = '')
if (buffer.length === 0) {
throw new ServerError('Empty video upload', { status: 400, code: 'VALIDATION_ERROR' });
}
- if (buffer.length > MAX_GALLERY_VIDEO_UPLOAD_BYTES) {
- throw new ServerError(`Video exceeds maximum size of ${MAX_GALLERY_VIDEO_UPLOAD_BYTES / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });
- }
- const ext = detectVideoContainer(buffer);
+ return persistGalleryVideo(buffer, originalName, buffer.length, (outPath) => atomicWrite(outPath, buffer));
+}
+
+// Read only the container signature; copy the streamed file without buffering it.
+export async function saveUploadedGalleryVideoFile(tempPath, originalName = '') {
+ const file = await open(tempPath, 'r');
+ const header = Buffer.alloc(12);
+ const bytesRead = await file.read(header, 0, header.length, 0)
+ .then((result) => result.bytesRead).finally(() => file.close());
+ const { size } = await stat(tempPath);
+ return persistGalleryVideo(header.subarray(0, bytesRead), originalName, size,
+ async (outPath) => {
+ const staging = `${outPath}.tmp`;
+ try {
+ await copyFileGuarded(tempPath, staging);
+ await rename(staging, outPath);
+ } finally {
+ await unlinkGuarded(staging).catch(() => {});
+ }
+ });
+}
+
+async function persistGalleryVideo(header, originalName, size, write) {
+ const ext = detectVideoContainer(header);
if (!ext) {
throw new ServerError('Unsupported video format (expected MP4, MOV/M4V, or WebM)', { status: 400, code: 'UNSUPPORTED_VIDEO' });
}
@@ -84,8 +104,8 @@ export async function saveUploadedGalleryVideoBuffer(buffer, originalName = '')
const filename = `${id}.${ext}`;
await ensureDir(PATHS.videos);
const outPath = join(PATHS.videos, filename);
- await atomicWrite(outPath, buffer);
try {
+ await write(outPath);
// Both best-effort: a missing ffmpeg/ffprobe degrades to a thumbnail-less
// entry (normalizeVideo renders a no-preview tile), never a failed upload.
const [thumbnail, durationSec] = await Promise.all([
@@ -100,7 +120,7 @@ export async function saveUploadedGalleryVideoBuffer(buffer, originalName = '')
// Let the live media-asset index hook index this immediately (same event
// the generation and download paths emit). Reconcile is the backstop.
videoGenEvents.emit('completed', { generationId: id, filename, path: `/data/videos/${filename}`, thumbnail });
- console.log(`📥 Saved uploaded gallery video: ${filename} (${(buffer.length / 1024 / 1024).toFixed(1)}MB)`);
+ console.log(`📥 Saved uploaded gallery video: ${filename} (${(size / 1024 / 1024).toFixed(1)}MB)`);
return entry;
} catch (err) {
// A throw between the byte write and the history write would orphan a
diff --git a/server/services/videoUpload.test.js b/server/services/videoUpload.test.js
index 272b80c274..35119aa977 100644
--- a/server/services/videoUpload.test.js
+++ b/server/services/videoUpload.test.js
@@ -6,15 +6,31 @@
* the route surface, not re-run here against real dirs.
*/
-import { describe, it, expect } from 'vitest';
+import { mkdtempSync, writeFileSync, readFileSync, rmSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { describe, it, expect, vi, afterAll } from 'vitest';
import {
detectVideoContainer,
buildUploadHistoryEntry,
saveUploadedGalleryVideo,
saveUploadedGalleryVideoBuffer,
- MAX_GALLERY_VIDEO_UPLOAD_BYTES,
+ saveUploadedGalleryVideoFile,
} from './videoUpload.js';
+const uploadState = vi.hoisted(() => ({ root: '', history: [], fail: false }));
+vi.mock('../lib/fileUtils.js', async (original) => {
+ const actual = await original();
+ return { ...actual, PATHS: { ...actual.PATHS, get videos() { return uploadState.root; } } };
+});
+vi.mock('../lib/ffmpeg.js', () => ({ generateThumbnail: vi.fn(async () => null), probeVideoDuration: vi.fn(async () => 2) }));
+vi.mock('./videoGen/history.js', () => ({ mutateVideoHistory: vi.fn(async (mutate) => {
+ if (uploadState.fail) throw new Error('history write failed');
+ uploadState.history = mutate(uploadState.history);
+}) }));
+uploadState.root = mkdtempSync(join(tmpdir(), 'gallery-video-test-'));
+afterAll(() => rmSync(uploadState.root, { recursive: true, force: true }));
+
const ftyp = (brand) => Buffer.concat([
Buffer.from([0, 0, 0, 24]),
Buffer.from('ftyp', 'latin1'),
@@ -66,12 +82,25 @@ describe('saveUploadedGalleryVideo validation', () => {
it('rejects an empty upload before touching disk', async () => {
await expect(saveUploadedGalleryVideo('')).rejects.toThrow(/empty/i);
});
- it('rejects an oversize upload', async () => {
- const oversize = Buffer.alloc(MAX_GALLERY_VIDEO_UPLOAD_BYTES + 1, 1).toString('base64');
- await expect(saveUploadedGalleryVideo(oversize)).rejects.toThrow(/maximum size/i);
- });
it('rejects a non-video payload', async () => {
const notVideo = Buffer.from('hello world, definitely not a video').toString('base64');
await expect(saveUploadedGalleryVideo(notVideo)).rejects.toThrow(/unsupported video format/i);
});
});
+
+
+it('imports a large staged video without the JSON ceiling and removes failed imports', async () => {
+ const tempPath = join(uploadState.root, 'source.mp4');
+ const bytes = Buffer.concat([ftyp('isom'), Buffer.alloc(56 * 1024 * 1024)]);
+ writeFileSync(tempPath, bytes);
+ const entry = await saveUploadedGalleryVideoFile(tempPath, 'large.mp4');
+ expect(entry).toMatchObject({ title: 'large.mp4', source: 'upload', durationSec: 2 });
+ expect(uploadState.history[0]).toEqual(entry);
+ expect(readFileSync(join(uploadState.root, entry.filename)).equals(bytes)).toBe(true);
+ uploadState.fail = true;
+ const { readdirSync } = await import('fs');
+ const before = readdirSync(uploadState.root).sort();
+ await expect(saveUploadedGalleryVideoFile(tempPath, 'failed.mp4')).rejects.toThrow('history write failed');
+ expect(readdirSync(uploadState.root).sort()).toEqual(before);
+ expect(existsSync(tempPath)).toBe(true);
+});