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.

chore: remove PartnerStack tracking and tenant binding (#43641)

Joel572cb45b0f6c
diff --git a/api/.importlinter b/api/.importlinter
index ed0d82d4485..2550486a174 100644
--- a/api/.importlinter
+++ b/api/.importlinter
@@ -967,7 +967,6 @@ type = forbidden
source_modules =
services.billing_portal_service
services.compliance_download_service
- services.partner_tenant_binding_service
forbidden_modules =
configs
controllers
diff --git a/api/controllers/console/billing/billing.py b/api/controllers/console/billing/billing.py
index 033bc2427db..9e0ae7c1f4b 100644
--- a/api/controllers/console/billing/billing.py
+++ b/api/controllers/console/billing/billing.py
@@ -1,9 +1,7 @@
-import base64
-from typing import Any, Literal
+from typing import Literal
from flask_restx import Resource
-from pydantic import BaseModel, Field, RootModel
-from werkzeug.exceptions import BadRequest
+from pydantic import BaseModel, Field
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
from controllers.console import console_ns
@@ -31,14 +29,6 @@ class SubscriptionQuery(BaseModel):
interval: Literal["month", "year"] = Field(..., description="Billing interval")
-class PartnerTenantsPayload(BaseModel):
- click_id: str = Field(..., description="Click Id from partner referral link")
-
-
-class BillingResponse(RootModel[dict[str, Any]]):
- root: dict[str, Any]
-
-
class BillingInvoiceResponse(ResponseModel):
url: str
@@ -47,13 +37,12 @@ class BillingSubscriptionResponse(ResponseModel):
url: str
-register_schema_models(console_ns, SubscriptionQuery, PartnerTenantsPayload)
+register_schema_models(console_ns, SubscriptionQuery)
register_response_schema_models(
console_ns,
BillingOperationFailedErrorResponse,
BillingUnprocessableEntityErrorResponse,
BillingUnavailableErrorResponse,
- BillingResponse,
BillingInvoiceResponse,
BillingSubscriptionResponse,
)
@@ -120,30 +109,3 @@ class Invoices(Resource):
except BillingError as error:
raise to_billing_request_error(error) from error
return dump_response(BillingInvoiceResponse, data)
-
-
-@console_ns.route("/billing/partners/<string:partner_key>/tenants")
-class PartnerTenants(Resource):
- @console_ns.doc("sync_partner_tenants_bindings")
- @console_ns.doc(description="Sync partner tenants bindings")
- @console_ns.doc(params={"partner_key": "Partner key"})
- @console_ns.expect(console_ns.models[PartnerTenantsPayload.__name__])
- @console_ns.response(200, "Tenants synced to partner successfully", console_ns.models[BillingResponse.__name__])
- @console_ns.response(400, "Invalid partner information")
- @console_account_admission(editions=frozenset({DeploymentEdition.CLOUD}))
- @model_validate(PartnerTenantsPayload)
- def put(self, req_data: PartnerTenantsPayload, request_context: RequestContext, partner_key: str):
- try:
- click_id = req_data.click_id
- decoded_partner_key = base64.b64decode(partner_key).decode("utf-8")
- except Exception as e:
- raise BadRequest("Invalid partner_key") from e
-
- if not click_id or not decoded_partner_key:
- raise BadRequest("Invalid partner information")
-
- return application_services().partner_tenant_bindings.sync(
- account_id=request_context.account_id,
- partner_key=decoded_partner_key,
- click_id=click_id,
- )
diff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.py
index f86e4b10500..213d0e427e2 100644
--- a/api/extensions/ext_application_services.py
+++ b/api/extensions/ext_application_services.py
@@ -147,7 +147,6 @@ from services.oauth_device_application_service import (
)
from services.oauth_device_flow import DeviceFlowRedis
from services.oauth_server_service import OAUTH_ACCESS_TOKEN_EXPIRES_IN, OAuthServerService
-from services.partner_tenant_binding_service import PartnerTenantBindingService
from services.plugin_file_upload_gateway import ToolFilePluginUploadGateway
from services.plugin_file_upload_service import PluginFileUploadService
from services.recommended_app_catalog_gateway import (
@@ -282,7 +281,6 @@ class ApplicationServices:
installed_apps: InstalledAppServices
notifications: NotificationService
step_by_step_tour: StepByStepTourService
- partner_tenant_bindings: PartnerTenantBindingService
recommended_app_queries: RecommendedAppQueryService
recommended_app_packages: RecommendedAppPackageService
remote_files: RemoteFileService
@@ -641,9 +639,6 @@ def build_application_services(
enabled=dify_config.ENABLE_STEP_BY_STEP_TOUR,
rollout_started_at=dify_config.STEP_BY_STEP_TOUR_ROLLOUT_STARTED_AT,
),
- partner_tenant_bindings=PartnerTenantBindingService(
- sync_bindings=BillingService.sync_partner_tenants_bindings,
- ),
recommended_app_queries=recommended_app_queries,
recommended_app_packages=recommended_app_packages,
remote_files=remote_file_service,
diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md
index a06b2e6da02..2d2e98b7506 100644
--- a/api/openapi/markdown/console-openapi.md
+++ b/api/openapi/markdown/console-openapi.md
@@ -5006,28 +5006,6 @@ Delete an API key for an app
| 502 | Billing operation failed | **application/json**: [BillingOperationFailedErrorResponse](#billingoperationfailederrorresponse)<br> |
| 503 | Billing unavailable | **application/json**: [BillingUnavailableErrorResponse](#billingunavailableerrorresponse)<br> |
-### [PUT] /billing/partners/{partner_key}/tenants
-Sync partner tenants bindings
-
-#### Parameters
-
-| Name | Located in | Description | Required | Schema |
-| ---- | ---------- | ----------- | -------- | ------ |
-| partner_key | path | Partner key | Yes | string |
-
-#### Request Body
-
-| Required | Schema |
-| -------- | ------ |
-| Yes | **application/json**: [PartnerTenantsPayload](#partnertenantspayload)<br> |
-
-#### Responses
-
-| Code | Description | Schema |
-| ---- | ----------- | ------ |
-| 200 | Tenants synced to partner successfully | **application/json**: [BillingResponse](#billingresponse)<br> |
-| 400 | Invalid partner information | |
-
### [GET] /billing/subscription
#### Parameters
@@ -17178,12 +17156,6 @@ ExporleBanner status
| message | string | | Yes |
| status | integer | | Yes |
-#### BillingResponse
-
-| Name | Type | Description | Required |
-| ---- | ---- | ----------- | -------- |
-| BillingResponse | object | | |
-
#### BillingSubscriptionResponse
| Name | Type | Description | Required |
@@ -21617,12 +21589,6 @@ Enum class for parameter type.
| ---- | ---- | ----------- | -------- |
| data | [ string ] | | Yes |
-#### PartnerTenantsPayload
-
-| Name | Type | Description | Required |
-| ---- | ---- | ----------- | -------- |
-| click_id | string | Click Id from partner referral link | Yes |
-
#### PausedNodeResponse
| Name | Type | Description | Required |
diff --git a/api/services/billing_service.py b/api/services/billing_service.py
index c16f5b5142c..f6e66a08c38 100644
--- a/api/services/billing_service.py
+++ b/api/services/billing_service.py
@@ -608,11 +608,6 @@ class BillingService:
def clean_billing_info_cache(cls, tenant_id: str) -> None:
redis_client.delete(f"tenant:{tenant_id}:billing_info")
- @classmethod
- def sync_partner_tenants_bindings(cls, account_id: str, partner_key: str, click_id: str) -> dict[str, Any]:
- payload = {"account_id": account_id, "click_id": click_id}
- return cls._send_request("PUT", f"/partners/{partner_key}/tenants", json=payload)
-
@classmethod
def get_plan_bulk(cls, tenant_ids: Sequence[str]) -> dict[str, SubscriptionPlan]:
"""
diff --git a/api/services/partner_tenant_binding_service.py b/api/services/partner_tenant_binding_service.py
deleted file mode 100644
index 07f0e31b797..00000000000
--- a/api/services/partner_tenant_binding_service.py
+++ /dev/null
@@ -1,12 +0,0 @@
-"""Application service for partner tenant bindings."""
-
-from collections.abc import Callable
-from typing import Any
-
-
-class PartnerTenantBindingService:
- def __init__(self, *, sync_bindings: Callable[[str, str, str], dict[str, Any]]) -> None:
- self._sync_bindings = sync_bindings
-
- def sync(self, *, account_id: str, partner_key: str, click_id: str) -> dict[str, Any]:
- return self._sync_bindings(account_id, partner_key, click_id)
diff --git a/api/tests/unit_tests/controllers/console/billing/test_billing.py b/api/tests/unit_tests/controllers/console/billing/test_billing.py
index b69671a598d..ea509ee8f03 100644
--- a/api/tests/unit_tests/controllers/console/billing/test_billing.py
+++ b/api/tests/unit_tests/controllers/console/billing/test_billing.py
@@ -1,5 +1,3 @@
-import base64
-import json
from collections.abc import Iterator
from inspect import unwrap
from types import SimpleNamespace
@@ -7,24 +5,18 @@ from unittest.mock import MagicMock, patch
import pytest
from flask import Flask
-from sqlalchemy.orm import Session
-from werkzeug.exceptions import BadRequest, UnprocessableEntity
-from controllers.console import wraps as console_wraps
-from controllers.console.billing.billing import Invoices, PartnerTenants, Subscription, SubscriptionQuery
+from controllers.console.billing.billing import Invoices, Subscription, SubscriptionQuery
from controllers.console.billing.error import (
BillingOperationFailedError,
BillingUnavailableError,
)
-from enums import CloudPlan, DeploymentEdition
+from enums import CloudPlan
from machinery.context import RequestContext
-from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole
-from models.model import DifySetup
from services.errors.billing import (
BillingUpstreamInvalidResponseError,
BillingUpstreamUnavailableError,
)
-from tests.unit_tests.config_override import config_overrides_context
class TestBillingPortal:
@@ -132,248 +124,3 @@ class TestBillingPortal:
"message": "We couldn't complete this request. Please try again. If the problem persists, contact support.",
"status": 502,
}
-
-
- "sqlite_session",
- [(DifySetup, Account, Tenant, TenantAccountJoin)],
- indirect=True,
-)
-class TestPartnerTenants:
- """Unit tests for PartnerTenants controller."""
-
- @pytest.fixture
- def app(self):
- """Create Flask app for testing."""
- app = Flask(__name__)
- app.config["TESTING"] = True
- app.config["SECRET_KEY"] = "test-secret-key"
- return app
-
- @pytest.fixture
- def mock_account(self, sqlite_session: Session):
- """Persist an initialized account with an owner workspace membership."""
- tenant = Tenant(name="Billing Tenant")
- account = Account(name="Billing User", email="[email protected]")
- sqlite_session.add_all([tenant, account])
- sqlite_session.flush()
- sqlite_session.add_all(
- [
- TenantAccountJoin(
- tenant_id=tenant.id,
- account_id=account.id,
- current=True,
- role=TenantAccountRole.OWNER,
- invited_by=None,
- ),
- DifySetup(version="test"),
- ]
- )
- sqlite_session.commit()
- account._current_tenant = tenant
- sqlite_session.expunge(account)
- return account
-
- @pytest.fixture
- def partner_tenant_bindings(self):
- service = MagicMock()
- with patch(
- "controllers.console.billing.billing.application_services",
- return_value=SimpleNamespace(partner_tenant_bindings=service),
- ):
- yield service
-
- @pytest.fixture
- def mock_decorators(self, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session):
- """Keep authentication mocked while the setup guard uses SQLite."""
- console_wraps._is_setup_completed.reset_success()
- monkeypatch.setattr(console_wraps.db, "session", sqlite_session)
- with (
- config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD, LOGIN_DISABLED=False),
- patch("libs.login.check_csrf_token") as mock_csrf,
- ):
- mock_csrf.return_value = None
- yield mock_csrf
- console_wraps._is_setup_completed.reset_success()
-
- def test_put_success(self, app: Flask, mock_account, partner_tenant_bindings, mock_decorators):
- """Test successful partner tenants bindings sync."""
- # Arrange
- partner_key_encoded = base64.b64encode(b"partner-key-123").decode("utf-8")
- click_id = "click-id-789"
- expected_response = {"result": "success", "data": {"synced": True}}
-
- partner_tenant_bindings.sync.return_value = expected_response
-
- with app.test_request_context(
- method="PUT",
- json={"click_id": click_id},
- path=f"/billing/partners/{partner_key_encoded}/tenants",
- ):
- with (
- patch(
- "controllers.console.wraps.current_account_with_tenant",
- return_value=(mock_account, mock_account.current_tenant_id),
- ),
- patch("libs.login._get_user", return_value=mock_account),
- ):
- resource = PartnerTenants()
- result = resource.put(partner_key_encoded)
-
- # Assert
- assert result == expected_response
- partner_tenant_bindings.sync.assert_called_once_with(
- account_id=mock_account.id,
- partner_key="partner-key-123",
- click_id=click_id,
- )
-
- def test_put_invalid_partner_key_base64(self, app: Flask, mock_account, partner_tenant_bindings, mock_decorators):
- """Test that invalid base64 partner_key raises BadRequest."""
- # Arrange
- invalid_partner_key = "invalid-base64-!@#$"
- click_id = "click-id-789"
-
- with app.test_request_context(
- method="PUT",
- json={"click_id": click_id},
- path=f"/billing/partners/{invalid_partner_key}/tenants",
- ):
- with (
- patch(
- "controllers.console.wraps.current_account_with_tenant",
- return_value=(mock_account, mock_account.current_tenant_id),
- ),
- patch("libs.login._get_user", return_value=mock_account),
- ):
- resource = PartnerTenants()
-
- # Act & Assert
- with pytest.raises(BadRequest) as exc_info:
- resource.put(invalid_partner_key)
- assert "Invalid partner_key" in str(exc_info.value)
-
- def test_put_missing_click_id(self, app: Flask, mock_account, partner_tenant_bindings, mock_decorators):
- """Test that missing click_id raises UnprocessableEntity (422)."""
- # Arrange
- partner_key_encoded = base64.b64encode(b"partner-key-123").decode("utf-8")
-
- with app.test_request_context(
- method="PUT",
- json={},
- path=f"/billing/partners/{partner_key_encoded}/tenants",
- ):
- with (
- patch(
- "controllers.console.wraps.current_account_with_tenant",
- return_value=(mock_account, mock_account.current_tenant_id),
- ),
- patch("libs.login._get_user", return_value=mock_account),
- ):
- resource = PartnerTenants()
-
- # Act & Assert
- # Validation should raise UnprocessableEntity (422) for missing required field
- with pytest.raises(UnprocessableEntity):
- resource.put(partner_key_encoded)
-
- def test_put_billing_service_json_decode_error(
- self, app: Flask, mock_account, partner_tenant_bindings, mock_decorators
- ):
- """Test handling of billing service JSON decode error.
-
- When billing service returns non-200 status code with invalid JSON response,
- response.json() raises JSONDecodeError. This exception propagates to the controller
- and should be handled by the global error handler (handle_general_exception),
- which returns a 500 status code with error details.
-
- Note: In unit tests, when directly calling resource.put(), the exception is raised
- directly. In actual Flask application, the error handler would catch it and return
- a 500 response with JSON: {"code": "unknown", "message": "...", "status": 500}
- """
- # Arrange
- partner_key_encoded = base64.b64encode(b"partner-key-123").decode("utf-8")
- click_id = "click-id-789"
-
- # Simulate JSON decode error when billing service returns invalid JSON
- # This happens when billing service returns non-200 with empty/invalid response body
- json_decode_error = json.JSONDecodeError("Expecting value", "", 0)
- partner_tenant_bindings.sync.side_effect = json_decode_error
-
- with app.test_request_context(
- method="PUT",
- json={"click_id": click_id},
- path=f"/billing/partners/{partner_key_encoded}/tenants",
- ):
- with (
- patch(
- "controllers.console.wraps.current_account_with_tenant",
- return_value=(mock_account, mock_account.current_tenant_id),
- ),
- patch("libs.login._get_user", return_value=mock_account),
- ):
- resource = PartnerTenants()
-
- # Act & Assert
- # JSONDecodeError will be raised from the controller
- # In actual Flask app, this would be caught by handle_general_exception
- # which returns: {"code": "unknown", "message": str(e), "status": 500}
- with pytest.raises(json.JSONDecodeError) as exc_info:
- resource.put(partner_key_encoded)
-
- # Verify the exception is JSONDecodeError
- assert isinstance(exc_info.value, json.JSONDecodeError)
- assert "Expecting value" in str(exc_info.value)
-
- def test_put_empty_click_id(self, app: Flask, mock_account, partner_tenant_bindings, mock_decorators):
- """Test that empty click_id raises BadRequest."""
- # Arrange
- partner_key_encoded = base64.b64encode(b"partner-key-123").decode("utf-8")
- click_id = ""
-
- with app.test_request_context(
- method="PUT",
- json={"click_id": click_id},
- path=f"/billing/partners/{partner_key_encoded}/tenants",
- ):
- with (
- patch(
- "controllers.console.wraps.current_account_with_tenant",
- return_value=(mock_account, mock_account.current_tenant_id),
- ),
- patch("libs.login._get_user", return_value=mock_account),
- ):
- resource = PartnerTenants()
-
- # Act & Assert
- with pytest.raises(BadRequest) as exc_info:
- resource.put(partner_key_encoded)
- assert "Invalid partner information" in str(exc_info.value)
-
- def test_put_empty_partner_key_after_decode(
- self, app: Flask, mock_account, partner_tenant_bindings, mock_decorators
- ):
- """Test that empty partner_key after decode raises BadRequest."""
- # Arrange
- # Base64 encode an empty string
- empty_partner_key_encoded = base64.b64encode(b"").decode("utf-8")
- click_id = "click-id-789"
-
- with app.test_request_context(
- method="PUT",
- json={"click_id": click_id},
- path=f"/billing/partners/{empty_partner_key_encoded}/tenants",
- ):
- with (
- patch(
- "controllers.console.wraps.current_account_with_tenant",
- return_value=(mock_account, mock_account.current_tenant_id),
- ),
- patch("libs.login._get_user", return_value=mock_account),
- ):
- resource = PartnerTenants()
-
- # Act & Assert
- with pytest.raises(BadRequest) as exc_info:
- resource.put(empty_partner_key_encoded)
- assert "Invalid partner information" in str(exc_info.value)
diff --git a/api/tests/unit_tests/extensions/test_ext_application_services.py b/api/tests/unit_tests/extensions/test_ext_application_services.py
index f2d8182c471..c2acd4fe0e4 100644
--- a/api/tests/unit_tests/extensions/test_ext_application_services.py
+++ b/api/tests/unit_tests/extensions/test_ext_application_services.py
@@ -132,7 +132,6 @@ from services.knowledge.indexing.estimate import IndexingEstimateApplicationServ
from services.knowledge.segments.application import DatasetSegmentApplicationService
from services.message_file_preview_service import MessageFilePreviewService
from services.oauth_device_application_service import OAuthDeviceApplicationService
-from services.partner_tenant_binding_service import PartnerTenantBindingService
from services.plugin_file_upload_gateway import ToolFilePluginUploadGateway
from services.plugin_file_upload_service import PluginFileUploadService
from services.retention.workflow_run.archive_download_task_cache import WorkflowRunArchiveDownloadTaskCache
@@ -629,11 +628,6 @@ def test_build_application_services_wires_billing_service(
"get_invoices",
return_value={"url": "https://billing.example.com/portal"},
) as get_invoices,
- patch.object(
- BillingService,
- "sync_partner_tenants_bindings",
- return_value={"result": "success"},
- ) as sync_partner_tenants_bindings,
):
services = ext_application_services.build_application_services(
database_client=sqlite_session_factory,
@@ -655,15 +649,8 @@ def test_build_application_services_wires_billing_service(
interval="month",
) == {"url": "https://billing.example.com/checkout"}
assert services.billing_portal.get_invoices(request_context) == {"url": "https://billing.example.com/portal"}
- assert isinstance(services.partner_tenant_bindings, PartnerTenantBindingService)
- assert services.partner_tenant_bindings.sync(
- account_id="account-1",
- partner_key="partner-key",
- click_id="click-1",
- ) == {"result": "success"}
get_subscription.assert_called_once_with("professional", "month", "[email protected]", "workspace-1")
get_invoices.assert_called_once_with("[email protected]", "workspace-1")
- sync_partner_tenants_bindings.assert_called_once_with("account-1", "partner-key", "click-1")
def test_build_application_services_wires_compliance_downloads(
diff --git a/api/tests/unit_tests/services/test_billing_service.py b/api/tests/unit_tests/services/test_billing_service.py
index eaf116bf0f2..762d7a71dcc 100644
--- a/api/tests/unit_tests/services/test_billing_service.py
+++ b/api/tests/unit_tests/services/test_billing_service.py
@@ -1322,39 +1322,6 @@ class TestBillingServiceCacheManagement:
mock_redis_client.delete.assert_called_once_with(expected_key)
-class TestBillingServicePartnerIntegration:
- """Unit tests for partner integration features.
-
- Tests cover:
- - Partner tenant binding synchronization
- - Click ID tracking
- """
-
- @pytest.fixture
- def mock_send_request(self):
- """Mock _send_request method."""
- with patch.object(BillingService, "_send_request") as mock:
- yield mock
-
- def test_sync_partner_tenants_bindings(self, mock_send_request):
- """Test syncing partner tenant bindings."""
- # Arrange
- account_id = "account-123"
- partner_key = "partner-xyz"
- click_id = "click-789"
- expected_response = {"message": "Successfully synced partner tenants"}
- mock_send_request.return_value = expected_response
-
- # Act
- result = BillingService.sync_partner_tenants_bindings(account_id, partner_key, click_id)
-
- # Assert
- assert result == expected_response
- mock_send_request.assert_called_once_with(
- "PUT", f"/partners/{partner_key}/tenants", json={"account_id": account_id, "click_id": click_id}
- )
-
-
class TestBillingServiceEdgeCases:
"""Unit tests for edge cases and error scenarios.
diff --git a/packages/contracts/generated/api/console/billing/orpc.gen.ts b/packages/contracts/generated/api/console/billing/orpc.gen.ts
index 9d0dbb85b54..c7842c265e0 100644
--- a/packages/contracts/generated/api/console/billing/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/billing/orpc.gen.ts
@@ -6,9 +6,6 @@ import {
zGetBillingInvoicesResponse,
zGetBillingSubscriptionQuery,
zGetBillingSubscriptionResponse,
- zPutBillingPartnersByPartnerKeyTenantsBody,
- zPutBillingPartnersByPartnerKeyTenantsPath,
- zPutBillingPartnersByPartnerKeyTenantsResponse,
} from './zod.gen.ts'
export const get = oc
@@ -25,38 +22,6 @@ export const invoices = {
get,
}
-/**
- * Sync partner tenants bindings
- */
-export const put = oc
- .route({
- description: 'Sync partner tenants bindings',
- inputStructure: 'detailed',
- method: 'PUT',
- operationId: 'putBillingPartnersByPartnerKeyTenants',
- path: '/billing/partners/{partner_key}/tenants',
- tags: ['console'],
- })
- .input(
- z.object({
- body: zPutBillingPartnersByPartnerKeyTenantsBody,
- params: zPutBillingPartnersByPartnerKeyTenantsPath,
- }),
- )
- .output(zPutBillingPartnersByPartnerKeyTenantsResponse)
-
-export const tenants = {
- put,
-}
-
-export const byPartnerKey = {
- tenants,
-}
-
-export const partners = {
- byPartnerKey,
-}
-
export const get2 = oc
.route({
inputStructure: 'detailed',
@@ -74,7 +39,6 @@ export const subscription = {
export const billing = {
invoices,
- partners,
subscription,
}
diff --git a/packages/contracts/generated/api/console/billing/types.gen.ts b/packages/contracts/generated/api/console/billing/types.gen.ts
index 7dd614bdcb1..3e1ced16781 100644
--- a/packages/contracts/generated/api/console/billing/types.gen.ts
+++ b/packages/contracts/generated/api/console/billing/types.gen.ts
@@ -20,14 +20,6 @@ export type BillingUnavailableErrorResponse = {
status: 503
}
-export type PartnerTenantsPayload = {
- click_id: string
-}
-
-export type BillingResponse = {
- [key: string]: unknown
-}
-
export type BillingSubscriptionResponse = {
url: string
}
@@ -60,26 +52,6 @@ export type GetBillingInvoicesResponses = {
export type GetBillingInvoicesResponse =
GetBillingInvoicesResponses[keyof GetBillingInvoicesResponses]
-export type PutBillingPartnersByPartnerKeyTenantsData = {
- body: PartnerTenantsPayload
- path: {
- partner_key: string
- }
- query?: never
- url: '/billing/partners/{partner_key}/tenants'
-}
-
-export type PutBillingPartnersByPartnerKeyTenantsErrors = {
- 400: unknown
-}
-
-export type PutBillingPartnersByPartnerKeyTenantsResponses = {
- 200: BillingResponse
-}
-
-export type PutBillingPartnersByPartnerKeyTenantsResponse =
- PutBillingPartnersByPartnerKeyTenantsResponses[keyof PutBillingPartnersByPartnerKeyTenantsResponses]
-
export type GetBillingSubscriptionData = {
body?: never
path?: never
diff --git a/packages/contracts/generated/api/console/billing/zod.gen.ts b/packages/contracts/generated/api/console/billing/zod.gen.ts
index 2e0ce6887ed..150bfd4028c 100644
--- a/packages/contracts/generated/api/console/billing/zod.gen.ts
+++ b/packages/contracts/generated/api/console/billing/zod.gen.ts
@@ -27,18 +27,6 @@ export const zBillingUnavailableErrorResponse = z.object({
status: z.literal(503),
})
-/**
- * PartnerTenantsPayload
- */
-export const zPartnerTenantsPayload = z.object({
- click_id: z.string(),
-})
-
-/**
- * BillingResponse
- */
-export const zBillingResponse = z.record(z.string(), z.unknown())
-
/**
* BillingSubscriptionResponse
*/
@@ -60,17 +48,6 @@ export const zBillingUnprocessableEntityErrorResponse = z.object({
*/
export const zGetBillingInvoicesResponse = zBillingInvoiceResponse
-export const zPutBillingPartnersByPartnerKeyTenantsBody = zPartnerTenantsPayload
-
-export const zPutBillingPartnersByPartnerKeyTenantsPath = z.object({
- partner_key: z.string(),
-})
-
-/**
- * Tenants synced to partner successfully
- */
-export const zPutBillingPartnersByPartnerKeyTenantsResponse = zBillingResponse
-
export const zGetBillingSubscriptionQuery = z.object({
interval: z.enum(['month', 'year']),
plan: z.enum(['professional', 'team']),
diff --git a/web/__tests__/billing/partner-stack-flow.test.tsx b/web/__tests__/billing/partner-stack-flow.test.tsx
deleted file mode 100644
index 3db886f76da..00000000000
--- a/web/__tests__/billing/partner-stack-flow.test.tsx
+++ /dev/null
@@ -1,324 +0,0 @@
-/**
- * Integration test: Partner Stack Flow
- *
- * Tests the PartnerStack integration:
- * PartnerStack component → usePSInfo hook → cookie management → bind API call
- *
- * Covers URL param reading, cookie persistence, API bind on mount,
- * cookie cleanup after successful bind, and error handling for 400 status.
- */
-import { act, cleanup, waitFor } from '@testing-library/react'
-import Cookies from 'js-cookie'
-import * as React from 'react'
-import usePSInfo from '@/app/components/billing/partner-stack/use-ps-info'
-import { PARTNER_STACK_CONFIG } from '@/config'
-import { renderHookWithConsoleQuery, renderWithConsoleQuery } from '@/test/console/query-data'
-
-const render = (ui: React.ReactElement) =>
- renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'CLOUD' } })
-
-const renderPSInfo = () =>
- renderHookWithConsoleQuery(() => usePSInfo(), {
- systemFeatures: { deployment_edition: 'CLOUD' },
- })
-
-// ─── Mock state ──────────────────────────────────────────────────────────────
-let mockSearchParams = new URLSearchParams()
-const mocks = vi.hoisted(() => ({
- request: vi.fn(),
-}))
-
-// ─── Module mocks ────────────────────────────────────────────────────────────
-vi.mock('@/next/navigation', () => ({
- useSearchParams: () => mockSearchParams,
- useRouter: () => ({ push: vi.fn() }),
- usePathname: () => '/',
-}))
-
-vi.mock('@/service/base', () => ({
- request: (...args: unknown[]) => mocks.request(...args),
- sseGeneratorPost: vi.fn(),
-}))
-
-vi.mock('@/config', async (importOriginal) => {
- const actual = await importOriginal<Record<string, unknown>>()
- return {
- ...actual,
- PARTNER_STACK_CONFIG: {
- cookieName: 'partner_stack_info',
- saveCookieDays: 90,
- },
- }
-})
-
-// ─── Cookie helpers ──────────────────────────────────────────────────────────
-const getCookieData = () => {
- const raw = Cookies.get(PARTNER_STACK_CONFIG.cookieName)
- if (!raw) return null
- try {
- return JSON.parse(raw)
- } catch {
- return null
- }
-}
-
-const setCookieData = (data: Record<string, string>) => {
- Cookies.set(PARTNER_STACK_CONFIG.cookieName, JSON.stringify(data))
-}
-
-const clearCookie = () => {
- Cookies.remove(PARTNER_STACK_CONFIG.cookieName)
-}
-
-const getBindRequest = () => mocks.request.mock.calls[0]?.[2]?.request as Request | undefined
-
-// ═══════════════════════════════════════════════════════════════════════════════
-describe('Partner Stack Flow', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- cleanup()
- clearCookie()
- mockSearchParams = new URLSearchParams()
- mocks.request.mockResolvedValue(Response.json({}))
- })
-
- // ─── 1. URL Param Reading ───────────────────────────────────────────────
- describe('URL param reading', () => {
- it('should read ps_partner_key and ps_xid from URL search params', () => {
- mockSearchParams = new URLSearchParams({
- ps_partner_key: 'partner-123',
- ps_xid: 'click-456',
- })
-
- const { result } = renderPSInfo()
-
- expect(result.current.psPartnerKey).toBe('partner-123')
- expect(result.current.psClickId).toBe('click-456')
- })
-
- it('should fall back to cookie when URL params are not present', () => {
- setCookieData({ partnerKey: 'cookie-partner', clickId: 'cookie-click' })
-
- const { result } = renderPSInfo()
-
- expect(result.current.psPartnerKey).toBe('cookie-partner')
- expect(result.current.psClickId).toBe('cookie-click')
- })
-
- it('should prefer URL params over cookie values', () => {
- setCookieData({ partnerKey: 'cookie-partner', clickId: 'cookie-click' })
- mockSearchParams = new URLSearchParams({
- ps_partner_key: 'url-partner',
- ps_xid: 'url-click',
- })
-
- const { result } = renderPSInfo()
-
- expect(result.current.psPartnerKey).toBe('url-partner')
- expect(result.current.psClickId).toBe('url-click')
- })
-
- it('should return null for both values when no params and no cookie', () => {
- const { result } = renderPSInfo()
-
- expect(result.current.psPartnerKey).toBeUndefined()
- expect(result.current.psClickId).toBeUndefined()
- })
- })
-
- // ─── 2. Cookie Persistence (saveOrUpdate) ───────────────────────────────
- describe('Cookie persistence via saveOrUpdate', () => {
- it('should save PS info to cookie when URL params provide new values', () => {
- mockSearchParams = new URLSearchParams({
- ps_partner_key: 'new-partner',
- ps_xid: 'new-click',
- })
-
- const { result } = renderPSInfo()
- act(() => result.current.saveOrUpdate())
-
- const cookieData = getCookieData()
- expect(cookieData).toEqual({
- partnerKey: 'new-partner',
- clickId: 'new-click',
- })
- })
-
- it('should not update cookie when values have not changed', () => {
- setCookieData({ partnerKey: 'same-partner', clickId: 'same-click' })
- mockSearchParams = new URLSearchParams({
- ps_partner_key: 'same-partner',
- ps_xid: 'same-click',
- })
-
- const cookieSetSpy = vi.spyOn(Cookies, 'set')
- const { result } = renderPSInfo()
- act(() => result.current.saveOrUpdate())
-
- // Should not call set because values haven't changed
- expect(cookieSetSpy).not.toHaveBeenCalled()
- cookieSetSpy.mockRestore()
- })
-
- it('should not save to cookie when partner key is missing', () => {
- mockSearchParams = new URLSearchParams({
- ps_xid: 'click-only',
- })
-
- const cookieSetSpy = vi.spyOn(Cookies, 'set')
- const { result } = renderPSInfo()
- act(() => result.current.saveOrUpdate())
-
- expect(cookieSetSpy).not.toHaveBeenCalled()
- cookieSetSpy.mockRestore()
- })
-
- it('should not save to cookie when click ID is missing', () => {
- mockSearchParams = new URLSearchParams({
- ps_partner_key: 'partner-only',
- })
-
- const cookieSetSpy = vi.spyOn(Cookies, 'set')
- const { result } = renderPSInfo()
- act(() => result.current.saveOrUpdate())
-
- expect(cookieSetSpy).not.toHaveBeenCalled()
- cookieSetSpy.mockRestore()
- })
- })
-
- // ─── 3. Bind API Flow ──────────────────────────────────────────────────
- describe('Bind API flow', () => {
- it('should bind the partner key and click ID through the billing API', async () => {
- mockSearchParams = new URLSearchParams({
- ps_partner_key: 'bind-partner',
- ps_xid: 'bind-click',
- })
-
- const { result } = renderPSInfo()
- await act(async () => {
- await result.current.bind()
- })
-
- expect(mocks.request).toHaveBeenCalledTimes(1)
- const request = getBindRequest()
- expect(request?.method).toBe('PUT')
- expect(request?.url).toContain('/billing/partners/bind-partner/tenants')
- await expect(request?.clone().json()).resolves.toEqual({ click_id: 'bind-click' })
- })
-
- it('should remove cookie after successful bind', async () => {
- setCookieData({ partnerKey: 'rm-partner', clickId: 'rm-click' })
- mockSearchParams = new URLSearchParams({
- ps_partner_key: 'rm-partner',
- ps_xid: 'rm-click',
- })
-
- const { result } = renderPSInfo()
- await act(async () => {
- await result.current.bind()
- })
-
- // Cookie should be removed after successful bind
- expect(Cookies.get(PARTNER_STACK_CONFIG.cookieName)).toBeUndefined()
- })
-
- it('should remove cookie on 400 error (already bound)', async () => {
- mocks.request.mockRejectedValue({ status: 400 })
- setCookieData({ partnerKey: 'err-partner', clickId: 'err-click' })
- mockSearchParams = new URLSearchParams({
- ps_partner_key: 'err-partner',
- ps_xid: 'err-click',
- })
-
- const { result } = renderPSInfo()
- await act(async () => {
- await result.current.bind()
- })
-
- // Cookie should be removed even on 400
- expect(Cookies.get(PARTNER_STACK_CONFIG.cookieName)).toBeUndefined()
- })
-
- it('should not remove cookie on non-400 errors', async () => {
- mocks.request.mockRejectedValue({ status: 500 })
- setCookieData({ partnerKey: 'keep-partner', clickId: 'keep-click' })
- mockSearchParams = new URLSearchParams({
- ps_partner_key: 'keep-partner',
- ps_xid: 'keep-click',
- })
-
- const { result } = renderPSInfo()
- await act(async () => {
- await result.current.bind()
- })
-
- // Cookie should still exist for non-400 errors
- const cookieData = getCookieData()
- expect(cookieData).toBeTruthy()
- })
-
- it('should not call bind when partner key is missing', async () => {
- mockSearchParams = new URLSearchParams({
- ps_xid: 'click-only',
- })
-
- const { result } = renderPSInfo()
- await act(async () => {
- await result.current.bind()
- })
-
- expect(mocks.request).not.toHaveBeenCalled()
- })
-
- it('should not call bind a second time (idempotency)', async () => {
- mockSearchParams = new URLSearchParams({
- ps_partner_key: 'partner-once',
- ps_xid: 'click-once',
- })
-
- const { result } = renderPSInfo()
-
- // First bind
- await act(async () => {
- await result.current.bind()
- })
- expect(mocks.request).toHaveBeenCalledTimes(1)
-
- // Second bind should be skipped (hasBind = true)
- await act(async () => {
- await result.current.bind()
- })
- expect(mocks.request).toHaveBeenCalledTimes(1)
- })
- })
-
- // ─── 4. PartnerStack Component Mount ────────────────────────────────────
- describe('PartnerStack component mount behavior', () => {
- it('should call saveOrUpdate and bind on mount', async () => {
- mockSearchParams = new URLSearchParams({
- ps_partner_key: 'mount-partner',
- ps_xid: 'mount-click',
- })
-
- // Use lazy import so the mocks are applied
- const { default: PartnerStack } = await import('@/app/components/billing/partner-stack')
-
- render(<PartnerStack />)
-
- await waitFor(() => {
- expect(mocks.request).toHaveBeenCalledTimes(1)
- expect(getBindRequest()?.url).toContain('/billing/partners/mount-partner/tenants')
- expect(Cookies.get(PARTNER_STACK_CONFIG.cookieName)).toBeUndefined()
- })
- })
-
- it('should render nothing (return null)', async () => {
- const { default: PartnerStack } = await import('@/app/components/billing/partner-stack')
-
- const { container } = render(<PartnerStack />)
-
- expect(container.innerHTML).toBe('')
- })
- })
-})
diff --git a/web/app/(commonLayout)/global-mounts.tsx b/web/app/(commonLayout)/global-mounts.tsx
index b71fd2d768f..08749435f80 100644
--- a/web/app/(commonLayout)/global-mounts.tsx
+++ b/web/app/(commonLayout)/global-mounts.tsx
@@ -8,7 +8,6 @@ const InSiteMessageNotification = dynamic(
() => import('@/app/components/app/in-site-message/notification'),
{ ssr: false },
)
-const PartnerStack = dynamic(() => import('@/app/components/billing/partner-stack'), { ssr: false })
const ReadmePanel = dynamic(() => import('@/app/components/plugins/readme-panel'), { ssr: false })
const WorkflowGeneratorMount = dynamic(
() => import('@/app/components/workflow/workflow-generator/mount'),
@@ -23,7 +22,6 @@ export function CommonLayoutGlobalMounts() {
return (
<>
<InSiteMessageNotification />
- <PartnerStack />
<ReadmePanel />
<GotoAnything />
<WorkflowGeneratorMount />
diff --git a/web/app/components/billing/partner-stack/__tests__/cookie-recorder.spec.tsx b/web/app/components/billing/partner-stack/__tests__/cookie-recorder.spec.tsx
deleted file mode 100644
index 0d39887f0f4..00000000000
--- a/web/app/components/billing/partner-stack/__tests__/cookie-recorder.spec.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { waitFor } from '@testing-library/react'
-import { renderWithConsoleQuery } from '@/test/console/query-data'
-import { PartnerStackCookieRecorder } from '../cookie-recorder'
-
-const mocks = vi.hoisted(() => ({
- saveOrUpdate: vi.fn(),
-}))
-
-vi.mock('../use-ps-info', () => ({
- default: () => ({ saveOrUpdate: mocks.saveOrUpdate }),
-}))
-
-describe('PartnerStackCookieRecorder', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- it('records PartnerStack cookies in Cloud deployments', async () => {
- renderWithConsoleQuery(<PartnerStackCookieRecorder />, {
- systemFeatures: { deployment_edition: 'CLOUD' },
- })
-
- await waitFor(() => expect(mocks.saveOrUpdate).toHaveBeenCalledTimes(1))
- })
-
- it('does not record PartnerStack cookies outside Cloud deployments', () => {
- renderWithConsoleQuery(<PartnerStackCookieRecorder />, {
- systemFeatures: { deployment_edition: 'COMMUNITY' },
- })
-
- expect(mocks.saveOrUpdate).not.toHaveBeenCalled()
- })
-})
diff --git a/web/app/components/billing/partner-stack/cookie-recorder.tsx b/web/app/components/billing/partner-stack/cookie-recorder.tsx
deleted file mode 100644
index 06439bd3671..00000000000
--- a/web/app/components/billing/partner-stack/cookie-recorder.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-'use client'
-
-import { useSuspenseQuery } from '@tanstack/react-query'
-import { useEffect } from 'react'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
-import usePSInfo from './use-ps-info'
-
-export function PartnerStackCookieRecorder() {
- const { data: deploymentEdition } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: ({ deployment_edition }) => deployment_edition,
- })
-
- if (deploymentEdition !== 'CLOUD') return null
-
- return <CookieRecorder />
-}
-
-function CookieRecorder() {
- const { saveOrUpdate } = usePSInfo()
-
- useEffect(() => {
- saveOrUpdate()
- }, [saveOrUpdate])
-
- return null
-}
diff --git a/web/app/components/billing/partner-stack/index.tsx b/web/app/components/billing/partner-stack/index.tsx
deleted file mode 100644
index 4db93236acd..00000000000
--- a/web/app/components/billing/partner-stack/index.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-'use client'
-import type { FC } from 'react'
-import { useSuspenseQuery } from '@tanstack/react-query'
-import * as React from 'react'
-import { useEffect } from 'react'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
-import usePSInfo from './use-ps-info'
-
-const PartnerStack: FC = () => {
- const { data: deploymentEdition } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: ({ deployment_edition }) => deployment_edition,
- })
- const isCloudEdition = deploymentEdition === 'CLOUD'
- const { saveOrUpdate, bind } = usePSInfo()
- const hasProcessedRef = React.useRef(false)
- useEffect(() => {
- if (!isCloudEdition || hasProcessedRef.current) return
- hasProcessedRef.current = true
- // Save PartnerStack info in cookie first. Because if user hasn't logged in, redirecting to login page would cause lose the partnerStack info in URL.
- saveOrUpdate()
- // bind PartnerStack info after user logged in
- bind()
- }, [bind, isCloudEdition, saveOrUpdate])
-
- return null
-}
-export default React.memo(PartnerStack)
diff --git a/web/app/components/billing/partner-stack/use-ps-info.ts b/web/app/components/billing/partner-stack/use-ps-info.ts
deleted file mode 100644
index d961569de99..00000000000
--- a/web/app/components/billing/partner-stack/use-ps-info.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { useMutation } from '@tanstack/react-query'
-import { useBoolean } from 'ahooks'
-import Cookies from 'js-cookie'
-import { useCallback } from 'react'
-import { PARTNER_STACK_CONFIG } from '@/config'
-import { useSearchParams } from '@/next/navigation'
-import { consoleQuery } from '@/service/console'
-
-const usePSInfo = () => {
- const searchParams = useSearchParams()
- const psInfoInCookie = (() => {
- try {
- return JSON.parse(Cookies.get(PARTNER_STACK_CONFIG.cookieName) || '{}')
- } catch (e) {
- console.error('Failed to parse partner stack info from cookie:', e)
- return {}
- }
- })()
- const psPartnerKey = searchParams.get('ps_partner_key') || psInfoInCookie?.partnerKey
- const psClickId = searchParams.get('ps_xid') || psInfoInCookie?.clickId
- const isPSChanged =
- psInfoInCookie?.partnerKey !== psPartnerKey || psInfoInCookie?.clickId !== psClickId
- const [hasBind, { setTrue: setBind }] = useBoolean(false)
- const { mutateAsync: bindPartnerStackInfo } = useMutation(
- consoleQuery.billing.partners.byPartnerKey.tenants.put.mutationOptions(),
- )
- // Save to top domain. cloud.dify.ai => .dify.ai
- const domain = globalThis.location?.hostname.replace('cloud', '')
-
- const saveOrUpdate = useCallback(() => {
- if (!psPartnerKey || !psClickId) return
- if (!isPSChanged) return
- Cookies.set(
- PARTNER_STACK_CONFIG.cookieName,
- JSON.stringify({
- partnerKey: psPartnerKey,
- clickId: psClickId,
- }),
- {
- expires: PARTNER_STACK_CONFIG.saveCookieDays,
- path: '/',
- domain,
- },
- )
- }, [psPartnerKey, psClickId, isPSChanged, domain])
-
- const bind = useCallback(async () => {
- if (psPartnerKey && psClickId && !hasBind) {
- let shouldRemoveCookie = false
- try {
- await bindPartnerStackInfo({
- params: { partner_key: psPartnerKey },
- body: { click_id: psClickId },
- })
- shouldRemoveCookie = true
- } catch (error: unknown) {
- if ((error as { status: number })?.status === 400) shouldRemoveCookie = true
- }
- if (shouldRemoveCookie) Cookies.remove(PARTNER_STACK_CONFIG.cookieName, { path: '/', domain })
- setBind()
- }
- }, [psPartnerKey, psClickId, hasBind, domain, setBind, bindPartnerStackInfo])
- return {
- psPartnerKey,
- psClickId,
- saveOrUpdate,
- bind,
- }
-}
-export default usePSInfo
diff --git a/web/app/layout.tsx b/web/app/layout.tsx
index 810ba720edd..cc7e3e59c66 100644
--- a/web/app/layout.tsx
+++ b/web/app/layout.tsx
@@ -18,7 +18,6 @@ import { headers } from '@/next/headers'
import { getApplicationTitle } from '@/utils/document-title'
import { basePath } from '@/utils/var'
import { CloudAnalytics } from './components/base/analytics-consent/cloud-analytics'
-import { PartnerStackCookieRecorder } from './components/billing/partner-stack/cookie-recorder'
import { AgentationLoader } from './components/devtools/agentation-loader'
import { ReactScanLoader } from './components/devtools/react-scan/loader'
import { I18nServerProvider } from './components/provider/i18n-server'
@@ -83,7 +82,6 @@ export default async function RootLayout({ children }: { children: React.ReactNo
<I18nServerProvider>
<AppToastHost timeout={5000} limit={3} />
<SystemFeaturesBootstrapBoundary>
- <PartnerStackCookieRecorder />
<TooltipProvider delay={300} closeDelay={200}>
{children}
</TooltipProvider>
diff --git a/web/config/index.ts b/web/config/index.ts
index a755e101a31..01b7c1e9b56 100644
--- a/web/config/index.ts
+++ b/web/config/index.ts
@@ -346,8 +346,3 @@ export const STOP_PARAMETER_RULE: ModelParameterRule = {
zh_Hans: '输入序列并按 Tab 键',
},
}
-
-export const PARTNER_STACK_CONFIG = {
- cookieName: 'partner_stack_info',
- saveCookieDays: 90,
-}