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
test(automations): tramo extension suite + host/model refinements
Juan Denis79be6e082d98
diff --git a/backend/tests/test_tramo_extension.py b/backend/tests/test_tramo_extension.pynew file mode 100644index 00000000..e60661f5--- /dev/null+++ b/backend/tests/test_tramo_extension.py@@ -0,0 +1,604 @@+"""serverkit-tramo (Automations) extension tests.++Loads the builtin the way production does: ``plugin_service.+_ensure_builtin_backend_importable`` registers ``builtin-extensions/+serverkit-tramo/backend`` as the dashed package ``app.plugins.serverkit-tramo``.+The models module is imported at module top so its ``ext_serverkit_tramo_*``+tables register on ``db.metadata`` before the ``app`` fixture runs+``db.create_all()``.++Docker and the tramo HTTP API are mocked at the two service choke-points+(``TramoHostService._docker`` / ``._api``) so nothing shells out or talks HTTP.+Cross-platform: tests that exercise the ``os.name == 'nt'`` gate force it+explicitly so they behave the same on the Windows dev box and Linux CI.++Also covers plan 45 Phase 4: the retired ``/api/v1/workflows`` routes are gone,+the four ported event emitters reach EventService, ``app.stopped`` is no longer+double-emitted by docker_service, and the admin-only legacy export.+"""+import importlib+import json+import os+from types import SimpleNamespace++import pytest++from app.services import plugin_service++SLUG = 'serverkit-tramo'+EXT_DIR = os.path.join(+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),+ 'builtin-extensions', SLUG,+)+++def _load_ext():+ assert plugin_service._ensure_builtin_backend_importable(SLUG), (+ f'builtin extension backend not importable from {EXT_DIR}')+ mods = {}+ for name in ('models', 'host_service', 'workflow_store', 'events_bridge',+ 'run_sync', 'jobs', 'templates', 'lifecycle', 'tramo'):+ mods[name] = importlib.import_module(f'app.plugins.{SLUG}.{name}')+ return mods+++_M = _load_ext()+models_mod = _M['models']+host_mod = _M['host_service']+store_mod = _M['workflow_store']+eb_mod = _M['events_bridge']+run_sync_mod = _M['run_sync']+jobs_mod = _M['jobs']+templates_mod = _M['templates']+bp_mod = _M['tramo']++TramoWorkflow = models_mod.TramoWorkflow+TramoRun = models_mod.TramoRun+TramoHostService = host_mod.TramoHostService+WorkflowStore = store_mod.WorkflowStore+++# --------------------------------------------------------------------------- #+# helpers / fixtures+# --------------------------------------------------------------------------- #+def _mk_plugin_row(config=None):+ from app import db+ from app.models.plugin import InstalledPlugin+ row = InstalledPlugin(+ name=SLUG, display_name='Automations', slug=SLUG, version='1.0.0',+ status=InstalledPlugin.STATUS_ACTIVE,+ )+ row.config = config or {}+ db.session.add(row)+ db.session.commit()+ return row+++def _mk_admin():+ from app import db+ from app.models.user import User+ from werkzeug.security import generate_password_hash+ u = User(email='[email protected]', username='tramoadmin',+ password_hash=generate_password_hash('x'),+ role=User.ROLE_ADMIN, is_active=True)+ db.session.add(u)+ db.session.commit()+ return u+++def posix(monkeypatch):+ """Force the Linux path through the host service's Windows gate.++ Patches the ``_is_windows`` seam (never the global ``os.name`` -- that would+ swap ``pathlib`` to ``PosixPath`` and crash on the Windows dev box).+ """+ monkeypatch.setattr(TramoHostService, '_is_windows', classmethod(lambda cls: False))+ return True+++def tramo_client(app):+ if 'tramo' not in app.blueprints:+ app.register_blueprint(bp_mod.tramo_bp, url_prefix='/api/v1/tramo')+ return app.test_client()+++# --------------------------------------------------------------------------- #+# manifest+# --------------------------------------------------------------------------- #+def _manifest():+ with open(os.path.join(EXT_DIR, 'plugin.json'), encoding='utf-8') as f:+ return json.load(f)+++def test_manifest_passes_validator():+ m = _manifest()+ assert plugin_service._validate_manifest(m) is True+ assert m['name'] == SLUG+ assert m['entry_point'] == 'tramo:tramo_bp'+ assert m['url_prefix'] == '/api/v1/tramo'+ assert m['models'] == 'models:register'+ nav = m['contributions']['nav'][0]+ assert nav['route'] == '/automations' and nav['id'] == 'automations'+ assert m['contributions']['page_titles']['/automations'] == 'Automations'+++def test_manifest_permissions_known_and_no_dashes():+ from app.plugins_sdk import permissions as sdk_perms+ m = _manifest()+ assert sdk_perms.unknown_permissions(m['permissions']) == []+ assert '—' not in m['description'] and '–' not in m['description']+++def test_lifecycle_and_job_refs_resolve():+ m = _manifest()+ for ref in m['lifecycle'].values():+ module_name, func_name = ref.split(':')+ mod = importlib.import_module(f'app.plugins.{SLUG}.{module_name}')+ assert callable(getattr(mod, func_name, None)), ref+ for job in m['jobs']:+ module_name, func_name = job['handler'].split(':')+ mod = importlib.import_module(f'app.plugins.{SLUG}.{module_name}')+ assert callable(getattr(mod, func_name, None)), job['handler']+++def test_entry_point_resolves_to_blueprint():+ assert getattr(bp_mod, 'tramo_bp', None) is not None+ assert bp_mod.tramo_bp.name == 'tramo'+++# --------------------------------------------------------------------------- #+# models + purge+# --------------------------------------------------------------------------- #+def test_models_register_and_tables_exist(app):+ from app import db+ from sqlalchemy import inspect+ assert set(models_mod.register(db)) == {TramoWorkflow, TramoRun}+ tables = [t for t in inspect(db.engine).get_table_names()+ if t.startswith('ext_serverkit_tramo')]+ assert 'ext_serverkit_tramo_workflows' in tables+ assert 'ext_serverkit_tramo_runs' in tables+++def test_purge_drops_only_prefixed_tables(app):+ from app import db+ from app.services import extension_lifecycle+ from sqlalchemy import inspect+ plugin = SimpleNamespace(slug=SLUG)+ dropped = extension_lifecycle.purge_models(plugin)+ assert dropped >= 2+ remaining = [t for t in inspect(db.engine).get_table_names()+ if t.startswith('ext_serverkit_tramo')]+ assert remaining == []+ # A core table must survive.+ assert 'users' in inspect(db.engine).get_table_names()+ db.create_all() # restore for later tests in this module+++# --------------------------------------------------------------------------- #+# workflow store CRUD + slug + materialize + deploy+# --------------------------------------------------------------------------- #+def test_create_slugifies_and_uniquifies(app):+ a = WorkflowStore.create('My Flow!')+ b = WorkflowStore.create('My Flow!')+ assert a.slug == 'my-flow'+ assert b.slug == 'my-flow-2'+ assert a.get_doc().get('nodes') == []+++def test_create_rejects_blank_name(app):+ with pytest.raises(ValueError):+ WorkflowStore.create(' ')+++def test_update_bumps_doc_version_and_dirty(app):+ wf = WorkflowStore.create('flow')+ assert wf.doc_version == 1+ WorkflowStore.update(wf.slug, doc={'nodes': [{'id': 'n1'}], 'edges': []})+ assert wf.doc_version == 2+ # Never deployed + enabled => dirty.+ assert wf.is_dirty() is True+++def test_delete_removes_row(app):+ wf = WorkflowStore.create('gone')+ WorkflowStore.delete(wf.slug)+ assert WorkflowStore.get('gone') is None+++def test_materialize_writes_only_enabled(app, monkeypatch, posix):+ on = WorkflowStore.create('on-flow', enabled=True)+ WorkflowStore.create('off-flow', enabled=False)+ written = {}+ removed = []+ monkeypatch.setattr(WorkflowStore, '_write_file',+ classmethod(lambda cls, slug, doc: written.__setitem__(slug, doc)))+ monkeypatch.setattr(WorkflowStore, '_list_files',+ classmethod(lambda cls: ['on-flow', 'stale-flow']))+ monkeypatch.setattr(WorkflowStore, '_remove_file',+ classmethod(lambda cls, slug: removed.append(slug)))+ summary = WorkflowStore.materialize()+ assert summary['written'] == ['on-flow']+ assert 'on-flow' in written and 'off-flow' not in written+ # stale + disabled files pruned.+ assert 'stale-flow' in removed+++def test_deploy_stamps_deployed_at(app, monkeypatch, posix):+ wf = WorkflowStore.create('dep')+ monkeypatch.setattr(TramoHostService, 'is_installed', classmethod(lambda cls: True))+ monkeypatch.setattr(WorkflowStore, 'materialize',+ classmethod(lambda cls: {'written': ['dep'], 'pruned': []}))+ monkeypatch.setattr(TramoHostService, 'control',+ classmethod(lambda cls, action: {'success': True}))+ res = WorkflowStore.deploy()+ assert res['success'] is True+ assert wf.deployed_at is not None+ assert wf.is_dirty() is False+++def test_deploy_requires_installed_engine(app, monkeypatch):+ monkeypatch.setattr(TramoHostService, 'is_installed', classmethod(lambda cls: False))+ res = WorkflowStore.deploy()+ assert res['success'] is False+ assert 'not installed' in res['error']+++# --------------------------------------------------------------------------- #+# host service: argv, control, status, nt guard+# --------------------------------------------------------------------------- #+def test_build_run_args_argv(app):+ argv = TramoHostService._build_run_args(8377, 'SECRETKEY', callback_api_key='CBKEY')+ joined = ' '.join(argv)+ assert argv[0] == 'run' and '-d' in argv+ assert '127.0.0.1:8377:3000' in argv # loopback publish only+ assert f'{host_mod.HOST_WORKFLOWS_DIR}:/workflows' in argv+ assert f'{host_mod.HOST_STATE_DIR}:/state' in argv+ assert 'TRAMO_API_KEY=SECRETKEY' in argv+ assert 'TRAMO_PACKS=all' in argv+ assert 'SERVERKIT_API_KEY=CBKEY' in argv+ assert any(a.startswith('SERVERKIT_URL=') for a in argv)+ assert 'host.docker.internal:host-gateway' in argv+ assert argv[-1] == host_mod.IMAGE+ assert 'ghcr.io/jhd3197/tramo-server:0.1.1' == host_mod.IMAGE+++def test_build_run_args_includes_pack_secrets(app, monkeypatch):+ _mk_plugin_row()+ TramoHostService.set_pack_secrets({'TELEGRAM_BOT_TOKEN': 'abc123'})+ argv = TramoHostService._build_run_args(8377, 'KEY')+ assert 'TELEGRAM_BOT_TOKEN=abc123' in argv+++def test_pack_secrets_round_trip_encrypted(app):+ _mk_plugin_row()+ TramoHostService.set_pack_secrets({'GMAIL_OAUTH_TOKEN': 'tok'})+ # Stored value must not be the plaintext (when encryption is configured).+ from app.utils.crypto import is_encryption_configured+ raw = TramoHostService._config().get('pack_secrets', {}).get('GMAIL_OAUTH_TOKEN')+ if is_encryption_configured():+ assert raw != 'tok'+ assert TramoHostService.get_pack_secrets()['GMAIL_OAUTH_TOKEN'] == 'tok'+++def test_set_pack_secret_empty_value_deletes(app):+ _mk_plugin_row()+ TramoHostService.set_pack_secrets({'X_TOKEN': 'v'})+ names = TramoHostService.set_pack_secrets({'X_TOKEN': ''})+ assert 'X_TOKEN' not in names+++def test_control_maps_actions(app, monkeypatch, posix):+ calls = []+ monkeypatch.setattr(TramoHostService, 'is_installed', classmethod(lambda cls: True))+ monkeypatch.setattr(TramoHostService, '_docker',+ classmethod(lambda cls, args, **kw: calls.append(args) or {'success': True}))+ for action in ('start', 'stop', 'restart'):+ res = TramoHostService.control(action)+ assert res['success'] and res['action'] == action+ assert calls[0] == ['start', host_mod.CONTAINER_NAME]+ assert calls[2] == ['restart', host_mod.CONTAINER_NAME]+++def test_control_rejects_bad_action(app):+ assert TramoHostService.control('nuke')['success'] is False+++def test_status_states(app, monkeypatch, posix):+ # not installed+ monkeypatch.setattr(TramoHostService, '_docker',+ classmethod(lambda cls, args, **kw: {'success': False}))+ assert TramoHostService.get_status()['state'] == 'not_installed'++ # stopped+ monkeypatch.setattr(TramoHostService, '_docker',+ classmethod(lambda cls, args, **kw: {'success': True, 'stdout': 'false'}))+ assert TramoHostService.get_status()['state'] == 'stopped'++ # running + unhealthy+ monkeypatch.setattr(TramoHostService, '_docker',+ classmethod(lambda cls, args, **kw: {'success': True, 'stdout': 'true'}))+ monkeypatch.setattr(TramoHostService, '_api',+ classmethod(lambda cls, m, p, payload=None, timeout=None: {'success': False, 'error': 'x'}))+ assert TramoHostService.get_status()['state'] == 'unhealthy'++ # running + ready+ monkeypatch.setattr(TramoHostService, '_api',+ classmethod(lambda cls, m, p, payload=None, timeout=None: {'success': True, 'data': {'version': '0.1.1'}}))+ st = TramoHostService.get_status()+ assert st['state'] == 'ready' and st['healthy'] is True+++def test_nt_guard_returns_graceful_error(app, monkeypatch):+ monkeypatch.setattr(TramoHostService, '_is_windows', classmethod(lambda cls: True))+ assert TramoHostService.is_installed() is False+ d = TramoHostService._docker(['ps'])+ assert d['success'] is False and 'Windows' in d['error']+ st = TramoHostService.get_status()+ assert st['state'] == 'not_installed'+ inst = TramoHostService.install()+ assert inst['success'] is False and 'Windows' in inst['error']+++# --------------------------------------------------------------------------- #+# run_sync+# --------------------------------------------------------------------------- #+def test_upsert_run_inserts_then_updates(app):+ row1, new1 = run_sync_mod.upsert_run({'id': 'r1', 'status': 'running',+ 'workflowId': 'flow-a'})+ assert new1 is True and row1.status == 'running'+ row2, new2 = run_sync_mod.upsert_run({'id': 'r1', 'status': 'success'})+ assert new2 is False and row2.status == 'success'+ assert TramoRun.query.filter_by(run_id='r1').count() == 1+++def test_upsert_run_ignores_missing_id(app):+ row, new = run_sync_mod.upsert_run({'status': 'success'})+ assert row is None and new is False+++# --------------------------------------------------------------------------- #+# jobs+# --------------------------------------------------------------------------- #+def test_harvest_upserts_and_notifies_once(app, monkeypatch):+ monkeypatch.setattr(TramoHostService, 'is_installed', classmethod(lambda cls: True))+ runs = [{'id': 'a', 'status': 'success'}, {'id': 'b', 'status': 'failed'}]+ monkeypatch.setattr(TramoHostService, '_api',+ classmethod(lambda cls, m, p, payload=None, timeout=None: {'success': True, 'data': runs}))+ sent = []+ monkeypatch.setattr('app.plugins_sdk.notify.send',+ lambda *a, **k: sent.append((a, k)))+ r1 = jobs_mod.harvest_runs(None)+ assert r1['harvested'] == 2 and r1['new_failures'] == 1+ # Second harvest: no new rows, no new failure notifications.+ r2 = jobs_mod.harvest_runs(None)+ assert r2['new_failures'] == 0+ assert len(sent) == 1+ assert TramoRun.query.count() == 2+++def test_health_check_notifies_after_threshold(app, monkeypatch):+ _mk_plugin_row()+ monkeypatch.setattr(TramoHostService, 'is_installed', classmethod(lambda cls: True))+ monkeypatch.setattr(TramoHostService, 'health',+ classmethod(lambda cls: {'success': False, 'error': 'down'}))+ sent = []+ monkeypatch.setattr('app.plugins_sdk.notify.send', lambda *a, **k: sent.append(k))+ jobs_mod.health_check(None) # streak 1: no notify+ assert len(sent) == 0+ jobs_mod.health_check(None) # streak 2: notify+ assert len(sent) == 1+ # Recovery resets the streak.+ monkeypatch.setattr(TramoHostService, 'health',+ classmethod(lambda cls: {'success': True}))+ jobs_mod.health_check(None)+ assert TramoHostService._config().get('health_fail_streak') == 0+++# --------------------------------------------------------------------------- #+# events bridge + call-back key+# --------------------------------------------------------------------------- #+def test_events_bridge_toggle(app):+ _mk_plugin_row()+ _mk_admin()+ from app.models.event_subscription import EventSubscription+ sub_id = eb_mod.enable_events_bridge()+ assert sub_id is not None+ sub = EventSubscription.query.get(sub_id)+ assert sub.get_events() == ['*']+ assert '/sk/events' in sub.url+ assert eb_mod.is_events_bridge_enabled() is True+ # Idempotent.+ assert eb_mod.enable_events_bridge() == sub_id+ # Disable removes it.+ assert eb_mod.disable_events_bridge() is True+ assert EventSubscription.query.get(sub_id) is None+ assert eb_mod.is_events_bridge_enabled() is False+++def test_callback_key_issue_and_revoke(app):+ _mk_plugin_row()+ _mk_admin()+ from app.models.api_key import ApiKey+ raw = eb_mod.issue_callback_key()+ assert raw and raw.startswith('sk_')+ key_id = eb_mod._config().get('callback_key_id')+ key = ApiKey.query.get(key_id)+ assert key.name == 'serverkit-tramo'+ assert 'apps:deploy' in key.get_scopes()+ assert key.is_valid() is True+ eb_mod.revoke_callback_key()+ from app import db+ db.session.refresh(key)+ assert key.is_active is False and key.revoked_at is not None+++def test_uninstall_revokes_key_and_subscription(app, monkeypatch):+ _mk_plugin_row()+ _mk_admin()+ from app.models.api_key import ApiKey+ from app.models.event_subscription import EventSubscription+ eb_mod.issue_callback_key()+ eb_mod.enable_events_bridge()+ key_id = eb_mod._config().get('callback_key_id')+ sub_id = eb_mod._config().get('events_subscription_id')+ # Container teardown is a no-op here (not installed).+ monkeypatch.setattr(TramoHostService, 'is_installed', classmethod(lambda cls: False))+ lifecycle = importlib.import_module(f'app.plugins.{SLUG}.lifecycle')+ lifecycle.on_uninstall(SimpleNamespace(slug=SLUG), purge=False)+ from app import db+ key = ApiKey.query.get(key_id)+ assert key.is_active is False+ assert EventSubscription.query.get(sub_id) is None+++# --------------------------------------------------------------------------- #+# blueprint: auth, run proxy, runs filter, settings mask, hooks passthrough+# --------------------------------------------------------------------------- #+def test_routes_require_auth(tramo_client):+ assert tramo_client.get('/api/v1/tramo/workflows').status_code in (401, 422)+ assert tramo_client.get('/api/v1/tramo/host/status').status_code in (401, 422)+++def test_workflow_crud_via_routes(tramo_client, auth_headers):+ r = tramo_client.post('/api/v1/tramo/workflows', headers=auth_headers,+ json={'name': 'Route Flow'})+ assert r.status_code == 201+ slug = r.get_json()['slug']+ assert tramo_client.get(f'/api/v1/tramo/workflows/{slug}',+ headers=auth_headers).status_code == 200+ lst = tramo_client.get('/api/v1/tramo/workflows', headers=auth_headers).get_json()+ assert any(w['slug'] == slug for w in lst['workflows'])+++def test_run_proxy_persists_row(tramo_client, auth_headers, monkeypatch):+ WorkflowStore.create('runme')+ monkeypatch.setattr(bp_mod.TramoHostService, 'is_installed', classmethod(lambda cls: True))+ monkeypatch.setattr(bp_mod.TramoHostService, '_api',+ classmethod(lambda cls, m, p, payload=None, timeout=None:+ {'success': True, 'data': {'id': 'run-77', 'status': 'success',+ 'workflowId': 'runme'}}))+ r = tramo_client.post('/api/v1/tramo/workflows/runme/run', headers=auth_headers, json={})+ assert r.status_code == 200+ assert r.get_json()['run']['run_id'] == 'run-77'+ assert TramoRun.query.filter_by(run_id='run-77').count() == 1+++def test_runs_list_filters_by_workflow(tramo_client, auth_headers, app):+ run_sync_mod.upsert_run({'id': 'x1', 'status': 'success', 'workflowId': 'flowA'})+ run_sync_mod.upsert_run({'id': 'x2', 'status': 'success', 'workflowId': 'flowB'})+ r = tramo_client.get('/api/v1/tramo/runs?workflow=flowA', headers=auth_headers)+ runs = r.get_json()['runs']+ assert len(runs) == 1 and runs[0]['run_id'] == 'x1'+++def test_settings_masks_secret_values(tramo_client, auth_headers, app):+ _mk_plugin_row()+ tramo_client.put('/api/v1/tramo/settings', headers=auth_headers,+ json={'pack_secrets': {'TELEGRAM_BOT_TOKEN': 'shh'}})+ body = tramo_client.get('/api/v1/tramo/settings', headers=auth_headers).get_json()+ assert 'TELEGRAM_BOT_TOKEN' in body['pack_secret_names']+ # The value must never be echoed anywhere in the settings response.+ assert 'shh' not in json.dumps(body)+++def test_hooks_passthrough_is_auth_exempt_and_forwards(tramo_client, monkeypatch):+ monkeypatch.setattr(bp_mod.TramoHostService, 'is_installed', classmethod(lambda cls: True))+ monkeypatch.setattr(bp_mod.TramoHostService, 'host_port', classmethod(lambda cls: 8377))+ captured = {}++ def fake_request(method, url, **kw):+ captured['method'] = method+ captured['url'] = url+ captured['data'] = kw.get('data')+ return SimpleNamespace(status_code=200, content=b'{"ok":true}',+ headers={'Content-Type': 'application/json'})++ monkeypatch.setattr(bp_mod.requests, 'request', fake_request)+ # NO auth headers -> still reachable (auth-exempt).+ r = tramo_client.post('/api/v1/tramo/hooks/my-trigger', data=b'{"a":1}',+ content_type='application/json')+ assert r.status_code == 200+ assert captured['method'] == 'POST'+ assert captured['url'].endswith('/hooks/my-trigger')+ assert captured['data'] == b'{"a":1}'+++def test_starter_templates_route(tramo_client, auth_headers):+ r = tramo_client.get('/api/v1/tramo/templates', headers=auth_headers)+ ids = [t['id'] for t in r.get_json()['templates']]+ assert 'backup-failed-telegram' in ids+ # Instantiate one.+ c = tramo_client.post('/api/v1/tramo/workflows/from-template/backup-failed-telegram',+ headers=auth_headers, json={})+ assert c.status_code == 201+ assert c.get_json()['doc']['nodes']+++# --------------------------------------------------------------------------- #+# Phase 4: retired engine + ported emitters + legacy export+# --------------------------------------------------------------------------- #+def test_legacy_workflows_route_admin_only(tramo_client, auth_headers, app):+ # Admin gets a (possibly empty) list, never a 500.+ r = tramo_client.get('/api/v1/tramo/legacy-workflows', headers=auth_headers)+ assert r.status_code == 200+ assert 'workflows' in r.get_json()+++def test_old_workflows_routes_are_gone(client, auth_headers):+ # The /api/v1/workflows blueprint was removed in Phase 4.+ r = client.get('/api/v1/workflows', headers=auth_headers)+ assert r.status_code == 404+ # The execute route no longer has a POST handler; the SPA catch-all is+ # GET-only, so an unmatched POST is 404/405 -- either proves it is gone.+ r2 = client.post('/api/v1/workflows/1/execute', headers=auth_headers, json={})+ assert r2.status_code in (404, 405)+++def test_event_catalog_has_ported_types():+ from app.services.event_service import EVENT_CATALOG+ types = {e['type'] for e in EVENT_CATALOG}+ assert {'health.check_failed', 'git.push',+ 'monitor.high_cpu', 'monitor.high_memory'} <= types+++def _wildcard_sub(app):+ from app import db+ from app.models.event_subscription import EventSubscription+ admin = _mk_admin()+ sub = EventSubscription(user_id=admin.id, name='cap', url='http://x/y', is_active=True)+ sub.set_events(['*'])+ db.session.add(sub)+ db.session.commit()+ return sub+++def test_ported_emitters_reach_event_service(app, monkeypatch):+ from app.services.event_service import EventService+ from app.models.event_subscription import EventDelivery+ _wildcard_sub(app)+ enqueued = []+ monkeypatch.setattr('app.services.event_service.enqueue_webhook_delivery',+ lambda did: enqueued.append(did))+ for evt in ('health.check_failed', 'git.push', 'monitor.high_cpu'):+ EventService.emit(evt, {'event': evt})+ delivered = {d.event_type for d in EventDelivery.query.all()}+ assert {'health.check_failed', 'git.push', 'monitor.high_cpu'} <= delivered+ assert len(enqueued) == 3+++def test_app_stopped_not_double_emitted_by_docker_service(app, monkeypatch):+ """docker_service.stop_container no longer emits app.stopped itself."""+ from app.models.event_subscription import EventDelivery+ _wildcard_sub(app)+ from app.services.docker_service import DockerService+ monkeypatch.setattr('app.services.event_service.enqueue_webhook_delivery',+ lambda did: None)+ monkeypatch.setattr(+ 'app.services.docker_service.subprocess.run',+ lambda *a, **k: SimpleNamespace(returncode=0, stdout='', stderr=''))+ res = DockerService.stop_container('abc123')+ assert res['success'] is True+ # No app.stopped delivery came from the low-level stop helper.+ assert EventDelivery.query.filter_by(event_type='app.stopped').count() == 0diff --git a/builtin-extensions/serverkit-tramo/backend/host_service.py b/builtin-extensions/serverkit-tramo/backend/host_service.pyindex 21dbcdc9..a1f38e66 100644--- a/builtin-extensions/serverkit-tramo/backend/host_service.py+++ b/builtin-extensions/serverkit-tramo/backend/host_service.py@@ -120,6 +120,13 @@ class TramoHostService:return valuereturn decrypt_secret_safe(value)+ @classmethod+ def _is_windows(cls):+ """Windows (dev) has no Docker engine for us. Single testable seam so+ tests can force either platform without touching the global ``os.name``+ (which would break ``pathlib``)."""+ return os.name == 'nt'+@classmethoddef host_port(cls):"""Loopback host port the container's API is published on."""@@ -169,7 +176,7 @@ class TramoHostService:@classmethoddef _docker(cls, args, timeout=DOCKER_TIMEOUT):"""Run ``docker <args>`` and return a normalized result dict. Never raises."""- if os.name == 'nt':+ if cls._is_windows():return {'success': False,'error': 'The Automations extension is not supported on Windows.'}if not is_command_available('docker'):@@ -201,7 +208,7 @@ class TramoHostService:Returns ``{'success': True, 'data': <json-or-None>, 'status_code': int}``or an error dict. Auth is Bearer with the generated API key. Never raises."""- if os.name == 'nt':+ if cls._is_windows():return {'success': False,'error': 'The Automations extension is not supported on Windows.'}key = cls.api_key()@@ -241,7 +248,7 @@ class TramoHostService:@classmethoddef is_installed(cls):"""True when the managed container exists (running or not)."""- if os.name == 'nt':+ if cls._is_windows():return Falseres = cls._docker(['inspect', '--format', '{{.State.Running}}',CONTAINER_NAME], timeout=20)@@ -268,7 +275,7 @@ class TramoHostService:'api': f'{API_HOST}:{cls.host_port()}','docs_url': DOCS_URL,}- if os.name == 'nt':+ if cls._is_windows():status['error'] = 'The Automations extension is not supported on Windows.'return statusres = cls._docker(['inspect', '--format', '{{.State.Running}}',@@ -311,7 +318,7 @@ class TramoHostService:* Pack credentials + the scoped panel call-back key (SERVERKIT_URL /SERVERKIT_API_KEY) injected as container env."""- if os.name == 'nt':+ if cls._is_windows():return {'success': False,'error': 'The Automations extension is not supported on Windows.'}if cls.is_installed():@@ -383,7 +390,7 @@ class TramoHostService:@classmethoddef uninstall(cls, keep_data=True):"""Remove the container; optionally delete the data directory."""- if os.name == 'nt':+ if cls._is_windows():return {'success': False,'error': 'The Automations extension is not supported on Windows.'}res = cls._docker(['rm', '-f', CONTAINER_NAME])diff --git a/builtin-extensions/serverkit-tramo/backend/models.py b/builtin-extensions/serverkit-tramo/backend/models.pyindex 721bf4f5..9b508030 100644--- a/builtin-extensions/serverkit-tramo/backend/models.py+++ b/builtin-extensions/serverkit-tramo/backend/models.py@@ -41,6 +41,10 @@ class TramoWorkflow(db.Model):updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)# Stamped when this workflow was last materialized + deployed to the engine.deployed_at = db.Column(db.DateTime, nullable=True)+ # doc_version captured at the last deploy. Dirty detection compares this to+ # the live doc_version -- a version counter, not a timestamp, so the deploy+ # commit's own updated_at bump can't make a just-deployed row look dirty.+ deployed_version = db.Column(db.Integer, nullable=True)def get_doc(self):"""Return the parsed WorkflowDoc (empty dict if unset/invalid)."""@@ -61,12 +65,17 @@ class TramoWorkflow(db.Model):self.doc = json.dumps(doc)def is_dirty(self):- """True when the doc changed since the last deploy (needs redeploy)."""- if not self.deployed_at:- return self.enabled- if not self.updated_at:+ """True when an enabled workflow needs a (re)deploy.++ Dirty when it has never been deployed or its doc changed since the last+ deploy (``doc_version`` moved past ``deployed_version``). Disabled+ workflows are never dirty -- they materialize to nothing.+ """+ if not self.enabled:return False- return self.updated_at > self.deployed_at+ if not self.deployed_at:+ return True+ return (self.doc_version or 1) > (self.deployed_version or 0)def to_dict(self, include_doc=False):out = {diff --git a/builtin-extensions/serverkit-tramo/backend/workflow_store.py b/builtin-extensions/serverkit-tramo/backend/workflow_store.pyindex f90073e1..610c3f7c 100644--- a/builtin-extensions/serverkit-tramo/backend/workflow_store.py+++ b/builtin-extensions/serverkit-tramo/backend/workflow_store.py@@ -200,5 +200,6 @@ class WorkflowStore:now = datetime.utcnow()for wf in TramoWorkflow.query.filter_by(enabled=True).all():wf.deployed_at = now+ wf.deployed_version = wf.doc_versiondb.session.commit()return {'success': True, 'message': 'Automations deployed', 'materialized': summary}diff --git a/builtin-extensions/serverkit-tramo/frontend/components/AutomationEditorPage.jsx b/builtin-extensions/serverkit-tramo/frontend/components/AutomationEditorPage.jsxnew file mode 100644index 00000000..ca7bdd27--- /dev/null+++ b/builtin-extensions/serverkit-tramo/frontend/components/AutomationEditorPage.jsx@@ -0,0 +1,120 @@+import { Suspense, lazy, useCallback, useEffect, useState } from 'react';+import { useParams, useNavigate } from 'react-router-dom';+import { ArrowLeft, Play, Rocket, Check, AlertCircle, Loader2 } from 'lucide-react';+import api from '@/services/api';+import { Pill } from '@/components/ds';+import { Button } from '@/components/ui/button';+import EmptyState from '@/components/EmptyState';+import { useToast } from '@/contexts/ToastContext';++import '../styles/tramo-automations.scss';++// The tramo editor is the heavy chunk (canvas engine + 21 integration packs ++// tramo/styles.css). Lazy-load it so it never lands in the panel entry bundle.+const TramoEditor = lazy(() => import('./TramoEditor.jsx'));++// Map the editor's save lifecycle to a small header indicator.+const SaveIndicator = ({ state }) => {+ const status = state?.status || 'idle';+ if (status === 'saving' || status === 'pending') {+ return <span className="tramo-save tramo-save--busy"><Loader2 size={13} className="tramo-spin" /> Saving…</span>;+ }+ if (status === 'saved') {+ return <span className="tramo-save tramo-save--ok"><Check size={13} /> Saved</span>;+ }+ if (status === 'error') {+ return <span className="tramo-save tramo-save--err"><AlertCircle size={13} /> {state?.error || 'Save failed'}</span>;+ }+ return <span className="tramo-save tramo-save--idle">All changes saved</span>;+};++const AutomationEditorPage = () => {+ const { slug } = useParams();+ const navigate = useNavigate();+ const toast = useToast();++ const [workflow, setWorkflow] = useState(null);+ const [saveState, setSaveState] = useState(null);+ const [busy, setBusy] = useState(false);++ // Header metadata (name, enabled) — the doc itself is owned by the editor.+ useEffect(() => {+ let cancelled = false;+ (async () => {+ try {+ const data = await api.request(`/tramo/workflows/${slug}`);+ if (!cancelled) setWorkflow(data);+ } catch (error) {+ if (!cancelled) toast.error(`Could not load workflow: ${error.message}`);+ }+ })();+ return () => { cancelled = true; };+ }, [slug, toast]);++ const onSaveStateChange = useCallback((s) => setSaveState(s), []);++ const handleRun = async () => {+ setBusy(true);+ try {+ const res = await api.request(`/tramo/workflows/${slug}/run`, { method: 'POST', body: {} });+ const status = res?.run?.status || res?.result?.status || 'started';+ toast.success(`Run ${status} — see Runs for details`, {+ action: { label: 'View runs', onClick: () => navigate('/automations/runs') },+ });+ } catch (error) {+ toast.error(`Run failed: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleDeploy = async () => {+ setBusy(true);+ try {+ const res = await api.request('/tramo/deploy', { method: 'POST' });+ toast.success(res?.message || 'Deployed to the tramo engine');+ } catch (error) {+ toast.error(`Deploy failed: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ return (+ <div className="tramo-editor-page">+ <div className="tramo-editor-page__bar">+ <div className="tramo-editor-page__left">+ <Button variant="ghost" size="sm" onClick={() => navigate('/automations')} title="Back to Automations">+ <ArrowLeft size={16} />+ </Button>+ <div className="tramo-editor-page__title">+ <span className="tramo-editor-page__name">{workflow?.name || slug}</span>+ {workflow && (+ <Pill kind={workflow.enabled ? 'green' : 'gray'}>+ {workflow.enabled ? 'enabled' : 'disabled'}+ </Pill>+ )}+ </div>+ <SaveIndicator state={saveState} />+ </div>+ <div className="tramo-editor-page__actions">+ <Button variant="secondary" size="sm" onClick={handleRun} disabled={busy}>+ <Play size={14} /> Run+ </Button>+ <Button variant="default" size="sm" onClick={handleDeploy} disabled={busy}>+ <Rocket size={14} /> Deploy+ </Button>+ </div>+ </div>++ <div className="tramo-editor-page__body">+ <Suspense fallback={<EmptyState loading title="Loading editor..." />}>+ <TramoEditor slug={slug} onSaveStateChange={onSaveStateChange} />+ </Suspense>+ </div>+ </div>+ );+};++export { AutomationEditorPage };+export default AutomationEditorPage;diff --git a/builtin-extensions/serverkit-tramo/frontend/components/AutomationsPage.jsx b/builtin-extensions/serverkit-tramo/frontend/components/AutomationsPage.jsxnew file mode 100644index 00000000..6fc4fae9--- /dev/null+++ b/builtin-extensions/serverkit-tramo/frontend/components/AutomationsPage.jsx@@ -0,0 +1,749 @@+import { useCallback, useEffect, useState } from 'react';+import { useParams, useNavigate } from 'react-router-dom';+import {+ Workflow, RefreshCw, Plus, Trash2, Rocket, Pencil, Play, LayoutTemplate,+ Server, Power, KeyRound, CheckCircle2, X,+} from 'lucide-react';+import api from '@/services/api';+import { PageTopbar, Pill } from '@/components/ds';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import Modal from '@/components/Modal';+import ConfirmDialog from '@/components/ConfirmDialog';+import EmptyState from '@/components/EmptyState';+import { useToast } from '@/contexts/ToastContext';++import '../styles/tramo-automations.scss';++// Route-driven tabs (manifest maps /automations and /automations/:tab here).+const TABS = [+ { slug: 'workflows', to: '/automations', label: 'Workflows', end: true },+ { slug: 'runs', to: '/automations/runs', label: 'Runs' },+ { slug: 'settings', to: '/automations/settings', label: 'Settings' },+];+const VALID_TABS = TABS.map((t) => t.slug);++// Run status → Pill colour.+const runPill = (status) => {+ const kind = status === 'succeeded' || status === 'success' ? 'green'+ : status === 'running' || status === 'pending' ? 'amber'+ : status === 'failed' || status === 'error' ? 'red'+ : status === 'awaiting_approval' ? 'cyan' : 'gray';+ return <Pill kind={kind}>{status || 'unknown'}</Pill>;+};++// Host lifecycle state → Pill colour.+const hostPill = (state) => {+ const kind = state === 'ready' ? 'green'+ : state === 'unhealthy' ? 'amber'+ : state === 'stopped' ? 'gray' : 'red';+ return <Pill kind={kind}>{state || 'not_installed'}</Pill>;+};++const formatDuration = (start, finish) => {+ if (!start || !finish) return '—';+ const ms = new Date(finish).getTime() - new Date(start).getTime();+ if (Number.isNaN(ms) || ms < 0) return '—';+ if (ms < 1000) return `${ms}ms`;+ return `${(ms / 1000).toFixed(1)}s`;+};++const AutomationsPage = () => {+ const toast = useToast();+ const navigate = useNavigate();+ const { tab } = useParams();+ const activeTab = VALID_TABS.includes(tab) ? tab : 'workflows';++ const [busy, setBusy] = useState(false);+ const [confirmDialog, setConfirmDialog] = useState(null);++ // Workflows tab+ const [workflows, setWorkflows] = useState([]);+ const [wfLoading, setWfLoading] = useState(false);+ const [newModal, setNewModal] = useState(false);+ const [newName, setNewName] = useState('');+ const [templateModal, setTemplateModal] = useState(false);+ const [templates, setTemplates] = useState([]);++ // Runs tab+ const [runs, setRuns] = useState([]);+ const [approvals, setApprovals] = useState([]);+ const [runsLoading, setRunsLoading] = useState(false);++ // Settings tab+ const [host, setHost] = useState(null);+ const [settings, setSettings] = useState(null);+ const [settingsLoading, setSettingsLoading] = useState(false);+ const [installPort, setInstallPort] = useState('');+ const [newSecret, setNewSecret] = useState({ name: '', value: '' });+ const [hostPortDraft, setHostPortDraft] = useState('');++ // ── Loaders ──+ const loadWorkflows = useCallback(async () => {+ setWfLoading(true);+ try {+ const data = await api.request('/tramo/workflows');+ setWorkflows(data.workflows || []);+ } catch (error) {+ toast.error(`Could not load workflows: ${error.message}`);+ } finally {+ setWfLoading(false);+ }+ }, [toast]);++ const loadRuns = useCallback(async () => {+ setRunsLoading(true);+ try {+ const [runData, apprData] = await Promise.all([+ api.request('/tramo/runs?limit=100'),+ api.request('/tramo/approvals'),+ ]);+ setRuns(runData.runs || []);+ setApprovals(apprData.approvals || []);+ } catch (error) {+ toast.error(`Could not load runs: ${error.message}`);+ } finally {+ setRunsLoading(false);+ }+ }, [toast]);++ const loadSettings = useCallback(async () => {+ setSettingsLoading(true);+ try {+ const [statusData, settingsData] = await Promise.all([+ api.request('/tramo/host/status'),+ api.request('/tramo/settings'),+ ]);+ setHost(statusData);+ setSettings(settingsData);+ setHostPortDraft(String(settingsData.host_port ?? statusData.host_port ?? ''));+ } catch (error) {+ toast.error(`Could not load settings: ${error.message}`);+ } finally {+ setSettingsLoading(false);+ }+ }, [toast]);++ useEffect(() => {+ if (activeTab === 'workflows') loadWorkflows();+ else if (activeTab === 'runs') loadRuns();+ else if (activeTab === 'settings') loadSettings();+ }, [activeTab, loadWorkflows, loadRuns, loadSettings]);++ // ── Workflow actions ──+ const handleCreate = async () => {+ if (!newName.trim()) { toast.error('Name is required.'); return; }+ setBusy(true);+ try {+ const wf = await api.request('/tramo/workflows', { method: 'POST', body: { name: newName.trim() } });+ setNewModal(false);+ setNewName('');+ toast.success(`Workflow "${wf.name}" created`);+ navigate(`/automations/edit/${wf.slug}`);+ } catch (error) {+ toast.error(`Could not create workflow: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const openTemplateModal = async () => {+ setTemplateModal(true);+ try {+ const data = await api.request('/tramo/templates');+ setTemplates(data.templates || []);+ } catch (error) {+ toast.error(`Could not load templates: ${error.message}`);+ }+ };++ const handleFromTemplate = async (template) => {+ setBusy(true);+ try {+ const wf = await api.request(`/tramo/workflows/from-template/${template.id}`, { method: 'POST', body: {} });+ setTemplateModal(false);+ toast.success(`Created "${wf.name}" from ${template.name}`);+ navigate(`/automations/edit/${wf.slug}`);+ } catch (error) {+ toast.error(`Could not create from template: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleToggleEnabled = async (wf) => {+ try {+ await api.request(`/tramo/workflows/${wf.slug}`, { method: 'PUT', body: { enabled: !wf.enabled } });+ await loadWorkflows();+ } catch (error) {+ toast.error(`Could not update workflow: ${error.message}`);+ }+ };++ const handleDeleteWorkflow = (wf) => {+ setConfirmDialog({+ title: `Delete ${wf.name}?`,+ message: 'This removes the workflow and its stored document. Deployed runs already recorded are kept.',+ confirmText: 'Delete',+ variant: 'danger',+ onConfirm: async () => {+ setConfirmDialog(null);+ try {+ await api.request(`/tramo/workflows/${wf.slug}`, { method: 'DELETE' });+ toast.success('Workflow deleted');+ await loadWorkflows();+ } catch (error) {+ toast.error(error.message);+ }+ },+ onCancel: () => setConfirmDialog(null),+ });+ };++ const handleDeploy = async () => {+ setBusy(true);+ try {+ const res = await api.request('/tramo/deploy', { method: 'POST' });+ toast.success(res?.message || 'Deployed to the tramo engine');+ await loadWorkflows();+ } catch (error) {+ toast.error(`Deploy failed: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleRunWorkflow = async (wf) => {+ setBusy(true);+ try {+ const res = await api.request(`/tramo/workflows/${wf.slug}/run`, { method: 'POST', body: {} });+ const status = res?.run?.status || res?.result?.status || 'started';+ toast.success(`Run ${status} — see the Runs tab`);+ } catch (error) {+ toast.error(`Run failed: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ // ── Run actions ──+ const handleApprove = async (runId) => {+ setBusy(true);+ try {+ await api.request(`/tramo/runs/${runId}/approve`, { method: 'POST', body: {} });+ toast.success('Approved');+ await loadRuns();+ } catch (error) {+ toast.error(`Approve failed: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleReplay = async (runId) => {+ setBusy(true);+ try {+ await api.request(`/tramo/runs/${runId}/replay`, { method: 'POST' });+ toast.success('Replay queued');+ await loadRuns();+ } catch (error) {+ toast.error(`Replay failed: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ // ── Host / settings actions ──+ const handleInstall = async () => {+ setBusy(true);+ try {+ const body = installPort ? { host_port: Number(installPort) } : {};+ await api.request('/tramo/host/install', { method: 'POST', body });+ toast.success('tramo engine installed');+ setInstallPort('');+ await loadSettings();+ } catch (error) {+ toast.error(`Install failed: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleUninstall = (keepData) => {+ setConfirmDialog({+ title: 'Remove tramo engine',+ message: keepData+ ? 'Remove the tramo container? Workflow data stays on disk and a reinstall picks it back up.'+ : 'Remove the tramo container AND delete all engine data? This cannot be undone.',+ confirmText: 'Remove',+ variant: 'danger',+ onConfirm: async () => {+ setConfirmDialog(null);+ try {+ await api.request(`/tramo/host/install?keep_data=${keepData}`, { method: 'DELETE' });+ toast.success('tramo engine removed');+ await loadSettings();+ } catch (error) {+ toast.error(`Uninstall failed: ${error.message}`);+ }+ },+ onCancel: () => setConfirmDialog(null),+ });+ };++ const handleControl = async (action) => {+ setBusy(true);+ try {+ await api.request(`/tramo/host/control/${action}`, { method: 'POST' });+ toast.success(`Engine ${action} requested`);+ await loadSettings();+ } catch (error) {+ toast.error(`Could not ${action} engine: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleAddSecret = async () => {+ if (!newSecret.name.trim() || !newSecret.value) { toast.error('Name and value are required.'); return; }+ setBusy(true);+ try {+ await api.request('/tramo/settings', {+ method: 'PUT',+ body: { pack_secrets: { [newSecret.name.trim()]: newSecret.value } },+ });+ toast.success(`Secret ${newSecret.name.trim()} saved`);+ setNewSecret({ name: '', value: '' });+ await loadSettings();+ } catch (error) {+ toast.error(`Could not save secret: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleToggleBridge = async () => {+ setBusy(true);+ try {+ await api.request('/tramo/settings', {+ method: 'PUT',+ body: { events_bridge_enabled: !settings?.events_bridge_enabled },+ });+ await loadSettings();+ } catch (error) {+ toast.error(`Could not update events bridge: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleSaveHostPort = async () => {+ const port = Number(hostPortDraft);+ if (!port) { toast.error('Enter a valid port.'); return; }+ setBusy(true);+ try {+ await api.request('/tramo/settings', { method: 'PUT', body: { host_port: port } });+ toast.success('Host port updated');+ await loadSettings();+ } catch (error) {+ toast.error(`Could not update host port: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ // ── Renderers ──+ const renderWorkflows = () => (+ <div className="card sec-flush">+ <div className="card-header">+ <h3>Workflows {workflows.length > 0 && <span className="sec-count">· {workflows.length}</span>}</h3>+ <div className="card-actions tramo-toolbar">+ <Button variant="outline" size="sm" onClick={handleDeploy} disabled={busy}>+ <Rocket size={14} /> Deploy+ </Button>+ <Button variant="secondary" size="sm" onClick={openTemplateModal}>+ <LayoutTemplate size={14} /> New from template+ </Button>+ <Button variant="default" size="sm" onClick={() => { setNewName(''); setNewModal(true); }}>+ <Plus size={14} /> New workflow+ </Button>+ </div>+ </div>+ <div className="card-body">+ {wfLoading ? <EmptyState loading title="Loading workflows..." />+ : workflows.length === 0 ? (+ <EmptyState+ icon={Workflow}+ title="No automations yet"+ description="Create a workflow on the visual canvas, or start from a template. Enable it and deploy to run it headless on the tramo engine."+ />+ ) : (+ <table className="sk-dtable">+ <thead>+ <tr>+ <th>Name</th><th>Enabled</th><th>State</th><th>Version</th><th>Updated</th><th /></tr>+ </thead>+ <tbody>+ {workflows.map((wf) => (+ <tr key={wf.id ?? wf.slug}>+ <td className="sk-cell-mono">{wf.name}</td>+ <td>+ <button+ type="button"+ className={`tramo-toggle${wf.enabled ? ' tramo-toggle--on' : ''}`}+ onClick={() => handleToggleEnabled(wf)}+ aria-pressed={wf.enabled}+ title={wf.enabled ? 'Disable' : 'Enable'}+ >+ <span className="tramo-toggle__knob" />+ </button>+ </td>+ <td>+ {wf.dirty+ ? <Pill kind="amber" title="Edited since last deploy">undeployed</Pill>+ : <Pill kind="green">deployed</Pill>}+ </td>+ <td className="sk-cell-mono">{wf.doc_version ?? '—'}</td>+ <td className="sk-cell-mono">{wf.updated_at ? new Date(wf.updated_at).toLocaleString() : '—'}</td>+ <td className="tramo-row-actions">+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleRunWorkflow(wf)} title="Run now">+ <Play size={14} />+ </Button>+ <Button variant="secondary" size="sm" onClick={() => navigate(`/automations/edit/${wf.slug}`)} title="Edit">+ <Pencil size={14} />+ </Button>+ <Button variant="destructive" size="sm" onClick={() => handleDeleteWorkflow(wf)} title="Delete">+ <Trash2 size={14} />+ </Button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ </div>+ );++ const renderRuns = () => (+ <>+ {approvals.length > 0 && (+ <div className="card tramo-approvals">+ <div className="card-header">+ <h3>Pending approvals <span className="sec-count">· {approvals.length}</span></h3>+ </div>+ <div className="card-body">+ {approvals.map((a) => (+ <div className="tramo-approval" key={a.run_id}>+ <div className="tramo-approval__info">+ <span className="sk-cell-mono">{a.workflow_slug || a.workflow || '—'}</span>+ <span className="text-muted">{a.node || a.message || 'Awaiting approval'}</span>+ </div>+ <Button variant="default" size="sm" disabled={busy} onClick={() => handleApprove(a.run_id)}>+ <CheckCircle2 size={14} /> Approve+ </Button>+ </div>+ ))}+ </div>+ </div>+ )}+ <div className="card sec-flush">+ <div className="card-header">+ <h3>Runs {runs.length > 0 && <span className="sec-count">· {runs.length}</span>}</h3>+ <div className="card-actions">+ <Button variant="outline" size="sm" onClick={loadRuns} disabled={runsLoading}>+ <RefreshCw size={14} /> Refresh+ </Button>+ </div>+ </div>+ <div className="card-body">+ {runsLoading ? <EmptyState loading title="Loading runs..." />+ : runs.length === 0 ? (+ <EmptyState icon={Play} title="No runs yet" description="Deploy an enabled workflow, then trigger it or wait for a matching event." />+ ) : (+ <table className="sk-dtable">+ <thead>+ <tr>+ <th>Status</th><th>Workflow</th><th>Source</th><th>Duration</th><th>Tokens</th><th>Error</th><th /></tr>+ </thead>+ <tbody>+ {runs.map((r) => (+ <tr key={r.run_id}>+ <td>{runPill(r.status)}</td>+ <td className="sk-cell-mono">{r.workflow_slug || '—'}</td>+ <td><Pill kind="gray">{r.source || 'manual'}</Pill></td>+ <td className="sk-cell-mono">{formatDuration(r.started_at, r.finished_at)}</td>+ <td className="sk-cell-mono">{r.usage?.total_tokens ?? r.usage?.tokens ?? '—'}</td>+ <td className="sk-cell-mono tramo-truncate" title={r.error || ''}>{r.error || '—'}</td>+ <td className="tramo-row-actions">+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleReplay(r.run_id)} title="Replay">+ <RefreshCw size={14} />+ </Button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ </div>+ </>+ );++ const renderSettings = () => {+ const state = host?.state || 'not_installed';+ const installed = !!host?.installed;+ const notSupported = !installed && !!host?.error;+ return (+ <>+ <div className="card">+ <div className="card-header">+ <h3><Server size={16} /> Automation engine</h3>+ <div className="card-actions">+ <Button variant="outline" size="sm" onClick={loadSettings} disabled={settingsLoading}>+ <RefreshCw size={14} /> Refresh+ </Button>+ </div>+ </div>+ <div className="card-body">+ {settingsLoading && !host ? <EmptyState loading title="Loading engine status..." /> : (+ <>+ <div className="sec-rows">+ <div className="sk-info-row">+ <span className="k">Status</span>+ {hostPill(state)}+ </div>+ <div className="sk-info-row">+ <span className="k">Container</span>+ <span className="v sk-cell-mono">{host?.container || '—'}</span>+ </div>+ <div className="sk-info-row">+ <span className="k">Image</span>+ <span className="v sk-cell-mono">{host?.image || '—'}</span>+ </div>+ <div className="sk-info-row">+ <span className="k">Host port</span>+ <span className="v sk-cell-mono">{host?.host_port ?? '—'}</span>+ </div>+ {host?.version && (+ <div className="sk-info-row">+ <span className="k">Version</span>+ <span className="v sk-cell-mono">{host.version}</span>+ </div>+ )}+ </div>++ {notSupported && (+ <div className="tramo-note">+ Docker is required to run the tramo engine, and it is not available on this+ host (the engine does not run on Windows dev boxes). You can still design+ workflows; deploying and running them needs a Linux host with Docker.+ <div className="tramo-note__detail">{host.error}</div>+ </div>+ )}++ <div className="tramo-host-actions">+ {!installed ? (+ <div className="tramo-install">+ <div className="form-group">+ <Label>Host port (optional)</Label>+ <Input+ type="number"+ value={installPort}+ placeholder={String(host?.host_port ?? 3737)}+ onChange={(e) => setInstallPort(e.target.value)}+ />+ </div>+ <Button variant="default" size="sm" onClick={handleInstall} disabled={busy}>+ <Power size={14} /> Install engine+ </Button>+ </div>+ ) : (+ <>+ <Button variant="outline" size="sm" onClick={() => handleControl('restart')} disabled={busy}>+ <RefreshCw size={14} /> Restart+ </Button>+ {host?.running ? (+ <Button variant="outline" size="sm" onClick={() => handleControl('stop')} disabled={busy}>+ <Power size={14} /> Stop+ </Button>+ ) : (+ <Button variant="default" size="sm" onClick={() => handleControl('start')} disabled={busy}>+ <Power size={14} /> Start+ </Button>+ )}+ <Button variant="secondary" size="sm" onClick={() => handleUninstall(true)} disabled={busy}>+ Remove (keep data)+ </Button>+ <Button variant="destructive" size="sm" onClick={() => handleUninstall(false)} disabled={busy}>+ <Trash2 size={14} /> Remove + data+ </Button>+ </>+ )}+ </div>+ </>+ )}+ </div>+ </div>++ <div className="card">+ <div className="card-header"><h3>Engine settings</h3></div>+ <div className="card-body tramo-settings">+ <div className="tramo-field">+ <div className="tramo-field__label">+ <Label>Events bridge</Label>+ <p className="text-muted">Forward panel events to tramo so workflows can react to them.</p>+ </div>+ <button+ type="button"+ className={`tramo-toggle${settings?.events_bridge_enabled ? ' tramo-toggle--on' : ''}`}+ onClick={handleToggleBridge}+ disabled={busy}+ aria-pressed={!!settings?.events_bridge_enabled}+ >+ <span className="tramo-toggle__knob" />+ </button>+ </div>+ <div className="tramo-field tramo-field--inline">+ <div className="tramo-field__label">+ <Label>Host port</Label>+ <p className="text-muted">Port the tramo container is published on.</p>+ </div>+ <div className="tramo-field__control">+ <Input type="number" value={hostPortDraft} onChange={(e) => setHostPortDraft(e.target.value)} />+ <Button variant="secondary" size="sm" onClick={handleSaveHostPort} disabled={busy}>Save</Button>+ </div>+ </div>+ </div>+ </div>++ <div className="card sec-flush">+ <div className="card-header">+ <h3><KeyRound size={16} /> Pack secrets</h3>+ </div>+ <div className="card-body">+ <p className="text-muted">+ Credentials integration packs need (API keys, tokens). Values are write-only — they are+ stored encrypted and never shown again after saving.+ </p>+ {(settings?.pack_secret_names?.length ?? 0) === 0 ? (+ <p className="text-muted">No pack secrets set yet.</p>+ ) : (+ <div className="tramo-secret-list">+ {settings.pack_secret_names.map((name) => (+ <div className="tramo-secret" key={name}>+ <span className="sk-cell-mono">{name}</span>+ <Pill kind="green">set</Pill>+ </div>+ ))}+ </div>+ )}+ <div className="tramo-secret-add">+ <div className="form-group">+ <Label>Name</Label>+ <Input+ type="text"+ value={newSecret.name}+ placeholder="TELEGRAM_BOT_TOKEN"+ onChange={(e) => setNewSecret((s) => ({ ...s, name: e.target.value }))}+ />+ </div>+ <div className="form-group">+ <Label>Value</Label>+ <Input+ type="password"+ value={newSecret.value}+ onChange={(e) => setNewSecret((s) => ({ ...s, value: e.target.value }))}+ />+ </div>+ <Button variant="default" size="sm" onClick={handleAddSecret} disabled={busy}>+ <Plus size={14} /> Add secret+ </Button>+ </div>+ </div>+ </div>+ </>+ );+ };++ const topbarTabs = TABS.map(({ to, label, end }) => ({ to, label, end }));++ return (+ <div className="page-container tramo-page">+ <PageTopbar+ icon={<Workflow size={18} />}+ title="Automations"+ meta={<>tramo · workflows · triggers · integrations</>}+ tabs={topbarTabs}+ actions={+ <Button variant="default" size="sm" onClick={() => { setNewName(''); setNewModal(true); }}>+ <Plus size={14} /> New workflow+ </Button>+ }+ />++ {activeTab === 'workflows' && renderWorkflows()}+ {activeTab === 'runs' && renderRuns()}+ {activeTab === 'settings' && renderSettings()}++ {/* New workflow modal */}+ <Modal open={newModal} onClose={() => setNewModal(false)} title="New workflow">+ <div className="form-group">+ <Label>Name</Label>+ <Input+ type="text"+ value={newName}+ placeholder="Notify on deploy"+ onChange={(e) => setNewName(e.target.value)}+ onKeyDown={(e) => { if (e.key === 'Enter') handleCreate(); }}+ />+ <p className="text-muted">You will land on the visual editor to design the flow.</p>+ </div>+ <div className="modal-footer">+ <Button variant="outline" onClick={() => setNewModal(false)}>Cancel</Button>+ <Button variant="default" onClick={handleCreate} disabled={busy || !newName.trim()}>Create</Button>+ </div>+ </Modal>++ {/* New from template modal */}+ <Modal open={templateModal} onClose={() => setTemplateModal(false)} title="New from template">+ {templates.length === 0 ? (+ <EmptyState icon={LayoutTemplate} title="No templates available" />+ ) : (+ <div className="tramo-template-list">+ {templates.map((t) => (+ <button+ type="button"+ className="tramo-template"+ key={t.id}+ onClick={() => handleFromTemplate(t)}+ disabled={busy}+ >+ <span className="tramo-template__name">{t.name}</span>+ {t.description && <span className="tramo-template__desc">{t.description}</span>}+ </button>+ ))}+ </div>+ )}+ <div className="modal-footer">+ <Button variant="outline" onClick={() => setTemplateModal(false)}><X size={14} /> Close</Button>+ </div>+ </Modal>++ {confirmDialog && (+ <ConfirmDialog+ title={confirmDialog.title}+ message={confirmDialog.message}+ confirmText={confirmDialog.confirmText}+ variant={confirmDialog.variant}+ onConfirm={confirmDialog.onConfirm}+ onCancel={confirmDialog.onCancel}+ />+ )}+ </div>+ );+};++export { AutomationsPage };+export default AutomationsPage;diff --git a/builtin-extensions/serverkit-tramo/frontend/components/TramoEditor.jsx b/builtin-extensions/serverkit-tramo/frontend/components/TramoEditor.jsxnew file mode 100644index 00000000..3cf7f3f7--- /dev/null+++ b/builtin-extensions/serverkit-tramo/frontend/components/TramoEditor.jsx@@ -0,0 +1,62 @@+// TramoEditor — the heavy editor chunk.+//+// Everything tramo-visual lives behind this module so it code-splits away from+// the panel entry bundle. AutomationEditorPage React.lazy()-imports it; nothing+// on the entry path may import this file (or tramo/react / tramo/styles.css)+// statically, or the split collapses.+import { useEffect } from 'react';+import { Canvas, RightRail, useWorkflow } from 'tramo/react';+import api from '@/services/api';+import EmptyState from '@/components/EmptyState';+import { registry } from '../registry.js';++// tramo's own canvas + inspector CSS. Imported here (inside the lazy chunk) so+// it ships with the editor, not the entry bundle.+import 'tramo/styles.css';++const TramoEditor = ({ slug, onSaveStateChange }) => {+ const handle = useWorkflow({+ registry,+ key: slug,+ loadDoc: async () => {+ const data = await api.request(`/tramo/workflows/${slug}`);+ return data.doc || { name: slug, nodes: [], edges: [] };+ },+ saveDoc: async (doc) => {+ await api.request(`/tramo/workflows/${slug}`, { method: 'PUT', body: { doc } });+ },+ });++ // Surface the debounced save lifecycle up to the page's top strip.+ useEffect(() => {+ if (onSaveStateChange) onSaveStateChange(handle.saveState);+ }, [handle.saveState, onSaveStateChange]);++ if (!handle.ready) {+ return (+ <div className="tramo-editor__loading">+ <EmptyState loading title="Loading workflow..." />+ </div>+ );+ }++ return (+ <div className="tramo-editor">+ <div className="tramo-editor__canvas">+ <Canvas workflow={handle} />+ </div>+ <div className="tramo-editor__rail">+ <RightRail+ selection={handle.selection}+ registry={handle.registry}+ onApply={handle.applyPatch}+ onClose={handle.clearSelection}+ saveState={handle.saveState}+ doc={handle.doc}+ />+ </div>+ </div>+ );+};++export default TramoEditor;diff --git a/builtin-extensions/serverkit-tramo/frontend/index.jsx b/builtin-extensions/serverkit-tramo/frontend/index.jsxnew file mode 100644index 00000000..12933af4--- /dev/null+++ b/builtin-extensions/serverkit-tramo/frontend/index.jsx@@ -0,0 +1,12 @@+// Automations (tramo) UI, contributed through the extension system. Fully+// self-contained in the extension. After sync this folder lives at+// frontend/src/plugins/serverkit-tramo/, so '@/…' host aliases resolve.+//+// plugin.json declares two route components — AutomationsPage (the tabbed+// list/runs/settings surface) and AutomationEditorPage (the full-bleed canvas).+// Both are resolved by name from these exports.+export { AutomationsPage } from './components/AutomationsPage.jsx';+export { AutomationEditorPage } from './components/AutomationEditorPage.jsx';++// No default export on purpose: PluginLoader legacy-auto-renders any plugin+// default export globally. The route contributions resolve the NAMED exports.diff --git a/builtin-extensions/serverkit-tramo/frontend/registry.js b/builtin-extensions/serverkit-tramo/frontend/registry.jsnew file mode 100644index 00000000..3a6cc291--- /dev/null+++ b/builtin-extensions/serverkit-tramo/frontend/registry.js@@ -0,0 +1,69 @@+// Node registry for the tramo editor.+//+// tramo ships its node definitions as "packs": the built-in pack plus one pack+// per brand integration. `combinePacks` merges them into a single registry of+// editor-side node definitions (`.nodes`) and runtime executors (`.executors`).+// The editor only needs `.nodes` — executors run server-side inside the managed+// tramo container, never in the browser.+//+// This module is imported by TramoEditor.jsx (the lazy chunk) so all of these+// integration packs code-split into the editor bundle and never reach the+// panel's entry bundle.+import { combinePacks, BUILTIN_PACK } from 'tramo/runtime';++import gmail from 'tramo/integrations/gmail';+import github from 'tramo/integrations/github';+import telegram from 'tramo/integrations/telegram';+import discord from 'tramo/integrations/discord';+import notion from 'tramo/integrations/notion';+import openai from 'tramo/integrations/openai';+import anthropic from 'tramo/integrations/anthropic';+import linear from 'tramo/integrations/linear';+import airtable from 'tramo/integrations/airtable';+import stripe from 'tramo/integrations/stripe';+import cloudflare from 'tramo/integrations/cloudflare';+import googleDrive from 'tramo/integrations/google-drive';+import googleSheets from 'tramo/integrations/google-sheets';+import googleTasks from 'tramo/integrations/google-tasks';+import outlook from 'tramo/integrations/outlook';+import postgres from 'tramo/integrations/postgres';+import twilio from 'tramo/integrations/twilio';+import youtube from 'tramo/integrations/youtube';+import x from 'tramo/integrations/x';+import trello from 'tramo/integrations/trello';+import box from 'tramo/integrations/box';++// TODO(plan45): add SERVERKIT_PACK once @tramo/serverkit is published. Its+// executors run server-side; the editor only needs its node definitions here.++// Order matters only for the palette; combinePacks throws on id collisions, so+// the brand packs are all distinct by construction.+export const combined = combinePacks([+ BUILTIN_PACK,+ gmail,+ github,+ telegram,+ discord,+ notion,+ openai,+ anthropic,+ linear,+ airtable,+ stripe,+ cloudflare,+ googleDrive,+ googleSheets,+ googleTasks,+ outlook,+ postgres,+ twilio,+ youtube,+ x,+ trello,+ box,+]);++// The editor-side registry of node definitions. Pass straight to useWorkflow.+export const registry = combined.nodes;++export default registry;diff --git a/builtin-extensions/serverkit-tramo/frontend/styles/tramo-automations.scss b/builtin-extensions/serverkit-tramo/frontend/styles/tramo-automations.scssnew file mode 100644index 00000000..d0afd6b4--- /dev/null+++ b/builtin-extensions/serverkit-tramo/frontend/styles/tramo-automations.scss@@ -0,0 +1,363 @@+/* Automations (tramo) extension — layout-only styles. Colours, typography,+ spacing and controls all inherit from the host design system (card,+ sk-dtable, sk-info-row, Pill, empty-state, form controls). Plugin SCSS is+ compiled in isolation, so we lean on CSS custom properties (var(--…)) and+ neutral rgba tints — never SCSS $variables, which aren't in scope here.+ We never restyle tramo's own .tr-* classes; the editor owns those. */++.tramo-page {+ .tramo-toolbar {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+ }++ .tramo-row-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ justify-content: flex-end;+ }++ .tramo-truncate {+ max-width: 280px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ /* Pending-approval strip */+ .tramo-approvals {+ margin-bottom: 16px;+ }++ .tramo-approval {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 10px 0;+ border-bottom: 1px solid rgba(128, 128, 128, 0.16);++ &:last-child {+ border-bottom: 0;+ }++ &__info {+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+ }+ }++ /* Unsupported / Docker-required note */+ .tramo-note {+ margin-top: 14px;+ padding: 12px 14px;+ border-radius: var(--radius, 8px);+ border: 1px solid rgba(234, 179, 8, 0.35);+ background: rgba(234, 179, 8, 0.08);+ font-size: 13px;+ line-height: 1.5;++ &__detail {+ margin-top: 8px;+ font-family: var(--mono, ui-monospace, SFMono-Regular, Menlo, monospace);+ font-size: 12px;+ opacity: 0.75;+ word-break: break-word;+ }+ }++ /* Engine host actions */+ .tramo-host-actions {+ display: flex;+ align-items: flex-end;+ flex-wrap: wrap;+ gap: 8px;+ margin-top: 16px;+ }++ .tramo-install {+ display: flex;+ align-items: flex-end;+ gap: 8px;++ .form-group {+ margin: 0;+ min-width: 180px;+ }+ }++ /* Settings fields */+ .tramo-settings {+ display: flex;+ flex-direction: column;+ gap: 4px;+ }++ .tramo-field {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ padding: 12px 0;+ border-bottom: 1px solid rgba(128, 128, 128, 0.14);++ &:last-child {+ border-bottom: 0;+ }++ &__label {+ min-width: 0;++ p {+ margin: 2px 0 0;+ }+ }++ &__control {+ display: flex;+ align-items: center;+ gap: 8px;++ input {+ width: 140px;+ }+ }+ }++ /* Pack secrets */+ .tramo-secret-list {+ display: flex;+ flex-direction: column;+ gap: 6px;+ margin: 12px 0;+ }++ .tramo-secret {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 8px 12px;+ border-radius: var(--radius-sm, 6px);+ background: rgba(128, 128, 128, 0.06);+ }++ .tramo-secret-add {+ display: flex;+ align-items: flex-end;+ gap: 8px;+ flex-wrap: wrap;+ margin-top: 12px;+ padding-top: 12px;+ border-top: 1px solid rgba(128, 128, 128, 0.14);++ .form-group {+ margin: 0;+ min-width: 200px;+ flex: 1;+ }+ }++ /* Enable toggle (also used in the settings events-bridge field) */+ .tramo-toggle {+ --tramo-toggle-w: 38px;+ --tramo-toggle-h: 22px;+ position: relative;+ width: var(--tramo-toggle-w);+ height: var(--tramo-toggle-h);+ border-radius: 999px;+ border: 0;+ cursor: pointer;+ padding: 0;+ background: rgba(128, 128, 128, 0.35);+ transition: background 0.15s ease;++ &__knob {+ position: absolute;+ top: 2px;+ left: 2px;+ width: calc(var(--tramo-toggle-h) - 4px);+ height: calc(var(--tramo-toggle-h) - 4px);+ border-radius: 50%;+ background: #fff;+ transition: transform 0.15s ease;+ }++ &--on {+ background: var(--accent-bright, #3b82f6);++ .tramo-toggle__knob {+ transform: translateX(calc(var(--tramo-toggle-w) - var(--tramo-toggle-h)));+ }+ }++ &:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+ }++ /* Template picker (inside the modal) */+ .tramo-template-list {+ display: flex;+ flex-direction: column;+ gap: 8px;+ }++ .tramo-template {+ display: flex;+ flex-direction: column;+ gap: 3px;+ text-align: left;+ width: 100%;+ padding: 12px 14px;+ border-radius: var(--radius, 8px);+ border: 1px solid var(--border, rgba(128, 128, 128, 0.3));+ background: transparent;+ color: inherit;+ cursor: pointer;+ transition: border-color 0.15s ease, background 0.15s ease;++ &:hover {+ border-color: var(--accent-bright, #3b82f6);+ background: rgba(128, 128, 128, 0.06);+ }++ &:disabled {+ opacity: 0.6;+ cursor: not-allowed;+ }++ &__name {+ font-weight: 600;+ }++ &__desc {+ font-size: 12.5px;+ opacity: 0.7;+ }+ }+}++/* ── Full-bleed editor page (route automations/edit/:slug, layout "full") ── */+.tramo-editor-page {+ height: 100%;+ min-height: 0;+ display: flex;+ flex-direction: column;+ background: var(--bg-body, transparent);++ &__bar {+ flex-shrink: 0;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 10px 16px;+ border-bottom: 1px solid var(--border, rgba(128, 128, 128, 0.25));+ background: var(--bg-card, transparent);+ }++ &__left {+ display: flex;+ align-items: center;+ gap: 12px;+ min-width: 0;+ }++ &__title {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+ }++ &__name {+ font-weight: 600;+ font-size: 15px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ max-width: 320px;+ }++ &__actions {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-shrink: 0;+ }++ &__body {+ flex: 1;+ min-height: 0;+ position: relative;+ }+}++/* Save-state indicator in the editor top strip */+.tramo-save {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ font-size: 12.5px;++ &--busy { color: var(--text-dim, #9aa0a6); }+ &--ok { color: var(--green, #22c55e); }+ &--err { color: var(--red, #ef4444); }+ &--idle { color: var(--text-dim, #9aa0a6); opacity: 0.7; }+}++.tramo-spin {+ animation: tramo-spin 0.9s linear infinite;+}++@keyframes tramo-spin {+ to { transform: rotate(360deg); }+}++@media (prefers-reduced-motion: reduce) {+ .tramo-spin { animation: none; }+}++/* ── Editor composition: canvas fills, inspector rail is fixed-width ── */+.tramo-editor {+ position: absolute;+ inset: 0;+ display: flex;+ min-height: 0;++ &__canvas {+ position: relative;+ flex: 1;+ min-width: 0;+ min-height: 0;+ overflow: hidden;+ }++ &__rail {+ flex-shrink: 0;+ width: 340px;+ min-height: 0;+ overflow-y: auto;+ border-left: 1px solid var(--border, rgba(128, 128, 128, 0.25));+ background: var(--bg-card, transparent);+ }++ &__loading {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ }++ @media (max-width: 768px) {+ &__rail { width: 260px; }+ }+}diff --git a/frontend/src/plugins/serverkit-tramo/components/AutomationEditorPage.jsx b/frontend/src/plugins/serverkit-tramo/components/AutomationEditorPage.jsxnew file mode 100644index 00000000..ca7bdd27--- /dev/null+++ b/frontend/src/plugins/serverkit-tramo/components/AutomationEditorPage.jsx@@ -0,0 +1,120 @@+import { Suspense, lazy, useCallback, useEffect, useState } from 'react';+import { useParams, useNavigate } from 'react-router-dom';+import { ArrowLeft, Play, Rocket, Check, AlertCircle, Loader2 } from 'lucide-react';+import api from '@/services/api';+import { Pill } from '@/components/ds';+import { Button } from '@/components/ui/button';+import EmptyState from '@/components/EmptyState';+import { useToast } from '@/contexts/ToastContext';++import '../styles/tramo-automations.scss';++// The tramo editor is the heavy chunk (canvas engine + 21 integration packs ++// tramo/styles.css). Lazy-load it so it never lands in the panel entry bundle.+const TramoEditor = lazy(() => import('./TramoEditor.jsx'));++// Map the editor's save lifecycle to a small header indicator.+const SaveIndicator = ({ state }) => {+ const status = state?.status || 'idle';+ if (status === 'saving' || status === 'pending') {+ return <span className="tramo-save tramo-save--busy"><Loader2 size={13} className="tramo-spin" /> Saving…</span>;+ }+ if (status === 'saved') {+ return <span className="tramo-save tramo-save--ok"><Check size={13} /> Saved</span>;+ }+ if (status === 'error') {+ return <span className="tramo-save tramo-save--err"><AlertCircle size={13} /> {state?.error || 'Save failed'}</span>;+ }+ return <span className="tramo-save tramo-save--idle">All changes saved</span>;+};++const AutomationEditorPage = () => {+ const { slug } = useParams();+ const navigate = useNavigate();+ const toast = useToast();++ const [workflow, setWorkflow] = useState(null);+ const [saveState, setSaveState] = useState(null);+ const [busy, setBusy] = useState(false);++ // Header metadata (name, enabled) — the doc itself is owned by the editor.+ useEffect(() => {+ let cancelled = false;+ (async () => {+ try {+ const data = await api.request(`/tramo/workflows/${slug}`);+ if (!cancelled) setWorkflow(data);+ } catch (error) {+ if (!cancelled) toast.error(`Could not load workflow: ${error.message}`);+ }+ })();+ return () => { cancelled = true; };+ }, [slug, toast]);++ const onSaveStateChange = useCallback((s) => setSaveState(s), []);++ const handleRun = async () => {+ setBusy(true);+ try {+ const res = await api.request(`/tramo/workflows/${slug}/run`, { method: 'POST', body: {} });+ const status = res?.run?.status || res?.result?.status || 'started';+ toast.success(`Run ${status} — see Runs for details`, {+ action: { label: 'View runs', onClick: () => navigate('/automations/runs') },+ });+ } catch (error) {+ toast.error(`Run failed: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleDeploy = async () => {+ setBusy(true);+ try {+ const res = await api.request('/tramo/deploy', { method: 'POST' });+ toast.success(res?.message || 'Deployed to the tramo engine');+ } catch (error) {+ toast.error(`Deploy failed: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ return (+ <div className="tramo-editor-page">+ <div className="tramo-editor-page__bar">+ <div className="tramo-editor-page__left">+ <Button variant="ghost" size="sm" onClick={() => navigate('/automations')} title="Back to Automations">+ <ArrowLeft size={16} />+ </Button>+ <div className="tramo-editor-page__title">+ <span className="tramo-editor-page__name">{workflow?.name || slug}</span>+ {workflow && (+ <Pill kind={workflow.enabled ? 'green' : 'gray'}>+ {workflow.enabled ? 'enabled' : 'disabled'}+ </Pill>+ )}+ </div>+ <SaveIndicator state={saveState} />+ </div>+ <div className="tramo-editor-page__actions">+ <Button variant="secondary" size="sm" onClick={handleRun} disabled={busy}>+ <Play size={14} /> Run+ </Button>+ <Button variant="default" size="sm" onClick={handleDeploy} disabled={busy}>+ <Rocket size={14} /> Deploy+ </Button>+ </div>+ </div>++ <div className="tramo-editor-page__body">+ <Suspense fallback={<EmptyState loading title="Loading editor..." />}>+ <TramoEditor slug={slug} onSaveStateChange={onSaveStateChange} />+ </Suspense>+ </div>+ </div>+ );+};++export { AutomationEditorPage };+export default AutomationEditorPage;diff --git a/frontend/src/plugins/serverkit-tramo/components/AutomationsPage.jsx b/frontend/src/plugins/serverkit-tramo/components/AutomationsPage.jsxnew file mode 100644index 00000000..6fc4fae9--- /dev/null+++ b/frontend/src/plugins/serverkit-tramo/components/AutomationsPage.jsx@@ -0,0 +1,749 @@+import { useCallback, useEffect, useState } from 'react';+import { useParams, useNavigate } from 'react-router-dom';+import {+ Workflow, RefreshCw, Plus, Trash2, Rocket, Pencil, Play, LayoutTemplate,+ Server, Power, KeyRound, CheckCircle2, X,+} from 'lucide-react';+import api from '@/services/api';+import { PageTopbar, Pill } from '@/components/ds';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import Modal from '@/components/Modal';+import ConfirmDialog from '@/components/ConfirmDialog';+import EmptyState from '@/components/EmptyState';+import { useToast } from '@/contexts/ToastContext';++import '../styles/tramo-automations.scss';++// Route-driven tabs (manifest maps /automations and /automations/:tab here).+const TABS = [+ { slug: 'workflows', to: '/automations', label: 'Workflows', end: true },+ { slug: 'runs', to: '/automations/runs', label: 'Runs' },+ { slug: 'settings', to: '/automations/settings', label: 'Settings' },+];+const VALID_TABS = TABS.map((t) => t.slug);++// Run status → Pill colour.+const runPill = (status) => {+ const kind = status === 'succeeded' || status === 'success' ? 'green'+ : status === 'running' || status === 'pending' ? 'amber'+ : status === 'failed' || status === 'error' ? 'red'+ : status === 'awaiting_approval' ? 'cyan' : 'gray';+ return <Pill kind={kind}>{status || 'unknown'}</Pill>;+};++// Host lifecycle state → Pill colour.+const hostPill = (state) => {+ const kind = state === 'ready' ? 'green'+ : state === 'unhealthy' ? 'amber'+ : state === 'stopped' ? 'gray' : 'red';+ return <Pill kind={kind}>{state || 'not_installed'}</Pill>;+};++const formatDuration = (start, finish) => {+ if (!start || !finish) return '—';+ const ms = new Date(finish).getTime() - new Date(start).getTime();+ if (Number.isNaN(ms) || ms < 0) return '—';+ if (ms < 1000) return `${ms}ms`;+ return `${(ms / 1000).toFixed(1)}s`;+};++const AutomationsPage = () => {+ const toast = useToast();+ const navigate = useNavigate();+ const { tab } = useParams();+ const activeTab = VALID_TABS.includes(tab) ? tab : 'workflows';++ const [busy, setBusy] = useState(false);+ const [confirmDialog, setConfirmDialog] = useState(null);++ // Workflows tab+ const [workflows, setWorkflows] = useState([]);+ const [wfLoading, setWfLoading] = useState(false);+ const [newModal, setNewModal] = useState(false);+ const [newName, setNewName] = useState('');+ const [templateModal, setTemplateModal] = useState(false);+ const [templates, setTemplates] = useState([]);++ // Runs tab+ const [runs, setRuns] = useState([]);+ const [approvals, setApprovals] = useState([]);+ const [runsLoading, setRunsLoading] = useState(false);++ // Settings tab+ const [host, setHost] = useState(null);+ const [settings, setSettings] = useState(null);+ const [settingsLoading, setSettingsLoading] = useState(false);+ const [installPort, setInstallPort] = useState('');+ const [newSecret, setNewSecret] = useState({ name: '', value: '' });+ const [hostPortDraft, setHostPortDraft] = useState('');++ // ── Loaders ──+ const loadWorkflows = useCallback(async () => {+ setWfLoading(true);+ try {+ const data = await api.request('/tramo/workflows');+ setWorkflows(data.workflows || []);+ } catch (error) {+ toast.error(`Could not load workflows: ${error.message}`);+ } finally {+ setWfLoading(false);+ }+ }, [toast]);++ const loadRuns = useCallback(async () => {+ setRunsLoading(true);+ try {+ const [runData, apprData] = await Promise.all([+ api.request('/tramo/runs?limit=100'),+ api.request('/tramo/approvals'),+ ]);+ setRuns(runData.runs || []);+ setApprovals(apprData.approvals || []);+ } catch (error) {+ toast.error(`Could not load runs: ${error.message}`);+ } finally {+ setRunsLoading(false);+ }+ }, [toast]);++ const loadSettings = useCallback(async () => {+ setSettingsLoading(true);+ try {+ const [statusData, settingsData] = await Promise.all([+ api.request('/tramo/host/status'),+ api.request('/tramo/settings'),+ ]);+ setHost(statusData);+ setSettings(settingsData);+ setHostPortDraft(String(settingsData.host_port ?? statusData.host_port ?? ''));+ } catch (error) {+ toast.error(`Could not load settings: ${error.message}`);+ } finally {+ setSettingsLoading(false);+ }+ }, [toast]);++ useEffect(() => {+ if (activeTab === 'workflows') loadWorkflows();+ else if (activeTab === 'runs') loadRuns();+ else if (activeTab === 'settings') loadSettings();+ }, [activeTab, loadWorkflows, loadRuns, loadSettings]);++ // ── Workflow actions ──+ const handleCreate = async () => {+ if (!newName.trim()) { toast.error('Name is required.'); return; }+ setBusy(true);+ try {+ const wf = await api.request('/tramo/workflows', { method: 'POST', body: { name: newName.trim() } });+ setNewModal(false);+ setNewName('');+ toast.success(`Workflow "${wf.name}" created`);+ navigate(`/automations/edit/${wf.slug}`);+ } catch (error) {+ toast.error(`Could not create workflow: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const openTemplateModal = async () => {+ setTemplateModal(true);+ try {+ const data = await api.request('/tramo/templates');+ setTemplates(data.templates || []);+ } catch (error) {+ toast.error(`Could not load templates: ${error.message}`);+ }+ };++ const handleFromTemplate = async (template) => {+ setBusy(true);+ try {+ const wf = await api.request(`/tramo/workflows/from-template/${template.id}`, { method: 'POST', body: {} });+ setTemplateModal(false);+ toast.success(`Created "${wf.name}" from ${template.name}`);+ navigate(`/automations/edit/${wf.slug}`);+ } catch (error) {+ toast.error(`Could not create from template: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleToggleEnabled = async (wf) => {+ try {+ await api.request(`/tramo/workflows/${wf.slug}`, { method: 'PUT', body: { enabled: !wf.enabled } });+ await loadWorkflows();+ } catch (error) {+ toast.error(`Could not update workflow: ${error.message}`);+ }+ };++ const handleDeleteWorkflow = (wf) => {+ setConfirmDialog({+ title: `Delete ${wf.name}?`,+ message: 'This removes the workflow and its stored document. Deployed runs already recorded are kept.',+ confirmText: 'Delete',+ variant: 'danger',+ onConfirm: async () => {+ setConfirmDialog(null);+ try {+ await api.request(`/tramo/workflows/${wf.slug}`, { method: 'DELETE' });+ toast.success('Workflow deleted');+ await loadWorkflows();+ } catch (error) {+ toast.error(error.message);+ }+ },+ onCancel: () => setConfirmDialog(null),+ });+ };++ const handleDeploy = async () => {+ setBusy(true);+ try {+ const res = await api.request('/tramo/deploy', { method: 'POST' });+ toast.success(res?.message || 'Deployed to the tramo engine');+ await loadWorkflows();+ } catch (error) {+ toast.error(`Deploy failed: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleRunWorkflow = async (wf) => {+ setBusy(true);+ try {+ const res = await api.request(`/tramo/workflows/${wf.slug}/run`, { method: 'POST', body: {} });+ const status = res?.run?.status || res?.result?.status || 'started';+ toast.success(`Run ${status} — see the Runs tab`);+ } catch (error) {+ toast.error(`Run failed: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ // ── Run actions ──+ const handleApprove = async (runId) => {+ setBusy(true);+ try {+ await api.request(`/tramo/runs/${runId}/approve`, { method: 'POST', body: {} });+ toast.success('Approved');+ await loadRuns();+ } catch (error) {+ toast.error(`Approve failed: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleReplay = async (runId) => {+ setBusy(true);+ try {+ await api.request(`/tramo/runs/${runId}/replay`, { method: 'POST' });+ toast.success('Replay queued');+ await loadRuns();+ } catch (error) {+ toast.error(`Replay failed: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ // ── Host / settings actions ──+ const handleInstall = async () => {+ setBusy(true);+ try {+ const body = installPort ? { host_port: Number(installPort) } : {};+ await api.request('/tramo/host/install', { method: 'POST', body });+ toast.success('tramo engine installed');+ setInstallPort('');+ await loadSettings();+ } catch (error) {+ toast.error(`Install failed: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleUninstall = (keepData) => {+ setConfirmDialog({+ title: 'Remove tramo engine',+ message: keepData+ ? 'Remove the tramo container? Workflow data stays on disk and a reinstall picks it back up.'+ : 'Remove the tramo container AND delete all engine data? This cannot be undone.',+ confirmText: 'Remove',+ variant: 'danger',+ onConfirm: async () => {+ setConfirmDialog(null);+ try {+ await api.request(`/tramo/host/install?keep_data=${keepData}`, { method: 'DELETE' });+ toast.success('tramo engine removed');+ await loadSettings();+ } catch (error) {+ toast.error(`Uninstall failed: ${error.message}`);+ }+ },+ onCancel: () => setConfirmDialog(null),+ });+ };++ const handleControl = async (action) => {+ setBusy(true);+ try {+ await api.request(`/tramo/host/control/${action}`, { method: 'POST' });+ toast.success(`Engine ${action} requested`);+ await loadSettings();+ } catch (error) {+ toast.error(`Could not ${action} engine: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleAddSecret = async () => {+ if (!newSecret.name.trim() || !newSecret.value) { toast.error('Name and value are required.'); return; }+ setBusy(true);+ try {+ await api.request('/tramo/settings', {+ method: 'PUT',+ body: { pack_secrets: { [newSecret.name.trim()]: newSecret.value } },+ });+ toast.success(`Secret ${newSecret.name.trim()} saved`);+ setNewSecret({ name: '', value: '' });+ await loadSettings();+ } catch (error) {+ toast.error(`Could not save secret: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleToggleBridge = async () => {+ setBusy(true);+ try {+ await api.request('/tramo/settings', {+ method: 'PUT',+ body: { events_bridge_enabled: !settings?.events_bridge_enabled },+ });+ await loadSettings();+ } catch (error) {+ toast.error(`Could not update events bridge: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ const handleSaveHostPort = async () => {+ const port = Number(hostPortDraft);+ if (!port) { toast.error('Enter a valid port.'); return; }+ setBusy(true);+ try {+ await api.request('/tramo/settings', { method: 'PUT', body: { host_port: port } });+ toast.success('Host port updated');+ await loadSettings();+ } catch (error) {+ toast.error(`Could not update host port: ${error.message}`);+ } finally {+ setBusy(false);+ }+ };++ // ── Renderers ──+ const renderWorkflows = () => (+ <div className="card sec-flush">+ <div className="card-header">+ <h3>Workflows {workflows.length > 0 && <span className="sec-count">· {workflows.length}</span>}</h3>+ <div className="card-actions tramo-toolbar">+ <Button variant="outline" size="sm" onClick={handleDeploy} disabled={busy}>+ <Rocket size={14} /> Deploy+ </Button>+ <Button variant="secondary" size="sm" onClick={openTemplateModal}>+ <LayoutTemplate size={14} /> New from template+ </Button>+ <Button variant="default" size="sm" onClick={() => { setNewName(''); setNewModal(true); }}>+ <Plus size={14} /> New workflow+ </Button>+ </div>+ </div>+ <div className="card-body">+ {wfLoading ? <EmptyState loading title="Loading workflows..." />+ : workflows.length === 0 ? (+ <EmptyState+ icon={Workflow}+ title="No automations yet"+ description="Create a workflow on the visual canvas, or start from a template. Enable it and deploy to run it headless on the tramo engine."+ />+ ) : (+ <table className="sk-dtable">+ <thead>+ <tr>+ <th>Name</th><th>Enabled</th><th>State</th><th>Version</th><th>Updated</th><th /></tr>+ </thead>+ <tbody>+ {workflows.map((wf) => (+ <tr key={wf.id ?? wf.slug}>+ <td className="sk-cell-mono">{wf.name}</td>+ <td>+ <button+ type="button"+ className={`tramo-toggle${wf.enabled ? ' tramo-toggle--on' : ''}`}+ onClick={() => handleToggleEnabled(wf)}+ aria-pressed={wf.enabled}+ title={wf.enabled ? 'Disable' : 'Enable'}+ >+ <span className="tramo-toggle__knob" />+ </button>+ </td>+ <td>+ {wf.dirty+ ? <Pill kind="amber" title="Edited since last deploy">undeployed</Pill>+ : <Pill kind="green">deployed</Pill>}+ </td>+ <td className="sk-cell-mono">{wf.doc_version ?? '—'}</td>+ <td className="sk-cell-mono">{wf.updated_at ? new Date(wf.updated_at).toLocaleString() : '—'}</td>+ <td className="tramo-row-actions">+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleRunWorkflow(wf)} title="Run now">+ <Play size={14} />+ </Button>+ <Button variant="secondary" size="sm" onClick={() => navigate(`/automations/edit/${wf.slug}`)} title="Edit">+ <Pencil size={14} />+ </Button>+ <Button variant="destructive" size="sm" onClick={() => handleDeleteWorkflow(wf)} title="Delete">+ <Trash2 size={14} />+ </Button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ </div>+ );++ const renderRuns = () => (+ <>+ {approvals.length > 0 && (+ <div className="card tramo-approvals">+ <div className="card-header">+ <h3>Pending approvals <span className="sec-count">· {approvals.length}</span></h3>+ </div>+ <div className="card-body">+ {approvals.map((a) => (+ <div className="tramo-approval" key={a.run_id}>+ <div className="tramo-approval__info">+ <span className="sk-cell-mono">{a.workflow_slug || a.workflow || '—'}</span>+ <span className="text-muted">{a.node || a.message || 'Awaiting approval'}</span>+ </div>+ <Button variant="default" size="sm" disabled={busy} onClick={() => handleApprove(a.run_id)}>+ <CheckCircle2 size={14} /> Approve+ </Button>+ </div>+ ))}+ </div>+ </div>+ )}+ <div className="card sec-flush">+ <div className="card-header">+ <h3>Runs {runs.length > 0 && <span className="sec-count">· {runs.length}</span>}</h3>+ <div className="card-actions">+ <Button variant="outline" size="sm" onClick={loadRuns} disabled={runsLoading}>+ <RefreshCw size={14} /> Refresh+ </Button>+ </div>+ </div>+ <div className="card-body">+ {runsLoading ? <EmptyState loading title="Loading runs..." />+ : runs.length === 0 ? (+ <EmptyState icon={Play} title="No runs yet" description="Deploy an enabled workflow, then trigger it or wait for a matching event." />+ ) : (+ <table className="sk-dtable">+ <thead>+ <tr>+ <th>Status</th><th>Workflow</th><th>Source</th><th>Duration</th><th>Tokens</th><th>Error</th><th /></tr>+ </thead>+ <tbody>+ {runs.map((r) => (+ <tr key={r.run_id}>+ <td>{runPill(r.status)}</td>+ <td className="sk-cell-mono">{r.workflow_slug || '—'}</td>+ <td><Pill kind="gray">{r.source || 'manual'}</Pill></td>+ <td className="sk-cell-mono">{formatDuration(r.started_at, r.finished_at)}</td>+ <td className="sk-cell-mono">{r.usage?.total_tokens ?? r.usage?.tokens ?? '—'}</td>+ <td className="sk-cell-mono tramo-truncate" title={r.error || ''}>{r.error || '—'}</td>+ <td className="tramo-row-actions">+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleReplay(r.run_id)} title="Replay">+ <RefreshCw size={14} />+ </Button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ </div>+ </>+ );++ const renderSettings = () => {+ const state = host?.state || 'not_installed';+ const installed = !!host?.installed;+ const notSupported = !installed && !!host?.error;+ return (+ <>+ <div className="card">+ <div className="card-header">+ <h3><Server size={16} /> Automation engine</h3>+ <div className="card-actions">+ <Button variant="outline" size="sm" onClick={loadSettings} disabled={settingsLoading}>+ <RefreshCw size={14} /> Refresh+ </Button>+ </div>+ </div>+ <div className="card-body">+ {settingsLoading && !host ? <EmptyState loading title="Loading engine status..." /> : (+ <>+ <div className="sec-rows">+ <div className="sk-info-row">+ <span className="k">Status</span>+ {hostPill(state)}+ </div>+ <div className="sk-info-row">+ <span className="k">Container</span>+ <span className="v sk-cell-mono">{host?.container || '—'}</span>+ </div>+ <div className="sk-info-row">+ <span className="k">Image</span>+ <span className="v sk-cell-mono">{host?.image || '—'}</span>+ </div>+ <div className="sk-info-row">+ <span className="k">Host port</span>+ <span className="v sk-cell-mono">{host?.host_port ?? '—'}</span>+ </div>+ {host?.version && (+ <div className="sk-info-row">+ <span className="k">Version</span>+ <span className="v sk-cell-mono">{host.version}</span>+ </div>+ )}+ </div>++ {notSupported && (+ <div className="tramo-note">+ Docker is required to run the tramo engine, and it is not available on this+ host (the engine does not run on Windows dev boxes). You can still design+ workflows; deploying and running them needs a Linux host with Docker.+ <div className="tramo-note__detail">{host.error}</div>+ </div>+ )}++ <div className="tramo-host-actions">+ {!installed ? (+ <div className="tramo-install">+ <div className="form-group">+ <Label>Host port (optional)</Label>+ <Input+ type="number"+ value={installPort}+ placeholder={String(host?.host_port ?? 3737)}+ onChange={(e) => setInstallPort(e.target.value)}+ />+ </div>+ <Button variant="default" size="sm" onClick={handleInstall} disabled={busy}>+ <Power size={14} /> Install engine+ </Button>+ </div>+ ) : (+ <>+ <Button variant="outline" size="sm" onClick={() => handleControl('restart')} disabled={busy}>+ <RefreshCw size={14} /> Restart+ </Button>+ {host?.running ? (+ <Button variant="outline" size="sm" onClick={() => handleControl('stop')} disabled={busy}>+ <Power size={14} /> Stop+ </Button>+ ) : (+ <Button variant="default" size="sm" onClick={() => handleControl('start')} disabled={busy}>+ <Power size={14} /> Start+ </Button>+ )}+ <Button variant="secondary" size="sm" onClick={() => handleUninstall(true)} disabled={busy}>+ Remove (keep data)+ </Button>+ <Button variant="destructive" size="sm" onClick={() => handleUninstall(false)} disabled={busy}>+ <Trash2 size={14} /> Remove + data+ </Button>+ </>+ )}+ </div>+ </>+ )}+ </div>+ </div>++ <div className="card">+ <div className="card-header"><h3>Engine settings</h3></div>+ <div className="card-body tramo-settings">+ <div className="tramo-field">+ <div className="tramo-field__label">+ <Label>Events bridge</Label>+ <p className="text-muted">Forward panel events to tramo so workflows can react to them.</p>+ </div>+ <button+ type="button"+ className={`tramo-toggle${settings?.events_bridge_enabled ? ' tramo-toggle--on' : ''}`}+ onClick={handleToggleBridge}+ disabled={busy}+ aria-pressed={!!settings?.events_bridge_enabled}+ >+ <span className="tramo-toggle__knob" />+ </button>+ </div>+ <div className="tramo-field tramo-field--inline">+ <div className="tramo-field__label">+ <Label>Host port</Label>+ <p className="text-muted">Port the tramo container is published on.</p>+ </div>+ <div className="tramo-field__control">+ <Input type="number" value={hostPortDraft} onChange={(e) => setHostPortDraft(e.target.value)} />+ <Button variant="secondary" size="sm" onClick={handleSaveHostPort} disabled={busy}>Save</Button>+ </div>+ </div>+ </div>+ </div>++ <div className="card sec-flush">+ <div className="card-header">+ <h3><KeyRound size={16} /> Pack secrets</h3>+ </div>+ <div className="card-body">+ <p className="text-muted">+ Credentials integration packs need (API keys, tokens). Values are write-only — they are+ stored encrypted and never shown again after saving.+ </p>+ {(settings?.pack_secret_names?.length ?? 0) === 0 ? (+ <p className="text-muted">No pack secrets set yet.</p>+ ) : (+ <div className="tramo-secret-list">+ {settings.pack_secret_names.map((name) => (+ <div className="tramo-secret" key={name}>+ <span className="sk-cell-mono">{name}</span>+ <Pill kind="green">set</Pill>+ </div>+ ))}+ </div>+ )}+ <div className="tramo-secret-add">+ <div className="form-group">+ <Label>Name</Label>+ <Input+ type="text"+ value={newSecret.name}+ placeholder="TELEGRAM_BOT_TOKEN"+ onChange={(e) => setNewSecret((s) => ({ ...s, name: e.target.value }))}+ />+ </div>+ <div className="form-group">+ <Label>Value</Label>+ <Input+ type="password"+ value={newSecret.value}+ onChange={(e) => setNewSecret((s) => ({ ...s, value: e.target.value }))}+ />+ </div>+ <Button variant="default" size="sm" onClick={handleAddSecret} disabled={busy}>+ <Plus size={14} /> Add secret+ </Button>+ </div>+ </div>+ </div>+ </>+ );+ };++ const topbarTabs = TABS.map(({ to, label, end }) => ({ to, label, end }));++ return (+ <div className="page-container tramo-page">+ <PageTopbar+ icon={<Workflow size={18} />}+ title="Automations"+ meta={<>tramo · workflows · triggers · integrations</>}+ tabs={topbarTabs}+ actions={+ <Button variant="default" size="sm" onClick={() => { setNewName(''); setNewModal(true); }}>+ <Plus size={14} /> New workflow+ </Button>+ }+ />++ {activeTab === 'workflows' && renderWorkflows()}+ {activeTab === 'runs' && renderRuns()}+ {activeTab === 'settings' && renderSettings()}++ {/* New workflow modal */}+ <Modal open={newModal} onClose={() => setNewModal(false)} title="New workflow">+ <div className="form-group">+ <Label>Name</Label>+ <Input+ type="text"+ value={newName}+ placeholder="Notify on deploy"+ onChange={(e) => setNewName(e.target.value)}+ onKeyDown={(e) => { if (e.key === 'Enter') handleCreate(); }}+ />+ <p className="text-muted">You will land on the visual editor to design the flow.</p>+ </div>+ <div className="modal-footer">+ <Button variant="outline" onClick={() => setNewModal(false)}>Cancel</Button>+ <Button variant="default" onClick={handleCreate} disabled={busy || !newName.trim()}>Create</Button>+ </div>+ </Modal>++ {/* New from template modal */}+ <Modal open={templateModal} onClose={() => setTemplateModal(false)} title="New from template">+ {templates.length === 0 ? (+ <EmptyState icon={LayoutTemplate} title="No templates available" />+ ) : (+ <div className="tramo-template-list">+ {templates.map((t) => (+ <button+ type="button"+ className="tramo-template"+ key={t.id}+ onClick={() => handleFromTemplate(t)}+ disabled={busy}+ >+ <span className="tramo-template__name">{t.name}</span>+ {t.description && <span className="tramo-template__desc">{t.description}</span>}+ </button>+ ))}+ </div>+ )}+ <div className="modal-footer">+ <Button variant="outline" onClick={() => setTemplateModal(false)}><X size={14} /> Close</Button>+ </div>+ </Modal>++ {confirmDialog && (+ <ConfirmDialog+ title={confirmDialog.title}+ message={confirmDialog.message}+ confirmText={confirmDialog.confirmText}+ variant={confirmDialog.variant}+ onConfirm={confirmDialog.onConfirm}+ onCancel={confirmDialog.onCancel}+ />+ )}+ </div>+ );+};++export { AutomationsPage };+export default AutomationsPage;diff --git a/frontend/src/plugins/serverkit-tramo/components/TramoEditor.jsx b/frontend/src/plugins/serverkit-tramo/components/TramoEditor.jsxnew file mode 100644index 00000000..3cf7f3f7--- /dev/null+++ b/frontend/src/plugins/serverkit-tramo/components/TramoEditor.jsx@@ -0,0 +1,62 @@+// TramoEditor — the heavy editor chunk.+//+// Everything tramo-visual lives behind this module so it code-splits away from+// the panel entry bundle. AutomationEditorPage React.lazy()-imports it; nothing+// on the entry path may import this file (or tramo/react / tramo/styles.css)+// statically, or the split collapses.+import { useEffect } from 'react';+import { Canvas, RightRail, useWorkflow } from 'tramo/react';+import api from '@/services/api';+import EmptyState from '@/components/EmptyState';+import { registry } from '../registry.js';++// tramo's own canvas + inspector CSS. Imported here (inside the lazy chunk) so+// it ships with the editor, not the entry bundle.+import 'tramo/styles.css';++const TramoEditor = ({ slug, onSaveStateChange }) => {+ const handle = useWorkflow({+ registry,+ key: slug,+ loadDoc: async () => {+ const data = await api.request(`/tramo/workflows/${slug}`);+ return data.doc || { name: slug, nodes: [], edges: [] };+ },+ saveDoc: async (doc) => {+ await api.request(`/tramo/workflows/${slug}`, { method: 'PUT', body: { doc } });+ },+ });++ // Surface the debounced save lifecycle up to the page's top strip.+ useEffect(() => {+ if (onSaveStateChange) onSaveStateChange(handle.saveState);+ }, [handle.saveState, onSaveStateChange]);++ if (!handle.ready) {+ return (+ <div className="tramo-editor__loading">+ <EmptyState loading title="Loading workflow..." />+ </div>+ );+ }++ return (+ <div className="tramo-editor">+ <div className="tramo-editor__canvas">+ <Canvas workflow={handle} />+ </div>+ <div className="tramo-editor__rail">+ <RightRail+ selection={handle.selection}+ registry={handle.registry}+ onApply={handle.applyPatch}+ onClose={handle.clearSelection}+ saveState={handle.saveState}+ doc={handle.doc}+ />+ </div>+ </div>+ );+};++export default TramoEditor;diff --git a/frontend/src/plugins/serverkit-tramo/index.jsx b/frontend/src/plugins/serverkit-tramo/index.jsxnew file mode 100644index 00000000..12933af4--- /dev/null+++ b/frontend/src/plugins/serverkit-tramo/index.jsx@@ -0,0 +1,12 @@+// Automations (tramo) UI, contributed through the extension system. Fully+// self-contained in the extension. After sync this folder lives at+// frontend/src/plugins/serverkit-tramo/, so '@/…' host aliases resolve.+//+// plugin.json declares two route components — AutomationsPage (the tabbed+// list/runs/settings surface) and AutomationEditorPage (the full-bleed canvas).+// Both are resolved by name from these exports.+export { AutomationsPage } from './components/AutomationsPage.jsx';+export { AutomationEditorPage } from './components/AutomationEditorPage.jsx';++// No default export on purpose: PluginLoader legacy-auto-renders any plugin+// default export globally. The route contributions resolve the NAMED exports.diff --git a/frontend/src/plugins/serverkit-tramo/plugin.json b/frontend/src/plugins/serverkit-tramo/plugin.jsonnew file mode 100644index 00000000..9ca621ce--- /dev/null+++ b/frontend/src/plugins/serverkit-tramo/plugin.json@@ -0,0 +1,84 @@+{+ "name": "serverkit-tramo",+ "display_name": "Automations",+ "version": "1.0.0",+ "description": "Node-based automation builder powered by tramo. Design workflows on a visual canvas (triggers, actions, branches, loops, approval gates) that react to panel events or run on a schedule, with 21 brand integration packs (Telegram, GitHub, Gmail, Discord, Notion, Stripe, Cloudflare, Postgres, Twilio and more). Enabled workflows deploy to a managed tramo container on the panel host that runs them headless, with run history, approvals, and inbound webhooks proxied through the panel. This replaces the older drag-and-drop Workflow Builder.",+ "author": "ServerKit",+ "license": "MIT",+ "category": "deployment",+ "homepage": "https://github.com/jhd3197/ServerKit",+ "permissions": [+ "docker",+ "shell",+ "filesystem",+ "network"+ ],+ "min_panel_version": "1.7.0",+ "entry_point": "tramo:tramo_bp",+ "url_prefix": "/api/v1/tramo",+ "models": "models:register",+ "lifecycle": {+ "install": "lifecycle:on_install",+ "uninstall": "lifecycle:on_uninstall"+ },+ "jobs": [+ {+ "kind": "tramo.harvest_runs",+ "handler": "jobs:harvest_runs"+ },+ {+ "kind": "tramo.health_check",+ "handler": "jobs:health_check"+ }+ ],+ "schedules": [+ {+ "name": "tramo-harvest-runs",+ "kind": "tramo.harvest_runs",+ "interval_seconds": 120+ },+ {+ "name": "tramo-health-check",+ "kind": "tramo.health_check",+ "interval_seconds": 300+ }+ ],+ "icon": "<circle cx=\"18\" cy=\"5\" r=\"3\"/><circle cx=\"6\" cy=\"12\" r=\"3\"/><circle cx=\"18\" cy=\"19\" r=\"3\"/><path d=\"M8.59 13.51l6.83 3.98\"/><path d=\"M15.41 6.51l-6.82 3.98\"/>",+ "contributions": {+ "nav": [+ {+ "id": "automations",+ "label": "Automations",+ "route": "/automations",+ "category": "operations",+ "icon": "<circle cx=\"18\" cy=\"5\" r=\"3\"/><circle cx=\"6\" cy=\"12\" r=\"3\"/><circle cx=\"18\" cy=\"19\" r=\"3\"/><path d=\"M8.59 13.51l6.83 3.98\"/><path d=\"M15.41 6.51l-6.82 3.98\"/>"+ }+ ],+ "routes": [+ {+ "path": "automations",+ "component": "AutomationsPage"+ },+ {+ "path": "automations/:tab",+ "component": "AutomationsPage"+ },+ {+ "path": "automations/edit/:slug",+ "component": "AutomationEditorPage",+ "layout": "full"+ }+ ],+ "page_titles": {+ "/automations": "Automations"+ },+ "command_palette": [+ {+ "label": "Automations",+ "path": "/automations",+ "category": "Pages",+ "keywords": "automation workflow tramo trigger action schedule webhook telegram github integration pipeline event"+ }+ ]+ }+}diff --git a/frontend/src/plugins/serverkit-tramo/registry.js b/frontend/src/plugins/serverkit-tramo/registry.jsnew file mode 100644index 00000000..3a6cc291--- /dev/null+++ b/frontend/src/plugins/serverkit-tramo/registry.js@@ -0,0 +1,69 @@+// Node registry for the tramo editor.+//+// tramo ships its node definitions as "packs": the built-in pack plus one pack+// per brand integration. `combinePacks` merges them into a single registry of+// editor-side node definitions (`.nodes`) and runtime executors (`.executors`).+// The editor only needs `.nodes` — executors run server-side inside the managed+// tramo container, never in the browser.+//+// This module is imported by TramoEditor.jsx (the lazy chunk) so all of these+// integration packs code-split into the editor bundle and never reach the+// panel's entry bundle.+import { combinePacks, BUILTIN_PACK } from 'tramo/runtime';++import gmail from 'tramo/integrations/gmail';+import github from 'tramo/integrations/github';+import telegram from 'tramo/integrations/telegram';+import discord from 'tramo/integrations/discord';+import notion from 'tramo/integrations/notion';+import openai from 'tramo/integrations/openai';+import anthropic from 'tramo/integrations/anthropic';+import linear from 'tramo/integrations/linear';+import airtable from 'tramo/integrations/airtable';+import stripe from 'tramo/integrations/stripe';+import cloudflare from 'tramo/integrations/cloudflare';+import googleDrive from 'tramo/integrations/google-drive';+import googleSheets from 'tramo/integrations/google-sheets';+import googleTasks from 'tramo/integrations/google-tasks';+import outlook from 'tramo/integrations/outlook';+import postgres from 'tramo/integrations/postgres';+import twilio from 'tramo/integrations/twilio';+import youtube from 'tramo/integrations/youtube';+import x from 'tramo/integrations/x';+import trello from 'tramo/integrations/trello';+import box from 'tramo/integrations/box';++// TODO(plan45): add SERVERKIT_PACK once @tramo/serverkit is published. Its+// executors run server-side; the editor only needs its node definitions here.++// Order matters only for the palette; combinePacks throws on id collisions, so+// the brand packs are all distinct by construction.+export const combined = combinePacks([+ BUILTIN_PACK,+ gmail,+ github,+ telegram,+ discord,+ notion,+ openai,+ anthropic,+ linear,+ airtable,+ stripe,+ cloudflare,+ googleDrive,+ googleSheets,+ googleTasks,+ outlook,+ postgres,+ twilio,+ youtube,+ x,+ trello,+ box,+]);++// The editor-side registry of node definitions. Pass straight to useWorkflow.+export const registry = combined.nodes;++export default registry;diff --git a/frontend/src/plugins/serverkit-tramo/styles/tramo-automations.scss b/frontend/src/plugins/serverkit-tramo/styles/tramo-automations.scssnew file mode 100644index 00000000..d0afd6b4--- /dev/null+++ b/frontend/src/plugins/serverkit-tramo/styles/tramo-automations.scss@@ -0,0 +1,363 @@+/* Automations (tramo) extension — layout-only styles. Colours, typography,+ spacing and controls all inherit from the host design system (card,+ sk-dtable, sk-info-row, Pill, empty-state, form controls). Plugin SCSS is+ compiled in isolation, so we lean on CSS custom properties (var(--…)) and+ neutral rgba tints — never SCSS $variables, which aren't in scope here.+ We never restyle tramo's own .tr-* classes; the editor owns those. */++.tramo-page {+ .tramo-toolbar {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+ }++ .tramo-row-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ justify-content: flex-end;+ }++ .tramo-truncate {+ max-width: 280px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ /* Pending-approval strip */+ .tramo-approvals {+ margin-bottom: 16px;+ }++ .tramo-approval {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 10px 0;+ border-bottom: 1px solid rgba(128, 128, 128, 0.16);++ &:last-child {+ border-bottom: 0;+ }++ &__info {+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+ }+ }++ /* Unsupported / Docker-required note */+ .tramo-note {+ margin-top: 14px;+ padding: 12px 14px;+ border-radius: var(--radius, 8px);+ border: 1px solid rgba(234, 179, 8, 0.35);+ background: rgba(234, 179, 8, 0.08);+ font-size: 13px;+ line-height: 1.5;++ &__detail {+ margin-top: 8px;+ font-family: var(--mono, ui-monospace, SFMono-Regular, Menlo, monospace);+ font-size: 12px;+ opacity: 0.75;+ word-break: break-word;+ }+ }++ /* Engine host actions */+ .tramo-host-actions {+ display: flex;+ align-items: flex-end;+ flex-wrap: wrap;+ gap: 8px;+ margin-top: 16px;+ }++ .tramo-install {+ display: flex;+ align-items: flex-end;+ gap: 8px;++ .form-group {+ margin: 0;+ min-width: 180px;+ }+ }++ /* Settings fields */+ .tramo-settings {+ display: flex;+ flex-direction: column;+ gap: 4px;+ }++ .tramo-field {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ padding: 12px 0;+ border-bottom: 1px solid rgba(128, 128, 128, 0.14);++ &:last-child {+ border-bottom: 0;+ }++ &__label {+ min-width: 0;++ p {+ margin: 2px 0 0;+ }+ }++ &__control {+ display: flex;+ align-items: center;+ gap: 8px;++ input {+ width: 140px;+ }+ }+ }++ /* Pack secrets */+ .tramo-secret-list {+ display: flex;+ flex-direction: column;+ gap: 6px;+ margin: 12px 0;+ }++ .tramo-secret {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 8px 12px;+ border-radius: var(--radius-sm, 6px);+ background: rgba(128, 128, 128, 0.06);+ }++ .tramo-secret-add {+ display: flex;+ align-items: flex-end;+ gap: 8px;+ flex-wrap: wrap;+ margin-top: 12px;+ padding-top: 12px;+ border-top: 1px solid rgba(128, 128, 128, 0.14);++ .form-group {+ margin: 0;+ min-width: 200px;+ flex: 1;+ }+ }++ /* Enable toggle (also used in the settings events-bridge field) */+ .tramo-toggle {+ --tramo-toggle-w: 38px;+ --tramo-toggle-h: 22px;+ position: relative;+ width: var(--tramo-toggle-w);+ height: var(--tramo-toggle-h);+ border-radius: 999px;+ border: 0;+ cursor: pointer;+ padding: 0;+ background: rgba(128, 128, 128, 0.35);+ transition: background 0.15s ease;++ &__knob {+ position: absolute;+ top: 2px;+ left: 2px;+ width: calc(var(--tramo-toggle-h) - 4px);+ height: calc(var(--tramo-toggle-h) - 4px);+ border-radius: 50%;+ background: #fff;+ transition: transform 0.15s ease;+ }++ &--on {+ background: var(--accent-bright, #3b82f6);++ .tramo-toggle__knob {+ transform: translateX(calc(var(--tramo-toggle-w) - var(--tramo-toggle-h)));+ }+ }++ &:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+ }++ /* Template picker (inside the modal) */+ .tramo-template-list {+ display: flex;+ flex-direction: column;+ gap: 8px;+ }++ .tramo-template {+ display: flex;+ flex-direction: column;+ gap: 3px;+ text-align: left;+ width: 100%;+ padding: 12px 14px;+ border-radius: var(--radius, 8px);+ border: 1px solid var(--border, rgba(128, 128, 128, 0.3));+ background: transparent;+ color: inherit;+ cursor: pointer;+ transition: border-color 0.15s ease, background 0.15s ease;++ &:hover {+ border-color: var(--accent-bright, #3b82f6);+ background: rgba(128, 128, 128, 0.06);+ }++ &:disabled {+ opacity: 0.6;+ cursor: not-allowed;+ }++ &__name {+ font-weight: 600;+ }++ &__desc {+ font-size: 12.5px;+ opacity: 0.7;+ }+ }+}++/* ── Full-bleed editor page (route automations/edit/:slug, layout "full") ── */+.tramo-editor-page {+ height: 100%;+ min-height: 0;+ display: flex;+ flex-direction: column;+ background: var(--bg-body, transparent);++ &__bar {+ flex-shrink: 0;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 10px 16px;+ border-bottom: 1px solid var(--border, rgba(128, 128, 128, 0.25));+ background: var(--bg-card, transparent);+ }++ &__left {+ display: flex;+ align-items: center;+ gap: 12px;+ min-width: 0;+ }++ &__title {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+ }++ &__name {+ font-weight: 600;+ font-size: 15px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ max-width: 320px;+ }++ &__actions {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-shrink: 0;+ }++ &__body {+ flex: 1;+ min-height: 0;+ position: relative;+ }+}++/* Save-state indicator in the editor top strip */+.tramo-save {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ font-size: 12.5px;++ &--busy { color: var(--text-dim, #9aa0a6); }+ &--ok { color: var(--green, #22c55e); }+ &--err { color: var(--red, #ef4444); }+ &--idle { color: var(--text-dim, #9aa0a6); opacity: 0.7; }+}++.tramo-spin {+ animation: tramo-spin 0.9s linear infinite;+}++@keyframes tramo-spin {+ to { transform: rotate(360deg); }+}++@media (prefers-reduced-motion: reduce) {+ .tramo-spin { animation: none; }+}++/* ── Editor composition: canvas fills, inspector rail is fixed-width ── */+.tramo-editor {+ position: absolute;+ inset: 0;+ display: flex;+ min-height: 0;++ &__canvas {+ position: relative;+ flex: 1;+ min-width: 0;+ min-height: 0;+ overflow: hidden;+ }++ &__rail {+ flex-shrink: 0;+ width: 340px;+ min-height: 0;+ overflow-y: auto;+ border-left: 1px solid var(--border, rgba(128, 128, 128, 0.25));+ background: var(--bg-card, transparent);+ }++ &__loading {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ }++ @media (max-width: 768px) {+ &__rail { width: 260px; }+ }+}