Add cancel, history, revert, and quality-of-life features
UX - Add elapsed-time counter and Cancel button to in-flight generations, wired through AbortController so partial responses are discarded cleanly. The cancel action is available from both the input panel and the results header. - Add a Recent generations panel below the input. The last 6 successful generations are saved to localStorage; one click reloads both the input fields and the generated assets. - Add a Revert button to every editable card. It appears the moment the current value diverges from the last generated value and restores the field with a single click. - Add an Empty state to the right panel with a friendly hint pointing at the Generate button and the Settings page. - Add a 'Try an example' button that fills the input with a random starter idea (idea + mood + vocals). - Add Cmd/Ctrl+Enter as a keyboard shortcut to generate. - Add a Footer with project info and a privacy reminder. - Add a 'Clear saved key' button to the Settings page so the user can remove the API key without overwriting it. Bug fix - Settings > Test Connection used to save the in-progress form values to localStorage before testing. It now uses the in-memory candidate config, so failed tests don't pollute the saved config. Code quality - Extract the duplicated useAutoHeight hook to src/lib/useAutoHeight.ts. - Extract a useElapsed hook for the loading timer. - Move InputValues into src/lib/types.ts (was duplicated in InputPanel.tsx) and add SECTION_LABELS, replacing the humanizeSection switch in HomePage. - Centralize the filename sanitization: HomePage now calls sanitizeFilename from zip.ts instead of duplicating the regex. - Add previewConfig / testConnectionWithConfig helpers to llm.ts to support in-memory connection tests.
This commit is contained in:
+159
-82
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { InputPanel, type InputValues } from "../components/InputPanel";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { InputPanel } from "../components/InputPanel";
|
||||
import type { InputValues } from "../components/InputPanel";
|
||||
import {
|
||||
ResultsPanel,
|
||||
type RegeneratingMap,
|
||||
@@ -9,10 +9,17 @@ import {
|
||||
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 { buildSongZip, downloadBlob } from "../lib/zip";
|
||||
import type { SongAssets, VideoPrompt } from "../lib/types";
|
||||
import { addToHistory, type HistoryEntry } from "../lib/history";
|
||||
import { buildSongZip, downloadBlob, sanitizeFilename } from "../lib/zip";
|
||||
import {
|
||||
SECTION_LABELS,
|
||||
type SongAssets,
|
||||
type VideoPrompt,
|
||||
} from "../lib/types";
|
||||
|
||||
const DEFAULT_INPUT: InputValues = {
|
||||
idea: "",
|
||||
@@ -28,16 +35,32 @@ 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;
|
||||
return false;
|
||||
}
|
||||
|
||||
export function HomePage() {
|
||||
const toast = useToast();
|
||||
|
||||
const [input, setInput] = useState<InputValues>(DEFAULT_INPUT);
|
||||
const [assets, setAssets] = useState<SongAssets | null>(null);
|
||||
// The "last generated" snapshot. The cards compare their current editable
|
||||
// values against these to decide whether to show the Revert button.
|
||||
const [originalAssets, setOriginalAssets] = useState<SongAssets | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [regenerating, setRegenerating] = useState<RegeneratingMap>({});
|
||||
const [selectedTitleIndex, setSelectedTitleIndex] = useState(0);
|
||||
const [apiKeySet, setApiKeySet] = useState<boolean>(false);
|
||||
|
||||
// AbortController for the *current* network request. Refs are used so the
|
||||
// cancel handler always sees the latest value without re-binding.
|
||||
const abortRef = useRef<AbortController | null>(null);
|
||||
|
||||
const anyRegenerating = isAnyBusy(loading, regenerating);
|
||||
|
||||
// Check localStorage on mount: if the API key isn't set, show a banner
|
||||
// pointing the user at Settings.
|
||||
useEffect(() => {
|
||||
@@ -45,6 +68,9 @@ export function HomePage() {
|
||||
setApiKeySet(cfg.api_key_set);
|
||||
}, []);
|
||||
|
||||
// Clean up any in-flight request on unmount.
|
||||
useEffect(() => () => abortRef.current?.abort(), []);
|
||||
|
||||
const selectedTitle = useMemo(() => {
|
||||
if (!assets || assets.titles.length === 0) return undefined;
|
||||
return assets.titles[
|
||||
@@ -52,94 +78,129 @@ export function HomePage() {
|
||||
];
|
||||
}, [assets, selectedTitleIndex]);
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
abortRef.current?.abort();
|
||||
abortRef.current = null;
|
||||
}, []);
|
||||
|
||||
const runGeneration = useCallback(
|
||||
async (
|
||||
buildRequest: (
|
||||
signal: AbortSignal,
|
||||
) => Promise<GenerateCall> | GenerateCall,
|
||||
onSuccess: (result: Partial<SongAssets>) => void,
|
||||
busySetter: (b: boolean) => void,
|
||||
successMsg: string,
|
||||
) => {
|
||||
// Cancel any in-flight request before starting a new one.
|
||||
abortRef.current?.abort();
|
||||
const ctrl = new AbortController();
|
||||
abortRef.current = ctrl;
|
||||
|
||||
busySetter(true);
|
||||
try {
|
||||
const req = await buildRequest(ctrl.signal);
|
||||
const result = await generateSong(req, { signal: ctrl.signal });
|
||||
onSuccess(result);
|
||||
toast.success(successMsg);
|
||||
} catch (err) {
|
||||
if (err instanceof DOMException && err.name === "AbortError") {
|
||||
toast.info("Generation cancelled");
|
||||
} else {
|
||||
toast.error(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Generation failed — please try again",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
busySetter(false);
|
||||
if (abortRef.current === ctrl) abortRef.current = null;
|
||||
}
|
||||
},
|
||||
[toast],
|
||||
);
|
||||
|
||||
const handleGenerate = useCallback(async () => {
|
||||
if (!input.idea.trim()) return;
|
||||
setLoading(true);
|
||||
setAssets(null);
|
||||
try {
|
||||
const result = await generateSong({
|
||||
await runGeneration(
|
||||
() => ({
|
||||
input: input.idea.trim(),
|
||||
language: resolveLanguage(input),
|
||||
mood: input.mood.trim() || undefined,
|
||||
vocals: input.vocals,
|
||||
section: "all",
|
||||
});
|
||||
setAssets(result);
|
||||
setSelectedTitleIndex(0);
|
||||
toast.success("Song assets generated");
|
||||
} catch (err) {
|
||||
toast.error(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Generation failed — please try again",
|
||||
);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [input, toast]);
|
||||
section: "all" as const,
|
||||
}),
|
||||
(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]);
|
||||
|
||||
const handleRegenerateAll = useCallback(async () => {
|
||||
if (!input.idea.trim()) return;
|
||||
setLoading(true);
|
||||
setRegenerating((m) => ({ ...m, all: true }));
|
||||
try {
|
||||
const result = await generateSong({
|
||||
await runGeneration(
|
||||
() => ({
|
||||
input: input.idea.trim(),
|
||||
language: resolveLanguage(input),
|
||||
mood: input.mood.trim() || undefined,
|
||||
vocals: input.vocals,
|
||||
section: "all",
|
||||
});
|
||||
setAssets(result);
|
||||
setSelectedTitleIndex(0);
|
||||
toast.success("Regenerated all sections");
|
||||
} catch (err) {
|
||||
toast.error(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Generation failed — please try again",
|
||||
);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setRegenerating((m) => ({ ...m, all: false }));
|
||||
}
|
||||
}, [input, toast]);
|
||||
section: "all" as const,
|
||||
}),
|
||||
(result) => {
|
||||
const next = result as SongAssets;
|
||||
setAssets(next);
|
||||
setOriginalAssets(next);
|
||||
setSelectedTitleIndex(0);
|
||||
addToHistory(input, next);
|
||||
},
|
||||
(b) => {
|
||||
setLoading(b);
|
||||
setRegenerating((m) => ({ ...m, all: b }));
|
||||
},
|
||||
"Regenerated all sections",
|
||||
);
|
||||
}, [input, runGeneration]);
|
||||
|
||||
const handleRegenerateSection = useCallback(
|
||||
async (section: SectionKey) => {
|
||||
if (!input.idea.trim() || !assets) return;
|
||||
setRegenerating((m) => ({ ...m, [section]: true }));
|
||||
try {
|
||||
const result = await generateSong({
|
||||
await runGeneration(
|
||||
() => ({
|
||||
input: input.idea.trim(),
|
||||
language: resolveLanguage(input),
|
||||
mood: input.mood.trim() || undefined,
|
||||
vocals: input.vocals,
|
||||
section,
|
||||
// Pass the rest of the song as context so the model can stay consistent.
|
||||
context: assets,
|
||||
});
|
||||
setAssets({ ...assets, ...result });
|
||||
toast.success(`Regenerated ${humanizeSection(section)}`);
|
||||
} catch (err) {
|
||||
toast.error(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Generation failed — please try again",
|
||||
);
|
||||
} finally {
|
||||
setRegenerating((m) => ({ ...m, [section]: false }));
|
||||
}
|
||||
}),
|
||||
(result) => {
|
||||
// Merge partial into current assets, and update the original snapshot
|
||||
// for the keys that the model returned. Any keys the user has
|
||||
// hand-edited that the model *didn't* return stay as-is.
|
||||
const merged: SongAssets = { ...assets, ...result };
|
||||
setAssets(merged);
|
||||
setOriginalAssets((prev) => (prev ? { ...prev, ...result } : merged));
|
||||
},
|
||||
(b) => setRegenerating((m) => ({ ...m, [section]: b })),
|
||||
`Regenerated ${SECTION_LABELS[section]}`,
|
||||
);
|
||||
},
|
||||
[input, assets, toast],
|
||||
[input, assets, runGeneration],
|
||||
);
|
||||
|
||||
const handleDownload = useCallback(async () => {
|
||||
if (!assets || !selectedTitle) return;
|
||||
try {
|
||||
const blob = await buildSongZip(assets, selectedTitle);
|
||||
const filename = `${selectedTitle.replace(/\s+/g, "_").replace(/[^a-zA-Z0-9_-]/g, "")}.zip`;
|
||||
downloadBlob(blob, filename);
|
||||
downloadBlob(blob, `${sanitizeFilename(selectedTitle)}.zip`);
|
||||
} catch {
|
||||
toast.error("Could not generate ZIP — please try again");
|
||||
}
|
||||
@@ -166,16 +227,23 @@ export function HomePage() {
|
||||
[],
|
||||
);
|
||||
|
||||
// Restore a previous generation from history.
|
||||
const handleLoadHistory = useCallback(
|
||||
(entry: HistoryEntry) => {
|
||||
setInput(entry.input);
|
||||
setAssets(entry.assets);
|
||||
setOriginalAssets(entry.assets);
|
||||
setSelectedTitleIndex(0);
|
||||
toast.info(`Loaded "${truncate(entry.input.idea, 60)}"`);
|
||||
},
|
||||
[toast],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen pb-32">
|
||||
<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">
|
||||
<Link
|
||||
to="/"
|
||||
className="text-sm text-fg-muted hover:text-fg transition-colors"
|
||||
>
|
||||
MelodyMuse
|
||||
</Link>
|
||||
<span className="text-sm text-fg-muted">MelodyMuse</span>
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
</header>
|
||||
@@ -196,12 +264,23 @@ export function HomePage() {
|
||||
onChange={setInput}
|
||||
onSubmit={handleGenerate}
|
||||
loading={loading}
|
||||
cancelButton={
|
||||
<button
|
||||
type="button"
|
||||
onClick={cancel}
|
||||
className="btn-secondary w-full"
|
||||
>
|
||||
Cancel generation
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<HistoryPanel onLoad={handleLoadHistory} />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<ResultsPanel
|
||||
assets={assets}
|
||||
originalAssets={originalAssets}
|
||||
loading={loading}
|
||||
selectedTitleIndex={selectedTitleIndex}
|
||||
onSelectTitle={setSelectedTitleIndex}
|
||||
@@ -209,6 +288,8 @@ export function HomePage() {
|
||||
onChangeVideoPrompt={handleVideoPromptChange}
|
||||
onRegenerateAll={handleRegenerateAll}
|
||||
onRegenerateSection={handleRegenerateSection}
|
||||
onCancel={cancel}
|
||||
anyRegenerating={anyRegenerating}
|
||||
regenerating={regenerating}
|
||||
/>
|
||||
</div>
|
||||
@@ -222,21 +303,17 @@ export function HomePage() {
|
||||
onDownload={handleDownload}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function humanizeSection(s: SectionKey): string {
|
||||
switch (s) {
|
||||
case "titles":
|
||||
return "titles";
|
||||
case "lyrics":
|
||||
return "lyrics";
|
||||
case "style":
|
||||
return "style";
|
||||
case "video_prompts":
|
||||
return "video prompts";
|
||||
case "youtube_description":
|
||||
return "description";
|
||||
}
|
||||
function truncate(s: string, n: number): string {
|
||||
const t = s.trim();
|
||||
if (t.length <= n) return t || "previous generation";
|
||||
return t.slice(0, n - 1) + "…";
|
||||
}
|
||||
|
||||
// Internal alias so the `runGeneration` helper stays readable.
|
||||
type GenerateCall = Parameters<typeof generateSong>[0];
|
||||
|
||||
+56
-19
@@ -1,14 +1,30 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link, useNavigate } from "react-router-dom";
|
||||
import { ArrowLeft, Eye, EyeOff, Loader2, Save, Plug } from "lucide-react";
|
||||
import {
|
||||
ArrowLeft,
|
||||
Eye,
|
||||
EyeOff,
|
||||
Loader2,
|
||||
Save,
|
||||
Plug,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { ThemeToggle } from "../components/ThemeToggle";
|
||||
import { useToast } from "../lib/toast";
|
||||
import { getConfigDisplay, setConfig, testConnection } from "../lib/llm";
|
||||
import {
|
||||
getConfigDisplay,
|
||||
setConfig,
|
||||
previewConfig,
|
||||
testConnectionWithConfig,
|
||||
saveConfig,
|
||||
loadConfig,
|
||||
DEFAULT_MODEL,
|
||||
} from "../lib/llm";
|
||||
|
||||
const DEFAULTS = {
|
||||
api_endpoint: "",
|
||||
api_key: "",
|
||||
model_name: "MiniMax-M3",
|
||||
model_name: DEFAULT_MODEL,
|
||||
};
|
||||
|
||||
export function SettingsPage() {
|
||||
@@ -34,7 +50,7 @@ export function SettingsPage() {
|
||||
setLoading(false);
|
||||
}, []);
|
||||
|
||||
const onSave = async (e: React.FormEvent) => {
|
||||
const onSave = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setSaving(true);
|
||||
try {
|
||||
@@ -55,27 +71,28 @@ export function SettingsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// Test using *in-memory* form values — don't persist until the user clicks
|
||||
// Save. An empty API key field still falls back to the previously saved key,
|
||||
// matching the behaviour of Save.
|
||||
const onTest = async () => {
|
||||
setTesting(true);
|
||||
// Persist current form values first so the test reflects them. setConfig
|
||||
// preserves the existing key when the field is empty, so this is safe.
|
||||
try {
|
||||
const result = setConfig({
|
||||
api_endpoint: endpoint.trim(),
|
||||
api_key: apiKey,
|
||||
model_name: model.trim(),
|
||||
});
|
||||
setApiKey("");
|
||||
setApiKeySet(result.api_key_set);
|
||||
} catch (err) {
|
||||
const candidate = previewConfig({
|
||||
api_endpoint: endpoint.trim(),
|
||||
api_key: apiKey,
|
||||
model_name: model.trim(),
|
||||
});
|
||||
|
||||
if (
|
||||
!candidate.api_endpoint ||
|
||||
!candidate.api_key ||
|
||||
!candidate.model_name
|
||||
) {
|
||||
setTesting(false);
|
||||
toast.error(
|
||||
err instanceof Error ? err.message : "Failed to save configuration",
|
||||
);
|
||||
toast.error("❌ Fill in endpoint, key, and model before testing");
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await testConnection();
|
||||
const result = await testConnectionWithConfig(candidate);
|
||||
if (result.success) {
|
||||
toast.success(`✅ ${result.message}`);
|
||||
} else {
|
||||
@@ -84,6 +101,16 @@ export function SettingsPage() {
|
||||
setTesting(false);
|
||||
};
|
||||
|
||||
const onClearKey = () => {
|
||||
if (!apiKeySet) return;
|
||||
if (!window.confirm("Clear the saved API key from this browser?")) return;
|
||||
const current = loadConfig();
|
||||
saveConfig({ ...current, api_key: "" });
|
||||
setApiKeySet(false);
|
||||
setApiKey("");
|
||||
toast.info("Saved API key cleared");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen">
|
||||
<header className="sticky top-0 z-20 bg-bg/70 backdrop-blur border-b border-border">
|
||||
@@ -175,6 +202,16 @@ export function SettingsPage() {
|
||||
A key is currently saved.
|
||||
</p>
|
||||
)}
|
||||
{apiKeySet && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClearKey}
|
||||
className="mt-2 inline-flex items-center gap-1 text-xs text-fg-muted hover:text-rose-300 transition-colors"
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
Clear saved key
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
|
||||
Reference in New Issue
Block a user