Move LLM key to the server, add random-style buttons

Architectural change

The browser no longer talks to the LLM directly. A new Node server
(server.mjs) sits in the middle:

  [Browser] → [Node :3000] → [LLM provider]
    (no key)    (key in .env)

server.mjs is the production runtime: it serves the built SPA out of
dist/ and exposes three JSON endpoints that proxy to the LLM with
credentials held in process.env. The browser-side llm.ts is now a thin
fetch wrapper.

- server.mjs: single-file Node server, no production deps
- server/prompts.mjs: system + user prompt construction (was client-side)
- src/lib/prompts.ts removed (moved server-side)
- src/lib/llm.ts rewritten — no more direct LLM calls, no more
  JSON extraction, no more validation; just fetch the proxy
- src/lib/types.ts: drop SaveConfigPayload/TestConnectionResult, add
  style_hint and ServerStatus
- vite.config.ts: proxy /api/* → localhost:3000 in dev
- .env.example: LLM_* and PORT/CORS_ORIGIN instead of Supabase values

New feature: random style buttons

The Options → Music style field now has two AI buttons that fill it
with a fresh Suno style description:
- 'Surprise me' → coherent, production-ready style (max 25 words)
- 'Go crazy'   → deliberately clashing genre mashup (max 25 words)

The buttons hit a dedicated /api/style/random endpoint on the server
that uses a small, focused system prompt. Each click overwrites the
field. Both buttons show a spinner and disable while a request is
in flight. Errors surface as toasts. AbortController is used so a
fast second click cancels the first.

When the Music style field is non-empty at generation time, its value
is sent to the model as style_hint and used as the basis for the full
120-word style field (per the updated system prompt).

Other UX

- Settings page is now a server-status page: green/red indicator,
  model + endpoint, re-check button. The API key is no longer
  configurable in the browser (it never was reachable anyway — now
  the UI is honest about that).
- Home page header shows a small 'Server offline' warning when the
  server is unreachable.
- Settings has a Local data section: list what's in localStorage
  with one-click clear-history and clear-all buttons (with confirm).
- Esc cancels any in-flight generation.
- ZIP filename falls back to 'song' if the title sanitizes to empty.

Deployment

deploy/ holds reference files (Dockerfile, docker-compose example,
Caddy fragment, generate-env.sh, README) for adding the service to a
Jannik-Cloud-style stack. The repo is intentionally not wired into
the Jannik-Cloud repo; copy the four files when ready.
This commit is contained in:
2026-06-03 08:01:21 +02:00
parent b945417773
commit d8b25ec6ab
17 changed files with 1597 additions and 759 deletions
+74 -52
View File
@@ -7,12 +7,11 @@ import {
type SectionKey,
} from "../components/ResultsPanel";
import { StickyZipBar } from "../components/StickyZipBar";
import { ConfigBanner } from "../components/ConfigBanner";
import { ThemeToggle } from "../components/ThemeToggle";
import { HistoryPanel } from "../components/HistoryPanel";
import { Footer } from "../components/Footer";
import { useToast } from "../lib/toast";
import { generateSong, getConfigDisplay } from "../lib/llm";
import { generateSong, getServerStatus } from "../lib/llm";
import { addToHistory, type HistoryEntry } from "../lib/history";
import { buildSongZip, downloadBlob, sanitizeFilename } from "../lib/zip";
import {
@@ -25,6 +24,7 @@ const DEFAULT_INPUT: InputValues = {
idea: "",
language: "English",
customLanguage: "",
style_hint: "",
mood: "",
vocals: "vocals",
};
@@ -35,7 +35,6 @@ function resolveLanguage(v: InputValues): string {
: v.language;
}
// `true` when any in-flight generation is running, false otherwise.
function isAnyBusy(loading: boolean, regenerating: RegeneratingMap): boolean {
if (loading) return true;
for (const v of Object.values(regenerating)) if (v) return true;
@@ -53,7 +52,7 @@ export function HomePage() {
const [loading, setLoading] = useState(false);
const [regenerating, setRegenerating] = useState<RegeneratingMap>({});
const [selectedTitleIndex, setSelectedTitleIndex] = useState(0);
const [apiKeySet, setApiKeySet] = useState<boolean>(false);
const [serverOk, setServerOk] = useState<boolean | null>(null);
// AbortController for the *current* network request. Refs are used so the
// cancel handler always sees the latest value without re-binding.
@@ -61,11 +60,18 @@ export function HomePage() {
const anyRegenerating = isAnyBusy(loading, regenerating);
// Check localStorage on mount: if the API key isn't set, show a banner
// pointing the user at Settings.
// Check the server on mount. If unreachable, surface a quiet banner.
useEffect(() => {
const cfg = getConfigDisplay();
setApiKeySet(cfg.api_key_set);
const ctrl = new AbortController();
(async () => {
try {
const s = await getServerStatus(ctrl.signal);
setServerOk(Boolean(s.ok));
} catch {
setServerOk(false);
}
})();
return () => ctrl.abort();
}, []);
// Clean up any in-flight request on unmount.
@@ -83,11 +89,43 @@ export function HomePage() {
abortRef.current = null;
}, []);
// Esc cancels any in-flight generation.
useEffect(() => {
if (!anyRegenerating) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
cancel();
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [anyRegenerating, cancel]);
// Build the request payload from the current form values. Kept as a
// function so all three call sites (full / regenerate all / per-section)
// stay in sync.
const buildRequest = useCallback(
(
section: GenerateCall["section"],
extra: Partial<GenerateCall> = {},
): GenerateCall => ({
input: input.idea.trim(),
language: resolveLanguage(input),
...(input.mood.trim() ? { mood: input.mood.trim() } : {}),
...(input.style_hint.trim()
? { style_hint: input.style_hint.trim() }
: {}),
vocals: input.vocals,
section,
...extra,
}),
[input],
);
const runGeneration = useCallback(
async (
buildRequest: (
signal: AbortSignal,
) => Promise<GenerateCall> | GenerateCall,
build: () => GenerateCall,
onSuccess: (result: Partial<SongAssets>) => void,
busySetter: (b: boolean) => void,
successMsg: string,
@@ -99,7 +137,7 @@ export function HomePage() {
busySetter(true);
try {
const req = await buildRequest(ctrl.signal);
const req = build();
const result = await generateSong(req, { signal: ctrl.signal });
onSuccess(result);
toast.success(successMsg);
@@ -124,36 +162,23 @@ export function HomePage() {
const handleGenerate = useCallback(async () => {
if (!input.idea.trim()) return;
await runGeneration(
() => ({
input: input.idea.trim(),
language: resolveLanguage(input),
mood: input.mood.trim() || undefined,
vocals: input.vocals,
section: "all" as const,
}),
() => buildRequest("all"),
(result) => {
const next = result as SongAssets;
setAssets(next);
setOriginalAssets(next);
setSelectedTitleIndex(0);
// Persist to history. Don't `await` — the user shouldn't wait.
addToHistory(input, next);
},
setLoading,
"Song assets generated",
);
}, [input, runGeneration]);
}, [input, buildRequest, runGeneration]);
const handleRegenerateAll = useCallback(async () => {
if (!input.idea.trim()) return;
await runGeneration(
() => ({
input: input.idea.trim(),
language: resolveLanguage(input),
mood: input.mood.trim() || undefined,
vocals: input.vocals,
section: "all" as const,
}),
() => buildRequest("all"),
(result) => {
const next = result as SongAssets;
setAssets(next);
@@ -167,23 +192,16 @@ export function HomePage() {
},
"Regenerated all sections",
);
}, [input, runGeneration]);
}, [input, buildRequest, runGeneration]);
const handleRegenerateSection = useCallback(
async (section: SectionKey) => {
if (!input.idea.trim() || !assets) return;
await runGeneration(
() => ({
input: input.idea.trim(),
language: resolveLanguage(input),
mood: input.mood.trim() || undefined,
vocals: input.vocals,
section,
context: assets,
}),
() => buildRequest(section, { context: assets }),
(result) => {
// Merge partial into current assets, and update the original snapshot
// for the keys that the model returned. Any keys the user has
// Merge partial into current assets, and update the original
// snapshot for the keys that came back. Any keys the user has
// hand-edited that the model *didn't* return stay as-is.
const merged: SongAssets = { ...assets, ...result };
setAssets(merged);
@@ -193,14 +211,15 @@ export function HomePage() {
`Regenerated ${SECTION_LABELS[section]}`,
);
},
[input, assets, runGeneration],
[input, assets, buildRequest, runGeneration],
);
const handleDownload = useCallback(async () => {
if (!assets || !selectedTitle) return;
try {
const blob = await buildSongZip(assets, selectedTitle);
downloadBlob(blob, `${sanitizeFilename(selectedTitle)}.zip`);
const safe = sanitizeFilename(selectedTitle);
downloadBlob(blob, `${safe || "song"}.zip`);
} catch {
toast.error("Could not generate ZIP — please try again");
}
@@ -230,13 +249,14 @@ export function HomePage() {
// Restore a previous generation from history.
const handleLoadHistory = useCallback(
(entry: HistoryEntry) => {
if (anyRegenerating) cancel();
setInput(entry.input);
setAssets(entry.assets);
setOriginalAssets(entry.assets);
setSelectedTitleIndex(0);
toast.info(`Loaded "${truncate(entry.input.idea, 60)}"`);
},
[toast],
[anyRegenerating, cancel, toast],
);
return (
@@ -244,19 +264,21 @@ export function HomePage() {
<header className="sticky top-0 z-20 bg-bg/70 backdrop-blur border-b border-border">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-14 flex items-center justify-between">
<span className="text-sm text-fg-muted">MelodyMuse</span>
<ThemeToggle />
<div className="flex items-center gap-3">
{serverOk === false && (
<span
className="text-xs text-rose-300 hidden sm:inline"
title="The MelodyMuse server is unreachable. Generation will fail."
>
Server offline
</span>
)}
<ThemeToggle />
</div>
</div>
</header>
<main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 lg:py-10">
{!apiKeySet && (
<ConfigBanner
message="No API key configured —"
linkTo="/settings"
linkLabel="Go to Settings →"
/>
)}
<div className="grid grid-cols-1 lg:grid-cols-[35%_minmax(0,1fr)] gap-8">
<div className="lg:sticky lg:top-20 lg:self-start space-y-4">
<InputPanel
@@ -264,6 +286,7 @@ export function HomePage() {
onChange={setInput}
onSubmit={handleGenerate}
loading={loading}
disabled={anyRegenerating}
cancelButton={
<button
type="button"
@@ -315,5 +338,4 @@ function truncate(s: string, n: number): string {
return t.slice(0, n - 1) + "…";
}
// Internal alias so the `runGeneration` helper stays readable.
type GenerateCall = Parameters<typeof generateSong>[0];