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.

fix(agent): add roster publication status contract (#41435)

yyh78c85ae7c1cd
diff --git a/api/controllers/console/agent/roster.py b/api/controllers/console/agent/roster.py
index 8b9e8fb08c2..f95f9d8b00f 100644
--- a/api/controllers/console/agent/roster.py
+++ b/api/controllers/console/agent/roster.py
@@ -1,3 +1,4 @@
+from typing import Literal
from uuid import UUID
from flask import abort, request
@@ -76,16 +77,25 @@ from services.agent.observability_service import (
AgentStatisticsQueryParams,
)
from services.agent.roster_service import AgentRosterService
-from services.app_service import AppListParams, AppService, CreateAppParams
+from services.app_service import AgentAppPublicationCounts, AppListParams, AppService, CreateAppParams
from services.enterprise.enterprise_service import EnterpriseService
from services.entities.agent_entities import ComposerSavePayload, RosterListQuery
from services.feature_service import FeatureService
+AgentPublicationStatus = Literal["published", "drafts"]
+
class AgentInviteOptionsQuery(RosterListQuery):
app_id: str | None = Field(default=None, description="Workflow app id for in-current-workflow markers")
+class AgentAppListQuery(AppListQuery):
+ publication_status: AgentPublicationStatus | None = Field(
+ default=None,
+ description="Filter by published or draft Agent configuration status",
+ )
+
+
class AgentIdPath(BaseModel):
agent_id: str
@@ -299,7 +309,19 @@ class AgentSimpleResultResponse(BaseModel):
result: str
+class AgentPublicationCountsResponse(ResponseModel):
+ published: int = Field(
+ ge=0,
+ description="Published Agent Apps in the current list scope, excluding the publication status filter",
+ )
+ drafts: int = Field(
+ ge=0,
+ description="Draft Agent Apps in the current list scope, excluding the publication status filter",
+ )
+
+
class AgentAppPagination(GenericAppPagination):
+ publication_counts: AgentPublicationCountsResponse
data: list[AgentAppPartial] = Field( # type: ignore[assignment] # pyrefly: ignore[bad-override-mutable-attribute]
validation_alias=AliasChoices("items", "data")
)
@@ -314,6 +336,7 @@ register_schema_models(
AgentBuildDraftCheckoutPayload,
ComposerSavePayload,
AgentApiStatusPayload,
+ AgentAppListQuery,
AgentInviteOptionsQuery,
AgentLogsQuery,
AgentStatisticsQuery,
@@ -323,6 +346,7 @@ register_schema_models(
)
register_response_schema_models(
console_ns,
+ AgentPublicationCountsResponse,
AgentAppPagination,
AgentApiAccessResponse,
AgentAppPublishedReferenceResponse,
@@ -408,7 +432,14 @@ def _serialize_agent_app_detail(
return payload
-def _serialize_agent_app_pagination(session: Session, app_pagination, *, tenant_id: str, current_user: Account) -> dict:
+def _serialize_agent_app_pagination(
+ session: Session,
+ app_pagination,
+ *,
+ tenant_id: str,
+ current_user: Account,
+ publication_counts: AgentAppPublicationCounts,
+) -> dict:
"""Serialize Agent App lists with roster-shaped items.
Each item starts from the shared App list shape, then drops
@@ -441,8 +472,17 @@ def _serialize_agent_app_pagination(session: Session, app_pagination, *, tenant_
account_id=current_user.id,
)
payload = AgentAppPagination.model_validate(
- app_pagination,
- from_attributes=True,
+ {
+ "page": app_pagination.page,
+ "limit": app_pagination.per_page,
+ "total": app_pagination.total,
+ "has_more": app_pagination.has_next,
+ "data": app_pagination.items,
+ "publication_counts": {
+ "published": publication_counts.published,
+ "drafts": publication_counts.drafts,
+ },
+ },
context={"session": session},
).model_dump(mode="json")
for item in payload["data"]:
@@ -562,7 +602,7 @@ def _query_values(name: str, alias_name: str | None = None) -> list[str]:
@console_ns.route("/agent")
class AgentAppListApi(Resource):
- @console_ns.doc(params=query_params_from_model(AppListQuery))
+ @console_ns.doc(params=query_params_from_model(AgentAppListQuery))
@console_ns.response(200, "Agent app list", console_ns.models[AgentAppPagination.__name__])
@setup_required
@login_required
@@ -572,7 +612,9 @@ class AgentAppListApi(Resource):
@with_current_tenant_id
@with_session
def get(self, session: Session, current_tenant_id: str, current_user: Account):
- args = query_params_from_request(AppListQuery, list_fields=APP_LIST_QUERY_ARRAY_FIELDS)
+ args = query_params_from_request(AgentAppListQuery, list_fields=APP_LIST_QUERY_ARRAY_FIELDS)
+ agent_is_published = None if args.publication_status is None else args.publication_status == "published"
+
params = AppListParams(
page=args.page,
limit=args.limit,
@@ -583,11 +625,29 @@ class AgentAppListApi(Resource):
creator_ids=args.creator_ids,
is_created_by_me=args.is_created_by_me,
status="normal",
+ agent_is_published=agent_is_published,
)
- app_pagination = AppService().get_paginate_apps(current_user.id, current_tenant_id, params, session)
+ app_service = AppService()
+ publication_counts = app_service.get_agent_publication_counts(
+ current_user.id,
+ current_tenant_id,
+ params,
+ session,
+ )
+ app_pagination = app_service.get_paginate_apps(current_user.id, current_tenant_id, params, session)
if app_pagination is None:
- empty = AgentAppPagination(page=args.page, limit=args.limit, total=0, has_more=False, data=[])
+ empty = AgentAppPagination(
+ page=args.page,
+ limit=args.limit,
+ total=0,
+ has_more=False,
+ publication_counts=AgentPublicationCountsResponse(
+ published=publication_counts.published,
+ drafts=publication_counts.drafts,
+ ),
+ data=[],
+ )
return empty.model_dump(mode="json")
return _serialize_agent_app_pagination(
@@ -595,6 +655,7 @@ class AgentAppListApi(Resource):
app_pagination,
tenant_id=current_tenant_id,
current_user=current_user,
+ publication_counts=publication_counts,
)
@console_ns.expect(console_ns.models[AgentAppCreatePayload.__name__])
diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md
index 63970c8f5c7..b8008497e43 100644
--- a/api/openapi/markdown/console-openapi.md
+++ b/api/openapi/markdown/console-openapi.md
@@ -346,6 +346,7 @@ Check if activation token is valid
| mode | query | App mode filter | No | string, <br>**Available values:** "advanced-chat", "agent", "agent-chat", "all", "channel", "chat", "completion", "workflow", <br>**Default:** all |
| name | query | Filter by app name | No | string |
| page | query | Page number (1-99999) | No | integer, <br>**Default:** 1 |
+| publication_status | query | Filter by published or draft Agent configuration status | No | string, <br>**Available values:** "drafts", "published" |
| sort_by | query | Sort apps by last modified, recently created, or earliest created | No | string, <br>**Available values:** "earliest_created", "last_modified", "recently_created", <br>**Default:** last_modified |
| tag_ids | query | Filter by tag IDs | No | [ string ] |
@@ -13490,6 +13491,20 @@ default (the config form sends the full desired feature state on save).
| suggested_questions_after_answer | [AgentSuggestedQuestionsAfterAnswerFeatureConfig](#agentsuggestedquestionsafteranswerfeatureconfig) | Follow-up suggestions config, e.g. {'enabled': true} | No |
| text_to_speech | [AgentTextToSpeechFeatureConfig](#agenttexttospeechfeatureconfig) | Text-to-speech config | No |
+#### AgentAppListQuery
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| creator_ids | [ string ] | Filter by creator account IDs | No |
+| is_created_by_me | boolean | Filter by creator | No |
+| limit | integer, <br>**Default:** 20 | Page size (1-100) | No |
+| mode | string, <br>**Available values:** "advanced-chat", "agent", "agent-chat", "all", "channel", "chat", "completion", "workflow", <br>**Default:** all | App mode filter<br>*Enum:* `"advanced-chat"`, `"agent"`, `"agent-chat"`, `"all"`, `"channel"`, `"chat"`, `"completion"`, `"workflow"` | No |
+| name | string | Filter by app name | No |
+| page | integer, <br>**Default:** 1 | Page number (1-99999) | No |
+| publication_status | string | Filter by published or draft Agent configuration status | No |
+| sort_by | string, <br>**Available values:** "earliest_created", "last_modified", "recently_created", <br>**Default:** last_modified | Sort apps by last modified, recently created, or earliest created<br>*Enum:* `"earliest_created"`, `"last_modified"`, `"recently_created"` | No |
+| tag_ids | [ string ] | Filter by tag IDs | No |
+
#### AgentAppPagination
| Name | Type | Description | Required |
@@ -13498,6 +13513,7 @@ default (the config form sends the full desired feature state on save).
| has_more | boolean | | Yes |
| limit | integer | | Yes |
| page | integer | | Yes |
+| publication_counts | [AgentPublicationCountsResponse](#agentpublicationcountsresponse) | | Yes |
| total | integer | | Yes |
#### AgentAppPartial
@@ -14574,6 +14590,13 @@ section may be empty, which is how callers express "no knowledge layer".
| ---- | ---- | ----------- | -------- |
| AgentProviderResponse | object | | |
+#### AgentPublicationCountsResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| drafts | integer | Draft Agent Apps in the current list scope, excluding the publication status filter | Yes |
+| published | integer | Published Agent Apps in the current list scope, excluding the publication status filter | Yes |
+
#### AgentPublishPayload
| Name | Type | Description | Required |
diff --git a/api/services/app_service.py b/api/services/app_service.py
index 1a9f0497774..89b622463b7 100644
--- a/api/services/app_service.py
+++ b/api/services/app_service.py
@@ -90,12 +90,19 @@ class AppListBaseParams(BaseModel):
class AppListParams(AppListBaseParams):
status: str | None = None
openapi_visible: bool = False
+ agent_is_published: bool | None = None
class StarredAppListParams(AppListBaseParams):
pass
+@dataclass(frozen=True)
+class AgentAppPublicationCounts:
+ published: int
+ drafts: int
+
+
@dataclass(frozen=True)
class RecentAppListItem:
id: str
@@ -188,6 +195,24 @@ class AppResponseView:
class AppService:
+ @staticmethod
+ def _agent_app_exists_filter(tenant_id: str, *, is_published: bool | None = None) -> sa.Exists:
+ agent_filters = [
+ Agent.tenant_id == tenant_id,
+ Agent.app_id == App.id,
+ Agent.scope == AgentScope.ROSTER,
+ Agent.source.in_(APP_BACKED_AGENT_SOURCES),
+ Agent.status == AgentStatus.ACTIVE,
+ ]
+ if is_published is not None:
+ has_published_config = sa.and_(
+ Agent.active_config_snapshot_id.is_not(None),
+ Agent.active_config_is_published.is_(True),
+ )
+ agent_filters.append(has_published_config if is_published else sa.not_(has_published_config))
+
+ return sa.exists().where(*agent_filters).correlate(App)
+
@staticmethod
def _build_app_list_filters(
user_id: str, tenant_id: str, params: AppListBaseParams, session: Session
@@ -206,17 +231,8 @@ class AppService:
filters.append(App.mode == AppMode.AGENT_CHAT)
elif params.mode == "agent":
filters.append(App.mode == AppMode.AGENT)
- filters.append(
- sa.exists()
- .where(
- Agent.tenant_id == tenant_id,
- Agent.app_id == App.id,
- Agent.scope == AgentScope.ROSTER,
- Agent.source.in_(APP_BACKED_AGENT_SOURCES),
- Agent.status == AgentStatus.ACTIVE,
- )
- .correlate(App)
- )
+ publication_filter = params.agent_is_published if isinstance(params, AppListParams) else None
+ filters.append(AppService._agent_app_exists_filter(tenant_id, is_published=publication_filter))
elif params.mode == "all":
filters.append(App.mode != AppMode.AGENT)
@@ -374,6 +390,31 @@ class AppService:
return app_models
+ def get_agent_publication_counts(
+ self,
+ user_id: str,
+ tenant_id: str,
+ params: AppListParams,
+ session: Session,
+ ) -> AgentAppPublicationCounts:
+ unfiltered_params = params.model_copy(update={"agent_is_published": None})
+ filters = self._build_app_list_filters(user_id, tenant_id, unfiltered_params, session)
+ if not filters:
+ return AgentAppPublicationCounts(published=0, drafts=0)
+
+ published_filter = self._agent_app_exists_filter(tenant_id, is_published=True)
+ draft_filter = self._agent_app_exists_filter(tenant_id, is_published=False)
+ published_count, draft_count = session.execute(
+ sa.select(
+ sa.func.coalesce(sa.func.sum(sa.case((published_filter, 1), else_=0)), 0),
+ sa.func.coalesce(sa.func.sum(sa.case((draft_filter, 1), else_=0)), 0),
+ )
+ .select_from(App)
+ .where(*filters)
+ ).one()
+
+ return AgentAppPublicationCounts(published=int(published_count), drafts=int(draft_count))
+
def get_recent_apps(
self,
user_id: str,
diff --git a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
index 9cd219971db..112b3a0264f 100644
--- a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
+++ b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
@@ -325,6 +325,11 @@ def test_agent_app_list_and_create_use_agent_route(
items=[_app_detail_obj(id="app-list", bound_agent_id="agent-list")],
)
+ def get_agent_publication_counts(self, user_id: str, tenant_id: str, params, session):
+ del session
+ captured["counts"] = {"user_id": user_id, "tenant_id": tenant_id, "params": params}
+ return roster_controller.AgentAppPublicationCounts(published=1, drafts=0)
+
def create_app(self, tenant_id: str, params, current_user: object, *, session: object) -> object:
captured["create"] = {"tenant_id": tenant_id, "params": params, "current_user": current_user}
return _app_detail_obj(id="app-created", bound_agent_id="agent-created")
@@ -408,7 +413,8 @@ def test_agent_app_list_and_create_use_agent_route(
lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),
)
with app.test_request_context(
- "/console/api/agent?page=1&limit=10&mode=workflow&sort_by=recently_created&is_created_by_me=true"
+ "/console/api/agent?page=1&limit=10&mode=workflow&sort_by=recently_created"
+ "&is_created_by_me=true&publication_status=published"
):
listed = unwrap(AgentAppListApi.get)(
AgentAppListApi(), sqlite_session, "tenant-1", _account(account_id=account_id)
@@ -416,6 +422,7 @@ def test_agent_app_list_and_create_use_agent_route(
assert listed["page"] == 1
assert listed["limit"] == 10
assert listed["total"] == 1
+ assert listed["publication_counts"] == {"published": 1, "drafts": 0}
assert listed["data"][0]["id"] == "agent-list"
assert listed["data"][0]["app_id"] == "app-list"
assert listed["data"][0]["debug_conversation_id"] == "debug-conversation-list"
@@ -438,7 +445,11 @@ def test_agent_app_list_and_create_use_agent_route(
assert list_params.mode == "agent"
assert list_params.sort_by == "recently_created"
assert list_params.is_created_by_me is True
+ assert list_params.agent_is_published is True
assert list_params.status == "normal"
+ count_call = cast(dict[str, object], captured["counts"])
+ count_params = cast(Any, count_call["params"])
+ assert count_params.agent_is_published is True
with app.test_request_context(
"/console/api/agent",
json={"name": "Iris", "description": "Agent app", "role": "Coordinator", "icon_type": "emoji", "icon": "robot"},
diff --git a/api/tests/unit_tests/services/test_app_service.py b/api/tests/unit_tests/services/test_app_service.py
index 223be9f678b..8c71979a726 100644
--- a/api/tests/unit_tests/services/test_app_service.py
+++ b/api/tests/unit_tests/services/test_app_service.py
@@ -67,9 +67,18 @@ def _persist_app(session: Session, *, tenant_id: str, name: str = "Visible App")
return app
-def _persist_agent_app(session: Session, *, app_name: str = "Old", agent_name: str = "Old") -> tuple[App, Agent]:
- tenant_id = str(uuid4())
- creator_id = str(uuid4())
+def _persist_agent_app(
+ session: Session,
+ *,
+ app_name: str = "Old",
+ agent_name: str = "Old",
+ tenant_id: str | None = None,
+ creator_id: str | None = None,
+ active_config_snapshot_id: str | None = None,
+ active_config_is_published: bool = False,
+) -> tuple[App, Agent]:
+ tenant_id = tenant_id or str(uuid4())
+ creator_id = creator_id or str(uuid4())
app = App(
id=str(uuid4()),
tenant_id=tenant_id,
@@ -95,6 +104,8 @@ def _persist_agent_app(session: Session, *, app_name: str = "Old", agent_name: s
icon="robot",
icon_background="#fff",
app_id=app.id,
+ active_config_snapshot_id=active_config_snapshot_id,
+ active_config_is_published=active_config_is_published,
created_by=creator_id,
)
session.add_all([app, agent])
@@ -493,6 +504,78 @@ class TestAgentAppType:
params = CreateAppParams(name="Iris", mode="agent")
assert params.mode == "agent"
+ def test_list_filter_and_counts_use_server_owned_publication_state(self, sqlite_session: Session):
+ tenant_id = str(uuid4())
+ creator_id = str(uuid4())
+ published_app, _ = _persist_agent_app(
+ sqlite_session,
+ app_name="Published",
+ agent_name="Published Agent",
+ tenant_id=tenant_id,
+ creator_id=creator_id,
+ active_config_snapshot_id=str(uuid4()),
+ active_config_is_published=True,
+ )
+ draft_app, _ = _persist_agent_app(
+ sqlite_session,
+ app_name="Draft",
+ agent_name="Draft Agent",
+ tenant_id=tenant_id,
+ creator_id=creator_id,
+ active_config_snapshot_id=str(uuid4()),
+ )
+ unpublished_app, _ = _persist_agent_app(
+ sqlite_session,
+ app_name="Unpublished",
+ agent_name="Unpublished Agent",
+ tenant_id=tenant_id,
+ creator_id=creator_id,
+ )
+ _persist_agent_app(
+ sqlite_session,
+ app_name="Other tenant",
+ agent_name="Other Agent",
+ active_config_snapshot_id=str(uuid4()),
+ active_config_is_published=True,
+ )
+
+ service = AppService()
+ published_page = service.get_paginate_apps(
+ creator_id,
+ tenant_id,
+ AppListParams(mode="agent", status="normal", agent_is_published=True),
+ sqlite_session,
+ )
+ draft_page = service.get_paginate_apps(
+ creator_id,
+ tenant_id,
+ AppListParams(mode="agent", status="normal", agent_is_published=False),
+ sqlite_session,
+ )
+ counts = service.get_agent_publication_counts(
+ creator_id,
+ tenant_id,
+ AppListParams(mode="agent", status="normal", agent_is_published=True),
+ sqlite_session,
+ )
+ searched_counts = service.get_agent_publication_counts(
+ creator_id,
+ tenant_id,
+ AppListParams(mode="agent", status="normal", name="Draft", agent_is_published=True),
+ sqlite_session,
+ )
+
+ assert published_page is not None
+ assert {app.id for app in published_page.items} == {published_app.id}
+ assert published_page.total == 1
+ assert draft_page is not None
+ assert {app.id for app in draft_page.items} == {draft_app.id, unpublished_app.id}
+ assert draft_page.total == 2
+ assert counts.published == 1
+ assert counts.drafts == 2
+ assert searched_counts.published == 0
+ assert searched_counts.drafts == 1
+
def test_bound_agent_id_is_none_for_non_agent_app(self):
"""Non-agent apps short-circuit without touching the DB."""
from models.model import App, AppMode
diff --git a/packages/contracts/generated/api/console/agent/types.gen.ts b/packages/contracts/generated/api/console/agent/types.gen.ts
index 3991a7dfee0..1fb8deaf323 100644
--- a/packages/contracts/generated/api/console/agent/types.gen.ts
+++ b/packages/contracts/generated/api/console/agent/types.gen.ts
@@ -9,6 +9,7 @@ export type AgentAppPagination = {
has_more: boolean
limit: number
page: number
+ publication_counts: AgentPublicationCountsResponse
total: number
}
@@ -467,6 +468,11 @@ export type AgentAppPartial = {
workflow?: WorkflowPartial | null
}
+export type AgentPublicationCountsResponse = {
+ drafts: number
+ published: number
+}
+
export type IconType = 'emoji' | 'image' | 'link'
export type DeletedTool = {
@@ -1733,6 +1739,7 @@ export type AgentAppPaginationWritable = {
has_more: boolean
limit: number
page: number
+ publication_counts: AgentPublicationCountsResponse
total: number
}
@@ -1854,6 +1861,7 @@ export type GetAgentData = {
| 'workflow'
name?: string
page?: number
+ publication_status?: 'drafts' | 'published'
sort_by?: 'earliest_created' | 'last_modified' | 'recently_created'
tag_ids?: Array<string>
}
diff --git a/packages/contracts/generated/api/console/agent/zod.gen.ts b/packages/contracts/generated/api/console/agent/zod.gen.ts
index d33b96e344b..a6cc2c12347 100644
--- a/packages/contracts/generated/api/console/agent/zod.gen.ts
+++ b/packages/contracts/generated/api/console/agent/zod.gen.ts
@@ -204,6 +204,14 @@ export const zAgentConfigSnapshotRestoreResponse = z.object({
result: z.literal('success'),
})
+/**
+ * AgentPublicationCountsResponse
+ */
+export const zAgentPublicationCountsResponse = z.object({
+ drafts: z.int().gte(0),
+ published: z.int().gte(0),
+})
+
/**
* IconType
*/
@@ -871,6 +879,7 @@ export const zAgentAppPagination = z.object({
has_more: z.boolean(),
limit: z.int(),
page: z.int(),
+ publication_counts: zAgentPublicationCountsResponse,
total: z.int(),
})
@@ -2493,6 +2502,7 @@ export const zAgentAppPaginationWritable = z.object({
has_more: z.boolean(),
limit: z.int(),
page: z.int(),
+ publication_counts: zAgentPublicationCountsResponse,
total: z.int(),
})
@@ -2585,6 +2595,7 @@ export const zGetAgentQuery = z.object({
.default('all'),
name: z.string().optional(),
page: z.int().gte(1).lte(99999).optional().default(1),
+ publication_status: z.enum(['drafts', 'published']).optional(),
sort_by: z
.enum(['earliest_created', 'last_modified', 'recently_created'])
.optional()
diff --git a/web/app/components/goto-anything/actions/__tests__/agent.spec.tsx b/web/app/components/goto-anything/actions/__tests__/agent.spec.tsx
index 0adc11781c8..73a2ed6bfde 100644
--- a/web/app/components/goto-anything/actions/__tests__/agent.spec.tsx
+++ b/web/app/components/goto-anything/actions/__tests__/agent.spec.tsx
@@ -67,6 +67,7 @@ describe('agent search query', () => {
has_more: false,
limit: 10,
page: 1,
+ publication_counts: { drafts: 0, published: 1 },
total: 1,
})