ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Add native Windows desktop wizard & ARM64 builds
Juan Denis0d7672693606
diff --git a/.github/workflows/agent-release.yml b/.github/workflows/agent-release.ymlindex aa397e03..55efbfab 100644--- a/.github/workflows/agent-release.yml+++ b/.github/workflows/agent-release.yml@@ -31,6 +31,9 @@ jobs:- goos: windowsgoarch: amd64suffix: '.exe'+ - goos: windows+ goarch: arm64+ suffix: '.exe'steps:- name: Checkout code@@ -60,7 +63,15 @@ jobs:CGO_ENABLED: 0run: |cd agent- go build -ldflags="-s -w -X main.Version=${{ steps.version.outputs.version }} -X github.com/serverkit/agent/internal/agent.Version=${{ steps.version.outputs.version }}" \+ # Windows builds use -H windowsgui so Start-menu launches don't+ # flash a console. attachParentConsole() in cmd/agent restores+ # stdio when invoked from PowerShell/cmd for CLI subcommands.+ if [ "${{ matrix.goos }}" = "windows" ]; then+ EXTRA_LDFLAGS="-H=windowsgui"+ else+ EXTRA_LDFLAGS=""+ fi+ go build -ldflags="-s -w $EXTRA_LDFLAGS -X main.Version=${{ steps.version.outputs.version }} -X github.com/serverkit/agent/internal/agent.Version=${{ steps.version.outputs.version }}" \-o ../dist/serverkit-agent-${{ matrix.goos }}-${{ matrix.goarch }}${{ matrix.suffix }} \./cmd/agent@@ -190,12 +201,20 @@ jobs:path: packages/*.rpmretention-days: 5- # Build Windows MSI+ # Build Windows MSI installers (one per architecture)build-msi:- name: Build MSI Installer+ name: Build MSI Installer (${{ matrix.arch }})runs-on: windows-latestneeds: build+ strategy:+ matrix:+ include:+ - goarch: amd64+ arch: x64+ - goarch: arm64+ arch: arm64+steps:- name: Checkout codeuses: actions/checkout@v4@@ -218,25 +237,25 @@ jobs:- name: Download binaryuses: actions/download-artifact@v4with:- name: serverkit-agent-windows-amd64+ name: serverkit-agent-windows-${{ matrix.goarch }}path: dist/- name: Extract binaryshell: bashrun: |cd dist- unzip serverkit-agent-${{ steps.version.outputs.version }}-windows-amd64.zip+ unzip serverkit-agent-${{ steps.version.outputs.version }}-windows-${{ matrix.goarch }}.zip- name: Build MSIshell: pwshrun: |cd agent/packaging/msi- .\build.ps1 -Version "${{ steps.version.outputs.version }}" -BinaryPath "..\..\..\dist\serverkit-agent-windows-amd64.exe" -OutputDir "..\..\..\packages"+ .\build.ps1 -Version "${{ steps.version.outputs.version }}" -Arch "${{ matrix.arch }}" -BinaryPath "..\..\..\dist\serverkit-agent-windows-${{ matrix.goarch }}.exe" -OutputDir "..\..\..\packages"- name: Upload MSIuses: actions/upload-artifact@v4with:- name: serverkit-agent-msi+ name: serverkit-agent-msi-${{ matrix.arch }}path: packages/*.msiretention-days: 5@@ -352,6 +371,7 @@ jobs:| Linux | x64 (amd64) | `serverkit-agent-${{ steps.version.outputs.version }}-linux-amd64.tar.gz` || Linux | ARM64 | `serverkit-agent-${{ steps.version.outputs.version }}-linux-arm64.tar.gz` || Windows | x64 (amd64) | `serverkit-agent-${{ steps.version.outputs.version }}-windows-amd64.zip` |+ | Windows | ARM64 | `serverkit-agent-${{ steps.version.outputs.version }}-windows-arm64.zip` |#### Linux Packages| Format | Architecture | Download |@@ -365,8 +385,9 @@ jobs:| Format | Architecture | Download ||--------|--------------|----------|| MSI | x64 | `serverkit-agent-${{ steps.version.outputs.version }}-x64.msi` |+ | MSI | ARM64 | `serverkit-agent-${{ steps.version.outputs.version }}-arm64.msi` |- > **New:** Run `serverkit-agent tray` to launch the **System Tray Application** which provides a visual indicator that the agent is running, along with quick access to status, logs, and service controls. The MSI installer auto-starts the tray on Windows login.+ > **New:** The Windows MSI now opens a native pairing wizard right after install — no browser, no WebView2 runtime needed. The Start-menu shortcut and login autostart both run the unified desktop app: pairing wizard if not yet configured, otherwise the system tray.#### Docker```bash@@ -458,6 +479,7 @@ jobs:echo "| RPM | x86_64 | ✅ Built |" >> $GITHUB_STEP_SUMMARYecho "| RPM | aarch64 | ✅ Built |" >> $GITHUB_STEP_SUMMARYecho "| MSI | x64 | ✅ Built |" >> $GITHUB_STEP_SUMMARY+ echo "| MSI | ARM64 | ✅ Built |" >> $GITHUB_STEP_SUMMARYecho "| Docker | multi-arch | ✅ Built |" >> $GITHUB_STEP_SUMMARYecho "" >> $GITHUB_STEP_SUMMARYecho "### Release" >> $GITHUB_STEP_SUMMARYdiff --git a/.gitignore b/.gitignoreindex 6c620389..612f17d3 100644--- a/.gitignore+++ b/.gitignore@@ -40,6 +40,7 @@/agent/*.test/agent/*.out/agent/bin/+/dist/# Environment / Secrets.env@@ -96,4 +97,13 @@ nulSECURITY_AUDIT.mdAPP_IMPROVEMENTS.md*.png-/agent/packaging++# MSI / build artifacts that should not be committed.+/agent/packaging/msi/output/+/agent/packaging/msi/*.wixpdb++# Brand assets that the agent embeds at build time are generated by+# agent/packaging/icons/generate_icons.py from the SVG, but must be checked+# in so CI builds don't have to install cairo/Pillow.+!agent/internal/setupui/serverkit.ico+!agent/internal/setupui/serverkit_header.pngdiff --git a/VERSION b/VERSIONindex f689e8c1..63ebd3fe 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.4.18+1.5.4\ No newline at end of filediff --git a/agent/cmd/agent/app.manifest b/agent/cmd/agent/app.manifestnew file mode 100644index 00000000..428de2cb--- /dev/null+++ b/agent/cmd/agent/app.manifest@@ -0,0 +1,46 @@+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">+ <assemblyIdentity+ type="win32"+ name="ServerKit.Agent"+ version="1.0.0.0"+ processorArchitecture="*"/>+ <description>ServerKit Agent</description>++ <dependency>+ <dependentAssembly>+ <assemblyIdentity+ type="win32"+ name="Microsoft.Windows.Common-Controls"+ version="6.0.0.0"+ processorArchitecture="*"+ publicKeyToken="6595b64144ccf1df"+ language="*"/>+ </dependentAssembly>+ </dependency>++ <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">+ <security>+ <requestedPrivileges>+ <requestedExecutionLevel level="asInvoker" uiAccess="false"/>+ </requestedPrivileges>+ </security>+ </trustInfo>++ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">+ <application>+ <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>+ <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>+ <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>+ <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>+ <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>+ </application>+ </compatibility>++ <application xmlns="urn:schemas-microsoft-com:asm.v3">+ <windowsSettings>+ <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/PM</dpiAware>+ <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2,PerMonitor</dpiAwareness>+ </windowsSettings>+ </application>+</assembly>diff --git a/agent/cmd/agent/console_other.go b/agent/cmd/agent/console_other.gonew file mode 100644index 00000000..96a507e2--- /dev/null+++ b/agent/cmd/agent/console_other.go@@ -0,0 +1,8 @@+//go:build !windows++package main++// attachParentConsole is a no-op outside Windows. The Windows build needs it+// to keep CLI output working when the binary is built with the windowsgui+// subsystem; on POSIX that subsystem distinction does not exist.+func attachParentConsole() {}diff --git a/agent/cmd/agent/console_windows.go b/agent/cmd/agent/console_windows.gonew file mode 100644index 00000000..4e09c3c7--- /dev/null+++ b/agent/cmd/agent/console_windows.go@@ -0,0 +1,34 @@+//go:build windows++package main++import (+ "os"+ "syscall"+)++// attachParentConsole reattaches stdin/stdout/stderr to the parent console+// (e.g. PowerShell or cmd.exe) when the binary was built with the+// "windowsgui" subsystem. With that subsystem set, double-clicking a+// shortcut no longer flashes a console — but CLI invocations like+// `serverkit-agent register` would also lose their output. This call+// restores the terminal experience when one is available, and is a+// silent no-op when launched from Explorer/Start menu.+func attachParentConsole() {+ const attachParentProcess = ^uint32(0) // -1, ATTACH_PARENT_PROCESS+ kernel32 := syscall.NewLazyDLL("kernel32.dll")+ proc := kernel32.NewProc("AttachConsole")+ r, _, _ := proc.Call(uintptr(attachParentProcess))+ if r == 0 {+ return // no parent console; we're a GUI process+ }+ if h, err := syscall.Open("CONOUT$", os.O_WRONLY, 0); err == nil {+ os.Stdout = os.NewFile(uintptr(h), "stdout")+ }+ if h, err := syscall.Open("CONOUT$", os.O_WRONLY, 0); err == nil {+ os.Stderr = os.NewFile(uintptr(h), "stderr")+ }+ if h, err := syscall.Open("CONIN$", os.O_RDONLY, 0); err == nil {+ os.Stdin = os.NewFile(uintptr(h), "stdin")+ }+}diff --git a/agent/cmd/agent/debuglog.go b/agent/cmd/agent/debuglog.godeleted file mode 100644index 3b75f566..00000000--- a/agent/cmd/agent/debuglog.go+++ /dev/null@@ -1,51 +0,0 @@-package main--import (- "fmt"- "os"- "path/filepath"- "sync"- "time"-)--type debugLog struct {- mu sync.Mutex- f *os.File- path string-}--func (d *debugLog) Path() string { return d.path }--func (d *debugLog) Logf(format string, args ...interface{}) {- if d == nil {- return- }- d.mu.Lock()- defer d.mu.Unlock()- line := fmt.Sprintf("[%s] %s\n", time.Now().Format("15:04:05.000"), fmt.Sprintf(format, args...))- if d.f != nil {- _, _ = d.f.WriteString(line)- _ = d.f.Sync()- }-}--func (d *debugLog) Close() {- if d == nil || d.f == nil {- return- }- _ = d.f.Close()-}--func openSetupDebugLog() *debugLog {- dir := os.TempDir()- if d, err := os.UserCacheDir(); err == nil {- dir = filepath.Join(d, "ServerKit")- _ = os.MkdirAll(dir, 0o755)- }- path := filepath.Join(dir, "serverkit-agent-setup.log")- f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)- if err != nil {- return &debugLog{path: path}- }- return &debugLog{f: f, path: path}-}diff --git a/agent/cmd/agent/desktop_debug.go b/agent/cmd/agent/desktop_debug.gonew file mode 100644index 00000000..946c6645--- /dev/null+++ b/agent/cmd/agent/desktop_debug.go@@ -0,0 +1,63 @@+package main++import (+ "fmt"+ "os"+ "path/filepath"+ "sync"+ "time"+)++// desktopLog is a small file-backed log used by runDesktop / runSetup so a+// failed launch is never invisible. We deliberately live alongside the agent's+// other state in %LOCALAPPDATA%\ServerKit\Agent rather than next to the exe+// (Program Files needs admin to write into).+type desktopLog struct {+ mu sync.Mutex+ f *os.File+ p string+}++func (d *desktopLog) Path() string { return d.p }++func (d *desktopLog) Logf(format string, args ...interface{}) {+ if d == nil || d.f == nil {+ return+ }+ d.mu.Lock()+ defer d.mu.Unlock()+ line := fmt.Sprintf("[%s] %s\n", time.Now().Format("2006-01-02 15:04:05.000"), fmt.Sprintf(format, args...))+ _, _ = d.f.WriteString(line)+ _ = d.f.Sync()+}++func (d *desktopLog) Close() {+ if d == nil || d.f == nil {+ return+ }+ _ = d.f.Close()+}++func openDesktopLog() *desktopLog {+ candidates := []string{}+ if v := os.Getenv("LOCALAPPDATA"); v != "" {+ candidates = append(candidates, filepath.Join(v, "ServerKit", "Agent"))+ }+ if home, err := os.UserHomeDir(); err == nil {+ candidates = append(candidates, filepath.Join(home, "AppData", "Local", "ServerKit", "Agent"))+ }+ candidates = append(candidates, os.TempDir())++ for _, dir := range candidates {+ if err := os.MkdirAll(dir, 0o755); err != nil {+ continue+ }+ p := filepath.Join(dir, "desktop.log")+ f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)+ if err != nil {+ continue+ }+ return &desktopLog{f: f, p: p}+ }+ return &desktopLog{}+}diff --git a/agent/cmd/agent/instance_other.go b/agent/cmd/agent/instance_other.gonew file mode 100644index 00000000..ecb8a476--- /dev/null+++ b/agent/cmd/agent/instance_other.go@@ -0,0 +1,9 @@+//go:build !windows++package main++// acquireSingleInstance is a Windows-specific concern; on POSIX the user+// runs at most one tray per session anyway and we don't enforce it.+func acquireSingleInstance() (alreadyRunning bool, release func()) {+ return false, func() {}+}diff --git a/agent/cmd/agent/instance_windows.go b/agent/cmd/agent/instance_windows.gonew file mode 100644index 00000000..4d5d2644--- /dev/null+++ b/agent/cmd/agent/instance_windows.go@@ -0,0 +1,47 @@+//go:build windows++package main++import (+ "syscall"+ "unsafe"+)++// 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+// for the lifetime of the process.+//+// 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+ )++ kernel32 := syscall.NewLazyDLL("kernel32.dll")+ createMutexW := kernel32.NewProc("CreateMutexW")+ closeHandle := kernel32.NewProc("CloseHandle")++ name, err := syscall.UTF16PtrFromString(`Local\ServerKitAgentDesktop`)+ if err != nil {+ return false, func() {}+ }++ handle, _, lastErr := createMutexW.Call(+ 0, // lpMutexAttributes = NULL+ 0, // bInitialOwner = FALSE+ uintptr(unsafe.Pointer(name)),+ )++ if handle == 0 {+ return false, func() {}+ }++ if errno, ok := lastErr.(syscall.Errno); ok && uintptr(errno) == errAlreadyExists {+ closeHandle.Call(handle)+ return true, func() {}+ }++ return false, func() { closeHandle.Call(handle) }+}diff --git a/agent/cmd/agent/main.go b/agent/cmd/agent/main.goindex b7ed450e..70265000 100644--- a/agent/cmd/agent/main.go+++ b/agent/cmd/agent/main.go@@ -4,9 +4,9 @@ import ("context""fmt""os"+ "os/exec""os/signal""path/filepath"- "runtime""syscall""github.com/serverkit/agent/internal/agent"@@ -27,19 +27,31 @@ var (var (cfgFile stringdebugMode bool+ repair bool)func main() {+ attachParentConsole()+rootCmd := &cobra.Command{Use: "serverkit-agent",Short: "ServerKit Agent - Remote server management agent",Long: `ServerKit Agent connects your server to a ServerKit control plane,-enabling remote Docker management, monitoring, and more.`,+enabling remote Docker management, monitoring, and more.++When run without a subcommand on Windows, opens the desktop application+(pairing wizard if not configured, otherwise system tray).`,+ RunE: func(cmd *cobra.Command, args []string) error {+ return runDesktop()+ },+ SilenceUsage: true,+ SilenceErrors: true,}// Global flagsrootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file path")rootCmd.PersistentFlags().BoolVarP(&debugMode, "debug", "d", false, "enable debug logging")+ rootCmd.PersistentFlags().BoolVar(&repair, "repair", false, "force the pairing wizard even if a config already exists")// Add commandsrootCmd.AddCommand(startCmd())@@ -377,40 +389,34 @@ func showStatus() error {func setupCmd() *cobra.Command {return &cobra.Command{Use: "setup",- Short: "Open a browser-based pairing wizard (recommended for desktops)",- Long: `Launches a small local web server on 127.0.0.1 and opens your default-browser to a pairing wizard. You enter the panel URL and a passphrase, then-type the displayed code into the panel UI to claim this server.+ 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.-This is the easiest way to pair on Windows/macOS desktops. For headless-servers, use 'serverkit-agent pair' instead.`,+For headless servers, use 'serverkit-agent pair' instead.`,RunE: func(cmd *cobra.Command, args []string) error {return runSetup()},}}+// 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.func runSetup() error {- // WebView2 / OS UI must run on the main OS thread on Windows.- runtime.LockOSThread()-- // Diagnostic file log — invaluable when launched from a Start Menu- // shortcut (no console) and the wizard "does nothing".- dbg := openSetupDebugLog()+ dbg := openDesktopLog()defer dbg.Close()dbg.Logf("--- runSetup start, version=%s pid=%d ---", Version, os.Getpid())- // Catch panics so they end up in the log + a MessageBox instead of vanishing.defer func() {if r := recover(); r != nil {- msg := fmt.Sprintf("panic: %v", r)- dbg.Logf(msg)- showFatalError(fmt.Errorf("%s\n\nLog: %s", msg, dbg.Path()))+ 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)}}()log := logger.New(config.LoggingConfig{Level: "info"})- dbg.Logf("logger ready")configPath := cfgFileif configPath == "" {@@ -418,9 +424,6 @@ func runSetup() error {}dbg.Logf("configPath=%s", configPath)- srv := setupui.New(log, configPath)- dbg.Logf("setupui.New OK")-ctx, cancel := context.WithCancel(context.Background())defer cancel()@@ -428,22 +431,103 @@ func runSetup() error {signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)go func() {<-sigCh- fmt.Println("\nCancelling…")cancel()}()- dbg.Logf("calling srv.Run …")- err := srv.Run(ctx)- dbg.Logf("srv.Run returned: %v", err)+ dbg.Logf("calling setupui.Run …")+ err := setupui.Run(ctx, log, configPath)+ dbg.Logf("setupui.Run returned: %v", err)if err != nil {- // We're built with -H windowsgui so there's no console. Surface- // failures via a MessageBox so the user isn't left staring at a- // shortcut that "does nothing".- showFatalError(fmt.Errorf("%w\n\nLog: %s", err, dbg.Path()))+ showMessageBox("ServerKit Agent",+ fmt.Sprintf("Couldn't open the pairing wizard.\n\n%v\n\nLog: %s", err, dbg.Path()),+ mbIconError)}return err}+// 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.+// runDesktop is what `serverkit-agent` (no args) does on a desktop install.+// Architecture: the tray always runs in this process and is the primary+// entry point — the user-visible app. If the agent is unconfigured (or the+// caller passed --repair) we spawn the pairing wizard as a *separate*+// detached process so the tray is visible immediately and remains the+// recovery surface even if the wizard fails to render.+func runDesktop() error {+ dbg := openDesktopLog()+ defer dbg.Close()+ dbg.Logf("--- runDesktop start, version=%s pid=%d ---", Version, os.Getpid())++ // Single-instance: if a tray is already running for this user, just+ // kick the wizard if needed and exit. Avoids the two-trays-in-one-bar+ // problem when the autostart and a Start-menu click race.+ if alreadyRunning, release := acquireSingleInstance(); alreadyRunning {+ dbg.Logf("another instance is already running; not starting a second tray")+ if repair {+ spawnSetupWizard(dbg)+ }+ return nil+ } else {+ defer release()+ }++ cfg, cfgErr := config.Load(cfgFile)+ dbg.Logf("config.Load err=%v", cfgErr)+ if cfg != nil {+ dbg.Logf("agent.id=%q server.url=%q", cfg.Agent.ID, cfg.Server.URL)+ }++ needsSetup := cfg == nil || cfg.Agent.ID == "" || repair+ dbg.Logf("needsSetup=%v (repair=%v)", needsSetup, repair)++ if needsSetup {+ spawnSetupWizard(dbg)+ }++ dbg.Logf("→ launching tray (needsSetup=%v)", needsSetup)+ return runTrayWithOpts(cfg, needsSetup)+}++func cfgName(cfg *config.Config) string {+ if cfg == nil {+ return ""+ }+ return cfg.Agent.Name+}++// spawnSetupWizard launches `serverkit-agent setup` as a detached child so+// the wizard runs in its own process and the parent (the tray) is unaffected+// by what happens to the wizard's window. Used both at desktop boot when+// pairing is needed and from the tray's "Open setup wizard…" menu.+func spawnSetupWizard(dbg *desktopLog) {+ exe, err := os.Executable()+ if err != nil {+ if dbg != nil {+ dbg.Logf("spawn: os.Executable err=%v", err)+ }+ return+ }+ cmd := exec.Command(exe, "setup")+ cmd.SysProcAttr = detachedProcessAttrs()+ if err := cmd.Start(); err != nil {+ if dbg != nil {+ dbg.Logf("spawn: cmd.Start err=%v", err)+ }+ return+ }+ if dbg != nil {+ dbg.Logf("spawn: wizard pid=%d started", cmd.Process.Pid)+ }+}++// reopenSetupWizard is the OnOpenSetup callback the tray hands to its menu.+// Same as spawnSetupWizard but without a debug log (the tray runs in the+// long-lived parent process where re-opening logs would be noisy).+func reopenSetupWizard() {+ spawnSetupWizard(nil)+}+func trayCmd() *cobra.Command {return &cobra.Command{Use: "tray",@@ -461,14 +545,18 @@ This is typically auto-started on Windows login when installed via MSI.`,}func runTray() error {- // Load agent config to get server URL and IPC settingscfg, err := config.Load(cfgFile)if err != nil {- // Continue without config - tray can still show status+ cfg = config.Default()+ }+ return runTrayWithOpts(cfg, cfg.Agent.ID == "")+}++func runTrayWithOpts(cfg *config.Config, needsSetup bool) error {+ if cfg == nil {cfg = config.Default()}- // Create and run tray applicationapp := tray.NewApp(tray.AppConfig{Version: Version,IPCAddress: cfg.IPC.Address,@@ -476,9 +564,10 @@ func runTray() error {ServerURL: cfg.Server.URL,DashboardURL: getDashboardURL(cfg.Server.URL),LogFile: cfg.Logging.File,+ NeedsSetup: needsSetup,+ OnOpenSetup: reopenSetupWizard,})- // Handle signals for graceful shutdownsigCh := make(chan os.Signal, 1)signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)@@ -487,7 +576,6 @@ func runTray() error {app.Quit()}()- // Run the tray app (blocking)app.Run()return nil}diff --git a/agent/cmd/agent/msgbox_other.go b/agent/cmd/agent/msgbox_other.goindex 494a04d0..a72c6aa1 100644--- a/agent/cmd/agent/msgbox_other.go+++ b/agent/cmd/agent/msgbox_other.go@@ -2,11 +2,9 @@package main-import (- "fmt"- "os"+const (+ mbIconError = 0+ mbIconInfo = 0)-func showFatalError(err error) {- fmt.Fprintln(os.Stderr, err)-}+func showMessageBox(_ string, _ string, _ uint32) {}diff --git a/agent/cmd/agent/msgbox_windows.go b/agent/cmd/agent/msgbox_windows.goindex 7a551547..9167b5b8 100644--- a/agent/cmd/agent/msgbox_windows.go+++ b/agent/cmd/agent/msgbox_windows.go@@ -7,11 +7,18 @@ import ("unsafe")-func showFatalError(err error) {+const (+ mbIconError = 0x00000010+ mbIconInfo = 0x00000040+)++// showMessageBox is a tiny user32!MessageBoxW wrapper for early-stage failures+// where we either don't have walk loaded yet or we want to display before the+// main window exists. Modal; blocks until the user clicks OK.+func showMessageBox(title, body string, icon uint32) {user32 := syscall.NewLazyDLL("user32.dll")- messageBox := user32.NewProc("MessageBoxW")- title, _ := syscall.UTF16PtrFromString("ServerKit Agent")- body, _ := syscall.UTF16PtrFromString("Setup failed:\n\n" + err.Error())- const MB_ICONERROR = 0x00000010- _, _, _ = messageBox.Call(0, uintptr(unsafe.Pointer(body)), uintptr(unsafe.Pointer(title)), MB_ICONERROR)+ mb := user32.NewProc("MessageBoxW")+ t, _ := syscall.UTF16PtrFromString(title)+ b, _ := syscall.UTF16PtrFromString(body)+ _, _, _ = mb.Call(0, uintptr(unsafe.Pointer(b)), uintptr(unsafe.Pointer(t)), uintptr(icon))}diff --git a/agent/cmd/agent/rsrc_windows_amd64.syso b/agent/cmd/agent/rsrc_windows_amd64.sysonew file mode 100644index 00000000..4fa39879Binary files /dev/null and b/agent/cmd/agent/rsrc_windows_amd64.syso differdiff --git a/agent/cmd/agent/rsrc_windows_arm64.syso b/agent/cmd/agent/rsrc_windows_arm64.sysonew file mode 100644index 00000000..e6663a50Binary files /dev/null and b/agent/cmd/agent/rsrc_windows_arm64.syso differdiff --git a/agent/cmd/agent/spawn_other.go b/agent/cmd/agent/spawn_other.gonew file mode 100644index 00000000..3302450b--- /dev/null+++ b/agent/cmd/agent/spawn_other.go@@ -0,0 +1,9 @@+//go:build !windows++package main++import "syscall"++func detachedProcessAttrs() *syscall.SysProcAttr {+ return &syscall.SysProcAttr{Setpgid: true}+}diff --git a/agent/cmd/agent/spawn_windows.go b/agent/cmd/agent/spawn_windows.gonew file mode 100644index 00000000..4f63f1ca--- /dev/null+++ b/agent/cmd/agent/spawn_windows.go@@ -0,0 +1,22 @@+//go:build windows++package main++import "syscall"++const (+ // CreateNoWindow: hide the new console window if any.+ createNoWindow = 0x08000000+ // DetachedProcess: child process is not bound to the parent's console.+ 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.+func detachedProcessAttrs() *syscall.SysProcAttr {+ return &syscall.SysProcAttr{+ HideWindow: true,+ CreationFlags: createNoWindow | detachedProcess,+ }+}diff --git a/agent/go.mod b/agent/go.modindex 9fb8bb59..7cc7a676 100644--- a/agent/go.mod+++ b/agent/go.mod@@ -7,6 +7,7 @@ require (github.com/creack/pty v1.1.21github.com/docker/docker v24.0.7+incompatiblegithub.com/gorilla/websocket v1.5.1+ github.com/lxn/walk v0.0.0-20210112085537-c389da54e794github.com/shirou/gopsutil/v3 v3.24.1github.com/spf13/cobra v1.8.0golang.org/x/term v0.27.0@@ -24,9 +25,8 @@ require (github.com/godbus/dbus/v5 v5.1.0 // indirectgithub.com/gogo/protobuf v1.3.2 // indirectgithub.com/inconshreveable/mousetrap v1.1.0 // indirect- github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808 // indirect- github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirectgithub.com/lufia/plan9stats v0.0.0-20231016141302-07b5767bb0ed // indirect+ github.com/lxn/win v0.0.0-20210218163916-a377121e959e // indirectgithub.com/moby/term v0.5.0 // indirectgithub.com/morikuni/aec v1.0.0 // indirectgithub.com/opencontainers/go-digest v1.0.0 // indirect@@ -43,5 +43,6 @@ require (golang.org/x/sys v0.28.0 // indirectgolang.org/x/time v0.5.0 // indirectgolang.org/x/tools v0.16.1 // indirect+ gopkg.in/Knetic/govaluate.v3 v3.0.0 // indirectgotest.tools/v3 v3.5.1 // indirect)diff --git a/agent/go.sum b/agent/go.sumindex 6ffd524b..c6c0cb31 100644--- a/agent/go.sum+++ b/agent/go.sum@@ -35,15 +35,15 @@ github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=-github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808 h1:ftnsTqIUH57XQEF+PnXX9++nlHCzdkuB5zbWyMMruZo=-github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808/go.mod h1:rWifBlzkgrvd7zUqlfq91sWt3473OikgnglnIILx/Jo=-github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 h1:njuLRcjAuMKr7kI3D85AXWkw6/+v9PwtV6M6o11sWHQ=-github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=github.com/lufia/plan9stats v0.0.0-20231016141302-07b5767bb0ed h1:036IscGBfJsFIgJQzlui7nK1Ncm0tp2ktmPj8xO4N/0=github.com/lufia/plan9stats v0.0.0-20231016141302-07b5767bb0ed/go.mod h1:ilwx/Dta8jXAgpFYFvSWEMwxmbWXyiUHkd5FwyKhb5k=+github.com/lxn/walk v0.0.0-20210112085537-c389da54e794 h1:NVRJ0Uy0SOFcXSKLsS65OmI1sgCCfiDUPj+cwnH7GZw=+github.com/lxn/walk v0.0.0-20210112085537-c389da54e794/go.mod h1:E23UucZGqpuUANJooIbHWCufXvOcT6E7Stq81gU+CSQ=+github.com/lxn/win v0.0.0-20210218163916-a377121e959e h1:H+t6A/QJMbhCSEH5rAuRxh+CtW96g0Or0Fxa9IKr4uc=+github.com/lxn/win v0.0.0-20210218163916-a377121e959e/go.mod h1:KxxjdtRkfNoYDCUP5ryK7XJJNTnpC8atvtmTheChOtk=github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=@@ -108,10 +108,9 @@ golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20201018230417-eeed37f84f13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20210218145245-beda7e5e158e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=@@ -134,6 +133,8 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8Tgolang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+gopkg.in/Knetic/govaluate.v3 v3.0.0 h1:18mUyIt4ZlRlFZAAfVetz4/rzlJs9yhN+U02F4u1AOc=+gopkg.in/Knetic/govaluate.v3 v3.0.0/go.mod h1:csKLBORsPbafmSCGTEh3U7Ozmsuq8ZSIlKk1bcqph0E=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=diff --git a/agent/internal/setupui/foreground_windows.go b/agent/internal/setupui/foreground_windows.gonew file mode 100644index 00000000..5535833f--- /dev/null+++ b/agent/internal/setupui/foreground_windows.go@@ -0,0 +1,124 @@+//go:build windows++package setupui++import (+ "syscall"+ "time"+ "unsafe"++ "github.com/lxn/walk"+)++// forceForegroundWindow uses the documented AttachThreadInput recipe to bring+// a freshly-created walk window to the front, working around Windows'+// anti-focus-stealing rules.+//+// The plain TopMost-toggle trick is unreliable: it changes the Z-order but+// Windows still treats the activation as a focus-steal attempt and silently+// drops it on Windows 10/11 if our process isn't already in the foreground.+// AttachThreadInput briefly merges our input queue with the current+// foreground thread's, which Windows treats as the same UI session — and so+// SetForegroundWindow goes through.+func forceForegroundWindow(form walk.Form) {+ if form == nil {+ return+ }+ hwnd := uintptr(form.Handle())+ if hwnd == 0 {+ return+ }++ user32 := syscall.NewLazyDLL("user32.dll")+ kernel32 := syscall.NewLazyDLL("kernel32.dll")++ showWindow := user32.NewProc("ShowWindow")+ setForegroundWindow := user32.NewProc("SetForegroundWindow")+ setFocus := user32.NewProc("SetFocus")+ setActiveWindow := user32.NewProc("SetActiveWindow")+ bringWindowToTop := user32.NewProc("BringWindowToTop")+ getForegroundWindow := user32.NewProc("GetForegroundWindow")+ getWindowThreadProcessId := user32.NewProc("GetWindowThreadProcessId")+ getCurrentThreadId := kernel32.NewProc("GetCurrentThreadId")+ attachThreadInput := user32.NewProc("AttachThreadInput")+ setWindowPos := user32.NewProc("SetWindowPos")+ keybdEvent := user32.NewProc("keybd_event")+ allowSetForegroundWindow := user32.NewProc("AllowSetForegroundWindow")++ const (+ swRestore = 9+ hwndTopmost = ^uintptr(0) // -1+ hwndNotTopmost = ^uintptr(0) - 1 // -2+ swpNoSize = 0x0001+ swpNoMove = 0x0002+ swpShowWindow = 0x0040+ keyEventfKeyUp = 0x0002+ ASFW_ANY = ^uint32(0) // -1+ )++ // (1) Allow ourselves to be the foreground for the next operation,+ // regardless of who's calling. -1 = ASFW_ANY.+ allowSetForegroundWindow.Call(uintptr(ASFW_ANY))++ // (2) Make sure the window is at least restored from any minimized state.+ showWindow.Call(hwnd, swRestore)++ // (3) Simulate a no-op keypress. Windows treats keyboard input as user+ // activity and grants the receiving thread foreground privilege —+ // even on Win10/11 where SetForegroundWindow is otherwise denied.+ keybdEvent.Call(0, 0, 0, 0)+ keybdEvent.Call(0, 0, keyEventfKeyUp, 0)++ // (4) AttachThreadInput trick: temporarily fuse our input queue with the+ // current foreground thread's so SetForegroundWindow is treated as+ // coming from the same UI session.+ fgHwnd, _, _ := getForegroundWindow.Call()+ var fgPid uint32+ fgThread, _, _ := getWindowThreadProcessId.Call(fgHwnd, uintptr(unsafe.Pointer(&fgPid)))+ ourThread, _, _ := getCurrentThreadId.Call()++ attached := false+ if fgThread != 0 && fgThread != ourThread {+ r, _, _ := attachThreadInput.Call(fgThread, ourThread, 1)+ attached = r != 0+ }++ // (5) The full activation sequence: Z-order, foreground, active, focus.+ bringWindowToTop.Call(hwnd)+ setWindowPos.Call(hwnd, hwndTopmost, 0, 0, 0, 0,+ uintptr(swpNoMove|swpNoSize|swpShowWindow))+ setForegroundWindow.Call(hwnd)+ setActiveWindow.Call(hwnd)+ setFocus.Call(hwnd)+ setWindowPos.Call(hwnd, hwndNotTopmost, 0, 0, 0, 0,+ uintptr(swpNoMove|swpNoSize|swpShowWindow))++ if attached {+ attachThreadInput.Call(fgThread, ourThread, 0)+ }+}++// scheduleForceForeground fires the activation recipe several times across+// the first ~1.5 seconds of window life. The first attempt usually races+// the message loop start; later attempts win once the pump is servicing.+// Cheap and idempotent.+func scheduleForceForeground(form walk.Form) {+ if form == nil {+ return+ }+ go func() {+ for _, d := range []time.Duration{+ 0,+ 50 * time.Millisecond,+ 150 * time.Millisecond,+ 400 * time.Millisecond,+ 900 * time.Millisecond,+ 1500 * time.Millisecond,+ } {+ time.Sleep(d)+ form.Synchronize(func() {+ forceForegroundWindow(form)+ })+ }+ }()+}diff --git a/agent/internal/setupui/serverkit.ico b/agent/internal/setupui/serverkit.iconew file mode 100644index 00000000..e6f126dbBinary files /dev/null and b/agent/internal/setupui/serverkit.ico differdiff --git a/agent/internal/setupui/serverkit_header.png b/agent/internal/setupui/serverkit_header.pngnew file mode 100644index 00000000..d3484310Binary files /dev/null and b/agent/internal/setupui/serverkit_header.png differdiff --git a/agent/internal/setupui/setupui.go b/agent/internal/setupui/setupui.goindex 30facd52..29269422 100644--- a/agent/internal/setupui/setupui.go+++ b/agent/internal/setupui/setupui.go@@ -1,21 +1,15 @@-// Package setupui implements a local-loopback HTTP wizard that walks an-// operator through agent pairing without forcing them onto the CLI.+// 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 setupuiimport ("context"- _ "embed"- "encoding/json"- "errors""fmt"- "net"- "net/http""os"- "os/exec""path/filepath""runtime""strings"- "sync""time""github.com/serverkit/agent/internal/config"@@ -24,249 +18,49 @@ import ("github.com/serverkit/agent/internal/pairing")-//go:embed wizard.html-var wizardHTML []byte--// errNoWebView2 signals that a native WebView2 window could not be opened-// and the caller should fall back to the system browser.-var errNoWebView2 = errors.New("native window unavailable")--// Server hosts the local pairing wizard.-type Server struct {- log *logger.Logger- configPath string-- mu sync.RWMutex- state *State- cancel context.CancelFunc- doneCh chan struct{}- listener net.Listener-}--// State is the JSON shape returned by /api/status.-type State struct {- Phase string `json:"phase"` // idle | enrolling | waiting | claimed | error- PanelURL string `json:"panel_url,omitempty"`- PairCode string `json:"pair_code,omitempty"`- PairCodeShort string `json:"pair_code_short,omitempty"`- Fingerprint string `json:"fingerprint,omitempty"`- ServerName string `json:"server_name,omitempty"`- ErrorMessage string `json:"error,omitempty"`-}--// New constructs a wizard server using the given config path for credential persistence.-func New(log *logger.Logger, configPath string) *Server {- return &Server{- log: log.WithComponent("setupui"),- configPath: configPath,- state: &State{Phase: "idle"},- }-}--// Run starts the HTTP server, opens a browser and blocks until pairing-// completes (success or user cancel) or ctx is cancelled.-// Run starts the wizard. It returns when the user closes the window/browser-// or when ctx is cancelled.-//-// On Windows the WebView2 window must be created on the *main* OS thread, so-// the caller is expected to invoke Run from the program's main goroutine-// (i.e. directly from cobra RunE, not from a background goroutine). The HTTP-// server runs in a background goroutine.-func (s *Server) Run(ctx context.Context) error {- ln, err := net.Listen("tcp", "127.0.0.1:0")- if err != nil {- return fmt.Errorf("listen: %w", err)- }- s.listener = ln-- s.doneCh = make(chan struct{})- mux := http.NewServeMux()- mux.HandleFunc("/", s.handleIndex)- mux.HandleFunc("/api/start", s.handleStart)- mux.HandleFunc("/api/status", s.handleStatus)- mux.HandleFunc("/api/cancel", s.handleCancel)- mux.HandleFunc("/api/close", s.handleClose)-- srv := &http.Server{- Handler: mux,- ReadHeaderTimeout: 10 * time.Second,- }-- go func() {- _ = srv.Serve(ln)- }()-- url := fmt.Sprintf("http://%s/", ln.Addr().String())- fmt.Printf("ServerKit Agent — pairing wizard:\n %s\n\n", url)-- // Try the native WebView2 window on the *main* goroutine. It blocks- // until the window is closed. If WebView2 isn't available we fall- // back to the system browser.- winErr := openInNativeWindow(url, "ServerKit Agent · Setup")- if winErr == nil {- // Window closed by the user — tear down.- s.signalDone()- } else {- fmt.Println("Opening in your default browser…")- fmt.Println("Leave this terminal open until pairing completes. Press Ctrl+C to cancel.")- if err := openBrowser(url); err != nil {- s.log.Warn("could not open browser automatically", "error", err)- fmt.Println("(Couldn't open browser automatically — copy the URL above into your browser.)")- }- // Wait for either context cancel or the user pressing "Done" in the wizard.- select {- case <-ctx.Done():- case <-s.doneCh:- }- }-- shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)- defer cancel()- _ = srv.Shutdown(shutdownCtx)-- s.mu.RLock()- defer s.mu.RUnlock()- if s.state.Phase == "error" {- return fmt.Errorf("pairing failed: %s", s.state.ErrorMessage)- }- return nil-}--// ---- handlers ------func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {- if r.URL.Path != "/" {- http.NotFound(w, r)- return- }- w.Header().Set("Content-Type", "text/html; charset=utf-8")- w.Header().Set("Cache-Control", "no-store")- _, _ = w.Write(wizardHTML)-}--func (s *Server) handleStart(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- http.Error(w, "method not allowed", http.StatusMethodNotAllowed)- return- }- var req struct {- PanelURL string `json:"panel_url"`- Passphrase string `json:"passphrase"`- }- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- http.Error(w, "invalid json", http.StatusBadRequest)- return- }- req.PanelURL = strings.TrimSpace(req.PanelURL)- req.Passphrase = strings.TrimSpace(req.Passphrase)- if req.PanelURL == "" || req.Passphrase == "" {- http.Error(w, "panel_url and passphrase are required", http.StatusBadRequest)- return- }- if len(req.Passphrase) < 4 {- http.Error(w, "passphrase must be at least 4 characters", http.StatusBadRequest)- return- }- if !strings.HasPrefix(req.PanelURL, "http://") && !strings.HasPrefix(req.PanelURL, "https://") {- req.PanelURL = "https://" + req.PanelURL- }-- s.mu.Lock()- if s.state.Phase != "idle" && s.state.Phase != "error" && s.state.Phase != "claimed" {- s.mu.Unlock()- http.Error(w, "pairing already in progress", http.StatusConflict)- return- }- if s.cancel != nil {- s.cancel()- }- ctx, cancel := context.WithCancel(context.Background())- s.cancel = cancel- s.state = &State{Phase: "enrolling", PanelURL: req.PanelURL}- s.mu.Unlock()-- go s.runPairing(ctx, req.PanelURL, req.Passphrase)-- w.WriteHeader(http.StatusAccepted)- _, _ = w.Write([]byte(`{"ok":true}`))-}--func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {- s.mu.RLock()- state := *s.state- s.mu.RUnlock()- w.Header().Set("Content-Type", "application/json")- w.Header().Set("Cache-Control", "no-store")- _ = json.NewEncoder(w).Encode(state)-}--func (s *Server) handleCancel(w http.ResponseWriter, r *http.Request) {- s.mu.Lock()- if s.cancel != nil {- s.cancel()- s.cancel = 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 {+ if configPath == "" {+ configPath = config.DefaultConfigPath()}- s.state = &State{Phase: "idle"}- s.mu.Unlock()- w.WriteHeader(http.StatusNoContent)-}--func (s *Server) handleClose(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusNoContent)- go func() {- time.Sleep(200 * time.Millisecond)- s.signalDone()- }()+ return runWindow(ctx, log.WithComponent("setupui"), configPath)}-func (s *Server) signalDone() {- select {- case <-s.doneCh:- default:- close(s.doneCh)- }+// 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)}-// ---- pairing driver ------func (s *Server) runPairing(ctx context.Context, panelURL, passphrase string) {- setErr := func(msg string) {- s.mu.Lock()- s.state.Phase = "error"- s.state.ErrorMessage = msg- s.mu.Unlock()- }+// 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 {- setErr(fmt.Sprintf("could not load keypair: %v", err))+ cb.onError(fmt.Errorf("load keypair: %w", err))return}- collector := metrics.NewCollector(config.MetricsConfig{}, s.log)+ collector := metrics.NewCollector(config.MetricsConfig{}, log)infoCtx, infoCancel := context.WithTimeout(ctx, 8*time.Second)sysInfo, _ := collector.GetSystemInfo(infoCtx)infoCancel()- sysMap := map[string]interface{}{}- if sysInfo != nil {- sysMap = map[string]interface{}{- "hostname": sysInfo.Hostname,- "os": sysInfo.OS,- "platform": sysInfo.Platform,- "platform_version": sysInfo.PlatformVersion,- "architecture": sysInfo.Architecture,- "cpu_cores": sysInfo.CPUCores,- "total_memory": sysInfo.TotalMemory,- "total_disk": sysInfo.TotalDisk,- }- } else {- hostname, _ := os.Hostname()- sysMap["hostname"] = hostname- sysMap["os"] = runtime.GOOS- sysMap["architecture"] = runtime.GOARCH- }- client := pairing.NewClient(panelURL, s.log)+ 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(),@@ -276,43 +70,61 @@ func (s *Server) runPairing(ctx context.Context, panelURL, passphrase string) {})enrollCancel()if err != nil {- setErr(fmt.Sprintf("enroll: %v", err))+ cb.onError(fmt.Errorf("enroll: %w", err))return}- s.mu.Lock()- s.state.Phase = "waiting"- s.state.PairCode = enrollResp.PairCode- s.state.PairCodeShort = enrollResp.PairCodeFormatted- s.state.Fingerprint = enrollResp.PubkeyFingerprint- s.mu.Unlock()+ cb.onEnrolled(enrollResp.PairCode, enrollResp.PairCodeFormatted)- creds, err := client.WaitForClaim(ctx, func(code, formatted, expiresAt string) {- s.mu.Lock()- s.state.PairCode = code- s.state.PairCodeShort = formatted- s.mu.Unlock()+ creds, err := client.WaitForClaim(ctx, func(code, formatted, _ string) {+ cb.onEnrolled(code, formatted)})if err != nil {if ctx.Err() != nil {- return+ return // user cancelled}- setErr(fmt.Sprintf("waiting for claim: %v", err))+ cb.onError(fmt.Errorf("waiting for claim: %w", err))return}- if err := saveCredentials(s.configPath, panelURL, creds); err != nil {- setErr(fmt.Sprintf("save credentials: %v", err))+ if err := saveCredentials(configPath, panelURL, creds); err != nil {+ cb.onError(fmt.Errorf("save credentials: %w", err))return}- s.mu.Lock()- s.state.Phase = "claimed"- s.state.ServerName = creds.Name- s.mu.Unlock()-- // On Windows, flip the service to auto-start and start it now that we have credentials.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 {@@ -340,15 +152,3 @@ func saveCredentials(configPath, panelURL string, creds *pairing.Credentials) er}return cfg.SaveCredentials()}--// openBrowser opens the URL in the user's default browser.-func openBrowser(url string) error {- switch runtime.GOOS {- case "windows":- return exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()- case "darwin":- return exec.Command("open", url).Start()- default:- return exec.Command("xdg-open", url).Start()- }-}diff --git a/agent/internal/setupui/window_other.go b/agent/internal/setupui/window_other.goindex 96eecdb4..27f13217 100644--- a/agent/internal/setupui/window_other.go+++ b/agent/internal/setupui/window_other.go@@ -2,9 +2,15 @@package setupui-// openInNativeWindow falls back to opening the user's default browser on-// non-Windows platforms. Returns errNoWebView2 to signal "no native window-// available; caller should keep the HTTP server running until done."-func openInNativeWindow(url, title string) error {- return errNoWebView2+import (+ "context"+ "fmt"++ "github.com/serverkit/agent/internal/logger"+)++// runWindow returns an error directing non-Windows users to the CLI command.+// The desktop wizard is Windows-only because it uses native Win32 controls.+func runWindow(_ context.Context, _ *logger.Logger, _ string) error {+ return fmt.Errorf("the graphical setup wizard is only available on Windows; on this platform run: serverkit-agent pair")}diff --git a/agent/internal/setupui/window_windows.go b/agent/internal/setupui/window_windows.goindex 4992a4c0..61fdcb5e 100644--- a/agent/internal/setupui/window_windows.go+++ b/agent/internal/setupui/window_windows.go@@ -3,29 +3,517 @@package setupuiimport (- wv "github.com/jchv/go-webview2"+ "bytes"+ "context"+ _ "embed"+ "errors"+ "fmt"+ "image/png"+ "os"+ "runtime"+ "sync"++ "github.com/lxn/walk"+ dec "github.com/lxn/walk/declarative"++ "github.com/serverkit/agent/internal/logger"+)++//go:embed serverkit.ico+var iconBytes []byte++//go:embed serverkit_header.png+var headerPNG []byte++// stage names (used as panel keys for clarity)+const (+ stageForm = "form"+ stagePairing = "pairing"+ stageDone = "done")-// openInNativeWindow opens the wizard URL in a real WebView2 window-// (no browser chrome). It blocks until the user closes the window.-func openInNativeWindow(url, title string) error {- w := wv.NewWithOptions(wv.WebViewOptions{- Debug: false,- AutoFocus: true,- WindowOptions: wv.WindowOptions{- Title: title,- Width: 720,- Height: 760,- Center: true,+// runWindow shows the native pairing wizard. It blocks until the user closes+// the window (success, cancel, or X-button). Returns nil on graceful close.+//+// Walk's MainWindow event loop must run on the OS main thread; the caller+// (cmd/agent.runDesktop) is responsible for runtime.LockOSThread before us.+func runWindow(ctx context.Context, log *logger.Logger, configPath string) (retErr error) {+ runtime.LockOSThread()++ // Surface panics as a real error dialog so a misconfigured widget can+ // never produce the silent-failure mode that motivated this rewrite.+ defer func() {+ if r := recover(); r != nil {+ retErr = fmt.Errorf("setup wizard panic: %v", r)+ walk.MsgBox(nil, "ServerKit Agent", retErr.Error(), walk.MsgBoxIconError)+ }+ }()++ w := &wizardUI{+ log: log,+ configPath: configPath,+ }++ // Hook ctx cancellation into the wizard: if the parent ctx is cancelled+ // (e.g. SIGINT) we close the window from a goroutine.+ w.runCtx, w.cancel = context.WithCancel(ctx)+ defer w.cancel()++ go func() {+ <-w.runCtx.Done()+ if w.mw != nil {+ w.mw.Synchronize(func() {+ if w.mw != nil {+ w.mw.Close()+ }+ })+ }+ }()++ return w.show()+}++type wizardUI struct {+ log *logger.Logger+ configPath string++ runCtx context.Context+ cancel context.CancelFunc++ mu sync.Mutex+ pairCancel context.CancelFunc++ mw *walk.MainWindow++ headerImage *walk.ImageView++ // stage 1 widgets+ urlEdit *walk.LineEdit+ passEdit *walk.LineEdit+ nameEdit *walk.LineEdit+ formErr *walk.Label+ startBtn *walk.PushButton++ // stage 2 widgets+ codeLabel *walk.Label+ statusLabel *walk.Label+ pairErrLabel *walk.Label+ cancelBtn *walk.PushButton++ // stage 3 widgets+ doneTitle *walk.Label+ doneSub *walk.Label++ // stage panels+ formPanel *walk.Composite+ pairPanel *walk.Composite+ donePanel *walk.Composite+}++func (w *wizardUI) show() error {+ hostname, _ := os.Hostname()++ const (+ brandPurple = 0x6366F1+ errorRed = 0xDC2626+ mutedGray = 0x6B7280+ subtleGray = 0x9CA3AF+ darkText = 0x111827+ medText = 0x374151+ titleSize = 14+ bodySize = 9+ smallSize = 8+ codeSize = 32+ )++ err := (dec.MainWindow{+ AssignTo: &w.mw,+ Title: "ServerKit Agent",+ MinSize: dec.Size{Width: 440, Height: 580},+ Size: dec.Size{Width: 440, Height: 580},+ Layout: dec.VBox{MarginsZero: false, Margins: dec.Margins{Left: 28, Top: 24, Right: 28, Bottom: 28}, Spacing: 0},+ Background: dec.SolidColorBrush{Color: walk.RGB(248, 250, 252)},+ Children: []dec.Widget{+ // ── Brand header ───────────────────────────────────────────────+ dec.Composite{+ Layout: dec.HBox{MarginsZero: true, Spacing: 16},+ Children: []dec.Widget{+ dec.ImageView{+ AssignTo: &w.headerImage,+ MinSize: dec.Size{Width: 60, Height: 60},+ MaxSize: dec.Size{Width: 60, Height: 60},+ Mode: dec.ImageViewModeZoom,+ },+ dec.Composite{+ Layout: dec.VBox{MarginsZero: true, Spacing: 4},+ Children: []dec.Widget{+ dec.VSpacer{},+ dec.Label{+ Text: "Pair this server",+ Font: dec.Font{PointSize: titleSize, Bold: true},+ TextColor: rgbHex(darkText),+ },+ dec.Label{+ Text: "Connect this machine to your ServerKit panel.",+ Font: dec.Font{PointSize: bodySize},+ TextColor: rgbHex(mutedGray),+ },+ dec.VSpacer{},+ },+ },+ },+ },++ dec.VSpacer{Size: 22},++ // ── Stage 1: connection form ────────────────────────────────────+ dec.Composite{+ AssignTo: &w.formPanel,+ Layout: dec.VBox{MarginsZero: false, Margins: dec.Margins{Left: 16, Top: 18, Right: 16, Bottom: 18}, Spacing: 2},+ Background: dec.SolidColorBrush{Color: walk.RGB(255, 255, 255)},+ Children: []dec.Widget{+ // Panel URL+ dec.Label{+ Text: "Panel URL",+ Font: dec.Font{Bold: true, PointSize: bodySize},+ TextColor: rgbHex(medText),+ },+ dec.VSpacer{Size: 2},+ dec.LineEdit{+ AssignTo: &w.urlEdit,+ CueBanner: "https://panel.example.com",+ MaxLength: 500,+ },+ dec.Label{+ Text: "The full URL of your ServerKit control panel.",+ Font: dec.Font{PointSize: smallSize},+ TextColor: rgbHex(subtleGray),+ },++ dec.VSpacer{Size: 12},++ // Passphrase+ dec.Label{+ Text: "Passphrase",+ Font: dec.Font{Bold: true, PointSize: bodySize},+ TextColor: rgbHex(medText),+ },+ dec.VSpacer{Size: 2},+ dec.LineEdit{+ AssignTo: &w.passEdit,+ PasswordMode: true,+ CueBanner: "Set in the panel under Add Server",+ MaxLength: 200,+ },+ dec.Label{+ Text: "Generated in your panel under Servers → Add Server.",+ Font: dec.Font{PointSize: smallSize},+ TextColor: rgbHex(subtleGray),+ },++ dec.VSpacer{Size: 12},++ // Server name+ dec.Label{+ Text: "Server name (optional)",+ Font: dec.Font{Bold: true, PointSize: bodySize},+ TextColor: rgbHex(medText),+ },+ dec.VSpacer{Size: 2},+ dec.LineEdit{+ AssignTo: &w.nameEdit,+ Text: hostname,+ CueBanner: "Defaults to hostname",+ },+ dec.Label{+ Text: "How this machine appears in your panel.",+ Font: dec.Font{PointSize: smallSize},+ TextColor: rgbHex(subtleGray),+ },++ dec.VSpacer{Size: 14},++ dec.Label{+ AssignTo: &w.formErr,+ TextColor: rgbHex(errorRed),+ Font: dec.Font{PointSize: bodySize},+ Text: "",+ },+ dec.PushButton{+ AssignTo: &w.startBtn,+ Text: "Connect →",+ MinSize: dec.Size{Height: 36},+ OnClicked: w.handleConnect,+ },+ },+ },++ // ── Stage 2: pairing code (hidden initially) ──────────────────+ dec.Composite{+ AssignTo: &w.pairPanel,+ Visible: false,+ Layout: dec.VBox{MarginsZero: false, Margins: dec.Margins{Left: 16, Top: 24, Right: 16, Bottom: 24}, Spacing: 0},+ Background: dec.SolidColorBrush{Color: walk.RGB(255, 255, 255)},+ Children: []dec.Widget{+ dec.Label{+ Text: "Open your panel and enter this code:",+ Font: dec.Font{PointSize: bodySize},+ TextColor: rgbHex(mutedGray),+ },+ dec.VSpacer{Size: 16},+ dec.Composite{+ Layout: dec.HBox{MarginsZero: true},+ Children: []dec.Widget{+ dec.HSpacer{},+ dec.Label{+ AssignTo: &w.codeLabel,+ Text: "",+ Font: dec.Font{PointSize: codeSize, Bold: true, Family: "Consolas"},+ TextColor: rgbHex(brandPurple),+ TextAlignment: dec.AlignCenter,+ },+ dec.HSpacer{},+ },+ },+ dec.VSpacer{Size: 16},+ dec.Label{+ AssignTo: &w.statusLabel,+ Text: "Waiting for the panel to claim this server…",+ Font: dec.Font{PointSize: bodySize},+ TextColor: rgbHex(mutedGray),+ TextAlignment: dec.AlignCenter,+ },+ dec.Label{+ AssignTo: &w.pairErrLabel,+ TextColor: rgbHex(errorRed),+ Font: dec.Font{PointSize: bodySize},+ Text: "",+ },+ dec.VSpacer{Size: 16},+ dec.PushButton{+ AssignTo: &w.cancelBtn,+ Text: "Cancel",+ MinSize: dec.Size{Height: 34},+ OnClicked: w.handleCancel,+ },+ },+ },++ // ── Stage 3: success ───────────────────────────────────────────+ dec.Composite{+ AssignTo: &w.donePanel,+ Visible: false,+ Layout: dec.VBox{MarginsZero: false, Margins: dec.Margins{Left: 16, Top: 24, Right: 16, Bottom: 24}, Spacing: 10},+ Background: dec.SolidColorBrush{Color: walk.RGB(255, 255, 255)},+ Children: []dec.Widget{+ dec.Label{+ AssignTo: &w.doneTitle,+ Text: "Successfully paired",+ Font: dec.Font{PointSize: titleSize, Bold: true},+ TextColor: walk.RGB(16, 185, 129),+ },+ dec.Label{+ AssignTo: &w.doneSub,+ Text: "",+ Font: dec.Font{PointSize: bodySize},+ },+ dec.VSpacer{Size: 8},+ dec.PushButton{+ Text: "Close",+ MinSize: dec.Size{Height: 36},+ OnClicked: func() { w.mw.Close() },+ },+ },+ },++ dec.VSpacer{},},- })- if w == nil {- return errNoWebView2+ }).Create()+ if err != nil {+ return fmt.Errorf("create window: %w", err)+ }++ if icon, err := loadAppIcon(); err == nil && icon != nil {+ _ = w.mw.SetIcon(icon)}- defer w.Destroy()+ if bmp, err := loadHeaderBitmap(); err == nil && bmp != nil && w.headerImage != nil {+ _ = w.headerImage.SetImage(bmp)+ }++ w.mw.Show()+ // Windows' anti-focus-stealing rule will leave the window invisible behind+ // the desktop when the agent is launched from the Start menu shortcut.+ // scheduleForceForeground retries the AttachThreadInput-based activation+ // recipe several times across the first ~1.5s of window life so we win+ // regardless of when walk's message pump actually starts servicing.+ scheduleForceForeground(w.mw)+ w.mw.Run()++ w.mu.Lock()+ if w.pairCancel != nil {+ w.pairCancel()+ }+ w.mu.Unlock()- w.SetTitle(title)- w.Navigate(url)- w.Run()return nil}++// handleConnect is fired by the "Connect" button. Validates inputs, kicks off+// pairing in a goroutine, and transitions to the pairing stage on success.+func (w *wizardUI) handleConnect() {+ url := w.urlEdit.Text()+ pass := w.passEdit.Text()+ name := w.nameEdit.Text()++ if url == "" {+ w.formErr.SetText("Panel URL is required.")+ return+ }+ if len(pass) < 4 {+ w.formErr.SetText("Passphrase must be at least 4 characters.")+ return+ }+ w.formErr.SetText("")+ w.startBtn.SetEnabled(false)+ w.startBtn.SetText("Connecting…")++ pairCtx, cancel := context.WithCancel(w.runCtx)+ w.mu.Lock()+ w.pairCancel = cancel+ w.mu.Unlock()++ cb := pairingCallbacks{+ onEnrolled: func(code, formatted string) {+ w.mw.Synchronize(func() {+ w.codeLabel.SetText(displayCode(code, formatted))+ w.showStage(stagePairing)+ })+ },+ onClaimed: func(serverName string) {+ w.mw.Synchronize(func() {+ if serverName == "" {+ serverName = "this server"+ }+ 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)+ })+ },+ onError: func(err error) {+ w.mw.Synchronize(func() {+ msg := errorPretty(err)+ if w.pairPanel.Visible() {+ w.pairErrLabel.SetText(msg)+ w.cancelBtn.SetText("Try again")+ } else {+ w.formErr.SetText(msg)+ w.startBtn.SetEnabled(true)+ w.startBtn.SetText("Connect")+ }+ })+ },+ }++ go runPairing(pairCtx, w.log, w.configPath, url, pass, name, cb)+}++// handleCancel rolls back to the form stage and cancels any in-flight pairing.+func (w *wizardUI) handleCancel() {+ w.mu.Lock()+ if w.pairCancel != nil {+ w.pairCancel()+ w.pairCancel = nil+ }+ w.mu.Unlock()++ w.formErr.SetText("")+ w.pairErrLabel.SetText("")+ w.codeLabel.SetText("")+ w.cancelBtn.SetText("Cancel")+ w.startBtn.SetEnabled(true)+ w.startBtn.SetText("Connect")+ w.showStage(stageForm)+}++func (w *wizardUI) showStage(stage string) {+ w.formPanel.SetVisible(stage == stageForm)+ w.pairPanel.SetVisible(stage == stagePairing)+ w.donePanel.SetVisible(stage == stageDone)+}++// errorPretty turns errors from runPairing into a user-friendly one-liner.+func errorPretty(err error) string {+ if err == nil {+ return ""+ }+ if errors.Is(err, context.Canceled) {+ return "Cancelled."+ }+ return err.Error()+}++// displayCode prefers the server-formatted code (e.g. "1234-5678") and falls+// back to the raw code if the panel didn't supply one.+func displayCode(code, formatted string) string {+ if formatted != "" {+ return formatted+ }+ return code+}++func rgbHex(rgb uint32) walk.Color {+ return walk.RGB(byte(rgb>>16), byte(rgb>>8), byte(rgb))+}++// loadAppIcon writes the embedded .ico to a temp file (walk doesn't load icons+// from raw bytes) and returns it. The temp file lingers until process exit;+// Windows handles cleanup of %TEMP%.+var (+ iconOnce sync.Once+ iconRef *walk.Icon+)++func loadAppIcon() (*walk.Icon, error) {+ iconOnce.Do(func() {+ f, err := os.CreateTemp("", "serverkit-*.ico")+ if err != nil {+ return+ }+ _, _ = f.Write(iconBytes)+ _ = f.Close()+ ic, err := walk.NewIconFromFile(f.Name())+ if err != nil {+ return+ }+ iconRef = ic+ })+ if iconRef == nil {+ return nil, fmt.Errorf("icon not loaded")+ }+ return iconRef, nil+}++// loadHeaderBitmap decodes the embedded brand PNG into a walk Bitmap suitable+// for an ImageView. Must be called after the walk runtime is up (i.e. after+// MainWindow.Create), otherwise the underlying GDI calls return errors.+var (+ headerOnce sync.Once+ headerBmp *walk.Bitmap+)++func loadHeaderBitmap() (*walk.Bitmap, error) {+ headerOnce.Do(func() {+ img, err := png.Decode(bytes.NewReader(headerPNG))+ if err != nil {+ return+ }+ bmp, err := walk.NewBitmapFromImageForDPI(img, 96)+ if err != nil {+ return+ }+ headerBmp = bmp+ })+ if headerBmp == nil {+ return nil, fmt.Errorf("header bitmap not loaded")+ }+ return headerBmp, nil+}diff --git a/agent/internal/setupui/wizard.html b/agent/internal/setupui/wizard.htmldeleted file mode 100644index 5f537d44..00000000--- a/agent/internal/setupui/wizard.html+++ /dev/null@@ -1,513 +0,0 @@-<!doctype html>-<html lang="en">-<head>-<meta charset="utf-8">-<meta name="viewport" content="width=device-width,initial-scale=1">-<title>ServerKit Agent Setup</title>-<style>- /* Windows 11 Fluent-inspired design system */- :root {- --accent: #0067c0;- --accent-hover: #1a78c9;- --accent-pressed: #2f87d1;- --bg: #f3f3f3;- --bg-mica: #f9f9f9;- --layer: #ffffff;- --layer-alt: #fbfbfb;- --stroke: #e5e5e5;- --stroke-soft: #ededed;- --text: #1b1b1b;- --text-secondary: #5d5d5d;- --text-tertiary: #8a8a8a;- --success: #0e7c3a;- --danger: #c42b1c;- --shadow-sm: 0 1px 2px rgba(0,0,0,0.04);- --shadow-md: 0 2px 6px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.04);- --radius: 8px;- --radius-sm: 4px;- --radius-lg: 12px;- }- @media (prefers-color-scheme: dark) {- :root {- --bg: #202020;- --bg-mica: #2c2c2c;- --layer: #2b2b2b;- --layer-alt: #323232;- --stroke: #3a3a3a;- --stroke-soft: #353535;- --text: #ffffff;- --text-secondary: #c5c5c5;- --text-tertiary: #8a8a8a;- --accent: #4cc2ff;- --accent-hover: #5cc9ff;- --accent-pressed: #74cfff;- --success: #6ccb5f;- --danger: #ff99a4;- }- }- * { box-sizing: border-box; }- html, body {- margin: 0; padding: 0;- height: 100vh;- font-family: "Segoe UI Variable", "Segoe UI", system-ui, -apple-system, sans-serif;- font-size: 14px;- color: var(--text);- background: var(--bg-mica);- -webkit-font-smoothing: antialiased;- overflow: hidden;- user-select: none;- }- input { user-select: text; -webkit-user-select: text; }- .app {- display: flex; flex-direction: column;- height: 100vh;- background: var(--bg-mica);- }-- /* Title bar (Win11 style, drag region simulated) */- .titlebar {- height: 40px;- display: flex; align-items: center;- padding: 0 16px;- border-bottom: 1px solid var(--stroke-soft);- background: var(--bg-mica);- flex-shrink: 0;- }- .titlebar .title {- font-size: 12px; font-weight: 600; color: var(--text);- letter-spacing: 0.01em;- }- .titlebar .icon {- width: 16px; height: 16px;- background: linear-gradient(135deg, #0067c0, #4cc2ff);- border-radius: 3px;- margin-right: 10px;- display: inline-flex; align-items: center; justify-content: center;- color: white; font-size: 9px; font-weight: 800;- }-- /* Content area */- .content {- flex: 1;- overflow-y: auto;- padding: 28px 36px;- display: flex; flex-direction: column;- }-- /* Page header */- .page-title {- font-size: 28px; font-weight: 600; line-height: 1.2;- margin: 0 0 6px;- letter-spacing: -0.01em;- }- .page-sub {- font-size: 14px; color: var(--text-secondary);- margin: 0 0 24px; line-height: 1.5;- max-width: 520px;- }-- /* Card (Layer / Mica) */- .card {- background: var(--layer);- border: 1px solid var(--stroke);- border-radius: var(--radius);- padding: 20px;- box-shadow: var(--shadow-sm);- margin-bottom: 12px;- }- .card + .card { margin-top: 0; }-- /* Form fields */- .field { margin-bottom: 18px; }- .field:last-child { margin-bottom: 0; }- .field label {- display: block;- font-size: 13px; font-weight: 600;- margin-bottom: 6px;- color: var(--text);- }- .field .desc {- font-size: 12px; color: var(--text-secondary);- margin-top: 6px; line-height: 1.45;- }- .input {- width: 100%;- height: 32px;- padding: 0 10px;- background: var(--layer-alt);- border: 1px solid var(--stroke);- border-bottom: 1px solid var(--text-tertiary);- border-radius: var(--radius-sm);- color: var(--text);- font-family: inherit; font-size: 14px;- transition: border-color 0.12s;- outline: none;- }- .input:hover { background: var(--layer); }- .input:focus {- border-bottom: 2px solid var(--accent);- padding-bottom: 0;- }-- /* Buttons */- .actions {- display: flex; gap: 8px; justify-content: flex-end;- margin-top: 20px;- }- .btn {- height: 32px; min-width: 100px;- padding: 0 16px;- border-radius: var(--radius-sm);- font-family: inherit; font-size: 14px; font-weight: 600;- cursor: pointer;- transition: background 0.1s, border-color 0.1s, transform 0.05s;- border: 1px solid var(--stroke);- background: var(--layer);- color: var(--text);- }- .btn:hover { background: var(--layer-alt); }- .btn:active { transform: translateY(0.5px); }- .btn-primary {- background: var(--accent);- border-color: var(--accent);- color: white;- }- .btn-primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }- .btn-primary:active { background: var(--accent-pressed); border-color: var(--accent-pressed); }- .btn-primary:disabled {- background: var(--stroke); border-color: var(--stroke);- color: var(--text-tertiary); cursor: not-allowed;- }-- /* InfoBar */- .infobar {- display: flex; align-items: flex-start; gap: 10px;- padding: 10px 12px; border-radius: var(--radius-sm);- background: rgba(196,43,28,0.08);- border: 1px solid rgba(196,43,28,0.25);- color: var(--text);- font-size: 13px;- margin-bottom: 16px;- }- .infobar.success {- background: rgba(14,124,58,0.08);- border-color: rgba(14,124,58,0.25);- }- .infobar .ico { font-size: 16px; line-height: 1; flex-shrink: 0; }-- /* Stepper */- .steps {- display: flex; gap: 0; margin-bottom: 22px;- background: var(--layer); border: 1px solid var(--stroke);- border-radius: var(--radius); padding: 6px; align-items: center;- }- .step {- flex: 1; display: flex; align-items: center; gap: 8px;- padding: 6px 10px; border-radius: var(--radius-sm);- font-size: 12px; color: var(--text-tertiary);- transition: background 0.12s;- }- .step .num {- width: 18px; height: 18px; border-radius: 50%;- background: var(--stroke); color: var(--text-secondary);- display: inline-flex; align-items: center; justify-content: center;- font-weight: 600; font-size: 11px;- }- .step.active { color: var(--text); background: var(--layer-alt); }- .step.active .num { background: var(--accent); color: white; }- .step.done .num { background: var(--success); color: white; }- .step.done { color: var(--text-secondary); }-- /* Pair code display */- .pair-display {- display: flex; flex-direction: column; align-items: center;- padding: 24px 16px;- background: linear-gradient(135deg, var(--layer-alt), var(--layer));- border: 1px solid var(--stroke);- border-radius: var(--radius-lg);- margin-bottom: 16px;- }- .pair-label {- font-size: 12px; font-weight: 600;- color: var(--text-secondary);- text-transform: uppercase; letter-spacing: 0.08em;- margin-bottom: 10px;- }- .pair-code {- font-family: "Cascadia Mono", "Consolas", "SF Mono", ui-monospace, monospace;- font-size: 44px; font-weight: 700;- letter-spacing: 0.18em;- color: var(--accent);- line-height: 1.1;- margin-bottom: 6px;- user-select: text; -webkit-user-select: text;- }- .fingerprint-row {- display: flex; align-items: center; gap: 6px;- font-size: 11px; color: var(--text-tertiary);- margin-top: 8px;- font-family: "Cascadia Mono", "Consolas", monospace;- word-break: break-all;- text-align: center;- user-select: text; -webkit-user-select: text;- }-- /* Spinner */- .progress-row {- display: flex; align-items: center; gap: 10px;- padding: 10px 0;- color: var(--text-secondary);- font-size: 13px;- }- .ring {- width: 16px; height: 16px; flex-shrink: 0;- border: 2px solid var(--stroke);- border-top-color: var(--accent);- border-radius: 50%;- animation: spin 0.8s linear infinite;- }- @keyframes spin { to { transform: rotate(360deg); } }-- /* Success */- .success-hero {- display: flex; flex-direction: column; align-items: center;- padding: 24px 0;- }- .success-circle {- width: 56px; height: 56px;- background: var(--success);- border-radius: 50%;- display: flex; align-items: center; justify-content: center;- margin-bottom: 14px;- box-shadow: 0 4px 12px rgba(14,124,58,0.35);- }- .success-circle svg { width: 28px; height: 28px; color: white; }-- /* Instructions list */- .instr {- list-style: none; padding: 0; margin: 0;- display: flex; flex-direction: column; gap: 10px;- }- .instr li {- display: flex; align-items: flex-start; gap: 12px;- font-size: 13px; color: var(--text-secondary);- line-height: 1.5;- }- .instr .bullet {- width: 22px; height: 22px; flex-shrink: 0;- background: var(--accent);- color: white;- border-radius: 50%;- display: flex; align-items: center; justify-content: center;- font-size: 12px; font-weight: 700;- margin-top: -1px;- }- .instr strong { color: var(--text); }-- .hidden { display: none !important; }-</style>-</head>-<body>-<div class="app">- <div class="titlebar">- <span class="icon">SK</span>- <span class="title">ServerKit Agent · Setup</span>- </div>-- <div class="content">- <!-- Stepper -->- <div class="steps" id="stepper">- <div class="step active" data-step="1"><span class="num">1</span><span>Connect</span></div>- <div class="step" data-step="2"><span class="num">2</span><span>Pair code</span></div>- <div class="step" data-step="3"><span class="num">3</span><span>Done</span></div>- </div>-- <!-- View 1: Form -->- <div id="view-form">- <h1 class="page-title">Pair this server</h1>- <p class="page-sub">- Connect this machine to your ServerKit panel. We'll generate a short- code that you'll type into the panel to confirm.- </p>-- <div id="form-error" class="infobar hidden">- <span class="ico">⚠</span><span id="form-error-text"></span>- </div>-- <div class="card">- <form id="pair-form" autocomplete="off">- <div class="field">- <label for="panel">ServerKit panel URL</label>- <input id="panel" class="input" type="url" placeholder="https://panel.example.com" required autofocus>- <div class="desc">The address you use to log into your ServerKit panel.</div>- </div>- <div class="field">- <label for="passphrase">Passphrase</label>- <input id="passphrase" class="input" type="password" placeholder="Pick something memorable" required minlength="4">- <div class="desc">You'll type this into the panel along with the pair code. 4+ characters.</div>- </div>- </form>- </div>-- <div class="actions">- <button id="quit-btn" class="btn" type="button">Cancel</button>- <button id="submit-btn" class="btn btn-primary" type="button">Begin pairing</button>- </div>- </div>-- <!-- View 2: Waiting / pair code -->- <div id="view-waiting" class="hidden">- <h1 class="page-title">Enter this code in the panel</h1>- <p class="page-sub">- The code rotates every minute. As soon as someone in the panel claims- this server, this window will continue.- </p>-- <div class="pair-display">- <div class="pair-label">Pair code</div>- <div class="pair-code" id="pair-code">— — — — — —</div>- <div class="fingerprint-row">- fingerprint: <span id="fingerprint">—</span>- </div>- </div>-- <div class="card">- <ol class="instr">- <li><span class="bullet">1</span><div>Open the <strong>ServerKit panel</strong> in your browser.</div></li>- <li><span class="bullet">2</span><div>Go to <strong>Servers → Add Server → Pair existing agent</strong>.</div></li>- <li><span class="bullet">3</span><div>Enter the <strong>pair code</strong> above and the <strong>passphrase</strong> you just set.</div></li>- </ol>- </div>-- <div class="progress-row">- <span class="ring"></span>- <span id="wait-msg">Waiting for the panel to claim this agent…</span>- </div>-- <div class="actions">- <button id="cancel-btn" class="btn" type="button">Cancel</button>- </div>- </div>-- <!-- View 3: Success -->- <div id="view-success" class="hidden">- <div class="success-hero">- <div class="success-circle">- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">- <polyline points="20 6 9 17 4 12"/>- </svg>- </div>- <h1 class="page-title" style="text-align:center; margin-bottom:4px">All set</h1>- <p class="page-sub" id="success-name" style="text-align:center">Your agent is paired with the panel.</p>- </div>-- <div class="infobar success">- <span class="ico">✓</span>- <span>The agent service will start automatically. This server should appear as <strong>Online</strong> in the panel within a few seconds.</span>- </div>-- <div class="actions">- <button id="close-btn" class="btn btn-primary" type="button">Close</button>- </div>- </div>- </div>-</div>--<script>- const $ = (id) => document.getElementById(id);- function setStep(n) {- document.querySelectorAll('#stepper .step').forEach(el => {- const s = Number(el.dataset.step);- el.classList.remove('active', 'done');- if (s < n) el.classList.add('done');- else if (s === n) el.classList.add('active');- });- }- function show(view) {- ['view-form','view-waiting','view-success'].forEach(v => $(v).classList.toggle('hidden', v !== view));- }- function showError(msg) {- $('form-error-text').textContent = msg;- $('form-error').classList.remove('hidden');- }- function clearError() { $('form-error').classList.add('hidden'); }-- let pollTimer = null;- async function poll() {- try {- const r = await fetch('/api/status', { cache: 'no-store' });- const s = await r.json();- if (s.phase === 'enrolling') {- $('wait-msg').textContent = 'Contacting panel…';- } else if (s.phase === 'waiting') {- $('pair-code').textContent = s.pair_code_short || s.pair_code || '— — — — — —';- $('fingerprint').textContent = s.fingerprint || '—';- $('wait-msg').textContent = 'Waiting for the panel to claim this agent…';- setStep(2);- show('view-waiting');- } else if (s.phase === 'claimed') {- stopPoll();- if (s.server_name) {- $('success-name').textContent = '"' + s.server_name + '" is paired with the panel.';- }- setStep(3);- show('view-success');- } else if (s.phase === 'error') {- stopPoll();- showError(s.error || 'Pairing failed.');- $('submit-btn').disabled = false;- $('submit-btn').textContent = 'Try again';- setStep(1);- show('view-form');- }- } catch (e) { /* keep polling */ }- }- function startPoll() { if (!pollTimer) { poll(); pollTimer = setInterval(poll, 1500); } }- function stopPoll() { if (pollTimer) { clearInterval(pollTimer); pollTimer = null; } }-- $('submit-btn').addEventListener('click', async () => {- clearError();- const panel = $('panel').value.trim();- const pass = $('passphrase').value;- if (!panel) { showError('Panel URL is required.'); return; }- if (pass.length < 4) { showError('Passphrase must be at least 4 characters.'); return; }- $('submit-btn').disabled = true;- $('submit-btn').textContent = 'Connecting…';- try {- const r = await fetch('/api/start', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ panel_url: panel, passphrase: pass })- });- if (!r.ok) throw new Error((await r.text()) || 'Request failed');- setStep(2);- show('view-waiting');- startPoll();- } catch (err) {- showError(err.message);- $('submit-btn').disabled = false;- $('submit-btn').textContent = 'Begin pairing';- }- });-- $('cancel-btn').addEventListener('click', async () => {- await fetch('/api/cancel', { method: 'POST' });- stopPoll();- setStep(1);- show('view-form');- $('submit-btn').disabled = false;- $('submit-btn').textContent = 'Begin pairing';- });-- $('quit-btn').addEventListener('click', async () => {- await fetch('/api/close', { method: 'POST' });- });-- $('close-btn').addEventListener('click', async () => {- await fetch('/api/close', { method: 'POST' });- });-- startPoll();-</script>-</body>-</html>diff --git a/agent/internal/tray/icons/connected.ico b/agent/internal/tray/icons/connected.icoindex c388bd93..8d1b44a4 100644Binary files a/agent/internal/tray/icons/connected.ico and b/agent/internal/tray/icons/connected.ico differdiff --git a/agent/internal/tray/icons/disconnected.ico b/agent/internal/tray/icons/disconnected.icoindex c388bd93..6c21cc3d 100644Binary files a/agent/internal/tray/icons/disconnected.ico and b/agent/internal/tray/icons/disconnected.ico differdiff --git a/agent/internal/tray/icons/error.ico b/agent/internal/tray/icons/error.icoindex c388bd93..565eeab5 100644Binary files a/agent/internal/tray/icons/error.ico and b/agent/internal/tray/icons/error.ico differdiff --git a/agent/internal/tray/icons/stopped.ico b/agent/internal/tray/icons/stopped.icoindex c388bd93..435cb151 100644Binary files a/agent/internal/tray/icons/stopped.ico and b/agent/internal/tray/icons/stopped.ico differdiff --git a/agent/internal/tray/tray.go b/agent/internal/tray/tray.goindex 17967bc2..40750fa5 100644--- a/agent/internal/tray/tray.go+++ b/agent/internal/tray/tray.go@@ -8,6 +8,8 @@ import ("time""fyne.io/systray"++ "github.com/serverkit/agent/internal/config")// AppConfig holds tray app configuration@@ -18,6 +20,12 @@ type AppConfig struct {ServerURL stringDashboardURL stringLogFile string+ // NeedsSetup is set by runDesktop when the agent has no pairing config+ // yet. The tray shows a prominent "Open setup wizard…" item in that case+ // so the user can recover from a closed-without-pairing wizard window.+ NeedsSetup bool+ OnOpenSetup func()+ OnOpenLogs func()}// App is the system tray application@@ -34,16 +42,17 @@ type App struct {memPercent float64// Menu items- menuStatus *systray.MenuItem- menuCPU *systray.MenuItem- menuMem *systray.MenuItem- menuStartAgent *systray.MenuItem- menuStopAgent *systray.MenuItem+ menuSetup *systray.MenuItem+ menuStatus *systray.MenuItem+ menuCPU *systray.MenuItem+ menuMem *systray.MenuItem+ menuStartAgent *systray.MenuItem+ menuStopAgent *systray.MenuItemmenuRestartAgent *systray.MenuItem- menuViewLogs *systray.MenuItem- menuDashboard *systray.MenuItem- menuAbout *systray.MenuItem- menuQuit *systray.MenuItem+ menuViewLogs *systray.MenuItem+ menuDashboard *systray.MenuItem+ menuAbout *systray.MenuItem+ menuQuit *systray.MenuItem// Control channelsquitCh chan struct{}@@ -73,7 +82,14 @@ func (a *App) onReady() {// Set initial icon (gray/stopped)systray.SetIcon(GetIcon(IconStateStopped))systray.SetTitle("ServerKit")- systray.SetTooltip("ServerKit Agent - Checking...")+ systray.SetTooltip("ServerKit Agent")++ // Always create the setup item — its title flips between "Open setup+ // wizard…" (unconfigured) and "Re-pair this server…" (configured) based+ // on what refresh() observes. Putting it first means the user can always+ // reach pairing from the tray, which is the user-visible recovery surface.+ a.menuSetup = systray.AddMenuItem("Open setup wizard…", "Pair this server with a ServerKit panel")+ systray.AddSeparator()// Create menu itemsa.menuStatus = systray.AddMenuItem("Status: Checking...", "Agent status")@@ -135,6 +151,39 @@ func (a *App) refreshLoop() {}func (a *App) refresh() {+ // Re-load config every refresh so the tray picks up freshly-saved+ // credentials from a separate setup-wizard process the moment they+ // land. Cheap; the file is tiny.+ cfg, _ := config.Load("")+ configured := cfg != nil && cfg.Agent.ID != ""++ if a.menuSetup != nil {+ if configured {+ a.menuSetup.SetTitle("Re-pair this server…")+ a.menuSetup.SetTooltip("Replace the current pairing with a fresh one")+ } else {+ a.menuSetup.SetTitle("Open setup wizard…")+ a.menuSetup.SetTooltip("Pair this server with a ServerKit panel")+ }+ }++ if !configured {+ a.mu.Lock()+ defer a.mu.Unlock()+ a.agentRunning = false+ a.connected = false+ a.lastStatus = "Not configured"+ systray.SetIcon(GetIcon(IconStateStopped))+ systray.SetTooltip("ServerKit Agent - Setup required")+ a.menuStatus.SetTitle("Status: Not configured")+ a.menuCPU.SetTitle("CPU: --")+ a.menuMem.SetTitle("Memory: --")+ a.menuStartAgent.Disable()+ a.menuStopAgent.Disable()+ a.menuRestartAgent.Disable()+ return+ }+status, err := a.client.GetStatus()a.mu.Lock()@@ -199,6 +248,10 @@ func (a *App) handleMenuClicks() {select {case <-a.quitCh:return+ case <-a.menuSetup.ClickedCh:+ if a.config.OnOpenSetup != nil {+ a.config.OnOpenSetup()+ }case <-a.menuStartAgent.ClickedCh:a.startAgent()case <-a.menuStopAgent.ClickedCh:diff --git a/agent/packaging/icons/generate_icons.py b/agent/packaging/icons/generate_icons.pynew file mode 100644index 00000000..1c326dfb--- /dev/null+++ b/agent/packaging/icons/generate_icons.py@@ -0,0 +1,86 @@+"""Generate ServerKit icon set from the brand SVG.++Outputs:+ agent/internal/setupui/serverkit.ico — main app/installer icon (embedded into the exe)+ agent/internal/tray/icons/connected.ico — tray (full color)+ agent/internal/tray/icons/disconnected.ico — tray (yellow tint)+ agent/internal/tray/icons/error.ico — tray (red tint)+ agent/internal/tray/icons/stopped.ico — tray (gray)++Run from repo root:+ python agent/packaging/icons/generate_icons.py+"""+from __future__ import annotations++import io+from pathlib import Path++import cairosvg+from PIL import Image, ImageEnhance++REPO = Path(__file__).resolve().parents[3]+SVG = REPO / "frontend" / "src" / "assets" / "ServerKitLogo.svg"+SETUPUI_DIR = REPO / "agent" / "internal" / "setupui"+TRAY_DIR = REPO / "agent" / "internal" / "tray" / "icons"++SETUPUI_DIR.mkdir(parents=True, exist_ok=True)+TRAY_DIR.mkdir(parents=True, exist_ok=True)++APP_SIZES = [16, 24, 32, 48, 64, 128, 256]+TRAY_SIZES = [16, 24, 32, 48, 64]+++def render_png(size: int) -> Image.Image:+ png_bytes = cairosvg.svg2png(+ url=str(SVG), output_width=size, output_height=size+ )+ return Image.open(io.BytesIO(png_bytes)).convert("RGBA")+++def tint(img: Image.Image, rgb: tuple[int, int, int], strength: float = 0.65) -> Image.Image:+ """Apply a hue shift by blending non-transparent pixels toward `rgb`."""+ base = img.copy()+ overlay = Image.new("RGBA", base.size, rgb + (0,))+ alpha = base.split()[3]+ overlay.putalpha(alpha)+ blended = Image.blend(base, overlay, strength)+ blended.putalpha(alpha)+ return blended+++def desaturate(img: Image.Image) -> Image.Image:+ enhancer = ImageEnhance.Color(img)+ return enhancer.enhance(0.0)+++def write_ico(images: list[Image.Image], out: Path) -> None:+ primary = images[-1]+ primary.save(out, format="ICO", sizes=[(im.width, im.height) for im in images])+ print(f" wrote {out.relative_to(REPO)} ({len(images)} sizes)")+++def main() -> None:+ print("Rendering brand PNGs…")+ app_pngs = [render_png(s) for s in APP_SIZES]+ tray_pngs = [render_png(s) for s in TRAY_SIZES]++ print("Building serverkit.ico…")+ write_ico(app_pngs, SETUPUI_DIR / "serverkit.ico")++ print("Building wizard header PNG…")+ header = render_png(96)+ header_path = SETUPUI_DIR / "serverkit_header.png"+ header.save(header_path, format="PNG")+ print(f" wrote {header_path.relative_to(REPO)}")++ print("Building tray icons…")+ write_ico(tray_pngs, TRAY_DIR / "connected.ico")+ write_ico([tint(p, (245, 158, 11)) for p in tray_pngs], TRAY_DIR / "disconnected.ico")+ write_ico([tint(p, (220, 38, 38)) for p in tray_pngs], TRAY_DIR / "error.ico")+ write_ico([desaturate(p) for p in tray_pngs], TRAY_DIR / "stopped.ico")++ print("Done.")+++if __name__ == "__main__":+ main()diff --git a/agent/packaging/msi/Product.wxs b/agent/packaging/msi/Product.wxsindex ac82d60e..bc369dda 100644--- a/agent/packaging/msi/Product.wxs+++ b/agent/packaging/msi/Product.wxs@@ -22,6 +22,11 @@Keywords="ServerKit,Agent,Docker,Management"Manufacturer="ServerKit" />+ <!-- Branding: icon shown in Add/Remove Programs and on the install banner. -->+ <Icon Id="ServerKitAgentIco" SourceFile="serverkit.ico" />+ <Property Id="ARPPRODUCTICON" Value="ServerKitAgentIco" />+ <Property Id="ARPHELPLINK" Value="https://github.com/jhd3197/ServerKit" />+<!-- Upgrade handling --><MajorUpgradeDowngradeErrorMessage="A newer version of [ProductName] is already installed."@@ -95,33 +100,27 @@<RemoveFolder Id="RemoveAgentDataFolder" On="uninstall" /></Component>- <!-- Auto-start tray on user login (uses main binary with tray command) -->+ <!-- Auto-start the desktop app on user login. With no args, the binary+ opens the pairing wizard if not yet configured, otherwise just the tray. --><Component Id="TrayAutoStart" Directory="INSTALLFOLDER" Guid="E5F6A7B8-C9D0-1234-EF01-567890123456"><RegistryValueRoot="HKCU"Key="Software\Microsoft\Windows\CurrentVersion\Run"- Name="ServerKitTray"+ Name="ServerKitAgent"Type="string"- Value=""[INSTALLFOLDER]serverkit-agent.exe" tray"+ Value=""[INSTALLFOLDER]serverkit-agent.exe""KeyPath="yes" /></Component>- <!-- Start Menu shortcuts -->+ <!-- Start Menu shortcut: single entry that opens the desktop app. --><Component Id="StartMenuShortcuts" Directory="ServerKitStartMenuFolder" Guid="B7C8D9E0-F1A2-3456-7890-ABCDEF123456">- <Shortcut Id="SetupShortcut"- Name="ServerKit Agent Setup"- Description="Pair this server with a ServerKit panel"+ <Shortcut Id="AppShortcut"+ Name="ServerKit Agent"+ Description="Pair and manage this ServerKit Agent"Target="[INSTALLFOLDER]serverkit-agent.exe"- Arguments="setup"WorkingDirectory="INSTALLFOLDER"- Icon="ServerKitAgentIcon.exe"+ Icon="ServerKitAgentIco"IconIndex="0" />- <Shortcut Id="StatusShortcut"- Name="ServerKit Agent Status"- Description="Show ServerKit Agent connection status"- Target="[INSTALLFOLDER]serverkit-agent.exe"- Arguments="status"- WorkingDirectory="INSTALLFOLDER" /><RemoveFolder Id="RemoveStartMenuFolder" On="uninstall" /><RegistryValueRoot="HKCU"@@ -131,9 +130,22 @@Value="1"KeyPath="yes" /></Component>+ </Fragment>- <!-- Icon used for shortcut (reuses the agent exe's embedded icon) -->- <Icon Id="ServerKitAgentIcon.exe" SourceFile="serverkit-agent.exe" />+ <!-- Launch the desktop app at the end of installation so the user is taken+ straight into the pairing wizard. Impersonate so it inherits the user's+ session, not the elevated installer. -->+ <Fragment>+ <CustomAction Id="LaunchApp"+ FileRef="ServerKitAgentExe"+ ExeCommand=""+ Impersonate="yes"+ Return="asyncNoWait" />++ <InstallExecuteSequence>+ <Custom Action="LaunchApp" After="InstallFinalize"+ Condition="NOT Installed AND NOT REMOVE" />+ </InstallExecuteSequence></Fragment></Wix>diff --git a/agent/packaging/msi/build.ps1 b/agent/packaging/msi/build.ps1index f42d8f97..9b03ed98 100644--- a/agent/packaging/msi/build.ps1+++ b/agent/packaging/msi/build.ps1@@ -4,14 +4,17 @@param([string]$Version = "1.0.0",[string]$BinaryPath = "..\..\dist\serverkit-agent-windows-amd64.exe",- [string]$OutputDir = ".\output"+ [string]$OutputDir = ".\output",+ [ValidateSet("x64", "arm64")]+ [string]$Arch = "x64")$ErrorActionPreference = "Stop"Write-Host "Building MSI installer..."Write-Host " Version: $Version"-Write-Host " Binary: $BinaryPath"+Write-Host " Arch: $Arch"+Write-Host " Binary: $BinaryPath"# Check for WiX Toolset$wixPath = Get-Command wix -ErrorAction SilentlyContinue@@ -30,6 +33,14 @@ try {# Copy binaryCopy-Item $BinaryPath "$buildDir\serverkit-agent.exe"+ # Copy brand icon (used by the installer banner / Add-Remove Programs entry)+ $iconSource = Join-Path $PSScriptRoot "..\..\internal\setupui\serverkit.ico"+ if (-not (Test-Path $iconSource)) {+ Write-Host "Brand icon not found at $iconSource - run agent/packaging/icons/generate_icons.py first."+ exit 1+ }+ Copy-Item $iconSource "$buildDir\serverkit.ico"+# Create default config file$configContent = @"# ServerKit Agent Configuration@@ -113,7 +124,7 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\parPush-Location $buildDirtry {Write-Host "Running WiX build..."- wix build Product.wxs -o "$absOutputDir\serverkit-agent-$Version-x64.msi" -define Version=$Version+ wix build -arch $Arch Product.wxs -o "$absOutputDir\serverkit-agent-$Version-$Arch.msi" -define Version=$Version}finally {Pop-Location@@ -121,7 +132,7 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\parWrite-Host ""Write-Host "MSI built successfully!"- Write-Host "Output: $absOutputDir\serverkit-agent-$Version-x64.msi"+ Write-Host "Output: $absOutputDir\serverkit-agent-$Version-$Arch.msi"}finally {# Cleanupdiff --git a/frontend/src/styles/pages/_settings.scss b/frontend/src/styles/pages/_settings.scssindex 48d37c82..cab331ce 100644--- a/frontend/src/styles/pages/_settings.scss+++ b/frontend/src/styles/pages/_settings.scss@@ -69,6 +69,7 @@.settings-nav-item {display: flex;align-items: center;+ justify-content: flex-start;gap: $space-3;padding: $space-3 $space-4;background: transparent;