Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: fold music/Authors gallery uploads into GalleryImagePicker allowUpload (#4127)

[._.]/ Adam Eivyc2243fba9bb3
diff --git a/.changelog/next/changed-issue-4127.md b/.changelog/next/changed-issue-4127.md
new file mode 100644
index 0000000000..c1788c1bf5
--- /dev/null
+++ b/.changelog/next/changed-issue-4127.md
@@ -0,0 +1 @@
+- Album cover, artist portrait, and author headshot uploads now go through the shared gallery picker's Upload button (one "Choose or upload" control instead of a separate file input), and that picker now rejects unsupported formats and oversized files before uploading
diff --git a/client/src/components/imageGen/GalleryImagePicker.jsx b/client/src/components/imageGen/GalleryImagePicker.jsx
index e9e26d2d03..102570a134 100644
--- a/client/src/components/imageGen/GalleryImagePicker.jsx
+++ b/client/src/components/imageGen/GalleryImagePicker.jsx
@@ -12,7 +12,9 @@
// disk: it's saved into the gallery via POST /api/image-gen/upload (so the
// stored `/data/images/<f>` URL syncs to peers, unlike a generic upload) and
// then selected exactly like a gallery image — the same source-image flow the
-// image→3D page feeds to createImageTo3dModel.
+// 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.
//
// Local gallery only — no external/web search (deliberate, see plan).
@@ -25,7 +27,9 @@ import { normalizeImage } from '../media/normalize';
import { listImageGallery, listMediaCollections } from '../../services/apiImageVideo';
import { listUniverses } from '../../services/apiUniverseBuilder';
import { uploadGalleryImage } from '../../services/apiSystem';
-import { readFileAsBase64 } from '../../utils/fileUpload';
+import {
+ readFileAsBase64, validateImageFile, JSON_UPLOAD_MAX_FILE_SIZE, UPLOAD_IMAGE_ACCEPT,
+} from '../../utils/fileUpload';
import { buildMediaHaystack, tokenizeQuery, matchHaystack } from '../../lib/mediaSearch';
import { humanizeCategory } from '../../lib/universeBuilderShared';
import toast from '../ui/Toast';
@@ -51,7 +55,9 @@ const byLabel = (a, b) => a.label.localeCompare(b.label);
// bad value drops the option rather than throwing during render.
const asText = (value) => (typeof value === 'string' && value.trim() ? value : null);
-export default function GalleryImagePicker({ open, onClose, onSelect, allowUpload = false }) {
+export default function GalleryImagePicker({
+ open, onClose, onSelect, allowUpload = false, maxBytes = JSON_UPLOAD_MAX_FILE_SIZE,
+}) {
const [items, setItems] = useState([]);
const [loading, setLoading] = useState(false);
const [uploading, setUploading] = useState(false);
@@ -184,10 +190,17 @@ export default function GalleryImagePicker({ open, onClose, onSelect, allowUploa
// Upload a file off disk into the gallery, then select it like any gallery
// image. Saving goes through the peer-syncable `/data/images/` upload so the
- // resulting `filename` resolves for createImageTo3dModel.
+ // resulting `filename` resolves for createImageTo3dModel — and so a host that
+ // stores the returned URL on a record (album cover, artist portrait, author
+ // headshot) gets bytes that actually transfer to federated peers (issue #1327).
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.
+ const invalid = validateImageFile(file, maxBytes);
+ if (invalid) { toast.error(invalid); return; }
setUploading(true);
const base64 = await readFileAsBase64(file).catch(() => null);
if (!base64) { setUploading(false); toast.error(`Failed to read ${file.name}`); return; }
@@ -222,7 +235,7 @@ export default function GalleryImagePicker({ open, onClose, onSelect, allowUploa
<div className="flex items-center gap-2 shrink-0">
{allowUpload && (
<FilePickerButton
- accept="image/png,image/jpeg,image/webp,image/gif"
+ accept={UPLOAD_IMAGE_ACCEPT}
onChange={handleUpload}
disabled={uploading}
title="Upload an image from your device"
diff --git a/client/src/components/imageGen/GalleryImagePicker.test.jsx b/client/src/components/imageGen/GalleryImagePicker.test.jsx
index cca2824f36..0ab7b4c2b3 100644
--- a/client/src/components/imageGen/GalleryImagePicker.test.jsx
+++ b/client/src/components/imageGen/GalleryImagePicker.test.jsx
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import GalleryImagePicker from './GalleryImagePicker';
+import toast from '../ui/Toast';
const listImageGallery = vi.fn();
const listMediaCollections = vi.fn();
@@ -23,7 +24,10 @@ vi.mock('../../services/apiSystem', () => ({
uploadGalleryImage: (...args) => uploadGalleryImage(...args),
}));
-vi.mock('../../utils/fileUpload', () => ({
+// Only the FileReader round-trip is stubbed — `validateImageFile` and the size
+// constants stay real so the upload gate is genuinely under test.
+vi.mock('../../utils/fileUpload', async (importOriginal) => ({
+ ...(await importOriginal()),
readFileAsBase64: vi.fn().mockResolvedValue('ZmFrZS1iYXNlNjQ='),
}));
@@ -64,8 +68,16 @@ describe('GalleryImagePicker', () => {
listMediaCollections.mockResolvedValue(COLLECTIONS);
listUniverses.mockReset();
listUniverses.mockResolvedValue(UNIVERSES);
+ uploadGalleryImage.mockReset();
+ toast.error.mockReset();
});
+ // Drop a file on the (portalled) upload input and wait for the grid to settle.
+ const pickFile = async (file) => {
+ await screen.findByAltText('a neon sunset');
+ fireEvent.change(document.querySelector('input[type="file"]'), { target: { files: [file] } });
+ };
+
it('does not fetch or render while closed', () => {
render(<GalleryImagePicker open={false} onClose={vi.fn()} onSelect={vi.fn()} />);
expect(listImageGallery).not.toHaveBeenCalled();
@@ -115,17 +127,50 @@ describe('GalleryImagePicker', () => {
const onSelect = vi.fn();
const onClose = vi.fn();
render(<GalleryImagePicker open allowUpload onSelect={onSelect} onClose={onClose} />);
- await screen.findByAltText('a neon sunset');
// Modal portals to <body>, so query the whole document for the file input.
- const fileInput = document.querySelector('input[type="file"]');
- const file = new File(['x'], 'photo.png', { type: 'image/png' });
- fireEvent.change(fileInput, { target: { files: [file] } });
+ await pickFile(new File(['x'], 'photo.png', { type: 'image/png' }));
await waitFor(() => expect(uploadGalleryImage).toHaveBeenCalledTimes(1));
await waitFor(() => expect(onSelect).toHaveBeenCalledTimes(1));
expect(onSelect.mock.calls[0][0]).toMatchObject({ filename: 'upload-abcd1234.png', previewUrl: '/data/images/upload-abcd1234.png' });
expect(onClose).toHaveBeenCalledTimes(1);
});
+ // A host that stores the picked URL on a record (album cover, artist portrait,
+ // author headshot) caps uploads below the wire limit — a drag-drop or a paste
+ // bypasses the input's `accept`, so the gate has to live in the handler.
+ it('refuses a file over maxBytes without uploading it', async () => {
+ const onSelect = vi.fn();
+ const onClose = vi.fn();
+ render(<GalleryImagePicker open allowUpload maxBytes={4} onSelect={onSelect} onClose={onClose} />);
+ await pickFile(new File(['0123456789'], 'huge.png', { type: 'image/png' }));
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1));
+ expect(toast.error.mock.calls[0][0]).toMatch(/exceeds/i);
+ expect(uploadGalleryImage).not.toHaveBeenCalled();
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
+ it('refuses a format the upload endpoint cannot verify', async () => {
+ const onSelect = vi.fn();
+ render(<GalleryImagePicker open allowUpload onSelect={onSelect} onClose={vi.fn()} />);
+ await pickFile(new File(['x'], 'vector.svg', { type: 'image/svg+xml' }));
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1));
+ expect(toast.error.mock.calls[0][0]).toMatch(/PNG, JPEG, GIF, WebP/);
+ expect(uploadGalleryImage).not.toHaveBeenCalled();
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+
+ it('allows a large file when no host cap narrows the wire limit', async () => {
+ uploadGalleryImage.mockResolvedValue({ filename: 'big.png', path: '/data/images/big.png' });
+ render(<GalleryImagePicker open allowUpload onSelect={vi.fn()} onClose={vi.fn()} />);
+ await pickFile(new File(['0123456789'], 'big.png', { type: 'image/png' }));
+
+ await waitFor(() => expect(uploadGalleryImage).toHaveBeenCalledTimes(1));
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
it('filters by universe, preferring the fetched record name over the stamped one', async () => {
render(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);
await screen.findByAltText('a neon sunset');
diff --git a/client/src/components/music/AlbumsManager.jsx b/client/src/components/music/AlbumsManager.jsx
index 96e272c3ec..ed31fc4527 100644
--- a/client/src/components/music/AlbumsManager.jsx
+++ b/client/src/components/music/AlbumsManager.jsx
@@ -3,32 +3,33 @@
*
* Master-detail: a list of albums on the left, an editor on the right. An album
* carries a title, artist (via ArtistPicker), description, genre, release year,
- * cover art (generate via image-gen / upload / gallery — same affordances as the
- * artist portrait), and an ordered list of tracks (add from existing tracks,
- * reorder, remove). Mirrors the Authors/Artists master-detail pattern.
+ * cover art (generate via image-gen, or pick/upload through GalleryImagePicker —
+ * same affordances as the artist portrait), and an ordered list of tracks (add
+ * from existing tracks, reorder, remove). Mirrors the Authors/Artists
+ * master-detail pattern.
*/
import { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router';
-import { Plus, Loader2, Trash2, Save, Upload, ImageIcon, Sparkles, X, ArrowUp, ArrowDown } from 'lucide-react';
+import { Plus, Loader2, Trash2, Save, ImageIcon, Sparkles, X, ArrowUp, ArrowDown } from 'lucide-react';
import BrailleSpinner from '../BrailleSpinner';
import toast from '../ui/Toast';
-import FilePickerButton from '../ui/FilePickerButton';
import GalleryImagePicker from '../imageGen/GalleryImagePicker';
import ConfirmButtonPair from '../ui/ConfirmButtonPair';
import useMediaJobProgress from '../../hooks/useMediaJobProgress';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
import { DEFAULT_NEGATIVE_PROMPT } from '../../lib/imageGenDefaults';
-import { readFileAsBase64 } from '../../utils/fileUpload';
-import { formatBytes, formatTimecode } from '../../utils/formatters';
+import { formatTimecode } from '../../utils/formatters';
import ArtistPicker from './ArtistPicker';
import {
listAlbums, createAlbum, updateAlbum, deleteAlbum,
- listTracks, uploadGalleryImage, generateImage,
+ listTracks, generateImage,
ALBUM_TITLE_MAX, ALBUM_DESCRIPTION_MAX, ALBUM_GENRE_MAX,
ALBUM_RELEASE_YEAR_MIN, ALBUM_RELEASE_YEAR_MAX,
} from '../../services/api';
+// Cap cover uploads so the base64 round-trip stays small. Enforced by
+// GalleryImagePicker's `maxBytes`.
const COVER_MAX_BYTES = 12 * 1024 * 1024;
const emptyForm = () => ({
@@ -81,7 +82,6 @@ export default function AlbumsManager() {
const [saving, setSaving] = useState(false);
const { isConfirming: isConfirmingDelete, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
const [galleryOpen, setGalleryOpen] = useState(false);
- const [uploadingCover, setUploadingCover] = useState(false);
const [startingGen, setStartingGen] = useState(false);
const [genJobId, setGenJobId] = useState(null);
const genRequestRef = useRef(0);
@@ -145,7 +145,7 @@ export default function AlbumsManager() {
}, [selectionKey, isCreate, selected, loading]);
const handleGenerateCover = async () => {
- if (isGenerating || uploadingCover) return;
+ if (isGenerating) return;
if (!canGenerate) { toast.error('Add a title, genre, or description to generate from'); return; }
const requestId = genRequestRef.current;
setStartingGen(true);
@@ -164,26 +164,10 @@ export default function AlbumsManager() {
else toast.error('Cover generation returned no image');
};
- const handleCoverFile = async (e) => {
- const file = e.target.files?.[0];
- if (!file) return;
- if (!file.type.startsWith('image/')) { toast.error('Please choose an image file'); return; }
- if (file.size > COVER_MAX_BYTES) { toast.error(`Image exceeds ${formatBytes(COVER_MAX_BYTES, 0)}`); return; }
- // Capture the album-switch generation counter (bumped by selectAlbum/
- // startCreate) so a slow read+upload that finishes after the user moved to a
- // different album doesn't write this cover onto the wrong album's form.
- const requestId = genRequestRef.current;
- setUploadingCover(true);
- const base64 = await readFileAsBase64(file).catch(() => null);
- if (!base64) { setUploadingCover(false); toast.error('Could not read that file'); return; }
- const uploaded = await uploadGalleryImage(base64, { silent: true }).catch((err) => { toast.error(err.message || 'Upload failed'); return null; });
- // Always clear the in-flight flag (even on a stale result) so a mid-upload
- // album switch doesn't leave the new album's Upload/Generate stuck disabled.
- setUploadingCover(false);
- if (genRequestRef.current !== requestId) return; // album switched mid-upload — don't write the form
- if (uploaded?.path) { setCover(uploaded.path); toast.success('Cover uploaded'); }
- };
-
+ // Both "pick an existing gallery image" and "upload one from disk" land here —
+ // GalleryImagePicker's `allowUpload` owns the read + POST and hands back the
+ // saved image already normalized (issue #4127). No album-switch guard needed:
+ // this fires synchronously from the modal, which sits over the album list.
const handleCoverPick = (item) => {
setGalleryOpen(false);
const url = item?.previewUrl || (item?.filename ? `/data/images/${item.filename}` : '');
@@ -259,7 +243,7 @@ export default function AlbumsManager() {
<div className="flex items-center justify-between mb-4 flex-wrap gap-3">
<p className="text-sm text-gray-400 max-w-2xl">
Albums group ordered tracks under an artist, with cover art. Generate a cover from the title +
- genre, upload one, or pick from your gallery. Add tracks from the Tracks tab and order them here.
+ genre, or choose/upload one from your gallery. Add tracks from the Tracks tab and order them here.
</p>
<button
type="button"
@@ -343,14 +327,11 @@ export default function AlbumsManager() {
<input value={form.title} onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))} placeholder="Album title" maxLength={ALBUM_TITLE_MAX} className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white" autoFocus />
</Field>
<div className="flex items-center gap-2 flex-wrap">
- <button type="button" onClick={handleGenerateCover} disabled={isGenerating || uploadingCover || !canGenerate} title={canGenerate ? 'Generate a cover' : 'Add a title, genre, or description first'} className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50">
+ <button type="button" onClick={handleGenerateCover} disabled={isGenerating || !canGenerate} title={canGenerate ? 'Generate a cover' : 'Add a title, genre, or description first'} className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50">
{isGenerating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />} Generate cover
</button>
- <FilePickerButton accept="image/*" onChange={handleCoverFile} disabled={uploadingCover || isGenerating} ariaLabel="Upload album cover" className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent">
- {uploadingCover ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />} Upload
- </FilePickerButton>
- <button type="button" onClick={() => setGalleryOpen(true)} disabled={isGenerating} className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50">
- <ImageIcon size={14} /> Gallery
+ <button type="button" onClick={() => setGalleryOpen(true)} disabled={isGenerating} title="Pick a gallery image, or upload one from this device" className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50">
+ <ImageIcon size={14} /> Choose or upload
</button>
</div>
</div>
@@ -434,7 +415,7 @@ export default function AlbumsManager() {
</div>
</div>
- <GalleryImagePicker open={galleryOpen} onClose={() => setGalleryOpen(false)} onSelect={handleCoverPick} />
+ <GalleryImagePicker open={galleryOpen} onClose={() => setGalleryOpen(false)} onSelect={handleCoverPick} allowUpload maxBytes={COVER_MAX_BYTES} />
</div>
);
}
diff --git a/client/src/components/music/ArtistsManager.jsx b/client/src/components/music/ArtistsManager.jsx
index aaa3871f6c..b5d3afddfe 100644
--- a/client/src/components/music/ArtistsManager.jsx
+++ b/client/src/components/music/ArtistsManager.jsx
@@ -9,24 +9,22 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router';
-import { Plus, Loader2, Trash2, Save, Upload, ImageIcon, Sparkles, X } from 'lucide-react';
+import { Plus, Loader2, Trash2, Save, ImageIcon, Sparkles, X } from 'lucide-react';
import BrailleSpinner from '../BrailleSpinner';
import toast from '../ui/Toast';
-import FilePickerButton from '../ui/FilePickerButton';
import GalleryImagePicker from '../imageGen/GalleryImagePicker';
import ConfirmButtonPair from '../ui/ConfirmButtonPair';
import useMediaJobProgress from '../../hooks/useMediaJobProgress';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
import { DEFAULT_NEGATIVE_PROMPT } from '../../lib/imageGenDefaults';
-import { readFileAsBase64 } from '../../utils/fileUpload';
-import { formatBytes } from '../../utils/formatters';
import {
- listArtists, createArtist, updateArtist, deleteArtist, uploadGalleryImage, generateImage,
+ listArtists, createArtist, updateArtist, deleteArtist, generateImage,
ARTIST_NAME_MAX, ARTIST_GENRE_MAX, ARTIST_BIO_MAX, ARTIST_MUSICAL_STYLE_MAX,
ARTIST_PHYSICAL_DESCRIPTION_MAX, ARTIST_PORTRAIT_STYLE_MAX, ARTIST_PORTRAIT_IMAGE_URL_MAX,
} from '../../services/api';
-// Cap portrait uploads so the base64 round-trip stays small.
+// Cap portrait uploads so the base64 round-trip stays small. Enforced by
+// GalleryImagePicker's `maxBytes`.
const PORTRAIT_MAX_BYTES = 12 * 1024 * 1024;
const emptyForm = () => ({
@@ -75,7 +73,6 @@ export default function ArtistsManager() {
const [saving, setSaving] = useState(false);
const { isConfirming: isConfirmingDelete, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
const [galleryOpen, setGalleryOpen] = useState(false);
- const [uploadingPortrait, setUploadingPortrait] = useState(false);
const [startingGen, setStartingGen] = useState(false);
const [genJobId, setGenJobId] = useState(null);
// Bumped on every artist switch / new-artist so a stale generate response
@@ -101,7 +98,7 @@ export default function ArtistsManager() {
}, [genJobId, gen.status, gen.filename, gen.path, gen.error]);
const handleGeneratePortrait = async () => {
- if (isGenerating || uploadingPortrait) return;
+ if (isGenerating) return;
if (!form.physicalDescription.trim() && !form.portraitStyle.trim()) {
toast.error('Add a physical description or portrait style to generate from');
return;
@@ -134,30 +131,9 @@ export default function ArtistsManager() {
}
};
- const handlePortraitFile = async (e) => {
- const file = e.target.files?.[0];
- if (!file) return;
- if (!file.type.startsWith('image/')) { toast.error('Please choose an image file'); return; }
- if (file.size > PORTRAIT_MAX_BYTES) {
- toast.error(`Image exceeds ${formatBytes(PORTRAIT_MAX_BYTES, 0)}`);
- return;
- }
- setUploadingPortrait(true);
- const base64 = await readFileAsBase64(file).catch(() => null);
- if (!base64) { setUploadingPortrait(false); toast.error('Could not read that file'); return; }
- // Route through the gallery (`/data/images/`) so the stored portrait URL
- // rides the image asset path (matches Authors' headshot upload).
- const uploaded = await uploadGalleryImage(base64, { silent: true }).catch((err) => {
- toast.error(err.message || 'Upload failed');
- return null;
- });
- setUploadingPortrait(false);
- if (uploaded?.path) {
- setPortrait(uploaded.path);
- toast.success('Portrait uploaded');
- }
- };
-
+ // Both "pick an existing gallery image" and "upload one from disk" land here —
+ // GalleryImagePicker's `allowUpload` owns the read + POST and hands back the
+ // saved image already normalized (issue #4127).
const handlePortraitPick = (item) => {
setGalleryOpen(false);
const url = item?.previewUrl || (item?.filename ? `/data/images/${item.filename}` : '');
@@ -352,7 +328,7 @@ export default function ArtistsManager() {
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
/>
</Field>
- <Field label="Portrait image" hint="Optional — generate from the description + style, upload a photo, pick one from your gallery, or paste a URL.">
+ <Field label="Portrait image" hint="Optional — generate from the description + style, choose or upload one via the gallery, or paste a URL.">
<div className="flex items-start gap-3">
{isGenerating ? (
<div className="relative w-20 h-20 rounded border border-port-border bg-port-bg overflow-hidden flex items-center justify-center shrink-0">
@@ -397,7 +373,7 @@ export default function ArtistsManager() {
<button
type="button"
onClick={handleGeneratePortrait}
- disabled={isGenerating || uploadingPortrait || !canGenerate}
+ disabled={isGenerating || !canGenerate}
title={canGenerate
? 'Generate a portrait from the description + style'
: 'Add a physical description or portrait style first'}
@@ -406,23 +382,14 @@ export default function ArtistsManager() {
{isGenerating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
Generate
</button>
- <FilePickerButton
- accept="image/*"
- onChange={handlePortraitFile}
- disabled={uploadingPortrait || isGenerating}
- ariaLabel="Upload artist portrait"
- className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent"
- >
- {uploadingPortrait ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />}
- Upload
- </FilePickerButton>
<button
type="button"
onClick={() => setGalleryOpen(true)}
disabled={isGenerating}
+ title="Pick a gallery image, or upload one from this device"
className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50"
>
- <ImageIcon size={14} /> Choose from gallery
+ <ImageIcon size={14} /> Choose or upload
</button>
</div>
<input
@@ -477,6 +444,8 @@ export default function ArtistsManager() {
open={galleryOpen}
onClose={() => setGalleryOpen(false)}
onSelect={handlePortraitPick}
+ allowUpload
+ maxBytes={PORTRAIT_MAX_BYTES}
/>
</div>
);
diff --git a/client/src/pages/Authors.jsx b/client/src/pages/Authors.jsx
index 2363943b09..fbf938fccb 100644
--- a/client/src/pages/Authors.jsx
+++ b/client/src/pages/Authors.jsx
@@ -12,23 +12,20 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router';
-import { FilePen, Plus, Loader2, Trash2, Save, Upload, ImageIcon, Sparkles, X } from 'lucide-react';
+import { FilePen, Plus, Loader2, Trash2, Save, ImageIcon, Sparkles, X } from 'lucide-react';
import BrailleSpinner from '../components/BrailleSpinner';
import toast from '../components/ui/Toast';
-import FilePickerButton from '../components/ui/FilePickerButton';
import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';
import useMediaJobProgress from '../hooks/useMediaJobProgress';
import { DEFAULT_NEGATIVE_PROMPT } from '../lib/imageGenDefaults';
-import { readFileAsBase64 } from '../utils/fileUpload';
-import { formatBytes } from '../utils/formatters';
import {
- listAuthors, createAuthor, updateAuthor, deleteAuthor, uploadGalleryImage, generateImage,
+ listAuthors, createAuthor, updateAuthor, deleteAuthor, generateImage,
AUTHOR_NAME_MAX, AUTHOR_WRITING_STYLE_MAX, AUTHOR_BIO_MAX,
AUTHOR_PHYSICAL_DESCRIPTION_MAX, AUTHOR_HEADSHOT_STYLE_MAX, AUTHOR_HEADSHOT_IMAGE_URL_MAX,
} from '../services/api';
// Cap headshot uploads so the base64 round-trip stays small — a cover headshot
-// never needs more than a few MB.
+// never needs more than a few MB. Enforced by GalleryImagePicker's `maxBytes`.
const HEADSHOT_MAX_BYTES = 12 * 1024 * 1024;
const emptyForm = () => ({
@@ -76,7 +73,6 @@ export default function Authors() {
const [saving, setSaving] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
const [galleryOpen, setGalleryOpen] = useState(false);
- const [uploadingHeadshot, setUploadingHeadshot] = useState(false);
// Headshot generation: `startingGen` covers the request round-trip before a
// jobId exists; `genJobId` tracks an async (local/codex) render until it
// completes. External SD-API renders synchronously and never sets genJobId.
@@ -111,7 +107,7 @@ export default function Authors() {
}, [genJobId, gen.status, gen.filename, gen.path, gen.error]);
const handleGenerateHeadshot = async () => {
- if (isGenerating || uploadingHeadshot) return;
+ if (isGenerating) return;
if (!form.physicalDescription.trim() && !form.headshotStyle.trim()) {
toast.error('Add a physical description or headshot style to generate from');
return;
@@ -151,31 +147,9 @@ export default function Authors() {
}
};
- const handleHeadshotFile = async (e) => {
- const file = e.target.files?.[0];
- if (!file) return;
- if (!file.type.startsWith('image/')) { toast.error('Please choose an image file'); return; }
- if (file.size > HEADSHOT_MAX_BYTES) {
- toast.error(`Image exceeds ${formatBytes(HEADSHOT_MAX_BYTES, 0)}`);
- return;
- }
- setUploadingHeadshot(true);
- const base64 = await readFileAsBase64(file).catch(() => null);
- if (!base64) { setUploadingHeadshot(false); toast.error('Could not read that file'); return; }
- // Route through the gallery (`/data/images/`) — NOT the generic /uploads
- // path — so the stored headshot URL rides the `image` peer-sync asset path
- // and the bytes actually transfer to federated peers (issue #1327).
- const uploaded = await uploadGalleryImage(base64, { silent: true }).catch((err) => {
- toast.error(err.message || 'Upload failed');
- return null;
- });
- setUploadingHeadshot(false);
- if (uploaded?.path) {
- setHeadshot(uploaded.path);
- toast.success('Headshot uploaded');
- }
- };
-
+ // Both "pick an existing gallery image" and "upload one from disk" land here —
+ // GalleryImagePicker's `allowUpload` owns the read + POST and hands back the
+ // saved image already normalized (issue #4127).
const handleHeadshotPick = (item) => {
setGalleryOpen(false);
const url = item?.previewUrl || (item?.filename ? `/data/images/${item.filename}` : '');
@@ -372,7 +346,7 @@ export default function Authors() {
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
/>
</Field>
- <Field label="Headshot image" hint="Optional — generate from the description + style, upload a photo, pick one from your gallery, or paste a URL. Used on covers.">
+ <Field label="Headshot image" hint="Optional — generate from the description + style, choose or upload one via the gallery, or paste a URL. Used on covers.">
<div className="flex items-start gap-3">
{isGenerating ? (
<div className="relative w-20 h-20 rounded border border-port-border bg-port-bg overflow-hidden flex items-center justify-center shrink-0">
@@ -417,7 +391,7 @@ export default function Authors() {
<button
type="button"
onClick={handleGenerateHeadshot}
- disabled={isGenerating || uploadingHeadshot || !canGenerate}
+ disabled={isGenerating || !canGenerate}
title={canGenerate
? 'Generate a headshot from the description + style'
: 'Add a physical description or headshot style first'}
@@ -426,23 +400,14 @@ export default function Authors() {
{isGenerating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
Generate
</button>
- <FilePickerButton
- accept="image/*"
- onChange={handleHeadshotFile}
- disabled={uploadingHeadshot || isGenerating}
- ariaLabel="Upload author headshot"
- className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent"
- >
- {uploadingHeadshot ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />}
- Upload
- </FilePickerButton>
<button
type="button"
onClick={() => setGalleryOpen(true)}
disabled={isGenerating}
+ title="Pick a gallery image, or upload one from this device"
className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50"
>
- <ImageIcon size={14} /> Choose from gallery
+ <ImageIcon size={14} /> Choose or upload
</button>
</div>
<input
@@ -498,6 +463,8 @@ export default function Authors() {
open={galleryOpen}
onClose={() => setGalleryOpen(false)}
onSelect={handleHeadshotPick}
+ allowUpload
+ maxBytes={HEADSHOT_MAX_BYTES}
/>
</div>
);
diff --git a/client/src/pages/Authors.test.jsx b/client/src/pages/Authors.test.jsx
index 942561d063..47be682311 100644
--- a/client/src/pages/Authors.test.jsx
+++ b/client/src/pages/Authors.test.jsx
@@ -22,7 +22,6 @@ vi.mock('../services/api', () => ({
createAuthor: vi.fn(),
updateAuthor: vi.fn(),
deleteAuthor: vi.fn(),
- uploadGalleryImage: vi.fn(),
generateImage: (...a) => generateImage(...a),
AUTHOR_NAME_MAX: 120,
AUTHOR_WRITING_STYLE_MAX: 4000,
@@ -38,9 +37,13 @@ vi.mock('../components/ui/Toast', () => ({
default: { success: (...a) => toastSuccess(...a), error: (...a) => toastError(...a) },
}));
-// Gallery picker is exercised elsewhere; stub it so this suite focuses on
-// the generate flow.
-vi.mock('../components/imageGen/GalleryImagePicker', () => ({ default: () => null }));
+// Gallery picker internals are exercised in GalleryImagePicker.test.jsx; stub it
+// here but keep the last props so this suite can assert the page hands it the
+// upload duty (issue #4127) and drive its `onSelect` the way a real pick/upload does.
+let pickerProps = null;
+vi.mock('../components/imageGen/GalleryImagePicker', () => ({
+ default: (props) => { pickerProps = props; return null; },
+}));
// Drive the headshot-progress hook from a mutable module-level value so a test
// can transition an in-flight async render to 'completed' between renders. The
@@ -58,6 +61,7 @@ describe('Authors headshot generation', () => {
toastSuccess.mockReset();
toastError.mockReset();
hookState = idleProgress();
+ pickerProps = null;
});
const openCreateForm = async () => {
@@ -135,14 +139,29 @@ describe('Authors headshot generation', () => {
await waitFor(() => expect(generateImage).toHaveBeenCalledTimes(1));
// The async job is in flight — a manual headshot change would be clobbered
- // on completion, so Upload / gallery / URL are locked until it settles.
- // Upload is a <label> + file input (native picker activation) — matched by
- // its accessible label rather than a button role.
- expect(screen.getByLabelText('Upload author headshot').disabled).toBe(true);
- expect(screen.getByRole('button', { name: 'Choose from gallery' }).disabled).toBe(true);
+ // on completion, so the picker (which owns both pick and upload) and the URL
+ // field are locked until it settles.
+ expect(screen.getByRole('button', { name: 'Choose or upload' }).disabled).toBe(true);
expect(screen.getByPlaceholderText(/https:/i).disabled).toBe(true);
});
+ it('delegates headshot uploads to the gallery picker instead of a second file input', async () => {
+ await openCreateForm();
+
+ // The bespoke upload handler is gone — no file input lives beside the picker.
+ expect(document.querySelector('input[type="file"]')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Choose or upload' }));
+
+ expect(pickerProps.open).toBe(true);
+ expect(pickerProps.allowUpload).toBe(true);
+ // The page's own product cap still applies, rather than the wider wire limit.
+ expect(pickerProps.maxBytes).toBe(12 * 1024 * 1024);
+
+ // An uploaded image comes back through the same onSelect as a gallery pick.
+ act(() => pickerProps.onSelect({ filename: 'up.png', previewUrl: '/data/images/up.png' }));
+ expect(screen.getByPlaceholderText(/https:/i).value).toBe('/data/images/up.png');
+ });
+
it('does not overwrite a different author when one is selected mid-render', async () => {
generateImage.mockResolvedValue({ jobId: 'job-2', filename: 'job-2.png', path: '/data/images/job-2.png' });
listAuthors.mockResolvedValue([
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index a08e56a3e2..2a75391061 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -55,7 +55,7 @@ grep -i "what you want to do" client/src/utils/README.md
| Module | Purpose |
|---|---|
-| `fileUpload` | Pure screenshot/attachment upload helpers: base64 read (`readFileAsBase64`) and image validation (`validateImageFile`). Also the shared upload constants — `JSON_UPLOAD_MAX_FILE_SIZE` (max file size / wire limit, mirrors `server/lib/uploadLimits.js`), `ATTACHMENT_MAX_FILE_SIZE`, `ALLOWED_ATTACHMENT_EXTENSIONS`, and the `accept` strings `ATTACHMENT_ACCEPT` / `IMAGE_ACCEPT`. The actual upload orchestration (`processScreenshotUploads` / `processAttachmentUploads` and their single-file variants) does network I/O and lives in `services/apiMedia.js` — import those from there, not from here. |
+| `fileUpload` | Pure screenshot/attachment upload helpers: base64 read (`readFileAsBase64`) and image validation (`validateImageFile`). Also the shared upload constants — `JSON_UPLOAD_MAX_FILE_SIZE` (max file size / wire limit, mirrors `server/lib/uploadLimits.js`), `ATTACHMENT_MAX_FILE_SIZE`, `ALLOWED_ATTACHMENT_EXTENSIONS`, and the `accept` strings `ATTACHMENT_ACCEPT` / `IMAGE_ACCEPT` / `UPLOAD_IMAGE_ACCEPT`. The actual upload orchestration (`processScreenshotUploads` / `processAttachmentUploads` and their single-file variants) does network I/O and lives in `services/apiMedia.js` — import those from there, not from here. |
## CyberCity — character & avatar
diff --git a/client/src/utils/fileUpload.js b/client/src/utils/fileUpload.js
index 765f1dee8d..106f8e9280 100644
--- a/client/src/utils/fileUpload.js
+++ b/client/src/utils/fileUpload.js
@@ -100,6 +100,17 @@ export function readFileAsBase64(file) {
*/
export const SUPPORTED_UPLOAD_IMAGE_MIME = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
+/**
+ * `accept` for pickers whose file goes straight to an upload endpoint (the
+ * gallery picker's Upload button). Derived from `SUPPORTED_UPLOAD_IMAGE_MIME` so
+ * the picker filter and `validateImageFile` can never disagree about which
+ * formats are allowed.
+ *
+ * Distinct from `IMAGE_ACCEPT`, which is narrower (no GIF) because its consumers
+ * feed image-gen backends rather than this upload pipeline.
+ */
+export const UPLOAD_IMAGE_ACCEPT = SUPPORTED_UPLOAD_IMAGE_MIME.join(',');
+
const SUPPORTED_LABEL = 'PNG, JPEG, GIF, WebP';
/**