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 console actions, logs UI, and log rotation

Juan Denis354c625fa4d9
diff --git a/VERSION b/VERSION
index 2b26b8d2..9c6d6293 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.5.9
+1.6.1
diff --git a/agent/Makefile b/agent/Makefile
index 7926298f..94a74d76 100644
--- a/agent/Makefile
+++ b/agent/Makefile
@@ -9,10 +9,17 @@ LDFLAGS := -s -w \
-X main.BuildTime=$(BUILD_TIME) \
-X main.GitCommit=$(GIT_COMMIT)
-# Agent-specific LDFLAGS (includes agent package version var)
+# Agent-specific LDFLAGS (includes agent package version var). On Windows
+# we MUST select the GUI subsystem; otherwise Windows attaches a console to
+# every launch (the desktop console then renders behind a stray black
+# cmd.exe-looking window). attachParentConsole() in console_windows.go
+# still re-hooks stdio for CLI subcommands like `status` when invoked from
+# a real terminal.
AGENT_LDFLAGS := $(LDFLAGS) \
-X github.com/serverkit/agent/internal/agent.Version=$(VERSION)
+WINDOWS_LDFLAGS := $(AGENT_LDFLAGS) -H=windowsgui
+
BINARY_NAME := serverkit-agent
DIST_DIR := dist
@@ -45,9 +52,9 @@ build-all:
@echo "Building for Linux arm64..."
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-linux-arm64 ./cmd/agent
@echo "Building for Windows amd64..."
- CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-windows-amd64.exe ./cmd/agent
+ CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "$(WINDOWS_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-windows-amd64.exe ./cmd/agent
@echo "Building for Windows arm64..."
- CGO_ENABLED=0 GOOS=windows GOARCH=arm64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-windows-arm64.exe ./cmd/agent
+ CGO_ENABLED=0 GOOS=windows GOARCH=arm64 go build -ldflags "$(WINDOWS_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-windows-arm64.exe ./cmd/agent
@echo "Building for macOS amd64..."
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-darwin-amd64 ./cmd/agent
@echo "Building for macOS arm64..."
@@ -63,7 +70,7 @@ build-linux:
# Build Windows only
build-windows:
@mkdir -p $(DIST_DIR)
- CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-windows-amd64.exe ./cmd/agent
+ CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "$(WINDOWS_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-windows-amd64.exe ./cmd/agent
# Run tests
test:
diff --git a/agent/cmd/agent/desktop_debug.go b/agent/cmd/agent/desktop_debug.go
index 946c6645..060587bd 100644
--- a/agent/cmd/agent/desktop_debug.go
+++ b/agent/cmd/agent/desktop_debug.go
@@ -20,6 +20,16 @@ type desktopLog struct {
func (d *desktopLog) Path() string { return d.p }
+// File exposes the underlying append-only handle so callers can redirect
+// other writers (stdlib log, slog handlers) into the same file. Returns
+// nil if the desktop log couldn't be opened — callers must guard.
+func (d *desktopLog) File() *os.File {
+ if d == nil {
+ return nil
+ }
+ return d.f
+}
+
func (d *desktopLog) Logf(format string, args ...interface{}) {
if d == nil || d.f == nil {
return
diff --git a/agent/cmd/agent/main.go b/agent/cmd/agent/main.go
index 5cde03c5..5a9d1df2 100644
--- a/agent/cmd/agent/main.go
+++ b/agent/cmd/agent/main.go
@@ -3,6 +3,7 @@ package main
import (
"context"
"fmt"
+ stdlog "log"
"os"
"os/exec"
"os/signal"
@@ -10,9 +11,9 @@ import (
"syscall"
"github.com/serverkit/agent/internal/agent"
+ "github.com/serverkit/agent/internal/agentui"
"github.com/serverkit/agent/internal/config"
"github.com/serverkit/agent/internal/logger"
- "github.com/serverkit/agent/internal/agentui"
"github.com/serverkit/agent/internal/setupui"
"github.com/serverkit/agent/internal/tray"
"github.com/serverkit/agent/internal/updater"
@@ -392,12 +393,19 @@ func setupCmd() *cobra.Command {
return &cobra.Command{
Use: "setup",
Short: "Open the pairing wizard",
- Long: `Opens the native pairing wizard window. Enter the panel URL and a
-passphrase, then type the displayed code into the panel UI to claim this server.
+ Long: `Opens the desktop console at the pairing wizard. Enter the panel
+URL and a server name; the agent generates a code and passphrase to type
+into the panel UI to claim this server.
For headless servers, use 'serverkit-agent pair' instead.`,
RunE: func(cmd *cobra.Command, args []string) error {
- return runSetup()
+ // The wizard now lives inside the React console; setup is a
+ // thin alias that opens it. The PairGate component routes the
+ // user straight to /pair when no config is present.
+ if legacyWizard {
+ return runSetup()
+ }
+ return runConsole()
},
}
}
@@ -423,6 +431,17 @@ func runConsole() error {
defer dbg.Close()
dbg.Logf("--- runConsole start, version=%s pid=%d ---", Version, os.Getpid())
+ // go-webview2 uses the stdlib log package internally for fatal errors
+ // during chromium init. Without this redirect, "Error calling
+ // Webview2Loader: ..." goes to a hidden stdout and we'd never see it
+ // on a blank-window report. Path is the same desktop.log so all the
+ // diagnostic breadcrumbs end up in one file.
+ if f := dbg.File(); f != nil {
+ stdlog.SetOutput(f)
+ stdlog.SetFlags(stdlog.LstdFlags | stdlog.Lmicroseconds)
+ stdlog.SetPrefix("[stdlib] ")
+ }
+
defer func() {
if r := recover(); r != nil {
msg := fmt.Sprintf("ServerKit Agent console crashed:\n\n%v\n\nLog: %s", r, dbg.Path())
@@ -431,7 +450,18 @@ func runConsole() error {
}
}()
- log := logger.New(config.LoggingConfig{Level: "info"})
+ // Point the slog logger at the same desktop.log so internal log.Info
+ // calls in agentui land alongside the dbg.Logf trail. Without this, any
+ // diagnostic logging from the package goes to a hidden stdout (the
+ // console binary uses the windowsgui subsystem) and we end up debugging
+ // blank windows blind.
+ log := logger.New(config.LoggingConfig{
+ Level: "info",
+ File: dbg.Path(),
+ MaxSize: 10,
+ MaxBackups: 2,
+ MaxAge: 7,
+ })
configPath := cfgFile
if configPath == "" {
@@ -460,21 +490,14 @@ func runConsole() error {
return err
}
-// runSetup shows the pairing wizard and exits when it closes.
-// runDesktop runs the unified desktop app (wizard if needed, then tray).
-// The shared body lives in setupui.Run.
+// runSetup is retained as a fallback into the legacy walk wizard. The
+// current setup command points at runConsole, but if WebView2 is somehow
+// unavailable on a target machine the user can still pair via this path
+// by setting SERVERKIT_AGENT_LEGACY_WIZARD=1.
func runSetup() error {
dbg := openDesktopLog()
defer dbg.Close()
- dbg.Logf("--- runSetup start, version=%s pid=%d ---", Version, os.Getpid())
-
- defer func() {
- if r := recover(); r != nil {
- msg := fmt.Sprintf("ServerKit Agent setup crashed:\n\n%v\n\nLog: %s", r, dbg.Path())
- dbg.Logf("PANIC: %v", r)
- showMessageBox("ServerKit Agent", msg, mbIconError)
- }
- }()
+ dbg.Logf("--- runSetup (legacy) start, version=%s pid=%d ---", Version, os.Getpid())
log := logger.New(config.LoggingConfig{Level: "info"})
@@ -482,7 +505,6 @@ func runSetup() error {
if configPath == "" {
configPath = config.DefaultConfigPath()
}
- dbg.Logf("configPath=%s", configPath)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -494,17 +516,20 @@ func runSetup() error {
cancel()
}()
- dbg.Logf("calling setupui.Run …")
- err := setupui.Run(ctx, log, configPath)
- dbg.Logf("setupui.Run returned: %v", err)
- if err != nil {
- showMessageBox("ServerKit Agent",
- fmt.Sprintf("Couldn't open the pairing wizard.\n\n%v\n\nLog: %s", err, dbg.Path()),
- mbIconError)
+ return setupui.Run(ctx, log, configPath)
+}
+
+// init wires the legacy fallback when explicitly requested, replacing the
+// console-based setup runner with the walk wizard. This is purely an escape
+// hatch — primary path is the React console.
+func init() {
+ if os.Getenv("SERVERKIT_AGENT_LEGACY_WIZARD") == "1" {
+ legacyWizard = true
}
- return err
}
+var legacyWizard bool
+
// runDesktop is what `serverkit-agent` (no args) does on a desktop install.
// First-run: shows the pairing wizard. Subsequent runs (config exists): goes
// straight to tray. Either way the tray runs after pairing completes.
diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.go
index d5d8c1ce..7349e6c1 100644
--- a/agent/internal/agent/agent.go
+++ b/agent/internal/agent/agent.go
@@ -1432,6 +1432,20 @@ func (a *Agent) GetEvents(since int64) []events.Event {
return a.events.Snapshot(since)
}
+// ClearLogs rotates agent.log so the desktop console can start with a
+// clean tail. Existing content moves to an automatic backup file. Records
+// the action in the activity log so the user has an audit trail.
+func (a *Agent) ClearLogs() error {
+ if err := a.log.Rotate(); err != nil {
+ return err
+ }
+ if a.events != nil {
+ a.events.Append(events.KindInfo, events.SeverityInfo,
+ "Logs cleared from console", nil)
+ }
+ return nil
+}
+
// GetConnectionInfo returns WebSocket connection information for the IPC API
func (a *Agent) GetConnectionInfo() ipc.ConnectionInfo {
info := ipc.ConnectionInfo{
diff --git a/agent/internal/agentui/actions.go b/agent/internal/agentui/actions.go
new file mode 100644
index 00000000..b77a8f4b
--- /dev/null
+++ b/agent/internal/agentui/actions.go
@@ -0,0 +1,129 @@
+package agentui
+
+import (
+ "encoding/json"
+ "net/http"
+ "os/exec"
+ "time"
+)
+
+// localActions exposes a small set of console-process-level operations to
+// the React app: things that need to happen even when the agent service is
+// down, or that need to be performed by a Windows interactive session
+// rather than by SYSTEM-context service code.
+//
+// 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
+}
+
+func newLocalActions() *localActions {
+ exe, _ := exeForSpawn()
+ return &localActions{exePath: exe}
+}
+
+// register hooks the action handlers into the asset server's mux.
+func (a *localActions) register(mux *http.ServeMux) {
+ mux.HandleFunc("/local/service/restart", a.handleServiceAction("restart"))
+ mux.HandleFunc("/local/service/start", a.handleServiceAction("start"))
+ mux.HandleFunc("/local/service/stop", a.handleServiceAction("stop"))
+ mux.HandleFunc("/local/open", a.handleOpen)
+ mux.HandleFunc("/local/wizard", a.handleWizard)
+ mux.HandleFunc("/local/diag", a.handleDiag)
+}
+
+func writeJSON(w http.ResponseWriter, status int, v interface{}) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(v)
+}
+
+// handleServiceAction performs sc.exe stop/start/restart against the
+// installed ServerKitAgent service. Restart is "stop, brief wait, start"
+// because sc.exe has no native restart verb and the agent's IPC restart
+// is just a graceful stop with no auto-spin-up.
+func (a *localActions) handleServiceAction(action string) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ switch action {
+ case "start":
+ if err := runServiceCmd("start"); err != nil {
+ writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ return
+ }
+ case "stop":
+ if err := runServiceCmd("stop"); err != nil {
+ writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ return
+ }
+ case "restart":
+ // Best-effort stop — ignore "service not running" errors and
+ // move on. Then start. This is what the tray's restart button
+ // should have been doing all along.
+ _ = runServiceCmd("stop")
+ time.Sleep(1500 * time.Millisecond)
+ if err := runServiceCmd("start"); err != nil {
+ writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ return
+ }
+ }
+
+ writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
+ }
+}
+
+// handleOpen launches a path in Explorer or a URL in the default browser.
+// Body: {"path": "C:\\..."} OR {"url": "https://..."}.
+func (a *localActions) handleOpen(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ var body struct {
+ Path string `json:"path"`
+ URL string `json:"url"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid body"})
+ return
+ }
+ target := body.URL
+ if target == "" {
+ target = body.Path
+ }
+ if target == "" {
+ writeJSON(w, http.StatusBadRequest, map[string]string{"error": "path or url required"})
+ return
+ }
+ if err := openTarget(target); err != nil {
+ writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
+}
+
+// handleWizard spawns the pairing wizard as a detached child process.
+// Used by the Re-pair button — gives the user a fresh form without
+// interrupting the running console window.
+func (a *localActions) handleWizard(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ if a.exePath == "" {
+ writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "agent executable path unknown"})
+ return
+ }
+ cmd := exec.Command(a.exePath, "setup")
+ if err := cmd.Start(); err != nil {
+ writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ return
+ }
+ // We don't Wait on the child — it lives on its own.
+ writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
+}
diff --git a/agent/internal/agentui/diag.go b/agent/internal/agentui/diag.go
new file mode 100644
index 00000000..eb490e6f
--- /dev/null
+++ b/agent/internal/agentui/diag.go
@@ -0,0 +1,214 @@
+package agentui
+
+import (
+ "archive/zip"
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "time"
+
+ "gopkg.in/yaml.v3"
+)
+
+// handleDiag builds a diagnostic bundle on the user's Desktop. Includes the
+// current agent log, the activity events file, a redacted copy of
+// config.yaml, and a small system info JSON. Returns the path so the React
+// app can prompt "Open in Explorer" or just inform the user where it is.
+//
+// We write to Desktop on purpose: the most common reason to grab a bundle
+// is to share it with someone, and Desktop is the universally-known spot.
+// Falls back to the user's home dir if Desktop can't be located.
+func (a *localActions) handleDiag(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ dest, err := buildDiagBundle()
+ if err != nil {
+ writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]string{"path": dest})
+}
+
+func buildDiagBundle() (string, error) {
+ dataDir := dataDirGuess()
+ dest := diagDestPath()
+
+ out, err := os.Create(dest)
+ if err != nil {
+ return "", fmt.Errorf("create diag: %w", err)
+ }
+ defer out.Close()
+
+ zw := zip.NewWriter(out)
+ defer zw.Close()
+
+ // Current agent log (might not exist if never started — that's fine)
+ if dataDir != "" {
+ _ = addFileToZip(zw, filepath.Join(dataDir, "logs", "agent.log"), "agent.log")
+ // Most-recent rotated backup, if any (lumberjack names them with a
+ // timestamp suffix). Search and add up to 3 to keep the bundle slim.
+ if backups, err := findLogBackups(filepath.Join(dataDir, "logs")); err == nil {
+ for i, p := range backups {
+ if i >= 3 {
+ break
+ }
+ _ = addFileToZip(zw, p, "logs-backups/"+filepath.Base(p))
+ }
+ }
+ // Events
+ _ = addFileToZip(zw, filepath.Join(dataDir, "events.json"), "events.json")
+ // Config (redacted)
+ if redacted, err := redactedConfigYAML(filepath.Join(dataDir, "config.yaml")); err == nil {
+ _ = addBytesToZip(zw, "config.redacted.yaml", redacted)
+ }
+ }
+
+ // System info written last so it's the easiest to find when somebody
+ // opens the zip.
+ sysJSON, _ := json.MarshalIndent(systemInfo(), "", " ")
+ _ = addBytesToZip(zw, "sysinfo.json", sysJSON)
+
+ return dest, nil
+}
+
+func addFileToZip(zw *zip.Writer, src, archivedName string) error {
+ info, err := os.Stat(src)
+ if err != nil || info.IsDir() {
+ return err
+ }
+ f, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ w, err := zw.Create(archivedName)
+ if err != nil {
+ return err
+ }
+ _, err = io.Copy(w, f)
+ return err
+}
+
+func addBytesToZip(zw *zip.Writer, name string, data []byte) error {
+ w, err := zw.Create(name)
+ if err != nil {
+ return err
+ }
+ _, err = w.Write(data)
+ return err
+}
+
+// redactedConfigYAML reads config.yaml and returns it with any auth secrets
+// stripped. We don't need the api_key / api_secret to debug connectivity,
+// and shipping them through casual support channels is a bad habit.
+func redactedConfigYAML(path string) ([]byte, error) {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ var doc map[string]interface{}
+ if err := yaml.Unmarshal(data, &doc); err != nil {
+ // Couldn't parse — return the raw bytes with a header noting that
+ // redaction was skipped. Better than failing the bundle.
+ var buf bytes.Buffer
+ buf.WriteString("# diag: failed to parse for redaction; original returned as-is\n")
+ buf.Write(data)
+ return buf.Bytes(), nil
+ }
+ if auth, ok := doc["auth"].(map[string]interface{}); ok {
+ for _, k := range []string{"api_key", "api_secret", "apikey", "apisecret"} {
+ if _, has := auth[k]; has {
+ auth[k] = "[REDACTED]"
+ }
+ }
+ }
+ return yaml.Marshal(doc)
+}
+
+func findLogBackups(dir string) ([]string, error) {
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return nil, err
+ }
+ var out []string
+ for _, e := range entries {
+ name := e.Name()
+ if strings.HasPrefix(name, "agent-") && (strings.HasSuffix(name, ".log") || strings.HasSuffix(name, ".log.gz")) {
+ out = append(out, filepath.Join(dir, name))
+ }
+ }
+ // Newest first
+ sortDescByModTime(out)
+ return out, nil
+}
+
+func sortDescByModTime(paths []string) {
+ type entry struct {
+ path string
+ mod time.Time
+ }
+ infos := make([]entry, 0, len(paths))
+ for _, p := range paths {
+ st, err := os.Stat(p)
+ if err != nil {
+ continue
+ }
+ infos = append(infos, entry{p, st.ModTime()})
+ }
+ // Tiny list (<= a handful) — bubble sort is plenty.
+ for i := 0; i < len(infos); i++ {
+ for j := i + 1; j < len(infos); j++ {
+ if infos[j].mod.After(infos[i].mod) {
+ infos[i], infos[j] = infos[j], infos[i]
+ }
+ }
+ }
+ for i, e := range infos {
+ if i < len(paths) {
+ paths[i] = e.path
+ }
+ }
+}
+
+func systemInfo() map[string]interface{} {
+ host, _ := os.Hostname()
+ return map[string]interface{}{
+ "os": runtime.GOOS,
+ "arch": runtime.GOARCH,
+ "hostname": host,
+ "go_version": runtime.Version(),
+ "generated": time.Now().Format(time.RFC3339),
+ }
+}
+
+func dataDirGuess() string {
+ // Mirrors agent/config.DefaultConfigPath() without importing it (avoids
+ // a cycle with the rest of the agent package). Best-effort — if the env
+ // var isn't set we just skip the parts that need it.
+ if pd := os.Getenv("ProgramData"); pd != "" {
+ return filepath.Join(pd, "ServerKit", "Agent")
+ }
+ return ""
+}
+
+func diagDestPath() string {
+ stamp := time.Now().Format("20060102-150405")
+ name := fmt.Sprintf("serverkit-diag-%s.zip", stamp)
+ if home, err := os.UserHomeDir(); err == nil {
+ desktop := filepath.Join(home, "Desktop")
+ if st, err := os.Stat(desktop); err == nil && st.IsDir() {
+ return filepath.Join(desktop, name)
+ }
+ return filepath.Join(home, name)
+ }
+ return name
+}
diff --git a/agent/internal/agentui/pairer.go b/agent/internal/agentui/pairer.go
new file mode 100644
index 00000000..9b8efcba
--- /dev/null
+++ b/agent/internal/agentui/pairer.go
@@ -0,0 +1,174 @@
+package agentui
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "sync"
+
+ "github.com/serverkit/agent/internal/logger"
+ "github.com/serverkit/agent/internal/pairdriver"
+)
+
+// pairer adapts the callback-style pairdriver into a polled state machine
+// the React wizard can drive over HTTP. The wizard POSTs /local/pair/start
+// once with panel URL + server name; from then on it polls
+// /local/pair/state every second to render the current stage and react
+// to claim / error transitions.
+type pairer struct {
+ log *logger.Logger
+ configPath string
+
+ mu sync.Mutex
+ state string // "idle" | "enrolling" | "waiting" | "claimed" | "error"
+ code string
+ codeFmt string
+ pass string
+ panelURL string
+ server string
+ errMsg string
+ cancel context.CancelFunc
+}
+
+func newPairer(log *logger.Logger, configPath string) *pairer {
+ return &pairer{
+ log: log.WithComponent("agentui-pair"),
+ configPath: configPath,
+ state: "idle",
+ }
+}
+
+// register adds the wizard endpoints to the asset server's mux.
+func (p *pairer) register(mux *http.ServeMux) {
+ mux.HandleFunc("/local/pair/start", p.handleStart)
+ mux.HandleFunc("/local/pair/state", p.handleState)
+ mux.HandleFunc("/local/pair/cancel", p.handleCancel)
+}
+
+type pairStartRequest struct {
+ PanelURL string `json:"panel_url"`
+ ServerName string `json:"server_name"`
+}
+
+type pairStateResponse struct {
+ State string `json:"state"`
+ Code string `json:"code,omitempty"`
+ CodeFormatted string `json:"code_formatted,omitempty"`
+ Passphrase string `json:"passphrase,omitempty"`
+ PanelURL string `json:"panel_url,omitempty"`
+ ServerName string `json:"server_name,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+func (p *pairer) handleStart(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ var req pairStartRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid body"})
+ return
+ }
+ if req.PanelURL == "" {
+ writeJSON(w, http.StatusBadRequest, map[string]string{"error": "panel_url is required"})
+ return
+ }
+
+ pass, err := pairdriver.GeneratePassphrase()
+ if err != nil {
+ writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ return
+ }
+
+ p.mu.Lock()
+ if p.cancel != nil {
+ // Replace any in-flight pairing — typical when the user edits the
+ // form and re-submits.
+ p.cancel()
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ p.cancel = cancel
+ p.state = "enrolling"
+ p.errMsg = ""
+ p.code = ""
+ p.codeFmt = ""
+ p.pass = pass
+ p.panelURL = req.PanelURL
+ p.server = req.ServerName
+ p.mu.Unlock()
+
+ cb := pairdriver.Callbacks{
+ OnEnrolled: func(code, formatted string) {
+ p.mu.Lock()
+ p.state = "waiting"
+ p.code = code
+ p.codeFmt = formatted
+ p.mu.Unlock()
+ },
+ OnClaimed: func(serverName string) {
+ p.mu.Lock()
+ p.state = "claimed"
+ if serverName != "" {
+ p.server = serverName
+ }
+ 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")
+ },
+ OnError: func(err error) {
+ p.mu.Lock()
+ // Cancellation isn't a "failure" the UI should surface.
+ if !errors.Is(err, context.Canceled) {
+ p.state = "error"
+ p.errMsg = err.Error()
+ }
+ p.mu.Unlock()
+ },
+ }
+
+ go pairdriver.Run(ctx, p.log, p.configPath, req.PanelURL, pass, req.ServerName, cb)
+
+ writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
+}
+
+func (p *pairer) handleState(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ p.mu.Lock()
+ resp := pairStateResponse{
+ State: p.state,
+ Code: p.code,
+ CodeFormatted: p.codeFmt,
+ Passphrase: p.pass,
+ PanelURL: p.panelURL,
+ ServerName: p.server,
+ Error: p.errMsg,
+ }
+ p.mu.Unlock()
+ writeJSON(w, http.StatusOK, resp)
+}
+
+func (p *pairer) handleCancel(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ p.mu.Lock()
+ if p.cancel != nil {
+ p.cancel()
+ }
+ p.state = "idle"
+ p.code = ""
+ p.codeFmt = ""
+ p.pass = ""
+ p.errMsg = ""
+ p.mu.Unlock()
+ writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
+}
diff --git a/agent/internal/agentui/platform_other.go b/agent/internal/agentui/platform_other.go
new file mode 100644
index 00000000..1cdbb843
--- /dev/null
+++ b/agent/internal/agentui/platform_other.go
@@ -0,0 +1,20 @@
+//go:build !windows
+
+package agentui
+
+import "fmt"
+
+// runServiceCmd is a stub on non-Windows: the console window is Windows-only
+// for now, and the platform-specific service controls land alongside the
+// cross-platform webview wrapper later.
+func runServiceCmd(verb string) 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")
+}
+
+func exeForSpawn() (string, error) {
+ return "", fmt.Errorf("not implemented on this platform")
+}
diff --git a/agent/internal/agentui/platform_windows.go b/agent/internal/agentui/platform_windows.go
new file mode 100644
index 00000000..cd2a6d08
--- /dev/null
+++ b/agent/internal/agentui/platform_windows.go
@@ -0,0 +1,38 @@
+//go:build windows
+
+package agentui
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "syscall"
+)
+
+// runServiceCmd issues sc.exe verb against ServerKitAgent. The MSI grants
+// BUILTIN\Users start/stop/configure rights so this works as the regular
+// user with no UAC prompt.
+func runServiceCmd(verb string) error {
+ cmd := exec.Command("sc.exe", verb, "ServerKitAgent")
+ cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("sc %s: %w (output: %s)", verb, err, string(out))
+ }
+ return nil
+}
+
+// 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.
+func openTarget(target string) error {
+ cmd := exec.Command("rundll32", "url.dll,FileProtocolHandler", target)
+ cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
+ return cmd.Start()
+}
+
+// exeForSpawn returns the path to the currently running agent binary so the
+// wizard re-launch can spawn another instance of the same exe.
+func exeForSpawn() (string, error) {
+ return os.Executable()
+}
diff --git a/agent/internal/agentui/preflight_other.go b/agent/internal/agentui/preflight_other.go
new file mode 100644
index 00000000..3ea019dc
--- /dev/null
+++ b/agent/internal/agentui/preflight_other.go
@@ -0,0 +1,6 @@
+//go:build !windows
+
+package agentui
+
+func detectWebView2() string { return "" }
+func preflightWebView2() error { return nil }
diff --git a/agent/internal/agentui/preflight_windows.go b/agent/internal/agentui/preflight_windows.go
new file mode 100644
index 00000000..b0f66dc7
--- /dev/null
+++ b/agent/internal/agentui/preflight_windows.go
@@ -0,0 +1,59 @@
+//go:build windows
+
+package agentui
+
+import (
+ "fmt"
+
+ "golang.org/x/sys/windows/registry"
+)
+
+// WebView2 evergreen runtime registers itself under this UUID. We probe both
+// the 32-bit and 64-bit hives plus per-user, mirroring Microsoft's own
+// detection guidance. If pv is non-empty we treat the runtime as installed.
+//
+// https://learn.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution#detect-if-a-webview2-runtime-is-already-installed
+const webview2GUID = `{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}`
+
+// detectWebView2 returns the installed runtime version, or empty string if
+// not installed. Errors at the registry layer are folded into "not present"
+// — the calling code only needs a yes/no with a version when found.
+func detectWebView2() string {
+ candidates := []struct {
+ root registry.Key
+ path string
+ }{
+ {registry.LOCAL_MACHINE, `SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\` + webview2GUID},
+ {registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\EdgeUpdate\Clients\` + webview2GUID},
+ {registry.CURRENT_USER, `Software\Microsoft\EdgeUpdate\Clients\` + webview2GUID},
+ }
+ for _, c := range candidates {
+ k, err := registry.OpenKey(c.root, c.path, registry.QUERY_VALUE)
+ if err != nil {
+ continue
+ }
+ v, _, err := k.GetStringValue("pv")
+ k.Close()
+ if err == nil && v != "" {
+ return v
+ }
+ }
+ return ""
+}
+
+// preflightWebView2 returns nil when the runtime is present, or an error
+// pointing the user at the download URL. We surface this *before* trying
+// to construct the webview, because go-webview2's NewWithOptions can
+// silently produce a non-nil but non-functional handle in certain
+// failure modes — leaving the user with a blank window and no error.
+func preflightWebView2() error {
+ v := detectWebView2()
+ if v == "" {
+ return fmt.Errorf(
+ "WebView2 runtime not installed. " +
+ "Install the Evergreen Bootstrapper from " +
+ "https://developer.microsoft.com/microsoft-edge/webview2/ and try again",
+ )
+ }
+ return nil
+}
diff --git a/agent/internal/agentui/server.go b/agent/internal/agentui/server.go
index e313bf84..358e39a9 100644
--- a/agent/internal/agentui/server.go
+++ b/agent/internal/agentui/server.go
@@ -6,6 +6,8 @@ import (
"net"
"net/http"
"time"
+
+ "github.com/serverkit/agent/internal/logger"
)
// startAssetServer binds an HTTP server to a free 127.0.0.1 port and serves
@@ -15,7 +17,7 @@ import (
// panel all behave the same as when running the dev server, which keeps
// surprises out of the migration. Returns the URL to navigate to and a
// shutdown func that stops the server cleanly.
-func startAssetServer(ctx context.Context) (url string, shutdown func(), err error) {
+func startAssetServer(ctx context.Context, log *logger.Logger, configPath string) (url string, shutdown func(), err error) {
dist, err := distFS()
if err != nil {
return "", nil, fmt.Errorf("load embedded ui: %w", err)
@@ -29,6 +31,8 @@ func startAssetServer(ctx context.Context) (url string, shutdown func(), err err
}
mux := http.NewServeMux()
+ newLocalActions().register(mux)
+ newPairer(log, configPath).register(mux)
mux.Handle("/", http.FileServer(http.FS(dist)))
srv := &http.Server{
diff --git a/agent/internal/agentui/window_windows.go b/agent/internal/agentui/window_windows.go
index 82901820..65ab0f5f 100644
--- a/agent/internal/agentui/window_windows.go
+++ b/agent/internal/agentui/window_windows.go
@@ -24,39 +24,72 @@ import (
func Run(ctx context.Context, log *logger.Logger, configPath string) error {
runtime.LockOSThread()
+ log.Info("agentui.Run: starting")
+
+ // Preflight: bail with a clear error before constructing the webview.
+ // Skipping this leads to "blank window" reports when the runtime is
+ // missing — go-webview2 doesn't always return nil on failure.
+ if v := detectWebView2(); v == "" {
+ log.Error("agentui.Run: WebView2 runtime not detected")
+ return fmt.Errorf(
+ "WebView2 runtime not installed. " +
+ "Download the Evergreen Bootstrapper from " +
+ "https://developer.microsoft.com/microsoft-edge/webview2/ and re-run setup",
+ )
+ } else {
+ log.Info("agentui.Run: WebView2 runtime detected", "version", v)
+ }
+
target := os.Getenv("SERVERKIT_AGENT_UI_DEV")
var stopServer func()
if target == "" {
- url, shutdown, err := startAssetServer(ctx)
+ log.Info("agentui.Run: starting embedded asset server")
+ url, shutdown, err := startAssetServer(ctx, log, configPath)
if err != nil {
+ log.Error("agentui.Run: asset server failed", "error", err)
return fmt.Errorf("start asset server: %w", err)
}
+ log.Info("agentui.Run: asset server up", "url", url)
target = url
stopServer = shutdown
} else {
- log.Info("agent UI: using dev server", "url", target)
+ // Even in dev mode we still need the action/pair endpoints — the
+ // Vite dev server only serves UI assets. Start the asset server
+ // alongside it; dev UI fetches the local API by absolute origin.
+ _, shutdown, err := startAssetServer(ctx, log, configPath)
+ if err != nil {
+ return fmt.Errorf("start asset server: %w", err)
+ }
+ stopServer = shutdown
+ log.Info("agentui.Run: using dev server", "url", target)
}
if stopServer != nil {
defer stopServer()
}
+ log.Info("agentui.Run: constructing WebView2 window")
w := webview2.NewWithOptions(webview2.WebViewOptions{
Debug: os.Getenv("SERVERKIT_AGENT_UI_DEVTOOLS") == "true",
AutoFocus: true,
WindowOptions: webview2.WindowOptions{
- Title: "ServerKit Agent",
- Width: 900,
- Height: 620,
+ Title: "ServerKit Agent",
+ // Sidebar is 220px; content area at 1200x800 lands at 980x800
+ // which gives the Overview metric cards and the Logs/Activity
+ // timeline room to breathe without horizontal scrollbars.
+ Width: 1200,
+ Height: 800,
IconId: 2,
Center: true,
},
})
if w == nil {
- return fmt.Errorf("webview2 unavailable; ensure the WebView2 runtime is installed")
+ log.Error("agentui.Run: webview2.NewWithOptions returned nil")
+ return fmt.Errorf("webview2 init failed; the runtime may be present but blocked by group policy or AV")
}
defer w.Destroy()
- w.SetSize(900, 620, webview2.HintMin)
+ w.SetSize(900, 600, webview2.HintMin)
+ log.Info("agentui.Run: navigating", "url", target)
w.Navigate(target)
// Hook ctx cancellation to terminate the webview from a background
@@ -64,9 +97,12 @@ func Run(ctx context.Context, log *logger.Logger, configPath string) error {
// signal to break it cleanly when the parent process is torn down.
go func() {
<-ctx.Done()
+ log.Info("agentui.Run: ctx cancelled, terminating webview")
w.Terminate()
}()
+ log.Info("agentui.Run: entering message loop (w.Run)")
w.Run()
+ log.Info("agentui.Run: message loop exited cleanly")
return nil
}
diff --git a/agent/internal/ipc/handlers.go b/agent/internal/ipc/handlers.go
index 13e86820..e5aabaab 100644
--- a/agent/internal/ipc/handlers.go
+++ b/agent/internal/ipc/handlers.go
@@ -63,6 +63,25 @@ func (h *Handlers) HandleMetricsHistory(w http.ResponseWriter, r *http.Request)
})
}
+// HandleLogsClear rotates the agent log so the live tail in the desktop
+// console starts fresh. Existing entries move to a timestamped backup file
+// (lumberjack handles the rename) and the agent continues writing to a
+// brand-new agent.log without re-opening or interrupting any goroutine.
+func (h *Handlers) HandleLogsClear(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ if err := h.provider.ClearLogs(); err != nil {
+ h.writeJSON(w, map[string]interface{}{
+ "success": false,
+ "error": err.Error(),
+ })
+ return
+ }
+ h.writeJSON(w, map[string]bool{"success": true})
+}
+
// HandleEvents returns the agent's recent activity events. Optional `since`
// query param (unix milliseconds) makes the endpoint cheap to poll: clients
// pass the timestamp of the most recent event they've seen and only get
diff --git a/agent/internal/ipc/server.go b/agent/internal/ipc/server.go
index bcc2fa62..496b9a1e 100644
--- a/agent/internal/ipc/server.go
+++ b/agent/internal/ipc/server.go
@@ -19,6 +19,7 @@ type StatusProvider interface {
GetMetricsHistory() []MetricSample
GetConnectionInfo() ConnectionInfo
GetRecentLogs(lines int) []string
+ ClearLogs() error
GetEvents(since int64) []events.Event
Restart() error
}
@@ -129,6 +130,7 @@ func (s *Server) Start(ctx context.Context) error {
mux.HandleFunc("/metrics", handlers.HandleMetrics)
mux.HandleFunc("/metrics/history", handlers.HandleMetricsHistory)
mux.HandleFunc("/events", handlers.HandleEvents)
+ mux.HandleFunc("/logs/clear", handlers.HandleLogsClear)
mux.HandleFunc("/connection", handlers.HandleConnection)
mux.HandleFunc("/logs", handlers.HandleLogs)
mux.HandleFunc("/restart", handlers.HandleRestart)
diff --git a/agent/internal/logger/logger.go b/agent/internal/logger/logger.go
index d2ed06bc..7f65bc80 100644
--- a/agent/internal/logger/logger.go
+++ b/agent/internal/logger/logger.go
@@ -13,6 +13,11 @@ import (
// Logger wraps slog.Logger with additional context
type Logger struct {
*slog.Logger
+ // rotator is the lumberjack writer when file logging is enabled. Nil
+ // when only stdout is configured. Exposed via Rotate() so the desktop
+ // console's Logs-tab "Clear" button can roll the file without racing
+ // the live writer.
+ rotator *lumberjack.Logger
}
// New creates a new logger with the given configuration
@@ -41,19 +46,20 @@ func New(cfg config.LoggingConfig) *Logger {
writers = append(writers, os.Stdout)
// Also write to file if configured
+ var rotator *lumberjack.Logger
if cfg.File != "" {
// Ensure log directory exists
dir := filepath.Dir(cfg.File)
if err := os.MkdirAll(dir, 0755); err == nil {
// Use lumberjack for log rotation
- fileWriter := &lumberjack.Logger{
+ rotator = &lumberjack.Logger{
Filename: cfg.File,
MaxSize: cfg.MaxSize, // megabytes
MaxBackups: cfg.MaxBackups,
MaxAge: cfg.MaxAge, // days
Compress: cfg.Compress,
}
- writers = append(writers, fileWriter)
+ writers = append(writers, rotator)
}
}
@@ -63,12 +69,23 @@ func New(cfg config.LoggingConfig) *Logger {
handler := slog.NewJSONHandler(multiWriter, opts)
logger := slog.New(handler)
- return &Logger{Logger: logger}
+ return &Logger{Logger: logger, rotator: rotator}
}
-// With returns a new logger with additional attributes
+// Rotate triggers a manual log rotation. No-op when file logging is
+// disabled. Used by the desktop console's "Clear logs" button so the live
+// writer flushes to a backup before the in-memory tail clears.
+func (l *Logger) Rotate() error {
+ if l.rotator == nil {
+ return nil
+ }
+ return l.rotator.Rotate()
+}
+
+// With returns a new logger with additional attributes. Carries the rotator
+// reference so component loggers can also trigger rotation if needed.
func (l *Logger) With(args ...any) *Logger {
- return &Logger{Logger: l.Logger.With(args...)}
+ return &Logger{Logger: l.Logger.With(args...), rotator: l.rotator}
}
// WithComponent returns a logger with a component name
diff --git a/agent/internal/pairdriver/driver.go b/agent/internal/pairdriver/driver.go
new file mode 100644
index 00000000..b6c23d99
--- /dev/null
+++ b/agent/internal/pairdriver/driver.go
@@ -0,0 +1,172 @@
+// Package pairdriver runs the agent's pairing protocol: enroll with the
+// panel, wait for the operator to claim, persist the resulting credentials.
+// It's UI-agnostic — both the legacy walk wizard (setupui) and the
+// React-based console wizard (agentui) drive it via callbacks.
+package pairdriver
+
+import (
+ "context"
+ "crypto/rand"
+ "fmt"
+ "math/big"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "time"
+
+ "github.com/serverkit/agent/internal/config"
+ "github.com/serverkit/agent/internal/logger"
+ "github.com/serverkit/agent/internal/metrics"
+ "github.com/serverkit/agent/internal/pairing"
+)
+
+// passphraseAlphabet excludes confusable characters (0/o/1/i/l) for
+// readability. Lowercase so the operator's natural typing matches the
+// displayed value — no shift-dance, no caps-lock surprises.
+const passphraseAlphabet = "23456789abcdefghjkmnpqrstuvwxyz"
+
+// GeneratePassphrase returns a fresh 8-char passphrase for an enroll
+// request. 8 chars from this 30-char alphabet ≈ 39 bits of entropy, which
+// is overkill for a one-shot value that becomes useless once the panel
+// claims the agent.
+func GeneratePassphrase() (string, error) {
+ const n = 8
+ max := big.NewInt(int64(len(passphraseAlphabet)))
+ buf := make([]byte, n)
+ for i := 0; i < n; i++ {
+ idx, err := rand.Int(rand.Reader, max)
+ if err != nil {
+ return "", err
+ }
+ buf[i] = passphraseAlphabet[idx.Int64()]
+ }
+ return string(buf), nil
+}
+
+// Callbacks lets the UI observe state transitions in the pairing driver.
+// All callbacks fire on a background goroutine; UI code is responsible for
+// marshalling them onto its own thread when relevant.
+type Callbacks struct {
+ OnEnrolled func(code, formatted string)
+ OnClaimed func(serverName string)
+ OnError func(err error)
+}
+
+// Run performs the full enroll → wait-for-claim → save-credentials flow.
+// It returns when pairing succeeds, the user cancels (ctx done), or an
+// error occurs. All progress is reported via cb.
+func Run(
+ ctx context.Context,
+ log *logger.Logger,
+ configPath, panelURL, passphrase, displayName string,
+ cb Callbacks,
+) {
+ panelURL = NormalizePanelURL(panelURL)
+
+ kp, err := pairing.LoadOrCreate(pairing.DefaultKeyPath())
+ if err != nil {
+ cb.OnError(fmt.Errorf("load keypair: %w", err))
+ return
+ }
+
+ collector := metrics.NewCollector(config.MetricsConfig{}, log)
+ infoCtx, infoCancel := context.WithTimeout(ctx, 8*time.Second)
+ sysInfo, _ := collector.GetSystemInfo(infoCtx)
+ infoCancel()
+
+ sysMap := buildSystemInfo(sysInfo, displayName)
+
+ client := pairing.NewClient(panelURL, log)
+ enrollCtx, enrollCancel := context.WithTimeout(ctx, 30*time.Second)
+ enrollResp, err := client.Enroll(enrollCtx, pairing.EnrollRequest{
+ Pubkey: kp.PublicKeyHex(),
+ Passphrase: passphrase,
+ MachineID: config.MachineID(),
+ SystemInfo: sysMap,
+ })
+ enrollCancel()
+ if err != nil {
+ cb.OnError(fmt.Errorf("enroll: %w", err))
+ return
+ }
+
+ cb.OnEnrolled(enrollResp.PairCode, enrollResp.PairCodeFormatted)
+
+ creds, err := client.WaitForClaim(ctx, func(code, formatted, _ string) {
+ cb.OnEnrolled(code, formatted)
+ })
+ if err != nil {
+ if ctx.Err() != nil {
+ return // user cancelled
+ }
+ cb.OnError(fmt.Errorf("waiting for claim: %w", err))
+ return
+ }
+
+ if err := saveCredentials(configPath, panelURL, creds); err != nil {
+ cb.OnError(fmt.Errorf("save credentials: %w", err))
+ return
+ }
+
+ cb.OnClaimed(creds.Name)
+}
+
+// NormalizePanelURL strips trailing slashes and adds an https:// prefix
+// when the user types a bare hostname.
+func NormalizePanelURL(u string) string {
+ u = strings.TrimSpace(u)
+ if !strings.HasPrefix(u, "http://") && !strings.HasPrefix(u, "https://") {
+ u = "https://" + u
+ }
+ return strings.TrimSuffix(u, "/")
+}
+
+func buildSystemInfo(sysInfo *metrics.SystemInfo, displayName string) map[string]interface{} {
+ m := map[string]interface{}{}
+ if sysInfo != nil {
+ m["hostname"] = sysInfo.Hostname
+ m["os"] = sysInfo.OS
+ m["platform"] = sysInfo.Platform
+ m["platform_version"] = sysInfo.PlatformVersion
+ m["architecture"] = sysInfo.Architecture
+ m["cpu_cores"] = sysInfo.CPUCores
+ m["total_memory"] = sysInfo.TotalMemory
+ m["total_disk"] = sysInfo.TotalDisk
+ } else {
+ hostname, _ := os.Hostname()
+ m["hostname"] = hostname
+ m["os"] = runtime.GOOS
+ m["architecture"] = runtime.GOARCH
+ }
+ if displayName = strings.TrimSpace(displayName); displayName != "" {
+ m["display_name"] = displayName
+ }
+ return m
+}
+
+func saveCredentials(configPath, panelURL string, creds *pairing.Credentials) error {
+ cfg, err := config.Load(configPath)
+ if err != nil {
+ cfg = config.Default()
+ }
+ wsURL := strings.TrimSuffix(panelURL, "/")
+ wsURL = strings.Replace(wsURL, "https://", "wss://", 1)
+ wsURL = strings.Replace(wsURL, "http://", "ws://", 1)
+ cfg.Server.URL = wsURL + "/agent"
+ cfg.Agent.ID = creds.AgentID
+ cfg.Agent.Name = creds.Name
+ cfg.Auth.APIKey = creds.APIKey
+ cfg.Auth.APISecret = creds.APISecret
+
+ if configPath == "" {
+ configPath = config.DefaultConfigPath()
+ }
+ if err := os.MkdirAll(filepath.Dir(configPath), 0700); err != nil {
+ return err
+ }
+ if err := cfg.Save(configPath); err != nil {
+ return err
+ }
+ return cfg.SaveCredentials()
+}
diff --git a/agent/internal/setupui/setupui.go b/agent/internal/setupui/setupui.go
index 4601a225..5fdbc545 100644
--- a/agent/internal/setupui/setupui.go
+++ b/agent/internal/setupui/setupui.go
@@ -1,47 +1,15 @@
-// Package setupui shows a small native desktop wizard that walks an operator
-// through pairing the agent with a ServerKit panel. The pairing protocol
-// itself lives here; the platform-specific window code lives in window_*.go.
+// Package setupui shows the legacy native-walk pairing wizard. The pairing
+// protocol itself moved to internal/pairdriver so both this wizard and the
+// React-based agentui console can drive it.
package setupui
import (
"context"
- "crypto/rand"
- "fmt"
- "math/big"
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "time"
"github.com/serverkit/agent/internal/config"
"github.com/serverkit/agent/internal/logger"
- "github.com/serverkit/agent/internal/metrics"
- "github.com/serverkit/agent/internal/pairing"
)
-// passphraseAlphabet excludes confusable characters (0/o/1/i/l) for
-// readability. Lowercase so the operator's natural typing matches the
-// displayed value — no shift-dance, no caps-lock surprises.
-const passphraseAlphabet = "23456789abcdefghjkmnpqrstuvwxyz"
-
-// generatePassphrase returns a fresh 8-char passphrase for an enroll request.
-// 8 chars from this 30-char alphabet ≈ 39 bits of entropy, which is overkill
-// for a one-shot value that becomes useless once the panel claims the agent.
-func generatePassphrase() (string, error) {
- const n = 8
- max := big.NewInt(int64(len(passphraseAlphabet)))
- buf := make([]byte, n)
- for i := 0; i < n; i++ {
- idx, err := rand.Int(rand.Reader, max)
- if err != nil {
- return "", err
- }
- buf[i] = passphraseAlphabet[idx.Int64()]
- }
- return string(buf), nil
-}
-
// Run shows the pairing wizard and blocks until the user closes it.
// configPath may be empty to use the default location.
func Run(ctx context.Context, log *logger.Logger, configPath string) error {
@@ -50,129 +18,3 @@ func Run(ctx context.Context, log *logger.Logger, configPath string) error {
}
return runWindow(ctx, log.WithComponent("setupui"), configPath)
}
-
-// pairingCallbacks lets the platform-specific window observe state
-// transitions in the pairing driver. All callbacks fire on a background
-// goroutine; UI code is responsible for marshalling them onto its own thread.
-type pairingCallbacks struct {
- onEnrolled func(code, formatted string)
- onClaimed func(serverName string)
- onError func(err error)
-}
-
-// runPairing performs the full enroll → wait-for-claim → save-credentials flow.
-// It returns when pairing succeeds, the user cancels, or an error occurs.
-// All progress is reported via cb.
-func runPairing(
- ctx context.Context,
- log *logger.Logger,
- configPath, panelURL, passphrase, displayName string,
- cb pairingCallbacks,
-) {
- panelURL = normalizePanelURL(panelURL)
-
- kp, err := pairing.LoadOrCreate(pairing.DefaultKeyPath())
- if err != nil {
- cb.onError(fmt.Errorf("load keypair: %w", err))
- return
- }
-
- collector := metrics.NewCollector(config.MetricsConfig{}, log)
- infoCtx, infoCancel := context.WithTimeout(ctx, 8*time.Second)
- sysInfo, _ := collector.GetSystemInfo(infoCtx)
- infoCancel()
-
- sysMap := buildSystemInfo(sysInfo, displayName)
-
- client := pairing.NewClient(panelURL, log)
- enrollCtx, enrollCancel := context.WithTimeout(ctx, 30*time.Second)
- enrollResp, err := client.Enroll(enrollCtx, pairing.EnrollRequest{
- Pubkey: kp.PublicKeyHex(),
- Passphrase: passphrase,
- MachineID: config.MachineID(),
- SystemInfo: sysMap,
- })
- enrollCancel()
- if err != nil {
- cb.onError(fmt.Errorf("enroll: %w", err))
- return
- }
-
- cb.onEnrolled(enrollResp.PairCode, enrollResp.PairCodeFormatted)
-
- creds, err := client.WaitForClaim(ctx, func(code, formatted, _ string) {
- cb.onEnrolled(code, formatted)
- })
- if err != nil {
- if ctx.Err() != nil {
- return // user cancelled
- }
- cb.onError(fmt.Errorf("waiting for claim: %w", err))
- return
- }
-
- if err := saveCredentials(configPath, panelURL, creds); err != nil {
- cb.onError(fmt.Errorf("save credentials: %w", err))
- return
- }
-
- startServiceIfInstalled()
- cb.onClaimed(creds.Name)
-}
-
-func normalizePanelURL(u string) string {
- u = strings.TrimSpace(u)
- if !strings.HasPrefix(u, "http://") && !strings.HasPrefix(u, "https://") {
- u = "https://" + u
- }
- return strings.TrimSuffix(u, "/")
-}
-
-func buildSystemInfo(sysInfo *metrics.SystemInfo, displayName string) map[string]interface{} {
- m := map[string]interface{}{}
- if sysInfo != nil {
- m["hostname"] = sysInfo.Hostname
- m["os"] = sysInfo.OS
- m["platform"] = sysInfo.Platform
- m["platform_version"] = sysInfo.PlatformVersion
- m["architecture"] = sysInfo.Architecture
- m["cpu_cores"] = sysInfo.CPUCores
- m["total_memory"] = sysInfo.TotalMemory
- m["total_disk"] = sysInfo.TotalDisk
- } else {
- hostname, _ := os.Hostname()
- m["hostname"] = hostname
- m["os"] = runtime.GOOS
- m["architecture"] = runtime.GOARCH
- }
- if displayName = strings.TrimSpace(displayName); displayName != "" {
- m["display_name"] = displayName
- }
- return m
-}
-
-func saveCredentials(configPath, panelURL string, creds *pairing.Credentials) error {
- cfg, err := config.Load(configPath)
- if err != nil {
- cfg = config.Default()
- }
- wsURL := strings.TrimSuffix(panelURL, "/")
- wsURL = strings.Replace(wsURL, "https://", "wss://", 1)
- wsURL = strings.Replace(wsURL, "http://", "ws://", 1)
- cfg.Server.URL = wsURL + "/agent"
- cfg.Agent.ID = creds.AgentID
- cfg.Agent.Name = creds.Name
- cfg.Auth.APIKey = creds.APIKey
- cfg.Auth.APISecret = creds.APISecret
-
- if configPath == "" {
- configPath = config.DefaultConfigPath()
- }
- if err := os.MkdirAll(filepath.Dir(configPath), 0700); err != nil {
- return err
- }
- if err := cfg.Save(configPath); err != nil {
- return err
- }
- return cfg.SaveCredentials()
-}
diff --git a/agent/internal/setupui/window_windows.go b/agent/internal/setupui/window_windows.go
index 000696a9..e079cd3d 100644
--- a/agent/internal/setupui/window_windows.go
+++ b/agent/internal/setupui/window_windows.go
@@ -19,6 +19,7 @@ import (
dec "github.com/lxn/walk/declarative"
"github.com/serverkit/agent/internal/logger"
+ "github.com/serverkit/agent/internal/pairdriver"
)
//go:embed serverkit.ico
@@ -496,7 +497,7 @@ func (w *wizardUI) handleConnect() {
w.formErr.SetText("Panel URL is required.")
return
}
- pass, err := generatePassphrase()
+ pass, err := pairdriver.GeneratePassphrase()
if err != nil {
w.formErr.SetText("Could not generate a passphrase: " + err.Error())
return
@@ -511,8 +512,8 @@ func (w *wizardUI) handleConnect() {
w.pairCancel = cancel
w.mu.Unlock()
- cb := pairingCallbacks{
- onEnrolled: func(code, formatted string) {
+ cb := pairdriver.Callbacks{
+ OnEnrolled: func(code, formatted string) {
w.mw.Synchronize(func() {
w.rawCode = code
w.codeLabel.SetText(displayCode(code, formatted))
@@ -520,7 +521,7 @@ func (w *wizardUI) handleConnect() {
w.showStage(stagePairing)
})
},
- onClaimed: func(serverName string) {
+ OnClaimed: func(serverName string) {
w.mw.Synchronize(func() {
if serverName == "" {
serverName = "this server"
@@ -528,8 +529,9 @@ func (w *wizardUI) handleConnect() {
w.doneSub.SetText(fmt.Sprintf("This machine is now connected to ServerKit as %q.\n\nThe agent service has been started in the background. You can close this window.", serverName))
w.showStage(stageDone)
})
+ startServiceIfInstalled()
},
- onError: func(err error) {
+ OnError: func(err error) {
w.mw.Synchronize(func() {
msg := errorPretty(err)
if w.pairPanel.Visible() {
@@ -544,7 +546,7 @@ func (w *wizardUI) handleConnect() {
},
}
- go runPairing(pairCtx, w.log, w.configPath, url, pass, name, cb)
+ go pairdriver.Run(pairCtx, w.log, w.configPath, url, pass, name, cb)
}
// handleCancel rolls back to the form stage and cancels any in-flight pairing.
diff --git a/agent/internal/tray/tray.go b/agent/internal/tray/tray.go
index 40750fa5..a7d9ea1b 100644
--- a/agent/internal/tray/tray.go
+++ b/agent/internal/tray/tray.go
@@ -290,17 +290,10 @@ func (a *App) stopAgent() {
}
func (a *App) restartAgent() {
- // Try IPC restart first (graceful)
- if a.client.IsAgentRunning() {
- if err := a.client.Restart(); err == nil {
- a.showNotification("Agent Restarting", "ServerKit agent is restarting")
- time.Sleep(2 * time.Second)
- a.refresh()
- return
- }
- }
-
- // Fall back to service restart
+ // IPC "restart" is actually just a graceful stop — SCM doesn't
+ // auto-relaunch a service that exits cleanly, so the previous
+ // IPC-first path silently left the user with a stopped agent and
+ // required a second click. Always do sc stop + sc start instead.
if err := restartService(); err != nil {
a.showNotification("Failed to Restart", err.Error())
return
diff --git a/agent/ui/src/App.jsx b/agent/ui/src/App.jsx
index 0ab76d5a..64c811ee 100644
--- a/agent/ui/src/App.jsx
+++ b/agent/ui/src/App.jsx
@@ -1,22 +1,47 @@
-import { Routes, Route, Navigate } from 'react-router-dom';
+import { useEffect } from 'react';
+import { Routes, Route, Navigate, useLocation, useNavigate } from 'react-router-dom';
import Shell from './components/Shell.jsx';
import Overview from './pages/Overview.jsx';
import Activity from './pages/Activity.jsx';
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';
+
+// 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.
+function PairGate({ children }) {
+ const { status } = useStatus(2000);
+ const location = useLocation();
+ const navigate = useNavigate();
+
+ useEffect(() => {
+ if (!status) return;
+ const onPair = location.pathname === '/pair';
+ if (!status.registered && !onPair) {
+ navigate('/pair', { replace: true });
+ }
+ }, [status, location.pathname, navigate]);
+
+ return children;
+}
export default function App() {
return (
- <Routes>
- <Route element={<Shell />}>
- <Route path="/overview" element={<Overview />} />
- <Route path="/activity" element={<Activity />} />
- <Route path="/logs" element={<Logs />} />
- <Route path="/actions" element={<Actions />} />
- <Route path="/about" element={<About />} />
- </Route>
- <Route path="*" element={<Navigate to="/overview" replace />} />
- </Routes>
+ <PairGate>
+ <Routes>
+ <Route path="/pair" element={<Pair />} />
+ <Route element={<Shell />}>
+ <Route path="/overview" element={<Overview />} />
+ <Route path="/activity" element={<Activity />} />
+ <Route path="/logs" element={<Logs />} />
+ <Route path="/actions" element={<Actions />} />
+ <Route path="/about" element={<About />} />
+ </Route>
+ <Route path="*" element={<Navigate to="/overview" replace />} />
+ </Routes>
+ </PairGate>
);
}
diff --git a/agent/ui/src/ipc/client.js b/agent/ui/src/ipc/client.js
index 994eaeb8..ad803345 100644
--- a/agent/ui/src/ipc/client.js
+++ b/agent/ui/src/ipc/client.js
@@ -47,5 +47,52 @@ export const ipc = {
events: (since = 0) => get(`/events${since ? `?since=${since}` : ''}`),
connection: () => get('/connection'),
logs: (lines = 200) => get(`/logs?lines=${lines}`),
+ clearLogs: () => post('/logs/clear'),
restart: () => post('/restart'),
};
+
+// "local" calls hit the asset server in the *console process*, not the
+// agent service. These are the operations that have to happen even when
+// the agent service is down (Start the service, Re-pair) or that need an
+// interactive Windows session (Open in Explorer / browser).
+async function localCall(path, body) {
+ const res = await fetch(path, {
+ method: 'POST',
+ headers: body ? { 'Content-Type': 'application/json' } : undefined,
+ body: body ? JSON.stringify(body) : null,
+ });
+ if (!res.ok) {
+ let msg = res.statusText;
+ try {
+ const j = await res.json();
+ if (j && j.error) msg = j.error;
+ } catch { /* keep statusText */ }
+ const err = new Error(msg);
+ err.status = res.status;
+ throw err;
+ }
+ return res.json();
+}
+
+async function localGet(path) {
+ const res = await fetch(path);
+ if (!res.ok) {
+ const err = new Error(res.statusText);
+ err.status = res.status;
+ throw err;
+ }
+ return res.json();
+}
+
+export const local = {
+ serviceStart: () => localCall('/local/service/start'),
+ serviceStop: () => localCall('/local/service/stop'),
+ serviceRestart: () => localCall('/local/service/restart'),
+ open: (target) => localCall('/local/open', target),
+ repair: () => localCall('/local/wizard'),
+ diag: () => localCall('/local/diag'),
+ pairStart: (panelUrl, serverName) =>
+ localCall('/local/pair/start', { panel_url: panelUrl, server_name: serverName }),
+ pairState: () => localGet('/local/pair/state'),
+ pairCancel: () => localCall('/local/pair/cancel'),
+};
diff --git a/agent/ui/src/ipc/hooks.js b/agent/ui/src/ipc/hooks.js
index 9c9fff88..8a357afb 100644
--- a/agent/ui/src/ipc/hooks.js
+++ b/agent/ui/src/ipc/hooks.js
@@ -56,3 +56,8 @@ export function useEvents(intervalMs = 3000) {
const { data, error } = usePolling(() => ipc.events(0), intervalMs);
return { events: data?.events || [], error };
}
+
+export function useLogs(lines = 500, intervalMs = 2000) {
+ const { data, error } = usePolling(() => ipc.logs(lines), intervalMs);
+ return { lines: data?.lines || [], count: data?.count || 0, error };
+}
diff --git a/agent/ui/src/pages/Actions.jsx b/agent/ui/src/pages/Actions.jsx
index 74e7f6c5..f07d14d8 100644
--- a/agent/ui/src/pages/Actions.jsx
+++ b/agent/ui/src/pages/Actions.jsx
@@ -1,15 +1,161 @@
+import { useState } from 'react';
+import {
+ Power,
+ Square,
+ RefreshCw,
+ FolderOpen,
+ Globe,
+ KeyRound,
+ Package,
+} from 'lucide-react';
+import { useStatus } from '../ipc/hooks.js';
+import { local } from '../ipc/client.js';
+
+// Actions are bucketed so the most-common operations sit on top and the
+// destructive / re-pair ones live further down. A shared ActionRow renders
+// them with icon + label + description + button.
+
+function ActionRow({ icon: Icon, title, desc, action, label = 'Run', danger }) {
+ const [busy, setBusy] = useState(false);
+ const [feedback, setFeedback] = useState(null);
+
+ async function onClick() {
+ if (busy) return;
+ setBusy(true);
+ setFeedback(null);
+ try {
+ await action();
+ setFeedback({ ok: true, msg: 'Done' });
+ } catch (err) {
+ setFeedback({ ok: false, msg: err.message || 'Failed' });
+ } finally {
+ setBusy(false);
+ setTimeout(() => setFeedback(null), 3000);
+ }
+ }
+
+ return (
+ <div className="action">
+ <div className="action__icon">
+ <Icon size={18} />
+ </div>
+ <div className="action__body">
+ <div className="action__title">{title}</div>
+ <div className="action__desc">{desc}</div>
+ </div>
+ <div className="action__buttons">
+ {feedback && (
+ <span
+ className={
+ 'action__feedback ' +
+ (feedback.ok ? 'action__feedback--ok' : 'action__feedback--err')
+ }
+ >
+ {feedback.msg}
+ </span>
+ )}
+ <button
+ type="button"
+ className={'btn' + (danger ? ' btn--danger' : '')}
+ onClick={onClick}
+ disabled={busy}
+ >
+ {busy ? '…' : label}
+ </button>
+ </div>
+ </div>
+ );
+}
+
export default function Actions() {
+ const { status } = useStatus(5000);
+ const dashboardUrl = status?.server_url
+ ? status.server_url.replace(/^wss?:\/\//, 'https://').replace(/\/agent$/, '')
+ : '';
+
return (
<div className="page">
<header className="page__header">
- <h1 className="page__title">Actions</h1>
- <p className="page__sub">
- <span className="muted">Coming next milestone — Start, Stop, Restart, Re-pair, diagnostic bundle.</span>
- </p>
+ <div>
+ <h1 className="page__title">Actions</h1>
+ <p className="page__sub muted">Service controls, recovery, and quick-open shortcuts.</p>
+ </div>
</header>
- <div className="card empty-state">
- Service controls and recovery actions will live here.
- </div>
+
+ <section className="card card--padded">
+ <div className="action-group__heading">Service</div>
+ <ActionRow
+ icon={RefreshCw}
+ title="Restart agent"
+ desc="Stops then starts the ServerKitAgent service. Use this after re-pairing or changing config."
+ action={local.serviceRestart}
+ label="Restart"
+ />
+ <ActionRow
+ icon={Power}
+ title="Start agent"
+ desc="Starts the service if it's not running."
+ action={local.serviceStart}
+ label="Start"
+ />
+ <ActionRow
+ icon={Square}
+ title="Stop agent"
+ desc="Stops the service. The console window stays open."
+ action={local.serviceStop}
+ label="Stop"
+ danger
+ />
+ </section>
+
+ <section className="card card--padded">
+ <div className="action-group__heading">Quick open</div>
+ <ActionRow
+ icon={FolderOpen}
+ title="Open log folder"
+ desc="Opens C:\\ProgramData\\ServerKit\\Agent\\logs in Explorer."
+ action={() => local.open({ path: 'C:\\ProgramData\\ServerKit\\Agent\\logs' })}
+ label="Open"
+ />
+ <ActionRow
+ icon={Globe}
+ title="Open dashboard"
+ desc={dashboardUrl ? `Opens ${dashboardUrl} in your browser.` : 'Opens the panel URL once the agent is paired.'}
+ action={() => local.open({ url: dashboardUrl })}
+ label="Open"
+ />
+ </section>
+
+ <section className="card card--padded">
+ <div className="action-group__heading">Pairing</div>
+ <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}
+ label="Open wizard"
+ />
+ </section>
+
+ <section className="card card--padded">
+ <div className="action-group__heading">Support</div>
+ <ActionRow
+ icon={Package}
+ title="Generate diagnostic bundle"
+ desc="Zips agent.log, recent backups, redacted config, events, and system info to your Desktop. Safe to share — credentials are stripped."
+ action={async () => {
+ const res = await local.diag();
+ if (res?.path) {
+ // Open the parent folder so the user sees the
+ // newly-created zip in Explorer rather than
+ // opening the zip itself.
+ const parent = res.path.replace(/[\\/][^\\/]*$/, '');
+ await local.open({ path: parent });
+ }
+ }}
+ label="Generate"
+ />
+ </section>
</div>
);
}
diff --git a/agent/ui/src/pages/Logs.jsx b/agent/ui/src/pages/Logs.jsx
index 4199d17f..9cd44833 100644
--- a/agent/ui/src/pages/Logs.jsx
+++ b/agent/ui/src/pages/Logs.jsx
@@ -1,15 +1,185 @@
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { Trash2, Search } from 'lucide-react';
+import { useLogs } from '../ipc/hooks.js';
+import { ipc } from '../ipc/client.js';
+
+const LEVELS = ['all', 'info', 'warn', 'error'];
+
+// Each line is one JSON object emitted by slog. Tolerate plain text too —
+// during early boot the lumberjack rotation can produce a mixed file.
+function parseLine(raw) {
+ try {
+ const obj = JSON.parse(raw);
+ return {
+ time: obj.time || '',
+ level: (obj.level || 'INFO').toLowerCase(),
+ msg: obj.msg || '',
+ component: obj.component || '',
+ extras: extractExtras(obj),
+ raw,
+ };
+ } catch {
+ return { time: '', level: 'info', msg: raw, component: '', extras: {}, raw };
+ }
+}
+
+function extractExtras(obj) {
+ const skip = new Set(['time', 'level', 'msg', 'component']);
+ const out = {};
+ for (const [k, v] of Object.entries(obj)) {
+ if (!skip.has(k)) out[k] = v;
+ }
+ return out;
+}
+
+function formatTime(iso) {
+ if (!iso) return '';
+ // ISO strings are long; surface only HH:MM:SS plus milliseconds.
+ const m = /T(\d{2}:\d{2}:\d{2}\.\d{3})/.exec(iso);
+ return m ? m[1] : iso;
+}
+
+function LogRow({ entry }) {
+ const lvl = entry.level || 'info';
+ return (
+ <div className={`logrow logrow--${lvl}`}>
+ <span className="logrow__time">{formatTime(entry.time)}</span>
+ <span className={`logrow__level logrow__level--${lvl}`}>{lvl}</span>
+ {entry.component && <span className="logrow__component">{entry.component}</span>}
+ <span className="logrow__msg">{entry.msg}</span>
+ {Object.keys(entry.extras).length > 0 && (
+ <span className="logrow__extras">
+ {Object.entries(entry.extras).map(([k, v]) => (
+ <span key={k}>
+ <em>{k}=</em>
+ <code>{typeof v === 'string' ? v : JSON.stringify(v)}</code>
+ </span>
+ ))}
+ </span>
+ )}
+ </div>
+ );
+}
+
export default function Logs() {
+ const { lines, error } = useLogs(500, 2000);
+ const [filter, setFilter] = useState('all');
+ const [query, setQuery] = useState('');
+ const [autoScroll, setAutoScroll] = useState(true);
+ const [clearing, setClearing] = useState(false);
+ const scrollerRef = useRef(null);
+
+ const parsed = useMemo(() => lines.map(parseLine), [lines]);
+
+ const visible = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ return parsed.filter((e) => {
+ if (filter !== 'all' && e.level !== filter) return false;
+ if (q && !e.raw.toLowerCase().includes(q)) return false;
+ return true;
+ });
+ }, [parsed, filter, query]);
+
+ // Auto-scroll on new lines unless the user has scrolled up. Conservative
+ // heuristic: if the scroller is within 100 px of the bottom we treat the
+ // user as "following" the tail.
+ useEffect(() => {
+ if (!autoScroll || !scrollerRef.current) return;
+ const el = scrollerRef.current;
+ el.scrollTop = el.scrollHeight;
+ }, [visible.length, autoScroll]);
+
+ function onScroll() {
+ if (!scrollerRef.current) return;
+ const el = scrollerRef.current;
+ const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 100;
+ setAutoScroll(atBottom);
+ }
+
+ async function handleClear() {
+ if (clearing) return;
+ setClearing(true);
+ try {
+ await ipc.clearLogs();
+ } catch (err) {
+ // Surface the failure on the auto-scroll banner area; full error
+ // reporting comes when we add toast notifications later.
+ console.error('clearLogs failed', err);
+ } finally {
+ setClearing(false);
+ }
+ }
+
return (
- <div className="page">
+ <div className="page page--full">
<header className="page__header">
- <h1 className="page__title">Logs</h1>
- <p className="page__sub">
- <span className="muted">Coming next milestone — tail of agent.log with level filter and clear.</span>
- </p>
+ <div>
+ <h1 className="page__title">Logs</h1>
+ <p className="page__sub muted">
+ Live tail of agent.log — last {lines.length} lines.
+ </p>
+ </div>
+ <div className="filter-group">
+ {LEVELS.map((l) => (
+ <button
+ key={l}
+ type="button"
+ className={'chip' + (filter === l ? ' chip--active' : '')}
+ onClick={() => setFilter(l)}
+ >
+ {l}
+ </button>
+ ))}
+ </div>
</header>
- <div className="card empty-state">
- The raw JSON-line agent log will be tailed here, with INFO/WARN/ERROR filtering, search, and a Clear button.
+
+ <div className="toolbar">
+ <div className="search">
+ <Search size={14} />
+ <input
+ type="text"
+ placeholder="Search…"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ spellCheck={false}
+ />
+ </div>
+ <div className="toolbar__spacer" />
+ <button
+ type="button"
+ className="btn btn--danger"
+ onClick={handleClear}
+ disabled={clearing}
+ title="Rotates agent.log to a backup file"
+ >
+ <Trash2 size={14} />
+ {clearing ? 'Clearing…' : 'Clear'}
+ </button>
+ </div>
+
+ {error && (
+ <div className="banner banner--warn">
+ Can't reach the agent IPC server. ({error})
+ </div>
+ )}
+
+ <div className="log-viewer" ref={scrollerRef} onScroll={onScroll}>
+ {visible.length === 0 ? (
+ <div className="empty-state empty-state--log">
+ {lines.length === 0
+ ? 'Waiting for log lines…'
+ : `No matches for "${query}" / ${filter}`}
+ </div>
+ ) : (
+ visible.map((entry, i) => <LogRow key={i} entry={entry} />)
+ )}
</div>
+
+ {!autoScroll && (
+ <div className="follow-pill" onClick={() => setAutoScroll(true)}>
+ Resume tail ↓
+ </div>
+ )}
</div>
);
}
diff --git a/agent/ui/src/pages/Pair.jsx b/agent/ui/src/pages/Pair.jsx
new file mode 100644
index 00000000..f21f2b0e
--- /dev/null
+++ b/agent/ui/src/pages/Pair.jsx
@@ -0,0 +1,233 @@
+import { useEffect, useRef, useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import { Copy, Check, Server, ArrowRight, Loader2, CircleCheck, AlertTriangle } from 'lucide-react';
+import { local } from '../ipc/client.js';
+
+// Three-stage React port of the legacy walk wizard. The actual pairing
+// protocol still runs in Go via internal/pairdriver — this component just
+// drives the form, kicks off /local/pair/start, polls /local/pair/state,
+// and renders whatever stage the backend reports.
+
+function CopyValue({ value, large }) {
+ const [copied, setCopied] = useState(false);
+ return (
+ <div className={'copy-value ' + (large ? 'copy-value--large' : '')}>
+ <span className="copy-value__text">{value}</span>
+ <button
+ type="button"
+ className="copy-btn"
+ onClick={() => {
+ navigator.clipboard.writeText(value);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1200);
+ }}
+ title={copied ? 'Copied!' : 'Copy'}
+ >
+ {copied ? <Check size={16} /> : <Copy size={16} />}
+ </button>
+ </div>
+ );
+}
+
+function FormStage({ onSubmit, busy, defaultName }) {
+ const [panelUrl, setPanelUrl] = useState('');
+ const [name, setName] = useState(defaultName || '');
+ const [error, setError] = useState('');
+
+ function submit(e) {
+ e.preventDefault();
+ if (!panelUrl.trim()) {
+ setError('Panel URL is required');
+ return;
+ }
+ setError('');
+ onSubmit(panelUrl.trim(), name.trim());
+ }
+
+ return (
+ <form onSubmit={submit} className="wizard">
+ <div className="wizard__head">
+ <div className="wizard__brand">
+ <Server size={28} />
+ </div>
+ <h1 className="wizard__title">Pair this server</h1>
+ <p className="wizard__sub">Connect this machine to your ServerKit panel.</p>
+ </div>
+
+ <div className="wizard__body">
+ <label className="field">
+ <span className="field__label">Panel URL</span>
+ <input
+ type="text"
+ className="field__input"
+ placeholder="https://panel.example.com"
+ value={panelUrl}
+ onChange={(e) => setPanelUrl(e.target.value)}
+ autoFocus
+ spellCheck={false}
+ />
+ <span className="field__hint">The full URL of your ServerKit control panel.</span>
+ </label>
+
+ <label className="field">
+ <span className="field__label">Server name <span className="muted">(optional)</span></span>
+ <input
+ type="text"
+ className="field__input"
+ placeholder="Defaults to hostname"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ spellCheck={false}
+ />
+ <span className="field__hint">How this machine appears in your panel.</span>
+ </label>
+
+ {error && <div className="banner banner--warn">{error}</div>}
+
+ <button type="submit" className="btn btn--primary btn--large" disabled={busy}>
+ {busy ? (
+ <><Loader2 size={16} className="spin" /> Connecting…</>
+ ) : (
+ <>Connect <ArrowRight size={16} /></>
+ )}
+ </button>
+ </div>
+ </form>
+ );
+}
+
+function PairCodeStage({ state, onCancel }) {
+ return (
+ <div className="wizard">
+ <div className="wizard__head">
+ <h1 className="wizard__title">Enter both values in your panel</h1>
+ <p className="wizard__sub">
+ On your panel, open <strong>Add Server → Pair existing agent</strong>, then type these in.
+ </p>
+ </div>
+
+ <div className="wizard__body">
+ <div className="pair-display">
+ <div className="pair-display__label">Pair code</div>
+ <CopyValue value={state.code_formatted || state.code} large />
+ </div>
+ <div className="pair-display">
+ <div className="pair-display__label">Passphrase</div>
+ <CopyValue value={state.passphrase} />
+ </div>
+
+ <div className="wizard__status">
+ <Loader2 size={14} className="spin" />
+ <span>Waiting for the panel to claim this server…</span>
+ </div>
+
+ <button type="button" className="btn" onClick={onCancel}>
+ Cancel
+ </button>
+ </div>
+ </div>
+ );
+}
+
+function DoneStage({ state, onContinue }) {
+ return (
+ <div className="wizard">
+ <div className="wizard__head">
+ <div className="wizard__brand wizard__brand--ok">
+ <CircleCheck size={28} />
+ </div>
+ <h1 className="wizard__title">Successfully paired</h1>
+ <p className="wizard__sub">
+ This machine is now connected to ServerKit as <strong>{state.server_name || 'this server'}</strong>.
+ </p>
+ </div>
+
+ <div className="wizard__body">
+ <p className="muted" style={{ textAlign: 'center', margin: 0 }}>
+ The agent service has been restarted with the new configuration.
+ </p>
+ <button type="button" className="btn btn--primary btn--large" onClick={onContinue}>
+ Open console <ArrowRight size={16} />
+ </button>
+ </div>
+ </div>
+ );
+}
+
+function ErrorStage({ state, onRetry }) {
+ return (
+ <div className="wizard">
+ <div className="wizard__head">
+ <div className="wizard__brand wizard__brand--err">
+ <AlertTriangle size={28} />
+ </div>
+ <h1 className="wizard__title">Pairing failed</h1>
+ </div>
+
+ <div className="wizard__body">
+ <div className="banner banner--warn">{state.error || 'Unknown error'}</div>
+ <button type="button" className="btn btn--primary btn--large" onClick={onRetry}>
+ Try again
+ </button>
+ </div>
+ </div>
+ );
+}
+
+export default function Pair() {
+ const navigate = useNavigate();
+ const [state, setState] = useState({ state: 'idle' });
+ const [busy, setBusy] = useState(false);
+ const pollRef = useRef(null);
+
+ // Poll /local/pair/state once a second while the wizard is open. The
+ // initial fetch on mount also covers the case where the user closed and
+ // reopened the console mid-pairing — we land back on the right stage.
+ useEffect(() => {
+ let cancelled = false;
+ async function tick() {
+ try {
+ const s = await local.pairState();
+ if (!cancelled) setState(s);
+ } catch {
+ // Asset server is in the same process — if it's gone, the
+ // window is closing anyway.
+ }
+ }
+ tick();
+ pollRef.current = setInterval(tick, 1000);
+ return () => {
+ cancelled = true;
+ clearInterval(pollRef.current);
+ };
+ }, []);
+
+ async function handleSubmit(panelUrl, name) {
+ setBusy(true);
+ try {
+ await local.pairStart(panelUrl, name);
+ const s = await local.pairState();
+ setState(s);
+ } catch (err) {
+ setState({ state: 'error', error: err.message });
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function handleCancel() {
+ await local.pairCancel();
+ setState({ state: 'idle' });
+ }
+
+ if (state.state === 'claimed') {
+ return <DoneStage state={state} onContinue={() => navigate('/overview')} />;
+ }
+ if (state.state === 'error') {
+ return <ErrorStage state={state} onRetry={() => setState({ state: 'idle' })} />;
+ }
+ if (state.state === 'enrolling' || state.state === 'waiting') {
+ return <PairCodeStage state={state} onCancel={handleCancel} />;
+ }
+ return <FormStage onSubmit={handleSubmit} busy={busy} />;
+}
diff --git a/agent/ui/src/styles/main.scss b/agent/ui/src/styles/main.scss
index e005e1d7..9195ef57 100644
--- a/agent/ui/src/styles/main.scss
+++ b/agent/ui/src/styles/main.scss
@@ -126,6 +126,12 @@ a {
display: flex;
flex-direction: column;
gap: $space-lg;
+
+ &--full {
+ max-width: none;
+ height: 100vh;
+ padding: $space-lg $space-xl;
+ }
}
.page__header {
@@ -437,3 +443,426 @@ a {
}
}
}
+
+// ─── Buttons ─────────────────────────────────────────────────────────────
+
+.btn {
+ background: $bg-elevated;
+ color: $text-primary;
+ border: 1px solid $border-default;
+ border-radius: $radius-sm;
+ padding: 7px 14px;
+ font-size: 13px;
+ font-weight: 500;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ cursor: pointer;
+ transition: all 120ms;
+
+ &:hover:not(:disabled) {
+ border-color: $border-active;
+ background: $bg-hover;
+ }
+
+ &:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+
+ &--primary {
+ background: $accent;
+ color: white;
+ border-color: $accent;
+
+ &:hover:not(:disabled) {
+ background: $accent-hover;
+ border-color: $accent-hover;
+ }
+ }
+
+ &--danger {
+ color: $danger;
+
+ &:hover:not(:disabled) {
+ border-color: rgba($danger, 0.5);
+ background: rgba($danger, 0.08);
+ }
+ }
+}
+
+// ─── Toolbar (Logs page top strip) ───────────────────────────────────────
+
+.toolbar {
+ display: flex;
+ align-items: center;
+ gap: $space-sm;
+}
+
+.toolbar__spacer {
+ flex: 1;
+}
+
+.search {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ background: $bg-card;
+ border: 1px solid $border-default;
+ border-radius: $radius-sm;
+ padding: 6px 10px;
+ color: $text-tertiary;
+ flex: 0 0 280px;
+
+ input {
+ background: transparent;
+ border: none;
+ outline: none;
+ color: $text-primary;
+ flex: 1;
+ font-size: 13px;
+ font-family: inherit;
+ }
+}
+
+// ─── Log viewer ──────────────────────────────────────────────────────────
+
+.log-viewer {
+ flex: 1;
+ background: $bg-card;
+ border: 1px solid $border-default;
+ border-radius: $radius-md;
+ overflow-y: auto;
+ font-family: 'JetBrains Mono', 'Consolas', ui-monospace, monospace;
+ font-size: 12px;
+ line-height: 1.5;
+ padding: 10px 12px;
+}
+
+.empty-state--log {
+ padding: 32px 0;
+ text-align: center;
+ color: $text-tertiary;
+ font-family: 'Segoe UI', system-ui, sans-serif;
+}
+
+.logrow {
+ display: grid;
+ grid-template-columns: 92px 60px auto auto 1fr;
+ gap: 8px;
+ padding: 4px 0;
+ border-bottom: 1px solid rgba($border-default, 0.4);
+ align-items: baseline;
+
+ &:last-child {
+ border-bottom: none;
+ }
+
+ &__time {
+ color: $text-tertiary;
+ font-variant-numeric: tabular-nums;
+ }
+
+ &__level {
+ text-transform: uppercase;
+ font-size: 10px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ padding: 1px 6px;
+ border-radius: 4px;
+ text-align: center;
+
+ &--info {
+ background: rgba($accent, 0.12);
+ color: $accent-hover;
+ }
+ &--warn {
+ background: rgba($warning, 0.12);
+ color: $warning;
+ }
+ &--error {
+ background: rgba($danger, 0.12);
+ color: $danger;
+ }
+ }
+
+ &__component {
+ color: $text-tertiary;
+ font-size: 11px;
+ white-space: nowrap;
+ }
+
+ &__msg {
+ color: $text-primary;
+ word-break: break-word;
+ }
+
+ &__extras {
+ grid-column: 5;
+ color: $text-tertiary;
+ font-size: 11px;
+
+ > span {
+ margin-right: 12px;
+
+ em {
+ font-style: normal;
+ color: $text-tertiary;
+ }
+ code {
+ color: $text-secondary;
+ }
+ }
+ }
+
+ &--warn .logrow__msg {
+ color: lighten($warning, 12%);
+ }
+ &--error .logrow__msg {
+ color: lighten($danger, 8%);
+ }
+}
+
+.follow-pill {
+ position: fixed;
+ bottom: 24px;
+ right: 32px;
+ background: $accent;
+ color: white;
+ padding: 8px 14px;
+ border-radius: 999px;
+ font-size: 12px;
+ font-weight: 500;
+ cursor: pointer;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
+
+ &:hover {
+ background: $accent-hover;
+ }
+}
+
+// ─── Actions tab ─────────────────────────────────────────────────────────
+
+.action-group__heading {
+ padding: 14px 18px 8px;
+ font-size: 11px;
+ font-weight: 600;
+ color: $text-tertiary;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+}
+
+// ─── Wizard ──────────────────────────────────────────────────────────────
+
+.wizard {
+ width: 100%;
+ height: 100vh;
+ display: grid;
+ place-items: center;
+ padding: $space-xl;
+ background:
+ radial-gradient(1200px 600px at 50% -10%, rgba($accent, 0.08), transparent),
+ $bg-body;
+}
+
+.wizard > .wizard__head + .wizard__body,
+.wizard > .wizard__head,
+.wizard > .wizard__body {
+ width: 100%;
+}
+
+.wizard__head {
+ text-align: center;
+ margin-bottom: $space-lg;
+}
+
+.wizard__brand {
+ width: 56px;
+ height: 56px;
+ border-radius: $radius-md;
+ background: linear-gradient(135deg, $accent, #8b5cf6);
+ color: white;
+ display: grid;
+ place-items: center;
+ margin: 0 auto 16px;
+
+ &--ok {
+ background: linear-gradient(135deg, $success, #34d399);
+ }
+
+ &--err {
+ background: linear-gradient(135deg, $danger, #f87171);
+ }
+}
+
+.wizard__title {
+ font-size: 24px;
+ font-weight: 600;
+ margin: 0 0 8px;
+ letter-spacing: -0.01em;
+}
+
+.wizard__sub {
+ color: $text-secondary;
+ margin: 0;
+ line-height: 1.55;
+}
+
+.wizard__body {
+ background: $bg-card;
+ border: 1px solid $border-default;
+ border-radius: $radius-lg;
+ padding: $space-xl;
+ display: flex;
+ flex-direction: column;
+ gap: $space-md;
+ max-width: 460px;
+ margin: 0 auto;
+}
+
+.wizard__status {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ color: $text-tertiary;
+ font-size: 13px;
+ padding: $space-sm 0;
+}
+
+// Form fields used by the wizard
+.field {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.field__label {
+ font-size: 12px;
+ font-weight: 600;
+ color: $text-secondary;
+}
+
+.field__input {
+ background: $bg-elevated;
+ border: 1px solid $border-default;
+ border-radius: $radius-sm;
+ padding: 10px 12px;
+ color: $text-primary;
+ font-size: 14px;
+ font-family: inherit;
+ outline: none;
+ transition: border-color 120ms;
+
+ &:focus {
+ border-color: $accent;
+ }
+}
+
+.field__hint {
+ font-size: 12px;
+ color: $text-tertiary;
+}
+
+// Inline copy-able value (pair code, passphrase)
+.copy-value {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ background: $bg-elevated;
+ border: 1px solid $border-default;
+ border-radius: $radius-md;
+ padding: 14px 16px;
+ font-family: 'JetBrains Mono', 'Consolas', ui-monospace, monospace;
+
+ &__text {
+ font-size: 18px;
+ font-weight: 600;
+ letter-spacing: 0.12em;
+ color: $text-primary;
+ }
+
+ &--large {
+ .copy-value__text {
+ font-size: 28px;
+ color: $accent-hover;
+ letter-spacing: 0.2em;
+ }
+ }
+}
+
+.pair-display {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+
+ &__label {
+ font-size: 11px;
+ font-weight: 600;
+ color: $text-tertiary;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ }
+}
+
+.btn--large {
+ padding: 12px 20px;
+ font-size: 14px;
+ justify-content: center;
+}
+
+.spin {
+ animation: wizard-spin 0.9s linear infinite;
+}
+
+@keyframes wizard-spin {
+ to { transform: rotate(360deg); }
+}
+
+.action {
+ display: grid;
+ grid-template-columns: 36px 1fr auto;
+ gap: $space-md;
+ padding: 14px 18px;
+ border-top: 1px solid $border-subtle;
+ align-items: center;
+
+ &__icon {
+ width: 36px;
+ height: 36px;
+ border-radius: $radius-sm;
+ background: $bg-elevated;
+ color: $text-secondary;
+ display: grid;
+ place-items: center;
+ }
+
+ &__title {
+ font-size: 13px;
+ font-weight: 500;
+ color: $text-primary;
+ }
+
+ &__desc {
+ font-size: 12px;
+ color: $text-tertiary;
+ margin-top: 2px;
+ }
+
+ &__buttons {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ }
+
+ &__feedback {
+ font-size: 12px;
+
+ &--ok {
+ color: $success;
+ }
+ &--err {
+ color: $danger;
+ }
+ }
+}