feat: add Telegram Mini App dashboard

- Single-file HTML Mini App with 4 tabs: Plan, Skills, Session, Config
- Plan tab shows phase/step list parsed from MEMORY.md with tap-to-complete
- Skills tab lists available skills with send bar for command construction
- Tailscale auto-detection for HTTPS hosting with TLS cert provisioning
- HMAC-SHA256 validation of Telegram initData for API authentication
- WebAppData handler in Telegram channel for command relay
- Menu Button registration for "Dashboard" in Telegram
- Health server extended with Mux() accessor and StartTLS support
- GetPlanPhases() as single source of truth for plan parsing

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
dj-oyu 2026-02-22 05:26:26 +09:00
parent 4523d76b7d
commit bf29d4ca2e
13 changed files with 1387 additions and 42 deletions

View file

@ -21,8 +21,12 @@ import (
"github.com/sipeed/picoclaw/pkg/health" "github.com/sipeed/picoclaw/pkg/health"
"github.com/sipeed/picoclaw/pkg/heartbeat" "github.com/sipeed/picoclaw/pkg/heartbeat"
"github.com/sipeed/picoclaw/pkg/logger" "github.com/sipeed/picoclaw/pkg/logger"
"github.com/sipeed/picoclaw/pkg/miniapp"
"github.com/sipeed/picoclaw/pkg/providers" "github.com/sipeed/picoclaw/pkg/providers"
"github.com/sipeed/picoclaw/pkg/skills"
"github.com/sipeed/picoclaw/pkg/state" "github.com/sipeed/picoclaw/pkg/state"
"github.com/sipeed/picoclaw/pkg/stats"
"github.com/sipeed/picoclaw/pkg/tailscale"
"github.com/sipeed/picoclaw/pkg/tools" "github.com/sipeed/picoclaw/pkg/tools"
"github.com/sipeed/picoclaw/pkg/voice" "github.com/sipeed/picoclaw/pkg/voice"
) )
@ -187,12 +191,55 @@ func gatewayCmd() {
} }
healthServer := health.NewServer(cfg.Gateway.Host, cfg.Gateway.Port) healthServer := health.NewServer(cfg.Gateway.Host, cfg.Gateway.Port)
// Mini App setup: register routes and determine TLS mode
useTLS := false
var tlsCert, tlsKey string
if cfg.Channels.Telegram.Enabled {
webAppURL := cfg.Channels.Telegram.WebAppURL
if webAppURL == "" {
// Auto-detect Tailscale hostname and fetch TLS cert
hostname, tsErr := tailscale.DetectHostname()
if tsErr != nil {
logger.InfoCF("miniapp", "Tailscale not available, Mini App disabled", map[string]any{"error": tsErr.Error()})
} else {
certDir := filepath.Join(cfg.WorkspacePath(), "state", "certs")
certFile, keyFile, certErr := tailscale.FetchCert(hostname, certDir)
if certErr != nil {
logger.ErrorCF("miniapp", "Failed to fetch TLS cert", map[string]any{"error": certErr.Error()})
} else {
webAppURL = fmt.Sprintf("https://%s:%d/miniapp", hostname, cfg.Gateway.Port)
cfg.Channels.Telegram.WebAppURL = webAppURL
tlsCert, tlsKey = certFile, keyFile
useTLS = true
}
}
}
if webAppURL != "" {
provider := &agentLoopDataProvider{loop: agentLoop}
handler := miniapp.NewHandler(provider, cfg.Channels.Telegram.Token)
handler.RegisterRoutes(healthServer.Mux())
fmt.Printf("✓ Mini App registered at %s\n", webAppURL)
}
}
go func() { go func() {
if err := healthServer.Start(); err != nil && err != http.ErrServerClosed { var serverErr error
logger.ErrorCF("health", "Health server error", map[string]any{"error": err.Error()}) if useTLS {
serverErr = healthServer.StartTLS(tlsCert, tlsKey)
} else {
serverErr = healthServer.Start()
}
if serverErr != nil && serverErr != http.ErrServerClosed {
logger.ErrorCF("health", "Health server error", map[string]any{"error": serverErr.Error()})
} }
}() }()
if useTLS {
fmt.Printf("✓ Health endpoints available at https://%s:%d/health and /ready (TLS)\n", cfg.Gateway.Host, cfg.Gateway.Port)
} else {
fmt.Printf("✓ Health endpoints available at http://%s:%d/health and /ready\n", cfg.Gateway.Host, cfg.Gateway.Port) fmt.Printf("✓ Health endpoints available at http://%s:%d/health and /ready\n", cfg.Gateway.Host, cfg.Gateway.Port)
}
go agentLoop.Run(ctx) go agentLoop.Run(ctx)
@ -236,3 +283,48 @@ func setupCronTool(
return cronService return cronService
} }
// agentLoopDataProvider adapts AgentLoop to the miniapp.DataProvider interface.
type agentLoopDataProvider struct {
loop *agent.AgentLoop
}
func (p *agentLoopDataProvider) ListSkills() []skills.SkillInfo {
return p.loop.ListSkills()
}
func (p *agentLoopDataProvider) GetPlanInfo() miniapp.PlanInfo {
hasPlan, status, currentPhase, totalPhases, display := p.loop.GetPlanInfo()
// Convert agent.PlanPhase → miniapp.PlanPhase
agentPhases := p.loop.GetPlanPhases()
phases := make([]miniapp.PlanPhase, 0, len(agentPhases))
for _, ap := range agentPhases {
steps := make([]miniapp.PlanStep, 0, len(ap.Steps))
for _, as := range ap.Steps {
steps = append(steps, miniapp.PlanStep{
Index: as.Index,
Description: as.Description,
Done: as.Done,
})
}
phases = append(phases, miniapp.PlanPhase{
Number: ap.Number,
Title: ap.Title,
Steps: steps,
})
}
return miniapp.PlanInfo{
HasPlan: hasPlan,
Status: status,
CurrentPhase: currentPhase,
TotalPhases: totalPhases,
Display: display,
Phases: phases,
}
}
func (p *agentLoopDataProvider) GetSessionStats() *stats.Stats {
return p.loop.GetSessionStats()
}

