Agent Zero AI framework
feat: add test connection button in config UI, restyle add handler button
linuztx96cc2cd1982b
diff --git a/plugins/_email_integration/api/test_connection.py b/plugins/_email_integration/api/test_connection.pynew file mode 100644index 000000000..8daa70d7e--- /dev/null+++ b/plugins/_email_integration/api/test_connection.py@@ -0,0 +1,78 @@+"""Test IMAP/SMTP connection for an email handler config."""++from helpers.api import ApiHandler, Request+from helpers.errors import format_error++from plugins._email_integration.helpers.imap_client import (+ connect_imap,+ disconnect_imap,+ get_highest_uid,+)+from plugins._email_integration.helpers.smtp_client import SmtpConfig, send_reply+++class TestConnection(ApiHandler):++ async def process(self, input: dict, request: Request) -> dict:+ handler = input.get("handler", {})+ results: list[dict] = []+ account_type = handler.get("account_type", "imap")++ if account_type == "imap":+ await self._test_imap(handler, results)+ await self._test_smtp(handler, results)++ ok = all(r["ok"] for r in results)+ return {"success": ok, "results": results}++ async def _test_imap(self, handler: dict, results: list[dict]):+ try:+ client = await connect_imap(+ server=handler.get("imap_server", ""),+ port=int(handler.get("imap_port", 993)),+ username=handler.get("username", ""),+ password=handler.get("password", ""),+ )+ uid = await get_highest_uid(client)+ await disconnect_imap(client)+ results.append({+ "test": "IMAP",+ "ok": True,+ "message": f"Connected, highest UID: {uid}",+ })+ except Exception as e:+ results.append({+ "test": "IMAP",+ "ok": False,+ "message": format_error(e),+ })++ async def _test_smtp(self, handler: dict, results: list[dict]):+ try:+ smtp_server = handler.get("smtp_server") or handler.get("imap_server", "")+ cfg = SmtpConfig(+ server=smtp_server,+ port=int(handler.get("smtp_port", 587)),+ username=handler.get("username", ""),+ password=handler.get("password", ""),+ )+ error = await send_reply(+ config=cfg,+ to=handler.get("username", ""),+ subject="Agent Zero - Connection Test",+ body="SMTP connection test successful.",+ )+ if error:+ results.append({"test": "SMTP", "ok": False, "message": error})+ else:+ results.append({+ "test": "SMTP",+ "ok": True,+ "message": "Connected, test email sent to self",+ })+ except Exception as e:+ results.append({+ "test": "SMTP",+ "ok": False,+ "message": format_error(e),+ })diff --git a/plugins/_email_integration/test_connection.py b/plugins/_email_integration/test_connection.pydeleted file mode 100644index ed7ab8b15..000000000--- a/plugins/_email_integration/test_connection.py+++ /dev/null@@ -1,111 +0,0 @@-"""-Email integration connection test.-Usage: [email protected] EMAIL_PASS=xxxx python plugins/_email_integration/test_connection.py--Tests:- 1. IMAP connect + get highest UID (baseline)- 2. Fetch new emails since that UID (should be 0 on first run)- 3. SMTP send test email to self- 4. Fetch again (should find the test email)-"""--import asyncio-import os-import sys--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/../..")--from plugins._email_integration.helpers.imap_client import (- connect_imap,- disconnect_imap,- fetch_new,- get_highest_uid,-)-from plugins._email_integration.helpers.smtp_client import SmtpConfig, send_reply---async def test_full_flow(user: str, password: str):- print(f"\n--- Full Flow Test ({user}) ---\n")-- # Step 1: Connect and get baseline UID- client = await connect_imap(- server="imap.gmail.com", port=993,- username=user, password=password,- )- print("[OK] IMAP login")-- baseline_uid = await get_highest_uid(client)- print(f"[OK] Baseline UID: {baseline_uid}")-- # Step 2: Fetch new since baseline — should be 0- messages, new_uid = await fetch_new(- client, "/tmp/email_test_attachments",- last_uid=baseline_uid, max_messages=5,- )- print(f"[OK] Fetch new since UID {baseline_uid}: {len(messages)} messages (expected 0)")-- await disconnect_imap(client)-- # Step 3: Send test email to self- print("\n--- Sending test email to self ---")- cfg = SmtpConfig(- server="smtp.gmail.com", port=587,- username=user, password=password,- )- ok = await send_reply(- config=cfg, to=user,- subject="A0 Email Test [a0-test123]",- body="Test email from Agent Zero. If you see this, SMTP works.",- )- print(f"[{'OK' if ok else 'FAIL'}] SMTP send")-- if not ok:- return-- # Step 4: Wait for email to arrive, then fetch- print("\n--- Waiting 5s for email delivery ---")- await asyncio.sleep(5)-- client2 = await connect_imap(- server="imap.gmail.com", port=993,- username=user, password=password,- )-- messages2, new_uid2 = await fetch_new(- client2, "/tmp/email_test_attachments",- last_uid=baseline_uid, max_messages=5,- )- print(f"[OK] Fetch new since UID {baseline_uid}: {len(messages2)} messages")- for msg in messages2:- print(f" From: {msg.sender}")- print(f" Subject: {msg.subject}")- print(f" Body: {msg.body[:80]}...")- print()-- print(f"[OK] New last_uid: {new_uid2}")-- # Step 5: Fetch again with updated UID — should be 0- messages3, _ = await fetch_new(- client2, "/tmp/email_test_attachments",- last_uid=new_uid2, max_messages=5,- )- print(f"[OK] Re-fetch since UID {new_uid2}: {len(messages3)} messages (expected 0)")-- await disconnect_imap(client2)- print("\n--- ALL TESTS PASSED ---")---async def main():- user = os.environ.get("EMAIL_USER", "")- password = os.environ.get("EMAIL_PASS", "")-- if not user or not password:- print("Set EMAIL_USER and EMAIL_PASS environment variables")- print("Example: [email protected] EMAIL_PASS=xxxx python ...")- sys.exit(1)-- await test_full_flow(user, password)---if __name__ == "__main__":- asyncio.run(main())diff --git a/plugins/_email_integration/webui/config.html b/plugins/_email_integration/webui/config.htmlindex 9d5b54cac..d353ff4ae 100644--- a/plugins/_email_integration/webui/config.html+++ b/plugins/_email_integration/webui/config.html@@ -7,6 +7,8 @@<div x-data="{get handlers() { return config?.handlers || [] },editing: null,+ testing: null,+ test_results: null,add_handler() {if (!config.handlers) config.handlers = [];config.handlers.push({@@ -38,6 +40,20 @@},set_whitelist(handler, val) {handler.sender_whitelist = val.split(',').map(s => s.trim()).filter(s => s);+ },+ async test_connection(idx) {+ this.testing = idx;+ this.test_results = null;+ try {+ const { callJsonApi } = await import('/js/api.js');+ const res = await callJsonApi('/plugins/_email_integration/test_connection', {+ handler: this.handlers[idx]+ });+ this.test_results = res;+ } catch (e) {+ this.test_results = { success: false, results: [{ test: 'Connection', ok: false, message: String(e) }] };+ }+ this.testing = null;}}"><template x-if="config">@@ -218,12 +234,37 @@</div></div>+ <!-- Test connection -->+ <div style="margin-top: 12px; display: flex; align-items: center; gap: 12px;">+ <button class="btn-cancel" @click.stop="test_connection(idx)"+ :disabled="testing === idx"+ style="padding: 4px 16px; font-size: 0.85rem;">+ <span x-show="testing !== idx">Test Connection</span>+ <span x-show="testing === idx">Testing...</span>+ </button>+ </div>++ <!-- Test results -->+ <template x-if="test_results && editing === idx">+ <div style="margin-top: 8px; padding: 8px 12px; border-radius: 6px; font-size: 0.85rem;+ border: 1px solid var(--border-color, #333);">+ <template x-for="r in test_results.results" :key="r.test">+ <div style="display: flex; align-items: center; gap: 8px; padding: 4px 0;">+ <span x-text="r.ok ? '✓' : '✗'"+ :style="'font-weight: bold; color:' + (r.ok ? '#4caf50' : '#f44336')"></span>+ <span style="font-weight: 500; min-width: 50px;" x-text="r.test"></span>+ <span style="opacity: 0.8;" x-text="r.message"></span>+ </div>+ </template>+ </div>+ </template>+</div></template></div></template>- <button class="btn-ok" @click="add_handler()" style="margin-top: 8px;">+ <button class="btn-cancel" @click="add_handler()" style="margin-top: 8px; padding: 4px 16px; font-size: 0.85rem;">Add Handler</button></div>