Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(workflow): name-derived slug for folders, Temporal UI, sidebar
trohitg8ba5c8e57a26
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsxindex e1acaf92..33de8185 100644--- a/client/src/contexts/WebSocketContext.tsx+++ b/client/src/contexts/WebSocketContext.tsx@@ -714,17 +714,20 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi}case 'workflow_lifecycle': {- // CloudEvents-typed workflow lifecycle (today: workflow.imported).- // Frontend action: invalidate the workflows query so the sidebar- // picks up the new entry on every connected client. Other stages- // (deployment.started, lock.acquired, ...) are read for future- // dispatch but currently have side effects elsewhere.+ // CloudEvents-typed workflow lifecycle. ``.imported`` and+ // ``.renamed`` both invalidate the workflows query so every+ // connected client refreshes the sidebar. The renaming tab+ // already updated its in-memory store from the save response+ // — this broadcast covers other open tabs of the same user.const event = data as WorkflowEvent<{name?: string;+ slug?: string;+ old_slug?: string;node_count?: number;edge_count?: number;}>;- if (event?.type?.endsWith('.imported')) {+ const eventType = event?.type ?? '';+ if (eventType.endsWith('.imported') || eventType.endsWith('.renamed')) {void queryClient.invalidateQueries({ queryKey: WORKFLOWS_QUERY_KEY });}break;diff --git a/client/src/services/workflowApi.ts b/client/src/services/workflowApi.tsindex 5e8e126d..035b27af 100644--- a/client/src/services/workflowApi.ts+++ b/client/src/services/workflowApi.ts@@ -10,6 +10,7 @@ const getApiBase = () => `${API_CONFIG.PYTHON_BASE_URL}/api/database`;export interface WorkflowSummary {id: string;name: string;+ slug: string;nodeCount: number;createdAt: string;lastModified: string;@@ -18,6 +19,7 @@ export interface WorkflowSummary {export interface WorkflowData {id: string;name: string;+ slug: string;data: {nodes: any[];edges: any[];@@ -26,8 +28,14 @@ export interface WorkflowData {lastModified: string;}+export interface SaveWorkflowResult {+ success: boolean;+ slug?: string;+ name?: string;+}+export const workflowApi = {- async saveWorkflow(workflowId: string, name: string, data: { nodes: any[]; edges: any[] }): Promise<boolean> {+ async saveWorkflow(workflowId: string, name: string, data: { nodes: any[]; edges: any[] }): Promise<SaveWorkflowResult | null> {try {const response = await fetch(`${getApiBase()}/workflows`, {method: 'POST',@@ -36,10 +44,11 @@ export const workflowApi = {body: JSON.stringify({ workflow_id: workflowId, name, data })});const result = await response.json();- return result.success;+ if (!result.success) return null;+ return { success: true, slug: result.slug, name: result.name };} catch (error) {console.error('Failed to save workflow:', error);- return false;+ return null;}},diff --git a/client/src/store/useAppStore.ts b/client/src/store/useAppStore.tsindex 78a88246..4646cf5c 100644--- a/client/src/store/useAppStore.ts+++ b/client/src/store/useAppStore.ts@@ -21,7 +21,13 @@ export interface WorkflowData {nodes: Node[];edges: Edge[];name: string;+ /** Stable UUID — backend system identity. Never changes on rename. */id: string;+ /** Human-readable slug derived from name (e.g. "AI_Assistant_1").+ * Backend recomputes on every name change and rotates the on-disk+ * workspace dir + Temporal Web UI prefix to match. Read-only on+ * the client — server is the source of truth. */+ slug: string;createdAt: Date;lastModified: Date;}@@ -109,6 +115,7 @@ interface AppStore {const createDefaultWorkflow = (): WorkflowData => ({id: generateWorkflowId(),name: theme.constants.defaultWorkflowName,+ slug: '', // Server allocates on first save.nodes: [],edges: [],createdAt: new Date(),@@ -213,26 +220,27 @@ export const useAppStore = create<AppStore>((set, get) => ({const { currentWorkflow } = get();if (!currentWorkflow) return;- const updatedWorkflow = {- ...currentWorkflow,- lastModified: new Date(),- };-// Save to database - sanitize node.data to only include UI fields (label, disabled, condition).// Parameters live in the DB node_parameters table, not in node.data.- const success = await workflowApi.saveWorkflow(- updatedWorkflow.id,- updatedWorkflow.name,- { nodes: sanitizeNodes(updatedWorkflow.nodes), edges: updatedWorkflow.edges }+ // The save handler returns the canonical slug (recomputed server-side+ // when the display name changed) so we can sync the store with it.+ const result = await workflowApi.saveWorkflow(+ currentWorkflow.id,+ currentWorkflow.name,+ { nodes: sanitizeNodes(currentWorkflow.nodes), edges: currentWorkflow.edges });- if (!success) {+ if (!result) {console.error('Failed to save workflow to database');return;}set({- currentWorkflow: updatedWorkflow,+ currentWorkflow: {+ ...currentWorkflow,+ slug: result.slug ?? currentWorkflow.slug,+ lastModified: new Date(),+ },hasUnsavedChanges: false,});invalidateWorkflowsList();@@ -248,6 +256,7 @@ export const useAppStore = create<AppStore>((set, get) => ({const workflowData: WorkflowData = {id: result.id,name: result.name,+ slug: result.slug ?? '',nodes,edges,createdAt: new Date(result.createdAt),diff --git a/server/core/database.py b/server/core/database.pyindex 34ffbe59..5039f825 100644--- a/server/core/database.py+++ b/server/core/database.py@@ -273,8 +273,23 @@ class Database:# Workflows# ============================================================================- async def save_workflow(self, workflow_id: str, name: str, data: Dict[str, Any], description: Optional[str] = None) -> bool:- """Save or update workflow."""+ async def save_workflow(+ self,+ workflow_id: str,+ name: str,+ slug: str,+ data: Dict[str, Any],+ description: Optional[str] = None,+ ) -> bool:+ """Save or update workflow.++ ``slug`` is required for new rows and is updated on every save+ for existing rows (so a rename routed through this path stays+ consistent). Callers compute the slug via+ :func:`services.workflow_naming.next_available_slug` before+ calling this method — the unique constraint on the column is+ the final check against collision.+ """try:async with self.get_session() as session:stmt = select(Workflow).where(Workflow.id == workflow_id)@@ -283,10 +298,11 @@ class Database:if existing:existing.name = name+ existing.slug = slugexisting.description = descriptionexisting.data = dataelse:- existing = Workflow(id=workflow_id, name=name, description=description, data=data)+ existing = Workflow(id=workflow_id, name=name, slug=slug, description=description, data=data)session.add(existing)await session.commit()@@ -320,6 +336,48 @@ class Database:logger.error("Failed to get all workflows", error=str(e))return []+ async def list_workflow_slugs(self) -> List[tuple]:+ """Cheap projection of ``(id, slug)`` pairs.++ Consumed by :func:`services.workflow_naming.next_available_slug`+ to find the lowest free ``_<N>`` suffix for a given slug base.+ Returns an empty list on error so the slug allocator falls+ through to ``_1``.+ """+ try:+ async with self.get_session() as session:+ stmt = select(Workflow.id, Workflow.slug)+ result = await session.execute(stmt)+ return list(result.all())+ except Exception as e:+ logger.error("Failed to list workflow slugs", error=str(e))+ return []++ async def rename_workflow(self, workflow_id: str, new_name: str, new_slug: str) -> bool:+ """Atomically update display name + slug. ``id`` (PK) never moves.++ Cross-table FK references (``Execution.workflow_id``) and soft+ refs (``ConsoleLog`` / ``TokenUsageMetric`` / etc.) all key on+ the UUID, so renaming is a single-row UPDATE — no cascade+ needed. The unique constraint on ``slug`` is the collision+ guard; the caller must pre-allocate a free slug via+ :func:`services.workflow_naming.next_available_slug`.+ """+ try:+ async with self.get_session() as session:+ stmt = select(Workflow).where(Workflow.id == workflow_id)+ result = await session.execute(stmt)+ existing = result.scalar_one_or_none()+ if not existing:+ return False+ existing.name = new_name+ existing.slug = new_slug+ await session.commit()+ return True+ except Exception as e:+ logger.error("Failed to rename workflow", workflow_id=workflow_id, error=str(e))+ return False+async def delete_workflow(self, workflow_id: str) -> bool:"""Delete workflow."""try:diff --git a/server/models/database.py b/server/models/database.pyindex 42f9b566..fb810234 100644--- a/server/models/database.py+++ b/server/models/database.py@@ -23,12 +23,27 @@ class NodeParameter(SQLModel, table=True):class Workflow(SQLModel, table=True):- """Workflow definitions."""+ """Workflow definitions.++ Three identity carriers (Wave 14 split):++ * ``id`` — opaque UUID, stable for the lifetime of the workflow.+ FK target for every cross-table reference (``Execution.workflow_id``,+ soft refs on ``ConsoleLog`` / ``TokenUsageMetric`` / etc.), Temporal+ Search Attributes, log context. Never changes on rename.+ * ``name`` — free-form human display name ("AI Assistant"). Mutable.+ * ``slug`` — sanitized + dedup-counter form ("AI_Assistant_1").+ Recomputed on rename via :func:`services.workflow_naming.next_available_slug`.+ Used for workspace dirs on disk, Temporal workflow IDs in the+ Web UI, cron Schedule IDs, export filenames — anywhere a human+ sees the workflow externally. UNIQUE by construction.+ """__tablename__ = "workflows"id: str = Field(primary_key=True, max_length=255)name: str = Field(max_length=255)+ slug: str = Field(default="", max_length=64, unique=True, index=True)description: Optional[str] = Field(default=None, max_length=1000)data: Dict[str, Any] = Field(sa_column=Column(JSON))created_at: datetime = Field(diff --git a/server/nodes/tool/agent_builder/__init__.py b/server/nodes/tool/agent_builder/__init__.pyindex 497ae348..8846c886 100644--- a/server/nodes/tool/agent_builder/__init__.py+++ b/server/nodes/tool/agent_builder/__init__.py@@ -40,6 +40,7 @@ from core.logging import get_loggerfrom services import workflow_opsfrom services.node_registry import registered_node_classesfrom services.plugin import NodeContext, Operation, TaskQueue, ToolNode+from services.workflow_naming import new_workflow_id, next_available_sluglogger = get_logger(__name__)@@ -595,12 +596,17 @@ class AgentBuilderNode(ToolNode):summary="create_workflow: workflow_name is required.",)- workflow_id = f"wf_{uuid.uuid4().hex[:12]}"+ from services.plugin.deps import get_database++ database = get_database()+ workflow_id = new_workflow_id()+ slug = await next_available_slug(name, database)start_node_id = f"start-{uuid.uuid4().hex[:8]}"description = (params.workflow_description or "").strip()workflow_data = {"id": workflow_id,"name": name,+ "slug": slug,"description": description,"nodes": [{@@ -614,12 +620,10 @@ class AgentBuilderNode(ToolNode):"nodeParameters": {},}- from services.plugin.deps import get_database-- database = get_database()ok = await database.save_workflow(workflow_id,name,+ slug,workflow_data,description=description or None,)@@ -630,6 +634,6 @@ class AgentBuilderNode(ToolNode):)return AgentBuilderOutput(operation="create_workflow",- summary=(f"Created workflow '{name}' (id: {workflow_id}). " "User can switch to it from the toast notification."),+ summary=(f"Created workflow '{name}' (slug: {slug}). " "User can switch to it from the toast notification."),workflow_id=workflow_id,)diff --git a/server/pyproject.toml b/server/pyproject.tomlindex 13cca381..9f9f53c4 100644--- a/server/pyproject.toml+++ b/server/pyproject.toml@@ -103,6 +103,14 @@ dependencies = [# Markdown formatting (GFM to platform-native)"markdown-it-py>=3.0.0",+ # Workflow naming — production-grade slugify with Unicode+ # transliteration (60M dl/mo, MIT). Used by+ # ``services.workflow_naming.slugify_name`` to derive+ # ``Workflow.slug`` from user display names. Brings ``text-unidecode``+ # as a transitive dep so "日本語" -> "Ri_Ben_Yu" instead of falling+ # back to "Workflow_N".+ "python-slugify>=8.0.0",+# Local LLM SDKs — used by `nodes/model/_local_validator.py` to# introspect the user's actually-loaded models (context_length,# max_output_tokens). Replaces hand-rolled httpx probes againstdiff --git a/server/routers/database.py b/server/routers/database.pyindex 1709779a..88393b41 100644--- a/server/routers/database.py+++ b/server/routers/database.py@@ -2,12 +2,13 @@from fastapi import APIRouter, Dependsfrom pydantic import BaseModel-from typing import Dict, Any+from typing import Any, Dictfrom core.container import containerfrom core.database import Databasefrom core.logging import get_loggerfrom services.example_loader import import_examples_for_user+from services.workflow_storage.handlers import handle_save_workflowlogger = get_logger(__name__)router = APIRouter(prefix="/api/database", tags=["database"])@@ -63,11 +64,19 @@ async def delete_node_parameters(node_id: str, database: Database = Depends(lamb@router.post("/workflows")-async def save_workflow(request: WorkflowSaveRequest, database: Database = Depends(lambda: container.database())):- """Save workflow to database."""+async def save_workflow(request: WorkflowSaveRequest):+ """Save workflow — REST passthrough to the WS handler.++ Single source of truth lives in+ :func:`services.workflow_storage.handlers.handle_save_workflow` —+ it owns slug allocation, the workspace-dir rename on name change,+ and the CloudEvents ``workflow.renamed`` broadcast.+ """try:- success = await database.save_workflow(workflow_id=request.workflow_id, name=request.name, data=request.data)- return {"success": success, "workflow_id": request.workflow_id}+ return await handle_save_workflow(+ {"workflow_id": request.workflow_id, "name": request.name, "data": request.data},+ websocket=None, # type: ignore[arg-type] # unused by the handler+ )except Exception as e:logger.error("Failed to save workflow", error=str(e), exc_info=True)return {"success": False, "error": "Failed to save workflow"}@@ -99,6 +108,7 @@ async def get_all_workflows(database: Database = Depends(lambda: container.datab{"id": w.id,"name": w.name,+ "slug": w.slug,"nodeCount": len(w.data.get("nodes", [])) if w.data else 0,"createdAt": w.created_at.isoformat() if w.created_at else None,"lastModified": w.updated_at.isoformat() if w.updated_at else None,@@ -122,6 +132,7 @@ async def get_workflow(workflow_id: str, database: Database = Depends(lambda: co"workflow": {"id": workflow.id,"name": workflow.name,+ "slug": workflow.slug,"data": workflow.data,"createdAt": workflow.created_at.isoformat() if workflow.created_at else None,"lastModified": workflow.updated_at.isoformat() if workflow.updated_at else None,diff --git a/server/services/events/envelope.py b/server/services/events/envelope.pyindex 661fc60e..d1a1322b 100644--- a/server/services/events/envelope.py+++ b/server/services/events/envelope.py@@ -188,6 +188,7 @@ class WorkflowEvent(BaseModel):"execution.started","execution.stopped","imported",+ "renamed",],*,workflow_id: str,@@ -202,6 +203,13 @@ class WorkflowEvent(BaseModel):after the new workflow is persisted. Frontend listeners invalidatethe workflows query so the sidebar picks up the new entry acrossall connected clients (browser tabs).++ ``renamed`` fires from the ``rename_workflow`` WebSocket+ handler. ``data`` carries ``{name, slug, old_slug}`` so the+ frontend updates the open workflow's display + invalidates the+ workflows query for the sidebar. The ``workflow_id`` (UUID) is+ unchanged across the rename — only the human-readable fields+ change."""return cls(source="machinaos://services/workflow",diff --git a/server/services/example_loader.py b/server/services/example_loader.pyindex b6136830..170bf022 100644--- a/server/services/example_loader.py+++ b/server/services/example_loader.py@@ -54,14 +54,20 @@ async def import_examples_for_user(database) -> int:Returns the count of workflows imported."""from services.workflow_import import remap_node_ids+ from services.workflow_naming import new_workflow_id, next_available_slugfrom services.workflow_validator import validate_workflowexamples = get_example_workflows()imported = 0for example in examples:- # Use ID from JSON, prefixed with 'example_' for clarity- workflow_id = f"example_{example.get('id', 'unknown')}"+ # Fresh UUID for each example (pre-Wave-14 used "example_"+ # prefix + JSON id which produced ugly "example_example_workflow-..."+ # double-prefixed strings). Slug comes from the seed's display+ # name via the standard helper.+ workflow_id = new_workflow_id()+ example_name = example.get("name", "Example Workflow")+ slug = await next_available_slug(example_name, database)# Rewrite every node id so two examples that share ids don't# overwrite each other's parameters in the node_parameters table.@@ -107,7 +113,8 @@ async def import_examples_for_user(database) -> int:# Reuse existing save_workflow methodsuccess = await database.save_workflow(workflow_id=workflow_id,- name=example.get("name", "Example Workflow"),+ name=example_name,+ slug=slug,description=example.get("description"),data={"nodes": nodes, "edges": edges},)diff --git a/server/services/temporal/executor.py b/server/services/temporal/executor.pyindex 353bb47f..b47b3809 100644--- a/server/services/temporal/executor.py+++ b/server/services/temporal/executor.py@@ -48,25 +48,35 @@ class TemporalExecutor:edges: List[Dict],session_id: str = "default",enable_caching: bool = True,+ workflow_slug: Optional[str] = None,) -> Dict[str, Any]:"""Execute a workflow using Temporal.Args:- workflow_id: Unique workflow identifier+ workflow_id: Stable UUID system identity (FK target).nodes: List of node definitionsedges: List of edge definitionssession_id: Session identifierenable_caching: Whether to enable result caching (passed to activity)+ workflow_slug: Human-readable slug used in the Temporal Web UI+ listing prefix. Optional — falls back to ``"workflow"`` for+ one-off Runs without a saved DB row.Returns:Dict with success, outputs, execution_trace, and timing info"""start_time = time.time()- execution_id = f"temporal-{uuid.uuid4().hex[:8]}"+ # Temporal start ID surfaces in the Web UI — prefix with the+ # human-readable slug so an operator browsing the workflows+ # listing can find runs by name. The uuid8 suffix keeps per-run+ # uniqueness.+ slug_prefix = workflow_slug or "workflow"+ execution_id = f"{slug_prefix}_{uuid.uuid4().hex[:8]}"logger.info("Starting Temporal workflow execution",workflow_id=workflow_id,+ workflow_slug=workflow_slug,execution_id=execution_id,node_count=len(nodes),edge_count=len(edges),@@ -81,6 +91,7 @@ class TemporalExecutor:"edges": edges,"session_id": session_id,"workflow_id": workflow_id,+ "workflow_slug": workflow_slug,},id=execution_id,task_queue=self.task_queue,diff --git a/server/services/workflow.py b/server/services/workflow.pyindex 7c62220b..7c424119 100644--- a/server/services/workflow.py+++ b/server/services/workflow.py@@ -139,16 +139,38 @@ class WorkflowService:# NODE EXECUTION# =========================================================================- def _get_workspace_dir(self, workflow_id: Optional[str]) -> str:- """Get or create workspace directory for a workflow."""+ def _get_workspace_dir(self, workflow_slug: Optional[str]) -> str:+ """Get or create workspace directory for a workflow.++ Keyed by the human-readable ``workflow_slug`` (Wave 14) so the+ on-disk dir name matches the Temporal Web UI listing and the+ sidebar entry. Callers that don't have a slug yet pass+ ``"default"`` (one-off Run, no DB row) — preserved as the+ anonymous workspace.+ """base = Path(self.settings.workspace_base_resolved)- wf_id = workflow_id or "default"- workspace = base / wf_id+ slug = workflow_slug or "default"+ workspace = base / slugworkspace.mkdir(parents=True, exist_ok=True)resolved = str(workspace.resolve())- logger.info("[Workspace] workflow_id=%s -> %s", wf_id, resolved)+ logger.info("[Workspace] workflow_slug=%s -> %s", slug, resolved)return resolved+ async def _resolve_workflow_slug(self, workflow_id: Optional[str]) -> Optional[str]:+ """Look up the slug for a workflow_id (one query, opportunistic).++ Returns ``None`` if the row doesn't exist (one-off Run without+ a saved workflow). Callers fall back to ``"default"`` in that+ case via :meth:`_get_workspace_dir`.+ """+ if not workflow_id:+ return None+ try:+ wf = await self.database.get_workflow(workflow_id)+ return wf.slug if wf and wf.slug else None+ except Exception:+ return None+async def execute_node(self,node_id: str,@@ -159,16 +181,21 @@ class WorkflowService:session_id: str = "default",execution_id: str = None,workflow_id: str = None,+ workflow_slug: str = None,outputs: Dict[str, Any] = None,) -> Dict[str, Any]:"""Execute a single workflow node."""- workspace_dir = self._get_workspace_dir(workflow_id)+ # Resolve slug from DB if caller passed only workflow_id.+ if workflow_slug is None:+ workflow_slug = await self._resolve_workflow_slug(workflow_id)+ workspace_dir = self._get_workspace_dir(workflow_slug)context = {"nodes": nodes,"edges": edges,"session_id": session_id,"execution_id": execution_id,- "workflow_id": workflow_id, # For per-workflow status scoping (n8n pattern)+ "workflow_id": workflow_id, # UUID — stable system identity, FK target+ "workflow_slug": workflow_slug, # Human-readable, mutable on rename"workspace_dir": workspace_dir, # Per-workflow filesystem for nodes and agents"get_output_fn": self.get_node_output,"outputs": outputs or {}, # Upstream node outputs for data flow (e.g., taskTrigger -> chatAgent)@@ -198,6 +225,7 @@ class WorkflowService:session_id=context.get("session_id", "default"),execution_id=context.get("execution_id"),workflow_id=context.get("workflow_id"),+ workflow_slug=context.get("workflow_slug"),)# =========================================================================@@ -301,9 +329,14 @@ class WorkflowService:if not workflow_id:workflow_id = f"temporal_{session_id}_{int(time.time() * 1000)}"+ # Look up the human-readable slug so Temporal's Web UI shows+ # ``<slug>_<uuid8>`` instead of the opaque UUID.+ workflow_slug = await self._resolve_workflow_slug(workflow_id)+logger.info("Executing workflow via Temporal",workflow_id=workflow_id,+ workflow_slug=workflow_slug,node_count=len(nodes),)@@ -313,6 +346,7 @@ class WorkflowService:edges=edges,session_id=session_id,enable_caching=True,+ workflow_slug=workflow_slug,)# Notify status callback for completed nodes if provideddiff --git a/server/services/workflow_import.py b/server/services/workflow_import.pyindex b095c772..39281996 100644--- a/server/services/workflow_import.py+++ b/server/services/workflow_import.py@@ -35,6 +35,7 @@ from typing import Any, Dict, List, Optional, Tuplefrom core.logging import get_loggerfrom services.node_registry import get_node_class+from services.workflow_naming import new_workflow_id, next_available_slugfrom services.workflow_validator import validate_workflowlogger = get_logger(__name__)@@ -292,11 +293,14 @@ async def import_workflow(node_parameters,)- # 7. Save. Workflow id format matches the frontend's generateWorkflowId.- workflow_id = f"workflow-{int(time.time() * 1000)}-{secrets.token_hex(4)}"+ # 7. Save. UUID-based system identity + name-derived slug for+ # human-visible surfaces (folder names, Temporal Web UI).+ workflow_id = new_workflow_id()+ slug = await next_available_slug(proposed_name, database)saved = await database.save_workflow(workflow_id=workflow_id,name=proposed_name,+ slug=slug,description=workflow.get("description"),data={"nodes": remapped_nodes, "edges": remapped_edges},)diff --git a/server/services/workflow_naming.py b/server/services/workflow_naming.pynew file mode 100644index 00000000..5c9994cf--- /dev/null+++ b/server/services/workflow_naming.py@@ -0,0 +1,127 @@+"""Workflow naming — human-readable slugs derived from display names.++Separates two concerns the system used to conflate:++* ``Workflow.id`` (UUID) — stable system identity. Never changes on+ rename. Used for FK references (``Execution.workflow_id``), Temporal+ Search Attributes, CloudEvents extensions, log context, cache keys,+ in-memory ``DeploymentManager._deployments`` dict keys, frontend+ ``useAppStore.currentWorkflow.id``.+* ``Workflow.slug`` (e.g. ``AI_Assistant_1``) — human-readable derived+ identifier. Mutable on rename. Used for workspace dirs on disk,+ Temporal workflow IDs (visible in Temporal Web UI), cron Schedule IDs,+ export filenames — anywhere a human reads the workflow's name.++Slug format: ``<Sanitized_Name>_<N>`` where ``N`` starts at 1 and fills+gaps. Always-suffix — first creation of "AI Assistant" gets slug+``AI_Assistant_1``, never bare ``AI_Assistant``.++Slugification is delegated to ``python-slugify`` (declared in+``pyproject.toml``). It transliterates Unicode via ``text-unidecode``+("日本語" -> "Ri_Ben_Yu"), strips emoji, collapses runs of+non-alphanumerics, and truncates safely. We pass ``lowercase=False`` so+"AI Assistant" stays as ``AI_Assistant`` and ``separator="_"`` so the+slug is a valid Python identifier prefix (filesystem-safe on every OS,+Temporal-safe up to 1000 chars).+"""++from __future__ import annotations++import uuid+from typing import Set++from slugify import slugify++from core.logging import get_logger++logger = get_logger(__name__)+++_SLUG_SEPARATOR = "_"+_SLUG_MAX_LEN = 50+_FALLBACK_SLUG = "Workflow"+++def slugify_name(name: str) -> str:+ """Sanitize a display name into a filesystem-safe slug base.++ Examples::++ slugify_name("AI Assistant") -> "AI_Assistant"+ slugify_name("Test/Workflow:Beta!") -> "Test_Workflow_Beta"+ slugify_name("日本語") -> "Ri_Ben_Yu" (transliterated)+ slugify_name("Hello World 🚀") -> "Hello_World" (emoji stripped)+ slugify_name("!!!") -> "Workflow" (fallback)+ slugify_name("") -> "Workflow" (fallback)++ Always returns a non-empty ASCII string suitable as a slug BASE.+ Callers append ``_<N>`` to dedupe via :func:`next_available_slug`.+ """+ slug = slugify(+ name or "",+ separator=_SLUG_SEPARATOR,+ lowercase=False,+ max_length=_SLUG_MAX_LEN,+ word_boundary=False,+ )+ return slug or _FALLBACK_SLUG+++async def next_available_slug(+ name: str,+ database,+ *,+ exclude_id: str | None = None,+) -> str:+ """Return the next free ``<Slug>_<N>`` for the given display name.++ Fill-gap: if ``AI_Assistant_2`` was deleted, the next creation of+ "AI Assistant" reuses ``_2``. Always-suffix: first creation gets ``_1``.++ ``exclude_id`` lets a rename ignore its own current slug — important+ so renaming "AI Assistant" -> "AI Assistant!" (which slugifies to+ the same base) doesn't bump itself to ``_2``.++ Args:+ name: User display name (e.g. ``"AI Assistant"``).+ database: ``Database`` instance — must expose+ :meth:`list_workflow_slugs` returning ``(id, slug)`` pairs.+ exclude_id: Workflow id to skip (rename path, not creation).+ """+ base = slugify_name(name)+ prefix = f"{base}_"+ rows = await database.list_workflow_slugs()+ taken: Set[int] = set()+ for row_id, slug in rows:+ if exclude_id is not None and row_id == exclude_id:+ continue+ if slug and slug.startswith(prefix):+ tail = slug[len(prefix):]+ if tail.isdigit():+ taken.add(int(tail))+ n = 1+ while n in taken:+ n += 1+ return f"{base}_{n}"+++def new_workflow_id() -> str:+ """Canonical workflow UUID: 32 lowercase hex chars, no prefix.++ Replaces the three pre-Wave-14 generation conventions+ (``wf_<12hex>`` from agent_builder, ``workflow-<ms>-<8hex>`` from+ workflow_import, ``example_<original_id>`` from example_loader)+ with a single stable form. The id never appears in human-readable+ surfaces — it's pure system identity — so a bare UUID is the right+ shape. Stays on stdlib to avoid adding a dep for marginal benefit+ (ULID/UUIDv7 would gain sortability but every consumer treats the+ id as opaque).+ """+ return uuid.uuid4().hex+++__all__ = [+ "slugify_name",+ "next_available_slug",+ "new_workflow_id",+]diff --git a/server/services/workflow_storage/handlers.py b/server/services/workflow_storage/handlers.pyindex 7673ea31..b31d907c 100644--- a/server/services/workflow_storage/handlers.py+++ b/server/services/workflow_storage/handlers.py@@ -1,22 +1,19 @@"""Workflow storage WS handlers extracted from ``routers/websocket.py`` (Wave 13.7).-5 handlers wrapping the workflow-record CRUD surface:- - ``save_workflow`` — persist new/updated workflow JSON.- - ``import_workflow`` — two-step import preview + commit- (delegates to ``services.workflow_import``).- - ``get_workflow`` — fetch by ID.- - ``get_all_workflows`` — sidebar list (minimal projection).- - ``delete_workflow`` — remove by ID.--Wire shape preserved across the move.+5 handlers wrapping the workflow-record CRUD surface. ``save_workflow``+detects display-name changes and applies the slug-rename side effects+(folder move + lifecycle broadcast) inline, so the frontend's existing+auto-save chain IS the rename path — no separate rename endpoint."""from __future__ import annotations+from pathlib import Pathfrom typing import Any, Dictfrom fastapi import WebSocket+from core.config import Settingsfrom core.container import containerfrom core.logging import get_loggerfrom services.ws_handler_registry import ws_handler@@ -24,15 +21,71 @@ from services.ws_handler_registry import ws_handlerlogger = get_logger(__name__)+def _move_workspace(old_slug: str, new_slug: str) -> None:+ """Rename ``<workspace_base>/<old_slug>/`` on disk. No-op when the+ source is missing (lazy creation) or the target already exists.+ Failure is cosmetic — DB is the source of truth.+ """+ if not old_slug or old_slug == new_slug:+ return+ base = Path(Settings().workspace_base_resolved)+ src, dst = base / old_slug, base / new_slug+ if not src.is_dir() or dst.exists():+ return+ try:+ src.rename(dst)+ logger.info("[workflow] workspace renamed %s -> %s", old_slug, new_slug)+ except OSError as exc:+ logger.warning("[workflow] workspace rename failed: %s", exc)+++async def _broadcast_renamed(workflow_id: str, name: str, slug: str, old_slug: str) -> None:+ """CloudEvents ``workflow.renamed`` — sidebar + open workflow refresh."""+ try:+ from services.status_broadcaster import get_status_broadcaster++ await get_status_broadcaster().broadcast_workflow_lifecycle(+ "renamed",+ workflow_id=workflow_id,+ name=name,+ slug=slug,+ old_slug=old_slug,+ )+ except Exception:+ logger.debug("[workflow] rename broadcast failed", exc_info=True)++async def handle_save_workflow(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:- """Save workflow to database."""+ """Save workflow. Re-slugs + renames workspace dir when name changes.++ The frontend's auto-save chain (TopToolbar inline rename ->+ ``updateWorkflow({name})`` -> debounced save) flows through this+ handler, so renaming happens here — no dedicated rename endpoint.+ """+ from services.workflow_naming import next_available_slug+database = container.database()+ workflow_id = data["workflow_id"]+ name = data["name"]+ existing = await database.get_workflow(workflow_id)++ if existing and existing.name == name and existing.slug:+ slug = existing.slug+ else:+ slug = await next_available_slug(name, database, exclude_id=workflow_id)+success = await database.save_workflow(- workflow_id=data["workflow_id"],- name=data["name"],+ workflow_id=workflow_id,+ name=name,+ slug=slug,data=data.get("data", {}),)- return {"success": success, "workflow_id": data["workflow_id"]}++ if existing and existing.slug and existing.slug != slug:+ _move_workspace(existing.slug, slug)+ await _broadcast_renamed(workflow_id, name, slug, existing.slug)++ return {"success": success, "workflow_id": workflow_id, "name": name, "slug": slug}@ws_handler()@@ -79,6 +132,7 @@ async def handle_get_workflow(data: Dict[str, Any], websocket: WebSocket) -> Dic"workflow": {"id": workflow.id,"name": workflow.name,+ "slug": workflow.slug,"data": workflow.data,"created_at": workflow.created_at.isoformat() if workflow.created_at else None,"updated_at": workflow.updated_at.isoformat() if workflow.updated_at else None,@@ -97,6 +151,7 @@ async def handle_get_all_workflows(data: Dict[str, Any], websocket: WebSocket) -{"id": w.id,"name": w.name,+ "slug": w.slug,"nodeCount": len(w.data.get("nodes", [])) if w.data else 0,"created_at": w.created_at.isoformat() if w.created_at else None,"updated_at": w.updated_at.isoformat() if w.updated_at else None,diff --git a/server/tests/nodes/test_agent_builder.py b/server/tests/nodes/test_agent_builder.pyindex 82cea13f..e95ed189 100644--- a/server/tests/nodes/test_agent_builder.py+++ b/server/tests/nodes/test_agent_builder.py@@ -416,6 +416,9 @@ class TestCreateWorkflow:mock_db = MagicMock()mock_db.save_workflow = AsyncMock(return_value=True)+ # Wave 14: agent_builder calls next_available_slug, which+ # reads ``list_workflow_slugs`` for the dedup counter scan.+ mock_db.list_workflow_slugs = AsyncMock(return_value=[])mock_container = MagicMock()mock_container.database.return_value = mock_db@@ -423,8 +426,11 @@ class TestCreateWorkflow:result = await node.create_workflow(ctx, params)assert result.workflow_id is not None- assert result.workflow_id.startswith("wf_")- assert "My New Workflow" in result.summary+ # Wave 14: workflow ids are bare 32-hex UUIDs (no prefix).+ assert len(result.workflow_id) == 32+ assert all(c in "0123456789abcdef" for c in result.workflow_id)+ # Slug is the human-readable identifier surfaced in the summary.+ assert "My_New_Workflow_1" in result.summarymock_db.save_workflow.assert_awaited_once()async def test_returns_failure_summary_when_persist_fails(self):@@ -437,6 +443,7 @@ class TestCreateWorkflow:mock_db = MagicMock()mock_db.save_workflow = AsyncMock(return_value=False)+ mock_db.list_workflow_slugs = AsyncMock(return_value=[])mock_container = MagicMock()mock_container.database.return_value = mock_dbdiff --git a/server/tests/services/test_workflow_naming.py b/server/tests/services/test_workflow_naming.pynew file mode 100644index 00000000..a41ade0c--- /dev/null+++ b/server/tests/services/test_workflow_naming.py@@ -0,0 +1,193 @@+"""Unit tests for ``services.workflow_naming``.++Locks the contract for the slug allocator that derives human-readable+workflow identifiers (``AI_Assistant_1``) from arbitrary display names.+The slug surfaces as the on-disk workspace folder, the Temporal Web UI+prefix, and the sidebar label — so regressions here have visible+operator + filesystem impact.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import List, Tuple++import pytest++from services.workflow_naming import (+ new_workflow_id,+ next_available_slug,+ slugify_name,+)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _fake_db(rows: List[Tuple[str, str]]):+ """Minimal duck-typed Database exposing ``list_workflow_slugs``."""++ async def list_workflow_slugs():+ return list(rows)++ return SimpleNamespace(list_workflow_slugs=list_workflow_slugs)+++# ---------------------------------------------------------------------------+# slugify_name — every shape the user might type+# ---------------------------------------------------------------------------+++ "name,expected",+ [+ ("AI Assistant", "AI_Assistant"),+ ("Test/Workflow:Beta!", "Test_Workflow_Beta"),+ ("Hello World", "Hello_World"),+ ("already_snake", "already_snake"),+ ("UPPER", "UPPER"),+ ("lower", "lower"),+ ("MixedCase Workflow 3", "MixedCase_Workflow_3"),+ (" leading/trailing ", "leading_trailing"),+ ("dot.separated.name", "dot_separated_name"),+ ("colon:separated", "colon_separated"),+ ("a-b-c", "a_b_c"),+ ],+)+def test_slugify_name_ascii(name: str, expected: str) -> None:+ assert slugify_name(name) == expected+++ "name",+ ["", " ", "!!!", "@#$%", "...", "___", " - "],+)+def test_slugify_name_falls_back_when_empty(name: str) -> None:+ assert slugify_name(name) == "Workflow"+++def test_slugify_name_truncates_long_input() -> None:+ long_name = "a" * 200+ assert slugify_name(long_name) == "a" * 50+++def test_slugify_name_preserves_case() -> None:+ # python-slugify lowercases by default; we explicitly disable that.+ assert slugify_name("AI Assistant") == "AI_Assistant"+ assert slugify_name("AI Assistant") != "ai_assistant"+++def test_slugify_name_strips_emoji() -> None:+ assert slugify_name("Hello World 🚀") == "Hello_World"+++def test_slugify_name_transliterates_unicode() -> None:+ # python-slugify pulls in text-unidecode by default — non-ASCII names+ # transliterate to ASCII instead of falling back to "Workflow_N".+ # Exact transliteration depends on the lib version; assert ASCII ++ # non-empty + not the bare fallback.+ result = slugify_name("日本語")+ assert result != "Workflow"+ assert result.isascii()+ assert result.replace("_", "").isalnum()+++def test_slugify_name_none_input() -> None:+ # Defensive — callers should pass strings, but the helper must not+ # raise on None.+ assert slugify_name(None) == "Workflow" # type: ignore[arg-type]+++# ---------------------------------------------------------------------------+# next_available_slug — fill-gap counter+# ---------------------------------------------------------------------------+++async def test_next_available_slug_first_creation_gets_underscore_1() -> None:+ db = _fake_db([])+ assert await next_available_slug("AI Assistant", db) == "AI_Assistant_1"+++async def test_next_available_slug_increments_on_collision() -> None:+ db = _fake_db([("u1", "AI_Assistant_1")])+ assert await next_available_slug("AI Assistant", db) == "AI_Assistant_2"+++async def test_next_available_slug_fills_gaps() -> None:+ # AI_Assistant_2 was deleted; next allocation reuses the slot.+ db = _fake_db([("u1", "AI_Assistant_1"), ("u3", "AI_Assistant_3")])+ assert await next_available_slug("AI Assistant", db) == "AI_Assistant_2"+++async def test_next_available_slug_skips_unrelated_prefixes() -> None:+ # Other workflows with different slug bases must not bump our counter.+ db = _fake_db([+ ("u1", "Cool_Bot_1"),+ ("u2", "Cool_Bot_2"),+ ("u3", "Different_3"),+ ])+ assert await next_available_slug("AI Assistant", db) == "AI_Assistant_1"+++async def test_next_available_slug_ignores_non_numeric_suffix() -> None:+ # Slugs that share the prefix but have a non-digit suffix shouldn't+ # mess with the counter (defensive — shouldn't happen in practice).+ db = _fake_db([("u1", "AI_Assistant_X"), ("u2", "AI_Assistant_1")])+ assert await next_available_slug("AI Assistant", db) == "AI_Assistant_2"+++async def test_next_available_slug_exclude_id_skips_self() -> None:+ # Rename path: a workflow renaming itself to a name whose slug base+ # is unchanged must NOT bump itself to _2 over its own existing slug.+ db = _fake_db([("self_uuid", "AI_Assistant_1"), ("other_uuid", "AI_Assistant_2")])+ result = await next_available_slug(+ "AI Assistant", db, exclude_id="self_uuid",+ )+ # _1 is free now (because we're excluding self) — fill-gap returns _1.+ assert result == "AI_Assistant_1"+++async def test_next_available_slug_empty_name_uses_fallback_base() -> None:+ db = _fake_db([])+ assert await next_available_slug("", db) == "Workflow_1"+ assert await next_available_slug("!!!", db) == "Workflow_1"+++async def test_next_available_slug_special_chars_in_name() -> None:+ db = _fake_db([])+ assert await next_available_slug("Test/Workflow:Beta!", db) == "Test_Workflow_Beta_1"+++# ---------------------------------------------------------------------------+# new_workflow_id — UUID shape+# ---------------------------------------------------------------------------+++def test_new_workflow_id_is_32_hex_chars() -> None:+ wid = new_workflow_id()+ assert len(wid) == 32+ assert all(c in "0123456789abcdef" for c in wid)+++def test_new_workflow_id_is_unique() -> None:+ ids = {new_workflow_id() for _ in range(1000)}+ assert len(ids) == 1000+++def test_new_workflow_id_no_prefix() -> None:+ # Wave 14 dropped the per-site prefixes (wf_, workflow-, example_).+ wid = new_workflow_id()+ assert not wid.startswith("wf_")+ assert not wid.startswith("workflow-")+ assert not wid.startswith("example_")+ assert "-" not in wid # bare hex, no separatorsdiff --git a/server/tests/services/test_workflow_rename.py b/server/tests/services/test_workflow_rename.pynew file mode 100644index 00000000..7492c249--- /dev/null+++ b/server/tests/services/test_workflow_rename.py@@ -0,0 +1,303 @@+"""End-to-end tests for the workflow rename flow.++``handle_save_workflow`` IS the rename path: when the display name+changes, the handler must (1) allocate a fresh slug, (2) atomically+update DB name + slug while keeping the UUID id stable, (3) rename+the on-disk workspace dir if it exists, (4) broadcast a CloudEvents+``workflow.renamed`` envelope so other clients refresh.+"""++from __future__ import annotations++import sys+import types+from pathlib import Path+from types import SimpleNamespace+from typing import Any, Dict, List, Optional, Tuple+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+++# ---------------------------------------------------------------------------+# Fake Database — in-memory store with the same async surface+# ---------------------------------------------------------------------------+++class _FakeDatabase:+ def __init__(self) -> None:+ self._rows: Dict[str, SimpleNamespace] = {}++ async def get_workflow(self, workflow_id: str):+ return self._rows.get(workflow_id)++ async def save_workflow(+ self,+ workflow_id: str,+ name: str,+ slug: str,+ data: Dict[str, Any],+ description: Optional[str] = None,+ ) -> bool:+ self._rows[workflow_id] = SimpleNamespace(+ id=workflow_id,+ name=name,+ slug=slug,+ description=description,+ data=data,+ )+ return True++ async def list_workflow_slugs(self) -> List[Tuple[str, str]]:+ return [(r.id, r.slug) for r in self._rows.values()]+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++def fake_db():+ return _FakeDatabase()+++def workspace_root(tmp_path: Path):+ """Tmpdir as the ``workspace_base_resolved`` for the rename test."""+ root = tmp_path / "workspaces"+ root.mkdir()+ return root+++def patched_handler_deps(fake_db, workspace_root):+ """Wire the handler's container + Settings + broadcaster to fakes.++ The handler reaches into:+ * ``core.container.container.database()`` — DB row store+ * ``core.config.Settings().workspace_base_resolved`` — folder root+ * ``services.status_broadcaster.get_status_broadcaster()`` — broadcast++ All three are patched here so the handler runs against the in-memory+ store + tmpdir workspace + spy broadcaster. ``status_broadcaster`` is+ stubbed at the ``sys.modules`` level because the real module pulls in+ ``orjson`` (not installed in the unit-test env) — the handler does a+ lazy ``from services.status_broadcaster import get_status_broadcaster``+ inside the function body, so the sys.modules entry intercepts cleanly.+ """+ from services.workflow_storage import handlers++ broadcaster_spy = MagicMock()+ broadcaster_spy.broadcast_workflow_lifecycle = AsyncMock()++ stub_module = types.ModuleType("services.status_broadcaster")+ stub_module.get_status_broadcaster = lambda: broadcaster_spy+ sentinel = object()+ original = sys.modules.get("services.status_broadcaster", sentinel)+ sys.modules["services.status_broadcaster"] = stub_module++ settings_stub = MagicMock()+ settings_stub.workspace_base_resolved = str(workspace_root)++ with patch.object(handlers, "container") as mock_container, \+ patch.object(handlers, "Settings", return_value=settings_stub):+ mock_container.database.return_value = fake_db+ try:+ yield SimpleNamespace(+ db=fake_db,+ workspace_root=workspace_root,+ broadcaster=broadcaster_spy,+ )+ finally:+ if original is sentinel:+ sys.modules.pop("services.status_broadcaster", None)+ else:+ sys.modules["services.status_broadcaster"] = original+++# ---------------------------------------------------------------------------+# Tests+# ---------------------------------------------------------------------------+++async def test_save_new_workflow_allocates_slug(patched_handler_deps) -> None:+ from services.workflow_storage.handlers import handle_save_workflow++ result = await handle_save_workflow(+ {"workflow_id": "uuid-1", "name": "AI Assistant", "data": {"nodes": []}},+ websocket=None,+ )++ assert result["success"] is True+ assert result["workflow_id"] == "uuid-1"+ assert result["name"] == "AI Assistant"+ assert result["slug"] == "AI_Assistant_1"++ row = await patched_handler_deps.db.get_workflow("uuid-1")+ assert row.slug == "AI_Assistant_1"+ assert row.name == "AI Assistant"+++async def test_save_existing_workflow_same_name_keeps_slug(patched_handler_deps) -> None:+ """Re-saving with the same name must NOT bump the slug counter."""+ from services.workflow_storage.handlers import handle_save_workflow++ await handle_save_workflow(+ {"workflow_id": "uuid-1", "name": "AI Assistant", "data": {"nodes": []}},+ websocket=None,+ )+ # Second save with same name — slug stays as _1.+ result = await handle_save_workflow(+ {"workflow_id": "uuid-1", "name": "AI Assistant", "data": {"nodes": ["a"]}},+ websocket=None,+ )++ assert result["slug"] == "AI_Assistant_1"+ # And no broadcast since nothing changed visibly.+ patched_handler_deps.broadcaster.broadcast_workflow_lifecycle.assert_not_called()+++async def test_rename_via_save_recomputes_slug(patched_handler_deps) -> None:+ """The whole user story: create, rename, observe new slug + UUID stable."""+ from services.workflow_storage.handlers import handle_save_workflow++ create = await handle_save_workflow(+ {"workflow_id": "uuid-1", "name": "AI Assistant", "data": {"nodes": []}},+ websocket=None,+ )+ assert create["slug"] == "AI_Assistant_1"++ rename = await handle_save_workflow(+ {"workflow_id": "uuid-1", "name": "Cool Bot", "data": {"nodes": []}},+ websocket=None,+ )++ # UUID unchanged; slug + name updated.+ assert rename["workflow_id"] == "uuid-1"+ assert rename["name"] == "Cool Bot"+ assert rename["slug"] == "Cool_Bot_1"++ # DB reflects the same.+ row = await patched_handler_deps.db.get_workflow("uuid-1")+ assert row.id == "uuid-1"+ assert row.name == "Cool Bot"+ assert row.slug == "Cool_Bot_1"+++async def test_rename_moves_workspace_directory(patched_handler_deps) -> None:+ """When a workspace exists under the old slug, it follows the rename."""+ from services.workflow_storage.handlers import handle_save_workflow++ await handle_save_workflow(+ {"workflow_id": "uuid-1", "name": "AI Assistant", "data": {"nodes": []}},+ websocket=None,+ )+ # Simulate execution having created the workspace folder.+ old_ws = patched_handler_deps.workspace_root / "AI_Assistant_1"+ old_ws.mkdir()+ (old_ws / "marker.txt").write_text("preserved")++ await handle_save_workflow(+ {"workflow_id": "uuid-1", "name": "Cool Bot", "data": {"nodes": []}},+ websocket=None,+ )++ new_ws = patched_handler_deps.workspace_root / "Cool_Bot_1"+ assert not old_ws.exists()+ assert new_ws.is_dir()+ assert (new_ws / "marker.txt").read_text() == "preserved"+++async def test_rename_without_workspace_dir_is_harmless(patched_handler_deps) -> None:+ """A workflow that never executed has no workspace dir to move."""+ from services.workflow_storage.handlers import handle_save_workflow++ await handle_save_workflow(+ {"workflow_id": "uuid-1", "name": "AI Assistant", "data": {}},+ websocket=None,+ )++ # No folder on disk yet.+ assert not (patched_handler_deps.workspace_root / "AI_Assistant_1").exists()++ # Rename should still succeed.+ result = await handle_save_workflow(+ {"workflow_id": "uuid-1", "name": "Cool Bot", "data": {}},+ websocket=None,+ )++ assert result["slug"] == "Cool_Bot_1"+++async def test_rename_broadcasts_workflow_lifecycle(patched_handler_deps) -> None:+ """Every rename emits ``workflow.renamed`` so other clients refresh."""+ from services.workflow_storage.handlers import handle_save_workflow++ await handle_save_workflow(+ {"workflow_id": "uuid-1", "name": "AI Assistant", "data": {}},+ websocket=None,+ )+ patched_handler_deps.broadcaster.broadcast_workflow_lifecycle.reset_mock()++ await handle_save_workflow(+ {"workflow_id": "uuid-1", "name": "Cool Bot", "data": {}},+ websocket=None,+ )++ bcast = patched_handler_deps.broadcaster.broadcast_workflow_lifecycle+ bcast.assert_called_once()+ args, kwargs = bcast.call_args+ assert args == ("renamed",)+ assert kwargs == {+ "workflow_id": "uuid-1",+ "name": "Cool Bot",+ "slug": "Cool_Bot_1",+ "old_slug": "AI_Assistant_1",+ }+++async def test_three_same_name_workflows_get_sequential_slugs(patched_handler_deps) -> None:+ """Always-suffix semantics + sequential counter on collision."""+ from services.workflow_storage.handlers import handle_save_workflow++ r1 = await handle_save_workflow(+ {"workflow_id": "uuid-1", "name": "AI Assistant", "data": {}}, websocket=None,+ )+ r2 = await handle_save_workflow(+ {"workflow_id": "uuid-2", "name": "AI Assistant", "data": {}}, websocket=None,+ )+ r3 = await handle_save_workflow(+ {"workflow_id": "uuid-3", "name": "AI Assistant", "data": {}}, websocket=None,+ )++ assert (r1["slug"], r2["slug"], r3["slug"]) == (+ "AI_Assistant_1",+ "AI_Assistant_2",+ "AI_Assistant_3",+ )+++async def test_save_returns_slug_for_frontend_sync(patched_handler_deps) -> None:+ """Frontend reads ``slug`` from the save response to update its store+ without waiting for the broadcast. Contract: shape includes+ ``workflow_id``, ``name``, ``slug``, ``success``.+ """+ from services.workflow_storage.handlers import handle_save_workflow++ result = await handle_save_workflow(+ {"workflow_id": "uuid-1", "name": "AI Assistant", "data": {}},+ websocket=None,+ )++ assert set(result.keys()) >= {"success", "workflow_id", "name", "slug"}+ assert result["workflow_id"] == "uuid-1"+ assert result["slug"] == "AI_Assistant_1"diff --git a/server/tests/test_workflow_validator.py b/server/tests/test_workflow_validator.pyindex 2bf30aa2..be9054ba 100644--- a/server/tests/test_workflow_validator.py+++ b/server/tests/test_workflow_validator.py@@ -423,6 +423,9 @@ def _fake_database(existing_names: list[str] | None = None):db = MagicMock()db.get_all_workflows = AsyncMock(return_value=[_FakeWorkflow(n) for n in (existing_names or [])])+ # Wave 14: workflow_import.import_workflow allocates a slug via+ # ``next_available_slug`` before save, which scans existing slugs.+ db.list_workflow_slugs = AsyncMock(return_value=[])async def save_workflow(**kwargs):saved_workflows.append(kwargs)@@ -472,7 +475,9 @@ class TestImportWorkflowOrchestrator:)assert result["success"] is Trueassert result["preview"] is False- assert result["workflow_id"].startswith("workflow-")+ # Wave 14: workflow ids are bare 32-hex UUIDs (no prefix).+ assert len(result["workflow_id"]) == 32+ assert all(c in "0123456789abcdef" for c in result["workflow_id"])assert result["name"] == "My Workflow"assert len(db._saved_workflows) == 1@@ -633,7 +638,9 @@ class TestImportWorkflowOrchestrator:assert len(calls) == 1, "import_workflow save path must call broadcast_workflow_lifecycle " "exactly once on success."stage, kwargs = calls[0]assert stage == "imported"- assert kwargs["workflow_id"].startswith("workflow-")+ # Wave 14: workflow ids are bare 32-hex UUIDs (no prefix).+ assert len(kwargs["workflow_id"]) == 32+ assert all(c in "0123456789abcdef" for c in kwargs["workflow_id"])assert kwargs["name"] == "Broadcast Test"