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

Generate author headshots from the persona description + style

[._.]/ Adam Eivyd6cf350645bc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5002486fc6..805396a206 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Generate an author headshot from the persona's description + style** — The Authors editor's headshot field gains a **Generate** button alongside Upload and Choose from gallery: it folds the author's **physical description** (the subject) and **headshot style** (the art direction) into one portrait prompt and renders through the existing image-gen system, dropping the result straight into the headshot slot. The button stays disabled until at least one of those fields is filled. While a render is in flight the thumbnail shows the live diffusion preview and step percentage (async local/codex backends); the synchronous external SD-API backend lands the image directly. Switching authors mid-render cancels the in-flight tracking so a completed render can't write the wrong persona's headshot. (`client/src/pages/Authors.jsx`)
+
- **Author personas — manage reusable authors and pick one for a series** — Create gains an **Authors** page (`/authors`, reachable from the sidebar and ⌘K) for managing reusable author personas: each carries a **name**, **writing style**, **bio**, a **physical description** and a **headshot style** (the prompt inputs for generating a book-cover author headshot), plus an optional **headshot image** you can **upload** (a photo from your device), **choose from your image gallery** (the same searchable picker the image-gen page uses), or paste a URL into — with a live thumbnail preview and one-click clear. The Series Pipeline's author field — previously a free-text byline on both the create form and the series bible — is now an **author picker** that lists your personas: selecting one stores the persona link (`authorId`) **and** the denormalized byline string on the series, so covers and title screens still render the right name. Picking "— No author —" clears it; a legacy free-text byline with no linked persona is shown as a hint until you link one. Authors are stored in PostgreSQL (`authors` table, `db-primary`); they're local-only for now (a federated peer renders a synced series' byline from the string it carries) — cross-machine sync of the personas themselves is tracked as a follow-up. (`server/services/authors/`, `server/routes/authors.js`, `server/scripts/init-db.sql`, `server/lib/db.js`, `server/services/pipeline/series.js`, `client/src/pages/Authors.jsx`, `client/src/components/pipeline/AuthorPicker.jsx`, `client/src/services/apiAuthors.js`, `client/src/components/Layout.jsx`, `server/lib/navManifest.js`)
- **LoRA dataset grid: collapse captions, click-to-preview, and full-height thumbnails** — The dataset workbench image grid (`/media/training/:id`) gets three usability fixes. A **Hide captions / Show captions** toggle collapses every card's caption editor and action row at once, so you can scan the whole dataset as a clean thumbnail wall. Clicking any thumbnail now opens a **full-size preview lightbox** (← / → to step through the ready images, Esc to close) — the same affordance the media galleries already have. And thumbnails render at their **natural aspect ratio** (fixed column width, full relative height) instead of a fixed square crop, so portrait and landscape training images are no longer sliced off at the top and bottom. (`client/src/components/loraTraining/DatasetImageGrid.jsx`)
diff --git a/client/src/pages/Authors.jsx b/client/src/pages/Authors.jsx
index bd0ebde5b6..5ff97976d2 100644
--- a/client/src/pages/Authors.jsx
+++ b/client/src/pages/Authors.jsx
@@ -11,12 +11,14 @@
*/
import { useEffect, useMemo, useRef, useState } from 'react';
-import { FilePen, Plus, Loader2, Trash2, Save, Upload, ImageIcon, X } from 'lucide-react';
+import { FilePen, Plus, Loader2, Trash2, Save, Upload, ImageIcon, Sparkles, X } from 'lucide-react';
import toast from '../components/ui/Toast';
import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';
+import useMediaJobProgress from '../hooks/useMediaJobProgress';
+import { DEFAULT_NEGATIVE_PROMPT } from '../lib/imageGenDefaults';
import { readFileAsBase64 } from '../utils/fileUpload';
import {
- listAuthors, createAuthor, updateAuthor, deleteAuthor, uploadFile,
+ listAuthors, createAuthor, updateAuthor, deleteAuthor, uploadFile, 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';
@@ -38,6 +40,16 @@ const formFromAuthor = (a) => ({
headshotImageUrl: a.headshotImageUrl || '',
});
+// Build the image-gen prompt for an author headshot from the persona's
+// physical description (the subject) and headshot style (the art direction).
+// Either field alone is enough to render; both are folded into one prompt.
+const buildHeadshotPrompt = (f) => {
+ const desc = (f.physicalDescription || '').trim();
+ const style = (f.headshotStyle || '').trim();
+ const subject = desc ? `Author headshot portrait. ${desc}` : 'Professional author headshot portrait.';
+ return style ? `${subject} ${style}` : subject;
+};
+
function Field({ label, hint, children }) {
return (
<label className="block">
@@ -58,9 +70,69 @@ export default function Authors() {
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.
+ const [startingGen, setStartingGen] = useState(false);
+ const [genJobId, setGenJobId] = useState(null);
const fileInputRef = useRef(null);
+ const gen = useMediaJobProgress(genJobId);
+ const isGenerating = startingGen || !!genJobId;
+
const setHeadshot = (url) => setForm((f) => ({ ...f, headshotImageUrl: url }));
+ // Drop any in-flight render so its completion can't write the wrong author.
+ const clearGeneration = () => { setGenJobId(null); setStartingGen(false); };
+
+ // Land the finished async render into the form, or surface a failure. Cleared
+ // genJobId on author switch (see selectAuthor/startCreate) prevents a stale
+ // render from writing the wrong author's headshot.
+ useEffect(() => {
+ if (!genJobId) return;
+ if (gen.status === 'completed' && gen.filename) {
+ setHeadshot(gen.path || `/data/images/${gen.filename}`);
+ setGenJobId(null);
+ toast.success('Headshot generated');
+ } else if (gen.status === 'failed' || gen.status === 'canceled') {
+ setGenJobId(null);
+ toast.error(gen.error || 'Headshot generation failed');
+ }
+ }, [genJobId, gen.status, gen.filename, gen.path, gen.error]);
+
+ const handleGenerateHeadshot = async () => {
+ if (isGenerating) return;
+ if (!form.physicalDescription.trim() && !form.headshotStyle.trim()) {
+ toast.error('Add a physical description or headshot style to generate from');
+ return;
+ }
+ setStartingGen(true);
+ const queued = await generateImage({
+ prompt: buildHeadshotPrompt(form),
+ // Shared base plus portrait-specific guards (people-only artifacts).
+ negativePrompt: `${DEFAULT_NEGATIVE_PROMPT}, extra limbs, nsfw, nude`,
+ width: 768,
+ height: 1024,
+ }).catch((err) => {
+ toast.error(err.message || 'Headshot generation failed');
+ return null;
+ });
+ setStartingGen(false);
+ if (!queued) return;
+ if (queued.jobId) {
+ // Async backend — track progress until the job completes.
+ setGenJobId(queued.jobId);
+ toast.success('Generating headshot…');
+ return;
+ }
+ // Synchronous backend (external SD-API) returns the finished image directly.
+ const path = queued.path || (queued.filename ? `/data/images/${queued.filename}` : '');
+ if (path) {
+ setHeadshot(path);
+ toast.success('Headshot generated');
+ } else {
+ toast.error('Headshot generation returned no image');
+ }
+ };
const handleHeadshotFile = async (e) => {
const file = e.target.files?.[0];
@@ -103,17 +175,21 @@ export default function Authors() {
() => (isCreate || !selectedId ? null : authors.find((a) => a.id === selectedId) || null),
[authors, selectedId, isCreate],
);
+ // A headshot render needs at least a subject or an art-direction prompt.
+ const canGenerate = !!(form.physicalDescription.trim() || form.headshotStyle.trim());
const selectAuthor = (a) => {
setSelectedId(a.id);
setForm(formFromAuthor(a));
setConfirmDelete(false);
+ clearGeneration();
};
const startCreate = () => {
setSelectedId('new');
setForm(emptyForm());
setConfirmDelete(false);
+ clearGeneration();
};
const handleSave = async () => {
@@ -260,9 +336,26 @@ 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 — 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, upload a photo, pick one from your gallery, or paste a URL. Used on covers.">
<div className="flex items-start gap-3">
- {form.headshotImageUrl ? (
+ {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">
+ {gen.currentImage ? (
+ <img
+ src={`data:image/png;base64,${gen.currentImage}`}
+ alt="Generating headshot preview"
+ className="w-full h-full object-cover opacity-70"
+ />
+ ) : (
+ <Loader2 size={20} className="animate-spin text-port-accent" aria-hidden="true" />
+ )}
+ {gen.totalSteps ? (
+ <div className="absolute bottom-0 inset-x-0 bg-black/60 text-[9px] text-white text-center py-0.5 font-mono">
+ {Math.round((gen.step / gen.totalSteps) * 100)}%
+ </div>
+ ) : null}
+ </div>
+ ) : form.headshotImageUrl ? (
<div className="relative shrink-0">
<img
src={form.headshotImageUrl}
@@ -285,6 +378,18 @@ export default function Authors() {
)}
<div className="flex-1 space-y-2">
<div className="flex items-center gap-2 flex-wrap">
+ <button
+ type="button"
+ onClick={handleGenerateHeadshot}
+ disabled={isGenerating || !canGenerate}
+ title={canGenerate
+ ? 'Generate a headshot from the description + style'
+ : 'Add a physical description or headshot style 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
+ </button>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
diff --git a/client/src/pages/Authors.test.jsx b/client/src/pages/Authors.test.jsx
new file mode 100644
index 0000000000..d5d5c22f5b
--- /dev/null
+++ b/client/src/pages/Authors.test.jsx
@@ -0,0 +1,91 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import Authors from './Authors';
+
+const listAuthors = vi.fn();
+const generateImage = vi.fn();
+
+vi.mock('../services/api', () => ({
+ listAuthors: (...a) => listAuthors(...a),
+ createAuthor: vi.fn(),
+ updateAuthor: vi.fn(),
+ deleteAuthor: vi.fn(),
+ uploadFile: vi.fn(),
+ generateImage: (...a) => generateImage(...a),
+ AUTHOR_NAME_MAX: 120,
+ AUTHOR_WRITING_STYLE_MAX: 4000,
+ AUTHOR_BIO_MAX: 4000,
+ AUTHOR_PHYSICAL_DESCRIPTION_MAX: 2000,
+ AUTHOR_HEADSHOT_STYLE_MAX: 2000,
+ AUTHOR_HEADSHOT_IMAGE_URL_MAX: 1000,
+}));
+
+const toastSuccess = vi.fn();
+const toastError = vi.fn();
+vi.mock('../components/ui/Toast', () => ({
+ default: { success: (...a) => toastSuccess(...a), error: (...a) => toastError(...a) },
+}));
+
+// Gallery picker and headshot progress hook are exercised elsewhere; stub them
+// so this suite focuses on the generate flow.
+vi.mock('../components/imageGen/GalleryImagePicker', () => ({ default: () => null }));
+vi.mock('../hooks/useMediaJobProgress', () => ({
+ default: () => ({ status: 'unknown', currentImage: null, step: 0, totalSteps: null, filename: null, path: null, error: null }),
+}));
+
+describe('Authors headshot generation', () => {
+ beforeEach(() => {
+ listAuthors.mockReset().mockResolvedValue([]);
+ generateImage.mockReset();
+ toastSuccess.mockReset();
+ toastError.mockReset();
+ });
+
+ const openCreateForm = async () => {
+ render(<Authors />);
+ await screen.findByText(/No authors yet/i);
+ fireEvent.click(screen.getByRole('button', { name: /New Author/i }));
+ };
+
+ it('disables Generate until a description or style is provided', async () => {
+ await openCreateForm();
+ const genBtn = screen.getByRole('button', { name: /Generate/i });
+ expect(genBtn.disabled).toBe(true);
+
+ fireEvent.change(screen.getByPlaceholderText(/silver-streaked dark hair/i), {
+ target: { value: 'Woman in her 40s, warm gaze' },
+ });
+ expect(genBtn.disabled).toBe(false);
+ });
+
+ it('builds a prompt from description + style and lands a synchronous render', async () => {
+ generateImage.mockResolvedValue({ path: '/data/images/headshot.png' });
+ await openCreateForm();
+
+ fireEvent.change(screen.getByPlaceholderText(/silver-streaked dark hair/i), {
+ target: { value: 'Woman in her 40s, warm gaze' },
+ });
+ fireEvent.change(screen.getByPlaceholderText(/Rembrandt lighting/i), {
+ target: { value: 'Studio portrait, 85mm' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: /Generate/i }));
+
+ await waitFor(() => expect(generateImage).toHaveBeenCalledTimes(1));
+ const payload = generateImage.mock.calls[0][0];
+ expect(payload.prompt).toContain('Woman in her 40s, warm gaze');
+ expect(payload.prompt).toContain('Studio portrait, 85mm');
+
+ const img = await screen.findByAltText('Author headshot');
+ expect(img.getAttribute('src')).toBe('/data/images/headshot.png');
+ });
+
+ it('toasts when generation fails', async () => {
+ generateImage.mockRejectedValue(new Error('backend down'));
+ await openCreateForm();
+ fireEvent.change(screen.getByPlaceholderText(/silver-streaked dark hair/i), {
+ target: { value: 'Woman in her 40s' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: /Generate/i }));
+ await waitFor(() => expect(toastError).toHaveBeenCalledWith('backend down'));
+ });
+});