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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(deployments): simulated demo deploys through the real console pipeline
Juan Denis3cc708a1e26e
diff --git a/backend/app/api/deployment_jobs.py b/backend/app/api/deployment_jobs.pyindex 5b7ab83f..6e6e5c85 100644--- a/backend/app/api/deployment_jobs.py+++ b/backend/app/api/deployment_jobs.py@@ -1,6 +1,6 @@"""Deployment job API endpoints."""-from flask import Blueprint, request, jsonify+from flask import Blueprint, current_app, request, jsonifyfrom flask_jwt_extended import jwt_requiredfrom app.models.deployment_job import DeploymentJob, DeploymentJobLog@@ -9,6 +9,45 @@ from app.services.deployment_job_service import DeploymentJobServicedeployment_jobs_bp = Blueprint('deployment_jobs', __name__)+@deployment_jobs_bp.route('/simulate', methods=['GET'])+@jwt_required()+def get_simulate_info():+ """Simulated-deploy availability + scenario catalog (plan 51.5 dev tool).++ 404 when the DEMO_DEPLOYS_ENABLED gate is off (production default), so the+ surface simply doesn't exist outside dev.+ """+ if not current_app.config.get('DEMO_DEPLOYS_ENABLED'):+ return jsonify({'error': 'Not found'}), 404+ from app.services.demo_deploy_service import DemoDeployService+ return jsonify({'enabled': True,+ 'scenarios': DemoDeployService.list_scenarios()}), 200+++@deployment_jobs_bp.route('/simulate', methods=['POST'])+@jwt_required()+def simulate_deployment():+ """Create a simulated deployment job that streams scripted output through+ the real console pipeline. Body: {scenario, speed?}; ?wait=true runs it+ synchronously (tests)."""+ if not current_app.config.get('DEMO_DEPLOYS_ENABLED'):+ return jsonify({'error': 'Not found'}), 404+ from flask_jwt_extended import get_jwt_identity+ from app.services.demo_deploy_service import DemoDeployService++ data = request.get_json(silent=True) or {}+ wait = request.args.get('wait', 'false').lower() == 'true'+ result = DemoDeployService.create(+ scenario=data.get('scenario') or '',+ speed=data.get('speed') or 'fast',+ user_id=get_jwt_identity(),+ wait=wait,+ )+ if not result.get('success'):+ return jsonify({'error': result.get('error')}), 400+ return jsonify(result), 202++@deployment_jobs_bp.route('', methods=['GET'])@jwt_required()def list_deployment_jobs():diff --git a/backend/app/services/demo_deploy_service.py b/backend/app/services/demo_deploy_service.pynew file mode 100644index 00000000..3b10cc1b--- /dev/null+++ b/backend/app/services/demo_deploy_service.py@@ -0,0 +1,325 @@+"""Simulated deployments — scripted DeploymentJobs for the Deploy Console.++Plan 51.5: lets a developer exercise the full console (StepRail, live log+stream, ErrorCard + hints, SuccessBanner, retry) on any dev machine with no+Docker, shell, or network access. The "runner" is a script that drives the+REAL ``RunLogStream``, so DB rows, socket batches, poll fallback, failure+tails, hints, row cap, and step timings behave exactly as they do for real+deploys — what you test locally is what production renders.++Gated by ``DEMO_DEPLOYS_ENABLED`` (on in development/testing config, off in+production; env override ``SERVERKIT_DEMO_DEPLOYS``). Demo jobs run on the+local panel only — never against remote/agent servers.+"""++import time+import uuid+from datetime import datetime+from typing import Dict, Optional++from app import db+from app.models.deployment_job import DeploymentJob+from app.services.run_log_service import RunLogStream+from app.services.telemetry_service import generate_correlation_id++DEMO_KIND = 'demo_deploy'++# Per-line pacing by requested speed. 'instant' exists for tests.+SPEED_DELAYS = {'instant': 0.0, 'fast': 0.02, 'realtime': 0.3}+++class _DemoFailure(Exception):+ """A scripted (intentional) failure inside a demo scenario."""+++def _step(name, lines, fail=None):+ step = {'name': name, 'lines': lines}+ if fail:+ step['fail'] = fail+ return step+++def _success_steps():+ return [+ _step('Validate configuration', [+ ('info', 'Reading service manifest'),+ ('debug', 'Manifest OK — 1 service, 2 volumes, 1 network'),+ ('info', 'Checking port availability for 8080'),+ ('info', 'Port 8080 is free'),+ ]),+ _step('Pull base image', [+ ('info', 'Pulling node:20-alpine'),+ ('info', '20-alpine: pulling from library/node'),+ ('debug', 'Layer a1b2c3d4 already exists'),+ ('info', 'Status: image is up to date for node:20-alpine'),+ ]),+ _step('Build application', [+ ('info', 'Step 1/6 : FROM node:20-alpine'),+ ('info', 'Step 2/6 : WORKDIR /app'),+ ('info', 'Step 3/6 : COPY package*.json ./'),+ ('info', 'Step 4/6 : RUN npm ci --omit=dev'),+ ('info', 'added 214 packages in 6s'),+ ('info', 'Step 5/6 : COPY . .'),+ ('info', 'Step 6/6 : CMD ["node", "server.js"]'),+ ('info', 'Successfully built 3f1c2a9d41bb'),+ ]),+ _step('Configure routing', [+ ('info', 'Writing vhost configuration for demo-app'),+ ('info', 'Testing web server configuration'),+ ('info', 'Configuration test passed'),+ ('info', 'Web server reloaded'),+ ]),+ _step('Start containers', [+ ('info', 'Creating network demo-app_default'),+ ('info', 'Creating container demo-app-web-1'),+ ('info', 'Container demo-app-web-1 started'),+ ]),+ _step('Health check', [+ ('info', 'Waiting for http://127.0.0.1:8080/healthz'),+ ('debug', 'Attempt 1: 503 (still starting)'),+ ('info', 'Attempt 2: 200 OK'),+ ('info', 'Service is healthy'),+ ]),+ ]+++def _fail_build_steps():+ return [+ _step('Validate configuration', [+ ('info', 'Reading service manifest'),+ ('info', 'Checking port availability for 8080'),+ ('info', 'Port 8080 is free'),+ ]),+ _step('Pull base image', [+ ('info', 'Pulling node:20-alpine'),+ ('info', 'Status: image is up to date for node:20-alpine'),+ ]),+ _step('Build application', [+ ('info', 'Step 4/6 : RUN npm run build'),+ ('info', '> [email protected] build'),+ ('info', '> vite build'),+ ('error', "src/pages/Dashboard.jsx: Rollup failed to resolve import 'chart.js'"),+ ('error', 'npm ERR! code ELIFECYCLE'),+ ('error', 'npm ERR! errno 1'),+ ('error', 'npm ERR! [email protected] build: `vite build`'),+ ('error', 'npm ERR! Failed at the [email protected] build script.'),+ ], fail='Build failed: npm run build exited with code 1'),+ # Present in the plan so the StepRail shows a pending step past the+ # failure; the script raises before reaching it.+ _step('Start containers', []),+ ]+++def _long_steps():+ bulk = [('info', f'line {i:05d}: synthetic build output for row-cap testing')+ for i in range(1, 6001)]+ return [+ _step('Prepare', [+ ('info', 'Generating a very chatty build (~6,000 lines)'),+ ('info', 'The persisted log caps at 5,000 rows with a truncation marker'),+ ]),+ _step('Generate output', bulk),+ _step('Finish', [+ ('info', 'Output generation complete (this line lands past the cap)'),+ ]),+ ]+++def _ansi_steps():+ return [+ _step('Raw output torture test', [+ ('info', '\x1b[1;32m✔\x1b[0m Compiled successfully in 3.2s'),+ ('info', 'Progress: [====> ] 42%\rProgress: [========> ] 78%\rProgress: [==========] 100%'),+ ('warn', '\x1b[33mwarning\x1b[0m Deprecated API used in src/legacy.js'),+ ('info', '\x1b]0;build\x07Title-setting sequences are stripped too'),+ ('info', 'Plain line for contrast'),+ ]),+ _step('Verify', [+ ('info', 'If the lines above read cleanly, the sanitizer works'),+ ]),+ ]+++def _slow_steps():+ return [+ _step('Queue wait demo', [+ ('info', 'This scenario idled in "pending" first — that was the queued strip'),+ ]),+ _step('Slow step one', [+ ('info', f'Working... ({i}/6)') for i in range(1, 7)+ ]),+ _step('Slow step two', [+ ('info', f'Still working... ({i}/6)') for i in range(1, 7)+ ]),+ _step('Wrap up', [+ ('info', 'Done taking our time'),+ ]),+ ]+++# Ordered catalog; dict order is the order the UI lists them in.+SCENARIOS = {+ 'success': {+ 'name': 'Successful deploy',+ 'description': 'Six realistic steps ending in success — step timings and a published URL.',+ 'build': _success_steps,+ 'result': {'auto_domain': {'success': True, 'url': 'http://demo-app.lvh.me', 'demo': True}},+ },+ 'fail-build': {+ 'name': 'Failing build',+ 'description': 'Fails mid-build with a realistic tail — exercises the error card, hint, and retry.',+ 'build': _fail_build_steps,+ },+ 'long': {+ 'name': 'Very long output',+ 'description': '~6,000 lines — proves the 5,000-row cap, truncation marker, and log-pane performance.',+ 'build': _long_steps,+ },+ 'ansi': {+ 'name': 'ANSI / carriage-return noise',+ 'description': 'Color codes and \\r progress rewrites — proves the output sanitizer.',+ 'build': _ansi_steps,+ },+ 'slow': {+ 'name': 'Slow deploy',+ 'description': 'Sits queued first, then streams slowly — exercises the live timer and follow mode.',+ 'build': _slow_steps,+ 'pending_delay': 3.0,+ 'line_delay_factor': 12.0,+ },+}+++class DemoDeployService:+ """Creates and runs simulated (scripted) deployment jobs."""++ @classmethod+ def list_scenarios(cls):+ return [+ {'id': key, 'name': spec['name'], 'description': spec['description']}+ for key, spec in SCENARIOS.items()+ ]++ @classmethod+ def create(cls, scenario: str, speed: str = 'fast',+ user_id: Optional[int] = None, wait: bool = False) -> Dict:+ """Create a demo DeploymentJob and queue it (or run it when wait=True).++ Mirrors DeploymentJobService.install_template's shape so callers and+ the console treat demo jobs like any other deployment.+ """+ spec = SCENARIOS.get(scenario)+ if not spec:+ return {'success': False,+ 'error': f'Unknown scenario "{scenario}". Valid: {", ".join(SCENARIOS)}'}+ if speed not in SPEED_DELAYS:+ return {'success': False,+ 'error': f'Unknown speed "{speed}". Valid: {", ".join(SPEED_DELAYS)}'}++ job = DeploymentJob(+ id=str(uuid.uuid4()),+ kind=DEMO_KIND,+ status='pending',+ target_server_id=None, # demo jobs are local-panel only+ requested_by=user_id,+ trigger='demo',+ correlation_id=generate_correlation_id(),+ )+ job.set_plan({+ 'demo': True,+ 'scenario': scenario,+ 'speed': speed,+ 'steps': [{'name': step['name']} for step in spec['build']()],+ })+ db.session.add(job)+ db.session.commit()++ from app.services.deployment_job_service import DeploymentJobService+ if wait:+ DeploymentJobService.run_job(job.id)+ else:+ try:+ DeploymentJobService._enqueue_demo(job)+ except Exception as exc:+ # Same guard as install_template: never leave a runner-less+ # 'pending' row behind.+ db.session.rollback()+ job.status = 'failed'+ job.error_message = f'Failed to queue demo deployment: {exc}'+ job.completed_at = datetime.utcnow()+ 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),+ }++ @classmethod+ def run(cls, job: DeploymentJob) -> Dict:+ """Play the job's scenario through a real RunLogStream."""+ plan = job.get_plan()+ scenario = plan.get('scenario')+ spec = SCENARIOS.get(scenario)+ stream = RunLogStream.for_job(job)+ if not spec:+ return cls._fail(job, stream, f'Unknown demo scenario: {scenario}')++ delay = SPEED_DELAYS.get(plan.get('speed') or 'fast', SPEED_DELAYS['fast'])+ line_delay = min(0.8, delay * spec.get('line_delay_factor', 1.0))++ try:+ if delay and spec.get('pending_delay'):+ # Stay 'pending' for a bit so the console's queued strip shows.+ time.sleep(spec['pending_delay'])++ job.status = 'running'+ job.started_at = datetime.utcnow()+ db.session.commit()++ for index, step in enumerate(spec['build'](), start=1):+ stream.set_step(index, step['name'])+ lines = step['lines']+ bulk = len(lines) > 200+ for i, (level, message) in enumerate(lines):+ stream.log(level, message, step_index=index)+ # Bulk steps only pace every 100th line so 'long' stays+ # snappy while normal steps stream visibly.+ if line_delay and (not bulk or i % 100 == 0):+ time.sleep(line_delay)+ if step.get('fail'):+ raise _DemoFailure(step['fail'])++ job.status = 'succeeded'+ job.completed_at = datetime.utcnow()+ job.current_step_name = None+ job.set_result({**job.get_result(), 'demo': True, 'scenario': scenario,+ **spec.get('result', {})})+ db.session.commit()+ stream.log('info', 'Simulated deployment finished — no real resources were created.')+ stream.close('succeeded')+ return {'success': True, 'job': job.to_dict(include_logs=True)}+ except _DemoFailure as exc:+ return cls._fail(job, stream, str(exc))+ except Exception as exc:+ # Same crash guard as the real runners: never leave 'running'.+ return cls._fail(job, stream, f'Demo deployment crashed: {exc}')++ @classmethod+ def _fail(cls, job: DeploymentJob, stream: RunLogStream, message: str) -> Dict:+ try:+ db.session.rollback()+ job.status = 'failed'+ job.error_message = message+ job.completed_at = datetime.utcnow()+ result = job.get_result()+ result['demo'] = True+ result.setdefault('scenario', (job.get_plan() or {}).get('scenario'))+ job.set_result(result)+ db.session.commit()+ stream.log('error', message)+ except Exception:+ db.session.rollback()+ stream.close('failed', error_message=message)+ return {'success': False, 'error': message, 'job': job.to_dict(include_logs=True)}diff --git a/backend/app/services/deployment_job_service.py b/backend/app/services/deployment_job_service.pyindex 036500e9..6da9ff5e 100644--- a/backend/app/services/deployment_job_service.py+++ b/backend/app/services/deployment_job_service.py@@ -14,10 +14,12 @@ from app.services.docker_service import DockerServicefrom app.services.template_service import TemplateServicefrom app.services.telemetry_service import generate_correlation_id-# Unified job kinds (see register_jobs()): asynchronous template installs and-# builds/deploys of existing apps (e.g. repo-based services from Flow A).+# Unified job kinds (see register_jobs()): asynchronous template installs,+# builds/deploys of existing apps (e.g. repo-based services from Flow A), and+# simulated demo deploys (plan 51.5 dev tool).JOB_KIND = 'deploy.install'APP_JOB_KIND = 'deploy.app'+DEMO_JOB_KIND = 'deploy.demo'class DeploymentJobService:@@ -165,6 +167,10 @@ class DeploymentJobService:if job.kind == 'app_deploy':return cls._run_app_deploy(job)+ if job.kind == 'demo_deploy':+ from app.services.demo_deploy_service import DemoDeployService+ return DemoDeployService.run(job)+if job.kind != 'template_install':return {'success': False, 'error': f'Unsupported deployment job kind: {job.kind}'}@@ -238,7 +244,10 @@ class DeploymentJobService:db.session.add(clone)db.session.commit()- enqueue = cls._enqueue_app_deploy if clone.kind == 'app_deploy' else cls._enqueue_install+ enqueue = {+ 'app_deploy': cls._enqueue_app_deploy,+ 'demo_deploy': cls._enqueue_demo,+ }.get(clone.kind, cls._enqueue_install)try:enqueue(clone)except Exception as exc:@@ -479,6 +488,33 @@ class DeploymentJobService:'app_id': result.get('app_id'),}+ @classmethod+ def _enqueue_demo(cls, job: DeploymentJob):+ """Hand a simulated demo deploy to the unified job system (same+ pattern as ``_enqueue_install``)."""+ from app.jobs.service import JobService+ return JobService.enqueue(+ DEMO_JOB_KIND,+ payload={'deployment_job_id': job.id},+ max_attempts=1,+ owner_type='deployment_job',+ owner_id=job.id,+ correlation_id=job.correlation_id,+ )++ @staticmethod+ def _run_demo_job(unified_job):+ """Unified-job handler for ``deploy.demo`` (same shape as+ ``_run_install_job``): a scripted failure raises so the unified job is+ marked failed too."""+ deployment_job_id = (unified_job.get_payload() or {}).get('deployment_job_id')+ if not deployment_job_id:+ raise ValueError('deploy.demo job missing deployment_job_id')+ result = DeploymentJobService.run_job(deployment_job_id)+ if not result.get('success'):+ raise RuntimeError(result.get('error') or 'Demo deployment failed')+ return {'deployment_job_id': deployment_job_id}+@classmethoddef register_jobs(cls):"""Register deployment handlers with the unified job registry. Called once@@ -486,6 +522,7 @@ class DeploymentJobService:from app.jobs import registryregistry.register(JOB_KIND, cls._run_install_job, replace=True)registry.register(APP_JOB_KIND, cls._run_app_deploy_job, replace=True)+ registry.register(DEMO_JOB_KIND, cls._run_demo_job, replace=True)cls._reconcile_interrupted_jobs()@classmethoddiff --git a/backend/config.py b/backend/config.pyindex edc1f39a..539cf021 100644--- a/backend/config.py+++ b/backend/config.py@@ -152,6 +152,12 @@ class Config:AUTH_IP_WINDOW_MINUTES = _env_int('AUTH_IP_WINDOW_MINUTES', 15)AUTH_IP_BLOCK_MINUTES = _env_int('AUTH_IP_BLOCK_MINUTES', 15)+ # ── Simulated deployments (plan 51.5) ───────────────────────────────+ # Dev tool: scripted "demo" DeploymentJobs that exercise the Deploy+ # Console through the real log/socket pipeline without Docker or a+ # server. Off in production by default; SERVERKIT_DEMO_DEPLOYS overrides.+ DEMO_DEPLOYS_ENABLED = _env_bool('SERVERKIT_DEMO_DEPLOYS', False)+# ── Build packs ─────────────────────────────────────────────────────# Path to the optional nixpacks binary (used by build_service's opaque# nixpacks path). The transparent build-pack layer (buildpack_service)@@ -169,6 +175,7 @@ class DevelopmentConfig(Config):# lvh.me resolves *.lvh.me -> 127.0.0.1, so subdomain routing works locally# with zero DNS setup.SITES_BASE_DOMAIN = os.environ.get('SITES_BASE_DOMAIN', 'lvh.me')+ DEMO_DEPLOYS_ENABLED = _env_bool('SERVERKIT_DEMO_DEPLOYS', True)@classmethoddef init_app(cls, app):@@ -188,6 +195,7 @@ class TestingConfig(Config):# Deterministic base domain so subdomain-provisioning tests don't depend on# the developer's shell environment.SITES_BASE_DOMAIN = 'lvh.me'+ DEMO_DEPLOYS_ENABLED = Trueclass ProductionConfig(Config):diff --git a/backend/tests/test_demo_deploys.py b/backend/tests/test_demo_deploys.pynew file mode 100644index 00000000..d53693bb--- /dev/null+++ b/backend/tests/test_demo_deploys.py@@ -0,0 +1,150 @@+"""Proving tests for plan 51.5 — simulated (demo) deployments.++Demo jobs must flow through the REAL DeploymentJob + RunLogStream pipeline so+the Deploy Console can be exercised locally: these tests prove each scenario+reaches its terminal state with truthful logs, and that the surface is gated+off outside development.+"""++import os++from app import db+from app.models.deployment_job import DeploymentJob, DeploymentJobLog+++def _simulate(client, auth_headers, scenario, speed='instant', wait=True):+ qs = '?wait=true' if wait else ''+ return client.post(+ f'/api/v1/deployment-jobs/simulate{qs}',+ json={'scenario': scenario, 'speed': speed},+ headers=auth_headers,+ )+++def _job(job_id):+ return DeploymentJob.query.get(job_id)+++class TestSimulateInfo:+ def test_lists_scenarios_when_enabled(self, client, auth_headers):+ res = client.get('/api/v1/deployment-jobs/simulate', headers=auth_headers)+ assert res.status_code == 200+ body = res.get_json()+ assert body['enabled'] is True+ ids = [s['id'] for s in body['scenarios']]+ assert ids == ['success', 'fail-build', 'long', 'ansi', 'slow']+ assert all(s['name'] and s['description'] for s in body['scenarios'])++ def test_gate_off_returns_404_both_verbs(self, app, client, auth_headers):+ app.config['DEMO_DEPLOYS_ENABLED'] = False+ assert client.get('/api/v1/deployment-jobs/simulate',+ headers=auth_headers).status_code == 404+ assert _simulate(client, auth_headers, 'success').status_code == 404++ def test_config_defaults(self):+ from config import DevelopmentConfig, ProductionConfig, TestingConfig+ assert TestingConfig.DEMO_DEPLOYS_ENABLED is True+ if os.environ.get('SERVERKIT_DEMO_DEPLOYS') is None:+ assert DevelopmentConfig.DEMO_DEPLOYS_ENABLED is True+ assert ProductionConfig.DEMO_DEPLOYS_ENABLED is False+++class TestScenarios:+ def test_success_scenario_succeeds(self, client, auth_headers):+ res = _simulate(client, auth_headers, 'success')+ assert res.status_code == 202+ job = _job(res.get_json()['job_id'])+ assert job.kind == 'demo_deploy'+ assert job.trigger == 'demo'+ assert job.status == 'succeeded'+ assert job.target_server_id is None+ assert job.total_steps == 6+ result = job.get_result()+ assert result['demo'] is True+ assert result['scenario'] == 'success'+ assert len(result['step_timings']) == 6+ assert result['auto_domain']['url'].startswith('http://')+ assert job.logs.count() > 10++ def test_fail_build_has_tail_and_hint(self, client, auth_headers):+ res = _simulate(client, auth_headers, 'fail-build')+ assert res.status_code == 202+ job = _job(res.get_json()['job_id'])+ assert job.status == 'failed'+ assert 'npm run build' in job.error_message+ result = job.get_result()+ assert any('npm ERR!' in line for line in result['failure_tail'])+ # The npm ERR! tail must match the hint table's Node entry.+ assert 'Node build failed' in result['hint']++ def test_long_scenario_caps_persisted_rows(self, client, auth_headers):+ res = _simulate(client, auth_headers, 'long')+ assert res.status_code == 202+ job_id = res.get_json()['job_id']+ assert _job(job_id).status == 'succeeded'+ rows = DeploymentJobLog.query.filter_by(job_id=job_id).count()+ assert rows <= 5001 # cap + one marker row+ marker = DeploymentJobLog.query.filter_by(job_id=job_id).filter(+ DeploymentJobLog.message.contains('Log truncated at 5000 lines')+ ).count()+ assert marker == 1++ def test_ansi_scenario_is_sanitized(self, client, auth_headers):+ res = _simulate(client, auth_headers, 'ansi')+ assert res.status_code == 202+ job_id = res.get_json()['job_id']+ assert _job(job_id).status == 'succeeded'+ messages = [log.message for log in+ DeploymentJobLog.query.filter_by(job_id=job_id).all()]+ assert messages, 'expected persisted log rows'+ assert all('\x1b' not in m for m in messages)+ # \r overwrites collapse to the final segment.+ assert any(m == 'Progress: [==========] 100%' for m in messages)++ def test_unknown_scenario_400(self, client, auth_headers):+ res = _simulate(client, auth_headers, 'nope')+ assert res.status_code == 400+ assert 'Unknown scenario' in res.get_json()['error']++ def test_unknown_speed_400(self, client, auth_headers):+ res = client.post(+ '/api/v1/deployment-jobs/simulate?wait=true',+ json={'scenario': 'success', 'speed': 'ludicrous'},+ headers=auth_headers,+ )+ assert res.status_code == 400+ assert 'Unknown speed' in res.get_json()['error']+++class TestLifecycle:+ def test_async_create_leaves_pending_job(self, client, auth_headers):+ res = _simulate(client, auth_headers, 'success', wait=False)+ assert res.status_code == 202+ job = _job(res.get_json()['job_id'])+ # No consumer runs in tests: the job sits queued, not failed.+ assert job.status == 'pending'+ assert job.get_plan()['scenario'] == 'success'++ def test_retry_failed_demo_job_clones_it(self, client, auth_headers):+ res = _simulate(client, auth_headers, 'fail-build')+ original_id = res.get_json()['job_id']+ assert _job(original_id).status == 'failed'++ retry = client.post(f'/api/v1/deployment-jobs/{original_id}/retry',+ headers=auth_headers)+ assert retry.status_code == 202+ clone_id = retry.get_json()['job_id']+ assert clone_id != original_id+ clone = _job(clone_id)+ assert clone.kind == 'demo_deploy'+ assert clone.status == 'pending'+ assert clone.trigger == 'retry'+ assert clone.get_plan()['scenario'] == 'fail-build'++ def test_run_job_dispatches_demo_kind(self, app, auth_headers, client):+ from app.services.deployment_job_service import DeploymentJobService+ res = _simulate(client, auth_headers, 'success', wait=False)+ job_id = res.get_json()['job_id']+ result = DeploymentJobService.run_job(job_id)+ assert result['success'] is True+ assert _job(job_id).status == 'succeeded'