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
fix(deployments): stop stuck 0% installs, deploy repo apps on create, unify install UX
Juan Denis98ad0481a564
diff --git a/.gitignore b/.gitignoreindex 3f8f2716..608fcd3a 100644--- a/.gitignore+++ b/.gitignore@@ -179,11 +179,16 @@ docs/SERVICES_ROADMAP.md# here — the source of truth is the extension's own repo, and vendoring a copy# guarantees the two drift apart.backend/app/plugins/serverkit-analytics/+backend/app/plugins/serverkit-cloud-provision/backend/app/plugins/serverkit-crowdsec/backend/app/plugins/serverkit-dns-server/+backend/app/plugins/serverkit-ftp/backend/app/plugins/serverkit-gpu/+backend/app/plugins/serverkit-gui/backend/app/plugins/serverkit-k8s/backend/app/plugins/serverkit-mail/+backend/app/plugins/serverkit-remote-access/+backend/app/plugins/serverkit-status/backend/app/plugins/serverkit-tramo/frontend/src/plugins/serverkit-analytics/frontend/src/plugins/serverkit-crowdsec/diff --git a/backend/app/api/apps.py b/backend/app/api/apps.pyindex 96877ca9..427ced23 100644--- a/backend/app/api/apps.py+++ b/backend/app/api/apps.py@@ -6,7 +6,7 @@ import jsonimport reimport shutilfrom datetime import datetime-from flask import Blueprint, request, jsonify+from flask import Blueprint, request, jsonify, current_appfrom flask_jwt_extended import jwt_required, get_jwt_identityfrom app import dbfrom app.models import Application, User@@ -895,9 +895,30 @@ def create_app_from_repository():except Exception:manifest_summary = None+ # Actually deploy + start the service: hand it to the same observable+ # DeploymentJob pipeline template installs use (kind 'app_deploy' →+ # unified job 'deploy.app' → DeploymentService.deploy). A queue failure+ # must NOT fail app creation — the service stays 'stopped' and the user+ # can deploy manually from the Builds tab.+ deploy_job_id = None+ try:+ from app.services.deployment_job_service import DeploymentJobService+ enqueue_result = DeploymentJobService.enqueue_app_deploy(+ app, user_id=current_user_id, trigger='install')+ if enqueue_result.get('success'):+ deploy_job_id = enqueue_result.get('job_id')+ else:+ current_app.logger.warning(+ 'app deploy enqueue failed for app %s: %s',+ app.id, enqueue_result.get('error'))+ except Exception as exc:+ current_app.logger.warning(+ 'app deploy enqueue failed for app %s: %s', app.id, exc)+return jsonify({'message': 'Repository service created','app': _attach_deploy_config(app.to_dict(include_linked=True)),+ 'deploy_job_id': deploy_job_id,'manifest_import': manifest_summary,'deploy_config': {'repo_url': _safe_repo_url(deploy_repo_url),diff --git a/backend/app/api/deployment_jobs.py b/backend/app/api/deployment_jobs.pyindex 55e0759e..ef5a043f 100644--- a/backend/app/api/deployment_jobs.py+++ b/backend/app/api/deployment_jobs.py@@ -14,10 +14,12 @@ deployment_jobs_bp = Blueprint('deployment_jobs', __name__)def list_deployment_jobs():status = request.args.get('status')target_server_id = request.args.get('server_id')+ app_id = request.args.get('app_id', type=int)limit = request.args.get('limit', 50, type=int)jobs = DeploymentJobService.list_jobs(status=status,target_server_id=target_server_id,+ app_id=app_id,limit=min(limit, 200),)return jsonify({'jobs': jobs}), 200diff --git a/backend/app/models/deployment_job.py b/backend/app/models/deployment_job.pyindex 3ec22c8c..4ebd9f72 100644--- a/backend/app/models/deployment_job.py+++ b/backend/app/models/deployment_job.py@@ -142,7 +142,14 @@ class DeploymentJobLog(db.Model):__tablename__ = 'deployment_job_logs'- id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)+ # BigInteger on SQLite is NOT a rowid alias, so it never autoincrements and+ # every insert fails with "NOT NULL constraint failed: deployment_job_logs.id".+ # Use a real Integer PK on SQLite (rowid alias → autoincrement works).+ id = db.Column(+ db.BigInteger().with_variant(db.Integer, 'sqlite'),+ primary_key=True,+ autoincrement=True,+ )job_id = db.Column(db.String(36), db.ForeignKey('deployment_jobs.id'), nullable=False, index=True)step_index = db.Column(db.Integer, nullable=True)level = db.Column(db.String(10), default='info')diff --git a/backend/app/services/compose_env_service.py b/backend/app/services/compose_env_service.pyindex 7385e547..48e98486 100644--- a/backend/app/services/compose_env_service.py+++ b/backend/app/services/compose_env_service.py@@ -8,7 +8,10 @@ app's containers we write a **managed override compose file**(``docker-compose.serverkit.yml``) next to the app's base compose. The overrideadds an ``environment:`` overlay to every service; Docker Compose merges it on topof the base (override wins on key collisions), so the effective env is-authoritative — matching the single-container behaviour.+authoritative — matching the single-container behaviour. The override also+carries per-app resource limits and a ``restart: unless-stopped`` default for+services that don't set their own restart policy, so app containers survive a+reboot / daemon restart.This is non-destructive: ServerKit owns only the override file and never edits theuser's / template's base compose. The override is regenerated on every@@ -85,17 +88,23 @@ class ComposeEnvService:return None@staticmethod- def _service_names(base_compose_path):- """Service names declared in the base compose (empty list on any error)."""+ def _services(base_compose_path):+ """Services declared in the base compose as {name: service-dict}+ (empty dict on any error)."""try:with open(base_compose_path, 'r', encoding='utf-8') as f:data = yaml.safe_load(f) or {}services = data.get('services') or {}if isinstance(services, dict):- return list(services.keys())+ return servicesexcept Exception as e:logger.debug('could not read services from %s: %s', base_compose_path, e)- return []+ return {}++ @classmethod+ def _service_names(cls, base_compose_path):+ """Service names declared in the base compose (empty list on any error)."""+ return list(cls._services(base_compose_path).keys())@staticmethoddef _limits_block(app):@@ -145,7 +154,8 @@ class ComposeEnvService:return {'applies': False, 'path': None, 'content': None}override_path = cls.override_path(project_path)base_path = base if os.path.isabs(base) else os.path.join(project_path, base)- service_names = cls._service_names(base_path)+ services = cls._services(base_path)+ service_names = list(services.keys())if not service_names:return {'applies': True, 'path': override_path, 'content': None}@@ -171,6 +181,14 @@ class ComposeEnvService:if limits:services_block.setdefault(service_names[0], {}).update(limits)+ # Restart policy: services without an explicit `restart:` get+ # `unless-stopped` so an app's containers come back after a reboot or+ # Docker daemon restart (a service that sets its own policy — even+ # `restart: "no"` — is left alone).+ for name, svc in services.items():+ if not (isinstance(svc, dict) and svc.get('restart')):+ services_block.setdefault(name, {})['restart'] = 'unless-stopped'+if not services_block:# Nothing to inject → no override should exist.return {'applies': True, 'path': override_path, 'content': None}@@ -180,7 +198,8 @@ class ComposeEnvService:'# Managed by ServerKit — do not edit.\n''# Injects the app\'s effective environment (shared variable groups\n''# under the app\'s own local env vars) into every compose service,\n'- '# plus any per-app resource limits on the primary service.\n'+ '# plus any per-app resource limits on the primary service and a\n'+ '# `restart: unless-stopped` default for services without one.\n''# Regenerated on every deploy; delete it and it will be recreated.\n')content = header + yaml.safe_dump(override, default_flow_style=False, sort_keys=True)diff --git a/backend/app/services/deployment_job_service.py b/backend/app/services/deployment_job_service.pyindex e738efa8..dfc8a8be 100644--- a/backend/app/services/deployment_job_service.py+++ b/backend/app/services/deployment_job_service.py@@ -13,8 +13,10 @@ from app.services.docker_service import DockerServicefrom app.services.template_service import TemplateServicefrom app.services.telemetry_service import generate_correlation_id-# Unified job kind for asynchronous template installs (see register_jobs()).+# Unified job kinds (see register_jobs()): asynchronous template installs and+# builds/deploys of existing apps (e.g. repo-based services from Flow A).JOB_KIND = 'deploy.install'+APP_JOB_KIND = 'deploy.app'class DeploymentJobService:@@ -75,7 +77,72 @@ class DeploymentJobService:if wait:cls.run_job(job.id)else:- cls._enqueue_install(job)+ try:+ cls._enqueue_install(job)+ except Exception as exc:+ # Enqueue failed after the DeploymentJob commit — without this+ # the row would sit 'pending' forever with no runner.+ db.session.rollback()+ job.status = 'failed'+ job.error_message = f'Failed to queue 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 enqueue_app_deploy(cls, app, user_id: int = None, trigger: str = 'install') -> Dict:+ """Create a deploy job for an existing app and queue it asynchronously.++ Used by the repo-based create flow (POST /apps/from-repository): the+ app row already exists (cloned + build/deploy configured) but nothing+ has been built or started yet. The job runs the existing+ DeploymentService.deploy pipeline with progress persisted to+ deployment_job_logs, so repo apps get the same observable deployment+ UX as template installs. Deploys create containers and are NOT+ idempotent, so max_attempts=1 (no auto-retry), same as installs.+ """+ job = DeploymentJob(+ id=str(uuid.uuid4()),+ kind='app_deploy',+ status='pending',+ app_id=app.id,+ target_server_id=app.server_id,+ requested_by=user_id,+ trigger=trigger,+ correlation_id=generate_correlation_id(),+ )+ # Execution is delegated to DeploymentService.deploy; these steps only+ # drive the progress bar and mirror the milestones _run_app_deploy logs.+ job.set_plan({+ 'app_id': app.id,+ 'app_name': app.name,+ 'steps': [+ {'name': 'Prepare deployment'},+ {'name': 'Build application'},+ {'name': 'Start containers'},+ ],+ })+ db.session.add(job)+ db.session.commit()++ try:+ cls._enqueue_app_deploy(job)+ except Exception as exc:+ # Enqueue failed after the DeploymentJob commit — without this the+ # row would sit 'pending' forever with no runner (same guard as+ # install_template).+ db.session.rollback()+ job.status = 'failed'+ job.error_message = f'Failed to queue deployment: {exc}'+ job.completed_at = datetime.utcnow()+ db.session.commit()+ return {'success': False, 'error': job.error_message, 'job_id': job.id}return {'success': True,@@ -90,11 +157,29 @@ class DeploymentJobService:if not job:return {'success': False, 'error': 'Deployment job not found'}+ if job.kind == 'app_deploy':+ return cls._run_app_deploy(job)+if job.kind != 'template_install':return {'success': False, 'error': f'Unsupported deployment job kind: {job.kind}'}runner = DeploymentPlanRunner(job)- run_result = runner.run()+ try:+ run_result = runner.run()+ except Exception as exc:+ # The runner died before/outside its own error handling (schema+ # bug, wedged session, ...). Mark the job failed visibly so the UI+ # never shows a deployment stuck at "running" with no explanation.+ try:+ db.session.rollback()+ job.status = 'failed'+ job.error_message = str(exc)+ job.completed_at = datetime.utcnow()+ db.session.commit()+ runner.log('error', f'Deployment crashed: {exc}')+ except Exception:+ db.session.rollback()+ return {'success': False, 'error': str(exc)}if not run_result.get('success'):return run_result@@ -115,14 +200,80 @@ class DeploymentJobService:return job.to_dict(include_logs=include_logs) if job else None@classmethod- def list_jobs(cls, status: str = None, target_server_id: str = None, limit: int = 50):+ def list_jobs(cls, status: str = None, target_server_id: str = None,+ app_id: int = None, limit: int = 50):query = DeploymentJob.query.order_by(DeploymentJob.created_at.desc())if status:query = query.filter_by(status=status)if target_server_id:query = query.filter_by(target_server_id=cls._normalize_server_id(target_server_id))+ if app_id is not None:+ query = query.filter_by(app_id=app_id)return [job.to_dict() for job in query.limit(limit).all()]+ @classmethod+ def _run_app_deploy(cls, job: DeploymentJob) -> Dict:+ """Run an 'app_deploy' job: build + start an existing app via the+ existing DeploymentService.deploy pipeline (no build logic is+ reimplemented here), with milestones logged to deployment_job_logs so+ the UI sees the same progress/log stream as a template install."""+ runner = DeploymentPlanRunner(job)+ try:+ app = Application.query.get(job.app_id) if job.app_id else None+ if not app:+ raise RuntimeError(f'Application not found for deployment job {job.id}')++ job.status = 'running'+ job.started_at = datetime.utcnow()+ job.current_step = 1+ job.current_step_name = 'Prepare deployment'+ db.session.commit()+ runner.log('info', f"Deploying application '{app.name}' (trigger: {job.trigger})")++ job.current_step = 2+ job.current_step_name = 'Build application'+ db.session.commit()++ from app.services.deployment_service import DeploymentService+ result = DeploymentService.deploy(+ app.id,+ user_id=job.requested_by,+ trigger=job.trigger or 'manual',+ log_callback=lambda line: runner.log('info', line),+ )+ if not result.get('success'):+ raise RuntimeError(result.get('error') or 'Deployment failed')++ job.current_step = 3+ job.current_step_name = 'Start containers'+ db.session.commit()+ runner.log('info', 'Containers started')++ deployment = result.get('deployment') or {}+ job.status = 'succeeded'+ job.completed_at = datetime.utcnow()+ job.current_step_name = None+ job.deployment_id = deployment.get('id')+ job.set_result({**job.get_result(), 'app_id': app.id,+ 'deployment_id': deployment.get('id')})+ db.session.commit()+ runner.log('info', f"Deployment completed: {app.name} is now live")+ return {'success': True, 'app_id': app.id, 'job': job.to_dict(include_logs=True)}+ except Exception as exc:+ # Never leave the job stuck 'running': mark it failed with a+ # visible error + log line, even if the session needs a rollback+ # first (mirrors the runner's own failure handling).+ try:+ db.session.rollback()+ job.status = 'failed'+ job.error_message = str(exc)+ job.completed_at = datetime.utcnow()+ db.session.commit()+ runner.log('error', f'Deployment failed: {exc}')+ except Exception:+ db.session.rollback()+ return {'success': False, 'error': str(exc)}+@classmethoddef _finalize_template_install(cls, job: DeploymentJob) -> Dict:plan = job.get_plan()@@ -245,12 +396,67 @@ class DeploymentJobService:'app_name': result.get('app_name'),}+ @classmethod+ def _enqueue_app_deploy(cls, job: DeploymentJob):+ """Hand an app deploy to the unified job system (same pattern as+ ``_enqueue_install``): persistent on the Queue Bus, run by the single+ JobConsumer, max_attempts=1 because deploys are not idempotent."""+ from app.jobs.service import JobService+ return JobService.enqueue(+ APP_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_app_deploy_job(unified_job):+ """Unified-job handler for ``deploy.app`` (same shape as+ ``_run_install_job``): a failed deploy 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.app job missing deployment_job_id')+ result = DeploymentJobService.run_job(deployment_job_id)+ if not result.get('success'):+ raise RuntimeError(result.get('error') or 'Deployment failed')+ return {+ 'deployment_job_id': deployment_job_id,+ 'app_id': result.get('app_id'),+ }+@classmethoddef register_jobs(cls):"""Register deployment handlers with the unified job registry. Called onceat app startup (see app/__init__.py)."""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)+ cls._reconcile_interrupted_jobs()++ @classmethod+ def _reconcile_interrupted_jobs(cls):+ """Fail DeploymentJobs left 'running' by a previous process.++ Called once at startup: a job still 'running' at boot has no live+ runner (the process that ran it is gone), so leaving it would show a+ forever-spinning deployment in the UI with no logs and no error.+ """+ try:+ stale = DeploymentJob.query.filter_by(status='running').all()+ for job in stale:+ job.status = 'failed'+ job.error_message = (+ 'Interrupted: the server restarted while this deployment was '+ 'running. Please retry the install.'+ )+ job.completed_at = datetime.utcnow()+ if stale:+ db.session.commit()+ except Exception:+ db.session.rollback()@staticmethoddef _normalize_server_id(server_id: Optional[str]) -> Optional[str]:diff --git a/backend/app/services/deployment_runner.py b/backend/app/services/deployment_runner.pyindex 7b7d12b0..a09f782a 100644--- a/backend/app/services/deployment_runner.py+++ b/backend/app/services/deployment_runner.py@@ -39,30 +39,34 @@ class DeploymentPlanRunner:steps = plan.get('steps', [])results = []- self.job.status = 'running'- self.job.started_at = datetime.utcnow()- self.job.total_steps = len(steps)- db.session.commit()-- self.log('info', f"Deployment started on {self.job.target_server_name}")- TelemetryService.emit(- source='deployment',- event_type='deployment.started',- message=f'Deployment started: {self.job.kind}',- severity='info',- resource_type='deployment_job',- resource_id=self.job.id,- correlation_id=self.correlation_id,- payload={- 'job_id': self.job.id,- 'kind': self.job.kind,- 'target_server_id': self.job.target_server_id,- 'total_steps': len(steps),- },- commit=False,- )-+ # Everything — including the very first status write and log line — runs+ # inside the try so ANY failure (schema bugs, telemetry errors, DB hiccups)+ # marks the job failed with a visible error instead of leaving it stuck+ # at "running 0%" with no logs forever.try:+ self.job.status = 'running'+ self.job.started_at = datetime.utcnow()+ self.job.total_steps = len(steps)+ db.session.commit()++ self.log('info', f"Deployment started on {self.job.target_server_name}")+ TelemetryService.emit(+ source='deployment',+ event_type='deployment.started',+ message=f'Deployment started: {self.job.kind}',+ severity='info',+ resource_type='deployment_job',+ resource_id=self.job.id,+ correlation_id=self.correlation_id,+ payload={+ 'job_id': self.job.id,+ 'kind': self.job.kind,+ 'target_server_id': self.job.target_server_id,+ 'total_steps': len(steps),+ },+ commit=False,+ )+for index, step in enumerate(steps, start=1):name = step.get('name') or step.get('type') or f"Step {index}"self.job.current_step = index@@ -105,29 +109,40 @@ class DeploymentPlanRunner:return {'success': True, 'steps': results}except Exception as exc:- self.job.status = 'failed'- self.job.completed_at = datetime.utcnow()- self.job.error_message = str(exc)- self.job.set_result({'steps': results})- db.session.commit()+ # The session may be wedged (e.g. a failed flush rolled everything+ # back) — start clean, then mark the job failed. Never let the+ # failure-handling itself raise: a stuck "running" job is worse+ # than a missing log line.+ try:+ db.session.rollback()+ self.job.status = 'failed'+ self.job.completed_at = datetime.utcnow()+ self.job.error_message = str(exc)+ self.job.set_result({'steps': results})+ db.session.commit()+ except Exception:+ db.session.rollback()self.log('error', str(exc), step_index=self.job.current_step)- TelemetryService.emit(- source='deployment',- event_type='deployment.failed',- message=f'Deployment failed: {self.job.kind}',- severity='error',- resource_type='deployment_job',- resource_id=self.job.id,- correlation_id=self.correlation_id,- payload={- 'job_id': self.job.id,- 'kind': self.job.kind,- 'error': str(exc),- 'failed_step': self.job.current_step,- },- commit=False,- )+ try:+ TelemetryService.emit(+ source='deployment',+ event_type='deployment.failed',+ message=f'Deployment failed: {self.job.kind}',+ severity='error',+ resource_type='deployment_job',+ resource_id=self.job.id,+ correlation_id=self.correlation_id,+ payload={+ 'job_id': self.job.id,+ 'kind': self.job.kind,+ 'error': str(exc),+ 'failed_step': self.job.current_step,+ },+ commit=False,+ )+ except Exception:+ passreturn {'success': False, 'error': str(exc), 'steps': results}def log(self, level: str, message: str, data: Any = None, step_index: int = None):@@ -138,15 +153,20 @@ class DeploymentPlanRunner:except TypeError:payload = json.dumps(str(data))- entry = DeploymentJobLog(- job_id=self.job.id,- step_index=step_index,- level=level,- message=message,- data=payload,- )- db.session.add(entry)- db.session.commit()+ # Logging must never kill the deployment: a failed log insert rolls+ # back and is skipped rather than crashing the runner mid-job.+ try:+ entry = DeploymentJobLog(+ job_id=self.job.id,+ step_index=step_index,+ level=level,+ message=message,+ data=payload,+ )+ db.session.add(entry)+ db.session.commit()+ except Exception:+ db.session.rollback()def _execute_step(self, step: Dict[str, Any]) -> Any:step_type = step.get('type')diff --git a/backend/migrations/versions/076_deployment_job_logs_sqlite_id.py b/backend/migrations/versions/076_deployment_job_logs_sqlite_id.pynew file mode 100644index 00000000..7e37bc17--- /dev/null+++ b/backend/migrations/versions/076_deployment_job_logs_sqlite_id.py@@ -0,0 +1,52 @@+"""Fix ``deployment_job_logs.id`` autoincrement on SQLite.++SQLite only treats an exact ``INTEGER PRIMARY KEY`` as a rowid alias; the+``BIGINT PRIMARY KEY`` created for ``deployment_job_logs.id`` never+autoincrements, so the very first deployment-log insert on a fresh SQLite+install fails with ``NOT NULL constraint failed: deployment_job_logs.id`` and+the deployment job wedges at "running", step 0, with zero logs.++The model now uses ``BigInteger().with_variant(Integer, 'sqlite')``; this+migration rebuilds the table on existing SQLite databases. Other dialects+handle BIGINT autoincrement natively and are left untouched.++Idempotent: guards on dialect, table presence, and the live column type.++Revision ID: 076_deployment_job_logs_sqlite_id+Revises: 075_sandbox_runs+Create Date: 2026-07-22+"""+from alembic import op+import sqlalchemy as sa++revision = '076_deployment_job_logs_sqlite_id'+down_revision = '075_sandbox_runs'+branch_labels = None+depends_on = None+++def upgrade():+ conn = op.get_bind()+ if conn.dialect.name != 'sqlite':+ return+ inspector = sa.inspect(conn)+ if 'deployment_job_logs' not in set(inspector.get_table_names()):+ return+ columns = {c['name']: c for c in inspector.get_columns('deployment_job_logs')}+ id_col = columns.get('id')+ if id_col is None or 'BIGINT' not in str(id_col['type']).upper():+ return+ # batch mode with recreate='always' rebuilds the table (the only way to+ # change a column type on SQLite) while preserving rows, indexes, and PK.+ with op.batch_alter_table('deployment_job_logs', recreate='always') as batch:+ batch.alter_column(+ 'id',+ existing_type=sa.BigInteger(),+ type_=sa.Integer(),+ existing_nullable=False,+ )+++def downgrade():+ # Harmless to keep the Integer PK; no-op on purpose.+ passdiff --git a/backend/tests/test_app_deploy_jobs.py b/backend/tests/test_app_deploy_jobs.pynew file mode 100644index 00000000..e0a20f16--- /dev/null+++ b/backend/tests/test_app_deploy_jobs.py@@ -0,0 +1,291 @@+"""Flow A app deploys — DeploymentJob kind 'app_deploy' + unified job+'deploy.app' (the repo-based create flow deploys through the same observable+pipeline as template installs)."""+import uuid++import pytest++from app import db+from app.jobs import registry+from app.jobs.models import Job+from app.jobs.service import JobService, GROUP_SLUG, QUEUE_SLUG+from app.jobs.consumer import JobConsumer+from app.queue_bus.service import QueueBusService++[email protected](autouse=True)+def reset_jobs(app):+ """Clean broker + handler registry before each test (same as test_jobs.py)."""+ QueueBusService.reset_broker()+ registry.clear()+ yield+ registry.clear()+++def _drain_once(consumer=None):+ consumer = consumer or JobConsumer()+ messages = QueueBusService.receive(GROUP_SLUG, QUEUE_SLUG, max_messages=1)+ assert messages, 'expected a queued job message'+ consumer.process_message(messages[0])+ return messages[0]+++def _make_app(name='repo-app'):+ from app.models.application import Application+ a = Application(name=name, app_type='docker', status='stopped',+ root_path='/srv/' + name, user_id=1)+ db.session.add(a)+ db.session.commit()+ return a+++def _make_job(app_id, kind='app_deploy', status='pending'):+ from app.models.deployment_job import DeploymentJob+ job = DeploymentJob(id=str(uuid.uuid4()), kind=kind, status=status,+ app_id=app_id, trigger='install')+ job.set_plan({'app_id': app_id, 'steps': [{'name': 'Prepare deployment'},+ {'name': 'Build application'},+ {'name': 'Start containers'}]})+ db.session.add(job)+ db.session.commit()+ return job+++class TestEnqueueAppDeploy:+ def test_creates_deployment_job_and_enqueues_unified_job(self, app):+ from app.services.deployment_job_service import DeploymentJobService+ from app.models.deployment_job import DeploymentJob+ with app.app_context():+ a = _make_app()+ result = DeploymentJobService.enqueue_app_deploy(a, user_id=1, trigger='install')++ assert result['success'] is True+ job = DeploymentJob.query.get(result['job_id'])+ assert job is not None+ assert job.kind == 'app_deploy'+ assert job.status == 'pending' # enqueued, not run inline+ assert job.app_id == a.id+ assert job.requested_by == 1+ assert job.trigger == 'install'+ assert job.total_steps == 3 # prepare / build / start++ unified = Job.query.filter_by(kind='deploy.app', owner_id=job.id).first()+ assert unified is not None+ assert unified.owner_type == 'deployment_job'+ assert unified.get_payload() == {'deployment_job_id': job.id}+ assert unified.max_attempts == 1+ assert unified.correlation_id == job.correlation_id++ def test_enqueue_failure_marks_job_failed(self, app, monkeypatch):+ from app.services.deployment_job_service import DeploymentJobService+ from app.models.deployment_job import DeploymentJob++ def _boom(job):+ raise RuntimeError('queue bus down')++ monkeypatch.setattr(DeploymentJobService, '_enqueue_app_deploy',+ classmethod(lambda cls, job: _boom(job)))+ with app.app_context():+ a = _make_app()+ result = DeploymentJobService.enqueue_app_deploy(a, user_id=1)+ assert result['success'] is False+ job = DeploymentJob.query.get(result['job_id'])+ assert job.status == 'failed'+ assert 'queue bus down' in (job.error_message or '')+ assert job.completed_at is not None+++class TestRunAppDeployJob:+ def test_success_marks_job_succeeded_with_logs(self, app, monkeypatch):+ from app.services.deployment_job_service import DeploymentJobService+ from app.services.deployment_service import DeploymentService+ from app.models.deployment_job import DeploymentJob++ seen = {}++ def fake_deploy(cls, app_id, user_id=None, trigger='manual', log_callback=None, **kw):+ seen['app_id'] = app_id+ seen['trigger'] = trigger+ if log_callback:+ log_callback('Starting build for repo-app...')+ return {'success': True, 'deployment': {'id': 42}}++ monkeypatch.setattr(DeploymentService, 'deploy', classmethod(fake_deploy))+ with app.app_context():+ a = _make_app()+ job = _make_job(a.id)++ result = DeploymentJobService.run_job(job.id)++ assert result['success'] is True+ assert result['app_id'] == a.id+ assert seen['app_id'] == a.id+ assert seen['trigger'] == 'install'++ refreshed = DeploymentJob.query.get(job.id)+ assert refreshed.status == 'succeeded'+ assert refreshed.completed_at is not None+ assert refreshed.get_result()['app_id'] == a.id+ assert refreshed.deployment_id == 42++ messages = [log.message for log in refreshed.logs.all()]+ assert any('Deploying application' in m for m in messages)+ assert any('Starting build' in m for m in messages) # streamed log_callback+ assert any('Containers started' in m for m in messages)+ assert any('now live' in m for m in messages)++ def test_failure_marks_job_failed_with_error(self, app, monkeypatch):+ from app.services.deployment_job_service import DeploymentJobService+ from app.services.deployment_service import DeploymentService+ from app.models.deployment_job import DeploymentJob++ monkeypatch.setattr(DeploymentService, 'deploy',+ classmethod(lambda cls, app_id, **kw: {+ 'success': False, 'error': 'build boom'}))+ with app.app_context():+ a = _make_app()+ job = _make_job(a.id)++ result = DeploymentJobService.run_job(job.id)++ assert result['success'] is False+ refreshed = DeploymentJob.query.get(job.id)+ assert refreshed.status == 'failed'+ assert refreshed.error_message == 'build boom'+ assert refreshed.completed_at is not None+ error_logs = [log for log in refreshed.logs.all() if log.level == 'error']+ assert error_logs and 'build boom' in error_logs[-1].message++ def test_missing_app_fails_visibly(self, app):+ from app.services.deployment_job_service import DeploymentJobService+ from app.models.deployment_job import DeploymentJob+ with app.app_context():+ job = _make_job(app_id=99999) # no such application+ result = DeploymentJobService.run_job(job.id)+ assert result['success'] is False+ refreshed = DeploymentJob.query.get(job.id)+ assert refreshed.status == 'failed'+ assert 'not found' in (refreshed.error_message or '').lower()+++class TestDeployAppUnifiedHandler:+ def test_register_jobs_adds_handler(self, app):+ from app.services.deployment_job_service import DeploymentJobService, APP_JOB_KIND+ with app.app_context():+ DeploymentJobService.register_jobs()+ assert APP_JOB_KIND == 'deploy.app'+ assert registry.is_registered('deploy.app')+ assert registry.is_registered('deploy.install')++ def test_handler_success(self, app, monkeypatch):+ from app.services.deployment_job_service import DeploymentJobService++ monkeypatch.setattr(DeploymentJobService, 'run_job',+ staticmethod(lambda job_id: {'success': True, 'app_id': 7}))+ with app.app_context():+ DeploymentJobService.register_jobs()+ unified = JobService.enqueue('deploy.app', {'deployment_job_id': 'dep-1'},+ max_attempts=1)+ _drain_once()++ refreshed = Job.query.get(unified.id)+ assert refreshed.status == Job.STATUS_SUCCEEDED+ assert refreshed.get_result()['app_id'] == 7++ def test_handler_failure_raises_and_marks_unified_failed(self, app, monkeypatch):+ from app.services.deployment_job_service import DeploymentJobService++ monkeypatch.setattr(DeploymentJobService, 'run_job',+ staticmethod(lambda job_id: {'success': False, 'error': 'build boom'}))+ with app.app_context():+ DeploymentJobService.register_jobs()+ unified = JobService.enqueue('deploy.app', {'deployment_job_id': 'dep-2'},+ max_attempts=1)+ _drain_once()++ refreshed = Job.query.get(unified.id)+ assert refreshed.status == Job.STATUS_FAILED+ assert 'build boom' in (refreshed.error_message or '')+++class TestFromRepositoryDeployWiring:+ """POST /apps/from-repository must hand the new service to the deploy+ pipeline and surface the job id (and must still succeed when it can't)."""++ def _mock_create_stack(self, monkeypatch, enqueue_result=None, enqueue_exc=None):+ from app.services.git_service import GitService+ from app.services.build_service import BuildService+ from app.services.repository_manifest_service import RepositoryManifestService+ from app.services.manifest_persistence_service import ManifestPersistenceService+ from app.services.deployment_job_service import DeploymentJobService++ monkeypatch.setattr(GitService, 'clone_repository',+ classmethod(lambda cls, *a, **kw: {'success': True}))+ monkeypatch.setattr(RepositoryManifestService, 'analyze_path',+ classmethod(lambda cls, *a, **kw: {+ 'recommended': {}, 'strategy': None, 'manifests': []}))+ monkeypatch.setattr(BuildService, 'detect_build_method',+ classmethod(lambda cls, *a, **kw: {+ 'build_method': 'dockerfile', 'has_dockerfile': True,+ 'has_docker_compose': False, 'language': 'python',+ 'framework': 'flask', 'detected_files': ['Dockerfile']}))+ monkeypatch.setattr(GitService, 'configure_deployment',+ classmethod(lambda cls, *a, **kw: {+ 'success': True, 'webhook_url': 'http://panel/hooks/1'}))+ monkeypatch.setattr(BuildService, 'configure_build',+ classmethod(lambda cls, *a, **kw: {+ 'success': True, 'config': {'build_method': 'dockerfile'}}))+ monkeypatch.setattr(ManifestPersistenceService, 'apply_import',+ classmethod(lambda cls, *a, **kw: None))++ def fake_enqueue(cls, app, user_id=None, trigger='install'):+ if enqueue_exc:+ raise enqueue_exc+ return enqueue_result++ monkeypatch.setattr(DeploymentJobService, 'enqueue_app_deploy',+ classmethod(fake_enqueue))++ def test_response_contains_deploy_job_id(self, app, client, auth_headers, monkeypatch):+ self._mock_create_stack(monkeypatch, enqueue_result={'success': True, 'job_id': 'dj-123'})+ res = client.post('/api/v1/apps/from-repository', headers=auth_headers, json={+ 'name': 'repo-svc', 'repo_url': 'https://github.com/acme/repo-svc.git',+ })+ assert res.status_code == 201+ body = res.get_json()+ assert body['deploy_job_id'] == 'dj-123'+ assert body['app']['name'] == 'repo-svc'++ def test_enqueue_failure_does_not_fail_creation(self, app, client, auth_headers, monkeypatch):+ self._mock_create_stack(monkeypatch, enqueue_exc=RuntimeError('queue bus down'))+ res = client.post('/api/v1/apps/from-repository', headers=auth_headers, json={+ 'name': 'repo-svc2', 'repo_url': 'https://github.com/acme/repo-svc2.git',+ })+ assert res.status_code == 201+ assert res.get_json()['deploy_job_id'] is None+++class TestListJobsAppIdFilter:+ def test_service_filter(self, app):+ from app.services.deployment_job_service import DeploymentJobService+ with app.app_context():+ j1 = _make_job(app_id=1)+ j2 = _make_job(app_id=2)+ j3 = _make_job(app_id=None, kind='template_install')++ filtered = DeploymentJobService.list_jobs(app_id=1)+ assert [j['id'] for j in filtered] == [j1.id]++ everything = DeploymentJobService.list_jobs()+ assert {j['id'] for j in everything} == {j1.id, j2.id, j3.id}++ def test_api_filter(self, app, client, auth_headers):+ with app.app_context():+ j1 = _make_job(app_id=11)+ _make_job(app_id=22)+ j1_id = j1.id+ res = client.get('/api/v1/deployment-jobs?app_id=11', headers=auth_headers)+ assert res.status_code == 200+ jobs = res.get_json()['jobs']+ assert [j['id'] for j in jobs] == [j1_id]+ assert jobs[0]['app_id'] == 11diff --git a/backend/tests/test_app_resource_limits.py b/backend/tests/test_app_resource_limits.pyindex e5346de2..ab70994c 100644--- a/backend/tests/test_app_resource_limits.py+++ b/backend/tests/test_app_resource_limits.py@@ -150,13 +150,18 @@ def test_compose_override_carries_limits_on_primary_service(tmp_path, docker_appweb = override['services']['web'] # primary (first-declared) serviceassert web['cpus'] == 2.0assert web['mem_limit'] == '1g'- assert 'db' not in override['services'] # secondary services untouched+ db_block = override['services']['db'] # secondary: no limits…+ assert 'cpus' not in db_block and 'mem_limit' not in db_block+ assert db_block['restart'] == 'unless-stopped' # …but restart policy defaultdef test_compose_override_removed_when_no_env_and_no_limits(tmp_path, docker_app, monkeypatch):project = tmp_path / 'proj'project.mkdir()- (project / 'docker-compose.yml').write_text('services:\n web:\n image: nginx:latest\n')+ # The service sets its own restart policy, so with no env and no limits+ # there is nothing for the override to carry.+ (project / 'docker-compose.yml').write_text(+ 'services:\n web:\n image: nginx:latest\n restart: always\n')docker_app.root_path = str(project)db.session.commit()diff --git a/backend/tests/test_compose_env_overlay.py b/backend/tests/test_compose_env_overlay.pyindex 93dfcf86..596a73fc 100644--- a/backend/tests/test_compose_env_overlay.py+++ b/backend/tests/test_compose_env_overlay.py@@ -132,7 +132,12 @@ def test_dollar_signs_are_escaped(app, tmp_path):def test_no_env_removes_stale_override(app, tmp_path):from app.services.compose_env_service import ComposeEnvServicewith app.app_context():- _make_compose_app(tmp_path, workspace_id=1) # app with no env vars+ a = _make_compose_app(tmp_path, workspace_id=1) # app with no env vars+ # Every service already sets its own restart policy and there is no env+ # to inject → nothing for the override to carry.+ with open(os.path.join(str(tmp_path), 'docker-compose.yml'), 'w', encoding='utf-8') as f:+ f.write("services:\n web:\n image: nginx:latest\n restart: always\n"+ " db:\n image: postgres:16\n restart: \"no\"\n")stale = ComposeEnvService.override_path(str(tmp_path))with open(stale, 'w', encoding='utf-8') as f:f.write('services: {}\n')@@ -141,6 +146,25 @@ def test_no_env_removes_stale_override(app, tmp_path):assert not os.path.exists(stale) # stale override cleaned up+def test_restart_policy_injected_for_services_without_one(app, tmp_path):+ from app.services.compose_env_service import ComposeEnvService+ with app.app_context():+ _make_compose_app(tmp_path, workspace_id=1) # no env vars at all+ # Base compose: web has no restart policy, db opts out explicitly.+ with open(os.path.join(str(tmp_path), 'docker-compose.yml'), 'w', encoding='utf-8') as f:+ f.write("services:\n web:\n image: nginx:latest\n"+ " db:\n image: postgres:16\n restart: \"no\"\n")++ path = ComposeEnvService.refresh_for_project(str(tmp_path))+ assert path and os.path.exists(path)+ with open(path, encoding='utf-8') as f:+ data = yaml.safe_load(f)++ assert data['services']['web']['restart'] == 'unless-stopped'+ # Explicit policy respected — nothing else to inject for db.+ assert 'db' not in data['services']++def test_non_app_dir_is_untouched(app, tmp_path):from app.services.compose_env_service import ComposeEnvServicewith app.app_context():diff --git a/frontend/src/components/DeploymentJobProgress.jsx b/frontend/src/components/DeploymentJobProgress.jsxnew file mode 100644index 00000000..0ea72bad--- /dev/null+++ b/frontend/src/components/DeploymentJobProgress.jsx@@ -0,0 +1,120 @@+import { useEffect, useRef, useState } from 'react';+import api from '../services/api';++// Give up after this many consecutive failed polls — a transient network blip+// shouldn't kill the watcher, but a permanently unreachable job must not spin+// forever.+const MAX_CONSECUTIVE_POLL_ERRORS = 5;++// Shared "watch it come up live" panel: polls a DeploymentJob and renders its+// status, progress bar, current step and log output. Used by the Templates+// install modal and the service Logs tab so every deploy flow behaves the same.+//+// Terminal handling:+// - status 'succeeded' -> onSuccess(job)+// - status 'failed' -> onFailure(job.error_message)+// - too many poll errors-> onFailure(last poll error)+// - timeoutMs elapsed -> onFailure('timed out' message)+export default function DeploymentJobProgress({+ jobId,+ onSuccess,+ onFailure,+ pollInterval = 1500,+ timeoutMs = 600000,+}) {+ const [job, setJob] = useState(null);+ const [pollError, setPollError] = useState(null); // { message, attempts }+ // Keep callbacks in refs so a re-rendering parent doesn't restart polling.+ const onSuccessRef = useRef(onSuccess);+ const onFailureRef = useRef(onFailure);+ onSuccessRef.current = onSuccess;+ onFailureRef.current = onFailure;++ useEffect(() => {+ if (!jobId) return undefined;+ let stopped = false;+ let consecutiveErrors = 0;+ let intervalId = null;+ let timeoutId = null;++ const finish = (cb, arg) => {+ if (stopped) return;+ stopped = true;+ if (intervalId) clearInterval(intervalId);+ if (timeoutId) clearTimeout(timeoutId);+ cb(arg);+ };++ async function poll() {+ try {+ const data = await api.getDeploymentJob(jobId, true);+ if (stopped) return;+ consecutiveErrors = 0;+ setPollError(null);+ const latest = data.job;+ setJob(latest);+ if (latest.status === 'succeeded') {+ finish(onSuccessRef.current, latest);+ } else if (latest.status === 'failed') {+ finish(onFailureRef.current, latest.error_message || 'Deployment failed');+ }+ } catch (err) {+ if (stopped) return;+ consecutiveErrors += 1;+ const message = err?.data?.error || err?.message || 'Failed to poll deployment status';+ if (consecutiveErrors >= MAX_CONSECUTIVE_POLL_ERRORS) {+ finish(onFailureRef.current, `Lost contact with the deployment job: ${message}`);+ } else {+ setPollError({ message, attempts: consecutiveErrors });+ }+ }+ }++ poll();+ intervalId = setInterval(poll, pollInterval);+ timeoutId = setTimeout(() => {+ const minutes = Math.round(timeoutMs / 60000);+ finish(onFailureRef.current, `Deployment timed out after ${minutes} minutes without reaching a final state`);+ }, timeoutMs);++ return () => {+ stopped = true;+ if (intervalId) clearInterval(intervalId);+ if (timeoutId) clearTimeout(timeoutId);+ };+ }, [jobId, pollInterval, timeoutMs]);++ const status = job?.status || 'pending';+ const progress = job?.progress_percent ?? 0;+ const logs = job?.logs || [];++ return (+ <div className="deployment-job-progress">+ <div className="deployment-progress">+ <div className="deployment-progress-track">+ <div+ className="deployment-progress-fill"+ style={{ width: `${progress}%` }}+ />+ </div>+ <span>{status} {progress}%</span>+ </div>+ {job?.current_step_name && (+ <p className="deployment-job-progress__step text-muted">+ Current step: {job.current_step_name}+ </p>+ )}+ {pollError && (+ <div className="alert alert-warning">+ Trouble reaching the deployment job (attempt {pollError.attempts}/{MAX_CONSECUTIVE_POLL_ERRORS}): {pollError.message}. Retrying…+ </div>+ )}+ <pre className="log-viewer">+ {logs.map(log => {+ const prefix = log.step_index ? `[${log.step_index}] ` : '';+ return `${prefix}${log.message}`;+ }).join('\n') || 'Waiting for deployment logs...'}+ </pre>+ </div>+ );+}diff --git a/frontend/src/components/service-detail/LogsTab.jsx b/frontend/src/components/service-detail/LogsTab.jsxindex 00465e6e..75616ae3 100644--- a/frontend/src/components/service-detail/LogsTab.jsx+++ b/frontend/src/components/service-detail/LogsTab.jsx@@ -1,6 +1,9 @@import { useState, useEffect, useRef, useMemo } from 'react';+import { useSearchParams } from 'react-router-dom';import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';import { useLogsDrawer } from '../../contexts/LogsDrawerContext';+import DeploymentJobProgress from '../DeploymentJobProgress';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Switch } from '@/components/ui/switch';@@ -9,6 +12,8 @@ const LOG_LEVELS = ['all', 'error', 'warn', 'info', 'debug'];const LogsTab = ({ app }) => {const { openDrawer } = useLogsDrawer();+ const toast = useToast();+ const [searchParams, setSearchParams] = useSearchParams();const [rawLogs, setRawLogs] = useState('');const [loading, setLoading] = useState(true);const [autoRefresh, setAutoRefresh] = useState(false);@@ -17,6 +22,11 @@ const LogsTab = ({ app }) => {const [lineCount, setLineCount] = useState(200);const [autoScroll, setAutoScroll] = useState(true);const logRef = useRef(null);+ // Live deploy tracking: seeded from the ?deploy_job=<id> query param+ // (set by the new-service wizard / template install), or discovered below+ // when a deploy is already pending/running for this app.+ const [deployJobId, setDeployJobId] = useState(() => searchParams.get('deploy_job'));+ const [deployError, setDeployError] = useState(null);const isDockerApp = app.app_type === 'docker';const isPythonApp = ['flask', 'django'].includes(app.app_type);@@ -25,6 +35,24 @@ const LogsTab = ({ app }) => {loadLogs();}, [app.id, lineCount]);+ // No explicit ?deploy_job= param — check whether a deployment job is+ // currently pending/running for this app so a mid-deploy visit to the+ // Logs tab still shows live progress.+ useEffect(() => {+ if (deployJobId || !app?.id) return undefined;+ let cancelled = false;+ api.getDeploymentJobs({ appId: app.id, limit: 5 })+ .then((data) => {+ if (cancelled) return;+ const active = (data.jobs || []).find(+ (j) => j.status === 'pending' || j.status === 'running'+ );+ if (active) setDeployJobId(active.id);+ })+ .catch(() => { /* non-fatal: container logs still work without it */ });+ return () => { cancelled = true; };+ }, [app?.id, deployJobId]);+useEffect(() => {if (!autoRefresh) return;const interval = setInterval(loadLogs, 5000);@@ -56,6 +84,27 @@ const LogsTab = ({ app }) => {}}+ function handleDeploySuccess() {+ setDeployJobId(null);+ setDeployError(null);+ // Drop the one-shot ?deploy_job= param so a refresh doesn't rewatch+ // a finished job.+ if (searchParams.has('deploy_job')) {+ const next = new URLSearchParams(searchParams);+ next.delete('deploy_job');+ setSearchParams(next, { replace: true });+ }+ toast.success('Deployment finished successfully');+ loadLogs();+ }++ function handleDeployFailure(message) {+ const reason = message || 'Deployment failed';+ setDeployJobId(null);+ setDeployError(reason);+ toast.error(reason);+ }+const filteredLines = useMemo(() => {if (!rawLogs) return [];let lines = rawLogs.split('\n');@@ -105,6 +154,23 @@ const LogsTab = ({ app }) => {return (<div className="logs-tab-v2">+ {/* Live deploy progress (from repo create / template install) */}+ {deployJobId && (+ <div className="deploy-job-banner">+ <h4 className="deploy-job-banner__title">Deploying this service</h4>+ <DeploymentJobProgress+ jobId={deployJobId}+ onSuccess={handleDeploySuccess}+ onFailure={handleDeployFailure}+ />+ </div>+ )}+ {deployError && (+ <div className="alert alert-danger">+ <strong>Deployment failed:</strong> {deployError}+ </div>+ )}+{/* Toolbar */}<div className="logs-toolbar"><div className="logs-toolbar__left">diff --git a/frontend/src/pages/ServiceDetail.jsx b/frontend/src/pages/ServiceDetail.jsxindex b116e7f7..b4871e65 100644--- a/frontend/src/pages/ServiceDetail.jsx+++ b/frontend/src/pages/ServiceDetail.jsx@@ -144,7 +144,7 @@ const ServiceDetail = () => {await performAction(action);toast.success(`Service ${action}ed successfully`);} catch (err) {- toast.error(`Failed to ${action} service`);+ toast.error(err?.data?.error || err?.message || `Failed to ${action} service`);} finally {setActionLoading(null);setShowDeployMenu(false);@@ -228,7 +228,7 @@ const ServiceDetail = () => {await deleteService();navigate('/services');} catch (err) {- toast.error('Failed to delete service');+ toast.error(err?.data?.error || err?.message || 'Failed to delete service');setActionLoading(null);}}diff --git a/frontend/src/pages/Templates.jsx b/frontend/src/pages/Templates.jsxindex 317fe0e1..3099d917 100644--- a/frontend/src/pages/Templates.jsx+++ b/frontend/src/pages/Templates.jsx@@ -1,4 +1,4 @@-import { useState, useEffect, useRef } from 'react';+import { useState, useEffect } from 'react';import { useNavigate, useSearchParams } from 'react-router-dom';import {Search, X, Star, ExternalLink, BookOpen, Container, Globe, BarChart3,@@ -18,6 +18,7 @@ import {} from '@/components/ds';import { useTopbarActions } from '@/hooks/useTopbarActions';import EmptyState from '../components/EmptyState';+import DeploymentJobProgress from '../components/DeploymentJobProgress';// Featured templates (curated list)const FEATURED_TEMPLATES = [@@ -832,7 +833,7 @@ const Templates = () => {setShowInstallModal(false);setSelectedTemplate(null);toast.success('Application installed successfully!');- navigate(`/apps/${appId}`);+ navigate(`/services/${appId}/logs`);}}/>)}@@ -940,9 +941,7 @@ const InstallModal = ({ template, onClose, onSuccess }) => {const [selectedServerId, setSelectedServerId] = useState('local');const [installing, setInstalling] = useState(false);const [errors, setErrors] = useState([]);- const [job, setJob] = useState(null);- const [jobLogs, setJobLogs] = useState([]);- const pollRef = useRef(null);+ const [jobId, setJobId] = useState(null);useEffect(() => {// Initialize variables with defaults@@ -957,11 +956,6 @@ const InstallModal = ({ template, onClose, onSuccess }) => {useEffect(() => {loadServers();- return () => {- if (pollRef.current) {- clearInterval(pollRef.current);- }- };}, []);async function loadServers() {@@ -978,42 +972,22 @@ const InstallModal = ({ template, onClose, onSuccess }) => {}}- function startPolling(jobId) {- if (pollRef.current) {- clearInterval(pollRef.current);- }+ function handleJobSuccess(latestJob) {+ setInstalling(false);+ onSuccess(latestJob.result?.app_id || latestJob.app_id);+ }- pollRef.current = setInterval(async () => {- try {- const data = await api.getDeploymentJob(jobId, true);- const latestJob = data.job;- setJob(latestJob);- setJobLogs(latestJob.logs || []);-- if (latestJob.status === 'succeeded' && latestJob.result?.app_id) {- clearInterval(pollRef.current);- pollRef.current = null;- setInstalling(false);- onSuccess(latestJob.result?.app_id);- } else if (latestJob.status === 'failed') {- clearInterval(pollRef.current);- pollRef.current = null;- setInstalling(false);- setErrors([latestJob.error_message || 'Deployment failed']);- toast.error(latestJob.error_message || 'Deployment failed');- }- } catch (err) {- console.error('Failed to poll deployment job:', err);- }- }, 1500);+ function handleJobFailure(message) {+ setInstalling(false);+ setErrors([message]);+ toast.error(message);}async function handleInstall(e) {e.preventDefault();setInstalling(true);setErrors([]);- setJob(null);- setJobLogs([]);+ setJobId(null);try {// Validate first@@ -1029,17 +1003,16 @@ const InstallModal = ({ template, onClose, onSuccess }) => {serverId: selectedServerId});if (result.success && result.job_id) {- setJob(result.job);- setJobLogs(result.job?.logs || []);- startPolling(result.job_id);+ setJobId(result.job_id);} else if (result.success) {+ setInstalling(false);onSuccess(result.app_id);} else {setErrors([result.error || 'Installation failed']);setInstalling(false);}} catch (err) {- setErrors([err.message || 'Installation failed']);+ setErrors([err?.data?.error || err.message || 'Installation failed']);setInstalling(false);}}@@ -1129,24 +1102,14 @@ const InstallModal = ({ template, onClose, onSuccess }) => {</>)}- {job && (+ {jobId && (<div className="detail-section"><h4>Deployment Status</h4>- <div className="deployment-progress">- <div className="deployment-progress-track">- <div- className="deployment-progress-fill"- style={{ width: `${job.progress_percent || 0}%` }}- />- </div>- <span>{job.status} {job.progress_percent || 0}%</span>- </div>- <pre className="log-viewer">- {(jobLogs || []).map(log => {- const prefix = log.step_index ? `[${log.step_index}] ` : '';- return `${prefix}${log.message}`;- }).join('\n') || 'Waiting for deployment logs...'}- </pre>+ <DeploymentJobProgress+ jobId={jobId}+ onSuccess={handleJobSuccess}+ onFailure={handleJobFailure}+ /></div>)}</div>diff --git a/frontend/src/pages/new-service/useNewServiceForm.js b/frontend/src/pages/new-service/useNewServiceForm.jsindex d8d2d760..59d6b5ac 100644--- a/frontend/src/pages/new-service/useNewServiceForm.js+++ b/frontend/src/pages/new-service/useNewServiceForm.js@@ -536,8 +536,16 @@ export function useNewServiceForm() {}const result = await api.createAppFromRepository(payload);- toast.success('Repository service created');- navigate(`/services/${result.app.id}`);+ if (result.deploy_job_id) {+ // A deploy job was queued — take the user straight to the+ // Logs tab so they can watch the build/startup live.+ toast.success('Repository service created — deploying…');+ navigate(`/services/${result.app.id}/logs?deploy_job=${encodeURIComponent(result.deploy_job_id)}`);+ } else {+ toast.success('Repository service created');+ toast.warning('Service was created without auto-deploy — start it manually from the service page.');+ navigate(`/services/${result.app.id}`);+ }}} catch (err) {toast.error(err.message || 'Failed to create service');diff --git a/frontend/src/services/api/deploymentJobs.js b/frontend/src/services/api/deploymentJobs.jsindex 97e6fd87..b81cc845 100644--- a/frontend/src/services/api/deploymentJobs.js+++ b/frontend/src/services/api/deploymentJobs.js@@ -3,6 +3,7 @@export async function getDeploymentJobs(params = {}) {const query = new URLSearchParams();if (params.status) query.append('status', params.status);+ if (params.appId) query.append('app_id', params.appId);if (params.serverId) query.append('server_id', params.serverId);if (params.limit) query.append('limit', params.limit);const suffix = query.toString() ? `?${query}` : '';diff --git a/frontend/src/styles/pages/_service-detail.scss b/frontend/src/styles/pages/_service-detail.scssindex c3453c6c..1f09f7dd 100644--- a/frontend/src/styles/pages/_service-detail.scss+++ b/frontend/src/styles/pages/_service-detail.scss@@ -1331,6 +1331,22 @@ h3.svc-eyebrow {gap: 0;}+// Live deploy progress shown above the container logs when a DeploymentJob+// is active for the app (repo create, template install, redeploy).+.deploy-job-banner {+ margin-bottom: $space-4;+ padding: $space-4;+ background: var(--surface);+ border: 1px solid var(--border-soft);+ border-radius: var(--radius);++ &__title {+ margin: 0 0 $space-3 0;+ font-size: $font-size-base;+ font-weight: $font-weight-semibold;+ }+}+.logs-toolbar {display: flex;justify-content: space-between;