View file

@ -53,6 +53,7 @@
"enabled": false, "enabled": false,
"token": "YOUR_TELEGRAM_BOT_TOKEN", "token": "YOUR_TELEGRAM_BOT_TOKEN",
"proxy": "", "proxy": "",
"web_app_url": "",
"allow_from": [ "allow_from": [
"YOUR_USER_ID" "YOUR_USER_ID"
] ]

View file

@ -347,6 +347,11 @@ func (cb *ContextBuilder) ListSkills() []skills.SkillInfo {
return cb.skillsLoader.ListSkills() return cb.skillsLoader.ListSkills()
} }
// Memory returns the underlying MemoryStore for direct plan queries.
func (cb *ContextBuilder) Memory() *MemoryStore {
return cb.memory
}
// ---------- Plan passthrough methods ---------- // ---------- Plan passthrough methods ----------
// ReadMemory reads the long-term memory (MEMORY.md). // ReadMemory reads the long-term memory (MEMORY.md).

View file

@ -1843,6 +1843,55 @@ func (al *AgentLoop) GetStartupInfo() map[string]any {
return info return info
} }
// ListSkills returns all available skills from the default agent.
func (al *AgentLoop) ListSkills() []skills.SkillInfo {
agent := al.registry.GetDefaultAgent()
if agent == nil {
return nil
}
return agent.ContextBuilder.ListSkills()
}
// GetPlanInfo returns plan state from the default agent's memory store.
func (al *AgentLoop) GetPlanInfo() (hasPlan bool, status string, currentPhase, totalPhases int, display string) {
agent := al.registry.GetDefaultAgent()
if agent == nil {
return false, "", 0, 0, "No agent available."
}
mem := agent.ContextBuilder.Memory()
if mem == nil {
return false, "", 0, 0, "No memory store."
}
hasPlan = mem.HasActivePlan()
status = mem.GetPlanStatus()
currentPhase = mem.GetCurrentPhase()
totalPhases = mem.GetTotalPhases()
display = mem.FormatPlanDisplay()
return
}
// GetPlanPhases returns structured phase/step data from the default agent's plan.
func (al *AgentLoop) GetPlanPhases() []PlanPhase {
agent := al.registry.GetDefaultAgent()
if agent == nil {
return nil
}
mem := agent.ContextBuilder.Memory()
if mem == nil {
return nil
}
return mem.GetPlanPhases()
}
// GetSessionStats returns the current session statistics snapshot, or nil if stats tracking is disabled.
func (al *AgentLoop) GetSessionStats() *stats.Stats {
if al.stats == nil {
return nil
}
s := al.stats.GetStats()
return &s
}
// formatMessagesForLog formats messages for logging // formatMessagesForLog formats messages for logging
func formatMessagesForLog(messages []providers.Message) string { func formatMessagesForLog(messages []providers.Message) string {
if len(messages) == 0 { if len(messages) == 0 {

View file

@ -188,34 +188,43 @@ func (ms *MemoryStore) GetTotalPhases() int {
// IsPlanComplete returns true if all steps in all phases are [x]. // IsPlanComplete returns true if all steps in all phases are [x].
func (ms *MemoryStore) IsPlanComplete() bool { func (ms *MemoryStore) IsPlanComplete() bool {
content := ms.ReadLongTerm() phases := ms.GetPlanPhases()
if !reActivePlan.MatchString(content) { if len(phases) == 0 {
return false return false
} }
// Must have at least one step hasSteps := false
if !reStepDone.MatchString(content) && !reStepTodo.MatchString(content) { for _, p := range phases {
for _, s := range p.Steps {
hasSteps = true
if !s.Done {
return false return false
} }
// No unchecked steps }
return !reStepTodo.MatchString(content) }
return hasSteps
} }
// IsCurrentPhaseComplete returns true if all steps in the current phase are [x]. // IsCurrentPhaseComplete returns true if all steps in the current phase are [x].
func (ms *MemoryStore) IsCurrentPhaseComplete() bool { func (ms *MemoryStore) IsCurrentPhaseComplete() bool {
content := ms.ReadLongTerm() current := ms.GetCurrentPhase()
phase := ms.GetCurrentPhase() if current == 0 {
if phase == 0 {
return false return false
} }
phaseContent := ms.extractPhaseContent(content, phase) phases := ms.GetPlanPhases()
if phaseContent == "" { for _, p := range phases {
if p.Number == current {
if len(p.Steps) == 0 {
return false return false
} }
// Must have at least one step for _, s := range p.Steps {
if !reStepDone.MatchString(phaseContent) && !reStepTodo.MatchString(phaseContent) { if !s.Done {
return false return false
} }
return !reStepTodo.MatchString(phaseContent) }
return true
}
}
return false
} }
// extractPhaseContent returns the content of a specific phase section. // extractPhaseContent returns the content of a specific phase section.
@ -242,6 +251,65 @@ func (ms *MemoryStore) extractPhaseContent(content string, phase int) string {
return strings.Join(result, "\n") return strings.Join(result, "\n")
} }
// PlanPhase represents a phase with its steps, for structured API output.
type PlanPhase struct {
Number int `json:"number"`
Title string `json:"title"`
Steps []PlanStep `json:"steps"`
}
// PlanStep represents a single step within a phase.
type PlanStep struct {
Index int `json:"index"` // 1-based within the phase
Description string `json:"description"`
Done bool `json:"done"`
}
// GetPlanPhases parses MEMORY.md and returns all phases with their steps.
func (ms *MemoryStore) GetPlanPhases() []PlanPhase {
content := ms.ReadLongTerm()
if !reActivePlan.MatchString(content) {
return nil
}
totalPhases := ms.GetTotalPhases()
phases := make([]PlanPhase, 0, totalPhases)
for p := 1; p <= totalPhases; p++ {
title := ms.getPhaseTitle(content, p)
phaseContent := ms.extractPhaseContent(content, p)
var steps []PlanStep
stepIdx := 0
for _, line := range strings.Split(phaseContent, "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "- [x] ") {
stepIdx++
steps = append(steps, PlanStep{
Index: stepIdx,
Description: line[6:],
Done: true,
})
} else if strings.HasPrefix(line, "- [ ] ") {
stepIdx++
steps = append(steps, PlanStep{
Index: stepIdx,
Description: line[6:],
Done: false,
})
}
}
phases = append(phases, PlanPhase{
Number: p,
Title: title,
Steps: steps,
})
}
return phases
}
// ---------- Plan mutation methods ---------- // ---------- Plan mutation methods ----------
// SetStatus sets the plan status (interviewing or executing). // SetStatus sets the plan status (interviewing or executing).
@ -514,37 +582,32 @@ func (ms *MemoryStore) FormatPlanDisplay() string {
} }
status := ms.GetPlanStatus() status := ms.GetPlanStatus()
currentPhase := ms.GetCurrentPhase() currentPhase := ms.GetCurrentPhase()
totalPhases := ms.GetTotalPhases() phases := ms.GetPlanPhases()
var sb strings.Builder var sb strings.Builder
sb.WriteString(fmt.Sprintf("Plan: %s\n", taskLine)) sb.WriteString(fmt.Sprintf("Plan: %s\n", taskLine))
sb.WriteString(fmt.Sprintf("Status: %s | Phase %d/%d\n\n", status, currentPhase, totalPhases)) sb.WriteString(fmt.Sprintf("Status: %s | Phase %d/%d\n\n", status, currentPhase, len(phases)))
for p := 1; p <= totalPhases; p++ {
title := ms.getPhaseTitle(content, p)
phaseContent := ms.extractPhaseContent(content, p)
for _, p := range phases {
// Determine phase emoji // Determine phase emoji
var emoji string var emoji string
if p < currentPhase { if p.Number < currentPhase {
emoji = "\u2705" // checkmark emoji = "\u2705" // checkmark
} else if p == currentPhase { } else if p.Number == currentPhase {
emoji = "\u25B6\uFE0F" // play button emoji = "\u25B6\uFE0F" // play button
} else { } else {
emoji = "\u23F3" // hourglass emoji = "\u23F3" // hourglass
} }
sb.WriteString(fmt.Sprintf("%s Phase %d: %s\n", emoji, p, title)) sb.WriteString(fmt.Sprintf("%s Phase %d: %s\n", emoji, p.Number, p.Title))
// Show steps for current and completed phases // Show steps for current and completed phases
if p <= currentPhase { if p.Number <= currentPhase {
lines := strings.Split(phaseContent, "\n") for _, s := range p.Steps {
for _, line := range lines { if s.Done {
line = strings.TrimSpace(line) sb.WriteString(" \u2611 " + s.Description + "\n")
if strings.HasPrefix(line, "- [x] ") { } else {
sb.WriteString(" \u2611 " + line[6:] + "\n") sb.WriteString(" \u2610 " + s.Description + "\n")
} else if strings.HasPrefix(line, "- [ ] ") {
sb.WriteString(" \u2610 " + line[6:] + "\n")
} }
} }
} }

View file

@ -142,6 +142,13 @@ func (c *TelegramChannel) Start(ctx context.Context) error {
return c.handleQuickCommand(ctx, message) return c.handleQuickCommand(ctx, message)
}, th.CommandEqual("skills")) }, th.CommandEqual("skills"))
// WebAppData handler: intercept messages from Mini App before AnyMessage
bh.HandleMessage(func(ctx *th.Context, message telego.Message) error {
return c.handleWebAppData(ctx, message)
}, func(_ context.Context, update telego.Update) bool {
return update.Message != nil && update.Message.WebAppData != nil
})
bh.HandleMessage(func(ctx *th.Context, message telego.Message) error { bh.HandleMessage(func(ctx *th.Context, message telego.Message) error {
return c.handleMessage(ctx, &message) return c.handleMessage(ctx, &message)
}, th.AnyMessage()) }, th.AnyMessage())
@ -151,6 +158,28 @@ func (c *TelegramChannel) Start(ctx context.Context) error {
"username": c.bot.Username(), "username": c.bot.Username(),
}) })
// Set Menu Button for Mini App (if WebAppURL is configured)
if webAppURL := c.config.Channels.Telegram.WebAppURL; webAppURL != "" {
menuErr := c.bot.SetChatMenuButton(ctx, &telego.SetChatMenuButtonParams{
MenuButton: &telego.MenuButtonWebApp{
Type: telego.ButtonTypeWebApp,
Text: "Dashboard",
WebApp: telego.WebAppInfo{
URL: webAppURL,
},
},
})
if menuErr != nil {
logger.ErrorCF("telegram", "Failed to set menu button", map[string]any{
"error": menuErr.Error(),
})
} else {
logger.InfoCF("telegram", "Menu button set", map[string]any{
"url": webAppURL,
})
}
}
go bh.Start() go bh.Start()
go func() { go func() {
@ -545,6 +574,63 @@ func (c *TelegramChannel) handleQuickCommand(ctx context.Context, message telego
return nil return nil
} }
// handleWebAppData processes messages sent via Telegram Mini App's sendData().
// The data is treated as a slash command and routed through the normal message bus.
func (c *TelegramChannel) handleWebAppData(ctx context.Context, message telego.Message) error {
if message.From == nil || message.WebAppData == nil {
return nil
}
user := message.From
senderID := fmt.Sprintf("%d", user.ID)
if user.Username != "" {
senderID = fmt.Sprintf("%d|%s", user.ID, user.Username)
}
if !c.IsAllowed(senderID) {
logger.DebugCF("telegram", "WebAppData rejected by allowlist", map[string]any{
"user_id": senderID,
})
return nil
}
content := message.WebAppData.Data
if !strings.HasPrefix(content, "/") {
logger.DebugCF("telegram", "WebAppData ignored (not a command)", map[string]any{
"data": utils.Truncate(content, 50),
})
return nil
}
chatID := message.Chat.ID
logger.InfoCF("telegram", "WebAppData command received", map[string]any{
"user_id": senderID,
"command": utils.Truncate(content, 80),
})
peerKind := "direct"
peerID := fmt.Sprintf("%d", user.ID)
if message.Chat.Type != "private" {
peerKind = "group"
peerID = fmt.Sprintf("%d", chatID)
}
metadata := map[string]string{
"message_id": fmt.Sprintf("%d", message.MessageID),
"user_id": fmt.Sprintf("%d", user.ID),
"username": user.Username,
"first_name": user.FirstName,
"is_group": fmt.Sprintf("%t", message.Chat.Type != "private"),
"peer_kind": peerKind,
"peer_id": peerID,
"source": "webapp",
}
c.HandleMessage(fmt.Sprintf("%d", user.ID), fmt.Sprintf("%d", chatID), content, nil, metadata)
return nil
}
func (c *TelegramChannel) downloadPhoto(ctx context.Context, fileID string) string { func (c *TelegramChannel) downloadPhoto(ctx context.Context, fileID string) string {
file, err := c.bot.GetFile(ctx, &telego.GetFileParams{FileID: fileID}) file, err := c.bot.GetFile(ctx, &telego.GetFileParams{FileID: fileID})
if err != nil { if err != nil {

View file

@ -206,6 +206,7 @@ type TelegramConfig struct {
Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_TELEGRAM_ENABLED"` Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_TELEGRAM_ENABLED"`
Token string `json:"token" env:"PICOCLAW_CHANNELS_TELEGRAM_TOKEN"` Token string `json:"token" env:"PICOCLAW_CHANNELS_TELEGRAM_TOKEN"`
Proxy string `json:"proxy" env:"PICOCLAW_CHANNELS_TELEGRAM_PROXY"` Proxy string `json:"proxy" env:"PICOCLAW_CHANNELS_TELEGRAM_PROXY"`
WebAppURL string `json:"web_app_url" env:"PICOCLAW_CHANNELS_TELEGRAM_WEB_APP_URL"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_TELEGRAM_ALLOW_FROM"` AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_TELEGRAM_ALLOW_FROM"`
} }

View file

@ -2,6 +2,7 @@ package health
import ( import (
"context" "context"
"crypto/tls"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
@ -11,6 +12,7 @@ import (
type Server struct { type Server struct {
server *http.Server server *http.Server
mux *http.ServeMux
mu sync.RWMutex mu sync.RWMutex
ready bool ready bool
checks map[string]Check checks map[string]Check
@ -33,6 +35,7 @@ type StatusResponse struct {
func NewServer(host string, port int) *Server { func NewServer(host string, port int) *Server {
mux := http.NewServeMux() mux := http.NewServeMux()
s := &Server{ s := &Server{
mux: mux,
ready: false, ready: false,
checks: make(map[string]Check), checks: make(map[string]Check),
startTime: time.Now(), startTime: time.Now(),
@ -52,6 +55,27 @@ func NewServer(host string, port int) *Server {
return s return s
} }
// Mux returns the underlying ServeMux so additional routes can be registered.
func (s *Server) Mux() *http.ServeMux {
return s.mux
}
// StartTLS starts the server with TLS using the provided certificate and key files.
func (s *Server) StartTLS(certFile, keyFile string) error {
s.mu.Lock()
s.ready = true
s.mu.Unlock()
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return fmt.Errorf("failed to load TLS cert: %w", err)
}
s.server.TLSConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
}
return s.server.ListenAndServeTLS("", "")
}
func (s *Server) Start() error { func (s *Server) Start() error {
s.mu.Lock() s.mu.Lock()
s.ready = true s.ready = true

160
pkg/miniapp/miniapp.go Normal file
View file

@ -0,0 +1,160 @@
package miniapp
import (
"crypto/hmac"
"crypto/sha256"
"embed"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/url"
"sort"
"strings"
"github.com/sipeed/picoclaw/pkg/skills"
"github.com/sipeed/picoclaw/pkg/stats"
)
//go:embed static/index.html
var staticFS embed.FS
// PlanPhase mirrors agent.PlanPhase for JSON serialization.
type PlanPhase struct {
Number int `json:"number"`
Title string `json:"title"`
Steps []PlanStep `json:"steps"`
}
// PlanStep mirrors agent.PlanStep for JSON serialization.
type PlanStep struct {
Index int `json:"index"`
Description string `json:"description"`
Done bool `json:"done"`
}
// PlanInfo represents the plan state exposed via the API.
type PlanInfo struct {
HasPlan bool `json:"has_plan"`
Status string `json:"status"`
CurrentPhase int `json:"current_phase"`
TotalPhases int `json:"total_phases"`
Display string `json:"display"`
Phases []PlanPhase `json:"phases"`
}
// DataProvider is the read-only interface to agent state for the Mini App API.
type DataProvider interface {
ListSkills() []skills.SkillInfo
GetPlanInfo() PlanInfo
GetSessionStats() *stats.Stats
}
// Handler serves the Mini App HTML and API endpoints.
type Handler struct {
provider DataProvider
botToken string
}
// NewHandler creates a new Mini App handler.
func NewHandler(provider DataProvider, botToken string) *Handler {
return &Handler{
provider: provider,
botToken: botToken,
}
}
// RegisterRoutes registers Mini App routes on the given mux.
func (h *Handler) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("/miniapp", h.serveIndex)
mux.HandleFunc("/miniapp/api/skills", h.requireAuth(h.apiSkills))
mux.HandleFunc("/miniapp/api/plan", h.requireAuth(h.apiPlan))
mux.HandleFunc("/miniapp/api/session", h.requireAuth(h.apiSession))
}
func (h *Handler) serveIndex(w http.ResponseWriter, r *http.Request) {
data, err := staticFS.ReadFile("static/index.html")
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(data)
}
func (h *Handler) requireAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
initData := r.URL.Query().Get("initData")
if initData == "" {
http.Error(w, `{"error":"missing initData"}`, http.StatusUnauthorized)
return
}
if !ValidateInitData(initData, h.botToken) {
http.Error(w, `{"error":"invalid initData"}`, http.StatusUnauthorized)
return
}
next(w, r)
}
}
func (h *Handler) apiSkills(w http.ResponseWriter, r *http.Request) {
skillsList := h.provider.ListSkills()
writeJSON(w, skillsList)
}
func (h *Handler) apiPlan(w http.ResponseWriter, r *http.Request) {
info := h.provider.GetPlanInfo()
writeJSON(w, info)
}
func (h *Handler) apiSession(w http.ResponseWriter, r *http.Request) {
s := h.provider.GetSessionStats()
if s == nil {
writeJSON(w, map[string]string{"status": "stats not enabled"})
return
}
writeJSON(w, s)
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(v)
}
// ValidateInitData verifies the Telegram WebApp initData HMAC-SHA256 signature.
// See https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app
func ValidateInitData(initData, botToken string) bool {
values, err := url.ParseQuery(initData)
if err != nil {
return false
}
receivedHash := values.Get("hash")
if receivedHash == "" {
return false
}
// Build the data-check-string: sort all key=value pairs except "hash",
// join with newlines.
var pairs []string
for key := range values {
if key == "hash" {
continue
}
pairs = append(pairs, fmt.Sprintf("%s=%s", key, values.Get(key)))
}
sort.Strings(pairs)
dataCheckString := strings.Join(pairs, "\n")
// secret_key = HMAC-SHA256("WebAppData", bot_token)
secretKeyMac := hmac.New(sha256.New, []byte("WebAppData"))
secretKeyMac.Write([]byte(botToken))
secretKey := secretKeyMac.Sum(nil)
// hash = HMAC-SHA256(secret_key, data_check_string)
hashMac := hmac.New(sha256.New, secretKey)
hashMac.Write([]byte(dataCheckString))
computedHash := hex.EncodeToString(hashMac.Sum(nil))
return hmac.Equal([]byte(computedHash), []byte(receivedHash))
}

View file

@ -0,0 +1,99 @@
package miniapp
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"net/url"
"sort"
"strings"
"testing"
)
// buildInitData constructs a valid initData string from params and a bot token.
func buildInitData(params map[string]string, botToken string) string {
// Build data-check-string
var pairs []string
for k, v := range params {
pairs = append(pairs, fmt.Sprintf("%s=%s", k, v))
}
sort.Strings(pairs)
dataCheckString := strings.Join(pairs, "\n")
// Compute secret key
secretKeyMac := hmac.New(sha256.New, []byte("WebAppData"))
secretKeyMac.Write([]byte(botToken))
secretKey := secretKeyMac.Sum(nil)
// Compute hash
hashMac := hmac.New(sha256.New, secretKey)
hashMac.Write([]byte(dataCheckString))
hash := hex.EncodeToString(hashMac.Sum(nil))
// Build query string
values := url.Values{}
for k, v := range params {
values.Set(k, v)
}
values.Set("hash", hash)
return values.Encode()
}
func TestValidateInitData(t *testing.T) {
botToken := "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
t.Run("valid initData", func(t *testing.T) {
params := map[string]string{
"query_id": "AAHdF6IQAAAAAN0XohDhrOrc",
"user": `{"id":279058397,"first_name":"Vlad"}`,
"auth_date": "1234567890",
}
initData := buildInitData(params, botToken)
if !ValidateInitData(initData, botToken) {
t.Error("ValidateInitData() returned false for valid data")
}
})
t.Run("tampered data", func(t *testing.T) {
params := map[string]string{
"query_id": "AAHdF6IQAAAAAN0XohDhrOrc",
"user": `{"id":279058397,"first_name":"Vlad"}`,
"auth_date": "1234567890",
}
initData := buildInitData(params, botToken)
// Tamper with the data
initData = strings.Replace(initData, "Vlad", "Evil", 1)
if ValidateInitData(initData, botToken) {
t.Error("ValidateInitData() returned true for tampered data")
}
})
t.Run("wrong bot token", func(t *testing.T) {
params := map[string]string{
"auth_date": "1234567890",
}
initData := buildInitData(params, botToken)
if ValidateInitData(initData, "wrong-token") {
t.Error("ValidateInitData() returned true for wrong bot token")
}
})
t.Run("missing hash", func(t *testing.T) {
if ValidateInitData("auth_date=1234567890", botToken) {
t.Error("ValidateInitData() returned true for missing hash")
}
})
t.Run("empty initData", func(t *testing.T) {
if ValidateInitData("", botToken) {
t.Error("ValidateInitData() returned true for empty initData")
}
})
t.Run("invalid query string", func(t *testing.T) {
if ValidateInitData("%%%invalid", botToken) {
t.Error("ValidateInitData() returned true for invalid query string")
}
})
}

View file

@ -0,0 +1,636 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>PicoClaw Dashboard</title>
<script src="https://telegram.org/js/telegram-web-app.js"></script>
<style>
:root {
--bg: var(--tg-theme-bg-color, #ffffff);
--text: var(--tg-theme-text-color, #000000);
--hint: var(--tg-theme-hint-color, #999999);
--link: var(--tg-theme-link-color, #2481cc);
--btn: var(--tg-theme-button-color, #2481cc);
--btn-text: var(--tg-theme-button-text-color, #ffffff);
--secondary-bg: var(--tg-theme-secondary-bg-color, #f0f0f0);
--done: #34c759;
--current: var(--btn);
--pending-phase: var(--hint);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: var(--bg);
color: var(--text);
font-size: 14px;
padding-bottom: 80px;
}
.tabs {
display: flex;
background: var(--secondary-bg);
position: sticky;
top: 0;
z-index: 10;
}
.tab {
flex: 1;
padding: 12px 4px;
text-align: center;
font-size: 13px;
font-weight: 500;
color: var(--hint);
border: none;
background: none;
cursor: pointer;
border-bottom: 2px solid transparent;
transition: all 0.2s;
}
.tab.active {
color: var(--btn);
border-bottom-color: var(--btn);
}
.panel { display: none; padding: 16px; }
.panel.active { display: block; }
.card {
background: var(--secondary-bg);
border-radius: 12px;
padding: 14px;
margin-bottom: 12px;
}
.card-title {
font-size: 13px;
color: var(--hint);
margin-bottom: 8px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.card-value {
font-size: 20px;
font-weight: 600;
}
/* Plan - phase/step list */
.phase {
margin-bottom: 16px;
}
.phase-header {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 0 6px;
font-weight: 600;
font-size: 14px;
}
.phase-indicator {
width: 22px;
height: 22px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 11px;
font-weight: 700;
color: #fff;
flex-shrink: 0;
}
.phase-indicator.done { background: var(--done); }
.phase-indicator.current { background: var(--current); }
.phase-indicator.pending { background: var(--pending-phase); }
.phase-title { flex: 1; }
.phase-progress {
font-size: 12px;
color: var(--hint);
font-weight: 400;
}
.step {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 8px 0 8px 30px;
border-bottom: 1px solid var(--secondary-bg);
cursor: pointer;
transition: opacity 0.15s;
}
.step:last-child { border-bottom: none; }
.step:active { opacity: 0.6; }
.step-check {
width: 20px;
height: 20px;
border-radius: 6px;
border: 2px solid var(--hint);
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
margin-top: 1px;
}
.step-check.done {
background: var(--done);
border-color: var(--done);
}
.step-check.done::after {
content: '';
width: 6px;
height: 10px;
border: solid #fff;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
margin-top: -2px;
}
.step-text {
flex: 1;
font-size: 14px;
line-height: 1.4;
}
.step-text.done {
color: var(--hint);
text-decoration: line-through;
}
/* Skills */
.skill-item {
background: var(--secondary-bg);
border-radius: 12px;
padding: 14px;
margin-bottom: 8px;
cursor: pointer;
transition: opacity 0.2s;
border-left: 3px solid transparent;
}
.skill-item:active { opacity: 0.7; }
.skill-item.selected { border-left-color: var(--btn); }
.skill-name {
font-weight: 600;
font-size: 15px;
margin-bottom: 4px;
}
.skill-desc {
font-size: 13px;
color: var(--hint);
line-height: 1.4;
}
.skill-source {
display: inline-block;
font-size: 11px;
padding: 2px 8px;
border-radius: 10px;
background: var(--btn);
color: var(--btn-text);
margin-top: 6px;
}
/* Stats */
.stat-row {
display: flex;
justify-content: space-between;
padding: 10px 0;
border-bottom: 1px solid var(--secondary-bg);
}
.stat-row:last-child { border-bottom: none; }
.stat-label { color: var(--hint); }
.stat-value { font-weight: 600; }
/* Send bar */
.send-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background: var(--bg);
padding: 12px 16px;
display: flex;
gap: 8px;
border-top: 1px solid var(--secondary-bg);
}
.send-input {
flex: 1;
padding: 10px 14px;
border-radius: 20px;
border: 1px solid var(--hint);
background: var(--bg);
color: var(--text);
font-size: 14px;
outline: none;
}
.send-input:focus { border-color: var(--btn); }
.send-btn {
padding: 10px 20px;
border-radius: 20px;
border: none;
background: var(--btn);
color: var(--btn-text);
font-size: 14px;
font-weight: 600;
cursor: pointer;
}
.send-btn:active { opacity: 0.8; }
.send-btn:disabled { opacity: 0.5; }
.empty-state {
text-align: center;
color: var(--hint);
padding: 40px 20px;
font-size: 14px;
}
.loading {
text-align: center;
color: var(--hint);
padding: 40px 20px;
}
.cmd-chips {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 12px;
}
.cmd-chip {
padding: 6px 14px;
border-radius: 16px;
border: 1px solid var(--hint);
background: var(--bg);
color: var(--text);
font-size: 13px;
cursor: pointer;
transition: all 0.2s;
}
.cmd-chip:active {
background: var(--btn);
color: var(--btn-text);
border-color: var(--btn);
}
.refresh-btn {
padding: 8px 16px;
border-radius: 8px;
border: 1px solid var(--hint);
background: var(--bg);
color: var(--text);
font-size: 13px;
cursor: pointer;
float: right;
margin-bottom: 8px;
}
.refresh-btn:active { opacity: 0.7; }
</style>
</head>
<body>
<div class="tabs">
<button class="tab active" data-panel="plan">Plan</button>
<button class="tab" data-panel="skills">Skills</button>
<button class="tab" data-panel="session">Session</button>
<button class="tab" data-panel="config">Config</button>
</div>
<div id="plan" class="panel active">
<div class="loading" id="plan-loading">Loading plan...</div>
<div id="plan-content" style="display:none"></div>
</div>
<div id="skills" class="panel">
<div class="loading" id="skills-loading">Loading skills...</div>
<div id="skills-list" style="display:none"></div>
</div>
<div id="session" class="panel">
<div class="loading" id="session-loading">Loading session...</div>
<div id="session-content" style="display:none"></div>
</div>
<div id="config" class="panel">
<div class="card">
<div class="card-title">Quick Commands</div>
<div class="cmd-chips">
<button class="cmd-chip" data-cmd="/session">/session</button>
<button class="cmd-chip" data-cmd="/skills">/skills</button>
<button class="cmd-chip" data-cmd="/todo">/todo</button>
<button class="cmd-chip" data-cmd="/plan status">/plan status</button>
</div>
</div>
<div class="card">
<div class="card-title">Custom Command</div>
<div style="display:flex;gap:8px;margin-top:8px">
<input id="custom-cmd" class="send-input" placeholder="/command args..." style="flex:1">
<button class="send-btn" onclick="sendCustomCmd()">Send</button>
</div>
</div>
</div>
<div class="send-bar" id="send-bar" style="display:none">
<input id="skill-msg" class="send-input" placeholder="Message for skill...">
<button class="send-btn" id="send-skill-btn" onclick="sendSkillCommand()">Send</button>
</div>
<script>
const tg = window.Telegram.WebApp;
tg.ready();
tg.expand();
const API_BASE = location.origin;
let initData = tg.initData || '';
let selectedSkill = null;
// Tab switching — always re-fetch data on tab switch
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', () => {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.panel').forEach(p => p.classList.remove('active'));
tab.classList.add('active');
document.getElementById(tab.dataset.panel).classList.add('active');
document.getElementById('send-bar').style.display =
tab.dataset.panel === 'skills' && selectedSkill ? 'flex' : 'none';
if (tab.dataset.panel === 'plan') loadPlan();
if (tab.dataset.panel === 'skills') loadSkills();
if (tab.dataset.panel === 'session') loadSession();
});
});
// Quick command chips
document.querySelectorAll('.cmd-chip').forEach(chip => {
chip.addEventListener('click', () => {
sendCommand(chip.dataset.cmd);
});
});
function sendCommand(cmd) {
if (!cmd.startsWith('/')) return;
try {
tg.sendData(cmd);
} catch (e) {
console.log('sendData:', cmd);
tg.showAlert('Command sent: ' + cmd);
}
}
function sendCustomCmd() {
const input = document.getElementById('custom-cmd');
const cmd = input.value.trim();
if (!cmd) return;
if (!cmd.startsWith('/')) {
tg.showAlert('Command must start with /');
return;
}
sendCommand(cmd);
input.value = '';
}
function sendSkillCommand() {
if (!selectedSkill) return;
const msg = document.getElementById('skill-msg').value.trim();
const cmd = msg ? '/skill ' + selectedSkill + ' ' + msg : '/skill ' + selectedSkill;
sendCommand(cmd);
}
async function apiFetch(path) {
const sep = path.includes('?') ? '&' : '?';
const res = await fetch(API_BASE + path + sep + 'initData=' + encodeURIComponent(initData));
if (!res.ok) throw new Error('API error: ' + res.status);
return res.json();
}
// ── Plan tab ──
async function loadPlan() {
const loading = document.getElementById('plan-loading');
const el = document.getElementById('plan-content');
loading.style.display = 'block';
loading.textContent = 'Loading plan...';
el.style.display = 'none';
try {
const data = await apiFetch('/miniapp/api/plan');
loading.style.display = 'none';
el.style.display = 'block';
if (!data.has_plan) {
el.innerHTML = '<div class="empty-state">No active plan.<br><br>Start one with /plan &lt;task&gt;</div>';
return;
}
let html = '';
// Status header card
html += '<div class="card">' +
'<div class="card-title">Status</div>' +
'<div class="card-value">' + escapeHtml(data.status) + '</div>' +
'<div style="color:var(--hint);margin-top:4px">Phase ' + data.current_phase + ' / ' + data.total_phases + '</div>' +
'</div>';
// Phase/step list
if (data.phases && data.phases.length > 0) {
html += renderPhases(data.phases, data.current_phase);
}
// Refresh button (in-app, not sendData)
html += '<button class="refresh-btn" onclick="loadPlan()">Refresh</button>';
el.innerHTML = html;
} catch (e) {
loading.textContent = 'Failed to load plan.';
loading.style.display = 'block';
el.style.display = 'none';
}
}
function renderPhases(phases, currentPhase) {
let html = '';
for (const phase of phases) {
const doneCount = phase.steps.filter(s => s.done).length;
const total = phase.steps.length;
let indicatorClass, indicator;
if (phase.number < currentPhase || (total > 0 && doneCount === total)) {
indicatorClass = 'done';
indicator = '\u2713';
} else if (phase.number === currentPhase) {
indicatorClass = 'current';
indicator = String(phase.number);
} else {
indicatorClass = 'pending';
indicator = String(phase.number);
}
html += '<div class="phase">';
html += '<div class="phase-header">';
html += '<div class="phase-indicator ' + indicatorClass + '">' + indicator + '</div>';
html += '<span class="phase-title">' + escapeHtml(phase.title || 'Phase ' + phase.number) + '</span>';
if (total > 0) {
html += '<span class="phase-progress">' + doneCount + '/' + total + '</span>';
}
html += '</div>';
// Steps
for (const step of phase.steps) {
const checkClass = step.done ? 'done' : '';
const textClass = step.done ? 'done' : '';
html += '<div class="step" data-phase="' + phase.number + '" data-step="' + step.index + '" data-done="' + step.done + '">';
html += '<div class="step-check ' + checkClass + '"></div>';
html += '<div class="step-text ' + textClass + '">' + escapeHtml(step.description) + '</div>';
html += '</div>';
}
html += '</div>';
}
return html;
}
// Delegate click on steps — tap to mark done (sends command, closes app)
document.getElementById('plan-content').addEventListener('click', function(e) {
const step = e.target.closest('.step');
if (!step) return;
if (step.dataset.done === 'true') return; // already done
const phase = step.dataset.phase;
const stepIdx = step.dataset.step;
sendCommand('/plan done ' + stepIdx);
});
// ── Skills tab ──
async function loadSkills() {
const loading = document.getElementById('skills-loading');
const el = document.getElementById('skills-list');
loading.style.display = 'block';
loading.textContent = 'Loading skills...';
el.style.display = 'none';
try {
const data = await apiFetch('/miniapp/api/skills');
loading.style.display = 'none';
el.style.display = 'block';
if (!data || data.length === 0) {
el.innerHTML = '<div class="empty-state">No skills installed.</div>';
return;
}
el.innerHTML = data.map(s =>
'<div class="skill-item" data-skill="' + escapeAttr(s.name) + '">' +
'<div class="skill-name">' + escapeHtml(s.name) + '</div>' +
'<div class="skill-desc">' + escapeHtml(s.description || 'No description') + '</div>' +
'<span class="skill-source">' + escapeHtml(s.source) + '</span>' +
'</div>'
).join('');
// Restore selection if still valid
if (selectedSkill) {
const prev = el.querySelector('[data-skill="' + CSS.escape(selectedSkill) + '"]');
if (prev) prev.classList.add('selected');
}
el.querySelectorAll('.skill-item').forEach(item => {
item.addEventListener('click', () => {
el.querySelectorAll('.skill-item').forEach(i => i.classList.remove('selected'));
item.classList.add('selected');
selectedSkill = item.dataset.skill;
document.getElementById('send-bar').style.display = 'flex';
document.getElementById('skill-msg').placeholder =
'Message for /' + selectedSkill + '...';
document.getElementById('skill-msg').focus();
});
});
} catch (e) {
loading.textContent = 'Failed to load skills.';
loading.style.display = 'block';
el.style.display = 'none';
}
}
// ── Session tab ──
async function loadSession() {
const loading = document.getElementById('session-loading');
const el = document.getElementById('session-content');
loading.style.display = 'block';
loading.textContent = 'Loading session...';
el.style.display = 'none';
try {
const data = await apiFetch('/miniapp/api/session');
loading.style.display = 'none';
el.style.display = 'block';
if (data.status === 'stats not enabled') {
el.innerHTML = '<div class="empty-state">Stats tracking not enabled.<br>Start gateway with --stats flag.</div>';
return;
}
const since = data.since ? new Date(data.since).toLocaleDateString() : 'N/A';
el.innerHTML =
'<div class="card">' +
'<div class="card-title">Today</div>' +
'<div class="stat-row"><span class="stat-label">Prompts</span><span class="stat-value">' + (data.today?.prompts || 0) + '</span></div>' +
'<div class="stat-row"><span class="stat-label">Requests</span><span class="stat-value">' + (data.today?.requests || 0) + '</span></div>' +
'<div class="stat-row"><span class="stat-label">Tokens</span><span class="stat-value">' + formatTokens(data.today?.total_tokens || 0) + '</span></div>' +
'</div>' +
'<div class="card">' +
'<div class="card-title">All Time (since ' + escapeHtml(since) + ')</div>' +
'<div class="stat-row"><span class="stat-label">Prompts</span><span class="stat-value">' + (data.total_prompts || 0) + '</span></div>' +
'<div class="stat-row"><span class="stat-label">Requests</span><span class="stat-value">' + (data.total_requests || 0) + '</span></div>' +
'<div class="stat-row"><span class="stat-label">Total Tokens</span><span class="stat-value">' + formatTokens(data.total_tokens || 0) + '</span></div>' +
'<div class="stat-row"><span class="stat-label">Prompt Tokens</span><span class="stat-value">' + formatTokens(data.total_prompt_tokens || 0) + '</span></div>' +
'<div class="stat-row"><span class="stat-label">Completion Tokens</span><span class="stat-value">' + formatTokens(data.total_completion_tokens || 0) + '</span></div>' +
'</div>';
} catch (e) {
loading.textContent = 'Failed to load session.';
loading.style.display = 'block';
el.style.display = 'none';
}
}
function formatTokens(n) {
if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M';
if (n >= 1000) return (n / 1000).toFixed(1) + 'K';
return String(n);
}
function escapeHtml(s) {
if (!s) return '';
return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
function escapeAttr(s) {
if (!s) return '';
return s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
// Initial load
loadPlan();
</script>
</body>
</html>

70
pkg/tailscale/detect.go Normal file
View file

@ -0,0 +1,70 @@
package tailscale
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
// tailscaleStatus is the subset of `tailscale status --json` we need.
type tailscaleStatus struct {
Self struct {
DNSName string `json:"DNSName"`
} `json:"Self"`
}
// DetectHostname runs `tailscale status --json` and returns the machine's
// MagicDNS hostname (e.g. "machine.tailnet.ts.net"), with the trailing dot
// stripped.
func DetectHostname() (string, error) {
out, err := exec.Command("tailscale", "status", "--json").Output()
if err != nil {
return "", fmt.Errorf("tailscale status failed: %w", err)
}
hostname, err := ParseHostname(out)
if err != nil {
return "", err
}
return hostname, nil
}
// ParseHostname extracts the hostname from `tailscale status --json` output.
func ParseHostname(jsonData []byte) (string, error) {
var status tailscaleStatus
if err := json.Unmarshal(jsonData, &status); err != nil {
return "", fmt.Errorf("failed to parse tailscale status: %w", err)
}
hostname := strings.TrimSuffix(status.Self.DNSName, ".")
if hostname == "" {
return "", fmt.Errorf("tailscale DNSName is empty")
}
return hostname, nil
}
// FetchCert runs `tailscale cert` to obtain a TLS certificate for the given
// hostname. Certificates are written to certDir. Returns paths to the cert
// and key files.
func FetchCert(hostname, certDir string) (certFile, keyFile string, err error) {
if err := os.MkdirAll(certDir, 0o700); err != nil {
return "", "", fmt.Errorf("failed to create cert dir: %w", err)
}
certFile = filepath.Join(certDir, hostname+".crt")
keyFile = filepath.Join(certDir, hostname+".key")
cmd := exec.Command("tailscale", "cert",
"--cert-file="+certFile,
"--key-file="+keyFile,
hostname,
)
if out, err := cmd.CombinedOutput(); err != nil {
return "", "", fmt.Errorf("tailscale cert failed: %w: %s", err, string(out))
}
return certFile, keyFile, nil
}

View file

@ -0,0 +1,59 @@
package tailscale
import (
"testing"
)
func TestParseHostname(t *testing.T) {
tests := []struct {
name string
json string
want string
wantErr bool
}{
{
name: "valid hostname with trailing dot",
json: `{"Self":{"DNSName":"mybox.tail1234.ts.net."}}`,
want: "mybox.tail1234.ts.net",
},
{
name: "valid hostname without trailing dot",
json: `{"Self":{"DNSName":"mybox.tail1234.ts.net"}}`,
want: "mybox.tail1234.ts.net",
},
{
name: "empty DNSName",
json: `{"Self":{"DNSName":""}}`,
wantErr: true,
},
{
name: "invalid JSON",
json: `not json`,
wantErr: true,
},
{
name: "missing Self field",
json: `{}`,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ParseHostname([]byte(tt.json))
if tt.wantErr {
if err == nil {
t.Errorf("ParseHostname() expected error, got %q", got)
}
return
}
if err != nil {
t.Errorf("ParseHostname() unexpected error: %v", err)
return
}
if got != tt.want {
t.Errorf("ParseHostname() = %q, want %q", got, tt.want)
}
})
}
}