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): migrate installed app audio to shared runtime (#42056)
非法操作bd08f6b0e318
diff --git a/api/controllers/console/app/error.py b/api/controllers/console/app/error.pyindex 97a0cbedbef..c2808f149a5 100644--- a/api/controllers/console/app/error.py+++ b/api/controllers/console/app/error.py@@ -89,6 +89,12 @@ class ProviderNotSupportSpeechToTextError(BaseHTTPException):code = 400+class ProviderNotSupportTextToSpeechError(BaseHTTPException):+ error_code = "provider_not_support_text_to_speech"+ description = "Provider does not support text to speech."+ code = 400++class SpeechToTextDisabledError(BaseHTTPException):error_code = "speech_to_text_disabled"description = "Speech to text is disabled."diff --git a/api/controllers/console/explore/audio.py b/api/controllers/console/explore/audio.pyindex e50fe8b16d3..5c30ac9de4d 100644--- a/api/controllers/console/explore/audio.py+++ b/api/controllers/console/explore/audio.py@@ -1,12 +1,18 @@+"""Installed-app audio admission, error translation, and response serialization."""+import logging+from collections.abc import Callable+from functools import wraps-from flask import request-from werkzeug.exceptions import InternalServerError+from flask import Response, request+from flask_restx import Resource+from werkzeug.exceptions import HTTPException, InternalServerError-import services+from controllers.common.audio_response import audio_binary_responsefrom controllers.common.controller_schemas import TextToAudioPayloadfrom controllers.common.fields import AudioBinaryResponse, AudioTranscriptResponsefrom controllers.common.schema import register_response_schema_models, register_schema_model+from controllers.console import console_nsfrom controllers.console.app.error import (AppUnavailableError,AudioTooLargeError,@@ -15,28 +21,31 @@ from controllers.console.app.error import (ProviderModelCurrentlyNotSupportError,ProviderNotInitializeError,ProviderNotSupportSpeechToTextError,+ ProviderNotSupportTextToSpeechError,ProviderQuotaExceededError,SpeechToTextDisabledError,UnsupportedAudioTypeError,)-from controllers.console.explore.wraps import InstalledAppResource+from controllers.console.explore.installed_app_admission import get_installed_app+from controllers.console.flask_admission import console_account_admissionfrom controllers.console.wraps import model_validatefrom core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError-from extensions.ext_database import db+from extensions.ext_application_services import application_servicesfrom graphon.model_runtime.errors.invoke import InvokeError-from libs.login import current_account_with_tenant-from models.model import InstalledApp-from services.app_ref_service import AppRefService-from services.audio_service import AudioService+from libs.helper import dump_response+from machinery.context import RequestContext+from services.app_definition_query_service import AppDefinitionUnavailableError+from services.audio_types import AudioAppRef, AudioUpload+from services.errors.app_model_config import AppModelConfigBrokenErrorfrom services.errors.audio import (AudioTooLargeServiceError,NoAudioUploadedServiceError,ProviderNotSupportSpeechToTextServiceError,+ ProviderNotSupportTextToSpeechServiceError,SpeechToTextDisabledServiceError,UnsupportedAudioTypeServiceError,)--from .. import console_ns+from services.installed_app_access_service import InstalledAppReflogger = logging.getLogger(__name__)@@ -44,111 +53,92 @@ register_schema_model(console_ns, TextToAudioPayload)register_response_schema_models(console_ns, AudioBinaryResponse, AudioTranscriptResponse)+def _audio_errors[**P, R](view: Callable[P, R]) -> Callable[P, R]:+ @wraps(view)+ def decorated(*args: P.args, **kwargs: P.kwargs) -> R:+ try:+ return view(*args, **kwargs)+ except AppDefinitionUnavailableError as error:+ raise AppUnavailableError() from error+ except AppModelConfigBrokenError as error:+ logger.exception("App model config broken")+ raise AppUnavailableError() from error+ except NoAudioUploadedServiceError as error:+ raise NoAudioUploadedError() from error+ except AudioTooLargeServiceError as error:+ raise AudioTooLargeError(str(error)) from error+ except UnsupportedAudioTypeServiceError as error:+ raise UnsupportedAudioTypeError() from error+ except ProviderNotSupportSpeechToTextServiceError as error:+ raise ProviderNotSupportSpeechToTextError() from error+ except ProviderNotSupportTextToSpeechServiceError as error:+ raise ProviderNotSupportTextToSpeechError() from error+ except SpeechToTextDisabledServiceError as error:+ raise SpeechToTextDisabledError() from error+ except ProviderTokenNotInitError as error:+ raise ProviderNotInitializeError(error.description) from error+ except QuotaExceededError as error:+ raise ProviderQuotaExceededError() from error+ except ModelCurrentlyNotSupportError as error:+ raise ProviderModelCurrentlyNotSupportError() from error+ except InvokeError as error:+ raise CompletionRequestError(error.description) from error+ except (HTTPException, ValueError):+ raise+ except Exception as error:+ logger.exception("Installed-app audio operation failed")+ raise InternalServerError() from error++ return decorated++@console_ns.route("/installed-apps/<uuid:installed_app_id>/audio-to-text",endpoint="installed_app_audio",)-class ChatAudioApi(InstalledAppResource):+class ChatAudioApi(Resource):@console_ns.response(200, "Success", console_ns.models[AudioTranscriptResponse.__name__])- def post(self, installed_app: InstalledApp):- app_model = installed_app.app_with_session(session=db.session())- if app_model is None:- raise AppUnavailableError()-- file = request.files["file"]-- try:- response = AudioService.transcript_asr(- app_model=app_model,- file=file,- session=db.session(),- end_user=None,- )-- return response- except services.errors.app_model_config.AppModelConfigBrokenError:- logger.exception("App model config broken.")- raise AppUnavailableError()- except NoAudioUploadedServiceError:- raise NoAudioUploadedError()- except AudioTooLargeServiceError as e:- raise AudioTooLargeError(str(e))- except UnsupportedAudioTypeServiceError:- raise UnsupportedAudioTypeError()- except ProviderNotSupportSpeechToTextServiceError:- raise ProviderNotSupportSpeechToTextError()- except SpeechToTextDisabledServiceError:- raise SpeechToTextDisabledError()- except ProviderTokenNotInitError as ex:- raise ProviderNotInitializeError(ex.description)- except QuotaExceededError:- raise ProviderQuotaExceededError()- except ModelCurrentlyNotSupportError:- raise ProviderModelCurrentlyNotSupportError()- except InvokeError as e:- raise CompletionRequestError(e.description)- except ValueError as e:- raise e- except Exception as e:- logger.exception("internal server error.")- raise InternalServerError()+ @console_account_admission()+ @get_installed_app+ @_audio_errors+ def post(self, request_context: RequestContext, installed_app: InstalledAppRef) -> dict[str, object]:+ file = request.files.get("file")+ audio = AudioUpload(stream=file.stream, mime_type=file.mimetype) if file is not None else None+ transcript = application_services().app_audio.transcript_asr(+ app=AudioAppRef(+ app_id=installed_app.app_id,+ tenant_id=installed_app.app_owner_tenant_id,+ app_mode=installed_app.app_mode,+ ),+ audio=audio,+ )+ return dump_response(AudioTranscriptResponse, transcript)@console_ns.route("/installed-apps/<uuid:installed_app_id>/text-to-audio",endpoint="installed_app_text",)-class ChatTextApi(InstalledAppResource):+class ChatTextApi(Resource):@console_ns.expect(console_ns.models[TextToAudioPayload.__name__])@console_ns.response(200, "Success", console_ns.models[AudioBinaryResponse.__name__])+ @console_account_admission()+ @get_installed_app@model_validate(TextToAudioPayload)- def post(self, req_data: TextToAudioPayload, installed_app: InstalledApp):- app_model = installed_app.app_with_session(session=db.session())- if app_model is None:- raise AppUnavailableError()- try:- message_id = req_data.message_id- text = req_data.text- voice = req_data.voice- message_ref = None- if message_id:- current_user, _ = current_account_with_tenant()- app_ref = AppRefService.create_app_ref(app_model)- message_ref = AppRefService.create_message_ref(- app_ref,- message_id,- account_id=current_user.id,- )-- response = AudioService.transcript_tts(- app_model=app_model,- session=db.session(),- text=text,- voice=voice,- message_ref=message_ref,- )- return response- except services.errors.app_model_config.AppModelConfigBrokenError:- logger.exception("App model config broken.")- raise AppUnavailableError()- except NoAudioUploadedServiceError:- raise NoAudioUploadedError()- except AudioTooLargeServiceError as e:- raise AudioTooLargeError(str(e))- except UnsupportedAudioTypeServiceError:- raise UnsupportedAudioTypeError()- except ProviderNotSupportSpeechToTextServiceError:- raise ProviderNotSupportSpeechToTextError()- except ProviderTokenNotInitError as ex:- raise ProviderNotInitializeError(ex.description)- except QuotaExceededError:- raise ProviderQuotaExceededError()- except ModelCurrentlyNotSupportError:- raise ProviderModelCurrentlyNotSupportError()- except InvokeError as e:- raise CompletionRequestError(e.description)- except ValueError as e:- raise e- except Exception as e:- logger.exception("internal server error.")- raise InternalServerError()+ @_audio_errors+ def post(+ self, payload: TextToAudioPayload, request_context: RequestContext, installed_app: InstalledAppRef+ ) -> Response | None:+ output = application_services().app_audio.transcript_tts(+ app=AudioAppRef(+ app_id=installed_app.app_id,+ tenant_id=installed_app.app_owner_tenant_id,+ app_mode=installed_app.app_mode,+ ),+ account_id=request_context.account_id,+ text=payload.text,+ voice=payload.voice,+ message_id=payload.message_id,+ )+ # response-contract:ignore audio_binary_response+ return audio_binary_response(output)diff --git a/api/controllers/console/explore/wraps.py b/api/controllers/console/explore/wraps.pydeleted file mode 100644index f10cb000c53..00000000000--- a/api/controllers/console/explore/wraps.py+++ /dev/null@@ -1,78 +0,0 @@-from collections.abc import Callable-from functools import wraps-from typing import Concatenate--from flask_restx import Resource-from sqlalchemy import select-from werkzeug.exceptions import NotFound--from controllers.console.explore.error import AppAccessDeniedError-from controllers.console.wraps import account_initialization_required-from extensions.ext_database import db-from libs.login import current_account_with_tenant, login_required-from models import InstalledApp-from services.enterprise.enterprise_service import EnterpriseService-from services.system_feature_service import SystemFeatureService---def installed_app_required[**P, R](view: Callable[Concatenate[InstalledApp, P], R] | None = None):- def decorator(view: Callable[Concatenate[InstalledApp, P], R]):- @wraps(view)- def decorated(installed_app_id: str, *args: P.args, **kwargs: P.kwargs):- _, current_tenant_id = current_account_with_tenant()- installed_app = db.session.scalar(- select(InstalledApp)- .where(InstalledApp.id == str(installed_app_id), InstalledApp.tenant_id == current_tenant_id)- .limit(1)- )-- if installed_app is None:- raise NotFound("Installed app not found")-- if not installed_app.app_with_session(session=db.session()):- db.session.delete(installed_app)- db.session.commit()-- raise NotFound("Installed app not found")-- return view(installed_app, *args, **kwargs)-- return decorated-- if view:- return decorator(view)- return decorator---def user_allowed_to_access_app[**P, R](view: Callable[Concatenate[InstalledApp, P], R] | None = None):- def decorator(view: Callable[Concatenate[InstalledApp, P], R]):- @wraps(view)- def decorated(installed_app: InstalledApp, *args: P.args, **kwargs: P.kwargs):- current_user, _ = current_account_with_tenant()- if SystemFeatureService.is_webapp_auth_enabled():- app_id = installed_app.app_id- res = EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp(- user_id=str(current_user.id),- app_id=app_id,- )- if not res:- raise AppAccessDeniedError()-- return view(installed_app, *args, **kwargs)-- return decorated-- if view:- return decorator(view)- return decorator---class InstalledAppResource(Resource):- # must be reversed if there are multiple decorators-- method_decorators = [- user_allowed_to_access_app,- installed_app_required,- account_initialization_required,- login_required,- ]diff --git a/api/repositories/installed_app_repository.py b/api/repositories/installed_app_repository.pyindex da345827be2..c5dcb086fd2 100644--- a/api/repositories/installed_app_repository.py+++ b/api/repositories/installed_app_repository.py@@ -104,14 +104,20 @@ class SQLAlchemyInstalledAppRepository(InstalledAppAccessStore, InstalledAppUsag# An installed public app can belong to another workspace. Admission# preserves the existence check; publication policy belongs to its callers.- app = session.execute(select(App.id, App.mode).where(App.id == installed_app.app_id).limit(1)).first()+ app = session.execute(+ select(App.id, App.tenant_id, App.mode).where(App.id == installed_app.app_id).limit(1)+ ).first()if app is None:session.delete(installed_app)session.commit()return Nonereturn InstalledAppRef(- id=installed_app.id, app_id=app.id, tenant_id=installed_app.tenant_id, app_mode=app.mode.value+ id=installed_app.id,+ app_id=app.id,+ tenant_id=installed_app.tenant_id,+ app_owner_tenant_id=app.tenant_id,+ app_mode=app.mode.value,)@overridediff --git a/api/services/app_audio_service.py b/api/services/app_audio_service.pyindex 7757fef6120..541e3c91b51 100644--- a/api/services/app_audio_service.py+++ b/api/services/app_audio_service.py@@ -16,4 +16,17 @@ class AppAudio(Protocol):text: str | None,voice: str | None,message_id: str | None,- ) -> AudioOutput | None: ...+ ) -> AudioOutput | None:+ """Synthesize a message answer or explicit text for the admitted app.++ A non-empty ``message_id`` takes precedence over ``text`` and selects+ a message belonging to this app and ``account_id``. When ``message_id``+ is None or empty, ``text`` is required; None raises ValueError.++ Return None without invoking the provider when the message ID is not+ a valid UUID, no owned message exists, or its answer is empty while its+ status is NORMAL or PAUSED. This means no message audio is available;+ it does not fall back to ``text``. Configuration and provider failures+ raise their corresponding exceptions instead of returning None.+ """+ ...diff --git a/api/services/installed_app_access_service.py b/api/services/installed_app_access_service.pyindex c686eababd2..eda3ad1b554 100644--- a/api/services/installed_app_access_service.py+++ b/api/services/installed_app_access_service.py@@ -10,11 +10,16 @@ from services.webapp_access_query_service import WebAppAccessModesQuery, WebAppU@dataclass(frozen=True, slots=True)class InstalledAppRef:- """Installation identity and app mode captured during request admission."""+ """Installation and app identity captured during request admission.++ tenant_id identifies the installing workspace; app_owner_tenant_id is the+ actual app owner's workspace and may differ for cross-workspace installs.+ """id: strapp_id: strtenant_id: str+ app_owner_tenant_id: strapp_mode: strdiff --git a/api/tests/unit_tests/controllers/console/explore/test_audio.py b/api/tests/unit_tests/controllers/console/explore/test_audio.pyindex b2b94440c21..bfcb8fef45d 100644--- a/api/tests/unit_tests/controllers/console/explore/test_audio.py+++ b/api/tests/unit_tests/controllers/console/explore/test_audio.py@@ -1,461 +1,432 @@+"""Explore audio HTTP contracts with real SQLite admission and an external runtime fake."""++from collections.abc import Generator, Iterator+from dataclasses import dataclass, fieldfrom io import BytesIO-from unittest.mock import MagicMock, patch+from typing import Literal, override+from uuid import uuid4import pytest-from flask import Flask-from sqlalchemy.orm import Session, scoped_session, sessionmaker-from werkzeug.exceptions import InternalServerError--import controllers.console.explore.audio as audio_module-from controllers.console.app.error import (- AppUnavailableError,- AudioTooLargeError,- CompletionRequestError,- NoAudioUploadedError,- ProviderModelCurrentlyNotSupportError,- ProviderNotInitializeError,- ProviderQuotaExceededError,- SpeechToTextDisabledError,-)-from core.errors.error import (- ModelCurrentlyNotSupportError,- ProviderTokenNotInitError,- QuotaExceededError,-)+from flask import has_request_context, request+from sqlalchemy import inspect, select+from sqlalchemy.orm import Session, sessionmaker+from werkzeug.test import TestResponse++import controllers.console.explore.audio as module+from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededErrorfrom graphon.model_runtime.errors.invoke import InvokeError-from models import Account-from models.model import App, AppMode, InstalledApp-from services.app_ref_service import AppRef, MessageRef+from models import AccountTrialAppRecord, App, AppMode, AppModelConfig, InstalledApp+from services import audio_provider_gateway+from services.app_audio_adapters import AppAudioRuntime+from services.app_audio_service import AppAudio+from services.app_definition_query_service import AppDefinitionUnavailableError+from services.audio_types import AudioAppRef, AudioOutput, AudioUpload+from services.errors.app_model_config import AppModelConfigBrokenErrorfrom services.errors.audio import (AudioTooLargeServiceError,NoAudioUploadedServiceError,+ ProviderNotSupportSpeechToTextServiceError,+ ProviderNotSupportTextToSpeechServiceError,SpeechToTextDisabledServiceError,+ UnsupportedAudioTypeServiceError,+)+from tests.unit_tests.controllers.console.explore.test_installed_app_admission import (+ _assert_json_response,+ _Harness,+ harness,)+__all__ = ["harness"]-def unwrap(func):- bound_self = getattr(func, "__self__", None)- while hasattr(func, "__wrapped__"):- func = func.__wrapped__- if bound_self is not None:- return func.__get__(bound_self, bound_self.__class__)- return func+type _Operation = Literal["audio-to-text", "text-to-audio"]+_OPERATIONS: tuple[_Operation, ...] = ("audio-to-text", "text-to-audio")+_WAV = b"RIFF\x24\x00\x00\x00WAVEfmt \x10\x00\x00\x00audio-data"-def installed_app(- sqlite_session: Session,- sqlite_session_factory: sessionmaker[Session],- monkeypatch: pytest.MonkeyPatch,-):- app = App(- id="app-1",- tenant_id="tenant-1",- name="Explore App",- mode=AppMode.CHAT,- enable_site=True,- enable_api=False,- )- installed = InstalledApp(- tenant_id="viewer-tenant",- app_id=app.id,- app_owner_tenant_id=app.tenant_id,- position=0,- is_pinned=False,- last_used_at=None,- )- sqlite_session.add_all([app, installed])- sqlite_session.commit()- session_proxy = scoped_session(sqlite_session_factory)- monkeypatch.setattr(audio_module.db, "session", session_proxy)- yield installed- session_proxy.remove()+@dataclass+class _Stream(Iterator[bytes]):+ chunks: Iterator[bytes] = field(default_factory=lambda: iter([b"a" * 32, b"remaining-audio"]))+ reads: int = 0+ close_calls: int = 0+ @override+ def __next__(self) -> bytes:+ chunk = next(self.chunks)+ self.reads += 1+ return chunk-def audio_file():- return (BytesIO(b"audio"), "audio.wav")+ def close(self) -> None:+ self.close_calls += 1-class TestChatAudioApi:- def setup_method(self):- self.api = audio_module.ChatAudioApi()- self.method = unwrap(self.api.post)+@dataclass+class _Runtime:+ harness: _Harness+ factory: sessionmaker[Session]+ error: Exception | None = None+ transcript: dict[str, str] = field(default_factory=lambda: {"text": "识别完成"})+ output: AudioOutput | None = field(default_factory=lambda: AudioOutput(data=_WAV, mime_type=None))+ asr_calls: list[tuple[AudioAppRef, bytes | None, str | None]] = field(default_factory=list)+ tts_calls: list[tuple[AudioAppRef, str, str | None, str | None, str | None]] = field(default_factory=list)- def test_post_success(self, app: Flask, installed_app, audio_file):- with (- app.test_request_context(- "/",- data={"file": audio_file},- content_type="multipart/form-data",- ),- patch.object(- audio_module.AudioService,- "transcript_asr",- return_value={"text": "ok"},- ),- ):- resp = self.method(installed_app)-- assert resp == {"text": "ok"}-- def test_app_unavailable(self, app: Flask, installed_app, audio_file):- with (- app.test_request_context(- "/",- data={"file": audio_file},- content_type="multipart/form-data",- ),- patch.object(- audio_module.AudioService,- "transcript_asr",- side_effect=audio_module.services.errors.app_model_config.AppModelConfigBrokenError(),- ),- ):- with pytest.raises(AppUnavailableError):- self.method(installed_app)-- def test_no_audio_uploaded(self, app: Flask, installed_app, audio_file):- with (- app.test_request_context(- "/",- data={"file": audio_file},- content_type="multipart/form-data",- ),- patch.object(- audio_module.AudioService,- "transcript_asr",- side_effect=NoAudioUploadedServiceError(),- ),- ):- with pytest.raises(NoAudioUploadedError):- self.method(installed_app)-- def test_audio_too_large(self, app: Flask, installed_app, audio_file):- with (- app.test_request_context(- "/",- data={"file": audio_file},- content_type="multipart/form-data",- ),- patch.object(- audio_module.AudioService,- "transcript_asr",- side_effect=AudioTooLargeServiceError("too big"),- ),- ):- with pytest.raises(AudioTooLargeError):- self.method(installed_app)-- def test_provider_quota_exceeded(self, app: Flask, installed_app, audio_file):- with (- app.test_request_context(- "/",- data={"file": audio_file},- content_type="multipart/form-data",- ),- patch.object(- audio_module.AudioService,- "transcript_asr",- side_effect=QuotaExceededError(),- ),- ):- with pytest.raises(ProviderQuotaExceededError):- self.method(installed_app)-- def test_unknown_exception(self, app: Flask, installed_app, audio_file):- with (- app.test_request_context(- "/",- data={"file": audio_file},- content_type="multipart/form-data",- ),- patch.object(- audio_module.AudioService,- "transcript_asr",- side_effect=Exception("boom"),- ),- ):- with pytest.raises(InternalServerError):- self.method(installed_app)-- def test_unsupported_audio_type(self, app: Flask, installed_app, audio_file):- with (- app.test_request_context(- "/",- data={"file": audio_file},- content_type="multipart/form-data",- ),- patch.object(- audio_module.AudioService,- "transcript_asr",- side_effect=audio_module.UnsupportedAudioTypeServiceError(),- ),- ):- with pytest.raises(audio_module.UnsupportedAudioTypeError):- self.method(installed_app)-- def test_provider_not_support_speech_to_text(self, app: Flask, installed_app, audio_file):- with (- app.test_request_context(- "/",- data={"file": audio_file},- content_type="multipart/form-data",- ),- patch.object(- audio_module.AudioService,- "transcript_asr",- side_effect=audio_module.ProviderNotSupportSpeechToTextServiceError(),- ),- ):- with pytest.raises(audio_module.ProviderNotSupportSpeechToTextError):- self.method(installed_app)-- def test_speech_to_text_disabled(self, app: Flask, installed_app, audio_file):- with (- app.test_request_context(- "/",- data={"file": audio_file},- content_type="multipart/form-data",- ),- patch.object(- audio_module.AudioService,- "transcript_asr",- side_effect=SpeechToTextDisabledServiceError(),- ),- ):- with pytest.raises(SpeechToTextDisabledError):- self.method(installed_app)-- def test_provider_not_initialized(self, app: Flask, installed_app, audio_file):- with (- app.test_request_context(- "/",- data={"file": audio_file},- content_type="multipart/form-data",- ),- patch.object(- audio_module.AudioService,- "transcript_asr",- side_effect=ProviderTokenNotInitError("not init"),- ),- ):- with pytest.raises(ProviderNotInitializeError):- self.method(installed_app)-- def test_model_currently_not_supported(self, app: Flask, installed_app, audio_file):- with (- app.test_request_context(- "/",- data={"file": audio_file},- content_type="multipart/form-data",- ),- patch.object(- audio_module.AudioService,- "transcript_asr",- side_effect=ModelCurrentlyNotSupportError(),- ),- ):- with pytest.raises(ProviderModelCurrentlyNotSupportError):- self.method(installed_app)-- def test_invoke_error_asr(self, app: Flask, installed_app, audio_file):- with (- app.test_request_context(- "/",- data={"file": audio_file},+ def transcript_asr(self, *, app: AudioAppRef, audio: AudioUpload | None) -> dict[str, str]:+ self._assert_reference(app)+ self.asr_calls.append(+ (app, audio.stream.read() if audio is not None else None, audio.mime_type if audio else None)+ )+ if self.error is not None:+ raise self.error+ return self.transcript++ def transcript_tts(+ self,+ *,+ app: AudioAppRef,+ account_id: str,+ text: str | None,+ voice: str | None,+ message_id: str | None,+ ) -> AudioOutput | None:+ self._assert_reference(app)+ self.tts_calls.append((app, account_id, text, voice, message_id))+ if self.error is not None:+ raise self.error+ return self.output++ def _assert_reference(self, app: AudioAppRef) -> None:+ assert inspect(app, raiseerr=False) is None+ assert app.app_id == self.harness.target_app.id+ assert app.tenant_id == self.harness.target_app.tenant_id+ assert app.tenant_id != self.harness.installed_app.tenant_id+ with self.factory() as session:+ installation = session.get(InstalledApp, self.harness.installed_app.id)+ assert installation is not None+ assert installation.last_used_at is None++ def request(+ self,+ operation: _Operation,+ *,+ body: dict[str, object] | None = None,+ installed_app_id: str | None = None,+ upload: bool = True,+ ) -> TestResponse:+ url = f"/installed-apps/{installed_app_id or self.harness.installed_app.id}/{operation}"+ if operation == "audio-to-text":+ return self.harness.app.test_client().post(+ url,+ data={"file": (BytesIO(_WAV), "recording.wav", "audio/wav")} if upload else {},content_type="multipart/form-data",- ),- patch.object(- audio_module.AudioService,- "transcript_asr",- side_effect=InvokeError("invoke failed"),- ),- ):- with pytest.raises(CompletionRequestError):- self.method(installed_app)---class TestChatTextApi:- def setup_method(self):- self.api = audio_module.ChatTextApi()- self.method = unwrap(self.api.post)-- def test_post_success(self, app: Flask, installed_app):- account = Account(name="User", email="[email protected]")- account.id = "account-1"- transcript_tts = MagicMock(return_value={"audio": "ok"})-- with (- app.test_request_context(- "/",- json={"message_id": "m1", "text": "hello", "voice": "v1"},- ),- patch.object(- audio_module,- "current_account_with_tenant",- return_value=(account, "tenant-1"),- ),- patch.object(audio_module.AudioService, "transcript_tts", transcript_tts),- ):- resp = self.method(- audio_module.TextToAudioPayload.model_validate({"message_id": "m1", "text": "hello", "voice": "v1"}),- installed_app,)+ return self.harness.app.test_client().post(url, json=body if body is not None else {"text": "你好"})+- assert resp == {"audio": "ok"}- assert transcript_tts.call_args.kwargs["message_ref"] == MessageRef(- app=AppRef(tenant_id="tenant-1", app_id="app-1"),- message_id="m1",- account_id="account-1",+@dataclass(frozen=True)+class _Services:+ app_audio: AppAudio+++def runtime(+ harness: _Harness, monkeypatch: pytest.MonkeyPatch, sqlite_session_factory: sessionmaker[Session]+) -> _Runtime:+ state = _Runtime(harness=harness, factory=sqlite_session_factory)+ services = _Services(app_audio=state)+ monkeypatch.setattr(module, "application_services", lambda: services)+ harness.api.add_resource(module.ChatAudioApi, "/installed-apps/<uuid:installed_app_id>/audio-to-text")+ harness.api.add_resource(module.ChatTextApi, "/installed-apps/<uuid:installed_app_id>/text-to-audio")+ return state+++def _error(response: TestResponse, *, status: int, code: str, message: str | None = None) -> None:+ assert response.status_code == status+ body = response.get_json()+ assert body["code"] == code+ assert body["status"] == status+ assert isinstance(body["message"], str)+ assert body["message"]+ if message is not None:+ assert body["message"] == message+ assert response.headers["Content-Type"] == "application/json"+ assert int(response.headers["Content-Length"]) == len(response.data)++[email protected]("text", ["识别完成", ""])+def test_asr_preserves_transcript_and_upload_stream_and_mime(runtime: _Runtime, text: str) -> None:+ runtime.transcript = {"text": text}+ _assert_json_response(runtime.request("audio-to-text"), status=200, body={"text": text})+ assert len(runtime.asr_calls) == 1+ app, data, mime_type = runtime.asr_calls[0]+ assert app.app_mode == "completion"+ assert data == _WAV+ assert mime_type == "audio/wav"+ assert runtime.tts_calls == []+++def test_missing_upload_reaches_runtime_and_returns_specific_error(runtime: _Runtime) -> None:+ runtime.error = NoAudioUploadedServiceError()+ _error(runtime.request("audio-to-text", upload=False), status=400, code="no_audio_uploaded")+ assert len(runtime.asr_calls) == 1+ assert runtime.asr_calls[0][1:] == (None, None)+++ ("body", "expected"),+ [+ ({"text": "你好", "voice": "voice-1"}, ("你好", "voice-1", None)),+ (+ {"text": "ignored text", "voice": "", "message_id": "11111111-1111-4111-8111-111111111111"},+ ("ignored text", "", "11111111-1111-4111-8111-111111111111"),+ ),+ ({}, (None, None, None)),+ ({"text": "", "voice": None, "message_id": "malformed", "streaming": False}, ("", None, "malformed")),+ ({"text": None, "streaming": True}, (None, None, None)),+ ],+)+def test_tts_keeps_payload_values_and_authenticated_account(+ runtime: _Runtime, body: dict[str, object], expected: tuple[str | None, str | None, str | None]+) -> None:+ response = runtime.request("text-to-audio", body=body)+ assert response.status_code == 200+ assert response.data == _WAV+ assert response.headers["Content-Type"] == "audio/wav"+ assert len(runtime.tts_calls) == 1+ app, account_id, text, voice, message_id = runtime.tts_calls[0]+ assert app.app_mode == "completion"+ assert account_id == runtime.harness.account.id+ assert (text, voice, message_id) == expected+ assert runtime.asr_calls == []++[email protected]("data", [_WAV, bytearray(_WAV), memoryview(_WAV)])+def test_tts_binary_carriers_preserve_bytes_and_audio_headers(+ runtime: _Runtime, data: bytes | bytearray | memoryview+) -> None:+ runtime.output = AudioOutput(data=data, mime_type="audio/x-wav")+ response = runtime.request("text-to-audio")+ assert response.status_code == 200+ assert response.data == _WAV+ assert dict(response.headers) == {"Content-Type": "audio/wav", "Content-Length": str(len(_WAV))}+++def test_tts_stream_preserves_split_signature_and_all_chunks(runtime: _Runtime) -> None:+ def chunks() -> Generator[bytes]:+ yield _WAV[:2]+ yield b""+ yield _WAV[2:11]+ yield _WAV[11:] + b"00"+ # This tail is consumed after MIME probing and the controller return.+ assert has_request_context()+ assert request.path.endswith("/text-to-audio")+ yield b"tail"++ runtime.output = AudioOutput(data=chunks(), mime_type=None)+ response = runtime.request("text-to-audio")+ assert response.status_code == 200+ assert response.data == _WAV + b"00tail"+ assert dict(response.headers) == {"Content-Type": "audio/wav"}++[email protected]("consume", [False, True])+def test_closing_http_response_releases_provider_without_reading_remaining_audio(+ runtime: _Runtime, consume: bool+) -> None:+ stream = _Stream()+ runtime.output = AudioOutput(data=stream, mime_type="audio/mpeg")+ url = f"/installed-apps/{runtime.harness.installed_app.id}/text-to-audio"+ # Dispatch before the WSGI client reads a chunk to cover an unstarted response.+ with runtime.harness.app.test_request_context(url, method="POST", json={"text": "hello"}):+ response = runtime.harness.app.full_dispatch_request()+ assert response.status_code == 200+ assert response.headers["Content-Type"] == "audio/mpeg"+ assert "Content-Length" not in response.headers+ if consume:+ assert next(iter(response.response)) == b"a" * 32+ assert stream.reads == 1+ assert stream.close_calls == 0+ response.close()+ assert stream.close_calls == 1+ assert stream.reads == 1+++def test_tts_rejects_provider_mime_mismatch_with_specific_completion_error(runtime: _Runtime) -> None:+ runtime.output = AudioOutput(data=_WAV, mime_type="audio/mpeg")+ _error(+ runtime.request("text-to-audio"),+ status=400,+ code="completion_request_error",+ message="TTS provider output MIME does not match its audio bytes: declared audio/mpeg, detected audio/wav",+ )+++def test_tts_no_result_remains_json_null(runtime: _Runtime) -> None:+ runtime.output = None+ response = runtime.request("text-to-audio", body={"message_id": "not-a-uuid"})+ assert response.status_code == 200+ assert response.get_json() is None+ assert response.data == b"null\n"+ assert response.headers["Content-Type"] == "application/json"+ assert int(response.headers["Content-Length"]) == len(response.data)+ assert runtime.tts_calls[0][-1] == "not-a-uuid"++[email protected]("body", [{"text": 123}, {"voice": []}, {"message_id": 123}, {"streaming": "invalid"}])+def test_invalid_tts_body_uses_shared_422_before_runtime(runtime: _Runtime, body: dict[str, object]) -> None:+ _error(runtime.request("text-to-audio", body=body), status=422, code="unprocessable_entity")+ assert runtime.tts_calls == []++[email protected]("operation", _OPERATIONS)[email protected]("mode", list(AppMode))+def test_audio_endpoints_have_no_app_mode_gate(runtime: _Runtime, operation: _Operation, mode: AppMode) -> None:+ with runtime.factory.begin() as session:+ app = session.get(App, runtime.harness.target_app.id)+ assert app is not None+ app.mode = mode+ assert runtime.request(operation).status_code == 200+ calls = runtime.asr_calls if operation == "audio-to-text" else runtime.tts_calls+ assert len(calls) == 1+ assert calls[0][0].app_mode == mode.value++[email protected]("operation", _OPERATIONS)+def test_installed_audio_does_not_record_trial_usage(runtime: _Runtime, operation: _Operation) -> None:+ assert runtime.request(operation).status_code == 200++ with runtime.factory() as session:+ assert session.scalar(select(AccountTrialAppRecord)) is None+ installation = session.get(InstalledApp, runtime.harness.installed_app.id)+ assert installation is not None+ assert installation.last_used_at is None++[email protected]("operation", _OPERATIONS)+def test_shared_runtime_routes_audio_to_actual_owner_despite_stale_installation_metadata(+ runtime: _Runtime, monkeypatch: pytest.MonkeyPatch, operation: _Operation+) -> None:+ with runtime.factory.begin() as session:+ app = session.get(App, runtime.harness.target_app.id)+ installation = session.get(InstalledApp, runtime.harness.installed_app.id)+ assert app is not None+ assert installation is not None+ assert app.tenant_id != installation.tenant_id+ installation.app_owner_tenant_id = installation.tenant_id+ config = AppModelConfig(+ app_id=app.id,+ speech_to_text='{"enabled":true}',+ text_to_speech='{"enabled":true,"voice":"configured"}',)+ session.add(config)+ session.flush()+ app.app_model_config_id = config.id++ calls: list[tuple[AudioAppRef, str | None]] = []++ def transcribe(*, app: AudioAppRef, content: bytes, end_user: str | None) -> str:+ calls.append((app, end_user))+ assert content == _WAV+ return "识别完成"++ def synthesize(*, app: AudioAppRef, text: str, voice: str | None, end_user: str | None) -> AudioOutput:+ calls.append((app, end_user))+ assert (text, voice) == ("你好", "configured")+ return AudioOutput(data=_WAV, mime_type="audio/wav")++ monkeypatch.setattr(audio_provider_gateway, "speech_to_text", transcribe)+ monkeypatch.setattr(audio_provider_gateway, "text_to_speech", synthesize)+ services = _Services(app_audio=AppAudioRuntime(session_factory=runtime.factory))+ monkeypatch.setattr(module, "application_services", lambda: services)++ response = runtime.request(operation)++ if operation == "audio-to-text":+ _assert_json_response(response, status=200, body={"text": "识别完成"})+ else:+ assert response.status_code == 200+ assert response.data == _WAV+ assert response.headers["Content-Type"] == "audio/wav"+ assert calls == [(AudioAppRef(app.id, app.tenant_id, app.mode), None)]++[email protected]("operation", _OPERATIONS)[email protected]("change", ["removed", "owner", "mode"])+def test_shared_runtime_rejects_app_changes_after_admission(+ runtime: _Runtime, monkeypatch: pytest.MonkeyPatch, operation: _Operation, change: str+) -> None:+ def change_app() -> None:+ with runtime.factory.begin() as session:+ app = session.get(App, runtime.harness.target_app.id)+ assert app is not None+ if change == "removed":+ session.delete(app)+ elif change == "owner":+ app.tenant_id = str(uuid4())+ else:+ app.mode = AppMode.CHAT++ runtime.harness.state.permission_action = change_app+ services = _Services(app_audio=AppAudioRuntime(session_factory=runtime.factory))+ monkeypatch.setattr(module, "application_services", lambda: services)++ _error(runtime.request(operation), status=400, code="app_unavailable")+ assert runtime.harness.state.permission_calls == [(runtime.harness.account.id, runtime.harness.target_app.id)]++[email protected]("operation", _OPERATIONS)[email protected]("admission", ["missing", "denied", "orphan"])+def test_audio_endpoints_apply_admission_before_reading_or_generating_audio(+ runtime: _Runtime, operation: _Operation, admission: str+) -> None:+ if admission == "denied":+ runtime.harness.state.allowed = False+ elif admission == "orphan":+ with runtime.factory.begin() as session:+ app = session.get(App, runtime.harness.target_app.id)+ assert app is not None+ session.delete(app)+ _error(+ runtime.request(operation, installed_app_id=str(uuid4()) if admission == "missing" else None),+ status=403 if admission == "denied" else 404,+ code="access_denied" if admission == "denied" else "installed_app_not_found",+ )+ assert runtime.asr_calls == runtime.tts_calls == []+ if admission == "orphan":+ assert runtime.harness.state.permission_calls == []+ with runtime.factory() as session:+ assert session.get(InstalledApp, runtime.harness.installed_app.id) is None++[email protected]("operation", _OPERATIONS)+ ("failure", "status", "code", "description"),+ [+ (AppDefinitionUnavailableError("app removed"), 400, "app_unavailable", None),+ (AppModelConfigBrokenError(), 400, "app_unavailable", None),+ (NoAudioUploadedServiceError(), 400, "no_audio_uploaded", None),+ (AudioTooLargeServiceError("30 MB limit exceeded"), 413, "audio_too_large", "30 MB limit exceeded"),+ (UnsupportedAudioTypeServiceError(), 415, "unsupported_audio_type", None),+ (ProviderNotSupportSpeechToTextServiceError(), 400, "provider_not_support_speech_to_text", None),+ (ProviderTokenNotInitError("Missing credentials"), 400, "provider_not_initialize", "Missing credentials"),+ (QuotaExceededError(), 400, "provider_quota_exceeded", None),+ (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"),+ (RuntimeError("Unexpected provider failure"), 500, "internal_server_error", None),+ ],+)+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)+ assert len(runtime.asr_calls) + len(runtime.tts_calls) == 1+++def test_asr_disabled_feature_preserves_400(runtime: _Runtime) -> None:+ runtime.error = SpeechToTextDisabledServiceError()+ _error(runtime.request("audio-to-text"), status=400, code="speech_to_text_disabled")+- def test_provider_not_initialized(self, app: Flask, installed_app):- with (- app.test_request_context(- "/",- json={"text": "hi"},- ),- patch.object(- audio_module.AudioService,- "transcript_tts",- side_effect=ProviderTokenNotInitError("not init"),- ),- ):- with pytest.raises(ProviderNotInitializeError):- self.method(audio_module.TextToAudioPayload.model_validate({"text": "hi"}), installed_app)-- def test_model_not_supported(self, app: Flask, installed_app):- with (- app.test_request_context(- "/",- json={"text": "hi"},- ),- patch.object(- audio_module.AudioService,- "transcript_tts",- side_effect=ModelCurrentlyNotSupportError(),- ),- ):- with pytest.raises(ProviderModelCurrentlyNotSupportError):- self.method(audio_module.TextToAudioPayload.model_validate({"text": "hi"}), installed_app)-- def test_invoke_error(self, app: Flask, installed_app):- with (- app.test_request_context(- "/",- json={"text": "hi"},- ),- patch.object(- audio_module.AudioService,- "transcript_tts",- side_effect=InvokeError("invoke failed"),- ),- ):- with pytest.raises(CompletionRequestError):- self.method(audio_module.TextToAudioPayload.model_validate({"text": "hi"}), installed_app)-- def test_unknown_exception(self, app: Flask, installed_app):- with (- app.test_request_context(- "/",- json={"text": "hi"},- ),- patch.object(- audio_module.AudioService,- "transcript_tts",- side_effect=Exception("boom"),- ),- ):- with pytest.raises(InternalServerError):- self.method(audio_module.TextToAudioPayload.model_validate({"text": "hi"}), installed_app)-- def test_app_unavailable_tts(self, app: Flask, installed_app):- with (- app.test_request_context(- "/",- json={"text": "hi"},- ),- patch.object(- audio_module.AudioService,- "transcript_tts",- side_effect=audio_module.services.errors.app_model_config.AppModelConfigBrokenError(),- ),- ):- with pytest.raises(AppUnavailableError):- self.method(audio_module.TextToAudioPayload.model_validate({"text": "hi"}), installed_app)-- def test_no_audio_uploaded_tts(self, app: Flask, installed_app):- with (- app.test_request_context(- "/",- json={"text": "hi"},- ),- patch.object(- audio_module.AudioService,- "transcript_tts",- side_effect=NoAudioUploadedServiceError(),- ),- ):- with pytest.raises(NoAudioUploadedError):- self.method(audio_module.TextToAudioPayload.model_validate({"text": "hi"}), installed_app)-- def test_audio_too_large_tts(self, app: Flask, installed_app):- with (- app.test_request_context(- "/",- json={"text": "hi"},- ),- patch.object(- audio_module.AudioService,- "transcript_tts",- side_effect=AudioTooLargeServiceError("too big"),- ),- ):- with pytest.raises(AudioTooLargeError):- self.method(audio_module.TextToAudioPayload.model_validate({"text": "hi"}), installed_app)-- def test_unsupported_audio_type_tts(self, app: Flask, installed_app):- with (- app.test_request_context(- "/",- json={"text": "hi"},- ),- patch.object(- audio_module.AudioService,- "transcript_tts",- side_effect=audio_module.UnsupportedAudioTypeServiceError(),- ),- ):- with pytest.raises(audio_module.UnsupportedAudioTypeError):- self.method(audio_module.TextToAudioPayload.model_validate({"text": "hi"}), installed_app)-- def test_provider_not_support_speech_to_text_tts(self, app: Flask, installed_app):- with (- app.test_request_context(- "/",- json={"text": "hi"},- ),- patch.object(- audio_module.AudioService,- "transcript_tts",- side_effect=audio_module.ProviderNotSupportSpeechToTextServiceError(),- ),- ):- with pytest.raises(audio_module.ProviderNotSupportSpeechToTextError):- self.method(audio_module.TextToAudioPayload.model_validate({"text": "hi"}), installed_app)-- def test_quota_exceeded_tts(self, app: Flask, installed_app):- with (- app.test_request_context(- "/",- json={"text": "hi"},- ),- patch.object(- audio_module.AudioService,- "transcript_tts",- side_effect=QuotaExceededError(),- ),- ):- with pytest.raises(ProviderQuotaExceededError):- self.method(audio_module.TextToAudioPayload.model_validate({"text": "hi"}), installed_app)+def test_unsupported_tts_provider_has_specific_error(runtime: _Runtime) -> None:+ runtime.error = ProviderNotSupportTextToSpeechServiceError()+ _error(runtime.request("text-to-audio"), status=400, code="provider_not_support_text_to_speech")diff --git a/api/tests/unit_tests/controllers/console/explore/test_parameter.py b/api/tests/unit_tests/controllers/console/explore/test_parameter.pyindex 30cdd70045f..f82901690df 100644--- a/api/tests/unit_tests/controllers/console/explore/test_parameter.py+++ b/api/tests/unit_tests/controllers/console/explore/test_parameter.py@@ -16,7 +16,13 @@ _REQUEST_CONTEXT = RequestContext(def _installed_app() -> InstalledAppRef:- return InstalledAppRef(id="installed-1", tenant_id="viewer-tenant", app_id="app-1", app_mode="completion")+ return InstalledAppRef(+ id="installed-1",+ tenant_id="viewer-tenant",+ app_id="app-1",+ app_owner_tenant_id="owner-tenant",+ app_mode="completion",+ )def _application_services() -> tuple[SimpleNamespace, MagicMock]: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 be49ddfa02f..70438e4ab76 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@@ -47,6 +47,7 @@ def _installed_app(*, app_mode: str = "completion") -> InstalledAppRef:id="99999999-9999-4999-8999-999999999999",tenant_id=_WORKSPACE_ID,app_id="33333333-3333-4333-8333-333333333333",+ app_owner_tenant_id="44444444-4444-4444-8444-444444444444",app_mode=app_mode,)diff --git a/api/tests/unit_tests/controllers/console/explore/test_wraps.py b/api/tests/unit_tests/controllers/console/explore/test_wraps.pydeleted file mode 100644index 5b1113a605d..00000000000--- a/api/tests/unit_tests/controllers/console/explore/test_wraps.py+++ /dev/null@@ -1,202 +0,0 @@-from unittest.mock import MagicMock, patch-from uuid import uuid4--import pytest-from sqlalchemy.orm import Session, scoped_session-from werkzeug.exceptions import NotFound--import controllers.console.explore.wraps as wraps_module-import models.model as model_module-from controllers.console.explore.error import (- AppAccessDeniedError,- TrialAppFeatureDisabledError,-)-from controllers.console.explore.trial_app_admission import trial_feature_enable-from controllers.console.explore.wraps import (- InstalledAppResource,- installed_app_required,- user_allowed_to_access_app,-)-from models import Account, App, InstalledApp-from tests.unit_tests.model_factories import make_account, make_app---def _bind_database(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None:- session_registry = scoped_session(lambda: sqlite_session)- monkeypatch.setattr(wraps_module.db, "session", session_registry)- monkeypatch.setattr(model_module.db, "session", session_registry)---def _account(*, account_id: str | None = None) -> Account:- return make_account(account_id=account_id, name="Explore user", email="[email protected]")---def _app() -> App:- return make_app(app_id=str(uuid4()), tenant_id=str(uuid4()), name="Explore App", icon_type=None)---def _installed_app(*, app_id: str, tenant_id: str) -> InstalledApp:- return InstalledApp(- tenant_id=tenant_id,- app_id=app_id,- app_owner_tenant_id=str(uuid4()),- position=0,- is_pinned=False,- last_used_at=None,- )--[email protected]("sqlite_session", [(InstalledApp, App)], indirect=True)-def test_installed_app_required_not_found(- monkeypatch: pytest.MonkeyPatch,- sqlite_session: Session,-):- tenant_id = str(uuid4())- _bind_database(monkeypatch, sqlite_session)-- @installed_app_required- def view(installed_app):- return "ok"-- with patch(- "controllers.console.explore.wraps.current_account_with_tenant",- return_value=(_account(), tenant_id),- ):- with pytest.raises(NotFound):- view(str(uuid4()))--[email protected]("sqlite_session", [(InstalledApp, App)], indirect=True)-def test_installed_app_required_app_deleted(- monkeypatch: pytest.MonkeyPatch,- sqlite_session: Session,-):- tenant_id = str(uuid4())- installed_app = _installed_app(app_id=str(uuid4()), tenant_id=tenant_id)- sqlite_session.add(installed_app)- sqlite_session.commit()- installed_app_id = installed_app.id- _bind_database(monkeypatch, sqlite_session)-- @installed_app_required- def view(installed_app):- return "ok"-- with patch(- "controllers.console.explore.wraps.current_account_with_tenant",- return_value=(_account(), tenant_id),- ):- with pytest.raises(NotFound):- view(installed_app_id)-- assert sqlite_session.get(InstalledApp, installed_app_id) is None--[email protected]("sqlite_session", [(InstalledApp, App)], indirect=True)-def test_installed_app_required_success(- monkeypatch: pytest.MonkeyPatch,- sqlite_session: Session,-):- app = _app()- installed_app = _installed_app(app_id=app.id, tenant_id=app.tenant_id)- sqlite_session.add_all([app, installed_app])- sqlite_session.commit()- _bind_database(monkeypatch, sqlite_session)-- @installed_app_required- def view(installed_app):- return installed_app-- with patch(- "controllers.console.explore.wraps.current_account_with_tenant",- return_value=(_account(), app.tenant_id),- ):- result = view(installed_app.id)-- assert result.id == installed_app.id- app_model = result.app_with_session(session=sqlite_session)- assert app_model is not None- assert app_model.id == app.id---def test_user_allowed_to_access_app_denied():- installed_app = _installed_app(app_id="app-1", tenant_id="tenant-1")-- @user_allowed_to_access_app- def view(installed_app):- return "ok"-- with (- patch(- "controllers.console.explore.wraps.current_account_with_tenant",- return_value=(_account(account_id="user-1"), None),- ),- patch(- "controllers.console.explore.wraps.SystemFeatureService.is_webapp_auth_enabled",- return_value=True,- ),- patch(- "controllers.console.explore.wraps.EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp",- return_value=False,- ),- ):- with pytest.raises(AppAccessDeniedError):- view(installed_app)---def test_user_allowed_to_access_app_success():- installed_app = _installed_app(app_id="app-1", tenant_id="tenant-1")-- @user_allowed_to_access_app- def view(installed_app):- return "ok"-- with (- patch(- "controllers.console.explore.wraps.current_account_with_tenant",- return_value=(_account(account_id="user-1"), None),- ),- patch(- "controllers.console.explore.wraps.SystemFeatureService.is_webapp_auth_enabled",- return_value=True,- ),- patch(- "controllers.console.explore.wraps.EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp",- return_value=True,- ),- ):- assert view(installed_app) == "ok"---def test_trial_feature_enable_disabled() -> None:- @trial_feature_enable- def view() -> str:- return "ok"-- services = MagicMock()- services.recommended_app_queries.is_trial_enabled.return_value = False- with patch("controllers.console.explore.trial_app_admission.application_services", return_value=services):- with pytest.raises(TrialAppFeatureDisabledError) as exc_info:- view()-- assert exc_info.value.data == {- "code": "trial_app_feature_disabled",- "message": "Trial app feature is not enabled.",- "status": 403,- }---def test_trial_feature_enable_enabled() -> None:- @trial_feature_enable- def view() -> str:- return "ok"-- services = MagicMock()- services.recommended_app_queries.is_trial_enabled.return_value = True- with patch("controllers.console.explore.trial_app_admission.application_services", return_value=services):- assert view() == "ok"---def test_installed_app_resource_decorators():- decorators = InstalledAppResource.method_decorators- assert len(decorators) == 4diff --git a/api/tests/unit_tests/extensions/test_ext_application_services.py b/api/tests/unit_tests/extensions/test_ext_application_services.pyindex a3b01cc84f5..71e80d8dd9d 100644--- a/api/tests/unit_tests/extensions/test_ext_application_services.py+++ b/api/tests/unit_tests/extensions/test_ext_application_services.py@@ -811,7 +811,11 @@ def installed_app_ref(sqlite_session_factory: sessionmaker[Session]) -> Installesession.add(installed_app)session.flush()result = InstalledAppRef(- id=installed_app.id, app_id=app.id, tenant_id=installed_app.tenant_id, app_mode=app.mode.value+ id=installed_app.id,+ app_id=app.id,+ tenant_id=installed_app.tenant_id,+ app_owner_tenant_id=app.tenant_id,+ app_mode=app.mode.value,)return resultdiff --git a/api/tests/unit_tests/repositories/test_installed_app_conversation_repository.py b/api/tests/unit_tests/repositories/test_installed_app_conversation_repository.pyindex 2571f2e7814..51ecfd88a30 100644--- a/api/tests/unit_tests/repositories/test_installed_app_conversation_repository.py+++ b/api/tests/unit_tests/repositories/test_installed_app_conversation_repository.py@@ -36,7 +36,11 @@ def installation(sqlite_session_factory: sessionmaker[Session]) -> InstalledAppRsession.add(installed_app)session.flush()return InstalledAppRef(- id=installed_app.id, tenant_id=installed_app.tenant_id, app_id=app.id, app_mode=app.mode.value+ id=installed_app.id,+ tenant_id=installed_app.tenant_id,+ app_id=app.id,+ app_owner_tenant_id=app.tenant_id,+ app_mode=app.mode.value,)diff --git a/api/tests/unit_tests/repositories/test_installed_app_message_repository.py b/api/tests/unit_tests/repositories/test_installed_app_message_repository.pyindex 0af872c65a4..37b4ce35024 100644--- a/api/tests/unit_tests/repositories/test_installed_app_message_repository.py+++ b/api/tests/unit_tests/repositories/test_installed_app_message_repository.py@@ -33,7 +33,13 @@ def installation(sqlite_session_factory: sessionmaker[Session]) -> InstalledAppR)session.add(installation)session.flush()- return InstalledAppRef(id=installation.id, tenant_id=installation.tenant_id, app_id=app.id, app_mode="chat")+ return InstalledAppRef(+ id=installation.id,+ tenant_id=installation.tenant_id,+ app_id=app.id,+ app_owner_tenant_id=app.tenant_id,+ app_mode="chat",+ )def _conversation(session: Session, installation: InstalledAppRef) -> Conversation:diff --git a/api/tests/unit_tests/repositories/test_installed_app_repository.py b/api/tests/unit_tests/repositories/test_installed_app_repository.pyindex eefe5424d81..146d088404e 100644--- a/api/tests/unit_tests/repositories/test_installed_app_repository.py+++ b/api/tests/unit_tests/repositories/test_installed_app_repository.py@@ -29,7 +29,7 @@ def _installation(*, app_id: str) -> InstalledApp:@pytest.mark.parametrize("app_mode", list(AppMode))-def test_resolve_returns_pure_reference_to_cross_workspace_app(+def test_resolve_returns_actual_owner_despite_stale_cross_workspace_installation(sqlite_session_factory: sessionmaker[Session],app_mode: AppMode,) -> None:@@ -46,6 +46,7 @@ def test_resolve_returns_pure_reference_to_cross_workspace_app(session.add(app)session.flush()installed_app = _installation(app_id=app.id)+ installed_app.app_owner_tenant_id = _VIEWER_TENANT_IDsession.add(installed_app)session.flush()installed_app_id = installed_app.id@@ -63,9 +64,13 @@ def test_resolve_returns_pure_reference_to_cross_workspace_app(result = repository.resolve(installed_app_id=installed_app_id, tenant_id=_VIEWER_TENANT_ID)assert result == InstalledAppRef(- id=installed_app_id, app_id=app_id, tenant_id=_VIEWER_TENANT_ID, app_mode=app_mode.value+ id=installed_app_id,+ app_id=app_id,+ tenant_id=_VIEWER_TENANT_ID,+ app_owner_tenant_id=_OWNER_TENANT_ID,+ app_mode=app_mode.value,)- # The app existence read also supplies its mode; no separate mode query.+ # Ownership and mode come from App, not the installation snapshot.assert select_count == 2assert inspect(result, raiseerr=False) is Nonewith sqlite_session_factory() as session:@@ -141,7 +146,11 @@ def installed_app(sqlite_session_factory: sessionmaker[Session]) -> InstalledAppdef _reference(installation: InstalledApp) -> InstalledAppRef:return InstalledAppRef(- id=installation.id, app_id=installation.app_id, tenant_id=installation.tenant_id, app_mode="completion"+ id=installation.id,+ app_id=installation.app_id,+ tenant_id=installation.tenant_id,+ app_owner_tenant_id=installation.app_owner_tenant_id,+ app_mode="completion",)diff --git a/api/tests/unit_tests/services/test_installed_app_access_service.py b/api/tests/unit_tests/services/test_installed_app_access_service.pyindex f5817925403..17d029b60a5 100644--- a/api/tests/unit_tests/services/test_installed_app_access_service.py+++ b/api/tests/unit_tests/services/test_installed_app_access_service.py@@ -11,7 +11,13 @@ from services.installed_app_access_service import (InstalledAppRef,)-_REF = InstalledAppRef(id="installation-1", app_id="app-1", tenant_id="workspace-1", app_mode="completion")+_REF = InstalledAppRef(+ id="installation-1",+ app_id="app-1",+ tenant_id="workspace-1",+ app_owner_tenant_id="owner-workspace",+ app_mode="completion",+)class _Store:diff --git a/api/tests/unit_tests/services/test_installed_app_conversation_service.py b/api/tests/unit_tests/services/test_installed_app_conversation_service.pyindex 97c20f764a5..356d0dedfed 100644--- a/api/tests/unit_tests/services/test_installed_app_conversation_service.py+++ b/api/tests/unit_tests/services/test_installed_app_conversation_service.py@@ -22,6 +22,7 @@ _REF = InstalledAppRef(id="11111111-1111-4111-8111-111111111111",app_id="22222222-2222-4222-8222-222222222222",tenant_id="33333333-3333-4333-8333-333333333333",+ app_owner_tenant_id="66666666-6666-4666-8666-666666666666",app_mode="chat",)_ACCOUNT_ID = "44444444-4444-4444-8444-444444444444"diff --git a/api/tests/unit_tests/services/test_installed_app_message_adapters.py b/api/tests/unit_tests/services/test_installed_app_message_adapters.pyindex 83dafad0ed2..680210ad929 100644--- a/api/tests/unit_tests/services/test_installed_app_message_adapters.py+++ b/api/tests/unit_tests/services/test_installed_app_message_adapters.py@@ -138,7 +138,11 @@ def harness(sqlite_session_factory: sessionmaker[Session], monkeypatch: pytest.Myield _Harness(runtime=InstalledAppMessageRuntime(session_factory=cast(sessionmaker[Session], factory)),installation=InstalledAppRef(- id=installed.id, tenant_id=installed.tenant_id, app_id=app.id, app_mode="chat"+ id=installed.id,+ tenant_id=installed.tenant_id,+ app_id=app.id,+ app_owner_tenant_id=app.tenant_id,+ app_mode="chat",),account_id=account.id,message_id=message.id,diff --git a/api/tests/unit_tests/services/test_installed_app_message_service.py b/api/tests/unit_tests/services/test_installed_app_message_service.pyindex d02a449f414..c74301b19f4 100644--- a/api/tests/unit_tests/services/test_installed_app_message_service.py+++ b/api/tests/unit_tests/services/test_installed_app_message_service.py@@ -17,7 +17,9 @@ from services.installed_app_message_service import (MessageRecord,)-_REF = InstalledAppRef(id="installed", app_id="app", tenant_id="viewer-workspace", app_mode="chat")+_REF = InstalledAppRef(+ id="installed", app_id="app", tenant_id="viewer-workspace", app_owner_tenant_id="owner-workspace", app_mode="chat"+)def _message(message_id: str) -> MessageRecord: