Merge branch 'worktree-add/telegram-miniapp'

This commit is contained in:
dj-oyu 2026-02-22 07:04:25 +09:00
commit 39aaacc1a1
14 changed files with 1616 additions and 45 deletions

View file

@ -306,6 +306,59 @@ Talk to your picoclaw through Telegram, Discord, DingTalk, LINE, or WeCom
picoclaw gateway picoclaw gateway
``` ```
#### Mini App (Dashboard)
PicoClaw includes a Telegram Mini App that provides a GUI dashboard directly inside Telegram. It shows plan progress, available skills, session stats, and lets you send commands without typing.
**How it works:**
When Telegram is enabled, PicoClaw automatically registers a "Dashboard" menu button in the chat. Tapping it opens the Mini App inside Telegram's WebView.
| Tab | Description |
|-----|-------------|
| **Plan** | View plan phases/steps as a checklist, tap to mark done, start new plans |
| **Skills** | Browse and invoke skills with a message input |
| **Session** | View token usage stats (requires `--stats` flag) |
| **Config** | Quick command buttons and custom command input |
**Setup — Tailscale (recommended for self-hosting):**
Telegram requires HTTPS for Mini Apps. The easiest way is to use [Tailscale](https://tailscale.com/) which provides automatic TLS certificates via MagicDNS.
1. Install Tailscale on both your server and phone
2. Allow cert provisioning (run once on the server):
```bash
sudo tailscale set --operator=$USER
```
3. Start the gateway — PicoClaw auto-detects the Tailscale hostname and fetches a TLS certificate:
```bash
picoclaw gateway --stats
```
You should see:
```
✓ Mini App registered at https://<machine>.<tailnet>.ts.net:18790/miniapp
```
> Your phone must also be connected to the same Tailnet to access the Mini App.
**Setup — Custom URL:**
If you already have an HTTPS endpoint (e.g., reverse proxy, Cloudflare Tunnel), set `web_app_url` manually:
```json
{
"channels": {
"telegram": {
"enabled": true,
"token": "YOUR_BOT_TOKEN",
"web_app_url": "https://your-domain.com/miniapp"
}
}
}
```
When `web_app_url` is set, PicoClaw skips Tailscale auto-detection and serves the Mini App over HTTP (your reverse proxy handles TLS).
</details> </details>
<details> <details>

View file

@ -21,20 +21,27 @@ 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"
) )
func gatewayCmd() { func gatewayCmd() {
// Check for --debug flag // Check for --debug and --stats flags
args := os.Args[2:] args := os.Args[2:]
enableStats := false
for _, arg := range args { for _, arg := range args {
if arg == "--debug" || arg == "-d" { if arg == "--debug" || arg == "-d" {
logger.SetLevel(logger.DEBUG) logger.SetLevel(logger.DEBUG)
fmt.Println("🔍 Debug mode enabled") fmt.Println("🔍 Debug mode enabled")
break }
if arg == "--stats" {
enableStats = true
} }
} }
@ -55,7 +62,7 @@ func gatewayCmd() {
} }
msgBus := bus.NewMessageBus() msgBus := bus.NewMessageBus()
agentLoop := agent.NewAgentLoop(cfg, msgBus, provider) agentLoop := agent.NewAgentLoop(cfg, msgBus, provider, enableStats)
// Print agent startup info // Print agent startup info
fmt.Println("\n📦 Agent Status:") fmt.Println("\n📦 Agent Status:")
@ -187,12 +194,56 @@ 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}
sender := &telegramCommandSender{bus: msgBus}
handler := miniapp.NewHandler(provider, sender, 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()})
} }
}() }()
fmt.Printf("✓ Health endpoints available at http://%s:%d/health and /ready\n", cfg.Gateway.Host, cfg.Gateway.Port) 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)
}
go agentLoop.Run(ctx) go agentLoop.Run(ctx)
@ -236,3 +287,65 @@ 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()
}
// telegramCommandSender injects Mini App commands into the message bus.
type telegramCommandSender struct {
bus *bus.MessageBus
}
func (s *telegramCommandSender) SendCommand(senderID, chatID, command string) {
s.bus.PublishInbound(bus.InboundMessage{
Channel: "telegram",
SenderID: senderID,
ChatID: chatID,
Content: command,
Metadata: map[string]string{
"source": "webapp",
},
})
}

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

