Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(music): explain why a song cannot be generated (#23025)

Rdmclin2d7c04e8db206
diff --git a/locales/en-US/music.json b/locales/en-US/music.json
index c5de6704758..43c41f38aa1 100644
--- a/locales/en-US/music.json
+++ b/locales/en-US/music.json
@@ -5,12 +5,14 @@
"config.duration.label": "Duration",
"config.format.label": "Audio Format",
"config.instrumental.label": "Instrumental",
+ "config.lyrics.autoLyricsIgnored": "These lyrics are sung as written. Clear them to have lyrics written from the description.",
"config.lyrics.instrumentalHint": "Instrumental tracks have no vocals, so lyrics are not used",
"config.lyrics.label": "Lyrics",
"config.lyrics.placeholder": "One line per row. Mark sections with tags like [Verse] and [Chorus]. Leave empty to let the model write them.",
"config.model.label": "Model",
"config.negativeStyle.label": "Exclude Styles",
"config.negativeStyle.placeholder": "e.g. heavy metal, screaming",
+ "config.prompt.minLength": "Describe the song in at least {{count}} characters",
"config.prompt.placeholder": "Describe the song: genre, mood, instruments, vocals",
"config.referenceAudio.hint": "{{min}}s – {{max}}s, up to {{size}} MB",
"config.referenceAudio.invalidUrl": "Enter a URL that starts with http:// or https://",
@@ -45,6 +47,8 @@
"generation.status.invalidApiKey": "{{name}} API Key is invalid or missing",
"generation.status.invalidApiKeyHint": "Check the key in the provider settings, then retry.",
"generation.status.queued": "Queued…",
+ "generation.submitFailed": "Could not start generating: {{message}}",
+ "generation.submittedRefreshFailed": "Generation started. Refresh the page if the new song does not appear.",
"notice.modelRemoved": "The current model is no longer available from {{name}}. Please switch to an available model.",
"notice.providerDisabled": "The provider {{name}} for the current model is disabled. Please enable it or switch to an available model.",
"topic.createNew": "Create New Topic",
diff --git a/locales/zh-CN/music.json b/locales/zh-CN/music.json
index a2a02a4b05e..2e923e8fef8 100644
--- a/locales/zh-CN/music.json
+++ b/locales/zh-CN/music.json
@@ -5,12 +5,14 @@
"config.duration.label": "时长",
"config.format.label": "音频格式",
"config.instrumental.label": "纯音乐",
+ "config.lyrics.autoLyricsIgnored": "歌词框有内容时会按原文演唱;清空后才会根据描述自动写词。",
"config.lyrics.instrumentalHint": "纯音乐没有人声,不会使用歌词",
"config.lyrics.label": "歌词",
"config.lyrics.placeholder": "每行一句,可用 [Verse]、[Chorus] 等标签标记段落。留空则由模型代写。",
"config.model.label": "模型",
"config.negativeStyle.label": "排除风格",
"config.negativeStyle.placeholder": "例如:重金属、嘶吼",
+ "config.prompt.minLength": "歌曲描述至少需要 {{count}} 个字",
"config.prompt.placeholder": "描述你想要的歌曲:曲风、情绪、乐器、人声",
"config.referenceAudio.hint": "{{min}} 秒 – {{max}} 秒,不超过 {{size}} MB",
"config.referenceAudio.invalidUrl": "请输入以 http:// 或 https:// 开头的链接",
@@ -45,6 +47,8 @@
"generation.status.invalidApiKey": "{{name}} API Key 无效或未填写",
"generation.status.invalidApiKeyHint": "请在服务商设置中检查密钥后重试。",
"generation.status.queued": "排队中…",
+ "generation.submitFailed": "未能开始生成:{{message}}",
+ "generation.submittedRefreshFailed": "已开始生成。如果没有看到新歌曲,请刷新页面。",
"notice.modelRemoved": "{{name}} 已不再提供当前模型,请切换到可用模型。",
"notice.providerDisabled": "当前模型的服务商 {{name}} 已停用,请启用该服务商或切换到可用模型。",
"topic.createNew": "创作新话题",
diff --git a/packages/locales/src/default/music.ts b/packages/locales/src/default/music.ts
index 6486a238295..f70ec43b5d3 100644
--- a/packages/locales/src/default/music.ts
+++ b/packages/locales/src/default/music.ts
@@ -5,6 +5,8 @@ export default {
'config.duration.label': 'Duration',
'config.format.label': 'Audio Format',
'config.instrumental.label': 'Instrumental',
+ 'config.lyrics.autoLyricsIgnored':
+ 'These lyrics are sung as written. Clear them to have lyrics written from the description.',
'config.lyrics.instrumentalHint': 'Instrumental tracks have no vocals, so lyrics are not used',
'config.lyrics.label': 'Lyrics',
'config.lyrics.placeholder':
@@ -12,6 +14,7 @@ export default {
'config.model.label': 'Model',
'config.negativeStyle.label': 'Exclude Styles',
'config.negativeStyle.placeholder': 'e.g. heavy metal, screaming',
+ 'config.prompt.minLength': 'Describe the song in at least {{count}} characters',
'config.prompt.placeholder': 'Describe the song: genre, mood, instruments, vocals',
'config.referenceAudio.hint': '{{min}}s – {{max}}s, up to {{size}} MB',
'config.referenceAudio.invalidUrl': 'Enter a URL that starts with http:// or https://',
@@ -40,6 +43,9 @@ export default {
'generation.metadata.instrumental': 'Instrumental',
'generation.song.fileName': 'Song',
'generation.song.untitled': 'Song {{index}}',
+ 'generation.submitFailed': 'Could not start generating: {{message}}',
+ 'generation.submittedRefreshFailed':
+ 'Generation started. Refresh the page if the new song does not appear.',
'generation.status.failed': 'Generation Failed',
'generation.status.generating': 'Generating…',
'generation.status.generatingHint': 'A song usually takes 1–3 minutes',
diff --git a/src/routes/(main)/(create)/music/features/PromptInput/MusicParams.tsx b/src/routes/(main)/(create)/music/features/PromptInput/MusicParams.tsx
index 70a0d8274a6..eb18f79144b 100644
--- a/src/routes/(main)/(create)/music/features/PromptInput/MusicParams.tsx
+++ b/src/routes/(main)/(create)/music/features/PromptInput/MusicParams.tsx
@@ -84,6 +84,9 @@ const LyricsParam = memo<{ disabled?: boolean }>(({ disabled }) => {
const { t } = useTranslation('music');
const { value, setValue, schema } = useMusicGenerationConfigParam('lyrics');
const { value: instrumental } = useMusicGenerationConfigParam('instrumental');
+ const { value: autoLyrics } = useMusicGenerationConfigParam('autoLyrics');
+ // Auto-written lyrics only apply to an empty lyrics box; filled text is sung as written
+ const lyricsOverrideAutoLyrics = !!autoLyrics && !instrumental && !!value?.trim();
return (
<Flexbox gap={4}>
@@ -103,6 +106,11 @@ const LyricsParam = memo<{ disabled?: boolean }>(({ disabled }) => {
}
onChange={(e) => setValue(e.target.value)}
/>
+ {lyricsOverrideAutoLyrics && (
+ <Text fontSize={12} type={'warning'}>
+ {t('config.lyrics.autoLyricsIgnored')}
+ </Text>
+ )}
</Flexbox>
);
});
diff --git a/src/routes/(main)/(create)/music/features/PromptInput/index.tsx b/src/routes/(main)/(create)/music/features/PromptInput/index.tsx
index 0c5c41b773a..2b9725c99b3 100644
--- a/src/routes/(main)/(create)/music/features/PromptInput/index.tsx
+++ b/src/routes/(main)/(create)/music/features/PromptInput/index.tsx
@@ -1,6 +1,7 @@
'use client';
-import { ActionIcon, Flexbox } from '@lobehub/ui';
+import { ActionIcon, Flexbox, Text } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { memo, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -36,6 +37,14 @@ import AudioSettings, { useHasAudioSettings } from './AudioSettings';
import MusicParams from './MusicParams';
import PromptTitle from './Title';
+const styles = stylex.create({
+ // Same inset as the blocked-prompt notice so the hint does not touch the input border
+ promptHint: {
+ paddingBlockStart: '8px',
+ paddingInline: '12px',
+ },
+});
+
interface PromptInputProps {
disableAnimation?: boolean;
showTitle?: boolean;
@@ -51,6 +60,7 @@ const PromptInput = memo<PromptInputProps>(({ showTitle = false }) => {
const dismissBlockedPrompt = useMusicStore((s) => s.dismissBlockedPrompt);
const createMusic = useMusicStore((s) => s.createMusic);
const canSubmit = useMusicStore(musicGenerationConfigSelectors.canSubmit);
+ const promptMinLength = useMusicStore(musicGenerationConfigSelectors.promptMinLength);
const isInit = useMusicStore((s) => s.isInit);
const currentModel = useMusicStore(musicGenerationConfigSelectors.model);
const currentProvider = useMusicStore(musicGenerationConfigSelectors.provider);
@@ -130,6 +140,12 @@ const PromptInput = memo<PromptInputProps>(({ showTitle = false }) => {
header={
isPromptBlocked ? (
<GenerationPromptBlockedNotice onClose={dismissBlockedPrompt} />
+ ) : promptMinLength ? (
+ <div className={stylex.props(styles.promptHint).className}>
+ <Text fontSize={12} type={'warning'}>
+ {t('config.prompt.minLength', { count: promptMinLength })}
+ </Text>
+ </div>
) : undefined
}
leftActions={
diff --git a/src/store/music/slices/createMusic/action.test.ts b/src/store/music/slices/createMusic/action.test.ts
index a15e4de565c..2b74e56e3bc 100644
--- a/src/store/music/slices/createMusic/action.test.ts
+++ b/src/store/music/slices/createMusic/action.test.ts
@@ -6,10 +6,17 @@ import { useMusicStore } from '@/store/music';
import { buildMusicRequestParams } from './action';
-const { isGenerationPromptModerationErrorMock } = vi.hoisted(() => ({
+const { isGenerationPromptModerationErrorMock, toastErrorMock, toastInfoMock } = vi.hoisted(() => ({
isGenerationPromptModerationErrorMock: vi.fn(),
+ toastErrorMock: vi.fn(),
+ toastInfoMock: vi.fn(),
}));
+vi.mock('@lobehub/ui', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, any>>();
+ return { ...actual, toast: { ...actual.toast, error: toastErrorMock, info: toastInfoMock } };
+});
+
vi.mock('@/business/client/isGenerationPromptModerationError', () => ({
isGenerationPromptModerationError: isGenerationPromptModerationErrorMock,
}));
@@ -131,6 +138,43 @@ describe('CreateMusicAction', () => {
expect(state.blockedPrompt).toBe('city pop');
expect(state.parameters.prompt).toBe('city pop');
expect(state.isCreating).toBe(false);
+ // The blocked notice on the input explains it; no second toast
+ expect(toastErrorMock).not.toHaveBeenCalled();
+ });
+
+ it('tells the user why any other rejected submission failed, keeping the draft', async () => {
+ vi.mocked(musicService.createMusic).mockRejectedValueOnce(
+ new Error('Invalid music params: "prompt" needs at least 10 characters'),
+ );
+
+ await expect(useMusicStore.getState().createMusic()).rejects.toThrow('Invalid music params');
+
+ // Before this, the error only reached the console and the generate button looked dead
+ expect(toastErrorMock).toHaveBeenCalledWith('generation.submitFailed');
+ expect(useMusicStore.getState().parameters.prompt).toBe('city pop');
+ });
+
+ it('treats a refresh failure after an accepted submission as started, not failed', async () => {
+ refreshGenerationBatches.mockRejectedValueOnce(new Error('network down'));
+
+ // Resolves: the server accepted the batch, so the user must not be invited to resubmit
+ await expect(useMusicStore.getState().createMusic()).resolves.toBeUndefined();
+
+ expect(musicService.createMusic).toHaveBeenCalledTimes(1);
+ expect(toastErrorMock).not.toHaveBeenCalled();
+ expect(toastInfoMock).toHaveBeenCalledWith('generation.submittedRefreshFailed');
+ expect(useMusicStore.getState().parameters.prompt).toBe('');
+ expect(useMusicStore.getState().isCreating).toBe(false);
+ });
+
+ it('refuses a prompt shorter than the model minimum without calling the server', async () => {
+ useMusicStore.setState({
+ parameters: { prompt: '和风' },
+ parametersSchema: { ...songSchema, prompt: { default: '', minLength: 10 } },
+ });
+
+ await expect(useMusicStore.getState().createMusic()).rejects.toThrow(TypeError);
+ expect(musicService.createMusic).not.toHaveBeenCalled();
});
it('refuses an empty draft without calling the server', async () => {
diff --git a/src/store/music/slices/createMusic/action.ts b/src/store/music/slices/createMusic/action.ts
index c6c6a316f0c..19fc9607bdd 100644
--- a/src/store/music/slices/createMusic/action.ts
+++ b/src/store/music/slices/createMusic/action.ts
@@ -1,4 +1,6 @@
+import { ChatErrorType } from '@lobechat/types';
import { toast } from '@lobehub/ui';
+import { TRPCClientError } from '@trpc/client';
import { t } from 'i18next';
import { type RuntimeMusicGenParams } from 'model-bank';
@@ -15,6 +17,10 @@ import { generationTopicSelectors } from '../generationTopic';
type Setter = StoreSetter<MusicStore>;
+/** Shown by `handleLobeHubModelDeprecatedError`; every other failure needs its own toast. */
+const isModelDeprecatedError = (error: unknown) =>
+ error instanceof TRPCClientError && error.message === ChatErrorType.LobeHubModelDeprecated;
+
/**
* Send only the params the selected model declares: the server rejects undeclared params, and
* empty optional text is dropped so it does not change how the provider reads the request. Lyrics
@@ -107,10 +113,8 @@ export class CreateMusicActionImpl {
provider,
});
- // 3. Show the new batch
- await this.#get().refreshGenerationBatches();
-
- // 4. Clear the prompt; lyrics, title and style stay for the next variation
+ // 3. Clear the prompt; lyrics, title and style stay for the next variation. The server
+ // accepted the batch, so a later refresh failure must not invite a duplicate (charged) retry.
this.#set(
(state) => ({ parameters: { ...state.parameters, prompt: '' } }),
false,
@@ -120,8 +124,18 @@ export class CreateMusicActionImpl {
// A rejected prompt is shown on the prompt input, where the user fixes it.
if (isGenerationPromptModerationError(error)) {
this.#set({ blockedPrompt: parameters.prompt }, false, 'createMusic/promptBlocked');
+ } else if (isModelDeprecatedError(error)) {
+ handleLobeHubModelDeprecatedError(error);
+ } else {
+ // Anything else (invalid params, a failed topic or batch request) would otherwise only reach
+ // the console and the generate button would look unresponsive.
+ toast.error(
+ t('generation.submitFailed', {
+ message: error instanceof Error ? error.message : String(error),
+ ns: 'music',
+ }),
+ );
}
- handleLobeHubModelDeprecatedError(error);
throw error;
} finally {
this.#set(
@@ -130,6 +144,15 @@ export class CreateMusicActionImpl {
'createMusic/endCreateMusic',
);
}
+
+ // 4. Show the new batch. The generation already started, so a failed refresh only hides it
+ // until the list reloads; tell the user instead of reporting a failed submission.
+ try {
+ await this.#get().refreshGenerationBatches();
+ } catch (error) {
+ console.error('[createMusic] failed to refresh batches after submitting', error);
+ toast.info(t('generation.submittedRefreshFailed', { ns: 'music' }));
+ }
};
dismissBlockedPrompt = (): void => {
diff --git a/src/store/music/slices/generationConfig/action.test.ts b/src/store/music/slices/generationConfig/action.test.ts
index 26b4e689d3e..c29a861e893 100644
--- a/src/store/music/slices/generationConfig/action.test.ts
+++ b/src/store/music/slices/generationConfig/action.test.ts
@@ -129,6 +129,25 @@ describe('music generationConfig', () => {
expect(canSubmit({ instrumental: true, prompt: 'pop' })).toBe(true);
});
+ it('blocks a prompt shorter than the model minimum and reports the required length', () => {
+ const base = {
+ ...useMusicStore.getState(),
+ parametersSchema: { prompt: { default: '', minLength: 10, required: true } },
+ };
+ const state = (prompt: string) => ({ ...base, parameters: { prompt } }) as typeof base;
+
+ expect(musicGenerationConfigSelectors.promptMinLength(state('和风'))).toBe(10);
+ expect(musicGenerationConfigSelectors.canSubmit(state('和风'))).toBe(false);
+ // An empty prompt is caught by the required rule, not reported as too short
+ expect(musicGenerationConfigSelectors.promptMinLength(state(''))).toBeUndefined();
+ expect(
+ musicGenerationConfigSelectors.promptMinLength(state('日系和风抒情流行,少女伤感')),
+ ).toBeUndefined();
+ expect(musicGenerationConfigSelectors.canSubmit(state('日系和风抒情流行,少女伤感'))).toBe(
+ true,
+ );
+ });
+
it('canSubmit accepts lyrics or style without a prompt but requires declared reference audio', () => {
const base = { ...useMusicStore.getState(), parametersSchema: songSchema };
diff --git a/src/store/music/slices/generationConfig/selectors.ts b/src/store/music/slices/generationConfig/selectors.ts
index eb26fd1e8be..f8c29fd012f 100644
--- a/src/store/music/slices/generationConfig/selectors.ts
+++ b/src/store/music/slices/generationConfig/selectors.ts
@@ -14,6 +14,18 @@ const isSupportedParam = (paramName: MusicModelParamsKeys) => (s: MusicGeneratio
const hasText = (value?: string | null) => !!value && value.trim().length > 0;
+/**
+ * The prompt length the selected model requires when the current prompt is shorter (MiniMax Music
+ * 2.6 needs 10 characters); `undefined` when the prompt is empty or long enough. The server rejects
+ * a shorter prompt, so the input blocks it and says why instead.
+ */
+const promptMinLength = (s: MusicGenerationConfigState) => {
+ const min = s.parametersSchema.prompt?.minLength;
+ const prompt = s.parameters.prompt ?? '';
+
+ return min && hasText(prompt) && prompt.length < min ? min : undefined;
+};
+
/**
* Whether the draft has enough input to submit: the selected model's required params are filled
* and the draft carries at least one piece of song input.
@@ -24,6 +36,7 @@ const canSubmit = (s: MusicGenerationConfigState) => {
if (!model) return false;
if (schema.referenceAudioUrl?.required && !hasText(params.referenceAudioUrl)) return false;
if (schema.prompt?.required && !hasText(params.prompt)) return false;
+ if (promptMinLength(s)) return false;
// Lyrics are not sent for an instrumental track, so they cannot count as input
const hasLyrics = !params.instrumental && hasText(params.lyrics);
@@ -43,6 +56,7 @@ export const musicGenerationConfigSelectors = {
model,
parameters,
parametersSchema,
+ promptMinLength,
provider,
uploadingReferenceAudio,
};