Skip to content

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.

Add poll transport; Windows UI & service fixes

Juan Denis96a6f31d75f9
diff --git a/agent/cmd/agent/instance_other.go b/agent/cmd/agent/instance_other.go
index ecb8a476..2aeb20d0 100644
--- a/agent/cmd/agent/instance_other.go
+++ b/agent/cmd/agent/instance_other.go
@@ -7,3 +7,9 @@ package main
func acquireSingleInstance() (alreadyRunning bool, release func()) {
return false, func() {}
}
+
+// acquireServiceInstance is a no-op on non-Windows; SCM doesn't exist
+// and POSIX deployments rely on systemd to enforce single-instance.
+func acquireServiceInstance() (alreadyRunning bool, release func()) {
+ return false, func() {}
+}
diff --git a/agent/cmd/agent/instance_windows.go b/agent/cmd/agent/instance_windows.go
index 4d5d2644..a61b107f 100644
--- a/agent/cmd/agent/instance_windows.go
+++ b/agent/cmd/agent/instance_windows.go
@@ -7,6 +7,8 @@ import (
"unsafe"
)
+const errAlreadyExists = 183
+
// acquireSingleInstance opens (or creates) a per-user named mutex. If the
// mutex already existed, another instance of the desktop app is already
// running for this user and we should bow out. Otherwise we hold the mutex
@@ -15,15 +17,26 @@ import (
// Per-user (Local\) namespace: each Windows user gets their own ServerKit
// tray, which matches the per-user Run-key autostart.
func acquireSingleInstance() (alreadyRunning bool, release func()) {
- const (
- errAlreadyExists = 183
- )
+ return acquireMutex(`Local\ServerKitAgentDesktop`)
+}
+
+// acquireServiceInstance is the agent-service equivalent of the desktop
+// mutex above. Lives in the Global\ namespace because the service runs as
+// SYSTEM and a per-user mutex wouldn't collide with a user-launched
+// `serverkit-agent start`. With this in place, a second invocation of
+// the start subcommand exits immediately with a clear message instead
+// of racing the SCM-launched service for port 19780 and tripping a
+// 30s "service did not respond" timeout.
+func acquireServiceInstance() (alreadyRunning bool, release func()) {
+ return acquireMutex(`Global\ServerKitAgentService`)
+}
+func acquireMutex(name string) (alreadyRunning bool, release func()) {
kernel32 := syscall.NewLazyDLL("kernel32.dll")
createMutexW := kernel32.NewProc("CreateMutexW")
closeHandle := kernel32.NewProc("CloseHandle")
- name, err := syscall.UTF16PtrFromString(`Local\ServerKitAgentDesktop`)
+ wname, err := syscall.UTF16PtrFromString(name)
if err != nil {
return false, func() {}
}
@@ -31,7 +44,7 @@ func acquireSingleInstance() (alreadyRunning bool, release func()) {
handle, _, lastErr := createMutexW.Call(
0, // lpMutexAttributes = NULL
0, // bInitialOwner = FALSE
- uintptr(unsafe.Pointer(name)),
+ uintptr(unsafe.Pointer(wname)),
)
if handle == 0 {
diff --git a/agent/cmd/agent/main.go b/agent/cmd/agent/main.go
index 5a9d1df2..99fc5b0f 100644
--- a/agent/cmd/agent/main.go
+++ b/agent/cmd/agent/main.go
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
stdlog "log"
+ "net"
"os"
"os/exec"
"os/signal"
@@ -26,6 +27,17 @@ var (
GitCommit = "unknown"
)
+// Mirror Version into the agent package at startup so /status reports the
+// real version. ldflags set main.Version but the IPC reads agent.Version
+// — they're two distinct package-level vars and were silently drifting,
+// which is why the UI showed "vdev" while `serverkit-agent version`
+// correctly printed "1.6.10".
+func init() {
+ if Version != "dev" {
+ agent.Version = Version
+ }
+}
+
var (
cfgFile string
debugMode bool
@@ -264,6 +276,41 @@ func runAgent() error {
"config", config.DefaultConfigPath(),
)
+ // Single-instance enforcement for the service. Multiple "start"
+ // invocations would fight for IPC port 19780 and the SCM-launched
+ // service would lose to a manually-started one (or vice versa) with
+ // a 30s timeout in either direction. Mutex is in the Global\
+ // namespace because the service runs as SYSTEM and a per-user lock
+ // wouldn't catch a user-context "serverkit-agent start" race.
+ if alreadyRunning, release := acquireServiceInstance(); alreadyRunning {
+ log.Error("Another ServerKit agent service is already running. " +
+ "If this is unexpected, end leftover serverkit-agent.exe processes via " +
+ "Task Manager (or run `taskkill /F /IM serverkit-agent.exe /T`) and try again.")
+ return fmt.Errorf("another agent service is already running (mutex held)")
+ } else {
+ defer release()
+ }
+
+ // Probe the IPC port up-front. If it's held by something else (a
+ // stale agent, another tool, anything), fail fast with a clear
+ // message instead of letting the IPC server later time out and
+ // trip SCM's 1053 "service did not respond" error.
+ if cfg.IPC.Enabled {
+ probe, perr := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", cfg.IPC.Port))
+ if perr != nil {
+ log.Error("IPC port is already in use — likely a leftover serverkit-agent.exe process",
+ "port", cfg.IPC.Port, "error", perr)
+ return fmt.Errorf("IPC port %d is in use; "+
+ "end leftover agent processes (Task Manager → 'serverkit-agent.exe') and try again",
+ cfg.IPC.Port)
+ }
+ // Release the probe — the real IPC server will rebind in a moment.
+ // There's a tiny race window where another process could grab the
+ // port between probe-close and real-bind, but that's acceptable
+ // for what's effectively a "is anyone else here?" check.
+ probe.Close()
+ }
+
// Check if registered
if cfg.Agent.ID == "" {
return fmt.Errorf("agent not registered. Run 'serverkit-agent register' first")
diff --git a/agent/cmd/agent/spawn_windows.go b/agent/cmd/agent/spawn_windows.go
index 4f63f1ca..ddc4c6e8 100644
--- a/agent/cmd/agent/spawn_windows.go
+++ b/agent/cmd/agent/spawn_windows.go
@@ -11,12 +11,20 @@ const (
detachedProcess = 0x00000008
)
-// detachedProcessAttrs returns SysProcAttr that fully detaches the spawned
-// process from the parent. Used when the tray spawns a fresh `serverkit-agent
-// --repair` to relaunch the wizard: the tray must keep running independently.
+// detachedProcessAttrs returns SysProcAttr that detaches the spawned process
+// from the parent without smothering its UI. Used when the tray spawns a
+// fresh `serverkit-agent setup` to relaunch the wizard.
+//
+// HideWindow MUST be false here. STARTUPINFO.wShowWindow propagates to the
+// child's first top-level window via SW_SHOWDEFAULT, so HideWindow:true
+// (which sets SW_HIDE) was leaving the wizard window invisible until the
+// user manually called ShowWindow from outside — exactly the "Start Menu
+// blank, CLI works" inconsistency users reported in 1.6.2. The agent .exe
+// is built as a GUI subsystem so there's no console window to hide; the
+// flag was redundant from the start.
func detachedProcessAttrs() *syscall.SysProcAttr {
return &syscall.SysProcAttr{
- HideWindow: true,
+ HideWindow: false,
CreationFlags: createNoWindow | detachedProcess,
}
}
diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.go
index 7349e6c1..e57dc1af 100644
--- a/agent/internal/agent/agent.go
+++ b/agent/internal/agent/agent.go
@@ -25,6 +25,8 @@ import (
"github.com/serverkit/agent/internal/logger"
"github.com/serverkit/agent/internal/metrics"
"github.com/serverkit/agent/internal/terminal"
+ "github.com/serverkit/agent/internal/transport"
+ "github.com/serverkit/agent/internal/transport/poll"
"github.com/serverkit/agent/internal/updater"
"github.com/serverkit/agent/internal/ws"
"github.com/serverkit/agent/pkg/protocol"
@@ -35,7 +37,10 @@ type Agent struct {
cfg *config.Config
log *logger.Logger
auth *auth.Authenticator
- ws *ws.Client
+ // ws is the active transport — either the WS client directly or the
+ // fallback Manager that wraps WS+poll. Named "ws" for compatibility
+ // with the dozens of existing call sites in this file.
+ ws transport.Transport
docker *docker.Client
metrics *metrics.Collector
terminal *terminal.Manager
@@ -65,8 +70,13 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {
// Create authenticator
authenticator := auth.New(cfg.Agent.ID, cfg.Auth.APIKey, cfg.Auth.APISecret)
- // Create WebSocket client
+ // Build the transport: a Manager wrapping the WS client (primary) and
+ // a polling client (fallback for tunnels that mangle WS frames). The
+ // Manager presents the same Transport surface as the bare WS client
+ // did, so the rest of the agent doesn't care which is active.
wsClient := ws.NewClient(cfg.Server, authenticator, log)
+ pollClient := poll.NewClient(cfg.Server, authenticator, log)
+ transportClient := transport.NewManager(wsClient, pollClient, log)
// Create Docker client if enabled
var dockerClient *docker.Client
@@ -105,7 +115,7 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {
cfg: cfg,
log: log,
auth: authenticator,
- ws: wsClient,
+ ws: transportClient,
docker: dockerClient,
metrics: metricsCollector,
terminal: termManager,
@@ -120,8 +130,10 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {
// Register command handlers
agent.registerHandlers()
- // Set WebSocket message handler
- wsClient.SetHandler(agent.handleMessage)
+ // Install the message handler on the transport (manager fans this
+ // out to both backends so a fallback switch doesn't drop the
+ // binding).
+ transportClient.SetHandler(agent.handleMessage)
// Create IPC server if enabled
if cfg.IPC.Enabled {
@@ -1349,6 +1361,7 @@ func (a *Agent) GetStatus() ipc.AgentStatus {
ServerURL: a.cfg.Server.URL,
Uptime: int64(time.Since(a.startTime).Seconds()),
Version: Version,
+ Transport: string(a.ws.Mode()),
}
// Collect current metrics if available
diff --git a/agent/internal/agentui/actions.go b/agent/internal/agentui/actions.go
index b77a8f4b..e32a503d 100644
--- a/agent/internal/agentui/actions.go
+++ b/agent/internal/agentui/actions.go
@@ -5,6 +5,8 @@ import (
"net/http"
"os/exec"
"time"
+
+ "github.com/serverkit/agent/internal/config"
)
// localActions exposes a small set of console-process-level operations to
@@ -15,12 +17,13 @@ import (
// All endpoints live under /local/ so they're trivially distinguishable
// from agent-service IPC calls (which target a different port entirely).
type localActions struct {
- exePath string
+ exePath string
+ configPath string
}
-func newLocalActions() *localActions {
+func newLocalActions(configPath string) *localActions {
exe, _ := exeForSpawn()
- return &localActions{exePath: exe}
+ return &localActions{exePath: exe, configPath: configPath}
}
// register hooks the action handlers into the asset server's mux.
@@ -31,6 +34,33 @@ func (a *localActions) register(mux *http.ServeMux) {
mux.HandleFunc("/local/open", a.handleOpen)
mux.HandleFunc("/local/wizard", a.handleWizard)
mux.HandleFunc("/local/diag", a.handleDiag)
+ mux.HandleFunc("/local/status", a.handleStatus)
+}
+
+// handleStatus reports whether the agent has been paired by reading
+// config.yaml directly. The React PairGate uses this as a fallback when
+// the agent service IPC is unreachable — which is exactly the case on a
+// fresh install: no config means no service, so the service can't tell
+// the UI it isn't registered. Without this endpoint the wizard is a
+// dead end on first run.
+func (a *localActions) handleStatus(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ resp := map[string]interface{}{
+ "registered": false,
+ "agent_id": "",
+ "server_url": "",
+ }
+ if cfg, err := config.Load(a.configPath); err == nil && cfg != nil {
+ if cfg.Agent.ID != "" {
+ resp["registered"] = true
+ resp["agent_id"] = cfg.Agent.ID
+ resp["server_url"] = cfg.Server.URL
+ }
+ }
+ writeJSON(w, http.StatusOK, resp)
}
func writeJSON(w http.ResponseWriter, status int, v interface{}) {
diff --git a/agent/internal/agentui/focus_windows.go b/agent/internal/agentui/focus_windows.go
new file mode 100644
index 00000000..d229894f
--- /dev/null
+++ b/agent/internal/agentui/focus_windows.go
@@ -0,0 +1,95 @@
+//go:build windows
+
+package agentui
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// 1.6.1 shipped without explicit show/focus, leaving the host window hidden
+// when the wizard was spawned with HideWindow:true (the STARTUPINFO bit
+// propagates to child windows on some Windows builds — explicit SW_SHOW in
+// the webview library wasn't enough). This file forces visibility from our
+// side so 1.6.2 doesn't depend on that race.
+
+const (
+ swHide = 0
+ swShow = 5
+ swRestore = 9
+ hwndTopmost = ^uintptr(0) // -1
+ hwndNotopmost = ^uintptr(1) // -2
+ swpNoMove = 0x0002
+ swpNoSize = 0x0001
+ swpShowWindow = 0x0040
+)
+
+// hideHostWindow stuffs the WebView2 host out of sight immediately after
+// construction so the user never sees the white pre-paint or black
+// post-CSS-but-pre-React frames. We re-show via forceForeground once the
+// JS bundle reports ready (or a safety timeout fires).
+func hideHostWindow(hwnd unsafe.Pointer) {
+ if hwnd == nil {
+ return
+ }
+ procShowWindow.Call(uintptr(hwnd), swHide)
+}
+
+var (
+ user32 = syscall.NewLazyDLL("user32.dll")
+ procShowWindow = user32.NewProc("ShowWindow")
+ procSetForegroundWindow = user32.NewProc("SetForegroundWindow")
+ procBringWindowToTop = user32.NewProc("BringWindowToTop")
+ procSetWindowPos = user32.NewProc("SetWindowPos")
+ procIsIconic = user32.NewProc("IsIconic")
+ procAttachThreadInput = user32.NewProc("AttachThreadInput")
+ procGetForegroundWindow = user32.NewProc("GetForegroundWindow")
+ procGetWindowThreadProc = user32.NewProc("GetWindowThreadProcessId")
+ kernel32 = syscall.NewLazyDLL("kernel32.dll")
+ procGetCurrentThreadID = kernel32.NewProc("GetCurrentThreadId")
+)
+
+// forceForeground does the dance Windows requires when a non-foreground
+// process wants to grab focus: attach to the foreground thread's input
+// queue, call SetForegroundWindow + BringWindowToTop, then detach. Without
+// the attach step Windows silently demotes the request to a flashing
+// taskbar button — exactly the symptom we saw in 1.6.1.
+func forceForeground(hwnd unsafe.Pointer) {
+ if hwnd == nil {
+ return
+ }
+ h := uintptr(hwnd)
+
+ // If minimized, restore first.
+ if iconic, _, _ := procIsIconic.Call(h); iconic != 0 {
+ procShowWindow.Call(h, swRestore)
+ } else {
+ procShowWindow.Call(h, swShow)
+ }
+
+ // Topmost-then-not flash forces the window onto Z-top reliably; some
+ // users reported the window living below the taskbar otherwise.
+ procSetWindowPos.Call(h, hwndTopmost, 0, 0, 0, 0, swpNoMove|swpNoSize|swpShowWindow)
+ procSetWindowPos.Call(h, hwndNotopmost, 0, 0, 0, 0, swpNoMove|swpNoSize|swpShowWindow)
+
+ fg, _, _ := procGetForegroundWindow.Call()
+ if fg == 0 {
+ procSetForegroundWindow.Call(h)
+ procBringWindowToTop.Call(h)
+ return
+ }
+
+ curThread, _, _ := procGetCurrentThreadID.Call()
+ var fgPid uint32
+ fgThread, _, _ := procGetWindowThreadProc.Call(fg, uintptr(unsafe.Pointer(&fgPid)))
+ if fgThread == 0 || fgThread == curThread {
+ procSetForegroundWindow.Call(h)
+ procBringWindowToTop.Call(h)
+ return
+ }
+
+ procAttachThreadInput.Call(curThread, fgThread, 1)
+ procSetForegroundWindow.Call(h)
+ procBringWindowToTop.Call(h)
+ procAttachThreadInput.Call(curThread, fgThread, 0)
+}
diff --git a/agent/internal/agentui/pairer.go b/agent/internal/agentui/pairer.go
index 9b8efcba..2b36aecc 100644
--- a/agent/internal/agentui/pairer.go
+++ b/agent/internal/agentui/pairer.go
@@ -6,6 +6,7 @@ import (
"errors"
"net/http"
"sync"
+ "time"
"github.com/serverkit/agent/internal/logger"
"github.com/serverkit/agent/internal/pairdriver"
@@ -116,9 +117,37 @@ func (p *pairer) handleStart(w http.ResponseWriter, r *http.Request) {
p.mu.Unlock()
// After credentials land on disk the running service still has
// the old config in memory — restart it so the new URL/agent_id
- // take effect immediately.
- _ = runServiceCmd("stop")
- _ = runServiceCmd("start")
+ // take effect immediately, and verify it actually came up.
+ // Earlier versions ignored sc start errors silently which is
+ // why users saw "successfully paired" on a dead service and
+ // had to start it manually from the CLI.
+ if err := runServiceCmd("stop"); err != nil {
+ p.log.Info("Service stop reported error (likely already stopped)", "error", err)
+ }
+ if err := runServiceCmd("start"); err != nil {
+ p.log.Error("Failed to start service after pairing", "error", err)
+ p.mu.Lock()
+ p.state = "error"
+ p.errMsg = "Pairing succeeded but the agent service failed to start: " + err.Error() +
+ "\n\nTry: restart the machine, or open Actions → Restart agent."
+ p.mu.Unlock()
+ return
+ }
+ // sc start returns as soon as the SCM accepts the request, not
+ // when the service is actually running. Poll for state=RUNNING
+ // so the wizard's "claimed" stage reflects reality.
+ if err := waitForServiceRunning(20 * time.Second); err != nil {
+ p.log.Error("Service did not reach RUNNING after pairing", "error", err)
+ p.mu.Lock()
+ p.state = "error"
+ p.errMsg = "Pairing succeeded but the agent service didn't come up within 20s. " +
+ "This usually means another agent process is holding port 19780 — " +
+ "try ending all serverkit-agent.exe processes from Task Manager and reopen the wizard.\n\n" +
+ "Detail: " + err.Error()
+ p.mu.Unlock()
+ return
+ }
+ p.log.Info("Agent service running after pair", "server", serverName)
},
OnError: func(err error) {
p.mu.Lock()
diff --git a/agent/internal/agentui/platform_other.go b/agent/internal/agentui/platform_other.go
index 1cdbb843..8a26086b 100644
--- a/agent/internal/agentui/platform_other.go
+++ b/agent/internal/agentui/platform_other.go
@@ -2,7 +2,10 @@
package agentui
-import "fmt"
+import (
+ "fmt"
+ "time"
+)
// runServiceCmd is a stub on non-Windows: the console window is Windows-only
// for now, and the platform-specific service controls land alongside the
@@ -11,6 +14,10 @@ func runServiceCmd(verb string) error {
return fmt.Errorf("service control not implemented on this platform")
}
+func waitForServiceRunning(timeout time.Duration) error {
+ return fmt.Errorf("service control not implemented on this platform")
+}
+
func openTarget(target string) error {
return fmt.Errorf("open not implemented on this platform")
}
diff --git a/agent/internal/agentui/platform_windows.go b/agent/internal/agentui/platform_windows.go
index cd2a6d08..feed0ad7 100644
--- a/agent/internal/agentui/platform_windows.go
+++ b/agent/internal/agentui/platform_windows.go
@@ -6,7 +6,9 @@ import (
"fmt"
"os"
"os/exec"
+ "strings"
"syscall"
+ "time"
)
// runServiceCmd issues sc.exe verb against ServerKitAgent. The MSI grants
@@ -22,6 +24,31 @@ func runServiceCmd(verb string) error {
return nil
}
+// waitForServiceRunning polls `sc query` until the service reports state
+// 4 (RUNNING) or the deadline passes. Returns nil when running, or a
+// descriptive error including the most recent state output. Used to
+// verify the post-pair sc start actually took — otherwise the wizard
+// silently shows "claimed" while the service quietly failed to start.
+func waitForServiceRunning(timeout time.Duration) error {
+ deadline := time.Now().Add(timeout)
+ var lastOut string
+ for time.Now().Before(deadline) {
+ cmd := exec.Command("sc.exe", "query", "ServerKitAgent")
+ cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
+ out, err := cmd.CombinedOutput()
+ lastOut = string(out)
+ if err == nil && strings.Contains(lastOut, "RUNNING") {
+ return nil
+ }
+ // STATE = 2 (START_PENDING) and 3 (STOP_PENDING) are transients —
+ // just wait. STATE = 1 (STOPPED) means the service either died or
+ // never came up; we'll catch it after the deadline.
+ time.Sleep(500 * time.Millisecond)
+ }
+ return fmt.Errorf("service did not reach RUNNING within %s (last sc query: %s)",
+ timeout, strings.TrimSpace(lastOut))
+}
+
// openTarget hands a path or URL to Explorer / the default browser via
// rundll32 + url.dll, which is the canonical "open this thing" entry point
// on Windows. Faster than shelling out to cmd /c start.
diff --git a/agent/internal/agentui/server.go b/agent/internal/agentui/server.go
index 358e39a9..560d4d07 100644
--- a/agent/internal/agentui/server.go
+++ b/agent/internal/agentui/server.go
@@ -31,9 +31,24 @@ func startAssetServer(ctx context.Context, log *logger.Logger, configPath string
}
mux := http.NewServeMux()
- newLocalActions().register(mux)
+ newLocalActions(configPath).register(mux)
newPairer(log, configPath).register(mux)
- mux.Handle("/", http.FileServer(http.FS(dist)))
+
+ // Wrap the static file server with no-store headers. WebView2 caches
+ // per-user-data-folder aggressively; on an MSI upgrade the new bundle
+ // would otherwise be shadowed by the previous index.html for several
+ // runs. Asset payload is ~600KB total, so loading it fresh each launch
+ // has no perceptible cost and removes a whole class of stale-asset
+ // bug reports.
+ noCache := func(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate")
+ w.Header().Set("Pragma", "no-cache")
+ w.Header().Set("Expires", "0")
+ h.ServeHTTP(w, r)
+ })
+ }
+ mux.Handle("/", noCache(http.FileServer(http.FS(dist))))
srv := &http.Server{
Handler: mux,
diff --git a/agent/internal/agentui/window_windows.go b/agent/internal/agentui/window_windows.go
index 65ab0f5f..7e657741 100644
--- a/agent/internal/agentui/window_windows.go
+++ b/agent/internal/agentui/window_windows.go
@@ -7,6 +7,7 @@ import (
"fmt"
"os"
"runtime"
+ "time"
webview2 "github.com/jchv/go-webview2"
@@ -21,6 +22,10 @@ import (
// Set SERVERKIT_AGENT_UI_DEV=http://localhost:5174 to point the webview at
// the Vite dev server instead of the embedded bundle. Useful while iterating
// on the UI: changes hot-reload without rebuilding the Go binary.
+//
+// Set SERVERKIT_AGENT_UI_DEVTOOLS=false to disable DevTools. By default the
+// 1.6.2 console ships with DevTools enabled so blank-page reports come with
+// a way for the user to press F12 and capture errors.
func Run(ctx context.Context, log *logger.Logger, configPath string) error {
runtime.LockOSThread()
@@ -67,9 +72,15 @@ func Run(ctx context.Context, log *logger.Logger, configPath string) error {
defer stopServer()
}
- log.Info("agentui.Run: constructing WebView2 window")
+ // 1.6.1 reports said: blank white window, no errors. We could not see
+ // what the React app was doing because the only diagnostic was the Go
+ // log on the host side. 1.6.2 ships with DevTools enabled by default so
+ // users can press F12 and screenshot errors. Set the env var to "false"
+ // to turn it off in installs where security policy prohibits it.
+ devtools := os.Getenv("SERVERKIT_AGENT_UI_DEVTOOLS") != "false"
+ log.Info("agentui.Run: constructing WebView2 window", "devtools", devtools)
w := webview2.NewWithOptions(webview2.WebViewOptions{
- Debug: os.Getenv("SERVERKIT_AGENT_UI_DEVTOOLS") == "true",
+ Debug: devtools,
AutoFocus: true,
WindowOptions: webview2.WindowOptions{
Title: "ServerKit Agent",
@@ -88,10 +99,107 @@ func Run(ctx context.Context, log *logger.Logger, configPath string) error {
}
defer w.Destroy()
+ // Bridge JS console + window errors back to the Go log so 1.6.2 doesn't
+ // leave us blind on blank-page reports. The page calls these via
+ // window.agentLog / window.agentNavReady, which Init() wires up below.
+ if err := w.Bind("agentLog", func(level, msg string) {
+ switch level {
+ case "error":
+ log.Error("ui.js: " + msg)
+ case "warn":
+ log.Warn("ui.js: " + msg)
+ default:
+ log.Info("ui.js: " + msg)
+ }
+ return
+ }); err != nil {
+ log.Warn("agentui.Run: Bind agentLog failed", "error", err)
+ }
+ navReady := make(chan struct{}, 1)
+ if err := w.Bind("agentNavReady", func(href string) {
+ log.Info("ui.js: navigation ready", "href", href)
+ select {
+ case navReady <- struct{}{}:
+ default:
+ }
+ return
+ }); err != nil {
+ log.Warn("agentui.Run: Bind agentNavReady failed", "error", err)
+ }
+
+ // Inject a tiny shim *before* the React bundle runs. It forwards every
+ // console.error / unhandledrejection / window.onerror through agentLog,
+ // and pings agentNavReady once the document has parsed. This is what
+ // fills the gap that NavigationCompleted would have filled if the
+ // upstream library exposed it on the public WebView interface.
+ w.Init(`
+ (function() {
+ var safe = function(fn) { try { fn(); } catch (e) {} };
+ var send = function(level, msg) {
+ if (window.agentLog) safe(function(){ window.agentLog(level, String(msg)); });
+ };
+ safe(function(){
+ var origErr = console.error;
+ console.error = function() {
+ send('error', Array.prototype.slice.call(arguments).map(String).join(' '));
+ return origErr.apply(console, arguments);
+ };
+ });
+ window.addEventListener('error', function(ev) {
+ send('error', (ev.message || 'window.onerror') + ' @ ' + (ev.filename||'?') + ':' + (ev.lineno||0));
+ });
+ window.addEventListener('unhandledrejection', function(ev) {
+ var r = ev && ev.reason;
+ send('error', 'unhandledrejection: ' + (r && r.message ? r.message : String(r)));
+ });
+ var ready = function() {
+ if (window.agentNavReady) safe(function(){ window.agentNavReady(location.href); });
+ };
+ if (document.readyState === 'complete' || document.readyState === 'interactive') {
+ setTimeout(ready, 0);
+ } else {
+ document.addEventListener('DOMContentLoaded', ready);
+ }
+ send('info', 'agent shim installed, ua=' + navigator.userAgent);
+ })();
+ `)
+
w.SetSize(900, 600, webview2.HintMin)
+
+ // Hide the host window immediately so the user never sees WebView2's
+ // pre-paint white rectangle or the dark-CSS-but-pre-React black gap.
+ // We re-show in forceForeground once navReady fires (or 3s elapses as
+ // a safety net for cases where the JS shim never installs).
+ hideHostWindow(w.Window())
+
log.Info("agentui.Run: navigating", "url", target)
w.Navigate(target)
+ // Reveal the window the moment the bundle reports ready. The 3s
+ // fallback is deliberately generous: on cold-start machines, WebView2
+ // can take ~1.5s to hydrate the first paint, and we'd rather show a
+ // real (if late) UI than show a flash. The 8s mark logs a louder
+ // warning so blank-page reports have a clear breadcrumb.
+ go func() {
+ select {
+ case <-navReady:
+ log.Info("agentui.Run: UI bundle reported ready, showing window")
+ forceForeground(w.Window())
+ case <-time.After(3 * time.Second):
+ log.Warn("agentui.Run: no UI ready signal after 3s; revealing window anyway")
+ forceForeground(w.Window())
+ select {
+ case <-navReady:
+ log.Info("agentui.Run: UI bundle reported ready (after fallback)")
+ case <-time.After(5 * time.Second):
+ log.Warn("agentui.Run: no UI ready signal after 8s; bundle likely failed (right-click → Inspect to debug)")
+ case <-ctx.Done():
+ }
+ case <-ctx.Done():
+ return
+ }
+ }()
+
// Hook ctx cancellation to terminate the webview from a background
// goroutine. Run() blocks on the OS message pump, so we need an external
// signal to break it cleanly when the parent process is torn down.
diff --git a/agent/internal/auth/auth.go b/agent/internal/auth/auth.go
index c522f467..8e111b0c 100644
--- a/agent/internal/auth/auth.go
+++ b/agent/internal/auth/auth.go
@@ -79,13 +79,18 @@ func (a *Authenticator) VerifyTimestamp(timestamp int64, maxAgeSeconds int64) bo
return diff <= maxAgeSeconds*1000
}
-// GetAPIKeyPrefix returns the first 8 characters of the API key
-// Used for identification without exposing full key
+// GetAPIKeyPrefix returns the first 12 characters of the API key for
+// server-side identification. Must match the panel's storage width
+// (backend/app/models/server.py: api_key_prefix = api_key[:12]) — the
+// panel does direct string equality, so any drift between the two
+// sides 401s every auth attempt. Was 8 here historically, which is a
+// dormant bug only exposed once the polling fallback transport made
+// auth failures visible (WS would just retry silently forever).
func (a *Authenticator) GetAPIKeyPrefix() string {
- if len(a.apiKey) < 8 {
+ if len(a.apiKey) < 12 {
return a.apiKey
}
- return a.apiKey[:8]
+ return a.apiKey[:12]
}
// AgentID returns the agent ID
diff --git a/agent/internal/ipc/server.go b/agent/internal/ipc/server.go
index 496b9a1e..c3662c08 100644
--- a/agent/internal/ipc/server.go
+++ b/agent/internal/ipc/server.go
@@ -34,6 +34,11 @@ type AgentStatus struct {
ServerURL string `json:"server_url"`
Uptime int64 `json:"uptime_seconds"`
Version string `json:"version"`
+ // Transport reports which link the agent is on right now: "ws" for
+ // the primary Socket.IO link, "poll" when WS-incompatible tunnels
+ // forced a fallback to the REST polling transport. UI uses this to
+ // surface a "limited mode" badge — streams are unavailable in poll.
+ Transport string `json:"transport,omitempty"`
CPUPercent float64 `json:"cpu_percent"`
MemPercent float64 `json:"mem_percent"`
DiskPercent float64 `json:"disk_percent"`
diff --git a/agent/internal/transport/manager.go b/agent/internal/transport/manager.go
new file mode 100644
index 00000000..aee0b4d7
--- /dev/null
+++ b/agent/internal/transport/manager.go
@@ -0,0 +1,230 @@
+package transport
+
+import (
+ "context"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/serverkit/agent/internal/auth"
+ "github.com/serverkit/agent/internal/logger"
+ "github.com/serverkit/agent/pkg/protocol"
+)
+
+// wsBackend is the slice of ws.Client functionality the manager needs.
+// We avoid importing ws here to keep the dependency graph clean — the
+// agent package wires concrete clients in via NewManager.
+type wsBackend interface {
+ Transport
+ LastError() error
+ EverConnected() bool
+}
+
+// Manager wraps two Transports (WS primary, poll fallback) and presents a
+// single Transport surface to the agent. It runs WS first; if WS doesn't
+// authenticate within the upgrade deadline OR errors out with a tunnel-
+// incompat signature (RSV1, "engine.io handshake failed"), it shuts WS
+// down and starts the polling client. The active transport is what every
+// Send/SendHeartbeat/etc. call goes to.
+//
+// Once we've fallen back to polling, we stay there until the process
+// restarts. Toggling back and forth would burn through reconnect/auth
+// cycles and the whole point of falling back is "this network can't do
+// WS." Restart-to-recover is fine — agents reconnect on service start
+// and try WS again.
+type Manager struct {
+ primary wsBackend
+ fallback Transport
+ log *logger.Logger
+ handler MessageHandler
+
+ mu sync.RWMutex
+ active Transport
+ mode atomic.Value // Mode
+
+ // Upgrade deadline: WS gets this long to complete a handshake before
+ // we declare it dead and switch to poll.
+ upgradeDeadline time.Duration
+}
+
+// NewManager constructs a transport manager. Pass the WS client as the
+// primary and a poll client as the fallback.
+func NewManager(primary wsBackend, fallback Transport, log *logger.Logger) *Manager {
+ m := &Manager{
+ primary: primary,
+ fallback: fallback,
+ log: log.WithComponent("transport"),
+ upgradeDeadline: 30 * time.Second,
+ }
+ m.active = primary
+ m.mode.Store(primary.Mode())
+ return m
+}
+
+// SetHandler installs the inbound dispatcher on both backends so a
+// transport switch doesn't lose the binding.
+func (m *Manager) SetHandler(h MessageHandler) {
+ m.handler = h
+ m.primary.SetHandler(h)
+ m.fallback.SetHandler(h)
+}
+
+// Mode reports which transport is currently active.
+func (m *Manager) Mode() Mode {
+ if v, ok := m.mode.Load().(Mode); ok {
+ return v
+ }
+ return ModeWS
+}
+
+func (m *Manager) IsConnected() bool {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return m.active.IsConnected()
+}
+
+func (m *Manager) Send(msg interface{}) error {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return m.active.Send(msg)
+}
+
+func (m *Manager) SendHeartbeat(metrics protocol.HeartbeatMetrics) error {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return m.active.SendHeartbeat(metrics)
+}
+
+func (m *Manager) SendCommandResult(commandID string, success bool, data interface{}, errMsg string, duration time.Duration) error {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return m.active.SendCommandResult(commandID, success, data, errMsg, duration)
+}
+
+func (m *Manager) SendStream(channel string, data interface{}) error {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return m.active.SendStream(channel, data)
+}
+
+func (m *Manager) SendError(code, details string) error {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return m.active.SendError(code, details)
+}
+
+func (m *Manager) Session() *auth.SessionToken {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return m.active.Session()
+}
+
+func (m *Manager) Close() error {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return m.active.Close()
+}
+
+// Run executes the WS transport and watches for tunnel-incompat
+// failures. When detected, it cancels WS and runs the poll transport.
+// Blocks until ctx is cancelled.
+func (m *Manager) Run(ctx context.Context) error {
+ wsCtx, cancelWS := context.WithCancel(ctx)
+ defer cancelWS()
+
+ wsDone := make(chan error, 1)
+ go func() {
+ wsDone <- m.primary.Run(wsCtx)
+ }()
+
+ // Watch WS for tunnel-incompat failure within the upgrade deadline.
+ // If detected, kill WS and run poll for the rest of ctx's lifetime.
+ deadline := time.NewTimer(m.upgradeDeadline)
+ defer deadline.Stop()
+
+ check := time.NewTicker(2 * time.Second)
+ defer check.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ cancelWS()
+ <-wsDone
+ return ctx.Err()
+
+ case err := <-wsDone:
+ // WS exited on its own (rare — its loop runs until ctx is
+ // done). If ctx isn't cancelled, treat this as a permanent
+ // WS failure and fall back.
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ m.log.Warn("WS transport exited; falling back to polling", "error", err)
+ return m.runFallback(ctx)
+
+ case <-deadline.C:
+ // Soft deadline: WS hasn't authenticated yet. If it never has
+ // AND the last error looks like a tunnel issue, fall back.
+ // If WS just hasn't connected yet for a benign reason
+ // (panel slow to start), give it more rope.
+ if !m.primary.EverConnected() {
+ lastErr := m.primary.LastError()
+ if isTunnelIncompat(lastErr) {
+ m.log.Warn("WS handshake failed with a tunnel-incompat signature; falling back to polling",
+ "error", lastErr)
+ cancelWS()
+ <-wsDone
+ return m.runFallback(ctx)
+ }
+ m.log.Info("WS not yet connected after upgrade deadline; continuing to retry",
+ "last_error", lastErr)
+ }
+ // Stop checking after the soft deadline; if WS is still
+ // trying it'll either succeed eventually or stay broken
+ // quietly. The user can restart the service to retry from
+ // scratch.
+
+ case <-check.C:
+ // While WS is still inside the upgrade window, check
+ // proactively for unambiguous failure modes that warrant a
+ // fast switch instead of waiting out the deadline.
+ if !m.primary.EverConnected() {
+ if isTunnelIncompat(m.primary.LastError()) {
+ m.log.Warn("WS reports tunnel-incompat error; falling back early to polling",
+ "error", m.primary.LastError())
+ cancelWS()
+ <-wsDone
+ return m.runFallback(ctx)
+ }
+ } else {
+ // WS got through. Stop the deadline timer — we're good.
+ deadline.Stop()
+ }
+ }
+ }
+}
+
+func (m *Manager) runFallback(ctx context.Context) error {
+ m.mu.Lock()
+ m.active = m.fallback
+ m.mu.Unlock()
+ m.mode.Store(m.fallback.Mode())
+ m.log.Info("Active transport switched to polling (streams unavailable in this mode)")
+ return m.fallback.Run(ctx)
+}
+
+// isTunnelIncompat reports whether err carries one of the known
+// signatures of a tunnel intermediary mangling WebSocket frames.
+// Matches both "RSV1" frame errors and engine.io handshake failures
+// after a successful TCP/TLS dial — both indicate the connection is
+// reaching the panel but the WS layer is unusable.
+func isTunnelIncompat(err error) bool {
+ if err == nil {
+ return false
+ }
+ msg := err.Error()
+ return strings.Contains(msg, "RSV1 set") ||
+ strings.Contains(msg, "engine.io handshake failed") ||
+ strings.Contains(msg, "websocket: close 1006") // abnormal closure mid-handshake
+}
diff --git a/agent/internal/transport/poll/client.go b/agent/internal/transport/poll/client.go
new file mode 100644
index 00000000..16619413
--- /dev/null
+++ b/agent/internal/transport/poll/client.go
@@ -0,0 +1,375 @@
+// Package poll implements the REST long-poll fallback transport.
+//
+// Used when WS-incompatible tunnels (free-tier ngrok, Cloudflare quick
+// tunnels) corrupt WebSocket frames. Endpoints (panel side):
+//
+// POST /api/v1/agent/connect — HMAC auth, returns session_token
+// POST /api/v1/agent/poll — heartbeat + long-poll for commands
+// POST /api/v1/agent/result — command result
+// POST /api/v1/agent/disconnect — clean shutdown
+//
+// Streams (logs/metrics fan-out, terminal) are intentionally dropped —
+// streaming features degrade to "view recent only" via the panel REST API.
+package poll
+
+import (
+ "bytes"
+ "context"
+ "crypto/tls"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/serverkit/agent/internal/auth"
+ "github.com/serverkit/agent/internal/config"
+ "github.com/serverkit/agent/internal/logger"
+ "github.com/serverkit/agent/internal/transport"
+ "github.com/serverkit/agent/pkg/protocol"
+)
+
+// Client is the polling-mode transport. Mirrors the surface of ws.Client
+// so agent.Agent doesn't need to know which transport is wired up.
+type Client struct {
+ cfg config.ServerConfig
+ auth *auth.Authenticator
+ log *logger.Logger
+ http *http.Client
+ handler transport.MessageHandler
+
+ mu sync.Mutex
+ session *auth.SessionToken
+ connected atomic.Bool
+
+ // Heartbeat metrics buffered between /poll requests. Updated when
+ // SendHeartbeat is called; read and cleared by the poll loop.
+ hbMu sync.Mutex
+ hbMetrics *protocol.HeartbeatMetrics
+ // One-shot system info, sent on the first /poll after it's queued.
+ sysInfo map[string]interface{}
+
+ baseURL string
+}
+
+// NewClient constructs a poll-mode client. baseURL is derived from the
+// configured server URL — wss://host/agent → https://host. The agent
+// already gets an http(s) scheme out of buildBaseURL.
+func NewClient(cfg config.ServerConfig, authenticator *auth.Authenticator, log *logger.Logger) *Client {
+ c := &Client{
+ cfg: cfg,
+ auth: authenticator,
+ log: log.WithComponent("poll"),
+ http: &http.Client{
+ Timeout: 35 * time.Second, // > server long-poll window (25s)
+ },
+ }
+ if os.Getenv("SERVERKIT_INSECURE_TLS") == "true" {
+ c.http.Transport = &http.Transport{
+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+ }
+ }
+ c.baseURL = buildBaseURL(cfg.URL)
+ return c
+}
+
+// buildBaseURL converts the configured ws(s) server URL to its http(s)
+// equivalent and strips the namespace path. Examples:
+// wss://panel.example.com/agent → https://panel.example.com
+// ws://localhost:5000/agent → http://localhost:5000
+func buildBaseURL(raw string) string {
+ if raw == "" {
+ return ""
+ }
+ u, err := url.Parse(raw)
+ if err != nil {
+ return ""
+ }
+ switch u.Scheme {
+ case "wss":
+ u.Scheme = "https"
+ case "ws":
+ u.Scheme = "http"
+ }
+ u.Path = ""
+ u.RawQuery = ""
+ return strings.TrimRight(u.String(), "/")
+}
+
+func (c *Client) SetHandler(h transport.MessageHandler) { c.handler = h }
+func (c *Client) Mode() transport.Mode { return transport.ModePoll }
+func (c *Client) Session() *auth.SessionToken {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.session
+}
+func (c *Client) IsConnected() bool { return c.connected.Load() }
+
+// Run authenticates, then runs the long-poll loop until ctx is cancelled
+// or auth fails irrecoverably. Reconnects on transient errors.
+func (c *Client) Run(ctx context.Context) error {
+ if err := c.connect(ctx); err != nil {
+ return fmt.Errorf("poll connect: %w", err)
+ }
+ c.log.Info("Connected via polling transport", "base", c.baseURL)
+ defer c.disconnect()
+
+ backoff := 1 * time.Second
+ const backoffMax = 30 * time.Second
+
+ for {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ err := c.pollOnce(ctx)
+ if err == nil {
+ backoff = 1 * time.Second
+ continue
+ }
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ // Transient — back off and retry. Fatal-class errors (401)
+ // are re-handled by re-authenticating.
+ c.log.Warn("Poll cycle failed", "error", err, "backoff", backoff)
+ c.connected.Store(false)
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-time.After(backoff):
+ }
+ if backoff < backoffMax {
+ backoff *= 2
+ }
+ if isAuthError(err) {
+ if cerr := c.connect(ctx); cerr != nil {
+ c.log.Warn("Re-auth failed", "error", cerr)
+ } else {
+ c.log.Info("Re-authenticated polling session")
+ backoff = 1 * time.Second
+ }
+ }
+ }
+}
+
+func (c *Client) connect(ctx context.Context) error {
+ timestamp := time.Now().UnixMilli()
+ nonce := auth.GenerateNonce()
+ signature := c.auth.SignMessageWithNonce(timestamp, nonce)
+
+ body := map[string]interface{}{
+ "agent_id": c.auth.AgentID(),
+ "api_key_prefix": c.auth.GetAPIKeyPrefix(),
+ "signature": signature,
+ "timestamp": timestamp,
+ "nonce": nonce,
+ }
+ var resp struct {
+ Success bool `json:"success"`
+ SessionToken string `json:"session_token"`
+ ServerID string `json:"server_id"`
+ PollInterval int `json:"poll_interval_s"`
+ Error string `json:"error"`
+ }
+ if err := c.postJSON(ctx, "/api/v1/agent/connect", "", body, &resp); err != nil {
+ return err
+ }
+ if !resp.Success {
+ return fmt.Errorf("auth rejected: %s", resp.Error)
+ }
+ c.mu.Lock()
+ c.session = &auth.SessionToken{
+ Token: resp.SessionToken,
+ ExpiresAt: time.Now().Add(1 * time.Hour),
+ }
+ c.mu.Unlock()
+ c.connected.Store(true)
+ return nil
+}
+
+func (c *Client) disconnect() {
+ c.mu.Lock()
+ tok := ""
+ if c.session != nil {
+ tok = c.session.Token
+ }
+ c.mu.Unlock()
+ if tok == "" {
+ return
+ }
+ // Best-effort, don't block — server cleans up on heartbeat timeout
+ // regardless. Use a short context so shutdown isn't held up.
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ _ = c.postJSON(ctx, "/api/v1/agent/disconnect", tok, nil, nil)
+ c.connected.Store(false)
+}
+
+// pollOnce executes a single /poll request, dispatches any returned
+// commands through the handler, and sends a one-shot system_info
+// payload if queued. Returns the request error, if any.
+func (c *Client) pollOnce(ctx context.Context) error {
+ c.mu.Lock()
+ tok := ""
+ if c.session != nil {
+ tok = c.session.Token
+ }
+ c.mu.Unlock()
+ if tok == "" {
+ return fmt.Errorf("no session")
+ }
+
+ c.hbMu.Lock()
+ body := map[string]interface{}{}
+ if c.hbMetrics != nil {
+ body["metrics"] = c.hbMetrics
+ }
+ if c.sysInfo != nil {
+ body["system_info"] = c.sysInfo
+ c.sysInfo = nil
+ }
+ c.hbMu.Unlock()
+
+ var resp struct {
+ Commands []json.RawMessage `json:"commands"`
+ Ack bool `json:"ack"`
+ }
+ if err := c.postJSON(ctx, "/api/v1/agent/poll", tok, body, &resp); err != nil {
+ return err
+ }
+ c.connected.Store(true)
+
+ for _, cmd := range resp.Commands {
+ c.dispatchCommand(cmd)
+ }
+ return nil
+}
+
+// dispatchCommand routes a server-issued command to the agent's
+// MessageHandler. The wire format mirrors what AgentNamespace emits.
+func (c *Client) dispatchCommand(payload json.RawMessage) {
+ if c.handler == nil {
+ c.log.Warn("Dropping command — no handler installed")
+ return
+ }
+ c.handler(protocol.TypeCommand, []byte(payload))
+}
+
+// SendHeartbeat buffers metrics for the next /poll request.
+func (c *Client) SendHeartbeat(metrics protocol.HeartbeatMetrics) error {
+ c.hbMu.Lock()
+ defer c.hbMu.Unlock()
+ m := metrics
+ c.hbMetrics = &m
+ return nil
+}
+
+// SendCommandResult posts the outcome of a server-issued command.
+func (c *Client) SendCommandResult(commandID string, success bool, data interface{}, errMsg string, duration time.Duration) error {
+ c.mu.Lock()
+ tok := ""
+ if c.session != nil {
+ tok = c.session.Token
+ }
+ c.mu.Unlock()
+ body := map[string]interface{}{
+ "command_id": commandID,
+ "success": success,
+ "data": data,
+ "error": errMsg,
+ "duration": int64(duration.Milliseconds()),
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ return c.postJSON(ctx, "/api/v1/agent/result", tok, body, nil)
+}
+
+// SendStream is a no-op in poll mode — streaming features degrade to
+// "view recent only" via the panel's REST API. We log at debug because
+// the agent emits these often (system metrics fan-out) and warning-level
+// would flood desktop.log.
+func (c *Client) SendStream(channel string, data interface{}) error {
+ c.log.Debug("Dropping stream in poll mode", "channel", channel)
+ return nil
+}
+
+// SendError is best-effort — embed in next /poll body. Acceptable to
+// drop because errors are also persisted server-side via heartbeat
+// metadata in most cases.
+func (c *Client) SendError(code, details string) error {
+ c.log.Warn("Agent error in poll mode", "code", code, "details", details)
+ return nil
+}
+
+// Send is the catch-all for protocol packets that don't fit the
+// dedicated methods. The polling protocol only handles the explicit
+// methods, so we surface a soft warning rather than fail.
+func (c *Client) Send(msg interface{}) error {
+ // Special-case system_info because the agent emits it on connect.
+ if m, ok := msg.(map[string]interface{}); ok {
+ if t, _ := m["type"].(string); t == string(protocol.TypeSystemInfo) {
+ info, _ := m["info"].(map[string]interface{})
+ c.hbMu.Lock()
+ c.sysInfo = info
+ c.hbMu.Unlock()
+ return nil
+ }
+ }
+ c.log.Debug("Dropping unsupported Send in poll mode")
+ return nil
+}
+
+func (c *Client) Close() error {
+ c.disconnect()
+ return nil
+}
+
+// postJSON sends a JSON body and decodes a JSON response. Empty body or
+// out is allowed for endpoints that don't have one.
+func (c *Client) postJSON(ctx context.Context, path, token string, body interface{}, out interface{}) error {
+ var rdr io.Reader
+ if body != nil {
+ buf, err := json.Marshal(body)
+ if err != nil {
+ return fmt.Errorf("marshal body: %w", err)
+ }
+ rdr = bytes.NewReader(buf)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, rdr)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("User-Agent", "ServerKit-Agent-Poll/dev")
+ if token != "" {
+ req.Header.Set("X-Session-Token", token)
+ }
+ resp, err := c.http.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode == http.StatusUnauthorized {
+ return errAuth
+ }
+ if resp.StatusCode >= 400 {
+ b, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
+ return fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(b))
+ }
+ if out == nil {
+ return nil
+ }
+ return json.NewDecoder(resp.Body).Decode(out)
+}
+
+var errAuth = fmt.Errorf("session unauthorized")
+
+func isAuthError(err error) bool {
+ return err != nil && (err == errAuth || strings.Contains(err.Error(), "session unauthorized"))
+}
diff --git a/agent/internal/transport/transport.go b/agent/internal/transport/transport.go
new file mode 100644
index 00000000..1c43f8d2
--- /dev/null
+++ b/agent/internal/transport/transport.go
@@ -0,0 +1,84 @@
+// Package transport abstracts the agent ↔ panel link. Two implementations
+// share the same surface:
+//
+// - ws (internal/ws.Client) — primary, long-lived Socket.IO connection.
+// - poll (internal/transport/poll.Client) — REST long-poll fallback used
+// when WS-incompatible tunnels (free-tier ngrok, cf quick tunnels)
+// mangle WebSocket frames.
+//
+// agent.Agent talks to a Transport, not a concrete client, and a small
+// fallback Manager swaps which one is wired up when WS connectivity
+// keeps failing.
+package transport
+
+import (
+ "context"
+ "time"
+
+ "github.com/serverkit/agent/internal/auth"
+ "github.com/serverkit/agent/pkg/protocol"
+)
+
+// MessageHandler is invoked when an inbound packet (typically a command)
+// arrives from the panel. data is the raw JSON payload.
+type MessageHandler func(msgType protocol.MessageType, data []byte)
+
+// Mode names a transport implementation. Surfaced through IPC so the UI
+// can show "Connected via polling" when the agent has fallen back.
+type Mode string
+
+const (
+ ModeWS Mode = "ws"
+ ModePoll Mode = "poll"
+)
+
+// Transport is the shared surface between WS and polling.
+//
+// Streaming methods (SendStream) are best-effort — the polling
+// implementation drops them silently. Callers must not rely on stream
+// delivery for correctness.
+type Transport interface {
+ // SetHandler installs the inbound message dispatcher.
+ SetHandler(MessageHandler)
+
+ // Run blocks until ctx is cancelled or the transport gives up. WS
+ // runs the read/write/ping/reconnect loops; poll runs the
+ // long-poll loop. Returns the reason it exited so the manager can
+ // decide whether to retry, fall back, or surface the error.
+ Run(ctx context.Context) error
+
+ // IsConnected reports whether the transport is currently live (WS:
+ // authenticated socket open; poll: at least one /poll round-trip
+ // succeeded recently).
+ IsConnected() bool
+
+ // Send pushes a generic JSON-able message; only meaningful for WS.
+ // Polling silently no-ops on these unless they map to a known
+ // command result.
+ Send(msg interface{}) error
+
+ // SendHeartbeat dispatches metrics. WS sends an event; polling
+ // piggybacks on the next /poll request.
+ SendHeartbeat(metrics protocol.HeartbeatMetrics) error
+
+ // SendCommandResult delivers the outcome of a command. Both
+ // transports route this synchronously.
+ SendCommandResult(commandID string, success bool, data interface{}, errMsg string, duration time.Duration) error
+
+ // SendStream pushes streaming data (logs, container output, real-time
+ // metrics fan-out). Polling drops these — streaming features
+ // degrade naturally to "view recent only" via the panel's REST API.
+ SendStream(channel string, data interface{}) error
+
+ // SendError surfaces an error to the panel. Best-effort.
+ SendError(code, details string) error
+
+ // Session returns the current session token, or nil if unauthenticated.
+ Session() *auth.SessionToken
+
+ // Close terminates the transport.
+ Close() error
+
+ // Mode reports which implementation this is.
+ Mode() Mode
+}
diff --git a/agent/internal/ws/client.go b/agent/internal/ws/client.go
index 4043e786..3910eeeb 100644
--- a/agent/internal/ws/client.go
+++ b/agent/internal/ws/client.go
@@ -16,11 +16,14 @@ import (
"github.com/serverkit/agent/internal/auth"
"github.com/serverkit/agent/internal/config"
"github.com/serverkit/agent/internal/logger"
+ "github.com/serverkit/agent/internal/transport"
"github.com/serverkit/agent/pkg/protocol"
)
-// MessageHandler is called when a message is received
-type MessageHandler func(msgType protocol.MessageType, data []byte)
+// MessageHandler is the callback fired on inbound packets. Aliased to the
+// transport package so ws.Client implements transport.Transport without
+// adapter glue.
+type MessageHandler = transport.MessageHandler
// Client is a Socket.IO client with auto-reconnect
type Client struct {
@@ -34,6 +37,8 @@ type Client struct {
mu sync.RWMutex
connected bool
reconnecting bool
+ lastErr error
+ everConnected bool
sendCh chan []byte
doneCh chan struct{}
@@ -105,13 +110,18 @@ func (c *Client) Connect(ctx context.Context) error {
return err
}
+ // Compression default: off. Some tunnel intermediaries (free-tier ngrok,
+ // trycloudflare.com quick tunnels) corrupt compressed WebSocket frames —
+ // gorilla then rejects them with "RSV1 set, FIN not set on control". The
+ // env var override exists for users behind a *permanent* cf tunnel or a
+ // reverse proxy that handles WS compression cleanly: setting
+ // SERVERKIT_WS_COMPRESSION=true makes the agent negotiate permessage-
+ // deflate, which is necessary if the panel/proxy unconditionally sends
+ // compressed frames regardless of negotiation.
+ enableCompression := os.Getenv("SERVERKIT_WS_COMPRESSION") == "true"
dialer := websocket.Dialer{
- HandshakeTimeout: 10 * time.Second,
- // Defensive: don't negotiate permessage-deflate. Some intermediaries
- // (notably free-tier ngrok) have been seen to corrupt compressed
- // frames so a control frame arrives with RSV1 set, which gorilla
- // rejects as "RSV1 set, FIN not set on control".
- EnableCompression: false,
+ HandshakeTimeout: 10 * time.Second,
+ EnableCompression: enableCompression,
}
// Only allow insecure TLS when explicitly set via environment variable
@@ -148,6 +158,17 @@ func (c *Client) Connect(ctx context.Context) error {
// Step 1: Read Engine.IO OPEN packet
if err := c.handleEngineIOOpen(); err != nil {
conn.Close()
+ // "RSV1 set, FIN not set on control" is the classic signature of a
+ // tunnel intermediary (cf quick tunnels, free-tier ngrok) injecting
+ // or corrupting WebSocket compression. The user can't fix the panel
+ // from the agent side — the only useful action is "try a different
+ // transport." Surface that explicitly so the error stops being
+ // cryptic.
+ if strings.Contains(err.Error(), "RSV1 set") {
+ c.log.Error("WebSocket frame compression conflict — likely caused by the tunnel between agent and panel",
+ "hint", "try SERVERKIT_WS_COMPRESSION=true, or switch from a Cloudflare quick tunnel (*.trycloudflare.com) to a permanent named tunnel, or front the panel with a direct HTTPS reverse proxy",
+ )
+ }
return fmt.Errorf("engine.io handshake failed: %w", err)
}
@@ -401,9 +422,16 @@ func (c *Client) Run(ctx context.Context) error {
if !connected {
if err := c.Connect(ctx); err != nil {
c.log.Warn("Connection failed", "error", err)
+ c.mu.Lock()
+ c.lastErr = err
+ c.mu.Unlock()
c.handleReconnect(ctx)
continue
}
+ c.mu.Lock()
+ c.everConnected = true
+ c.lastErr = nil
+ c.mu.Unlock()
}
// Start read/write/ping loops
@@ -699,6 +727,30 @@ func (c *Client) Close() error {
}
// Session returns the current session token
+// Mode reports this transport as WS so consumers (UI, log lines) can
+// distinguish from the polling fallback.
+func (c *Client) Mode() transport.Mode { return transport.ModeWS }
+
+// LastError returns the most recent connect or runloop error, or nil
+// when healthy. Used by the transport manager to decide whether to fall
+// back to polling — specifically, RSV1/handshake errors indicate a
+// tunnel intermediary that won't ever let WS through and we shouldn't
+// keep retrying the same dial.
+func (c *Client) LastError() error {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+ return c.lastErr
+}
+
+// EverConnected reports whether the client has successfully completed a
+// handshake at least once during this Run. False after several seconds
+// is the strongest signal that WS won't ever work for this network.
+func (c *Client) EverConnected() bool {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+ return c.everConnected
+}
+
func (c *Client) Session() *auth.SessionToken {
return c.session
}
diff --git a/agent/packaging/msi/Product.wxs b/agent/packaging/msi/Product.wxs
index 9e224dea..42b53923 100644
--- a/agent/packaging/msi/Product.wxs
+++ b/agent/packaging/msi/Product.wxs
@@ -28,11 +28,32 @@
<Property Id="ARPPRODUCTICON" Value="ServerKitAgentIco" />
<Property Id="ARPHELPLINK" Value="https://github.com/jhd3197/ServerKit" />
- <!-- Upgrade handling -->
+ <!-- Upgrade handling.
+ AllowSameVersionUpgrades=yes lets a rebuild of the same version
+ replace itself cleanly — handy during fast iteration where every
+ dev build is "1.6.7" until tagged.
+ Schedule=afterInstallInitialize uninstalls the old product right
+ after the new install begins, before any files are written, so
+ file replacement and ServiceControl Remove run in the right order. -->
<MajorUpgrade
+ AllowSameVersionUpgrades="yes"
DowngradeErrorMessage="A newer version of [ProductName] is already installed."
Schedule="afterInstallInitialize" />
+ <!-- Close any user-context serverkit-agent.exe processes (tray, wizard
+ window) before the install validates file usage. The Windows
+ service is handled by ServiceControl below; this covers the
+ non-service instances. Without this, a running tray pins the .exe
+ and Windows defers replacement to next reboot — which is why
+ users were seeing "installed but still old version" reports. -->
+ <util:CloseApplication
+ Id="CloseAgentExe"
+ Target="serverkit-agent.exe"
+ CloseMessage="yes"
+ TerminateProcess="5"
+ RebootPrompt="no"
+ ElevatedCloseMessage="yes" />
+
<!-- Media -->
<MediaTemplate EmbedCab="yes" />
@@ -181,7 +202,41 @@
Impersonate="yes"
Return="asyncNoWait" />
+ <!-- Hard-stop the service before file replacement. ServiceControl
+ already stops the service during a clean upgrade, but if the
+ service is hung or in a weird state, an ungraceful sc.exe stop
+ is a faster, more reliable cleanup. Errors are ignored — if
+ the service doesn't exist (fresh install) or already stopped,
+ that's fine.
+ deferred + impersonate=no = runs in the elevated installer
+ context, which is what you need to control services. -->
+ <CustomAction Id="StopServiceForce"
+ Directory="INSTALLFOLDER"
+ ExeCommand='[System64Folder]sc.exe stop ServerKitAgent'
+ Execute="deferred"
+ Impersonate="no"
+ Return="ignore" />
+
+ <!-- Final safety net: kill any serverkit-agent.exe still running
+ (the service if sc stop didn't take, the tray if CloseApplication
+ missed it, a ghosted wizard window). /T kills the process tree.
+ Must be deferred + elevated to reach SYSTEM-context children. -->
+ <CustomAction Id="TaskkillAgent"
+ Directory="INSTALLFOLDER"
+ ExeCommand='[System64Folder]taskkill.exe /F /IM serverkit-agent.exe /T'
+ Execute="deferred"
+ Impersonate="no"
+ Return="ignore" />
+
<InstallExecuteSequence>
+ <!-- Order: stop service → kill any lingering processes → MSI
+ replaces files. Both run only on install/upgrade, not on
+ uninstall (where ServiceControl already handles teardown).
+ InstallFiles is the standard action that writes our exe. -->
+ <Custom Action="StopServiceForce" Before="InstallFiles"
+ Condition="NOT REMOVE" />
+ <Custom Action="TaskkillAgent" After="StopServiceForce"
+ Condition="NOT REMOVE" />
<Custom Action="LaunchApp" After="InstallFinalize"
Condition="NOT Installed AND NOT REMOVE" />
</InstallExecuteSequence>
diff --git a/agent/ui/index.html b/agent/ui/index.html
index 6baa2d2b..fc89d814 100644
--- a/agent/ui/index.html
+++ b/agent/ui/index.html
@@ -4,9 +4,55 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ServerKit Agent</title>
+ <!--
+ Inline styles in <head> paint immediately, before main.scss loads.
+ Without this the WebView2 host shows a black rectangle for ~500ms
+ while the JS bundle hydrates — users reported it looked like the
+ app had hung. The loading shell matches the dark theme exactly so
+ there's no flash when React replaces it.
+ -->
+ <style>
+ html, body {
+ margin: 0;
+ height: 100%;
+ background: #09090b;
+ color: #f4f4f5;
+ font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
+ }
+ #root { height: 100%; }
+ .splash {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ height: 100%;
+ flex-direction: column;
+ gap: 12px;
+ color: #a1a1aa;
+ }
+ .splash__spinner {
+ width: 28px;
+ height: 28px;
+ border: 2px solid #27272a;
+ border-top-color: #6366f1;
+ border-radius: 50%;
+ animation: splash-spin 0.8s linear infinite;
+ }
+ .splash__label {
+ font-size: 13px;
+ letter-spacing: 0.02em;
+ }
+ @keyframes splash-spin {
+ to { transform: rotate(360deg); }
+ }
+ </style>
</head>
<body>
- <div id="root"></div>
+ <div id="root">
+ <div class="splash">
+ <div class="splash__spinner"></div>
+ <div class="splash__label">Starting ServerKit Agent…</div>
+ </div>
+ </div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
diff --git a/agent/ui/src/App.jsx b/agent/ui/src/App.jsx
index 64c811ee..be93969a 100644
--- a/agent/ui/src/App.jsx
+++ b/agent/ui/src/App.jsx
@@ -1,4 +1,4 @@
-import { useEffect } from 'react';
+import { useEffect, useState } from 'react';
import { Routes, Route, Navigate, useLocation, useNavigate } from 'react-router-dom';
import Shell from './components/Shell.jsx';
import Overview from './pages/Overview.jsx';
@@ -7,23 +7,55 @@ import Logs from './pages/Logs.jsx';
import Actions from './pages/Actions.jsx';
import About from './pages/About.jsx';
import Pair from './pages/Pair.jsx';
-import { useStatus } from './ipc/hooks.js';
+import { local } from './ipc/client.js';
-// PairGate redirects to /pair when the agent isn't registered yet, except
-// from /pair itself (so the wizard can render its "claimed" stage). Once
-// the agent is paired and we're on /pair, send the user to /overview.
+// PairGate uses /local/status (authoritative — reads config.yaml in this
+// process) as the single source of truth for registration. Earlier
+// versions also consulted the agent service IPC, but that endpoint is
+// silent on a fresh install (the service won't even start without a
+// config), which let users wander into Overview / Actions before pairing
+// — exactly the "let me click around an unconfigured app" report.
+//
+// We deliberately render NOTHING until the first /local/status resolves.
+// The HTML splash from index.html stays on screen during that window, so
+// the user sees a loading state instead of partial UI.
function PairGate({ children }) {
- const { status } = useStatus(2000);
+ const [registered, setRegistered] = useState(null); // null=unknown
const location = useLocation();
const navigate = useNavigate();
useEffect(() => {
- if (!status) return;
+ let cancelled = false;
+ async function tick() {
+ try {
+ const s = await local.status();
+ if (!cancelled) setRegistered(Boolean(s && s.registered));
+ } catch {
+ // Same-process call — if this fails the asset server is
+ // gone and the window is closing.
+ }
+ }
+ tick();
+ const id = setInterval(tick, 2000);
+ return () => { cancelled = true; clearInterval(id); };
+ }, []);
+
+ useEffect(() => {
+ if (registered === null) return; // wait for first answer
const onPair = location.pathname === '/pair';
- if (!status.registered && !onPair) {
+ if (!registered && !onPair) {
navigate('/pair', { replace: true });
}
- }, [status, location.pathname, navigate]);
+ }, [registered, location.pathname, navigate]);
+
+ // Hold render until we know — prevents the unpaired user from seeing
+ // Overview / Actions for a beat before being kicked to /pair.
+ if (registered === null) return null;
+
+ // Hard-deny the non-pair routes when unregistered. The navigate() in
+ // the effect handles the redirect; this keeps the children blank in
+ // the same render so we don't flash the wrong page.
+ if (!registered && location.pathname !== '/pair') return null;
return children;
}
diff --git a/agent/ui/src/components/Sidebar.jsx b/agent/ui/src/components/Sidebar.jsx
index c3d348fa..086be7f9 100644
--- a/agent/ui/src/components/Sidebar.jsx
+++ b/agent/ui/src/components/Sidebar.jsx
@@ -7,6 +7,7 @@ import {
Info,
Server,
} from 'lucide-react';
+import { useStatus } from '../ipc/hooks.js';
const NAV = [
{ to: '/overview', label: 'Overview', icon: LayoutDashboard },
@@ -17,6 +18,11 @@ const NAV = [
];
export default function Sidebar() {
+ // Pulled lazily — sidebar renders on every page so this hook is a
+ // single shared subscription to /status. Errors are intentionally
+ // ignored; the sidebar shows '—' when the version isn't known yet
+ // rather than an error spinner.
+ const { status } = useStatus(5000);
return (
<aside className="sidebar">
<div className="sidebar__brand">
@@ -42,6 +48,14 @@ export default function Sidebar() {
</NavLink>
))}
</nav>
+ <div className="sidebar__footer">
+ <div className="sidebar__version">v{status?.version || '—'}</div>
+ {status?.transport === 'poll' && (
+ <div className="sidebar__transport" title="Connected via REST polling fallback">
+ polling
+ </div>
+ )}
+ </div>
</aside>
);
}
diff --git a/agent/ui/src/ipc/client.js b/agent/ui/src/ipc/client.js
index ad803345..1a11b31f 100644
--- a/agent/ui/src/ipc/client.js
+++ b/agent/ui/src/ipc/client.js
@@ -91,6 +91,10 @@ export const local = {
open: (target) => localCall('/local/open', target),
repair: () => localCall('/local/wizard'),
diag: () => localCall('/local/diag'),
+ // status reads config.yaml in the console process so we can route the
+ // wizard correctly even when the agent service isn't running (which is
+ // the default state on a fresh install — no config, no service).
+ status: () => localGet('/local/status'),
pairStart: (panelUrl, serverName) =>
localCall('/local/pair/start', { panel_url: panelUrl, server_name: serverName }),
pairState: () => localGet('/local/pair/state'),
diff --git a/agent/ui/src/main.jsx b/agent/ui/src/main.jsx
index fbf5d424..69bcf9d7 100644
--- a/agent/ui/src/main.jsx
+++ b/agent/ui/src/main.jsx
@@ -1,13 +1,74 @@
-import { StrictMode } from 'react';
+import { StrictMode, Component } from 'react';
import { createRoot } from 'react-dom/client';
import { HashRouter } from 'react-router-dom';
import App from './App.jsx';
import './styles/main.scss';
+// 1.6.2 had a class of "blank #root" bug reports where a render exception
+// in App or any provider unmounted the index.html splash and left no
+// fallback. The user saw nothing and we got a navReady signal that lied —
+// the bundle ran, the listener fired, and *then* React crashed on mount.
+// This boundary keeps the window from going blank on render errors and
+// echoes the message back to the WebView2 host log via window.agentLog.
+class RootErrorBoundary extends Component {
+ state = { error: null };
+ static getDerivedStateFromError(error) {
+ return { error };
+ }
+ componentDidCatch(error, info) {
+ try {
+ if (window.agentLog) {
+ window.agentLog('error', 'react root: ' + (error && error.stack ? error.stack : String(error)));
+ }
+ } catch { /* ignore — host bridge may not be present */ }
+ }
+ render() {
+ if (this.state.error) {
+ const msg = this.state.error && this.state.error.message
+ ? this.state.error.message
+ : String(this.state.error);
+ return (
+ <div style={{
+ height: '100%',
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: '24px',
+ background: '#09090b',
+ color: '#f4f4f5',
+ fontFamily: 'Segoe UI, system-ui, sans-serif',
+ gap: '12px',
+ }}>
+ <div style={{ fontSize: 16, fontWeight: 600 }}>ServerKit Agent failed to start</div>
+ <div style={{ fontSize: 13, color: '#a1a1aa', maxWidth: 600, textAlign: 'center' }}>
+ Right-click anywhere and choose <strong>Inspect</strong> to see the full error in DevTools.
+ The message below has also been written to <code>desktop.log</code>.
+ </div>
+ <pre style={{
+ fontSize: 12,
+ color: '#fca5a5',
+ background: '#18181b',
+ border: '1px solid #27272a',
+ borderRadius: 6,
+ padding: '12px 16px',
+ maxWidth: '80%',
+ overflow: 'auto',
+ whiteSpace: 'pre-wrap',
+ }}>{msg}</pre>
+ </div>
+ );
+ }
+ return this.props.children;
+ }
+}
+
createRoot(document.getElementById('root')).render(
<StrictMode>
- <HashRouter>
- <App />
- </HashRouter>
+ <RootErrorBoundary>
+ <HashRouter>
+ <App />
+ </HashRouter>
+ </RootErrorBoundary>
</StrictMode>
);
diff --git a/agent/ui/src/pages/Actions.jsx b/agent/ui/src/pages/Actions.jsx
index f07d14d8..2eb2e5a3 100644
--- a/agent/ui/src/pages/Actions.jsx
+++ b/agent/ui/src/pages/Actions.jsx
@@ -1,4 +1,5 @@
import { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
import {
Power,
Square,
@@ -69,6 +70,7 @@ function ActionRow({ icon: Icon, title, desc, action, label = 'Run', danger }) {
export default function Actions() {
const { status } = useStatus(5000);
+ const navigate = useNavigate();
const dashboardUrl = status?.server_url
? status.server_url.replace(/^wss?:\/\//, 'https://').replace(/\/agent$/, '')
: '';
@@ -131,8 +133,8 @@ export default function Actions() {
<ActionRow
icon={KeyRound}
title="Re-pair this server"
- desc="Launches the pairing wizard. Useful when the panel URL changes (e.g. switching tunnels) or to rotate credentials."
- action={local.repair}
+ desc="Reopens the pairing wizard in this window. Useful when the panel URL changes (e.g. switching tunnels) or to rotate credentials."
+ action={async () => { navigate('/pair'); }}
label="Open wizard"
/>
</section>
diff --git a/agent/ui/src/pages/Overview.jsx b/agent/ui/src/pages/Overview.jsx
index 56a1915b..da9f2315 100644
--- a/agent/ui/src/pages/Overview.jsx
+++ b/agent/ui/src/pages/Overview.jsx
@@ -97,6 +97,16 @@ export default function Overview() {
</div>
)}
+ {status?.transport === 'poll' && (
+ <div className="banner banner--info" style={{ background: '#1e1b4b', borderColor: '#4338ca', color: '#c7d2fe' }}>
+ <strong>Limited mode (polling fallback).</strong> The WebSocket link to your panel
+ couldn't be established cleanly, so the agent fell back to a REST polling transport.
+ Heartbeats and commands continue to work; live logs, real-time metrics streaming, and
+ terminal sessions are unavailable in this mode. This usually points at the network
+ path between agent and panel mangling WebSocket frames.
+ </div>
+ )}
+
<section className="card">
<h2 className="card__title">Connection</h2>
<div className="info-row">
@@ -113,6 +123,16 @@ export default function Overview() {
<CopyButton value={status?.agent_id} />
</span>
</div>
+ <div className="info-row">
+ <span className="info-row__label">Transport</span>
+ <span className="info-row__value">
+ {status?.transport === 'poll' ? 'Polling (REST fallback)' : 'WebSocket'}
+ </span>
+ </div>
+ <div className="info-row">
+ <span className="info-row__label">Agent version</span>
+ <span className="info-row__value">{status?.version ? `v${status.version}` : '—'}</span>
+ </div>
<div className="info-row">
<span className="info-row__label">Uptime</span>
<span className="info-row__value">{formatUptime(status?.uptime_seconds)}</span>
diff --git a/agent/ui/src/styles/main.scss b/agent/ui/src/styles/main.scss
index 9195ef57..289ad33d 100644
--- a/agent/ui/src/styles/main.scss
+++ b/agent/ui/src/styles/main.scss
@@ -117,6 +117,32 @@ a {
}
}
+.sidebar__footer {
+ margin-top: auto;
+ padding: $space-sm 4px 4px;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: $space-sm;
+}
+
+.sidebar__version {
+ font-size: 11px;
+ color: $text-tertiary;
+ letter-spacing: 0.04em;
+}
+
+.sidebar__transport {
+ font-size: 10px;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: #c7d2fe;
+ background: #312e81;
+ border: 1px solid #4338ca;
+ padding: 2px 6px;
+ border-radius: $radius-sm;
+}
+
// ─── Page ────────────────────────────────────────────────────────────────
.page {
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index c845957d..92bb6330 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -82,6 +82,11 @@ def create_app(config_name=None):
from app.api.auth import auth_bp
app.register_blueprint(auth_bp, url_prefix='/api/v1/auth')
+ # Agent polling fallback transport (REST equivalent of the WS gateway,
+ # used when tunnels mangle WebSocket frames).
+ from app.api.agent_poll import agent_poll_bp
+ app.register_blueprint(agent_poll_bp, url_prefix='/api/v1/agent')
+
# Register blueprints - Core
from app.api.apps import apps_bp
from app.api.domains import domains_bp
@@ -142,11 +147,11 @@ def create_app(config_name=None):
from app.api.deploy import deploy_bp
app.register_blueprint(deploy_bp, url_prefix='/api/v1/deploy')
- # Register blueprints - Builds & Deployments
- from app.api.builds import builds_bp
- from app.api.deployment_jobs import deployment_jobs_bp
- app.register_blueprint(builds_bp, url_prefix='/api/v1/builds')
- app.register_blueprint(deployment_jobs_bp, url_prefix='/api/v1/deployment-jobs')
+ # Register blueprints - Builds & Deployments
+ from app.api.builds import builds_bp
+ from app.api.deployment_jobs import deployment_jobs_bp
+ app.register_blueprint(builds_bp, url_prefix='/api/v1/builds')
+ app.register_blueprint(deployment_jobs_bp, url_prefix='/api/v1/deployment-jobs')
# Register blueprints - Templates
from app.api.templates import templates_bp
diff --git a/backend/app/api/agent_poll.py b/backend/app/api/agent_poll.py
new file mode 100644
index 00000000..a7bb61bb
--- /dev/null
+++ b/backend/app/api/agent_poll.py
@@ -0,0 +1,141 @@
+"""
+Agent polling fallback transport.
+
+Provides REST endpoints that mirror the heartbeat / command / result
+exchange normally carried over Socket.IO, for agents behind tunnels that
+mangle WebSocket frames (Cloudflare quick tunnels, free-tier ngrok, some
+restrictive corporate proxies). Streaming features — live logs,
+real-time metrics fan-out, terminal sessions — are intentionally NOT
+supported here; they degrade to "view recent only" via the regular API.
+
+Auth model:
+ - POST /connect with the same HMAC payload the WS namespace uses;
+ receive a session_token.
+ - All subsequent calls send "X-Session-Token: <token>". The token
+ looks up the ConnectedAgent in the registry (transport='poll'),
+ which is what authenticates the request — no per-call HMAC.
+"""
+
+from datetime import datetime
+from flask import Blueprint, jsonify, request
+
+from app.services.agent_registry import agent_registry
+from app.utils.ip_utils import is_ip_allowed
+from app.services.anomaly_detection_service import anomaly_detection_service
+
+
+agent_poll_bp = Blueprint('agent_poll', __name__)
+
+
+def _client_ip():
+ return request.remote_addr or 'unknown'
+
+
+@agent_poll_bp.route('/connect', methods=['POST'])
+def connect():
+ """Authenticate an agent and return a session_token bound to a
+ polling-mode ConnectedAgent. Mirrors the on_auth handler in
+ AgentNamespace, minus the socket-room bookkeeping."""
+ data = request.get_json(silent=True) or {}
+ agent_id = data.get('agent_id')
+ api_key_prefix = data.get('api_key_prefix')
+ signature = data.get('signature')
+ timestamp = data.get('timestamp', 0)
+ nonce = data.get('nonce')
+
+ if not all([agent_id, api_key_prefix, signature]):
+ return jsonify({'success': False, 'error': 'Missing required fields'}), 400
+
+ ip = _client_ip()
+ server = agent_registry.verify_agent_auth(
+ agent_id, api_key_prefix, signature, timestamp,
+ nonce=nonce, ip_address=ip,
+ )
+ if not server:
+ return jsonify({'success': False, 'error': 'Authentication failed'}), 401
+
+ if server.allowed_ips and len(server.allowed_ips) > 0:
+ if not is_ip_allowed(ip, server.allowed_ips):
+ anomaly_detection_service.track_ip_blocked(server.id, ip, server.allowed_ips)
+ return jsonify({'success': False, 'error': 'IP not allowed'}), 403
+
+ anomaly_detection_service.check_new_ip(server.id, ip)
+
+ agent_version = (request.headers.get('User-Agent') or '').replace('ServerKit-Agent/', '')
+ # Synthesize a unique socket_id so the registry's existing storage and
+ # heartbeat machinery work unchanged. The "poll-" prefix is what tells
+ # WS-only code paths to skip these agents (no socket_id is reachable
+ # via socketio.emit).
+ import secrets
+ socket_id = f'poll-{secrets.token_urlsafe(12)}'
+
+ session_token = agent_registry.register_agent(
+ server_id=server.id,
+ socket_id=socket_id,
+ ip_address=ip,
+ agent_version=agent_version,
+ transport='poll',
+ )
+
+ return jsonify({
+ 'success': True,
+ 'session_token': session_token,
+ 'server_id': server.id,
+ # Hint for the agent on how often to poll. Long-polls for up to
+ # this many seconds before returning empty so loops are gentle.
+ 'poll_interval_s': 25,
+ })
+
+
+@agent_poll_bp.route('/poll', methods=['POST'])
+def poll():
+ """Long-polling endpoint. The agent posts a heartbeat (with metrics);
+ we record it, then block up to ~25s waiting for queued commands. On
+ return, the agent dispatches whatever commands came back and POSTs
+ each result via /result.
+
+ Body: {"metrics": {...}, "system_info": {...} (optional, sent once)}
+ """
+ token = request.headers.get('X-Session-Token')
+ agent = agent_registry.get_agent_by_token(token)
+ if not agent:
+ return jsonify({'error': 'invalid session'}), 401
+
+ body = request.get_json(silent=True) or {}
+ metrics = body.get('metrics') or {}
+ sysinfo = body.get('system_info')
+
+ agent_registry.update_heartbeat(agent.server_id, metrics)
+ if sysinfo:
+ agent_registry.update_system_info(agent.server_id, sysinfo)
+
+ # Long-poll up to 25s for any queued command. Below the typical
+ # tunnel idle-timeout (Cloudflare ~100s, ngrok ~60s) so we never
+ # discover a dead idle connection mid-wait.
+ commands = agent_registry.drain_outbound(agent, max_wait_s=25.0)
+ return jsonify({
+ 'commands': commands,
+ # Echo the heartbeat ack so the agent can detect a still-live
+ # session even when no commands arrive.
+ 'ack': True,
+ })
+
+
+@agent_poll_bp.route('/result', methods=['POST'])
+def result():
+ """Agent posts the outcome of a command it received from /poll.
+ Wakes the synchronous send_command waiter on the panel side."""
+ token = request.headers.get('X-Session-Token')
+ body = request.get_json(silent=True) or {}
+ if not agent_registry.deliver_result_by_token(token, body):
+ return jsonify({'error': 'unknown command or session'}), 404
+ return jsonify({'ok': True})
+
+
+@agent_poll_bp.route('/disconnect', methods=['POST'])
+def disconnect():
+ """Clean shutdown when the agent is going offline or switching
+ transports. Idempotent — missing token is fine."""
+ token = request.headers.get('X-Session-Token')
+ agent_registry.unregister_by_token(token, reason='client_disconnect')
+ return jsonify({'ok': True})
diff --git a/backend/app/api/servers.py b/backend/app/api/servers.py
index 1f5702ae..35341446 100644
--- a/backend/app/api/servers.py
+++ b/backend/app/api/servers.py
@@ -277,7 +277,15 @@ def get_server(server_id):
return jsonify({'error': 'Server not found'}), 404
result = server.to_dict(include_metrics=True)
- result['is_connected'] = agent_registry.is_agent_connected(server.id)
+ # Surface the live transport so the UI can disable / banner features
+ # that don't work when the agent is on the polling fallback (live
+ # logs, real-time metrics fan-out, terminal). Possible values:
+ # "ws" — long-lived Socket.IO connection, all features work
+ # "poll" — REST polling fallback, streams unavailable
+ # None — agent not connected
+ agent = agent_registry.get_agent(server.id)
+ result['is_connected'] = agent is not None
+ result['transport'] = agent.transport if agent else None
return jsonify(result)
diff --git a/backend/app/services/agent_registry.py b/backend/app/services/agent_registry.py
index 0118aa56..af6efa9f 100644
--- a/backend/app/services/agent_registry.py
+++ b/backend/app/services/agent_registry.py
@@ -24,7 +24,14 @@ from app.models.server import Server, ServerMetrics, ServerCommand, AgentSession
@dataclass
class ConnectedAgent:
- """Represents a connected agent"""
+ """Represents a connected agent.
+
+ transport='ws' — long-lived Socket.IO connection. socket_id is the sid.
+ transport='poll' — REST long-poll fallback. socket_id is a synthesized
+ "poll-<token>" that uniquely identifies the poll
+ session; outbound_queue holds commands waiting to be
+ handed back on the next /poll request.
+ """
server_id: str
socket_id: str
session_token: str
@@ -32,6 +39,9 @@ class ConnectedAgent:
last_heartbeat: datetime
ip_address: str
agent_version: str
+ transport: str = 'ws'
+ # Polling-mode only: commands queued for the next /poll response.
+ outbound_queue: Queue = field(default_factory=Queue)
# Pending commands waiting for response
pending_commands: Dict[str, 'PendingCommand'] = field(default_factory=dict)
@@ -164,11 +174,17 @@ class AgentRegistry:
server_id: str,
socket_id: str,
ip_address: str,
- agent_version: str = None
+ agent_version: str = None,
+ transport: str = 'ws'
) -> str:
"""
Register a newly connected agent.
+ transport='ws' is the existing Socket.IO path; 'poll' is the REST
+ long-poll fallback used when WS-incompatible tunnels (free-tier
+ ngrok, cf quick tunnels) corrupt frames. The two share storage
+ and the command-routing path differs only in send_command.
+
Returns: session_token
"""
session_token = secrets.token_urlsafe(32)
@@ -180,7 +196,8 @@ class AgentRegistry:
connected_at=datetime.utcnow(),
last_heartbeat=datetime.utcnow(),
ip_address=ip_address,
- agent_version=agent_version or 'unknown'
+ agent_version=agent_version or 'unknown',
+ transport=transport,
)
with self._lock:
@@ -413,20 +430,27 @@ class AgentRegistry:
with self._lock:
agent.pending_commands[command_id] = pending
- # Send command via WebSocket
+ # Hand the command to the agent. WS agents get an immediate emit;
+ # polling agents get the command pushed onto their outbound queue
+ # where it sits until the next /api/v1/agent/poll request drains
+ # it. Both paths block below on pending.result_queue.get(timeout).
+ command_payload = {
+ 'type': 'command',
+ 'id': command_id,
+ 'action': action,
+ 'params': params or {},
+ 'timeout': int(timeout * 1000)
+ }
try:
- self._socketio.emit(
- 'command',
- {
- 'type': 'command',
- 'id': command_id,
- 'action': action,
- 'params': params or {},
- 'timeout': int(timeout * 1000)
- },
- room=agent.socket_id,
- namespace='/agent'
- )
+ if agent.transport == 'poll':
+ agent.outbound_queue.put(command_payload)
+ else:
+ self._socketio.emit(
+ 'command',
+ command_payload,
+ room=agent.socket_id,
+ namespace='/agent'
+ )
# Update command status
command_record.status = 'running'
@@ -471,6 +495,70 @@ class AgentRegistry:
return result
+ # ==================== Polling Transport Support ====================
+
+ def get_agent_by_token(self, session_token: str) -> Optional[ConnectedAgent]:
+ """Look up an agent by its session token. Used by polling endpoints
+ which don't have a socket id and authenticate every request via
+ the token instead."""
+ if not session_token:
+ return None
+ with self._lock:
+ for agent in self._agents.values():
+ if agent.session_token == session_token:
+ return agent
+ return None
+
+ def drain_outbound(self, agent: 'ConnectedAgent', max_wait_s: float, max_items: int = 16):
+ """Pull queued commands for a polling-mode agent. Long-polls up to
+ max_wait_s for the FIRST command, then drains anything else
+ already queued without further blocking. Returns a list (possibly
+ empty if max_wait_s elapsed with no work)."""
+ items = []
+ try:
+ first = agent.outbound_queue.get(timeout=max_wait_s)
+ items.append(first)
+ except Empty:
+ return items
+ # Drain anything else already queued, no blocking
+ for _ in range(max_items - 1):
+ try:
+ items.append(agent.outbound_queue.get_nowait())
+ except Empty:
+ break
+ return items
+
+ def deliver_result_by_token(self, session_token: str, result: dict) -> bool:
+ """Polling-side equivalent of handle_command_result. Returns True
+ when the result was matched to a pending command and delivered."""
+ agent = self.get_agent_by_token(session_token)
+ if not agent:
+ return False
+ command_id = result.get('command_id')
+ if not command_id or not isinstance(command_id, str) or len(command_id) > 64:
+ return False
+ with self._lock:
+ pending = agent.pending_commands.get(command_id)
+ if not pending:
+ return False
+ pending.result_queue.put({
+ 'success': result.get('success', False),
+ 'data': result.get('data'),
+ 'error': result.get('error'),
+ 'duration': result.get('duration')
+ })
+ return True
+
+ def unregister_by_token(self, session_token: str, reason: str = 'disconnect'):
+ """Polling-side equivalent of unregister_agent — used when the
+ agent posts /disconnect or when the polling session times out."""
+ agent = self.get_agent_by_token(session_token)
+ if not agent:
+ return
+ self.unregister_agent(agent.socket_id, reason=reason)
+
+ # ==================== Command Result Handling (WS) ====================
+
def handle_command_result(self, socket_id: str, result: dict):
"""Handle command result from agent"""
agent = self.get_agent_by_socket(socket_id)
diff --git a/frontend/src/pages/ServerDetail.jsx b/frontend/src/pages/ServerDetail.jsx
index c64d0500..4db8e04a 100644
--- a/frontend/src/pages/ServerDetail.jsx
+++ b/frontend/src/pages/ServerDetail.jsx
@@ -202,6 +202,14 @@ const ServerDetail = () => {
)}
</div>
</div>
+ {server.transport === 'poll' && (
+ <div className="server-detail-header__transport-banner">
+ <strong>Limited mode:</strong> this agent connected via the REST polling
+ fallback because the WebSocket link couldn't be established cleanly.
+ Heartbeats and one-shot commands work; live logs, real-time metrics, and
+ terminal sessions are unavailable until the WS link is restored.
+ </div>
+ )}
<div className="server-detail-header__actions">
<Button variant="outline" onClick={handlePingServer}>
<RefreshIcon /> Ping
diff --git a/frontend/src/styles/pages/_servers.scss b/frontend/src/styles/pages/_servers.scss
index a1874c37..a0c6aa23 100644
--- a/frontend/src/styles/pages/_servers.scss
+++ b/frontend/src/styles/pages/_servers.scss
@@ -2754,6 +2754,7 @@
padding: $space-5 0 $space-5;
margin-bottom: $space-5;
border-bottom: 1px solid $border-subtle;
+ flex-wrap: wrap;
&__main {
display: flex;
@@ -2763,6 +2764,23 @@
flex: 1;
}
+ &__transport-banner {
+ flex-basis: 100%;
+ margin-top: $space-3;
+ padding: $space-3 $space-4;
+ background: rgba(79, 70, 229, 0.08);
+ border: 1px solid rgba(99, 102, 241, 0.4);
+ border-radius: $radius-md;
+ color: $text-secondary;
+ font-size: $font-size-sm;
+ line-height: 1.5;
+
+ strong {
+ color: $text-primary;
+ margin-right: $space-2;
+ }
+ }
+
&__avatar {
flex-shrink: 0;
width: 56px;