feat(N4): Restliche Module — Tasks/Kommunikation/Wiki/Reports/Agents/Tags/Search + Navigation + Dashboard-Schnittstelle (#368)
Check Cross-Plugin Imports / check (push) Has been cancelled

- Scope-Deklarationen: tasks only_mine, kommunikation conversation_ids, wiki category_ids (NEUE contracts.py), report_generator template_ids, automation agent_ids (module_key agents), tags tag_ids, unified_search entity_types dynamisch aus Provider-Registry
- Core-Beiträge: navigation default_route (Startseite) + dashboard widget_app_ids (Widget-TYP-Angebot, Layout bleibt Phase M)
- Backend-Filter (additive UND): /tasks (only_mine), /comm/conversations, /wiki/articles+/categories (Subtree), /reports/print-templates, /agents, /tags, /search GET+POST (entity_types-Schnitt), /miniapps?host=dashboard
- apply_entity_type_scope-Helper (requested ∧ scope)
- Frontend: WorkspaceSwitcher default_route-Navigation, Sidebar workspace-menu_order-Sortierung, workspaceStore moduleMenuOrder()
- Tests: 18/18 Deklarationen + 11/11 Filter (TDD), Frontend 2/2 + Store 18/18, tsc clean, Build OK
- Regression 64 passed (4 Kombi-Failures = Suite-Isolation, solo-bewiesen); Checker 0; Ruff = Vorbestand (Stash-bewiesen)
This commit is contained in:
Agent Zero
2026-09-01 23:23:15 +02:00
parent 26506a5027
commit 03dd477899
26 changed files with 1335 additions and 24 deletions
@@ -15,7 +15,7 @@ from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.db import get_db
from app.deps import get_current_user, require_permission
from app.deps import get_current_user, require_permission, require_workspace_scope
from app.plugins.builtins.automation.models import (
AgentDefinition,
AgentRun,
@@ -118,8 +118,13 @@ async def list_agents(
offset: int = Query(0, ge=0),
current_user: dict[str, Any] = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
workspace_scope: dict | None = Depends(require_workspace_scope("agents")),
):
"""List agent definitions with optional filters."""
"""List agent definitions with optional filters.
Phase N4: an active workspace scope restricts the list to the
configured agent subset (pure AND — never a grant).
"""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
is_system_admin = current_user.get("is_system_admin", False)
@@ -127,6 +132,14 @@ async def list_agents(
db, tenant_id, is_active=is_active, mode=mode, limit=limit, offset=offset,
user_id=user_id, is_system_admin=is_system_admin,
)
# Phase N4: workspace scope — agent subset (pure AND)
if workspace_scope:
from app.services.workspace_scope_service import scope_uuid_set
agent_scope = scope_uuid_set(workspace_scope.get("agent_ids"))
if agent_scope is not None:
items = [a for a in items if a.id in agent_scope]
total = len(items)
return AgentDefinitionListResponse(
items=[_agent_to_response(a) for a in items],
total=total,
@@ -63,6 +63,31 @@ class AutomationContract:
# ─── agent_comm ───
send_agent_message = staticmethod(send_agent_message)
# ─── Workspace Scopes contribution (Phase N4) ───
@staticmethod
def workspace_scopes() -> list[dict]:
"""Scope-Dimensionen des agents-Moduls: Agenten-Teilmengen (N4)."""
return [
{
"module_key": "agents",
"dimensions": [
{
"key": "agent_ids",
"label": "Agenten",
"control": "multiselect",
"options": [],
"value_source": {
"endpoint": "/api/v1/agents",
"items_path": "items",
"value_key": "id",
"label_key": "name",
},
},
],
}
]
@classmethod
def get_function(cls, name: str):
"""Return a callable exposed by this contract, or None if absent."""
@@ -105,6 +105,33 @@ class KommunikationContract:
}
# ─── Workspace Scopes contribution (Phase N4) ───
@staticmethod
def workspace_scopes() -> list[dict]:
"""Scope-Dimensionen des communication-Moduls: Räume-Teilmengen (N4)."""
return [
{
"module_key": "communication",
"dimensions": [
{
"key": "conversation_ids",
"label": "Räume",
"control": "multiselect",
"options": [],
"value_source": {
"endpoint": "/api/v1/comm/conversations",
"items_path": "items",
"value_key": "id",
"label_key": "title",
},
},
],
}
]
# ─── self-registration ───
_contract = KommunikationContract()
+14 -2
View File
@@ -19,7 +19,7 @@ from fastapi import (
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.db import get_db
from app.deps import get_current_user, require_permission
from app.deps import get_current_user, require_permission, require_workspace_scope
from app.plugins.builtins.kommunikation.content_types import list_block_types
from app.plugins.builtins.kommunikation.dms_bridge import DmsBridge
from app.plugins.builtins.kommunikation.rbac import CommRBAC
@@ -74,11 +74,23 @@ async def list_user_conversations(
archived: bool = Query(False, description="Include archived conversations"),
current_user: dict = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
workspace_scope: dict | None = Depends(require_workspace_scope("communication")),
):
"""List all conversations for the current user."""
"""List all conversations for the current user.
Phase N4: an active workspace scope (X-Workspace-ID) restricts the list
to the configured conversation subset (pure AND — never a grant).
"""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
convs = await list_conversations(db, tenant_id, user_id, include_archived=archived)
# Phase N4: conversation_ids scope — keep only scoped rooms
if workspace_scope:
from app.services.workspace_scope_service import scope_uuid_set
conv_scope = scope_uuid_set(workspace_scope.get("conversation_ids"))
if conv_scope is not None:
convs = [c for c in convs if uuid.UUID(c["id"]) in conv_scope]
return {"items": convs, "total": len(convs)}
@@ -43,6 +43,31 @@ class ReportGeneratorContract:
PRESET_META = PRESET_META
PRESET_TEMPLATES = PRESET_TEMPLATES
# ─── Workspace Scopes contribution (Phase N4) ───
@staticmethod
def workspace_scopes() -> list[dict]:
"""Scope-Dimensionen des reports-Moduls: Vorlagen-Teilmengen (N4)."""
return [
{
"module_key": "reports",
"dimensions": [
{
"key": "template_ids",
"label": "Vorlagen",
"control": "multiselect",
"options": [],
"value_source": {
"endpoint": "/api/v1/reports/print-templates",
"items_path": "items",
"value_key": "id",
"label_key": "name",
},
},
],
}
]
# ─── self-registration ───
@@ -21,7 +21,7 @@ from app.ai.llm_client import llm_complete
from app.core.audit import log_audit
from app.core.db import get_db, set_tenant_context
from app.core.storage import get_storage_backend
from app.deps import require_permission
from app.deps import require_permission, require_workspace_scope
from app.plugins.builtins.report_generator.document_blocks import (
BlockValidationError,
get_document_blocks,
@@ -423,8 +423,13 @@ async def list_letterhead_assets(
async def list_print_templates(
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("reports:read")),
workspace_scope: dict | None = Depends(require_workspace_scope("reports")),
):
"""List print templates for the current tenant."""
"""List print templates for the current tenant.
Phase N4: an active workspace scope restricts the template list to the
configured subset (pure AND — never a grant).
"""
tenant_id = uuid_mod.UUID(current_user["tenant_id"])
q = (
select(PrintTemplate)
@@ -435,6 +440,12 @@ async def list_print_templates(
.order_by(PrintTemplate.name)
)
items = (await db.execute(q)).scalars().all()
if workspace_scope:
from app.services.workspace_scope_service import scope_uuid_set
template_scope = scope_uuid_set(workspace_scope.get("template_ids"))
if template_scope is not None:
items = [t for t in items if t.id in template_scope]
return {
"items": [_template_to_response(t).model_dump() for t in items],
"total": len(items),
+25
View File
@@ -26,6 +26,31 @@ class TagsContract:
Tag = Tag
TagAssignment = TagAssignment
# ─── Workspace Scopes contribution (Phase N4) ───
@staticmethod
def workspace_scopes() -> list[dict]:
"""Scope-Dimensionen des tags-Moduls: Tag-Teilmengen (N4)."""
return [
{
"module_key": "tags",
"dimensions": [
{
"key": "tag_ids",
"label": "Tags",
"control": "multiselect",
"options": [],
"value_source": {
"endpoint": "/api/v1/tags",
"items_path": "",
"value_key": "id",
"label_key": "name",
},
},
],
}
]
# ─── self-registration ───
+10 -1
View File
@@ -11,7 +11,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.audit import log_audit
from app.core.db import get_db
from app.core.visibility import apply_visibility_filter
from app.deps import get_current_user, require_permission
from app.deps import get_current_user, require_permission, require_workspace_scope
from app.plugins.builtins.tags.models import Tag, TagAssignment
from app.plugins.builtins.tags.schemas import (
TagAssignRequest,
@@ -44,6 +44,7 @@ def _parse_uuid(val: str, field: str) -> uuid.UUID:
async def list_tags(
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
workspace_scope: dict | None = Depends(require_workspace_scope("tags")),
):
"""List all tags with entity counts."""
tenant_id = uuid.UUID(current_user["tenant_id"])
@@ -73,6 +74,14 @@ async def list_tags(
result = await db.execute(query)
rows = result.all()
# Phase N4: workspace scope — tag subset (pure AND, never a grant)
if workspace_scope:
from app.services.workspace_scope_service import scope_uuid_set
tag_scope = scope_uuid_set(workspace_scope.get("tag_ids"))
if tag_scope is not None:
rows = [(tag, count) for tag, count in rows if tag.id in tag_scope]
return [
{
"id": str(tag.id),
+21
View File
@@ -47,6 +47,27 @@ class TasksContract:
update_task_status = staticmethod(update_task_status)
get_due_tasks = staticmethod(get_due_tasks)
# ─── Workspace Scopes contribution (Phase N4) ───
@staticmethod
def workspace_scopes() -> list[dict]:
"""Scope-Dimensionen des tasks-Moduls: „nur meine" (Roadmap N4)."""
return [
{
"module_key": "tasks",
"dimensions": [
{
"key": "only_mine",
"label": "Nur meine Aufgaben",
"control": "toggle",
"options": [],
"value_source": None,
"default": False,
},
],
}
]
# ─── models (read-only for queries) ───
Task = Task
+8 -2
View File
@@ -9,7 +9,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.audit import log_audit
from app.core.db import get_db
from app.deps import get_current_user, require_permission
from app.deps import get_current_user, require_permission, require_workspace_scope
from app.plugins.builtins.tasks import services
from app.plugins.builtins.tasks.schemas import (
TaskAssignRequest,
@@ -53,8 +53,13 @@ async def list_tasks(
search: str | None = Query(None),
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
workspace_scope: dict | None = Depends(require_workspace_scope("tasks")),
):
"""List tasks with filtering and pagination."""
"""List tasks with filtering and pagination.
Phase N4: an active workspace scope with only_mine=true restricts the
list to tasks assigned to or created by the current user (pure AND).
"""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
is_system_admin = current_user.get("is_system_admin", False)
@@ -68,6 +73,7 @@ async def list_tasks(
parent_task_id=parent_task_id, task_type=task_type,
search=search,
user_id=user_id, is_system_admin=is_system_admin,
workspace_scope=workspace_scope,
)
+18 -2
View File
@@ -16,7 +16,7 @@ def _to_uuid(val: str | UUID | None) -> UUID | None:
return val
return uuid.UUID(str(val))
from sqlalchemy import func, select # noqa: E402 — after helper defs by design
from sqlalchemy import func, or_, select # noqa: E402 — after helper defs by design
from sqlalchemy.ext.asyncio import AsyncSession # noqa: E402
from app.core.visibility import apply_visibility_filter # noqa: E402
@@ -215,10 +215,26 @@ async def list_tasks(
task_type: str | None = None,
user_id: uuid.UUID | None = None,
is_system_admin: bool = False,
workspace_scope: dict | None = None,
) -> dict[str, Any]:
"""List tasks with filtering and pagination."""
"""List tasks with filtering and pagination.
Phase N4: ``workspace_scope`` with only_mine=true restricts the list to
tasks assigned to or created by the current user (pure AND on top of
all other filters — never a grant).
"""
query = select(Task).where(Task.tenant_id == tenant_id, Task.deleted_at.is_(None))
# Phase N4: workspace scope — only_mine restricts to own tasks (assigned
# to OR created by the current user). Pure AND, never a grant.
if workspace_scope and workspace_scope.get("only_mine") is True and user_id:
query = query.where(
or_(
Task.assigned_to == user_id,
Task.created_by == user_id,
)
)
if user_id and not is_system_admin:
query = await apply_visibility_filter(
db, query, "task", Task, user_id, tenant_id, is_system_admin
@@ -61,6 +61,68 @@ class UnifiedSearchContract:
await _auto_register(db)
# ─── Workspace Scopes contribution (Phase N4) ───
@staticmethod
def workspace_scopes() -> list[dict]:
"""Scope-Dimensionen des search-Moduls: Suchbereiche (N4).
Options come from the live search provider registry; when it has
not been initialized yet (sync context before activation), the
built-in provider classes are the deterministic fallback source
(same classes auto_register_providers registers at activation).
"""
entity_types = list(get_search_registry().get_entity_types())
if not entity_types:
from app.plugins.builtins.unified_search.providers import (
agent_memory_provider,
ai_chat_provider,
company_provider,
contact_provider,
contactperson_provider,
conversation_provider,
event_provider,
file_provider,
mail_provider,
tag_provider,
task_provider,
user_provider,
workflow_provider,
)
for module in (
agent_memory_provider, ai_chat_provider, company_provider,
contact_provider, contactperson_provider, conversation_provider,
event_provider, file_provider, mail_provider, tag_provider,
task_provider, user_provider, workflow_provider,
):
for attr in dir(module):
obj = getattr(module, attr)
if (
isinstance(obj, type)
and attr.endswith("Provider")
and attr != "BaseSearchProvider"
and getattr(obj, "entity_type", "")
):
entity_types.append(obj.entity_type)
entity_types = sorted(set(entity_types))
return [
{
"module_key": "search",
"dimensions": [
{
"key": "entity_types",
"label": "Suchbereiche",
"control": "multiselect",
"options": [
{"value": et, "label": et.replace("_", " ").title()}
for et in entity_types
],
},
],
}
]
@classmethod
def get_function(cls, name: str):
"""Return a callable exposed by this contract, or None if absent."""
+25 -3
View File
@@ -14,7 +14,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.db import get_db
from app.core.jobs import enqueue_job
from app.core.permissions import filter_fields_by_permission, resolve_permissions
from app.deps import get_current_user, require_permission
from app.deps import get_current_user, require_permission, require_workspace_scope
from app.plugins.builtins.unified_search.provider_registry import get_search_registry
from app.plugins.builtins.unified_search.query_understanding import (
llm_aggregate_results,
@@ -56,8 +56,13 @@ async def search_get(
sort: str = Query(default="relevance", description="Sort order: relevance, date, name"),
current_user: dict = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
workspace_scope: dict | None = Depends(require_workspace_scope("search")),
) -> SearchResponse:
"""Perform hybrid search via GET (same as POST but with query params)."""
"""Perform hybrid search via GET (same as POST but with query params).
Phase N4: an active workspace scope intersects the requested entity
types with the configured search areas (pure AND — never a grant).
"""
types_list = entity_types.split(",") if entity_types else None
tags_list = tags.split(",") if tags else None
req = SearchRequest(
@@ -70,6 +75,12 @@ async def search_get(
tags=tags_list,
sort=sort,
)
if workspace_scope:
from app.services.workspace_scope_service import apply_entity_type_scope
req.entity_types = apply_entity_type_scope(
req.entity_types, workspace_scope.get("entity_types")
)
return await _do_search(req, current_user, db)
@@ -219,8 +230,19 @@ async def search(
req: SearchRequest,
current_user: dict = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
workspace_scope: dict | None = Depends(require_workspace_scope("search")),
) -> SearchResponse:
"""Perform hybrid search with KI query understanding."""
"""Perform hybrid search with KI query understanding.
Phase N4: an active workspace scope intersects the requested entity
types with the configured search areas (pure AND — never a grant).
"""
if workspace_scope:
from app.services.workspace_scope_service import apply_entity_type_scope
req.entity_types = apply_entity_type_scope(
req.entity_types, workspace_scope.get("entity_types")
)
return await _do_search(req, current_user, db)
+55
View File
@@ -0,0 +1,55 @@
"""Wiki plugin contract — public interface for cross-plugin access (N4).
Created for the Phase N workspace_scopes contribution (the wiki previously
had no contract module — N4 needs one for the scope registry, mirroring the
contacts/dms/mail/calendar pattern from N1).
"""
from __future__ import annotations
from app.plugins.builtins.contracts import get_contract_registry
class WikiContract:
"""Public contract for the wiki plugin."""
contract_name = "wiki"
# ─── Workspace Scopes contribution (Phase N4) ───
@staticmethod
def workspace_scopes() -> list[dict]:
"""Scope-Dimensionen des wiki-Moduls: Kategorien-Teilmengen (N4)."""
return [
{
"module_key": "wiki",
"dimensions": [
{
"key": "category_ids",
"label": "Wiki-Kategorien",
"control": "multiselect",
"options": [],
"value_source": {
"endpoint": "/api/v1/wiki/categories",
"items_path": "items",
"value_key": "id",
"label_key": "name",
},
},
],
}
]
@classmethod
def get_function(cls, name: str):
"""Return a callable exposed by this contract, or None if absent."""
return getattr(cls, name, None)
# ─── self-registration ───
_contract = WikiContract()
get_contract_registry().register("wiki", _contract)
__all__ = ["WikiContract"]
+39 -3
View File
@@ -8,7 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.audit import log_audit
from app.core.db import get_db
from app.deps import require_permission
from app.deps import require_permission, require_workspace_scope
from app.plugins.builtins.wiki import services
from app.plugins.builtins.wiki.schemas import (
ArticleCreate,
@@ -28,11 +28,35 @@ async def list_articles(
search: str | None = None,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("wiki:read")),
workspace_scope: dict | None = Depends(require_workspace_scope("wiki")),
):
return await services.list_articles(
"""List wiki articles.
Phase N4: an active workspace scope (X-Workspace-ID) restricts articles
to the category subtree (category_ids incl. children — pure AND).
"""
scoped_category_ids: set | None = None
if workspace_scope:
from app.plugins.builtins.wiki.models import WikiCategory
from app.services.workspace_scope_service import expand_folder_scope
raw_ids = workspace_scope.get("category_ids")
if isinstance(raw_ids, list) and raw_ids:
scoped_category_ids = await expand_folder_scope(db, WikiCategory, raw_ids)
result = await services.list_articles(
db, uuid.UUID(current_user["tenant_id"]),
page=page, page_size=page_size, category_id=category_id, status=status, search=search,
)
# Phase N4: filter to the scoped category subtree (post-fetch AND filter)
if scoped_category_ids is not None:
items = [
a for a in result["items"]
if a.get("category_id") and uuid.UUID(a["category_id"]) in scoped_category_ids
]
result["items"] = items
result["total"] = len(items)
return result
@router.post("/articles", status_code=status.HTTP_201_CREATED)
@@ -120,8 +144,20 @@ async def restore_version(
async def list_categories(
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("wiki:read")),
workspace_scope: dict | None = Depends(require_workspace_scope("wiki")),
):
return {"items": await services.list_categories(db, uuid.UUID(current_user["tenant_id"]))}
"""List wiki categories (Phase N4: scope reduces to the category subtree)."""
items = await services.list_categories(db, uuid.UUID(current_user["tenant_id"]))
if workspace_scope:
from app.plugins.builtins.wiki.models import WikiCategory
from app.services.workspace_scope_service import expand_folder_scope
raw_ids = workspace_scope.get("category_ids")
if isinstance(raw_ids, list) and raw_ids:
subtree = await expand_folder_scope(db, WikiCategory, raw_ids)
allowed = subtree or set()
items = [c for c in items if uuid.UUID(c["id"]) in allowed]
return {"items": items}
@router.post("/categories", status_code=status.HTTP_201_CREATED)