Skip to content

Agent Zero AI framework

feat: Microsoft Dev Tunnels

linuztx5c9c21c2c7de
diff --git a/python/api/tunnel.py b/python/api/tunnel.py
index c682aff12..edcf8ab55 100644
--- a/python/api/tunnel.py
+++ b/python/api/tunnel.py
@@ -18,16 +18,19 @@ async def process(input: dict) -> dict | Response:
port = runtime.get_web_ui_port()
provider = input.get("provider", "serveo") # Default to serveo
tunnel_url = tunnel_manager.start_tunnel(port, provider)
- if tunnel_url is None:
- # Add a little delay and check again - tunnel might be starting
- import time
- time.sleep(2)
- tunnel_url = tunnel_manager.get_tunnel_url()
+ error = tunnel_manager.get_last_error()
+ if error:
+ return {
+ "success": False,
+ "tunnel_url": None,
+ "message": error,
+ "notifications": tunnel_manager.get_notifications()
+ }
return {
"success": tunnel_url is not None,
"tunnel_url": tunnel_url,
- "message": "Tunnel creation in progress" if tunnel_url is None else "Tunnel created successfully"
+ "notifications": tunnel_manager.get_notifications()
}
elif action == "stop":
@@ -41,9 +44,17 @@ async def process(input: dict) -> dict | Response:
"is_running": tunnel_manager.is_running
}
+ elif action == "notifications":
+ return {
+ "success": True,
+ "notifications": tunnel_manager.get_notifications(),
+ "tunnel_url": tunnel_manager.get_tunnel_url(),
+ "is_running": tunnel_manager.is_running
+ }
+
return {
"success": False,
- "error": "Invalid action. Use 'create', 'stop', or 'get'."
+ "error": "Invalid action. Use 'create', 'stop', 'get', or 'notifications'."
}
def stop():
diff --git a/python/helpers/tunnel_manager.py b/python/helpers/tunnel_manager.py
index 93e8ec635..5c68830b3 100644
--- a/python/helpers/tunnel_manager.py
+++ b/python/helpers/tunnel_manager.py
@@ -1,5 +1,11 @@
-from flaredantic import FlareTunnel, FlareConfig, ServeoConfig, ServeoTunnel
+from flaredantic import (
+ FlareTunnel, FlareConfig,
+ ServeoConfig, ServeoTunnel,
+ MicrosoftTunnel, MicrosoftConfig,
+ notifier, NotifyData, NotifyEvent
+)
import threading
+from collections import deque
# Singleton to manage the tunnel instance
@@ -19,6 +25,35 @@ class TunnelManager:
self.tunnel_url = None
self.is_running = False
self.provider = None
+ self.notifications = deque(maxlen=50)
+ self._subscribed = False
+
+ def _on_notify(self, data: NotifyData):
+ """Handle notifications from flaredantic"""
+ self.notifications.append({
+ "event": data.event.value,
+ "message": data.message,
+ "data": data.data
+ })
+
+ def _ensure_subscribed(self):
+ """Subscribe to flaredantic notifications if not already"""
+ if not self._subscribed:
+ notifier.subscribe(self._on_notify)
+ self._subscribed = True
+
+ def get_notifications(self):
+ """Get and clear pending notifications"""
+ notifications = list(self.notifications)
+ self.notifications.clear()
+ return notifications
+
+ def get_last_error(self):
+ """Check for recent error in notifications without clearing"""
+ for n in reversed(list(self.notifications)):
+ if n['event'] == NotifyEvent.ERROR.value:
+ return n['message']
+ return None
def start_tunnel(self, port=80, provider="serveo"):
"""Start a new tunnel or return the existing one's URL"""
@@ -26,6 +61,8 @@ class TunnelManager:
return self.tunnel_url
self.provider = provider
+ self._ensure_subscribed()
+ self.notifications.clear()
try:
# Start tunnel in a separate thread to avoid blocking
@@ -34,6 +71,9 @@ class TunnelManager:
if self.provider == "cloudflared":
config = FlareConfig(port=port, verbose=True)
self.tunnel = FlareTunnel(config)
+ elif self.provider == "microsoft":
+ config = MicrosoftConfig(port=port, verbose=True) # type: ignore
+ self.tunnel = MicrosoftTunnel(config)
else: # Default to serveo
config = ServeoConfig(port=port) # type: ignore
self.tunnel = ServeoTunnel(config)
@@ -42,18 +82,29 @@ class TunnelManager:
self.tunnel_url = self.tunnel.tunnel_url
self.is_running = True
except Exception as e:
- print(f"Error in tunnel thread: {str(e)}")
+ error_msg = str(e)
+ print(f"Error in tunnel thread: {error_msg}")
+ self.notifications.append({
+ "event": NotifyEvent.ERROR.value,
+ "message": error_msg,
+ "data": None
+ })
tunnel_thread = threading.Thread(target=run_tunnel)
tunnel_thread.daemon = True
tunnel_thread.start()
- # Wait for tunnel to start (max 15 seconds instead of 5)
- for _ in range(150): # Increased from 50 to 150 iterations
+ # Wait for tunnel to start (no timeout - user may need time for login)
+ import time
+ while True:
if self.tunnel_url:
break
- import time
-
+ # Check if we have errors
+ if any(n['event'] == NotifyEvent.ERROR.value for n in self.notifications):
+ break
+ # Check if thread died without producing URL
+ if not tunnel_thread.is_alive():
+ break
time.sleep(0.1)
return self.tunnel_url
diff --git a/webui/components/settings/tunnel/tunnel-section.html b/webui/components/settings/tunnel/tunnel-section.html
index cc385e943..da64d219b 100644
--- a/webui/components/settings/tunnel/tunnel-section.html
+++ b/webui/components/settings/tunnel/tunnel-section.html
@@ -31,6 +31,7 @@
<select id="tunnel-provider" x-model="$store.tunnelStore.provider"
:disabled="$store.tunnelStore.isLoading">
<option value="cloudflared">Cloudflare</option>
+ <option value="microsoft">Microsoft Dev Tunnels</option>
<option value="serveo">Serveo</option>
</select>
</div>
@@ -40,6 +41,17 @@
<span class="icon material-symbols-outlined spin">progress_activity</span>
<span x-text="$store.tunnelStore.loadingText || 'Processing tunnel request...'"></span>
</div>
+ <!-- Microsoft login code display -->
+ <div class="microsoft-login-box" x-show="$store.tunnelStore.microsoftLoginCode">
+ <div class="microsoft-login-title">Microsoft Login Required</div>
+ <div class="microsoft-login-instructions">
+ Open <a :href="$store.tunnelStore.microsoftLoginUrl" target="_blank" x-text="$store.tunnelStore.microsoftLoginUrl"></a> and enter the code:
+ </div>
+ <div class="microsoft-login-code" x-text="$store.tunnelStore.microsoftLoginCode"></div>
+ <button class="btn btn-copy-code" @click="$store.tunnelStore.copyLoginCode()">
+ <span class="icon material-symbols-outlined">content_copy</span> Copy Code
+ </button>
+ </div>
<!-- Tunnel content when not loading -->
<div x-show="!$store.tunnelStore.isLoading">
@@ -364,6 +376,67 @@
background-color: rgba(220, 53, 69, 0.05);
color: #dc3545;
}
+
+ /* Microsoft Login Box */
+ .microsoft-login-box {
+ margin: 1rem 0;
+ padding: 1.25rem;
+ background: linear-gradient(135deg, rgba(0, 120, 212, 0.15), rgba(0, 120, 212, 0.05));
+ border: 1px solid rgba(0, 120, 212, 0.4);
+ border-radius: 8px;
+ text-align: center;
+ }
+
+ .microsoft-login-title {
+ font-size: 1rem;
+ font-weight: 600;
+ color: #0078d4;
+ margin-bottom: 0.75rem;
+ }
+
+ .microsoft-login-instructions {
+ font-size: 0.9rem;
+ color: var(--text-color-secondary);
+ margin-bottom: 0.75rem;
+ line-height: 1.5;
+ }
+
+ .microsoft-login-instructions a {
+ color: #0078d4;
+ text-decoration: underline;
+ }
+
+ .microsoft-login-code {
+ font-family: 'Courier New', monospace;
+ font-size: 1.75rem;
+ font-weight: bold;
+ letter-spacing: 0.15em;
+ color: var(--text-color);
+ background-color: var(--bg-color-secondary);
+ padding: 0.75rem 1.5rem;
+ border-radius: 6px;
+ display: inline-block;
+ margin-bottom: 0.75rem;
+ border: 1px solid var(--border-color);
+ user-select: all;
+ }
+
+ .btn-copy-code {
+ background-color: #0078d4;
+ color: white;
+ border: none;
+ padding: 0.5rem 1rem;
+ border-radius: 4px;
+ cursor: pointer;
+ font-size: 0.875rem;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.25rem;
+ }
+
+ .btn-copy-code:hover {
+ background-color: #106ebe;
+ }
</style>
</body>
diff --git a/webui/components/settings/tunnel/tunnel-store.js b/webui/components/settings/tunnel/tunnel-store.js
index 60a2eed41..b72c5d9c9 100644
--- a/webui/components/settings/tunnel/tunnel-store.js
+++ b/webui/components/settings/tunnel/tunnel-store.js
@@ -9,11 +9,112 @@ const model = {
loadingText: "",
qrCodeInstance: null,
provider: "cloudflared",
+ microsoftLoginCode: "",
+ microsoftLoginUrl: "",
+ notificationPollInterval: null,
+ hasError: false,
init() {
this.checkTunnelStatus();
},
+ clearMicrosoftLogin() {
+ this.microsoftLoginCode = "";
+ this.microsoftLoginUrl = "";
+ },
+
+ copyLoginCode() {
+ if (!this.microsoftLoginCode) return;
+ navigator.clipboard.writeText(this.microsoftLoginCode).then(() => {
+ window.toastFrontendInfo("Login code copied to clipboard!", "Clipboard");
+ }).catch((err) => {
+ console.error("Failed to copy code: ", err);
+ window.toastFrontendError("Failed to copy login code", "Clipboard Error");
+ });
+ },
+
+ processNotifications(notifications) {
+ if (!notifications || !Array.isArray(notifications)) return;
+
+ for (const n of notifications) {
+ switch (n.event) {
+ case "downloading":
+ this.loadingText = n.message;
+ break;
+ case "download_progress":
+ if (n.data && n.data.percent !== undefined) {
+ this.loadingText = `Downloading: ${n.data.percent.toFixed(1)}%`;
+ } else {
+ this.loadingText = n.message;
+ }
+ break;
+ case "download_complete":
+ this.loadingText = n.message;
+ break;
+ case "creating_tunnel":
+ this.loadingText = n.message;
+ break;
+ case "info":
+ // Check for Microsoft login code
+ if (n.data && n.data.code) {
+ this.microsoftLoginCode = n.data.code;
+ this.microsoftLoginUrl = n.data.url || "";
+ this.loadingText = "Waiting for Microsoft login...";
+ } else {
+ this.loadingText = n.message;
+ }
+ break;
+ case "error":
+ this.hasError = true;
+ window.toastFrontendError(n.message, "Tunnel Error");
+ this.stopNotificationPolling();
+ break;
+ case "tunnel_url":
+ if (n.data && n.data.url) {
+ this.tunnelLink = n.data.url;
+ this.linkGenerated = true;
+ }
+ break;
+ case "tunnel_stopped":
+ this.loadingText = n.message;
+ break;
+ }
+ }
+ },
+
+ startNotificationPolling() {
+ this.stopNotificationPolling();
+ this.hasError = false;
+ this.notificationPollInterval = setInterval(async () => {
+ try {
+ const response = await fetchApi("/tunnel_proxy", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ action: "notifications" }),
+ });
+ const data = await response.json();
+ if (data.notifications) {
+ this.processNotifications(data.notifications);
+ }
+ // Check if tunnel is ready
+ if (data.tunnel_url && data.is_running) {
+ this.tunnelLink = data.tunnel_url;
+ this.linkGenerated = true;
+ this.stopNotificationPolling();
+ }
+ } catch (error) {
+ console.error("Error polling notifications:", error);
+ }
+ }, 500);
+ },
+
+ stopNotificationPolling() {
+ if (this.notificationPollInterval) {
+ clearInterval(this.notificationPollInterval);
+ this.notificationPollInterval = null;
+ }
+ },
+
generateQRCode() {
if (!this.tunnelLink) return;
@@ -110,6 +211,8 @@ const model = {
) {
this.isLoading = true;
+ this.hasError = false;
+ this.clearMicrosoftLogin();
this.loadingText = "Refreshing tunnel...";
// Change refresh button appearance
@@ -206,7 +309,9 @@ const model = {
}
this.isLoading = true;
- this.loadingText = "Creating tunnel...";
+ this.hasError = false;
+ this.clearMicrosoftLogin();
+ this.loadingText = "Starting tunnel...";
// Change create button appearance
const createButton = document.querySelector("#tunnel-settings-section .tunnel-actions .btn-ok");
@@ -217,6 +322,9 @@ const model = {
createButton.classList.add("creating");
}
+ // Start polling for notifications
+ this.startNotificationPolling();
+
try {
// Call the backend API to create a tunnel
const response = await fetchApi("/tunnel_proxy", {
@@ -227,18 +335,32 @@ const model = {
body: JSON.stringify({
action: "create",
provider: this.provider,
- // port: window.location.port || (window.location.protocol === 'https:' ? 443 : 80)
}),
});
const data = await response.json();
+ // Process any notifications from response
+ if (data.notifications) {
+ this.processNotifications(data.notifications);
+ }
+
+ // Check for error
+ if (!data.success && data.message) {
+ this.hasError = true;
+ window.toastFrontendError(data.message, "Tunnel Error");
+ console.error("Tunnel creation failed:", data);
+ this.stopNotificationPolling();
+ return;
+ }
+
if (data.success && data.tunnel_url) {
// Store the tunnel URL in localStorage for persistence
localStorage.setItem("agent_zero_tunnel_url", data.tunnel_url);
this.tunnelLink = data.tunnel_url;
this.linkGenerated = true;
+ this.stopNotificationPolling();
// Generate QR code for the tunnel URL
Sleep.Skip().then(() => this.generateQRCode());
@@ -248,52 +370,6 @@ const model = {
"Tunnel created successfully",
"Tunnel Status"
);
- } else {
- // The tunnel might still be starting up, check again after a delay
- this.loadingText = "Tunnel creation taking longer than expected...";
-
- // Wait for 5 seconds and check if the tunnel is running
- await new Promise((resolve) => setTimeout(resolve, 5000));
-
- // Check if tunnel is running now
- try {
- const statusResponse = await fetchApi("/tunnel_proxy", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ action: "get" }),
- });
-
- const statusData = await statusResponse.json();
-
- if (statusData.success && statusData.tunnel_url) {
- // Tunnel is now running, we can update the UI
- localStorage.setItem(
- "agent_zero_tunnel_url",
- statusData.tunnel_url
- );
- this.tunnelLink = statusData.tunnel_url;
- this.linkGenerated = true;
-
- // Generate QR code for the tunnel URL
- Sleep.Skip().then(() => this.generateQRCode());
-
- window.toastFrontendInfo(
- "Tunnel created successfully",
- "Tunnel Status"
- );
- return;
- }
- } catch (statusError) {
- console.error("Error checking tunnel status:", statusError);
- }
-
- // If we get here, the tunnel really failed to start
- const errorMessage =
- data.message || "Failed to create tunnel. Please try again.";
- window.toastFrontendError(errorMessage, "Tunnel Error");
- console.error("Tunnel creation failed:", data);
}
} catch (error) {
window.toastFrontendError("Error creating tunnel", "Tunnel Error");
@@ -301,6 +377,8 @@ const model = {
} finally {
this.isLoading = false;
this.loadingText = "";
+ this.stopNotificationPolling();
+ this.clearMicrosoftLogin();
// Reset create button if it's still in the DOM
const createButton = document.querySelector("#tunnel-settings-section .tunnel-actions .btn-ok");