Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat: add resumable recipe execution foundation

Juan Denis811cf7dde928
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index aa298160..467d1f5b 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -380,6 +380,8 @@ def create_app(config_name=None):
# scheduled backups).
from app.services.deployment_job_service import DeploymentJobService
DeploymentJobService.register_jobs()
+ from app.services.recipe_execution_service import RecipeExecutionService
+ RecipeExecutionService.register_jobs()
# WorkflowEngine.register_jobs() removed in plan 45 Phase 4 (engine retired).
from app.services.backup_service import BackupService
BackupService.register_jobs()
diff --git a/backend/app/api/recipes.py b/backend/app/api/recipes.py
new file mode 100644
index 00000000..0a1c9399
--- /dev/null
+++ b/backend/app/api/recipes.py
@@ -0,0 +1,114 @@
+"""Recipe run API (plan 68 Phase 0).
+
+Registry browsing and bundled recipe content land in later phases. This first
+surface accepts a reviewed inline/stored v1 manifest, creates a normal
+DeploymentJob, and resumes encrypted human handoffs on that same run.
+"""
+
+from flask import Blueprint, jsonify, request
+
+from app import db
+from app.middleware.rbac import admin_required, get_current_user
+from app.models.application_manifest import STATUS_ERROR, STATUS_PENDING
+from app.models.deployment_job import DeploymentJob
+from app.models.project import Project
+from app.services.manifest_persistence_service import ManifestPersistenceService
+from app.services.manifest_spec_service import ManifestError, ManifestSpecService
+from app.services.recipe_execution_service import (
+ RECIPE_JOB_KIND,
+ RecipeExecutionService,
+)
+
+
+recipes_bp = Blueprint('recipes', __name__)
+
+
+def _normalized_recipe(data, project_id):
+ if 'content' in data:
+ return ManifestSpecService.normalize_text(data['content']), data['content']
+ if 'manifest' in data:
+ return ManifestSpecService.normalize(data['manifest']), None
+ from app.models.application_manifest import ApplicationManifest
+ row = ApplicationManifest.query.filter_by(project_id=project_id).first()
+ if row and row.get_normalized():
+ return row.get_normalized(), row.raw_text
+ raise ManifestError(['Provide `content`/`manifest`, or store one first'])
+
+
+@recipes_bp.route('/runs', methods=['POST'])
+@admin_required
+def start_recipe_run():
+ data = request.get_json(silent=True) or {}
+ project = Project.query.get(data.get('project_id')) if data.get('project_id') else None
+ if not project:
+ return jsonify({'error': 'A valid project_id is required'}), 400
+ try:
+ normalized, raw = _normalized_recipe(data, project.id)
+ except ManifestError as exc:
+ return jsonify({'error': 'Invalid Recipe manifest', 'errors': exc.errors}), 400
+
+ unsupported = RecipeExecutionService.unsupported_capabilities(normalized)
+ if unsupported:
+ return jsonify({
+ 'success': False,
+ 'error': 'This panel does not support every Recipe capability',
+ 'unsupported_capabilities': unsupported,
+ }), 400
+
+ row = ManifestPersistenceService.store_manifest(
+ project_id=project.id, normalized=normalized, raw_text=raw,
+ status=STATUS_PENDING)
+ db.session.commit()
+
+ user = get_current_user()
+ wait = request.args.get('wait', 'false').lower() == 'true'
+ result = RecipeExecutionService.start(
+ project, normalized, user_id=user.id,
+ slug=data.get('slug'), title=data.get('title'),
+ manifest_row=row, wait=wait)
+ if not result.get('success'):
+ row.status = STATUS_ERROR
+ row.last_error = result.get('error')
+ db.session.commit()
+ return jsonify(result), 400
+
+ _audit('recipe.start', user.id, result.get('job_id'), {
+ 'project_id': project.id, 'slug': data.get('slug'),
+ })
+ return jsonify(result), 200 if wait else 202
+
+
+@recipes_bp.route('/runs/<job_id>', methods=['GET'])
+@admin_required
+def get_recipe_run(job_id):
+ job = DeploymentJob.query.get(job_id)
+ if not job or job.kind != RECIPE_JOB_KIND:
+ return jsonify({'error': 'Recipe run not found'}), 404
+ return jsonify({'job': job.to_dict(include_plan=True, include_logs=True)}), 200
+
+
+@recipes_bp.route('/runs/<job_id>/handoffs/<step_id>', methods=['POST'])
+@admin_required
+def submit_recipe_handoff(job_id, step_id):
+ job = DeploymentJob.query.get(job_id)
+ if not job or job.kind != RECIPE_JOB_KIND:
+ return jsonify({'error': 'Recipe run not found'}), 404
+ data = request.get_json(silent=True) or {}
+ user = get_current_user()
+ wait = request.args.get('wait', 'false').lower() == 'true'
+ result = RecipeExecutionService.submit_handoff(
+ job, step_id=step_id, value=data.get('value'), user_id=user.id, wait=wait)
+ if not result.get('success'):
+ return jsonify(result), 400
+ _audit('recipe.handoff.submit', user.id, job.id, {'step_id': step_id})
+ return jsonify(result), 200 if wait else 202
+
+
+def _audit(action, user_id, job_id, details):
+ try:
+ from app.services.audit_service import AuditService
+ AuditService.log(
+ action, user_id=user_id, target_type='deployment_job',
+ target_id=job_id, details=details)
+ except Exception:
+ pass
diff --git a/backend/app/core_blueprints.py b/backend/app/core_blueprints.py
index 31d2e603..1b0503c1 100644
--- a/backend/app/core_blueprints.py
+++ b/backend/app/core_blueprints.py
@@ -87,6 +87,7 @@ CORE_BLUEPRINTS: tuple[BlueprintSpec, ...] = (
BlueprintSpec('app.api.buildpacks', 'buildpacks_bp', '/api/v1/buildpacks'),
BlueprintSpec('app.api.snapshots', 'snapshots_bp', '/api/v1/apps'),
BlueprintSpec('app.api.manifests', 'manifests_bp', '/api/v1/manifests'),
+ BlueprintSpec('app.api.recipes', 'recipes_bp', '/api/v1/recipes'),
BlueprintSpec('app.api.projects', 'projects_bp', '/api/v1/projects'),
BlueprintSpec('app.api.environments', 'environments_bp', '/api/v1/environments'),
BlueprintSpec(
diff --git a/backend/app/models/deployment_job.py b/backend/app/models/deployment_job.py
index 2aab5b6d..73783b85 100644
--- a/backend/app/models/deployment_job.py
+++ b/backend/app/models/deployment_job.py
@@ -105,6 +105,10 @@ class DeploymentJob(RunLifecycleMixin, JsonColumnMixin, db.Model):
return self.target_server.name if self.target_server else 'Local server'
def to_dict(self, include_plan=False, include_logs=False):
+ result = self.get_result()
+ plan = self.get_plan()
+ recipe = plan.get('recipe') if self.kind == 'recipe.run' else None
+ handoff = result.get('handoff') if isinstance(result, dict) else None
data = {
'id': self.id,
'kind': self.kind,
@@ -125,7 +129,7 @@ class DeploymentJob(RunLifecycleMixin, JsonColumnMixin, db.Model):
'current_step': self.current_step,
'current_step_name': self.current_step_name,
'progress_percent': self.progress_percent,
- 'result': self.get_result(),
+ 'result': result,
'error_message': self.error_message,
'correlation_id': self.correlation_id,
'created_at': self.created_at.isoformat() if self.created_at else None,
@@ -133,9 +137,15 @@ class DeploymentJob(RunLifecycleMixin, JsonColumnMixin, db.Model):
'completed_at': self.completed_at.isoformat() if self.completed_at else None,
'updated_at': self.updated_at.isoformat() if self.updated_at else None,
'duration': self.duration,
+ 'requires_action': self.status == 'waiting' and bool(handoff),
+ 'needs_attention': self.status == 'waiting' or self.status == 'failed',
}
+ if recipe:
+ data['title'] = f"Recipe: {recipe.get('title') or recipe.get('slug') or 'Guided outcome'}"
+ data['recipe'] = recipe
+ data['handoff'] = handoff
if include_plan:
- data['plan'] = self.get_plan()
+ data['plan'] = plan
if include_logs:
data['logs'] = [log.to_dict() for log in self.logs.all()]
return data
diff --git a/backend/app/services/deployment_job_service.py b/backend/app/services/deployment_job_service.py
index 413bf048..3585894f 100644
--- a/backend/app/services/deployment_job_service.py
+++ b/backend/app/services/deployment_job_service.py
@@ -247,6 +247,26 @@ class DeploymentJobService:
return {'success': False,
'error': 'Only failed deployments can be retried'}
+ # Recipes are explicitly resumable. A clone would discard the
+ # completed-step ledger and orphan any still-valid encrypted handoff
+ # values under the old run id, turning Retry into "start over". Resume
+ # the same run from its first incomplete step instead.
+ if job.kind == 'recipe.run':
+ job.status = 'pending'
+ job.error_message = None
+ job.completed_at = None
+ job.requested_by = user_id or job.requested_by
+ db.session.commit()
+ try:
+ cls._enqueue_registered(job)
+ except Exception as exc:
+ db.session.rollback()
+ job.mark_failed(f'Failed to queue Recipe resume: {exc}')
+ db.session.commit()
+ return {'success': False, 'error': job.error_message, 'job_id': job.id}
+ return {'success': True, 'job_id': job.id,
+ 'job': job.to_dict(include_logs=True), 'resumed': True}
+
clone = DeploymentJob(
id=str(uuid.uuid4()),
kind=job.kind,
@@ -545,7 +565,11 @@ class DeploymentJobService:
trigger=trigger,
correlation_id=generate_correlation_id(),
)
- job.set_plan({**(plan or {}), 'steps': [{'name': n} for n in (steps or [])]})
+ normalized_steps = [
+ dict(step) if isinstance(step, dict) else {'name': step}
+ for step in (steps or [])
+ ]
+ job.set_plan({**(plan or {}), 'steps': normalized_steps})
job.total_steps = len(steps or [])
db.session.add(job)
db.session.commit()
@@ -622,8 +646,10 @@ class DeploymentJobService:
return {'success': False, 'error': str(exc), 'job_id': job.id}
stream.flush()
- # A handler may finalise the job itself; only fill in what it left.
- if job.status not in ('succeeded', 'failed'):
+ # A handler may finalise or pause the job itself; only fill in what it
+ # left. ``waiting`` is the Recipe handoff state: nonterminal, visible in
+ # Operations, and resumed by enqueueing this SAME deployment job.
+ if job.status not in ('succeeded', 'failed', 'waiting'):
if result.get('success', True):
job.mark_succeeded()
else:
@@ -633,6 +659,11 @@ class DeploymentJobService:
# A handler that reported failure by return value logged nothing;
# without this the console shows a failed run with no reason in it.
stream.log('error', job.error_message)
+ if job.status == 'waiting':
+ stream.flush()
+ stream.emit_status()
+ return {**result, 'success': True, 'paused': True, 'job_id': job.id}
+
# close() persists step timings (and, on failure, the tail + hint) into
# the job's result and emits the terminal status the console listens for.
stream.close(job.status, error_message=job.error_message)
diff --git a/backend/app/services/manifest_spec_service.py b/backend/app/services/manifest_spec_service.py
index 31f8f6cf..a41976d7 100644
--- a/backend/app/services/manifest_spec_service.py
+++ b/backend/app/services/manifest_spec_service.py
@@ -66,6 +66,12 @@ BACKUP_SCHEDULES = ('hourly', 'daily', 'weekly', 'monthly')
PORT_PROTOCOLS = ('tcp', 'udp')
PORT_EXPOSURES = ('public', 'local')
+# Recipes (plan 68): the execution type is deliberately small and closed. The
+# ``kind`` within each type is capability-gated by the runtime registry, so a
+# catalog entry can never smuggle an arbitrary command into an older panel.
+RECIPE_STEP_TYPES = ('probe', 'derive', 'apply', 'handoff', 'verify')
+RECIPE_HARDWARE_MODES = ('required', 'preferred', 'none')
+
_KEY_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
_NAME_RE = re.compile(r'^[a-z0-9]([a-z0-9-]*[a-z0-9])?$')
@@ -91,6 +97,20 @@ MANIFEST_SCHEMA: Dict[str, Any] = {
"items": {"$ref": "#/definitions/service"},
},
"domains": {"type": "array", "items": {"$ref": "#/definitions/domain"}},
+ "capabilities": {
+ "type": "array",
+ "uniqueItems": True,
+ "items": {"type": "string", "pattern": "^[a-z]+:[a-z0-9._-]+$"},
+ },
+ "requires": {"$ref": "#/definitions/recipeRequirements"},
+ "configure": {
+ "type": "array",
+ "items": {"$ref": "#/definitions/recipeStep"},
+ },
+ "verify": {
+ "type": "array",
+ "items": {"$ref": "#/definitions/recipeVerifyStep"},
+ },
},
"definitions": {
"service": {
@@ -274,6 +294,67 @@ MANIFEST_SCHEMA: Dict[str, Any] = {
},
},
},
+ "recipeRequirements": {
+ "type": "object",
+ "additionalProperties": True,
+ "properties": {
+ "cpuCores": {"type": "integer", "minimum": 1},
+ "memoryMB": {"type": "integer", "minimum": 1},
+ "diskGB": {"type": "integer", "minimum": 1},
+ "igpu": {"enum": list(RECIPE_HARDWARE_MODES)},
+ "gpu": {"enum": list(RECIPE_HARDWARE_MODES)},
+ },
+ },
+ "recipeStep": {
+ "type": "object",
+ "required": ["id", "type", "kind"],
+ "additionalProperties": True,
+ "properties": {
+ "id": {"type": "string", "pattern": "^[a-z0-9][a-z0-9._-]*$"},
+ "type": {"enum": list(RECIPE_STEP_TYPES)},
+ "kind": {"type": "string", "pattern": "^[a-z0-9][a-z0-9._-]*$"},
+ "title": {"type": "string", "minLength": 1},
+ "description": {"type": "string"},
+ "dependsOn": {
+ "type": "array",
+ "uniqueItems": True,
+ "items": {"type": "string"},
+ },
+ "params": {"type": "object"},
+ "ttlSeconds": {"type": "integer", "minimum": 1},
+ "input": {"$ref": "#/definitions/recipeInput"},
+ },
+ },
+ "recipeVerifyStep": {
+ "type": "object",
+ "required": ["id", "kind"],
+ "additionalProperties": True,
+ "properties": {
+ "id": {"type": "string", "pattern": "^[a-z0-9][a-z0-9._-]*$"},
+ "type": {"const": "verify"},
+ "kind": {"type": "string", "pattern": "^[a-z0-9][a-z0-9._-]*$"},
+ "title": {"type": "string", "minLength": 1},
+ "description": {"type": "string"},
+ "dependsOn": {
+ "type": "array",
+ "uniqueItems": True,
+ "items": {"type": "string"},
+ },
+ "params": {"type": "object"},
+ },
+ },
+ "recipeInput": {
+ "type": "object",
+ "required": ["key", "label"],
+ "additionalProperties": True,
+ "properties": {
+ "key": {"type": "string", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$"},
+ "label": {"type": "string", "minLength": 1},
+ "help": {"type": "string"},
+ "url": {"type": "string"},
+ "secret": {"type": "boolean"},
+ },
+ },
},
}
@@ -354,8 +435,8 @@ class ManifestSpecService:
def _manual_schema_errors(data: Dict[str, Any]) -> List[str]: # pragma: no cover
errors = []
services = data.get('services')
- if not isinstance(services, list) or not services:
- errors.append('services: at least one service is required')
+ if services is not None and not isinstance(services, list):
+ errors.append('services: must be an array')
return errors
# -- normalization + semantic checks -----------------------------------
@@ -411,6 +492,23 @@ class ManifestSpecService:
)
domains.append(normalized_dom)
+ declared_capabilities = list(data.get('capabilities') or [])
+ configure = []
+ verify = []
+ seen_step_ids = set()
+ for idx, raw in enumerate(data.get('configure') or []):
+ step = cls._normalize_recipe_step(raw, raw.get('type'), f'configure[{idx}]')
+ cls._check_recipe_step(
+ step, declared_capabilities, seen_step_ids, f'configure[{idx}]', errors)
+ configure.append(step)
+ seen_step_ids.add(step['id'])
+ for idx, raw in enumerate(data.get('verify') or []):
+ step = cls._normalize_recipe_step(raw, 'verify', f'verify[{idx}]')
+ cls._check_recipe_step(
+ step, declared_capabilities, seen_step_ids, f'verify[{idx}]', errors)
+ verify.append(step)
+ seen_step_ids.add(step['id'])
+
normalized = {
'version': 1,
'server': data.get('server') or None,
@@ -418,9 +516,74 @@ class ManifestSpecService:
'env_vars': manifest_env,
'services': services,
'domains': domains,
+ 'capabilities': declared_capabilities,
+ 'requires': cls._normalize_recipe_requirements(data.get('requires')),
+ 'configure': configure,
+ 'verify': verify,
}
return normalized, errors
+ @classmethod
+ def _normalize_recipe_step(cls, raw: Dict[str, Any], step_type: str,
+ prefix: str) -> Dict[str, Any]:
+ """Normalize one closed-vocabulary Recipe step.
+
+ ``params`` remains data, never executable code. The runtime resolves
+ ``type:kind`` through RecipeStepRegistry and refuses unknown entries.
+ """
+ depends = cls._alias(raw, 'dependsOn', 'depends_on', default=[]) or []
+ ttl = cls._alias(raw, 'ttlSeconds', 'ttl_seconds')
+ input_spec = raw.get('input') if isinstance(raw.get('input'), dict) else None
+ return {
+ 'id': raw.get('id'),
+ 'type': step_type,
+ 'kind': raw.get('kind'),
+ 'capability': f'{step_type}:{raw.get("kind")}',
+ 'title': raw.get('title') or raw.get('id'),
+ 'description': raw.get('description') or '',
+ 'depends_on': list(depends),
+ 'params': dict(raw.get('params') or {}),
+ 'ttl_seconds': int(ttl) if ttl else None,
+ 'input': ({
+ 'key': input_spec.get('key'),
+ 'label': input_spec.get('label'),
+ 'help': input_spec.get('help') or '',
+ 'url': input_spec.get('url'),
+ 'secret': input_spec.get('secret', True),
+ } if input_spec else None),
+ }
+
+ @staticmethod
+ def _check_recipe_step(step: Dict[str, Any], declared_capabilities: List[str],
+ seen_step_ids: set, prefix: str, errors: List[str]) -> None:
+ step_id = step.get('id')
+ if step_id in seen_step_ids:
+ errors.append(f'{prefix}: duplicate recipe step id `{step_id}`')
+ for dependency in step.get('depends_on') or []:
+ if dependency not in seen_step_ids:
+ errors.append(
+ f'{prefix}: dependency `{dependency}` must name an earlier recipe step')
+ capability = step.get('capability')
+ if capability not in declared_capabilities:
+ errors.append(
+ f'{prefix}: capability `{capability}` is used but not declared')
+ if step.get('type') == 'handoff' and not step.get('input'):
+ errors.append(f'{prefix}: handoff steps require an `input` declaration')
+ if step.get('type') != 'handoff' and step.get('ttl_seconds') is not None:
+ errors.append(f'{prefix}: `ttlSeconds` only applies to handoff steps')
+
+ @classmethod
+ def _normalize_recipe_requirements(cls, raw: Any) -> Dict[str, Any]:
+ if not isinstance(raw, dict):
+ return {}
+ return {
+ 'cpu_cores': cls._alias(raw, 'cpuCores', 'cpu_cores'),
+ 'memory_mb': cls._alias(raw, 'memoryMB', 'memory_mb'),
+ 'disk_gb': cls._alias(raw, 'diskGB', 'disk_gb'),
+ 'igpu': raw.get('igpu') or 'none',
+ 'gpu': raw.get('gpu') or 'none',
+ }
+
@classmethod
def _normalize_service(cls, svc: Dict[str, Any], idx: int, errors: List[str]) -> Dict[str, Any]:
name = svc.get('name')
@@ -782,7 +945,7 @@ class ManifestSpecService:
@classmethod
def summarize(cls, normalized: Dict[str, Any]) -> Dict[str, Any]:
"""A compact, UI-friendly summary of a normalized manifest."""
- services = normalized['services']
+ services = normalized.get('services', [])
env_required = []
for svc in services:
for var in svc['env_vars']:
@@ -810,6 +973,18 @@ class ManifestSpecService:
'domains': [{'host': d['host'], 'service': d['service'], 'ssl': d['ssl']}
for d in normalized['domains']],
'env_required': env_required,
+ 'recipe': {
+ 'capabilities': list(normalized.get('capabilities') or []),
+ 'requirements': dict(normalized.get('requires') or {}),
+ 'configure_steps': len(normalized.get('configure') or []),
+ 'verify_steps': len(normalized.get('verify') or []),
+ 'handoffs': [
+ {'id': step['id'], 'title': step['title'],
+ 'ttl_seconds': step.get('ttl_seconds')}
+ for step in normalized.get('configure') or []
+ if step.get('type') == 'handoff'
+ ],
+ },
}
# -- helpers ------------------------------------------------------------
diff --git a/backend/app/services/recipe_execution_service.py b/backend/app/services/recipe_execution_service.py
new file mode 100644
index 00000000..ae584c43
--- /dev/null
+++ b/backend/app/services/recipe_execution_service.py
@@ -0,0 +1,387 @@
+"""Resumable Recipe execution on the existing deployment run envelope.
+
+A Recipe is a normalized ``serverkit.yaml`` manifest with ``requires``,
+``configure`` and ``verify`` blocks. The manifest plan and Recipe steps share
+one DeploymentJob, one log stream, and one persisted progress record. Unknown
+``type:kind`` capabilities are refused before any mutation.
+
+Human handoffs pause the run in ``waiting``. Submitted values are stored in the
+existing encrypted Secret Vault, never in the job plan/result/logs, and are
+deleted when the run completes.
+"""
+
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from typing import Any, Callable, Dict, Optional
+
+from app import db
+from app.models.application_manifest import STATUS_APPLIED, STATUS_ERROR
+from app.models.deployment_job import DeploymentJob
+from app.models.environment import Environment
+from app.models.project import Project
+from app.models.secret_vault import Secret, SecretVault
+from app.services.manifest_apply_service import ManifestApplyService
+from app.services.run_log_service import stream_for
+from app.utils.crypto import encrypt_secret
+from app.utils.sensitive_data_filter import mask_payload
+
+
+RECIPE_JOB_KIND = 'recipe.run'
+RECIPE_WAITING = 'waiting'
+HANDOFF_VAULT_SLUG = 'recipe-runs'
+
+
+@dataclass
+class RecipeStepContext:
+ job: DeploymentJob
+ project: Project
+ environment: Optional[Environment]
+ step: Dict[str, Any]
+ completed: Dict[str, Any]
+
+ def input(self, key: str) -> Optional[str]:
+ """Return one encrypted-at-rest handoff value by declared input key."""
+ for plan_step in (self.job.get_plan() or {}).get('steps', []):
+ recipe_step = plan_step.get('recipe_step') or {}
+ input_spec = recipe_step.get('input') or {}
+ if input_spec.get('key') == key:
+ secret = RecipeExecutionService._handoff_secret(
+ self.job.id, recipe_step.get('id'))
+ if secret and not secret.is_expired:
+ return secret.value
+ return None
+
+
+class RecipeStepRegistry:
+ """Closed runtime vocabulary for data-only Recipe steps."""
+
+ _handlers: Dict[str, Dict[str, Optional[Callable]]] = {}
+
+ @classmethod
+ def register(cls, step_type: str, kind: str, handler: Callable,
+ check: Optional[Callable] = None, replace: bool = False) -> None:
+ capability = f'{step_type}:{kind}'
+ if not callable(handler):
+ raise ValueError('Recipe step handler must be callable')
+ if capability in cls._handlers and not replace:
+ raise ValueError(f'Recipe capability already registered: {capability}')
+ cls._handlers[capability] = {'handler': handler, 'check': check}
+
+ @classmethod
+ def supports(cls, capability: str) -> bool:
+ # Handoffs are an engine primitive; their ``kind`` only describes the
+ # input presentation (token, acknowledgement, credential, ...).
+ return capability.startswith('handoff:') or capability in cls._handlers
+
+ @classmethod
+ def execute(cls, context: RecipeStepContext) -> Dict[str, Any]:
+ capability = context.step['capability']
+ entry = cls._handlers.get(capability)
+ if not entry:
+ raise RuntimeError(f'Unsupported Recipe capability: {capability}')
+ check = entry.get('check')
+ if callable(check) and check(context):
+ return {'already_complete': True}
+ outcome = entry['handler'](context)
+ return outcome if isinstance(outcome, dict) else {'result': outcome}
+
+ @classmethod
+ def clear(cls) -> None:
+ """Test helper; production registrations are restored at app startup."""
+ cls._handlers.clear()
+
+
+class RecipeExecutionService:
+
+ @classmethod
+ def register_jobs(cls) -> None:
+ from app.services import deploy_kind_registry
+ deploy_kind_registry.register(RECIPE_JOB_KIND, cls.run, replace=True)
+
+ @staticmethod
+ def unsupported_capabilities(normalized: Dict[str, Any]) -> list[str]:
+ """Return unknown capabilities without creating or changing any rows."""
+ recipe_steps = list(normalized.get('configure') or []) + list(
+ normalized.get('verify') or [])
+ return sorted({
+ step['capability'] for step in recipe_steps
+ if not RecipeStepRegistry.supports(step['capability'])
+ })
+
+ @classmethod
+ def start(cls, project: Project, normalized: Dict[str, Any], *,
+ user_id: Optional[int], slug: Optional[str] = None,
+ title: Optional[str] = None, manifest_row=None,
+ wait: bool = False) -> Dict[str, Any]:
+ """Create one Recipe run after capability and manifest preflight."""
+ recipe_steps = list(normalized.get('configure') or []) + list(
+ normalized.get('verify') or [])
+ if not recipe_steps:
+ return {'success': False, 'error': 'Manifest does not contain Recipe steps'}
+
+ unsupported = cls.unsupported_capabilities(normalized)
+ if unsupported:
+ return {
+ 'success': False,
+ 'error': 'This panel does not support every Recipe capability',
+ 'unsupported_capabilities': unsupported,
+ }
+
+ environment = ManifestApplyService._default_environment(project)
+ manifest_plan = ManifestApplyService.plan(project, normalized, environment)
+ if manifest_plan.get('blockers'):
+ return {
+ 'success': False,
+ 'refused': True,
+ 'error': manifest_plan['blockers'][0]['message'],
+ 'blockers': manifest_plan['blockers'],
+ 'issues': manifest_plan.get('issues', []),
+ }
+
+ steps = []
+ for idx, step in enumerate(manifest_plan.get('steps') or []):
+ steps.append({
+ 'name': step['description'],
+ 'phase': 'manifest',
+ 'step_id': f'manifest-{idx + 1}-{step["type"]}',
+ 'manifest_step': step,
+ })
+ for step in normalized.get('configure') or []:
+ steps.append({
+ 'name': step['title'], 'phase': 'configure',
+ 'step_id': step['id'], 'recipe_step': step,
+ })
+ for step in normalized.get('verify') or []:
+ steps.append({
+ 'name': step['title'], 'phase': 'verify',
+ 'step_id': step['id'], 'recipe_step': step,
+ })
+
+ cls.register_jobs()
+ from app.services.deployment_job_service import DeploymentJobService
+ return DeploymentJobService.start_registered(
+ RECIPE_JOB_KIND,
+ steps=steps,
+ user_id=user_id,
+ trigger='recipe',
+ wait=wait,
+ plan={
+ 'recipe': {
+ 'slug': slug or normalized.get('project') or 'inline',
+ 'title': title or normalized.get('project') or 'Guided outcome',
+ 'requirements': normalized.get('requires') or {},
+ 'capabilities': normalized.get('capabilities') or [],
+ },
+ 'project_id': project.id,
+ 'environment_id': environment.id if environment else None,
+ 'manifest_row_id': getattr(manifest_row, 'id', None),
+ 'issues': manifest_plan.get('issues', []),
+ },
+ )
+
+ @classmethod
+ def run(cls, job: DeploymentJob) -> Dict[str, Any]:
+ """Run from the first incomplete step, pausing only at a handoff."""
+ plan = job.get_plan() or {}
+ try:
+ return cls._run_steps(job, plan)
+ except Exception:
+ cls._mark_manifest(plan.get('manifest_row_id'), success=False)
+ db.session.commit()
+ raise
+
+ @classmethod
+ def _run_steps(cls, job: DeploymentJob, plan: Dict[str, Any]) -> Dict[str, Any]:
+ project = Project.query.get(plan.get('project_id'))
+ if not project:
+ raise RuntimeError('Recipe project no longer exists')
+ environment = (Environment.query.get(plan.get('environment_id'))
+ if plan.get('environment_id') else None)
+ state = job.get_result() or {}
+ completed = dict(state.get('completed_steps') or {})
+ stream = stream_for(job)
+
+ for index, plan_step in enumerate(plan.get('steps') or []):
+ step_id = plan_step.get('step_id') or f'step-{index + 1}'
+ if step_id in completed:
+ continue
+
+ name = plan_step.get('name') or step_id
+ stream.set_step(index + 1, name)
+ if plan_step.get('phase') == 'manifest':
+ outcome = ManifestApplyService._execute_step(
+ project, environment, plan_step['manifest_step'], job.requested_by)
+ else:
+ step = plan_step.get('recipe_step') or {}
+ dependencies = step.get('depends_on') or []
+ missing = [dep for dep in dependencies if dep not in completed]
+ if missing:
+ raise RuntimeError(
+ f'Recipe step {step_id} is missing dependencies: {", ".join(missing)}')
+ if step.get('type') == 'handoff':
+ secret = cls._handoff_secret(job.id, step_id)
+ if secret and secret.is_expired:
+ db.session.delete(secret)
+ db.session.commit()
+ secret = None
+ if not secret:
+ return cls._pause_for_handoff(job, state, completed, step, stream)
+ outcome = {'accepted': True, 'input_key': step['input']['key']}
+ else:
+ context = RecipeStepContext(
+ job=job, project=project, environment=environment,
+ step=step, completed=completed)
+ outcome = RecipeStepRegistry.execute(context)
+
+ completed[step_id] = {
+ 'status': 'ok',
+ 'completed_at': datetime.utcnow().isoformat(),
+ 'result': mask_payload(outcome or {}),
+ }
+ state['completed_steps'] = completed
+ state['handoff'] = None
+ job.set_result(state)
+ job.current_step = index + 1
+ db.session.commit()
+ stream.log('info', f'Completed: {name}', step_index=index + 1)
+
+ cls._delete_handoff_secrets(job.id)
+ state['completed_steps'] = completed
+ state['handoff'] = None
+ state['verified'] = bool(normalized_verify_count(plan))
+ job.set_result(state)
+ cls._mark_manifest(plan.get('manifest_row_id'), success=True)
+ db.session.commit()
+ return {
+ 'success': True,
+ 'completed': len(completed),
+ 'verified': state['verified'],
+ }
+
+ @classmethod
+ def submit_handoff(cls, job: DeploymentJob, *, step_id: str, value: str,
+ user_id: Optional[int], wait: bool = False) -> Dict[str, Any]:
+ """Encrypt a waiting handoff value and resume the same run."""
+ state = job.get_result() or {}
+ handoff = state.get('handoff') or {}
+ if job.kind != RECIPE_JOB_KIND or job.status != RECIPE_WAITING:
+ return {'success': False, 'error': 'Recipe run is not waiting for input'}
+ if handoff.get('step_id') != step_id:
+ return {'success': False, 'error': 'Recipe run is waiting on a different step'}
+ if not isinstance(value, str) or not value.strip():
+ return {'success': False, 'error': 'A handoff value is required'}
+ if len(value) > 8192:
+ return {'success': False, 'error': 'Handoff value is too large'}
+
+ plan_step = next((entry for entry in (job.get_plan() or {}).get('steps', [])
+ if entry.get('step_id') == step_id), None)
+ step = (plan_step or {}).get('recipe_step') or {}
+ ttl = step.get('ttl_seconds')
+ cls._store_handoff_secret(
+ job, step_id, value.strip(), user_id=user_id,
+ expires_at=(datetime.utcnow() + timedelta(seconds=ttl)) if ttl else None)
+
+ state['handoff'] = {**handoff, 'received': True}
+ job.set_result(state)
+ job.status = 'pending'
+ job.completed_at = None
+ db.session.commit()
+
+ from app.services.deployment_job_service import DeploymentJobService
+ if wait:
+ result = DeploymentJobService.run_job(job.id)
+ else:
+ try:
+ DeploymentJobService._enqueue_registered(job)
+ result = {'success': True, 'queued': True}
+ except Exception as exc:
+ db.session.rollback()
+ job.status = RECIPE_WAITING
+ db.session.commit()
+ return {'success': False, 'error': f'Failed to resume Recipe: {exc}'}
+ return {**result, 'job_id': job.id, 'job': job.to_dict()}
+
+ @classmethod
+ def _pause_for_handoff(cls, job, state, completed, step, stream):
+ input_spec = step.get('input') or {}
+ state['completed_steps'] = completed
+ state['handoff'] = {
+ 'step_id': step['id'],
+ 'title': step['title'],
+ 'description': step.get('description') or '',
+ 'input': input_spec,
+ 'ttl_seconds': step.get('ttl_seconds'),
+ 'received': False,
+ }
+ job.set_result(state)
+ job.status = RECIPE_WAITING
+ job.completed_at = None
+ db.session.commit()
+ stream.log('warn', f'Waiting for operator input: {step["title"]}')
+ stream.flush()
+ stream.emit_status()
+ return {'success': True, 'paused': True, 'handoff': state['handoff']}
+
+ @staticmethod
+ def _handoff_secret_name(job_id: str, step_id: str) -> str:
+ return f'{job_id}:{step_id}'[:200]
+
+ @classmethod
+ def _handoff_secret(cls, job_id: str, step_id: str) -> Optional[Secret]:
+ vault = SecretVault.query.filter_by(slug=HANDOFF_VAULT_SLUG).first()
+ if not vault:
+ return None
+ return Secret.query.filter_by(
+ vault_id=vault.id, name=cls._handoff_secret_name(job_id, step_id)).first()
+
+ @classmethod
+ def _store_handoff_secret(cls, job, step_id, value, *, user_id, expires_at):
+ plan = job.get_plan() or {}
+ project = Project.query.get(plan.get('project_id'))
+ vault = SecretVault.query.filter_by(slug=HANDOFF_VAULT_SLUG).first()
+ if not vault:
+ vault = SecretVault(
+ name='Recipe run inputs', slug=HANDOFF_VAULT_SLUG,
+ description='Short-lived encrypted values supplied to Recipe handoffs',
+ created_by=user_id,
+ workspace_id=getattr(project, 'workspace_id', None),
+ )
+ db.session.add(vault)
+ db.session.flush()
+ name = cls._handoff_secret_name(job.id, step_id)
+ secret = Secret.query.filter_by(vault_id=vault.id, name=name).first()
+ if not secret:
+ secret = Secret(vault_id=vault.id, name=name)
+ db.session.add(secret)
+ secret.encrypted_value = encrypt_secret(value)
+ secret.expires_at = expires_at
+ secret.description = 'Encrypted Recipe handoff input; deleted after run completion'
+ db.session.commit()
+ return secret
+
+ @classmethod
+ def _delete_handoff_secrets(cls, job_id: str) -> None:
+ vault = SecretVault.query.filter_by(slug=HANDOFF_VAULT_SLUG).first()
+ if not vault:
+ return
+ prefix = f'{job_id}:%'
+ Secret.query.filter(Secret.vault_id == vault.id, Secret.name.like(prefix)).delete(
+ synchronize_session=False)
+ db.session.commit()
+
+ @staticmethod
+ def _mark_manifest(row_id, *, success: bool) -> None:
+ if not row_id:
+ return
+ from app.models.application_manifest import ApplicationManifest
+ row = ApplicationManifest.query.get(row_id)
+ if not row:
+ return
+ row.status = STATUS_APPLIED if success else STATUS_ERROR
+ if success:
+ row.applied_at = datetime.utcnow()
+ row.last_error = None
+
+
+def normalized_verify_count(plan: Dict[str, Any]) -> int:
+ return sum(1 for step in plan.get('steps') or [] if step.get('phase') == 'verify')
diff --git a/backend/tests/test_core_blueprint_registry.py b/backend/tests/test_core_blueprint_registry.py
index c90d97c1..fdfc7c97 100644
--- a/backend/tests/test_core_blueprint_registry.py
+++ b/backend/tests/test_core_blueprint_registry.py
@@ -7,9 +7,9 @@ from pathlib import Path
from app.core_blueprints import CORE_BLUEPRINTS
-EXPECTED_CORE_BLUEPRINT_COUNT = 109
+EXPECTED_CORE_BLUEPRINT_COUNT = 110
EXPECTED_MANIFEST_SHA256 = (
- '21e01071b82c9594f233bda5682bf044560ede6df3789ab95752f5adcf31d6d1'
+ '8d70318fa935817c1b92b03f186c75c8c9cd6eb7aa3483e0bc44b735fd5c5722'
)
diff --git a/backend/tests/test_manifest_spec.py b/backend/tests/test_manifest_spec.py
index 3d67f974..d7c8b8a4 100644
--- a/backend/tests/test_manifest_spec.py
+++ b/backend/tests/test_manifest_spec.py
@@ -168,6 +168,59 @@ def test_embedded_schema_matches_docs_copy():
set(MANIFEST_SCHEMA['definitions']['service']['properties']['type']['enum'])
+def test_recipe_blocks_normalize_and_summarize():
+ manifest = {
+ 'version': 1,
+ 'project': 'Media server',
+ 'capabilities': [
+ 'probe:render-group', 'handoff:token', 'apply:configure-media',
+ 'verify:hardware-transcode',
+ ],
+ 'requires': {
+ 'cpuCores': 4, 'memoryMB': 4096, 'diskGB': 100,
+ 'igpu': 'preferred',
+ },
+ 'configure': [
+ {'id': 'render', 'type': 'probe', 'kind': 'render-group'},
+ {
+ 'id': 'claim', 'type': 'handoff', 'kind': 'token',
+ 'dependsOn': ['render'], 'ttlSeconds': 240,
+ 'input': {'key': 'PLEX_CLAIM', 'label': 'Plex claim token',
+ 'url': 'https://plex.tv/claim'},
+ },
+ {'id': 'configure', 'type': 'apply', 'kind': 'configure-media',
+ 'dependsOn': ['claim']},
+ ],
+ 'verify': [
+ {'id': 'transcode', 'kind': 'hardware-transcode',
+ 'dependsOn': ['configure']},
+ ],
+ }
+ normalized = ManifestSpecService.normalize(manifest)
+ assert normalized['requires']['igpu'] == 'preferred'
+ assert normalized['configure'][1]['ttl_seconds'] == 240
+ assert normalized['verify'][0]['type'] == 'verify'
+ assert normalized['verify'][0]['capability'] == 'verify:hardware-transcode'
+ summary = ManifestSpecService.summarize(normalized)['recipe']
+ assert summary['configure_steps'] == 3
+ assert summary['verify_steps'] == 1
+ assert summary['handoffs'][0]['ttl_seconds'] == 240
+
+
+def test_recipe_requires_declared_capabilities_and_ordered_dependencies():
+ with pytest.raises(ManifestError) as exc:
+ ManifestSpecService.normalize({
+ 'version': 1,
+ 'capabilities': [],
+ 'configure': [
+ {'id': 'later', 'type': 'apply', 'kind': 'demo',
+ 'dependsOn': ['missing']},
+ ],
+ })
+ assert any('not declared' in error for error in exc.value.errors)
+ assert any('earlier recipe step' in error for error in exc.value.errors)
+
+
# -- RepositoryManifestService integration ---------------------------------
def test_repo_service_detects_v1(tmp_path):
diff --git a/backend/tests/test_recipes.py b/backend/tests/test_recipes.py
new file mode 100644
index 00000000..8c5cbb85
--- /dev/null
+++ b/backend/tests/test_recipes.py
@@ -0,0 +1,206 @@
+"""Plan 68 Phase 0 — Recipe capability, resume, handoff and API contracts."""
+
+import json
+
+from datetime import datetime, timedelta
+
+import pytest
+
+from app import db
+from app.models.deployment_job import DeploymentJob
+from app.models.application_manifest import ApplicationManifest
+from app.models.secret_vault import Secret, SecretVault
+from app.services.manifest_spec_service import ManifestSpecService
+from app.services.recipe_execution_service import (
+ HANDOFF_VAULT_SLUG,
+ RECIPE_WAITING,
+ RecipeExecutionService,
+ RecipeStepRegistry,
+)
+
+
+def project(app):
+ from app.models import Environment, Project
+ from app.services.workspace_service import WorkspaceService
+
+ workspace = WorkspaceService.ensure_default_workspace()
+ row = Project(workspace_id=workspace.id, name='Recipe test', slug='recipe-test')
+ db.session.add(row)
+ db.session.commit()
+ environment = Environment(
+ project_id=row.id, name='Production', slug='production', is_default=True)
+ db.session.add(environment)
+ db.session.commit()
+ return row
+
+
+def owner(app):
+ from app.models import User
+ row = User(
+ username='recipe-owner', email='[email protected]',
+ role=User.ROLE_ADMIN, is_active=True)
+ row.set_password('testpass')
+ db.session.add(row)
+ db.session.commit()
+ return row
+
+
[email protected](autouse=True)
+def _recipe_registry():
+ RecipeStepRegistry.clear()
+ yield
+ RecipeStepRegistry.clear()
+
+
+def _manifest():
+ return {
+ 'version': 1,
+ 'project': 'Media server',
+ 'capabilities': [
+ 'apply:test-before', 'handoff:token', 'apply:test-after',
+ 'verify:test-outcome',
+ ],
+ 'configure': [
+ {'id': 'before', 'type': 'apply', 'kind': 'test-before'},
+ {
+ 'id': 'claim', 'type': 'handoff', 'kind': 'token',
+ 'dependsOn': ['before'], 'ttlSeconds': 240,
+ 'input': {'key': 'CLAIM_TOKEN', 'label': 'Claim token', 'secret': True},
+ },
+ {'id': 'after', 'type': 'apply', 'kind': 'test-after',
+ 'dependsOn': ['claim']},
+ ],
+ 'verify': [
+ {'id': 'proof', 'kind': 'test-outcome', 'dependsOn': ['after']},
+ ],
+ }
+
+
+def test_recipe_refuses_unsupported_capability_before_creating_job(project, owner):
+ normalized = ManifestSpecService.normalize({
+ 'version': 1,
+ 'capabilities': ['apply:not-installed'],
+ 'configure': [{'id': 'nope', 'type': 'apply', 'kind': 'not-installed'}],
+ })
+ before = DeploymentJob.query.count()
+ result = RecipeExecutionService.start(
+ project, normalized, user_id=owner.id, wait=True)
+ assert result['success'] is False
+ assert result['unsupported_capabilities'] == ['apply:not-installed']
+ assert DeploymentJob.query.count() == before
+
+
+def test_recipe_api_refuses_unsupported_capability_before_persisting(
+ client, auth_headers, project):
+ before = ApplicationManifest.query.count()
+ response = client.post('/api/v1/recipes/runs', headers=auth_headers, json={
+ 'project_id': project.id,
+ 'manifest': {
+ 'version': 1,
+ 'capabilities': ['apply:not-installed'],
+ 'configure': [
+ {'id': 'nope', 'type': 'apply', 'kind': 'not-installed'},
+ ],
+ },
+ })
+ assert response.status_code == 400
+ assert response.get_json()['unsupported_capabilities'] == ['apply:not-installed']
+ assert ApplicationManifest.query.count() == before
+
+
+def test_recipe_pauses_resumes_and_does_not_repeat_completed_steps(project, owner):
+ calls = []
+
+ def before(context):
+ calls.append('before')
+ return {'prepared': True}
+
+ def after(context):
+ calls.append(('after', context.input('CLAIM_TOKEN')))
+ return {'configured': True, 'token': 'must-be-redacted'}
+
+ def verify(context):
+ calls.append('verify')
+ return {'verified': True}
+
+ RecipeStepRegistry.register('apply', 'test-before', before)
+ RecipeStepRegistry.register('apply', 'test-after', after)
+ RecipeStepRegistry.register('verify', 'test-outcome', verify)
+ normalized = ManifestSpecService.normalize(_manifest())
+
+ started = RecipeExecutionService.start(
+ project, normalized, user_id=owner.id,
+ slug='media-server', title='Media server', wait=True)
+ assert started['success'] is True
+ assert started['paused'] is True
+ job = DeploymentJob.query.get(started['job_id'])
+ assert job.status == RECIPE_WAITING
+ assert job.to_dict()['requires_action'] is True
+ assert job.get_result()['handoff']['step_id'] == 'claim'
+ assert calls == ['before']
+
+ resumed = RecipeExecutionService.submit_handoff(
+ job, step_id='claim', value='short-lived-token',
+ user_id=owner.id, wait=True)
+ assert resumed['success'] is True
+ job = DeploymentJob.query.get(job.id)
+ assert job.status == 'succeeded'
+ assert calls == ['before', ('after', 'short-lived-token'), 'verify']
+ completed = job.get_result()['completed_steps']
+ assert set(completed) == {'before', 'claim', 'after', 'proof'}
+ assert completed['after']['result']['token'] == '[redacted]'
+ assert job.get_result()['verified'] is True
+ assert 'short-lived-token' not in json.dumps(job.to_dict(include_plan=True))
+
+ vault = SecretVault.query.filter_by(slug=HANDOFF_VAULT_SLUG).first()
+ assert vault is not None
+ assert Secret.query.filter_by(vault_id=vault.id).count() == 0
+
+
+def test_expired_handoff_is_reprompted(project, owner):
+ RecipeStepRegistry.register('apply', 'test-before', lambda context: {'ok': True})
+ RecipeStepRegistry.register('apply', 'test-after', lambda context: {'ok': True})
+ RecipeStepRegistry.register('verify', 'test-outcome', lambda context: {'ok': True})
+ normalized = ManifestSpecService.normalize(_manifest())
+ started = RecipeExecutionService.start(project, normalized, user_id=owner.id, wait=True)
+ job = DeploymentJob.query.get(started['job_id'])
+
+ RecipeExecutionService._store_handoff_secret(
+ job, 'claim', 'expired', user_id=owner.id,
+ expires_at=datetime.utcnow() - timedelta(seconds=1))
+ job.status = 'pending'
+ db.session.commit()
+ rerun = RecipeExecutionService.run(job)
+ assert rerun['paused'] is True
+ assert job.status == RECIPE_WAITING
+ assert RecipeExecutionService._handoff_secret(job.id, 'claim') is None
+
+
+def test_recipe_api_starts_and_resumes_same_run(client, auth_headers, project, owner):
+ RecipeStepRegistry.register('apply', 'test-before', lambda context: {'ok': True})
+ RecipeStepRegistry.register('apply', 'test-after', lambda context: {
+ 'has_input': context.input('CLAIM_TOKEN') == 'api-token'})
+ RecipeStepRegistry.register('verify', 'test-outcome', lambda context: {'ok': True})
+
+ response = client.post(
+ '/api/v1/recipes/runs?wait=true', headers=auth_headers,
+ json={'project_id': project.id, 'slug': 'media-server', 'manifest': _manifest()})
+ assert response.status_code == 200, response.get_json()
+ job_id = response.get_json()['job_id']
+ assert response.get_json()['paused'] is True
+
+ response = client.post(
+ f'/api/v1/recipes/runs/{job_id}/handoffs/claim?wait=true',
+ headers=auth_headers, json={'value': 'api-token'})
+ assert response.status_code == 200, response.get_json()
+ assert response.get_json()['job']['id'] == job_id
+ assert response.get_json()['job']['status'] == 'succeeded'
+
+
+def test_recipe_mutations_require_admin(client, project):
+ response = client.post('/api/v1/recipes/runs', json={
+ 'project_id': project.id, 'manifest': _manifest(),
+ })
+ assert response.status_code in (401, 422)
diff --git a/docs/serverkit-yaml.schema.json b/docs/serverkit-yaml.schema.json
index 3f1f0bdf..64e4a5f9 100644
--- a/docs/serverkit-yaml.schema.json
+++ b/docs/serverkit-yaml.schema.json
@@ -36,6 +36,26 @@
"description": "Public domains routed to services.",
"type": "array",
"items": { "$ref": "#/definitions/domain" }
+ },
+ "capabilities": {
+ "description": "Closed Recipe capability set. Every configure/verify step must declare its type:kind capability here so older panels can refuse unsupported Recipes before doing work.",
+ "type": "array",
+ "uniqueItems": true,
+ "items": { "type": "string", "pattern": "^[a-z]+:[a-z0-9._-]+$" }
+ },
+ "requires": {
+ "description": "Recipe host requirements used by preflight and provider placement.",
+ "$ref": "#/definitions/recipeRequirements"
+ },
+ "configure": {
+ "description": "Ordered, idempotent Recipe steps run after the declared services are applied.",
+ "type": "array",
+ "items": { "$ref": "#/definitions/recipeStep" }
+ },
+ "verify": {
+ "description": "Outcome checks. A successful process is not a successful Recipe until these checks pass.",
+ "type": "array",
+ "items": { "$ref": "#/definitions/recipeVerifyStep" }
}
},
"definitions": {
@@ -364,6 +384,67 @@
]
}
}
+ },
+ "recipeRequirements": {
+ "type": "object",
+ "additionalProperties": true,
+ "properties": {
+ "cpuCores": { "type": "integer", "minimum": 1 },
+ "memoryMB": { "type": "integer", "minimum": 1 },
+ "diskGB": { "type": "integer", "minimum": 1 },
+ "igpu": { "enum": ["required", "preferred", "none"] },
+ "gpu": { "enum": ["required", "preferred", "none"] }
+ }
+ },
+ "recipeStep": {
+ "type": "object",
+ "required": ["id", "type", "kind"],
+ "additionalProperties": true,
+ "properties": {
+ "id": { "type": "string", "pattern": "^[a-z0-9][a-z0-9._-]*$" },
+ "type": { "enum": ["probe", "derive", "apply", "handoff", "verify"] },
+ "kind": { "type": "string", "pattern": "^[a-z0-9][a-z0-9._-]*$" },
+ "title": { "type": "string", "minLength": 1 },
+ "description": { "type": "string" },
+ "dependsOn": {
+ "type": "array",
+ "uniqueItems": true,
+ "items": { "type": "string" }
+ },
+ "params": { "type": "object" },
+ "ttlSeconds": { "type": "integer", "minimum": 1 },
+ "input": { "$ref": "#/definitions/recipeInput" }
+ }
+ },
+ "recipeVerifyStep": {
+ "type": "object",
+ "required": ["id", "kind"],
+ "additionalProperties": true,
+ "properties": {
+ "id": { "type": "string", "pattern": "^[a-z0-9][a-z0-9._-]*$" },
+ "type": { "const": "verify" },
+ "kind": { "type": "string", "pattern": "^[a-z0-9][a-z0-9._-]*$" },
+ "title": { "type": "string", "minLength": 1 },
+ "description": { "type": "string" },
+ "dependsOn": {
+ "type": "array",
+ "uniqueItems": true,
+ "items": { "type": "string" }
+ },
+ "params": { "type": "object" }
+ }
+ },
+ "recipeInput": {
+ "type": "object",
+ "required": ["key", "label"],
+ "additionalProperties": true,
+ "properties": {
+ "key": { "type": "string", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" },
+ "label": { "type": "string", "minLength": 1 },
+ "help": { "type": "string" },
+ "url": { "type": "string" },
+ "secret": { "type": "boolean" }
+ }
}
}
}
diff --git a/frontend/src/components/OperationsDock.jsx b/frontend/src/components/OperationsDock.jsx
index ae703c1c..a994deee 100644
--- a/frontend/src/components/OperationsDock.jsx
+++ b/frontend/src/components/OperationsDock.jsx
@@ -5,6 +5,7 @@ import {
AlertTriangle,
ArrowUpRight,
Clock3,
+ KeyRound,
ListRestart,
RotateCcw,
Square,
@@ -14,6 +15,7 @@ import {
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
import { useOperations } from '../contexts/OperationsContext';
import { useToast } from '../contexts/ToastContext';
import { useConfirm } from '../hooks/useConfirm';
@@ -23,6 +25,7 @@ import api from '../services/api';
import { operationKey } from '../services/operations';
import { formatDuration } from '../utils/time';
import IconButton from './IconButton';
+import FormField from './FormField';
import Pill from './ds/Pill';
import { statusKind, statusLabel } from './ds/status';
@@ -70,6 +73,96 @@ function OperationProgress({ operation, t }) {
);
}
+function RecipeHandoffCard({ operation, onSubmitted, t }) {
+ const handoff = operation.handoff;
+ const input = handoff?.input || {};
+ const [value, setValue] = useState('');
+ const [submitting, setSubmitting] = useState(false);
+ const [error, setError] = useState(null);
+ const fieldId = `recipe-handoff-${operation.id}-${handoff?.step_id || 'input'}`;
+
+ useEffect(() => {
+ setValue('');
+ setError(null);
+ setSubmitting(false);
+ }, [operation.id, handoff?.step_id]);
+
+ if (!handoff || !operation.requiresAction) return null;
+
+ const submit = async (event) => {
+ event.preventDefault();
+ if (!value.trim() || submitting) return;
+ setSubmitting(true);
+ setError(null);
+ try {
+ await api.submitRecipeHandoff(operation.id, handoff.step_id, value);
+ setValue('');
+ await onSubmitted();
+ } catch (submitError) {
+ setError(submitError?.message || t(
+ 'app.operationsDock.handoffFailed',
+ 'Could not submit this handoff',
+ ));
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ const ttlMinutes = handoff.ttl_seconds
+ ? Math.max(1, Math.ceil(handoff.ttl_seconds / 60))
+ : null;
+
+ return (
+ <form className="operations-dock__handoff" onSubmit={submit}>
+ <div className="operations-dock__handoff-head">
+ <span className="operations-dock__handoff-icon"><KeyRound size={15} /></span>
+ <div>
+ <span>{t('app.operationsDock.operatorHandoff', 'Operator handoff')}</span>
+ <strong>{handoff.title}</strong>
+ </div>
+ </div>
+ {handoff.description && <p>{handoff.description}</p>}
+ <FormField
+ label={input.label || t('app.operationsDock.handoffValue', 'Required value')}
+ htmlFor={fieldId}
+ hint={input.help || (ttlMinutes
+ ? t(
+ 'app.operationsDock.handoffExpiry',
+ 'The {{count}}-minute clock starts when you submit.',
+ { count: ttlMinutes },
+ )
+ : null)}
+ error={error}
+ required
+ >
+ <Input
+ id={fieldId}
+ type={input.secret === false ? 'text' : 'password'}
+ value={value}
+ onChange={(event) => setValue(event.target.value)}
+ autoComplete="off"
+ disabled={submitting}
+ />
+ </FormField>
+ <div className="operations-dock__handoff-actions">
+ {input.url && (
+ <Button asChild type="button" variant="ghost" size="sm">
+ <a href={input.url} target="_blank" rel="noreferrer">
+ {t('app.operationsDock.openHandoffLink', 'Open required link')}
+ <ArrowUpRight size={13} />
+ </a>
+ </Button>
+ )}
+ <Button type="submit" size="sm" disabled={!value.trim() || submitting}>
+ {submitting
+ ? t('app.operationsDock.resumingRecipe', 'Resuming…')
+ : t('app.operationsDock.continueRecipe', 'Continue Recipe')}
+ </Button>
+ </div>
+ </form>
+ );
+}
+
function ServiceLogDetail({ session, lines, error, onClear, onClose, logRef, t }) {
const source = session.logPath
|| (session.containerId != null ? `docker · ${String(session.containerId).slice(0, 12)}` : null)
@@ -352,6 +445,18 @@ export default function OperationsDock() {
<OperationProgress operation={selectedOperation} t={t} />
+ <RecipeHandoffCard
+ operation={selectedOperation}
+ onSubmitted={async () => {
+ await refresh();
+ toast.success(t(
+ 'app.operationsDock.recipeResumed',
+ 'Recipe resumed',
+ ));
+ }}
+ t={t}
+ />
+
{(selectedOperation.error || selectedStreamError) && (
<div className="operations-dock__error">
<AlertTriangle size={15} />
diff --git a/frontend/src/components/ds/status.js b/frontend/src/components/ds/status.js
index 2c7dbd85..d6c9edd8 100644
--- a/frontend/src/components/ds/status.js
+++ b/frontend/src/components/ds/status.js
@@ -86,6 +86,7 @@ const STATUS_KIND = {
canceled: 'amber',
identified: 'amber',
acknowledged: 'amber',
+ waiting: 'amber',
idle: 'amber',
'disk-sleep': 'amber',
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 20e41720..b0e431d3 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -4560,6 +4560,10 @@
"cancelQueued": "Cancellation requested",
"cancelTitle": "Cancel operation?",
"collapse": "Collapse Operations dock",
+ "continueRecipe": "Continue Recipe",
+ "handoffExpiry": "The {{count}}-minute clock starts when you submit.",
+ "handoffFailed": "Could not submit this handoff",
+ "handoffValue": "Required value",
"history": "History",
"lineCount": "{{count}} lines",
"live": "Live",
@@ -4569,8 +4573,12 @@
"noHistory": "No recent operations",
"open": "Open Operations dock",
"openDetails": "Open details",
+ "openHandoffLink": "Open required link",
+ "operatorHandoff": "Operator handoff",
"polling": "Polling",
"progress": "Progress",
+ "recipeResumed": "Recipe resumed",
+ "resumingRecipe": "Resuming…",
"retryQueued": "Retry queued",
"selectOperation": "Select an operation to inspect progress and logs",
"serviceLogs": "Service log session",
diff --git a/frontend/src/services/__tests__/operations.test.mjs b/frontend/src/services/__tests__/operations.test.mjs
index 9e6fa50a..c9f8fc57 100644
--- a/frontend/src/services/__tests__/operations.test.mjs
+++ b/frontend/src/services/__tests__/operations.test.mjs
@@ -76,6 +76,22 @@ test('bounds terminal history without dropping active or selected work', () => {
assert.deepEqual(bounded.map(operationKey), ['job:active', 'job:recent', 'job:selected']);
});
+test('keeps a handoff-waiting Recipe active and attention-worthy', () => {
+ const recipe = normalizeDeploymentOperation({
+ id: 'recipe-1',
+ kind: 'recipe.run',
+ status: 'waiting',
+ title: 'Recipe: Media server',
+ requires_action: true,
+ handoff: { step_id: 'claim', title: 'Claim the server' },
+ });
+ const bounded = boundOperationHistory([recipe], 0);
+ assert.deepEqual(bounded.map(operationKey), ['deploy:recipe-1']);
+ assert.equal(recipe.title, 'Recipe: Media server');
+ assert.equal(recipe.requiresAction, true);
+ assert.equal(recipe.handoff.step_id, 'claim');
+});
+
test('reconciles one run and marks a newly failed terminal operation unread', () => {
const current = [normalizeJobOperation({ id: 'job-1', kind: 'doctor.run', status: 'running' })];
const result = reconcileOperationStatus(current, {
diff --git a/frontend/src/services/api/deploymentJobs.js b/frontend/src/services/api/deploymentJobs.js
index 5988f34b..754fb20c 100644
--- a/frontend/src/services/api/deploymentJobs.js
+++ b/frontend/src/services/api/deploymentJobs.js
@@ -27,6 +27,13 @@ export async function retryDeploymentJob(jobId) {
return this.request(`/deployment-jobs/${jobId}/retry`, { method: 'POST' });
}
+export async function submitRecipeHandoff(jobId, stepId, value) {
+ return this.request(
+ `/recipes/runs/${encodeURIComponent(jobId)}/handoffs/${encodeURIComponent(stepId)}`,
+ { method: 'POST', body: { value } },
+ );
+}
+
// Simulated deployments (plan 51.5 dev tool). The GET 404s when the backend
// gate (DEMO_DEPLOYS_ENABLED) is off — callers treat that as "hidden".
export async function getDeploySimulateInfo() {
diff --git a/frontend/src/services/operations.js b/frontend/src/services/operations.js
index b1be537e..97411d45 100644
--- a/frontend/src/services/operations.js
+++ b/frontend/src/services/operations.js
@@ -1,6 +1,8 @@
import { isTerminalRunStatus } from '../hooks/runStream.js';
-const ACTIVE_STATUSES = new Set(['pending', 'running']);
+// A Recipe waiting on a human handoff is still an active run. It belongs in
+// the active list and the Needs attention filter, not buried in history.
+const ACTIVE_STATUSES = new Set(['pending', 'running', 'waiting']);
const SECURITY_KIND = /^security[.]/;
const stringId = (value) => (value == null ? null : String(value));
@@ -104,6 +106,7 @@ export function normalizeDeploymentOperation(job) {
canRetry: permissionFlag(job, 'can_retry', 'canRetry'),
requiresAction: permissionFlag(job, 'requires_action', 'requiresAction') || job.handoff === true,
needsAttention: permissionFlag(job, 'needs_attention', 'needsAttention'),
+ handoff: job.handoff || job.result?.handoff || null,
detailPath: job.detailPath || `/deployments/${encodeURIComponent(String(job.id))}`,
};
}
diff --git a/frontend/src/styles/components/_operations-dock.scss b/frontend/src/styles/components/_operations-dock.scss
index ac7756cc..a9669a4a 100644
--- a/frontend/src/styles/components/_operations-dock.scss
+++ b/frontend/src/styles/components/_operations-dock.scss
@@ -225,6 +225,86 @@
font-size: $font-size-xs;
}
+ &__handoff {
+ position: relative;
+ display: grid;
+ gap: $space-3;
+ padding: $space-3;
+ overflow: hidden;
+ border: 1px solid var(--amber);
+ border-radius: $radius-md;
+ background: var(--amber-bg);
+
+ &::before {
+ position: absolute;
+ inset-block: 0;
+ inset-inline-start: 0;
+ width: 3px;
+ background: var(--amber);
+ content: '';
+ }
+
+ > p {
+ margin: 0;
+ color: var(--text-dim);
+ font-size: $font-size-xs;
+ line-height: 1.55;
+ }
+
+ .form-field { gap: $space-1; }
+ .form-field__label { color: var(--text); font-size: $font-size-xs; }
+ .form-field__hint,
+ .form-field__error { margin-block: $space-1 0; font-size: 10px; }
+ input { font-family: var(--mono); }
+ }
+
+ &__handoff-head {
+ display: flex;
+ align-items: center;
+ gap: $space-2;
+
+ > div {
+ display: flex;
+ min-width: 0;
+ flex-direction: column;
+ }
+
+ span:not(.operations-dock__handoff-icon) {
+ color: var(--amber);
+ font-family: var(--mono);
+ font-size: 9px;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ }
+
+ strong {
+ overflow: hidden;
+ color: var(--text);
+ font-size: $font-size-sm;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ }
+
+ &__handoff-icon {
+ display: grid;
+ width: 28px;
+ height: 28px;
+ flex: 0 0 auto;
+ place-items: center;
+ border: 1px solid var(--amber);
+ border-radius: $radius-sm;
+ color: var(--amber);
+ background: var(--surface);
+ }
+
+ &__handoff-actions {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ gap: $space-2;
+ }
+
&__logs {
flex: 1;
min-height: 100px;