@ -1948,6 +1948,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 {
return false for _, s := range p.Steps {
hasSteps = true
if !s.Done {
return false
}
}
} }
// No unchecked steps return hasSteps
return !reStepTodo.MatchString(content)
} }
// 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 {
return false if p.Number == current {
if len(p.Steps) == 0 {
return false
}
for _, s := range p.Steps {
if !s.Done {
return false
}
}
return true
}
} }
// Must have at least one step return false
if !reStepDone.MatchString(phaseContent) && !reStepTodo.MatchString(phaseContent) {
return false
}
return !reStepTodo.MatchString(phaseContent)
} }
// 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

@ -203,10 +203,11 @@ type WhatsAppConfig struct {
} }
type TelegramConfig struct { 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"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_TELEGRAM_ALLOW_FROM"` WebAppURL string `json:"web_app_url" env:"PICOCLAW_CHANNELS_TELEGRAM_WEB_APP_URL"`
AllowFrom FlexibleStringSlice `json:"allow_from" env:"PICOCLAW_CHANNELS_TELEGRAM_ALLOW_FROM"`
} }
type FeishuConfig struct { type FeishuConfig struct {

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

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

@ -0,0 +1,228 @@
package miniapp
import (
"crypto/hmac"
"crypto/sha256"
"embed"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"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
}
// CommandSender injects a command into the message bus on behalf of a user.
type CommandSender interface {
SendCommand(senderID, chatID, command string)
}
// Handler serves the Mini App HTML and API endpoints.
type Handler struct {
provider DataProvider
sender CommandSender
botToken string
}
// NewHandler creates a new Mini App handler.
func NewHandler(provider DataProvider, sender CommandSender, botToken string) *Handler {
return &Handler{
provider: provider,
sender: sender,
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))
mux.HandleFunc("/miniapp/api/command", h.requireAuth(h.apiCommand))
}
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 (h *Handler) apiCommand(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, 4096))
if err != nil {
http.Error(w, `{"error":"bad request"}`, http.StatusBadRequest)
return
}
var req struct {
Command string `json:"command"`
}
if err := json.Unmarshal(body, &req); err != nil || req.Command == "" {
http.Error(w, `{"error":"missing command"}`, http.StatusBadRequest)
return
}
if !strings.HasPrefix(req.Command, "/") {
http.Error(w, `{"error":"command must start with /"}`, http.StatusBadRequest)
return
}
// Extract user ID from initData to identify the sender
initData := r.URL.Query().Get("initData")
userID, chatID := extractUserFromInitData(initData)
if userID == "" {
http.Error(w, `{"error":"cannot identify user"}`, http.StatusBadRequest)
return
}
h.sender.SendCommand(userID, chatID, req.Command)
writeJSON(w, map[string]string{"status": "ok"})
}
// extractUserFromInitData parses user.id from the initData query string.
// initData contains a "user" param with JSON like {"id":123456,...}.
func extractUserFromInitData(initData string) (userID, chatID string) {
values, err := url.ParseQuery(initData)
if err != nil {
return "", ""
}
userJSON := values.Get("user")
if userJSON == "" {
return "", ""
}
var user struct {
ID int64 `json:"id"`
}
if err := json.Unmarshal([]byte(userJSON), &user); err != nil || user.ID == 0 {
return "", ""
}
id := fmt.Sprintf("%d", user.ID)
// For Mini App commands, chatID = userID (private chat)
return id, id
}
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,720 @@
<!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);
}
@media (prefers-color-scheme: dark) {
:root {
--bg: var(--tg-theme-bg-color, #1c1c1e);
--text: var(--tg-theme-text-color, #ffffff);
--hint: var(--tg-theme-hint-color, #8e8e93);
--link: var(--tg-theme-link-color, #5ac8fa);
--btn: var(--tg-theme-button-color, #5ac8fa);
--btn-text: var(--tg-theme-button-text-color, #ffffff);
--secondary-bg: var(--tg-theme-secondary-bg-color, #2c2c2e);
}
}
* { 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: 10px 12px 10px 30px;
margin-bottom: 4px;
border-radius: 8px;
cursor: pointer;
transition: all 0.15s;
}
.step:active { transform: scale(0.97); }
.step:not(.step-done) { background: var(--secondary-bg); }
.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: linear-gradient(to bottom, var(--bg), var(--secondary-bg));
border-radius: 12px;
padding: 14px 14px 14px 16px;
margin-bottom: 10px;
cursor: pointer;
transition: all 0.12s;
border: 1px solid var(--hint);
display: flex;
align-items: center;
gap: 12px;
box-shadow: 0 2px 4px rgba(0,0,0,0.08), 0 1px 0 rgba(255,255,255,0.06) inset;
}
.skill-item:active {
transform: scale(0.98) translateY(1px);
box-shadow: 0 0 2px rgba(0,0,0,0.06);
}
.skill-item.selected { border-color: var(--btn); box-shadow: 0 2px 6px rgba(0,0,0,0.12); }
.skill-body { flex: 1; min-width: 0; }
.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;
}
.skill-arrow {
color: var(--hint);
font-size: 22px;
flex-shrink: 0;
transition: color 0.15s;
}
.skill-item.selected .skill-arrow { color: var(--btn); }
/* 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; }
.send-btn.sent { background: var(--done); transition: background 0.15s; }
.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-tiles {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.cmd-tile {
padding: 16px 14px;
border-radius: 12px;
border: 1px solid var(--hint);
background: linear-gradient(to bottom, var(--bg), var(--secondary-bg));
color: var(--text);
font-size: 15px;
font-weight: 600;
cursor: pointer;
transition: all 0.12s;
text-align: center;
box-shadow: 0 2px 4px rgba(0,0,0,0.1), 0 1px 0 rgba(255,255,255,0.06) inset;
}
.cmd-tile:active {
transform: scale(0.96) translateY(1px);
box-shadow: 0 0 2px rgba(0,0,0,0.08);
background: var(--secondary-bg);
}
.cmd-tile.sent {
background: var(--btn);
color: var(--btn-text);
border-color: var(--btn);
box-shadow: 0 2px 4px rgba(0,0,0,0.15);
transition: all 0.15s;
}
.refresh-btn {
display: block;
width: 100%;
padding: 12px 16px;
border-radius: 12px;
border: 1px solid var(--hint);
background: linear-gradient(to bottom, var(--bg), var(--secondary-bg));
color: var(--text);
font-size: 14px;
cursor: pointer;
margin-top: 8px;
transition: all 0.12s;
box-shadow: 0 2px 4px rgba(0,0,0,0.08);
}
.refresh-btn:active {
transform: scale(0.98) translateY(1px);
box-shadow: 0 0 2px rgba(0,0,0,0.06);
}
</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-tiles">
<button class="cmd-tile" data-cmd="/session">/session</button>
<button class="cmd-tile" data-cmd="/skills">/skills</button>
<button class="cmd-tile" data-cmd="/plan clear">/plan clear</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 tiles
document.querySelectorAll('.cmd-tile').forEach(tile => {
tile.addEventListener('click', async () => {
const ok = await sendCommand(tile.dataset.cmd);
if (ok) flashSent(tile);
});
});
async function sendCommand(cmd) {
if (!cmd.startsWith('/')) return false;
try {
const res = await fetch(API_BASE + '/miniapp/api/command?initData=' + encodeURIComponent(initData), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ command: cmd }),
});
if (!res.ok) throw new Error('API error: ' + res.status);
return true;
} catch (e) {
return false;
}
}
async function sendCustomCmd() {
const input = document.getElementById('custom-cmd');
const btn = input.nextElementSibling;
const cmd = input.value.trim();
if (!cmd) return;
if (!cmd.startsWith('/')) return;
const ok = await sendCommand(cmd);
if (ok) {
input.value = '';
flashSent(btn);
}
}
async function sendSkillCommand() {
if (!selectedSkill) return;
const msg = document.getElementById('skill-msg').value.trim();
const cmd = msg ? '/skill ' + selectedSkill + ' ' + msg : '/skill ' + selectedSkill;
const btn = document.getElementById('send-skill-btn');
const ok = await sendCommand(cmd);
if (ok) flashSent(btn);
}
async function startPlan() {
const input = document.getElementById('plan-task');
const btn = input.nextElementSibling;
const task = input.value.trim();
if (!task) return;
const ok = await sendCommand('/plan ' + task);
if (ok) {
input.value = '';
flashSent(btn);
}
}
function flashSent(el) {
el.classList.add('sent');
setTimeout(() => el.classList.remove('sent'), 600);
}
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.</div>' +
'<div class="card" style="margin-top:16px">' +
'<div class="card-title">Start a Plan</div>' +
'<div style="display:flex;gap:8px;margin-top:8px">' +
'<input id="plan-task" class="send-input" placeholder="Describe your task...">' +
'<button class="send-btn" onclick="startPlan()">Start</button>' +
'</div>' +
'</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' : '';
const stepClass = step.done ? 'step step-done' : 'step';
html += '<div class="' + stepClass + '" 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-body">' +
'<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>' +
'<span class="skill-arrow">\u203A</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)
}
})
}
}