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 system tray app and IPC server to agent
Juan Denis4dbda1b09215
diff --git a/.github/workflows/agent-release.yml b/.github/workflows/agent-release.ymlindex 989aea09..e8881ea6 100644--- a/.github/workflows/agent-release.yml+++ b/.github/workflows/agent-release.yml@@ -60,7 +60,7 @@ jobs:CGO_ENABLED: 0run: |cd agent- go build -ldflags="-s -w -X main.Version=${{ steps.version.outputs.version }}" \+ go build -ldflags="-s -w -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@@ -366,6 +366,8 @@ jobs:|--------|--------------|----------|| MSI | x64 | `serverkit-agent-${{ steps.version.outputs.version }}-x64.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.+#### Docker```bashdocker pull jhd3197/serverkit-agent:${{ steps.version.outputs.version }}diff --git a/.gitignore b/.gitignoreindex 967714db..dea2a4b2 100644--- a/.gitignore+++ b/.gitignore@@ -1,11 +1,56 @@-/frontend/node_modules-nul-/.claude-/.claude_+# Dependencies+/frontend/node_modules/+/backend/venv/+/backend/__pycache__/+**/__pycache__/+*.pyc++# Build outputs+/frontend/dist/+/agent/dist/+/agent/serverkit-agent+/agent/serverkit-agent.exe+*.exe+*.msi+*.deb+*.rpm++# IDE and editors+.idea/+.vscode/+*.swp+*.swo+*~++# Environment and secrets.env-/frontend/dist+.env.local+.env.*.local+*.key+*.pem++# OS files+.DS_Store+Thumbs.db+nul++# Claude Code+/.claude/+/.claude_/++# Temporary files*.tmp-.planning_old+*.temp+*.log+coverage.out+coverage.html++# Project specific+.planning_old/.mcp.jsonnew_templates/-/.marketing+/.marketing/++# Test artifacts+*.test+*.outdiff --git a/EXPLORATIONS_AND_FUTURE.md b/EXPLORATIONS_AND_FUTURE.mdnew file mode 100644index 00000000..87a67c7e--- /dev/null+++ b/EXPLORATIONS_AND_FUTURE.md@@ -0,0 +1,672 @@+# ServerKit: Explorations and Future Directions++> A deep dive into where ServerKit stands, where it should go, and practical next steps.+>+> *Written: January 2026*++---++## Table of Contents++1. [Current State Assessment](#current-state-assessment)+2. [WordPress Dev/Prod Environment Architecture](#wordpress-devprod-environment-architecture)+3. [Testing the Go Agent Locally](#testing-the-go-agent-locally)+4. [Future of ServerKit](#future-of-serverkit)+5. [Recommended Next Steps](#recommended-next-steps)++---++## Current State Assessment++### What ServerKit Has Achieved++ServerKit has matured into a **legitimate self-hosted server control panel** with impressive breadth:++| Area | Maturity | Notes |+|------|----------|-------|+| **Multi-Server Agents** | Production-Ready | Go agent with WSS, HMAC auth, cross-platform builds |+| **Docker Management** | Complete | Full container lifecycle, compose support, logs streaming |+| **WordPress Support** | Good | WP-CLI, one-click install, security hardening |+| **Git Deployment** | Complete | Webhooks, rollback, zero-downtime deploys |+| **Security** | Strong | 2FA, encryption at rest, audit logging, ClamAV |+| **Monitoring** | Good | Real-time metrics, alerts, webhooks |+| **Multi-Environment** | Partial | UI exists, but workflow needs refinement |++### What's Missing for Real-World Usage++1. **Backup & Restore** - Critical gap. No automated backups = risky for production.+2. **Database Sync/Clone** - For dev/prod workflows, you need this.+3. **Team Permissions** - Single-user limits commercial viability.+4. **Agent Stress Testing** - No evidence of load testing at scale.++---++## WordPress Dev/Prod Environment Architecture++### The Vision++You want to explore:+- **Dev and Prod WordPress instances**+- **Synced from GitHub**+- **Sharing the same DB (or a mini version of prod DB)**++This is a real-world workflow that ServerKit should excel at. Let me break down the options:++### Option A: Shared Database (Live Sync)++```+┌─────────────────────────────────────────────────────────────┐+│ GitHub Repository │+│ (wp-content/themes, wp-content/plugins) │+└─────────────────────────────────────────────────────────────┘+ │+ ┌───────────────┴───────────────┐+ ▼ ▼+ ┌─────────────────┐ ┌─────────────────┐+ │ DEV Server │ │ PROD Server │+ │ (Agent #1) │ │ (Agent #2) │+ │ │ │ │+ │ ┌───────────┐ │ │ ┌───────────┐ │+ │ │ WordPress │ │ │ │ WordPress │ │+ │ │ (Dev) │ │ │ │ (Prod) │ │+ │ └─────┬─────┘ │ │ └─────┬─────┘ │+ └────────┼────────┘ └────────┼────────┘+ │ │+ └───────────┬───────────────────┘+ ▼+ ┌─────────────────┐+ │ Shared MySQL │+ │ (Prod Server) │+ │ │+ │ wp_* tables │+ └─────────────────┘+```++**Pros:**+- Real-time content sync+- No data drift between environments+- Simple conceptually++**Cons:**+- **Dangerous** - Dev changes affect prod data+- URL serialization issues in WordPress (siteurl, home options)+- Not recommended for real workflows++**Verdict:** Avoid this pattern. WordPress stores serialized URLs in the database, making true DB sharing problematic.++### Option B: Mini Prod Database (Recommended)++```+┌─────────────────────────────────────────────────────────────┐+│ GitHub Repository │+│ (wp-content/themes, wp-content/plugins) │+└─────────────────────────────────────────────────────────────┘+ │+ ┌───────────────┴───────────────┐+ ▼ ▼+ ┌─────────────────┐ ┌─────────────────┐+ │ DEV Server │ │ PROD Server │+ │ (Agent #1) │ │ (Agent #2) │+ │ │ │ │+ │ ┌───────────┐ │ │ ┌───────────┐ │+ │ │ WordPress │ │ │ │ WordPress │ │+ │ │ (Dev) │ │ │ │ (Prod) │ │+ │ └─────┬─────┘ │ │ └─────┬─────┘ │+ │ │ │ │ │ │+ │ ┌─────┴─────┐ │ │ ┌─────┴─────┐ │+ │ │ MySQL │ │◄────────────│ │ MySQL │ │+ │ │ (Clone) │ │ Nightly │ │ (Prod) │ │+ │ └───────────┘ │ Sync │ └───────────┘ │+ └─────────────────┘ └─────────────────┘+```++**How It Works:**++1. **Prod runs normally** with live database+2. **Nightly job** creates a mysqldump of prod+3. **Sanitize the dump:**+ - Run search-replace for URLs (`prod.example.com` → `dev.example.com`)+ - Optionally anonymize user data+ - Truncate large tables (logs, analytics)+4. **Import to dev** database+5. **Dev has fresh, realistic data** without affecting prod++**Implementation in ServerKit:**++This requires a new feature: **Database Sync Jobs**++```python+# Proposed: backend/app/services/db_sync_service.py++class DatabaseSyncService:+ def create_sync_job(self, source_app_id, target_app_id, options):+ """+ Create a scheduled database sync from source to target.++ Options:+ - schedule: cron expression+ - search_replace: dict of find/replace patterns+ - anonymize: bool - anonymize user emails/names+ - exclude_tables: list of tables to skip+ - truncate_tables: list of tables to empty+ """+ pass++ def run_sync(self, job_id):+ """Execute a database sync job."""+ # 1. Dump source database+ # 2. Apply transformations+ # 3. Import to target+ # 4. Run wp search-replace if WordPress+ pass+```++### Option C: Read Replica (Advanced)++```+ ┌─────────────────┐ ┌─────────────────┐+ │ DEV Server │ │ PROD Server │+ │ │ │ │+ │ ┌───────────┐ │ │ ┌───────────┐ │+ │ │ WordPress │ │ │ │ WordPress │ │+ │ └─────┬─────┘ │ │ └─────┬─────┘ │+ │ │ │ │ │ │+ │ ┌─────┴─────┐ │ │ ┌─────┴─────┐ │+ │ │ MySQL │ │ │ │ MySQL │ │+ │ │ (Replica) │◄─┼─────────────┼──│ (Primary) │ │+ │ └───────────┘ │ Binlog │ └───────────┘ │+ └─────────────────┘ Replication └─────────────────┘+```++**Pros:**+- Near real-time sync (seconds)+- Dev sees exactly what prod sees++**Cons:**+- Read-only dev database+- Complex to set up cross-server+- Still has URL serialization issues++**Verdict:** Overkill for WordPress. Better for read-heavy APIs.++### Recommended Architecture: GitHub-Driven Dev/Prod++Here's what I'd actually build:++```+┌─────────────────────────────────────────────────────────────┐+│ GitHub Repository │+│ │+│ ├── wp-content/ │+│ │ ├── themes/my-theme/ │+│ │ └── plugins/my-plugin/ │+│ ├── .github/workflows/ │+│ │ ├── deploy-dev.yml # On push to develop branch │+│ │ └── deploy-prod.yml # On push to main branch │+│ └── serverkit.yaml # Environment config │+└─────────────────────────────────────────────────────────────┘+ │+ ┌────────────────────┴────────────────────┐+ │ │+ │ push to develop push to main │+ ▼ ▼+┌─────────────────┐ ┌─────────────────┐+│ ServerKit API │ │ ServerKit API │+│ (Webhook) │ │ (Webhook) │+└────────┬────────┘ └────────┬────────┘+ │ │+ ▼ ▼+┌─────────────────┐ ┌─────────────────┐+│ DEV Server │ │ PROD Server │+│ │ │ │+│ WordPress │ │ WordPress │+│ dev.site.com │ │ www.site.com │+│ │ │ │+│ MySQL (local) │◄────── Weekly ──────│ MySQL (local) │+│ Sanitized copy │ Sync │ Live data │+└─────────────────┘ └─────────────────┘+```++**The Workflow:**++1. **Developer pushes to `develop` branch**+2. **GitHub Action** calls ServerKit webhook+3. **ServerKit pulls code** on dev server+4. **Runs `wp theme activate`, `wp plugin activate`** as needed+5. **Developer tests on dev.site.com**+6. **When ready, merge PR to `main`**+7. **Same process for production**++**Weekly Database Sync:**++```yaml+# serverkit.yaml in repo root+environments:+ dev:+ server: dev-server-id+ app: wordpress-dev-id+ domain: dev.site.com+ db_sync:+ source: prod+ schedule: "0 3 * * 0" # Sunday 3 AM+ search_replace:+ - ["https://www.site.com", "https://dev.site.com"]+ anonymize_users: true+ truncate_tables:+ - wp_statistics_*+ - wp_actionscheduler_*++ prod:+ server: prod-server-id+ app: wordpress-prod-id+ domain: www.site.com+```++### What ServerKit Needs to Support This++| Feature | Current Status | Priority |+|---------|---------------|----------|+| Git webhook deployments | ✅ Done | - |+| Multi-environment app linking | ✅ Done | - |+| Database dump/export | ❌ Missing | **High** |+| Database import with transformations | ❌ Missing | **High** |+| WP-CLI search-replace integration | ⚠️ Partial | Medium |+| Scheduled sync jobs | ❌ Missing | Medium |+| Cross-server database operations | ❌ Missing | Medium |++---++## Testing the Go Agent Locally++### Your Goal++Test the ServerKit Go agent on your Windows PC to understand:+- How it connects to the control plane+- How commands flow through+- What happens with Docker operations+- Whether it's stable++### Setting Up the Test Environment++#### Prerequisites++1. **Go 1.21+** installed+2. **Docker Desktop** running (for Docker commands)+3. **ServerKit backend** running (localhost or remote)++#### Step 1: Build the Agent++```powershell+# Navigate to agent directory+cd C:\Users\Juan\Documents\GitHub\ServerKit\agent++# Build for Windows+go build -o serverkit-agent.exe ./cmd/agent++# Or use the Makefile (if you have make installed)+make build-windows+```++#### Step 2: Create Test Configuration++Create `agent-config.yaml` in the agent directory:++```yaml+# agent-config.yaml+server_url: "ws://localhost:5000" # Your ServerKit backend+# server_url: "wss://serverkit.yourdomain.com" # For production++# Leave empty - will be populated on first registration+api_key: ""+api_secret: ""++# Logging+log_level: "debug"+log_file: "agent.log"++# Heartbeat interval (seconds)+heartbeat_interval: 30++# Enable Docker integration+docker_enabled: true+docker_socket: "npipe:////./pipe/docker_engine" # Windows Docker socket+```++#### Step 3: Register the Agent++First, create a server in ServerKit UI to get a registration token, then:++```powershell+# Register with the control plane+.\serverkit-agent.exe register --token YOUR_REGISTRATION_TOKEN++# This will:+# 1. Connect to ServerKit backend+# 2. Exchange token for API credentials+# 3. Save credentials to config file+# 4. Print success message+```++#### Step 4: Run the Agent++```powershell+# Run in foreground (for testing)+.\serverkit-agent.exe run --config agent-config.yaml++# You should see:+# [INFO] Connecting to ws://localhost:5000/agent+# [INFO] Authenticated successfully+# [INFO] Starting heartbeat loop (30s interval)+# [DEBUG] Sending heartbeat with metrics...+```++### Testing Agent Functionality++#### Test 1: Verify Connection++In ServerKit UI:+- Go to Servers page+- Your test server should show as "Online"+- Last seen should update every 30 seconds++#### Test 2: Docker Commands++If Docker Desktop is running:++```powershell+# In ServerKit UI, try:+# - View containers+# - Start/stop a container+# - View container logs++# Agent logs should show:+# [DEBUG] Received command: docker:container:list+# [DEBUG] Executing Docker command...+# [DEBUG] Sending response with 5 containers+```++#### Test 3: System Metrics++Check Monitoring page in ServerKit:+- CPU usage should show Windows Task Manager equivalent+- Memory should match your system+- Disk usage for C: drive++#### Test 4: Terminal Access++Try opening a terminal session to your test server:+- Should spawn PowerShell on Windows+- Commands should execute+- Output should stream back++### Common Issues and Fixes++| Issue | Cause | Fix |+|-------|-------|-----|+| "Connection refused" | Backend not running | Start Flask backend |+| "Docker not available" | Docker Desktop not running | Start Docker Desktop |+| "Authentication failed" | Invalid/expired token | Re-register agent |+| "TLS handshake error" | Self-signed cert | Use `ws://` for local testing |+| Metrics not updating | Heartbeat blocked | Check firewall rules |++### Agent Architecture Deep Dive++```+┌─────────────────────────────────────────────────────────────┐+│ ServerKit Go Agent │+├─────────────────────────────────────────────────────────────┤+│ │+│ ┌───────────┐ ┌───────────┐ ┌───────────┐ │+│ │ Config │ │ Logger │ │ Auth │ │+│ │ Manager │ │ (Zerolog) │ │ (HMAC) │ │+│ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ │+│ │ │ │ │+│ └──────────────┼──────────────┘ │+│ │ │+│ ┌────────────────────┴────────────────────┐ │+│ │ WebSocket Client │ │+│ │ (gorilla/websocket + reconnect) │ │+│ └────────────────────┬────────────────────┘ │+│ │ │+│ ┌──────────────┼──────────────┐ │+│ │ │ │ │+│ ▼ ▼ ▼ │+│ ┌───────────┐ ┌───────────┐ ┌───────────┐ │+│ │ Docker │ │ Metrics │ │ Terminal │ │+│ │ Handler │ │ Collector │ │ PTY │ │+│ │ │ │ │ │ │ │+│ │ - List │ │ - CPU │ │ - Spawn │ │+│ │ - Start │ │ - Memory │ │ - Resize │ │+│ │ - Stop │ │ - Disk │ │ - Input │ │+│ │ - Logs │ │ - Network │ │ - Output │ │+│ │ - Stats │ │ │ │ │ │+│ └───────────┘ └───────────┘ └───────────┘ │+│ │+└─────────────────────────────────────────────────────────────┘+```++### Agent Test Checklist++- [ ] Agent builds without errors+- [ ] Agent connects to backend+- [ ] Heartbeat appears in server list+- [ ] Metrics show in monitoring page+- [ ] Docker containers list correctly+- [ ] Container start/stop works+- [ ] Container logs stream+- [ ] Terminal opens and accepts input+- [ ] Agent survives backend restart (reconnect)+- [ ] Agent handles network interruption gracefully++---++## Future of ServerKit++### My Honest Assessment++ServerKit has grown from a simple control panel into something with real architectural depth. The Go agent is a significant investment that positions it for multi-server, enterprise-like features. But there are strategic decisions ahead.++### Where ServerKit Sits in the Market++```+ Complexity+ ▲+ │+ Kubernetes ────┼──────────────● CloudPanel+ Nomad │ ● Coolify+ │ ● ServerKit (today)+ │ ● Dokku+ │ ● CapRover+ ────────────────────────────────────────► Features+ │+ Portainer ●+ │+ Cockpit ● │+ │+```++**Current Position:** ServerKit is between CapRover/Dokku (simple) and CloudPanel/Coolify (feature-rich).++**Opportunity:** The multi-server Go agent puts ServerKit closer to what teams actually need for real production workloads.++### Three Possible Futures++#### Future A: WordPress Hosting Platform++**Focus:** Become the best self-hosted WordPress management platform.++**What to build:**+- Staging/production sync (database cloning)+- WordPress-specific monitoring (slow queries, plugin conflicts)+- One-click backup to S3/Backblaze+- Malware scanning with auto-remediation+- WordPress multisite support+- WP-CLI exposed as API++**Target users:** WordPress agencies, freelancers with multiple client sites++**Competitors:** GridPane, SpinupWP, RunCloud++**My take:** This is a viable niche. WordPress agencies pay well for good tooling. But it limits ServerKit's appeal.++#### Future B: Mini-Kubernetes Alternative++**Focus:** Multi-server orchestration without Kubernetes complexity.++**What to build:**+- Service mesh between agents (internal DNS)+- Load balancing across servers+- Container scheduling (deploy to least-loaded server)+- Cross-server networking+- Secrets management (Vault-like)+- Log aggregation (ship logs to central location)++**Target users:** Small-medium teams who outgrew single servers but don't want Kubernetes++**Competitors:** Nomad, Docker Swarm (dead), Coolify++**My take:** This is the more ambitious path. The Go agent is already 70% of what's needed. The question is whether you want to compete at this level.++#### Future C: Developer-First Homelab Manager++**Focus:** Self-hosting for developers who want to own their infrastructure.++**What to build:**+- One-click apps (like Umbrel, CasaOS)+- Personal cloud features (Nextcloud, Vaultwarden integration)+- Tunnel support (Cloudflare Tunnel, Tailscale)+- Mobile-friendly dashboard+- Simple DNS management+- Local SSL with mkcert/step-ca++**Target users:** Developers, homelabbers, privacy-conscious users++**Competitors:** Umbrel, CasaOS, Tipi++**My take:** Growing market, but harder to monetize. Good for adoption, hard for revenue.++### My Recommendation: Hybrid Approach++Don't pick one future. Build the **foundation** that supports all three:++```+ ┌─────────────────────────────────┐+ │ User-Facing Products │+ ├─────────┬───────────┬───────────┤+ │WordPress│ App │ Homelab │+ │Platform │ Platform │ Suite │+ ├─────────┴───────────┴───────────┤+ │ ServerKit Core Platform │+ │ │+ │ ┌─────┐ ┌─────┐ ┌───────────┐ │+ │ │Agents│ │Apps │ │ Templates │ │+ │ └─────┘ └─────┘ └───────────┘ │+ │ ┌─────┐ ┌─────┐ ┌───────────┐ │+ │ │ DB │ │ SSL │ │ Webhooks │ │+ │ └─────┘ └─────┘ └───────────┘ │+ └─────────────────────────────────┘+```++**Core investments that pay off in all futures:**++1. **Backup & Restore** - Everyone needs this+2. **Database Sync** - Dev/prod workflows are universal+3. **API Stability** - Third-party integrations+4. **Agent Reliability** - More agents = more value+5. **Plugin/Extension System** - Let community build++### Roadmap Recommendation++#### Q1 2026: Foundation (Now)++| Priority | Feature | Why |+|----------|---------|-----|+| **P0** | Backup & Restore | Can't run production without backups |+| **P0** | Database sync/clone | Enables dev/prod workflows |+| **P1** | Agent stress testing | Prove multi-server works at scale |+| **P1** | WordPress staging sync | Popular request, differentiator |++#### Q2 2026: Scale++| Priority | Feature | Why |+|----------|---------|-----|+| **P0** | Team/user management | Required for teams |+| **P1** | Role-based permissions | Security requirement |+| **P1** | Cross-server log aggregation | Ops visibility |+| **P2** | Agent auto-update (production-grade) | Reduce maintenance burden |++#### Q3 2026: Ecosystem++| Priority | Feature | Why |+|----------|---------|-----|+| **P1** | Plugin/extension system | Community growth |+| **P1** | API v2 (stable, versioned) | Third-party integrations |+| **P2** | Template marketplace | Discoverability |+| **P2** | Tunnel support (Cloudflare/Tailscale) | Homelab market |++#### Q4 2026: Differentiation++Choose a direction based on traction:+- If WordPress is hot → WordPress-specific features+- If multi-server is hot → Orchestration features+- If homelab is hot → Personal cloud features++---++## Recommended Next Steps++### Immediate (This Week)++1. **Build and test the Go agent locally**+ - Follow the steps in Section 3+ - Document any issues you find+ - Test Docker commands specifically++2. **Prototype database sync**+ - Manual mysqldump → transform → import+ - Use WP-CLI for search-replace+ - Prove the workflow works before automating++3. **Set up a real dev/prod WordPress pair**+ - Two Docker instances on same machine+ - Different ports, different databases+ - Test the GitHub webhook flow++### Short-term (This Month)++4. **Design the Database Sync feature**+ - UI mockups+ - API design+ - Agent-side implementation++5. **Backup & Restore MVP**+ - Even if manual (cron + mysqldump + rsync)+ - Restore must actually work++### Medium-term (This Quarter)++6. **Agent reliability improvements**+ - Reconnection logic stress testing+ - Memory leak detection+ - Long-running connection stability++7. **Documentation**+ - Agent installation guide+ - Multi-server setup tutorial+ - WordPress dev/prod workflow guide++---++## Final Thoughts++ServerKit has the bones of something really useful. The Go agent is the right architectural choice for multi-server. The template system is flexible. The security features are more thorough than most open-source panels.++The risk is feature sprawl - trying to be everything to everyone. The WordPress dev/prod workflow you want to explore is exactly the kind of **focused, real-world problem** that differentiates ServerKit from generic panels.++Build for your own use case first. If you need WordPress staging with database sync, build that. You'll end up with something opinionated and useful rather than generic and forgettable.++The market doesn't need another cPanel clone. It needs tools built by people who actually deploy and manage servers.++---++*This document represents my analysis based on exploring the ServerKit codebase. These are recommendations, not requirements. Adjust based on your priorities and user feedback.*diff --git a/agent/Makefile b/agent/Makefileindex 9ef23088..7926298f 100644--- a/agent/Makefile+++ b/agent/Makefile@@ -9,6 +9,10 @@ LDFLAGS := -s -w \-X main.BuildTime=$(BUILD_TIME) \-X main.GitCommit=$(GIT_COMMIT)+# Agent-specific LDFLAGS (includes agent package version var)+AGENT_LDFLAGS := $(LDFLAGS) \+ -X github.com/serverkit/agent/internal/agent.Version=$(VERSION)+BINARY_NAME := serverkit-agentDIST_DIR := dist@@ -23,7 +27,7 @@ deps:# Build for current platformbuild:- CGO_ENABLED=0 go build -ldflags "$(LDFLAGS)" -o $(BINARY_NAME) ./cmd/agent+ CGO_ENABLED=0 go build -ldflags "$(AGENT_LDFLAGS)" -o $(BINARY_NAME) ./cmd/agent# Build for current platform with debug symbolsdev:@@ -37,29 +41,29 @@ run: buildbuild-all:@mkdir -p $(DIST_DIR)@echo "Building for Linux amd64..."- CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-linux-amd64 ./cmd/agent+ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-linux-amd64 ./cmd/agent@echo "Building for Linux arm64..."- CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-linux-arm64 ./cmd/agent+ 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 "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-windows-amd64.exe ./cmd/agent+ CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "$(AGENT_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 "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-windows-arm64.exe ./cmd/agent+ CGO_ENABLED=0 GOOS=windows GOARCH=arm64 go build -ldflags "$(AGENT_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 "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-darwin-amd64 ./cmd/agent+ 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..."- CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-darwin-arm64 ./cmd/agent+ CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-darwin-arm64 ./cmd/agent@echo "Done! Binaries in $(DIST_DIR)/"# Build Linux onlybuild-linux:@mkdir -p $(DIST_DIR)- CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-linux-amd64 ./cmd/agent- CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-linux-arm64 ./cmd/agent+ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-linux-amd64 ./cmd/agent+ CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-linux-arm64 ./cmd/agent# Build Windows onlybuild-windows:@mkdir -p $(DIST_DIR)- CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-windows-amd64.exe ./cmd/agent+ CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-windows-amd64.exe ./cmd/agent# Run teststest:@@ -150,3 +154,6 @@ help:@echo " docker-buildx Build multi-arch image (amd64, arm64)"@echo ""@echo " help Show this help"+ @echo ""+ @echo "Note: The agent includes a built-in tray command."+ @echo " Run 'serverkit-agent tray' for system tray mode."diff --git a/agent/agent.exe b/agent/agent.exedeleted file mode 100644index 7fce245a..00000000Binary files a/agent/agent.exe and /dev/null differdiff --git a/agent/cmd/agent/main.go b/agent/cmd/agent/main.goindex bca0d016..2129e0e5 100644--- a/agent/cmd/agent/main.go+++ b/agent/cmd/agent/main.go@@ -10,6 +10,7 @@ import ("github.com/serverkit/agent/internal/agent""github.com/serverkit/agent/internal/config""github.com/serverkit/agent/internal/logger"+ "github.com/serverkit/agent/internal/tray""github.com/serverkit/agent/internal/updater""github.com/spf13/cobra")@@ -44,6 +45,7 @@ enabling remote Docker management, monitoring, and more.`,rootCmd.AddCommand(versionCmd())rootCmd.AddCommand(configCmd())rootCmd.AddCommand(updateCmd())+ rootCmd.AddCommand(trayCmd())if err := rootCmd.Execute(); err != nil {fmt.Fprintln(os.Stderr, err)@@ -355,3 +357,73 @@ func showStatus() error {return nil}++func trayCmd() *cobra.Command {+ return &cobra.Command{+ Use: "tray",+ Short: "Run the system tray application",+ Long: `Start the ServerKit Agent system tray application.++The tray app shows the agent status in the system tray and provides+quick access to start/stop the service, view logs, and open the dashboard.++This is typically auto-started on Windows login when installed via MSI.`,+ RunE: func(cmd *cobra.Command, args []string) error {+ return runTray()+ },+ }+}++func runTray() error {+ // Load agent config to get server URL and IPC settings+ cfg, err := config.Load(cfgFile)+ if err != nil {+ // Continue without config - tray can still show status+ cfg = config.Default()+ }++ // Create and run tray application+ app := tray.NewApp(tray.AppConfig{+ Version: Version,+ IPCAddress: cfg.IPC.Address,+ IPCPort: cfg.IPC.Port,+ ServerURL: cfg.Server.URL,+ DashboardURL: getDashboardURL(cfg.Server.URL),+ LogFile: cfg.Logging.File,+ })++ // Handle signals for graceful shutdown+ sigCh := make(chan os.Signal, 1)+ signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)++ go func() {+ <-sigCh+ app.Quit()+ }()++ // Run the tray app (blocking)+ app.Run()+ return nil+}++func getDashboardURL(serverURL string) string {+ // Convert WebSocket URL to HTTP dashboard URL+ // wss://server.example.com/ws/agent -> https://server.example.com+ if serverURL == "" {+ return ""+ }+ // Simple conversion - strip /ws/agent suffix and convert wss to https+ url := serverURL+ if len(url) > 4 && url[:4] == "wss:" {+ url = "https:" + url[4:]+ } else if len(url) > 3 && url[:3] == "ws:" {+ url = "http:" + url[3:]+ }+ // Strip path suffix+ for i := len(url) - 1; i >= 0; i-- {+ if url[i] == '/' && i > 8 { // After https://+ return url[:i]+ }+ }+ return url+}diff --git a/agent/go.mod b/agent/go.modindex 9bd057c9..77af4156 100644--- a/agent/go.mod+++ b/agent/go.mod@@ -3,6 +3,7 @@ module github.com/serverkit/agentgo 1.21require (+ fyne.io/systray v1.11.0github.com/creack/pty v1.1.21github.com/docker/docker v24.0.7+incompatiblegithub.com/gorilla/websocket v1.5.1@@ -19,6 +20,7 @@ require (github.com/docker/go-connections v0.4.0 // indirectgithub.com/docker/go-units v0.5.0 // indirectgithub.com/go-ole/go-ole v1.3.0 // indirect+ github.com/godbus/dbus/v5 v5.1.0 // indirectgithub.com/gogo/protobuf v1.3.2 // indirectgithub.com/inconshreveable/mousetrap v1.1.0 // indirectgithub.com/lufia/plan9stats v0.0.0-20231016141302-07b5767bb0ed // indirectdiff --git a/agent/go.sum b/agent/go.sumindex 30a2141c..beaeb7c6 100644--- a/agent/go.sum+++ b/agent/go.sum@@ -1,3 +1,5 @@+fyne.io/systray v1.11.0 h1:D9HISlxSkx+jHSniMBR6fCFOUjk1x/OOOJLa9lJYAKg=+fyne.io/systray v1.11.0/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs=github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8=github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow=@@ -21,6 +23,8 @@ github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDgithub.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=+github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=+github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.goindex 9e032ddc..78b85ba0 100644--- a/agent/internal/agent/agent.go+++ b/agent/internal/agent/agent.go@@ -1,16 +1,19 @@package agentimport (+ "bufio""context""encoding/base64""encoding/json""fmt"+ "os""sync""time""github.com/serverkit/agent/internal/auth""github.com/serverkit/agent/internal/config""github.com/serverkit/agent/internal/docker"+ "github.com/serverkit/agent/internal/ipc""github.com/serverkit/agent/internal/logger""github.com/serverkit/agent/internal/metrics""github.com/serverkit/agent/internal/terminal"@@ -27,6 +30,7 @@ type Agent struct {docker *docker.Clientmetrics *metrics.Collectorterminal *terminal.Manager+ ipc *ipc.Server// Active subscriptionssubscriptions map[string]context.CancelFunc@@ -34,6 +38,12 @@ type Agent struct {// Command handlershandlers map[string]CommandHandler++ // Lifecycle tracking+ startTime time.Time+ restartCh chan struct{}+ lastConnected time.Time+ reconnectCount int}// CommandHandler is a function that handles a command@@ -81,6 +91,8 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {terminal: termManager,subscriptions: make(map[string]context.CancelFunc),handlers: make(map[string]CommandHandler),+ startTime: time.Now(),+ restartCh: make(chan struct{}),}// Register command handlers@@ -89,6 +101,11 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {// Set WebSocket message handlerwsClient.SetHandler(agent.handleMessage)+ // Create IPC server if enabled+ if cfg.IPC.Enabled {+ agent.ipc = ipc.NewServer(cfg.IPC, log, agent)+ }+return agent, nil}@@ -147,7 +164,8 @@ func (a *Agent) registerHandlers() {func (a *Agent) Run(ctx context.Context) error {a.log.Info("Starting agent","agent_id", a.cfg.Agent.ID,- "features", fmt.Sprintf("docker=%v metrics=%v", a.cfg.Features.Docker, a.cfg.Features.Metrics),+ "version", Version,+ "features", fmt.Sprintf("docker=%v metrics=%v ipc=%v", a.cfg.Features.Docker, a.cfg.Features.Metrics, a.cfg.IPC.Enabled),)// Verify Docker connection if enabled@@ -160,6 +178,13 @@ func (a *Agent) Run(ctx context.Context) error {}}+ // Start IPC server if enabled+ if a.ipc != nil {+ if err := a.ipc.Start(ctx); err != nil {+ a.log.Warn("Failed to start IPC server", "error", err)+ }+ }+// Start WebSocket connection in backgroundgo func() {if err := a.ws.Run(ctx); err != nil && err != context.Canceled {@@ -170,8 +195,12 @@ func (a *Agent) Run(ctx context.Context) error {// Start heartbeat loopgo a.heartbeatLoop(ctx)- // Wait for context cancellation- <-ctx.Done()+ // Wait for context cancellation or restart request+ select {+ case <-ctx.Done():+ case <-a.restartCh:+ a.log.Info("Restart requested")+ }// Cleanupa.cleanup()@@ -436,6 +465,11 @@ func (a *Agent) cleanup() {a.terminal.CloseAll()}+ // Stop IPC server+ if a.ipc != nil {+ a.ipc.Stop()+ }+// Close WebSocketa.ws.Close()@@ -927,3 +961,136 @@ func (a *Agent) handleTerminalClose(ctx context.Context, params json.RawMessage)"success": true,}, nil}++// IPC StatusProvider implementation++// GetStatus returns the current agent status for the IPC API+func (a *Agent) GetStatus() ipc.AgentStatus {+ status := ipc.AgentStatus{+ Running: true,+ Connected: a.ws.IsConnected(),+ Registered: a.cfg.Agent.ID != "",+ AgentID: a.cfg.Agent.ID,+ AgentName: a.cfg.Agent.Name,+ ServerURL: a.cfg.Server.URL,+ Uptime: int64(time.Since(a.startTime).Seconds()),+ Version: Version,+ }++ // Collect current metrics if available+ if a.metrics != nil {+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()+ if sysMetrics, err := a.metrics.Collect(ctx); err == nil {+ status.CPUPercent = sysMetrics.CPUPercent+ status.MemPercent = sysMetrics.MemoryPercent+ status.DiskPercent = sysMetrics.DiskPercent+ }+ }++ return status+}++// GetDetailedMetrics returns detailed system metrics for the IPC API+func (a *Agent) GetDetailedMetrics() *ipc.DetailedMetrics {+ if a.metrics == nil {+ return nil+ }++ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()++ sysMetrics, err := a.metrics.Collect(ctx)+ if err != nil {+ return nil+ }++ cores := 0+ if sysMetrics.CPUPerCore != nil {+ cores = len(sysMetrics.CPUPerCore)+ }++ return &ipc.DetailedMetrics{+ CPU: ipc.CPUMetrics{+ UsagePercent: sysMetrics.CPUPercent,+ PerCPU: sysMetrics.CPUPerCore,+ Cores: cores,+ },+ Memory: ipc.MemoryMetrics{+ Total: sysMetrics.MemoryTotal,+ Used: sysMetrics.MemoryUsed,+ Free: sysMetrics.MemoryTotal - sysMetrics.MemoryUsed,+ UsagePercent: sysMetrics.MemoryPercent,+ },+ Disk: ipc.DiskMetrics{+ Total: sysMetrics.DiskTotal,+ Used: sysMetrics.DiskUsed,+ Free: sysMetrics.DiskTotal - sysMetrics.DiskUsed,+ UsagePercent: sysMetrics.DiskPercent,+ },+ Network: ipc.NetworkMetrics{+ BytesSent: sysMetrics.NetworkTx,+ BytesRecv: sysMetrics.NetworkRx,+ PacketsSent: 0, // Not tracked in current implementation+ PacketsRecv: 0, // Not tracked in current implementation+ },+ Timestamp: time.Now().UnixMilli(),+ }+}++// GetConnectionInfo returns WebSocket connection information for the IPC API+func (a *Agent) GetConnectionInfo() ipc.ConnectionInfo {+ info := ipc.ConnectionInfo{+ Connected: a.ws.IsConnected(),+ ServerURL: a.cfg.Server.URL,+ ReconnectCount: a.reconnectCount,+ }++ if !a.lastConnected.IsZero() {+ info.LastConnected = a.lastConnected.UnixMilli()+ }++ if session := a.ws.Session(); session != nil {+ info.SessionExpires = session.ExpiresAt.UnixMilli()+ }++ return info+}++// GetRecentLogs returns recent log lines from the log file+func (a *Agent) GetRecentLogs(lines int) []string {+ logFile := a.cfg.Logging.File+ if logFile == "" {+ return []string{}+ }++ file, err := os.Open(logFile)+ if err != nil {+ return []string{}+ }+ defer file.Close()++ // Read all lines and keep the last N+ var allLines []string+ scanner := bufio.NewScanner(file)+ for scanner.Scan() {+ allLines = append(allLines, scanner.Text())+ }++ // Return the last N lines+ if len(allLines) <= lines {+ return allLines+ }+ return allLines[len(allLines)-lines:]+}++// Restart initiates a graceful restart of the agent+func (a *Agent) Restart() error {+ a.log.Info("Restart requested via IPC")+ select {+ case a.restartCh <- struct{}{}:+ return nil+ default:+ return fmt.Errorf("restart already in progress")+ }+}diff --git a/agent/internal/config/config.go b/agent/internal/config/config.goindex b1455718..bb6ef6bf 100644--- a/agent/internal/config/config.go+++ b/agent/internal/config/config.go@@ -27,6 +27,7 @@ type Config struct {Security SecurityConfig `yaml:"security"`Logging LoggingConfig `yaml:"logging"`Update UpdateConfig `yaml:"update"`+ IPC IPCConfig `yaml:"ipc"`}// ServerConfig holds connection settings@@ -98,6 +99,13 @@ type UpdateConfig struct {AutoInstall bool `yaml:"auto_install"`}+// IPCConfig holds local IPC server settings for tray app communication+type IPCConfig struct {+ Enabled bool `yaml:"enabled"`+ Port int `yaml:"port"`+ Address string `yaml:"address"`+}+// Default returns default configurationfunc Default() *Config {return &Config{@@ -145,6 +153,11 @@ func Default() *Config {CheckInterval: 1 * time.Hour,AutoInstall: false, // Require manual confirmation by default},+ IPC: IPCConfig{+ Enabled: true,+ Port: 19780,+ Address: "127.0.0.1",+ },}}diff --git a/agent/internal/ipc/handlers.go b/agent/internal/ipc/handlers.gonew file mode 100644index 00000000..c01bac6e--- /dev/null+++ b/agent/internal/ipc/handlers.go@@ -0,0 +1,128 @@+package ipc++import (+ "encoding/json"+ "net/http"+ "strconv"++ "github.com/serverkit/agent/internal/logger"+)++// Handlers contains the HTTP handlers for the IPC API+type Handlers struct {+ provider StatusProvider+ log *logger.Logger+}++// NewHandlers creates a new handlers instance+func NewHandlers(provider StatusProvider, log *logger.Logger) *Handlers {+ return &Handlers{+ provider: provider,+ log: log,+ }+}++// HandleStatus returns the current agent status+func (h *Handlers) HandleStatus(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ status := h.provider.GetStatus()+ h.writeJSON(w, status)+}++// HandleMetrics returns detailed system metrics+func (h *Handlers) HandleMetrics(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ metrics := h.provider.GetDetailedMetrics()+ if metrics == nil {+ h.writeJSON(w, map[string]string{"error": "metrics not available"})+ return+ }++ h.writeJSON(w, metrics)+}++// HandleConnection returns WebSocket connection information+func (h *Handlers) HandleConnection(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ info := h.provider.GetConnectionInfo()+ h.writeJSON(w, info)+}++// HandleLogs returns recent log lines+func (h *Handlers) HandleLogs(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ // Parse lines parameter (default 50)+ lines := 50+ if l := r.URL.Query().Get("lines"); l != "" {+ if parsed, err := strconv.Atoi(l); err == nil && parsed > 0 && parsed <= 1000 {+ lines = parsed+ }+ }++ logs := h.provider.GetRecentLogs(lines)+ h.writeJSON(w, map[string]interface{}{+ "lines": logs,+ "count": len(logs),+ })+}++// HandleRestart triggers a graceful agent restart+func (h *Handlers) HandleRestart(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ h.log.Info("Restart requested via IPC")++ if err := h.provider.Restart(); err != nil {+ h.writeJSON(w, map[string]interface{}{+ "success": false,+ "error": err.Error(),+ })+ return+ }++ h.writeJSON(w, map[string]interface{}{+ "success": true,+ "message": "Restart initiated",+ })+}++// HandleHealth returns a simple health check response+func (h *Handlers) HandleHealth(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ status := h.provider.GetStatus()+ h.writeJSON(w, map[string]interface{}{+ "healthy": status.Running,+ "connected": status.Connected,+ })+}++// writeJSON writes a JSON response+func (h *Handlers) writeJSON(w http.ResponseWriter, data interface{}) {+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(data); err != nil {+ h.log.Warn("Failed to encode JSON response", "error", err)+ }+}diff --git a/agent/internal/ipc/server.go b/agent/internal/ipc/server.gonew file mode 100644index 00000000..bd1d1970--- /dev/null+++ b/agent/internal/ipc/server.go@@ -0,0 +1,212 @@+package ipc++import (+ "context"+ "fmt"+ "net"+ "net/http"+ "time"++ "github.com/serverkit/agent/internal/config"+ "github.com/serverkit/agent/internal/logger"+)++// StatusProvider provides agent status information+type StatusProvider interface {+ GetStatus() AgentStatus+ GetDetailedMetrics() *DetailedMetrics+ GetConnectionInfo() ConnectionInfo+ GetRecentLogs(lines int) []string+ Restart() error+}++// AgentStatus represents the current agent status+type AgentStatus struct {+ Running bool `json:"running"`+ Connected bool `json:"connected"`+ Registered bool `json:"registered"`+ AgentID string `json:"agent_id"`+ AgentName string `json:"agent_name"`+ ServerURL string `json:"server_url"`+ Uptime int64 `json:"uptime_seconds"`+ Version string `json:"version"`+ CPUPercent float64 `json:"cpu_percent"`+ MemPercent float64 `json:"mem_percent"`+ DiskPercent float64 `json:"disk_percent"`+}++// DetailedMetrics contains detailed system metrics+type DetailedMetrics struct {+ CPU CPUMetrics `json:"cpu"`+ Memory MemoryMetrics `json:"memory"`+ Disk DiskMetrics `json:"disk"`+ Network NetworkMetrics `json:"network"`+ Timestamp int64 `json:"timestamp"`+}++// CPUMetrics contains CPU information+type CPUMetrics struct {+ UsagePercent float64 `json:"usage_percent"`+ PerCPU []float64 `json:"per_cpu,omitempty"`+ Cores int `json:"cores"`+}++// MemoryMetrics contains memory information+type MemoryMetrics struct {+ Total uint64 `json:"total"`+ Used uint64 `json:"used"`+ Free uint64 `json:"free"`+ UsagePercent float64 `json:"usage_percent"`+}++// DiskMetrics contains disk information+type DiskMetrics struct {+ Total uint64 `json:"total"`+ Used uint64 `json:"used"`+ Free uint64 `json:"free"`+ UsagePercent float64 `json:"usage_percent"`+}++// NetworkMetrics contains network information+type NetworkMetrics struct {+ BytesSent uint64 `json:"bytes_sent"`+ BytesRecv uint64 `json:"bytes_recv"`+ PacketsSent uint64 `json:"packets_sent"`+ PacketsRecv uint64 `json:"packets_recv"`+}++// ConnectionInfo contains WebSocket connection details+type ConnectionInfo struct {+ Connected bool `json:"connected"`+ ServerURL string `json:"server_url"`+ ReconnectCount int `json:"reconnect_count"`+ LastConnected int64 `json:"last_connected,omitempty"`+ SessionExpires int64 `json:"session_expires,omitempty"`+}++// Server is the IPC HTTP server for tray app communication+type Server struct {+ cfg config.IPCConfig+ log *logger.Logger+ server *http.Server+ provider StatusProvider+ startTime time.Time+}++// NewServer creates a new IPC server+func NewServer(cfg config.IPCConfig, log *logger.Logger, provider StatusProvider) *Server {+ return &Server{+ cfg: cfg,+ log: log.WithComponent("ipc"),+ provider: provider,+ startTime: time.Now(),+ }+}++// Start starts the IPC HTTP server+func (s *Server) Start(ctx context.Context) error {+ if !s.cfg.Enabled {+ s.log.Info("IPC server disabled")+ return nil+ }++ mux := http.NewServeMux()++ // Register handlers+ handlers := NewHandlers(s.provider, s.log)+ mux.HandleFunc("/status", handlers.HandleStatus)+ mux.HandleFunc("/metrics", handlers.HandleMetrics)+ mux.HandleFunc("/connection", handlers.HandleConnection)+ mux.HandleFunc("/logs", handlers.HandleLogs)+ mux.HandleFunc("/restart", handlers.HandleRestart)+ mux.HandleFunc("/health", handlers.HandleHealth)++ addr := fmt.Sprintf("%s:%d", s.cfg.Address, s.cfg.Port)++ // Verify we're only binding to localhost for security+ host, _, err := net.SplitHostPort(addr)+ if err != nil || (host != "127.0.0.1" && host != "localhost" && host != "::1") {+ s.log.Warn("IPC server can only bind to localhost, forcing 127.0.0.1")+ addr = fmt.Sprintf("127.0.0.1:%d", s.cfg.Port)+ }++ s.server = &http.Server{+ Addr: addr,+ Handler: corsMiddleware(mux),+ ReadTimeout: 5 * time.Second,+ WriteTimeout: 10 * time.Second,+ IdleTimeout: 60 * time.Second,+ }++ s.log.Info("Starting IPC server", "address", addr)++ // Start server in goroutine+ errCh := make(chan error, 1)+ go func() {+ if err := s.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {+ errCh <- err+ }+ }()++ // Check for immediate startup errors+ select {+ case err := <-errCh:+ return fmt.Errorf("IPC server failed to start: %w", err)+ case <-time.After(100 * time.Millisecond):+ // Server started successfully+ }++ // Wait for context cancellation+ go func() {+ <-ctx.Done()+ s.Stop()+ }()++ return nil+}++// Stop gracefully stops the IPC server+func (s *Server) Stop() error {+ if s.server == nil {+ return nil+ }++ s.log.Info("Stopping IPC server")++ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()++ return s.server.Shutdown(ctx)+}++// corsMiddleware adds CORS headers for local development+func corsMiddleware(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ // Only allow requests from localhost+ origin := r.Header.Get("Origin")+ if origin == "" || isLocalhost(origin) {+ w.Header().Set("Access-Control-Allow-Origin", origin)+ w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")+ w.Header().Set("Access-Control-Allow-Headers", "Content-Type")+ }++ if r.Method == "OPTIONS" {+ w.WriteHeader(http.StatusOK)+ return+ }++ next.ServeHTTP(w, r)+ })+}++// isLocalhost checks if the origin is from localhost+func isLocalhost(origin string) bool {+ return origin == "http://localhost" ||+ origin == "https://localhost" ||+ origin == "http://127.0.0.1" ||+ origin == "https://127.0.0.1" ||+ len(origin) > 17 && origin[:17] == "http://localhost:" ||+ len(origin) > 18 && origin[:18] == "https://localhost:" ||+ len(origin) > 17 && origin[:17] == "http://127.0.0.1:" ||+ len(origin) > 18 && origin[:18] == "https://127.0.0.1:"+}diff --git a/agent/internal/tray/client.go b/agent/internal/tray/client.gonew file mode 100644index 00000000..c3398287--- /dev/null+++ b/agent/internal/tray/client.go@@ -0,0 +1,145 @@+package tray++import (+ "encoding/json"+ "fmt"+ "net/http"+ "time"++ "github.com/serverkit/agent/internal/ipc"+)++// Client communicates with the agent's IPC server+type Client struct {+ baseURL string+ httpClient *http.Client+}++// NewClient creates a new IPC client+func NewClient(address string, port int) *Client {+ return &Client{+ baseURL: fmt.Sprintf("http://%s:%d", address, port),+ httpClient: &http.Client{+ Timeout: 5 * time.Second,+ },+ }+}++// GetStatus fetches the agent status+func (c *Client) GetStatus() (*ipc.AgentStatus, error) {+ resp, err := c.httpClient.Get(c.baseURL + "/status")+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("unexpected status: %d", resp.StatusCode)+ }++ var status ipc.AgentStatus+ if err := json.NewDecoder(resp.Body).Decode(&status); err != nil {+ return nil, err+ }++ return &status, nil+}++// GetMetrics fetches detailed system metrics+func (c *Client) GetMetrics() (*ipc.DetailedMetrics, error) {+ resp, err := c.httpClient.Get(c.baseURL + "/metrics")+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("unexpected status: %d", resp.StatusCode)+ }++ var metrics ipc.DetailedMetrics+ if err := json.NewDecoder(resp.Body).Decode(&metrics); err != nil {+ return nil, err+ }++ return &metrics, nil+}++// GetConnection fetches WebSocket connection info+func (c *Client) GetConnection() (*ipc.ConnectionInfo, error) {+ resp, err := c.httpClient.Get(c.baseURL + "/connection")+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("unexpected status: %d", resp.StatusCode)+ }++ var info ipc.ConnectionInfo+ if err := json.NewDecoder(resp.Body).Decode(&info); err != nil {+ return nil, err+ }++ return &info, nil+}++// GetLogs fetches recent log lines+func (c *Client) GetLogs(lines int) ([]string, error) {+ resp, err := c.httpClient.Get(fmt.Sprintf("%s/logs?lines=%d", c.baseURL, lines))+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("unexpected status: %d", resp.StatusCode)+ }++ var result struct {+ Lines []string `json:"lines"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {+ return nil, err+ }++ return result.Lines, nil+}++// Restart requests agent restart+func (c *Client) Restart() error {+ resp, err := c.httpClient.Post(c.baseURL+"/restart", "application/json", nil)+ if err != nil {+ return err+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ return fmt.Errorf("unexpected status: %d", resp.StatusCode)+ }++ var result struct {+ Success bool `json:"success"`+ Error string `json:"error,omitempty"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {+ return err+ }++ if !result.Success {+ return fmt.Errorf("restart failed: %s", result.Error)+ }++ return nil+}++// IsAgentRunning checks if the agent is reachable+func (c *Client) IsAgentRunning() bool {+ resp, err := c.httpClient.Get(c.baseURL + "/health")+ if err != nil {+ return false+ }+ defer resp.Body.Close()+ return resp.StatusCode == http.StatusOK+}diff --git a/agent/internal/tray/icons.go b/agent/internal/tray/icons.gonew file mode 100644index 00000000..f1ea61d5--- /dev/null+++ b/agent/internal/tray/icons.go@@ -0,0 +1,50 @@+package tray++import (+ _ "embed"+)++// Icon states for the system tray+// Icons should be 16x16 or 32x32 PNG/ICO files+// These are embedded at compile time++// Default icons are simple colored squares+// Replace these with actual icon files for production++//go:embed icons/connected.ico+var iconConnected []byte++//go:embed icons/disconnected.ico+var iconDisconnected []byte++//go:embed icons/error.ico+var iconError []byte++//go:embed icons/stopped.ico+var iconStopped []byte++// IconState represents the current icon state+type IconState int++const (+ IconStateConnected IconState = iota // Green - connected and running+ IconStateDisconnected // Yellow - running but disconnected+ IconStateError // Red - error state+ IconStateStopped // Gray - agent not running+)++// GetIcon returns the icon bytes for a given state+func GetIcon(state IconState) []byte {+ switch state {+ case IconStateConnected:+ return iconConnected+ case IconStateDisconnected:+ return iconDisconnected+ case IconStateError:+ return iconError+ case IconStateStopped:+ return iconStopped+ default:+ return iconStopped+ }+}diff --git a/agent/internal/tray/icons/connected.ico b/agent/internal/tray/icons/connected.iconew file mode 100644index 00000000..c388bd93Binary files /dev/null and b/agent/internal/tray/icons/connected.ico differdiff --git a/agent/internal/tray/icons/disconnected.ico b/agent/internal/tray/icons/disconnected.iconew file mode 100644index 00000000..c388bd93Binary files /dev/null and b/agent/internal/tray/icons/disconnected.ico differdiff --git a/agent/internal/tray/icons/error.ico b/agent/internal/tray/icons/error.iconew file mode 100644index 00000000..c388bd93Binary files /dev/null and b/agent/internal/tray/icons/error.ico differdiff --git a/agent/internal/tray/icons/stopped.ico b/agent/internal/tray/icons/stopped.iconew file mode 100644index 00000000..c388bd93Binary files /dev/null and b/agent/internal/tray/icons/stopped.ico differdiff --git a/agent/internal/tray/tray.go b/agent/internal/tray/tray.gonew file mode 100644index 00000000..17967bc2--- /dev/null+++ b/agent/internal/tray/tray.go@@ -0,0 +1,330 @@+package tray++import (+ "fmt"+ "os/exec"+ "runtime"+ "sync"+ "time"++ "fyne.io/systray"+)++// AppConfig holds tray app configuration+type AppConfig struct {+ Version string+ IPCAddress string+ IPCPort int+ ServerURL string+ DashboardURL string+ LogFile string+}++// App is the system tray application+type App struct {+ config AppConfig+ client *Client++ // Current state+ mu sync.RWMutex+ connected bool+ agentRunning bool+ lastStatus string+ cpuPercent float64+ memPercent float64++ // Menu items+ menuStatus *systray.MenuItem+ menuCPU *systray.MenuItem+ menuMem *systray.MenuItem+ menuStartAgent *systray.MenuItem+ menuStopAgent *systray.MenuItem+ menuRestartAgent *systray.MenuItem+ menuViewLogs *systray.MenuItem+ menuDashboard *systray.MenuItem+ menuAbout *systray.MenuItem+ menuQuit *systray.MenuItem++ // Control channels+ quitCh chan struct{}+}++// NewApp creates a new tray application+func NewApp(config AppConfig) *App {+ return &App{+ config: config,+ client: NewClient(config.IPCAddress, config.IPCPort),+ quitCh: make(chan struct{}),+ }+}++// Run starts the tray application (blocking)+func (a *App) Run() {+ systray.Run(a.onReady, a.onExit)+}++// Quit requests the tray app to quit+func (a *App) Quit() {+ close(a.quitCh)+ systray.Quit()+}++func (a *App) onReady() {+ // Set initial icon (gray/stopped)+ systray.SetIcon(GetIcon(IconStateStopped))+ systray.SetTitle("ServerKit")+ systray.SetTooltip("ServerKit Agent - Checking...")++ // Create menu items+ a.menuStatus = systray.AddMenuItem("Status: Checking...", "Agent status")+ a.menuStatus.Disable()++ a.menuCPU = systray.AddMenuItem("CPU: --", "CPU usage")+ a.menuCPU.Disable()++ a.menuMem = systray.AddMenuItem("Memory: --", "Memory usage")+ a.menuMem.Disable()++ systray.AddSeparator()++ a.menuStartAgent = systray.AddMenuItem("Start Agent", "Start the ServerKit agent service")+ a.menuStopAgent = systray.AddMenuItem("Stop Agent", "Stop the ServerKit agent service")+ a.menuRestartAgent = systray.AddMenuItem("Restart Agent", "Restart the ServerKit agent service")++ systray.AddSeparator()++ a.menuViewLogs = systray.AddMenuItem("View Logs", "Open log file")+ a.menuDashboard = systray.AddMenuItem("Open Dashboard", "Open ServerKit dashboard in browser")+ if a.config.DashboardURL == "" {+ a.menuDashboard.Disable()+ }++ systray.AddSeparator()++ a.menuAbout = systray.AddMenuItem(fmt.Sprintf("About ServerKit Tray v%s", a.config.Version), "About this application")+ a.menuAbout.Disable()++ a.menuQuit = systray.AddMenuItem("Quit Tray", "Exit the tray application")++ // Start background refresh+ go a.refreshLoop()++ // Handle menu clicks+ go a.handleMenuClicks()+}++func (a *App) onExit() {+ // Cleanup on exit+}++func (a *App) refreshLoop() {+ // Initial fetch+ a.refresh()++ ticker := time.NewTicker(5 * time.Second)+ defer ticker.Stop()++ for {+ select {+ case <-a.quitCh:+ return+ case <-ticker.C:+ a.refresh()+ }+ }+}++func (a *App) refresh() {+ status, err := a.client.GetStatus()++ a.mu.Lock()+ defer a.mu.Unlock()++ if err != nil {+ // Agent not reachable+ a.agentRunning = false+ a.connected = false+ a.lastStatus = "Agent Not Running"+ systray.SetIcon(GetIcon(IconStateStopped))+ systray.SetTooltip("ServerKit Agent - Not Running")+ a.menuStatus.SetTitle("Status: Agent Not Running")+ a.menuCPU.SetTitle("CPU: --")+ a.menuMem.SetTitle("Memory: --")+ a.menuStartAgent.Enable()+ a.menuStopAgent.Disable()+ a.menuRestartAgent.Disable()+ return+ }++ a.agentRunning = status.Running+ a.connected = status.Connected+ a.cpuPercent = status.CPUPercent+ a.memPercent = status.MemPercent++ // Update icon based on connection state+ if status.Connected {+ a.lastStatus = "Connected"+ systray.SetIcon(GetIcon(IconStateConnected))+ systray.SetTooltip(fmt.Sprintf("ServerKit Agent - Connected | CPU: %.1f%% | Mem: %.1f%%",+ status.CPUPercent, status.MemPercent))+ } else if status.Running {+ a.lastStatus = "Disconnected"+ systray.SetIcon(GetIcon(IconStateDisconnected))+ systray.SetTooltip("ServerKit Agent - Disconnected from server")+ } else {+ a.lastStatus = "Stopped"+ systray.SetIcon(GetIcon(IconStateStopped))+ systray.SetTooltip("ServerKit Agent - Stopped")+ }++ // Update menu items+ a.menuStatus.SetTitle(fmt.Sprintf("Status: %s", a.lastStatus))+ a.menuCPU.SetTitle(fmt.Sprintf("CPU: %.1f%%", status.CPUPercent))+ a.menuMem.SetTitle(fmt.Sprintf("Memory: %.1f%%", status.MemPercent))++ // Enable/disable service controls+ if status.Running {+ a.menuStartAgent.Disable()+ a.menuStopAgent.Enable()+ a.menuRestartAgent.Enable()+ } else {+ a.menuStartAgent.Enable()+ a.menuStopAgent.Disable()+ a.menuRestartAgent.Disable()+ }+}++func (a *App) handleMenuClicks() {+ for {+ select {+ case <-a.quitCh:+ return+ case <-a.menuStartAgent.ClickedCh:+ a.startAgent()+ case <-a.menuStopAgent.ClickedCh:+ a.stopAgent()+ case <-a.menuRestartAgent.ClickedCh:+ a.restartAgent()+ case <-a.menuViewLogs.ClickedCh:+ a.viewLogs()+ case <-a.menuDashboard.ClickedCh:+ a.openDashboard()+ case <-a.menuQuit.ClickedCh:+ systray.Quit()+ return+ }+ }+}++func (a *App) startAgent() {+ if err := startService(); err != nil {+ a.showNotification("Failed to Start", err.Error())+ return+ }+ a.showNotification("Agent Started", "ServerKit agent service started")+ // Refresh immediately+ time.Sleep(1 * time.Second)+ a.refresh()+}++func (a *App) stopAgent() {+ if err := stopService(); err != nil {+ a.showNotification("Failed to Stop", err.Error())+ return+ }+ a.showNotification("Agent Stopped", "ServerKit agent service stopped")+ a.refresh()+}++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+ if err := restartService(); err != nil {+ a.showNotification("Failed to Restart", err.Error())+ return+ }+ a.showNotification("Agent Restarted", "ServerKit agent service restarted")+ time.Sleep(2 * time.Second)+ a.refresh()+}++func (a *App) viewLogs() {+ if a.config.LogFile == "" {+ return+ }+ openFile(a.config.LogFile)+}++func (a *App) openDashboard() {+ if a.config.DashboardURL == "" {+ return+ }+ openURL(a.config.DashboardURL)+}++func (a *App) showNotification(title, message string) {+ // Note: systray doesn't have built-in notification support+ // For now, this is a placeholder - could use beeep or toast libraries+ fmt.Printf("Notification: %s - %s\n", title, message)+}++// Platform-specific helpers++func startService() error {+ if runtime.GOOS == "windows" {+ return exec.Command("sc", "start", "ServerKitAgent").Run()+ }+ return exec.Command("systemctl", "start", "serverkit-agent").Run()+}++func stopService() error {+ if runtime.GOOS == "windows" {+ return exec.Command("sc", "stop", "ServerKitAgent").Run()+ }+ return exec.Command("systemctl", "stop", "serverkit-agent").Run()+}++func restartService() error {+ if runtime.GOOS == "windows" {+ // Windows doesn't have restart, so stop then start+ stopService()+ time.Sleep(1 * time.Second)+ return startService()+ }+ return exec.Command("systemctl", "restart", "serverkit-agent").Run()+}++func openURL(url string) error {+ var cmd *exec.Cmd+ switch runtime.GOOS {+ case "windows":+ cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)+ case "darwin":+ cmd = exec.Command("open", url)+ default:+ cmd = exec.Command("xdg-open", url)+ }+ return cmd.Start()+}++func openFile(path string) error {+ var cmd *exec.Cmd+ switch runtime.GOOS {+ case "windows":+ cmd = exec.Command("notepad", path)+ case "darwin":+ cmd = exec.Command("open", "-t", path)+ default:+ cmd = exec.Command("xdg-open", path)+ }+ return cmd.Start()+}diff --git a/agent/packaging/msi/Product.wxs b/agent/packaging/msi/Product.wxsindex 7f138b95..200ccac5 100644--- a/agent/packaging/msi/Product.wxs+++ b/agent/packaging/msi/Product.wxs@@ -34,6 +34,7 @@<Feature Id="ProductFeature" Title="ServerKit Agent" Level="1"><ComponentGroupRef Id="ProductComponents" /><ComponentRef Id="ConfigComponent" />+ <ComponentRef Id="TrayAutoStart" /></Feature></Package>@@ -87,6 +88,17 @@<RemoveFile Id="RemoveKey" Name="agent.key" On="uninstall" /><RemoveFolder Id="RemoveAgentDataFolder" On="uninstall" /></Component>++ <!-- Auto-start tray on user login (uses main binary with tray command) -->+ <Component Id="TrayAutoStart" Directory="INSTALLFOLDER" Guid="E5F6A7B8-C9D0-1234-EF01-567890123456">+ <RegistryValue+ Root="HKCU"+ Key="Software\Microsoft\Windows\CurrentVersion\Run"+ Name="ServerKitTray"+ Type="string"+ Value=""[INSTALLFOLDER]serverkit-agent.exe" tray"+ KeyPath="yes" />+ </Component></Fragment></Wix>diff --git a/agent/packaging/msi/build.ps1 b/agent/packaging/msi/build.ps1index 4b4e9c75..279a6eff 100644--- a/agent/packaging/msi/build.ps1+++ b/agent/packaging/msi/build.ps1@@ -68,6 +68,11 @@ logging:max_backups: 5max_age_days: 30compress: true++ipc:+ enabled: true+ port: 19780+ address: 127.0.0.1"@$configContent | Out-File -FilePath "$buildDir\config.yaml" -Encoding UTF8