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.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(api): use project HTTP errors in Explore controllers (#43481)
非法操作63d2af7d276c
diff --git a/api/controllers/common/errors.py b/api/controllers/common/errors.pyindex 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 = 400diff --git a/api/controllers/console/explore/audio.py b/api/controllers/console/explore/audio.pyindex 171ff0f72e6..0bad46484b2 100644--- a/api/controllers/console/explore/audio.py+++ b/api/controllers/console/explore/audio.py@@ -7,10 +7,10 @@ from http import HTTPStatusfrom flask import Response, requestfrom flask_restx import Resource-from werkzeug.exceptions import HTTPException, InternalServerErrorfrom controllers.common.audio_response import audio_binary_responsefrom controllers.common.controller_schemas import TextToAudioPayload+from controllers.common.errors import InternalServerErrorfrom controllers.common.fields import AudioBinaryResponse, AudioTranscriptResponsefrom controllers.common.schema import register_response_schema_models, register_schema_modelfrom controllers.console import console_ns@@ -27,14 +27,17 @@ from controllers.console.app.error import (SpeechToTextDisabledError,UnsupportedAudioTypeError,)+from controllers.console.explore.error import AgentVersionNotFoundHTTPErrorfrom controllers.console.explore.installed_app_admission import get_installed_appfrom controllers.console.flask_admission import console_account_admissionfrom controllers.console.wraps import model_validatefrom core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededErrorfrom extensions.ext_application_services import application_servicesfrom graphon.model_runtime.errors.invoke import InvokeError+from libs.exception import BaseHTTPExceptionfrom libs.helper import dump_responsefrom machinery.context import RequestContext+from services.agent.errors import AgentVersionNotFoundErrorfrom services.app_definition_query_service import AppDefinitionUnavailableErrorfrom services.audio_types import AudioAppRef, AudioUploadfrom 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 errorexcept InvokeError as error:raise CompletionRequestError(error.description) from error- except (HTTPException, ValueError):+ except AgentVersionNotFoundError as error:+ raise AgentVersionNotFoundHTTPError() from error+ except (BaseHTTPException, ValueError):raiseexcept 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_errorsdef 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.pyindex 9e742140e9d..b6a469a0450 100644--- a/api/controllers/console/explore/completion.py+++ b/api/controllers/console/explore/completion.py@@ -6,9 +6,9 @@ from uuid import UUIDfrom flask import Responsefrom flask_restx import Resourcefrom pydantic import BaseModel, Field, field_validator-from werkzeug.exceptions import InternalServerError, NotFound, Unauthorizedimport services+from controllers.common.errors import InternalServerError, NotFoundError, UnauthorizedErrorfrom controllers.common.fields import SimpleResultResponsefrom controllers.common.schema import register_response_schema_models, register_schema_modelsfrom controllers.console.app.error import (@@ -112,11 +112,11 @@ class CompletionApi(Resource):except InstalledAppNotCompletionError:raise NotCompletionAppError() from Noneexcept InstalledAppNotFoundError:- raise NotFound("Installed app not found") from None+ raise NotFoundError("Installed app not found") from Noneexcept AccountNotFoundError:- raise Unauthorized("Account no longer exists.") from None+ raise UnauthorizedError("Account no longer exists.") from Noneexcept 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 Noneexcept InstalledAppNotFoundError:- raise NotFound("Installed app not found") from None+ raise NotFoundError("Installed app not found") from Noneexcept AccountNotFoundError:- raise Unauthorized("Account no longer exists.") from None+ raise UnauthorizedError("Account no longer exists.") from Noneexcept 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.pyindex 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_idfrom 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.pyindex 188b9a59409..c057d068183 100644--- a/api/controllers/console/explore/message.py+++ b/api/controllers/console/explore/message.py@@ -10,9 +10,9 @@ from uuid import UUIDfrom flask import Responsefrom flask_restx import Resourcefrom pydantic import BaseModel-from werkzeug.exceptions import HTTPException, InternalServerError, Unauthorizedfrom controllers.common.controller_schemas import MessageFeedbackPayload, MessageListQuery+from controllers.common.errors import InternalServerError, UnauthorizedErrorfrom controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_modelsfrom controllers.console import console_nsfrom controllers.console.app.error import (@@ -42,6 +42,7 @@ from fields.conversation_fields import ResultResponsefrom fields.message_fields import ExploreMessageInfiniteScrollPagination, SuggestedQuestionsResponsefrom graphon.model_runtime.errors.invoke import InvokeErrorfrom libs import helper+from libs.exception import BaseHTTPExceptionfrom machinery.context import RequestContextfrom services.account_errors import AccountNotFoundErrorfrom 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 errorexcept (AccountNotFoundError, SuggestedQuestionsActorNotFoundError) as error:- raise Unauthorized("Account no longer exists.") from error+ raise UnauthorizedError("Account no longer exists.") from errorexcept MessageNotChatAppError as error:raise NotChatAppError() from errorexcept InstalledAppNotCompletionError as error:@@ -109,7 +110,7 @@ def _message_errors[**P, R](view: Callable[P, R]) -> Callable[P, R]:raise ProviderModelCurrentlyNotSupportError() from errorexcept InvokeError as error:raise CompletionRequestError(error.description) from error- except (HTTPException, ValueError):+ except (BaseHTTPException, ValueError):raiseexcept 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.pyindex 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 HTTPStatusfrom uuid import UUIDfrom flask_restx import Resource-from werkzeug.exceptions import NotFoundfrom controllers.common.controller_schemas import SavedMessageCreatePayload, SavedMessageListQuery+from controllers.common.errors import NotFoundErrorfrom controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_modelsfrom controllers.console import console_nsfrom 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.pyindex 6de344785cd..b504885ccba 100644--- a/api/controllers/console/explore/trial.py+++ b/api/controllers/console/explore/trial.py@@ -10,11 +10,11 @@ from uuid import UUIDfrom flask import Response, requestfrom flask_restx import Resourcefrom pydantic import AliasChoices, BaseModel, Field, field_validator-from werkzeug.exceptions import HTTPException, InternalServerError, NotFound, Unauthorizedimport servicesfrom configs import dify_configfrom controllers.common.audio_response import audio_binary_response+from controllers.common.errors import InternalServerError, NotFoundError, UnauthorizedErrorfrom 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_appfrom 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_stopfrom controllers.console.files import FILE_UPLOAD_PARAMS, upload_file_from_request_contextfrom controllers.console.flask_admission import console_account_admission@@ -82,6 +83,7 @@ from fields.message_fields import SuggestedQuestionsResponsefrom graphon.model_runtime.errors.invoke import InvokeErrorfrom graphon.variables import SecretVariable, VariableBasefrom libs import helper+from libs.exception import BaseHTTPExceptionfrom libs.helper import dump_response, to_timestamp, uuid_valuefrom libs.stream import close_streamfrom libs.url_utils import normalize_api_base_url@@ -89,6 +91,7 @@ from machinery.context import RequestContextfrom models.enums import CreatorUserRolefrom models.model import AppModefrom services.account_errors import AccountNotFoundError+from services.agent.errors import AgentVersionNotFoundErrorfrom services.app_definition_query_service import AppDefinitionUnavailableErrorfrom services.app_preview_query_service import (AppPreviewOwnerUnavailableError,@@ -531,7 +534,7 @@ class TrialAppWorkflowRunApi(Resource):except AppDefinitionUnavailableError as error:raise AppUnavailableError() from errorexcept AccountNotFoundError as error:- raise Unauthorized("Account no longer exists.") from error+ raise UnauthorizedError("Account no longer exists.") from errorexcept services.errors.app_model_config.AppModelConfigBrokenError as error:raise AppUnavailableError() from errorexcept ProviderTokenNotInitError as ex:@@ -600,9 +603,9 @@ class TrialChatApi(Resource):except AppDefinitionUnavailableError as error:raise AppUnavailableError() from errorexcept AccountNotFoundError as error:- raise Unauthorized("Account no longer exists.") from error+ raise UnauthorizedError("Account no longer exists.") from errorexcept 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 errorexcept SuggestedQuestionsActorNotFoundError as error:- raise Unauthorized("Account no longer exists.") from error+ raise UnauthorizedError("Account no longer exists.") from errorexcept 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 errorexcept InvokeError as error:raise CompletionRequestError(error.description) from error- except (HTTPException, ValueError):+ except AgentVersionNotFoundError as error:+ raise AgentVersionNotFoundHTTPError() from error+ except (BaseHTTPException, ValueError):raiseexcept 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_errorsdef 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 errorexcept AccountNotFoundError as error:- raise Unauthorized("Account no longer exists.") from error+ raise UnauthorizedError("Account no longer exists.") from errorexcept 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 errorexcept AccountNotFoundError as error:- raise Unauthorized("Account no longer exists.") from error+ raise UnauthorizedError("Account no longer exists.") from errorexcept AppPreviewSiteUnavailableError as error:raise AppPreviewSiteUnavailableHttpError(str(error)) from errordiff --git a/api/controllers/console/explore/workflow.py b/api/controllers/console/explore/workflow.pyindex c59b31a5e6b..9eaea5c4d35 100644--- a/api/controllers/console/explore/workflow.py+++ b/api/controllers/console/explore/workflow.py@@ -3,9 +3,9 @@ from http import HTTPStatusfrom flask import Responsefrom flask_restx import Resource-from werkzeug.exceptions import InternalServerError, Unauthorizedfrom controllers.common.controller_schemas import WorkflowRunPayload+from controllers.common.errors import InternalServerError, UnauthorizedErrorfrom controllers.common.fields import SimpleResultResponsefrom controllers.common.schema import register_response_schema_models, register_schema_modelfrom controllers.console.app.error import (@@ -70,7 +70,7 @@ class InstalledAppWorkflowRunApi(Resource):except (AppDefinitionUnavailableError, InstalledAppNotWorkflowError):raise NotWorkflowAppError() from Noneexcept AccountNotFoundError:- raise Unauthorized("Account no longer exists.") from None+ raise UnauthorizedError("Account no longer exists.") from Noneexcept 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.pyindex 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 pytestfrom flask import has_request_context, requestfrom sqlalchemy import inspect, selectfrom sqlalchemy.orm import Session, sessionmaker+from werkzeug.exceptions import Forbiddenfrom werkzeug.test import TestResponseimport controllers.console.explore.audio as module+from controllers.common.errors import UnauthorizedErrorfrom core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededErrorfrom graphon.model_runtime.errors.invoke import InvokeErrorfrom models import AccountTrialAppRecord, App, AppMode, AppModelConfig, InstalledAppfrom services import audio_provider_gateway+from services.agent.errors import AgentVersionNotFoundErrorfrom services.app_audio_adapters import AppAudioRuntimefrom services.app_audio_service import AppAudiofrom services.app_definition_query_service import AppDefinitionUnavailableError@@ -170,6 +173,14 @@ def test_missing_upload_reaches_runtime_and_returns_specific_error(runtime: _Runassert 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) == 1diff --git a/api/tests/unit_tests/controllers/console/explore/test_message.py b/api/tests/unit_tests/controllers/console/explore/test_message.pyindex 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 pytestfrom pydantic import JsonValuefrom sqlalchemy import Connection, Engine, event, select, updatefrom sqlalchemy.orm import Session, SessionTransaction, sessionmaker+from werkzeug.exceptions import Forbiddenfrom werkzeug.test import TestResponseimport 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.pyindex 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 uuid4import pytestfrom flask import Flask-from werkzeug.exceptions import NotFoundimport controllers.console.explore.saved_message as module+from controllers.common.errors import NotFoundErrorfrom controllers.console.explore.error import NotCompletionAppErrorfrom graphon.file import File, FileTransferMethod, FileTypefrom 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.pyindex 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 pytestfrom flask import Flask, Requestfrom sqlalchemy import Connection, event, selectfrom sqlalchemy.orm import Mapper, Session, SessionTransaction, sessionmaker-from werkzeug.exceptions import Unauthorized+from werkzeug.exceptions import Forbidden, Unauthorizedfrom werkzeug.test import TestResponseimport controllers.console.explore.trial as trial_moduleimport controllers.console.explore.trial_app_admission as admission_moduleimport controllers.console.wraps as console_wrapsimport libs.login as login_module+from controllers.common.errors import UnauthorizedErrorfrom core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededErrorfrom enums import DeploymentEditionfrom extensions.ext_login import DifyLoginManager, unauthorized_handler@@ -25,6 +26,7 @@ from libs.external_api import ExternalApifrom models import Account, AccountTrialAppRecord, App, AppMode, Tenant, TrialAppfrom models.account import AccountStatusfrom repositories.trial_app_repository import TrialAppRepository+from services.agent.errors import AgentVersionNotFoundErrorfrom services.app_definition_query_service import AppDefinitionUnavailableErrorfrom services.audio_types import AudioAppRef, AudioOutput, AudioUploadfrom 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.descriptionelif 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