Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor(api): use project HTTP errors in Explore controllers (#43481)

非法操作63d2af7d276c
diff --git a/api/controllers/common/errors.py b/api/controllers/common/errors.py
index 78cee1b813c..aa8316d6103 100644
--- a/api/controllers/common/errors.py
+++ b/api/controllers/common/errors.py
@@ -92,6 +92,23 @@ class NotFoundError(BaseHTTPException):
code = 404
+class UnauthorizedError(BaseHTTPException):
+ error_code = "unauthorized"
+ code = HTTPStatus.UNAUTHORIZED
+ description = "Authentication is required."
+
+
+class InternalServerError(BaseHTTPException):
+ """Expose a safe response while retaining the original exception in server logs."""
+
+ error_code = "internal_server_error"
+ code = HTTPStatus.INTERNAL_SERVER_ERROR
+ description = (
+ "The server encountered an internal error and was unable to complete your request. "
+ "Either the server is overloaded or there is an error in the application."
+ )
+
+
class InvalidArgumentError(BaseHTTPException):
error_code = "invalid_param"
code = 400
diff --git a/api/controllers/console/explore/audio.py b/api/controllers/console/explore/audio.py
index 171ff0f72e6..0bad46484b2 100644
--- a/api/controllers/console/explore/audio.py
+++ b/api/controllers/console/explore/audio.py
@@ -7,10 +7,10 @@ from http import HTTPStatus
from flask import Response, request
from flask_restx import Resource
-from werkzeug.exceptions import HTTPException, InternalServerError
from controllers.common.audio_response import audio_binary_response
from controllers.common.controller_schemas import TextToAudioPayload
+from controllers.common.errors import InternalServerError
from controllers.common.fields import AudioBinaryResponse, AudioTranscriptResponse
from controllers.common.schema import register_response_schema_models, register_schema_model
from controllers.console import console_ns
@@ -27,14 +27,17 @@ from controllers.console.app.error import (
SpeechToTextDisabledError,
UnsupportedAudioTypeError,
)
+from controllers.console.explore.error import AgentVersionNotFoundHTTPError
from controllers.console.explore.installed_app_admission import get_installed_app
from controllers.console.flask_admission import console_account_admission
from controllers.console.wraps import model_validate
from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError
from extensions.ext_application_services import application_services
from graphon.model_runtime.errors.invoke import InvokeError
+from libs.exception import BaseHTTPException
from libs.helper import dump_response
from machinery.context import RequestContext
+from services.agent.errors import AgentVersionNotFoundError
from services.app_definition_query_service import AppDefinitionUnavailableError
from services.audio_types import AudioAppRef, AudioUpload
from services.errors.app_model_config import AppModelConfigBrokenError
@@ -84,7 +87,9 @@ def _audio_errors[**P, R](view: Callable[P, R]) -> Callable[P, R]:
raise ProviderModelCurrentlyNotSupportError() from error
except InvokeError as error:
raise CompletionRequestError(error.description) from error
- except (HTTPException, ValueError):
+ except AgentVersionNotFoundError as error:
+ raise AgentVersionNotFoundHTTPError() from error
+ except (BaseHTTPException, ValueError):
raise
except Exception as error:
logger.exception("Installed-app audio operation failed")
@@ -101,10 +106,15 @@ class ChatAudioApi(Resource):
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[AudioTranscriptResponse.__name__])
@console_account_admission()
@get_installed_app
- @_audio_errors
def post(self, request_context: RequestContext, installed_app: InstalledAppRef) -> dict[str, object]:
+ # Let Flask handle multipart parsing errors before mapping audio operation failures.
file = request.files.get("file")
audio = AudioUpload(stream=file.stream, mime_type=file.mimetype) if file is not None else None
+ return self._transcribe(installed_app, audio)
+
+ @_audio_errors
+ def _transcribe(self, installed_app: InstalledAppRef, audio: AudioUpload | None) -> dict[str, object]:
+ """Transcribe an upload; None lets the audio service report a missing file."""
transcript = application_services().app_audio.transcript_asr(
app=AudioAppRef(
app_id=installed_app.app_id,
diff --git a/api/controllers/console/explore/completion.py b/api/controllers/console/explore/completion.py
index 9e742140e9d..b6a469a0450 100644
--- a/api/controllers/console/explore/completion.py
+++ b/api/controllers/console/explore/completion.py
@@ -6,9 +6,9 @@ from uuid import UUID
from flask import Response
from flask_restx import Resource
from pydantic import BaseModel, Field, field_validator
-from werkzeug.exceptions import InternalServerError, NotFound, Unauthorized
import services
+from controllers.common.errors import InternalServerError, NotFoundError, UnauthorizedError
from controllers.common.fields import SimpleResultResponse
from controllers.common.schema import register_response_schema_models, register_schema_models
from controllers.console.app.error import (
@@ -112,11 +112,11 @@ class CompletionApi(Resource):
except InstalledAppNotCompletionError:
raise NotCompletionAppError() from None
except InstalledAppNotFoundError:
- raise NotFound("Installed app not found") from None
+ raise NotFoundError("Installed app not found") from None
except AccountNotFoundError:
- raise Unauthorized("Account no longer exists.") from None
+ raise UnauthorizedError("Account no longer exists.") from None
except services.errors.conversation.ConversationNotExistsError:
- raise NotFound("Conversation Not Exists.")
+ raise NotFoundError("Conversation Not Exists.")
except services.errors.conversation.ConversationCompletedError:
raise ConversationCompletedError()
except services.errors.app_model_config.AppModelConfigBrokenError:
@@ -192,11 +192,11 @@ class ChatApi(Resource):
except InstalledAppNotChatError:
raise NotChatAppError() from None
except InstalledAppNotFoundError:
- raise NotFound("Installed app not found") from None
+ raise NotFoundError("Installed app not found") from None
except AccountNotFoundError:
- raise Unauthorized("Account no longer exists.") from None
+ raise UnauthorizedError("Account no longer exists.") from None
except services.errors.conversation.ConversationNotExistsError:
- raise NotFound("Conversation Not Exists.")
+ raise NotFoundError("Conversation Not Exists.")
except services.errors.conversation.ConversationCompletedError:
raise ConversationCompletedError()
except services.errors.app_model_config.AppModelConfigBrokenError:
diff --git a/api/controllers/console/explore/error.py b/api/controllers/console/explore/error.py
index 37dba84470f..16818c7fda9 100644
--- a/api/controllers/console/explore/error.py
+++ b/api/controllers/console/explore/error.py
@@ -4,6 +4,12 @@ from core.logging.context import get_request_id
from libs.exception import BaseHTTPException
+class AgentVersionNotFoundHTTPError(BaseHTTPException):
+ error_code = "agent_version_not_found_error"
+ description = "Agent config version not found."
+ code = HTTPStatus.NOT_FOUND
+
+
class InstalledAppHTTPError(BaseHTTPException):
"""A Console error with safe details and a request ID for troubleshooting."""
diff --git a/api/controllers/console/explore/message.py b/api/controllers/console/explore/message.py
index 188b9a59409..c057d068183 100644
--- a/api/controllers/console/explore/message.py
+++ b/api/controllers/console/explore/message.py
@@ -10,9 +10,9 @@ from uuid import UUID
from flask import Response
from flask_restx import Resource
from pydantic import BaseModel
-from werkzeug.exceptions import HTTPException, InternalServerError, Unauthorized
from controllers.common.controller_schemas import MessageFeedbackPayload, MessageListQuery
+from controllers.common.errors import InternalServerError, UnauthorizedError
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
from controllers.console import console_ns
from controllers.console.app.error import (
@@ -42,6 +42,7 @@ from fields.conversation_fields import ResultResponse
from fields.message_fields import ExploreMessageInfiniteScrollPagination, SuggestedQuestionsResponse
from graphon.model_runtime.errors.invoke import InvokeError
from libs import helper
+from libs.exception import BaseHTTPException
from machinery.context import RequestContext
from services.account_errors import AccountNotFoundError
from services.app_definition_query_service import AppDefinitionUnavailableError
@@ -84,7 +85,7 @@ def _message_errors[**P, R](view: Callable[P, R]) -> Callable[P, R]:
except AppDefinitionUnavailableError as error:
raise AppUnavailableError() from error
except (AccountNotFoundError, SuggestedQuestionsActorNotFoundError) as error:
- raise Unauthorized("Account no longer exists.") from error
+ raise UnauthorizedError("Account no longer exists.") from error
except MessageNotChatAppError as error:
raise NotChatAppError() from error
except InstalledAppNotCompletionError as error:
@@ -109,7 +110,7 @@ def _message_errors[**P, R](view: Callable[P, R]) -> Callable[P, R]:
raise ProviderModelCurrentlyNotSupportError() from error
except InvokeError as error:
raise CompletionRequestError(error.description) from error
- except (HTTPException, ValueError):
+ except (BaseHTTPException, ValueError):
raise
except Exception as error:
logger.exception("Installed-app message operation failed")
diff --git a/api/controllers/console/explore/saved_message.py b/api/controllers/console/explore/saved_message.py
index ab40ed60690..826f698d46d 100644
--- a/api/controllers/console/explore/saved_message.py
+++ b/api/controllers/console/explore/saved_message.py
@@ -2,9 +2,9 @@ from http import HTTPStatus
from uuid import UUID
from flask_restx import Resource
-from werkzeug.exceptions import NotFound
from controllers.common.controller_schemas import SavedMessageCreatePayload, SavedMessageListQuery
+from controllers.common.errors import NotFoundError
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
from controllers.console import console_ns
from controllers.console.explore.error import NotCompletionAppError
@@ -72,7 +72,7 @@ class SavedMessageListApi(Resource):
message_id=str(req_data.message_id),
)
except MessageNotExistsError:
- raise NotFound("Message Not Exists.")
+ raise NotFoundError("Message Not Exists.")
return ResultResponse(result="success").model_dump(mode="json")
diff --git a/api/controllers/console/explore/trial.py b/api/controllers/console/explore/trial.py
index 6de344785cd..b504885ccba 100644
--- a/api/controllers/console/explore/trial.py
+++ b/api/controllers/console/explore/trial.py
@@ -10,11 +10,11 @@ from uuid import UUID
from flask import Response, request
from flask_restx import Resource
from pydantic import AliasChoices, BaseModel, Field, field_validator
-from werkzeug.exceptions import HTTPException, InternalServerError, NotFound, Unauthorized
import services
from configs import dify_config
from controllers.common.audio_response import audio_binary_response
+from controllers.common.errors import InternalServerError, NotFoundError, UnauthorizedError
from controllers.common.fields import (
AudioBinaryResponse,
AudioTranscriptResponse,
@@ -46,17 +46,18 @@ from controllers.console.app.error import (
)
from controllers.console.app.preview_admission import get_preview_app
from controllers.console.explore.error import (
- AppPreviewOwnerUnavailableError as AppPreviewOwnerUnavailableHttpError,
-)
-from controllers.console.explore.error import (
- AppPreviewSiteUnavailableError as AppPreviewSiteUnavailableHttpError,
-)
-from controllers.console.explore.error import (
+ AgentVersionNotFoundHTTPError,
AppSuggestedQuestionsAfterAnswerDisabledError,
NotChatAppError,
NotCompletionAppError,
NotWorkflowAppError,
)
+from controllers.console.explore.error import (
+ AppPreviewOwnerUnavailableError as AppPreviewOwnerUnavailableHttpError,
+)
+from controllers.console.explore.error import (
+ AppPreviewSiteUnavailableError as AppPreviewSiteUnavailableHttpError,
+)
from controllers.console.explore.trial_app_admission import get_trial_app, get_trial_app_for_stop
from controllers.console.files import FILE_UPLOAD_PARAMS, upload_file_from_request_context
from controllers.console.flask_admission import console_account_admission
@@ -82,6 +83,7 @@ from fields.message_fields import SuggestedQuestionsResponse
from graphon.model_runtime.errors.invoke import InvokeError
from graphon.variables import SecretVariable, VariableBase
from libs import helper
+from libs.exception import BaseHTTPException
from libs.helper import dump_response, to_timestamp, uuid_value
from libs.stream import close_stream
from libs.url_utils import normalize_api_base_url
@@ -89,6 +91,7 @@ from machinery.context import RequestContext
from models.enums import CreatorUserRole
from models.model import AppMode
from services.account_errors import AccountNotFoundError
+from services.agent.errors import AgentVersionNotFoundError
from services.app_definition_query_service import AppDefinitionUnavailableError
from services.app_preview_query_service import (
AppPreviewOwnerUnavailableError,
@@ -531,7 +534,7 @@ class TrialAppWorkflowRunApi(Resource):
except AppDefinitionUnavailableError as error:
raise AppUnavailableError() from error
except AccountNotFoundError as error:
- raise Unauthorized("Account no longer exists.") from error
+ raise UnauthorizedError("Account no longer exists.") from error
except services.errors.app_model_config.AppModelConfigBrokenError as error:
raise AppUnavailableError() from error
except ProviderTokenNotInitError as ex:
@@ -600,9 +603,9 @@ class TrialChatApi(Resource):
except AppDefinitionUnavailableError as error:
raise AppUnavailableError() from error
except AccountNotFoundError as error:
- raise Unauthorized("Account no longer exists.") from error
+ raise UnauthorizedError("Account no longer exists.") from error
except services.errors.conversation.ConversationNotExistsError:
- raise NotFound("Conversation Not Exists.")
+ raise NotFoundError("Conversation Not Exists.")
except services.errors.conversation.ConversationCompletedError:
raise ConversationCompletedError()
except services.errors.app_model_config.AppModelConfigBrokenError:
@@ -671,11 +674,11 @@ class TrialMessageSuggestedQuestionApi(Resource):
except AppDefinitionUnavailableError as error:
raise AppUnavailableError() from error
except SuggestedQuestionsActorNotFoundError as error:
- raise Unauthorized("Account no longer exists.") from error
+ raise UnauthorizedError("Account no longer exists.") from error
except MessageNotExistsError:
- raise NotFound("Message not found")
+ raise NotFoundError("Message not found")
except ConversationNotExistsError:
- raise NotFound("Conversation not found")
+ raise NotFoundError("Conversation not found")
except SuggestedQuestionsAfterAnswerDisabledError:
raise AppSuggestedQuestionsAfterAnswerDisabledError()
except ProviderTokenNotInitError as ex:
@@ -718,7 +721,9 @@ def _trial_audio_errors[**P, R](view: Callable[P, R]) -> Callable[P, R]:
raise ProviderModelCurrentlyNotSupportError() from error
except InvokeError as error:
raise CompletionRequestError(error.description) from error
- except (HTTPException, ValueError):
+ except AgentVersionNotFoundError as error:
+ raise AgentVersionNotFoundHTTPError() from error
+ except (BaseHTTPException, ValueError):
raise
except Exception as error:
logger.exception("Trial audio operation failed")
@@ -735,10 +740,17 @@ class TrialChatAudioApi(Resource):
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[AudioTranscriptResponse.__name__])
@console_account_admission()
@get_trial_app
- @_trial_audio_errors
def post(self, request_context: RequestContext, trial_app: TrialAppRef) -> dict[str, object]:
+ # Let Flask handle multipart parsing errors before mapping audio operation failures.
file = request.files.get("file")
audio = AudioUpload(stream=file.stream, mime_type=file.mimetype) if file is not None else None
+ return self._transcript_asr(request_context=request_context, trial_app=trial_app, audio=audio)
+
+ @_trial_audio_errors
+ def _transcript_asr(
+ self, *, request_context: RequestContext, trial_app: TrialAppRef, audio: AudioUpload | None
+ ) -> dict[str, object]:
+ """Transcribe an upload; None lets the audio service report a missing file."""
transcript = application_services().app_audio.transcript_asr(
app=AudioAppRef(app_id=trial_app.app_id, tenant_id=trial_app.tenant_id, app_mode=trial_app.app_mode),
audio=audio,
@@ -807,9 +819,9 @@ class TrialCompletionApi(Resource):
except AppDefinitionUnavailableError as error:
raise AppUnavailableError() from error
except AccountNotFoundError as error:
- raise Unauthorized("Account no longer exists.") from error
+ raise UnauthorizedError("Account no longer exists.") from error
except services.errors.conversation.ConversationNotExistsError:
- raise NotFound("Conversation Not Exists.")
+ raise NotFoundError("Conversation Not Exists.")
except services.errors.conversation.ConversationCompletedError:
raise ConversationCompletedError()
except services.errors.app_model_config.AppModelConfigBrokenError:
@@ -890,7 +902,7 @@ class AppApi(Resource):
except AppDefinitionUnavailableError as error:
raise AppUnavailableError() from error
except AccountNotFoundError as error:
- raise Unauthorized("Account no longer exists.") from error
+ raise UnauthorizedError("Account no longer exists.") from error
except AppPreviewSiteUnavailableError as error:
raise AppPreviewSiteUnavailableHttpError(str(error)) from error
diff --git a/api/controllers/console/explore/workflow.py b/api/controllers/console/explore/workflow.py
index c59b31a5e6b..9eaea5c4d35 100644
--- a/api/controllers/console/explore/workflow.py
+++ b/api/controllers/console/explore/workflow.py
@@ -3,9 +3,9 @@ from http import HTTPStatus
from flask import Response
from flask_restx import Resource
-from werkzeug.exceptions import InternalServerError, Unauthorized
from controllers.common.controller_schemas import WorkflowRunPayload
+from controllers.common.errors import InternalServerError, UnauthorizedError
from controllers.common.fields import SimpleResultResponse
from controllers.common.schema import register_response_schema_models, register_schema_model
from controllers.console.app.error import (
@@ -70,7 +70,7 @@ class InstalledAppWorkflowRunApi(Resource):
except (AppDefinitionUnavailableError, InstalledAppNotWorkflowError):
raise NotWorkflowAppError() from None
except AccountNotFoundError:
- raise Unauthorized("Account no longer exists.") from None
+ raise UnauthorizedError("Account no longer exists.") from None
except ProviderTokenNotInitError as ex:
raise ProviderNotInitializeError(ex.description)
except QuotaExceededError:
diff --git a/api/tests/unit_tests/controllers/console/explore/test_audio.py b/api/tests/unit_tests/controllers/console/explore/test_audio.py
index bfcb8fef45d..49295cf2d40 100644
--- a/api/tests/unit_tests/controllers/console/explore/test_audio.py
+++ b/api/tests/unit_tests/controllers/console/explore/test_audio.py
@@ -10,13 +10,16 @@ import pytest
from flask import has_request_context, request
from sqlalchemy import inspect, select
from sqlalchemy.orm import Session, sessionmaker
+from werkzeug.exceptions import Forbidden
from werkzeug.test import TestResponse
import controllers.console.explore.audio as module
+from controllers.common.errors import UnauthorizedError
from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError
from graphon.model_runtime.errors.invoke import InvokeError
from models import AccountTrialAppRecord, App, AppMode, AppModelConfig, InstalledApp
from services import audio_provider_gateway
+from services.agent.errors import AgentVersionNotFoundError
from services.app_audio_adapters import AppAudioRuntime
from services.app_audio_service import AppAudio
from services.app_definition_query_service import AppDefinitionUnavailableError
@@ -170,6 +173,14 @@ def test_missing_upload_reaches_runtime_and_returns_specific_error(runtime: _Run
assert runtime.asr_calls[0][1:] == (None, None)
+def test_asr_request_size_limit_preserves_413(runtime: _Runtime) -> None:
+ runtime.harness.app.config["MAX_CONTENT_LENGTH"] = 1
+
+ _error(runtime.request("audio-to-text"), status=413, code="request_entity_too_large")
+
+ assert runtime.asr_calls == []
+
+
@pytest.mark.parametrize(
("body", "expected"),
[
@@ -411,6 +422,15 @@ def test_audio_endpoints_apply_admission_before_reading_or_generating_audio(
(ModelCurrentlyNotSupportError(), 400, "model_currently_not_support", None),
(InvokeError("Provider rejected audio"), 400, "completion_request_error", "Provider rejected audio"),
(ValueError("Invalid audio arguments"), 400, "invalid_param", "Invalid audio arguments"),
+ (UnauthorizedError("Session expired"), 401, "unauthorized", "Session expired"),
+ (AgentVersionNotFoundError(), 404, "agent_version_not_found_error", "Agent config version not found."),
+ (
+ Forbidden("Private provider details"),
+ 500,
+ "internal_server_error",
+ "The server encountered an internal error and was unable to complete your request. "
+ "Either the server is overloaded or there is an error in the application.",
+ ),
(RuntimeError("Unexpected provider failure"), 500, "internal_server_error", None),
],
)
@@ -418,7 +438,10 @@ def test_audio_and_provider_failures_keep_precise_http_contract(
runtime: _Runtime, operation: _Operation, failure: Exception, status: int, code: str, description: str | None
) -> None:
runtime.error = failure
- _error(runtime.request(operation), status=status, code=code, message=description)
+ response = runtime.request(operation)
+ _error(response, status=status, code=code, message=description)
+ if status == 401:
+ assert response.headers["WWW-Authenticate"] == 'Bearer realm="api"'
assert len(runtime.asr_calls) + len(runtime.tts_calls) == 1
diff --git a/api/tests/unit_tests/controllers/console/explore/test_message.py b/api/tests/unit_tests/controllers/console/explore/test_message.py
index 84b40deb097..6e386bafb34 100644
--- a/api/tests/unit_tests/controllers/console/explore/test_message.py
+++ b/api/tests/unit_tests/controllers/console/explore/test_message.py
@@ -12,6 +12,7 @@ import pytest
from pydantic import JsonValue
from sqlalchemy import Connection, Engine, event, select, update
from sqlalchemy.orm import Session, SessionTransaction, sessionmaker
+from werkzeug.exceptions import Forbidden
from werkzeug.test import TestResponse
import controllers.console.explore.message as module
@@ -795,6 +796,13 @@ def test_suggested_questions_uses_admitted_installation_until_next_request(real_
(QuotaExceededError(), 400, "provider_quota_exceeded", None),
(ModelCurrentlyNotSupportError(), 400, "model_currently_not_support", None),
(InvokeError("Provider rejected input"), 400, "completion_request_error", "Provider rejected input"),
+ (
+ Forbidden("Private provider details"),
+ 500,
+ "internal_server_error",
+ "The server encountered an internal error and was unable to complete your request. "
+ "Either the server is overloaded or there is an error in the application.",
+ ),
(RuntimeError("Unexpected failure"), 500, "internal_server_error", None),
],
)
diff --git a/api/tests/unit_tests/controllers/console/explore/test_saved_message.py b/api/tests/unit_tests/controllers/console/explore/test_saved_message.py
index 9cce8c23fac..4f971feb178 100644
--- a/api/tests/unit_tests/controllers/console/explore/test_saved_message.py
+++ b/api/tests/unit_tests/controllers/console/explore/test_saved_message.py
@@ -7,9 +7,9 @@ from uuid import uuid4
import pytest
from flask import Flask
-from werkzeug.exceptions import NotFound
import controllers.console.explore.saved_message as module
+from controllers.common.errors import NotFoundError
from controllers.console.explore.error import NotCompletionAppError
from graphon.file import File, FileTransferMethod, FileType
from libs.external_api import ExternalApi
@@ -284,13 +284,14 @@ class TestSavedMessageListApi:
def test_post_maps_missing_message_to_not_found(self, services: _ApplicationServiceMocks) -> None:
services.saved_messages.save.side_effect = MessageNotExistsError()
- with pytest.raises(NotFound, match="Message Not Exists"):
+ with pytest.raises(NotFoundError, match="Message Not Exists") as raised:
unwrap(module.SavedMessageListApi().post)(
module.SavedMessageListApi(),
module.SavedMessageCreatePayload.model_validate({"message_id": str(uuid4())}),
_REQUEST_CONTEXT,
_installed_app(),
)
+ assert raised.value.data == {"code": "not_found", "message": "Message Not Exists.", "status": 404}
class TestSavedMessageApi:
diff --git a/api/tests/unit_tests/controllers/console/explore/test_trial_audio.py b/api/tests/unit_tests/controllers/console/explore/test_trial_audio.py
index 319b5c50870..d688df956f0 100644
--- a/api/tests/unit_tests/controllers/console/explore/test_trial_audio.py
+++ b/api/tests/unit_tests/controllers/console/explore/test_trial_audio.py
@@ -10,13 +10,14 @@ import pytest
from flask import Flask, Request
from sqlalchemy import Connection, event, select
from sqlalchemy.orm import Mapper, Session, SessionTransaction, sessionmaker
-from werkzeug.exceptions import Unauthorized
+from werkzeug.exceptions import Forbidden, Unauthorized
from werkzeug.test import TestResponse
import controllers.console.explore.trial as trial_module
import controllers.console.explore.trial_app_admission as admission_module
import controllers.console.wraps as console_wraps
import libs.login as login_module
+from controllers.common.errors import UnauthorizedError
from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError
from enums import DeploymentEdition
from extensions.ext_login import DifyLoginManager, unauthorized_handler
@@ -25,6 +26,7 @@ from libs.external_api import ExternalApi
from models import Account, AccountTrialAppRecord, App, AppMode, Tenant, TrialApp
from models.account import AccountStatus
from repositories.trial_app_repository import TrialAppRepository
+from services.agent.errors import AgentVersionNotFoundError
from services.app_definition_query_service import AppDefinitionUnavailableError
from services.audio_types import AudioAppRef, AudioOutput, AudioUpload
from services.errors.app_model_config import AppModelConfigBrokenError
@@ -298,6 +300,16 @@ def test_missing_upload_passes_none_and_does_not_record_usage(harness: _Harness)
assert harness.usage() is None
+def test_oversized_multipart_request_keeps_transport_error(harness: _Harness) -> None:
+ harness.app.config["MAX_CONTENT_LENGTH"] = 1
+
+ response = harness.post(_ASR)
+
+ _assert_error(response, 413, "request_entity_too_large")
+ assert harness.runtime.calls == []
+ assert harness.usage() is None
+
+
@pytest.mark.parametrize("endpoint", [_ASR, _TTS])
@pytest.mark.parametrize(
("error", "status", "code"),
@@ -314,8 +326,10 @@ def test_missing_upload_passes_none_and_does_not_record_usage(harness: _Harness)
(ModelCurrentlyNotSupportError(), 400, "model_currently_not_support"),
(InvokeError("provider rejected audio"), 400, "completion_request_error"),
(ValueError("Text is required"), 400, "invalid_param"),
- (Unauthorized("session expired"), 401, "unauthorized"),
+ (UnauthorizedError("session expired"), 401, "unauthorized"),
+ (AgentVersionNotFoundError(), 404, "agent_version_not_found_error"),
(RuntimeError("private provider failure"), 500, "internal_server_error"),
+ (Forbidden("private provider failure"), 500, "internal_server_error"),
],
)
def test_runtime_errors_keep_specific_codes_without_recording_usage(
@@ -329,6 +343,16 @@ def test_runtime_errors_keep_specific_codes_without_recording_usage(
assert body["message"] == error.description
elif code in {"audio_too_large", "invalid_param"}:
assert str(error) in str(body["message"])
+ elif status == 401:
+ assert body["message"] == "session expired"
+ assert response.headers["WWW-Authenticate"] == 'Bearer realm="api"'
+ elif status == 404:
+ assert body["message"] == "Agent config version not found."
+ elif status == 500:
+ assert body["message"] == (
+ "The server encountered an internal error and was unable to complete your request. "
+ "Either the server is overloaded or there is an error in the application."
+ )
assert harness.usage() is None