package web import ( "context" "encoding/json" "errors" "net/http" "os" "path/filepath" "strconv" "strings" "sync" "time" "supermarket/internal/ai" "supermarket/internal/bridge" "supermarket/internal/core" "supermarket/internal/inventory" "supermarket/internal/profile" "supermarket/internal/secrets" ) // Connection is a social account the user signed in to. type Connection struct { Account string `json:"account"` At time.Time `json:"at"` } const connectionsKey = "connections" func (s *Server) connections() map[string]Connection { c := map[string]Connection{} if _, err := s.DB.GetJSON(connectionsKey, &c); err != nil { s.Log.Error("loading connections", "err", err) } return c } func (s *Server) saveConnection(provider string, c Connection) error { all := s.connections() all[provider] = c return s.DB.PutJSON(connectionsKey, all) } type step struct { Label string Done bool Detail string Link string } type module struct { Name, Phase, Body string } func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) { p, err := profile.Load(s.DB) if err != nil { s.serverError(w, err) return } entries, err := inventory.List(s.DB, "") if err != nil { s.serverError(w, err) return } counts := map[string]int{} for _, e := range entries { counts[e.Relationship]++ } aiCfg, err := ai.LoadConfig(s.DB) if err != nil { s.serverError(w, err) return } _, aiErr := ai.New(aiCfg, s.Secrets) last, err := bridge.Last(s.DB) if err != nil { s.serverError(w, err) return } conns := s.connections() steps := []step{ {Label: "Company profile", Done: p.IsSet(), Link: "/profile", Detail: ifElse(p.IsSet(), p.Name, "Describe the company, its products and its customers")}, {Label: "AI provider", Done: aiErr == nil, Link: "/settings/ai", Detail: ifElse(aiErr == nil, aiCfg.Provider+" ยท "+aiCfg.Model, "Choose Anthropic or a server on your network")}, {Label: "Inventory", Done: len(entries) > 0, Link: "/inventory", Detail: inventorySummary(counts)}, {Label: "Social accounts", Done: s.Secrets.Has(secrets.XAccessToken) || s.Secrets.Has(secrets.LinkedInAccessToken), Link: "/settings/credentials", Detail: s.connectionSummary(conns)}, {Label: "Federated Core", Done: s.Core != nil, Link: "/core", Detail: ifElse(s.Core != nil, coreDomain(s.Core), "No Core found; run `configure core` in CoreDesktop")}, {Label: "Hermes bridge", Done: last != nil, Link: "/core", Detail: ifElse(last != nil, "Last check-in "+ago(atOf(last)), "Hermes hasn't checked in yet")}, } modules := []module{ {"Content", "Phase 1", "Draft posts from partner and competitor news and your own products; review and publish to X, LinkedIn and Reddit."}, {"Prospects", "Phase 2", "Find companies and people who fit your targets, and add the ones you approve to EspoCRM through Hermes."}, {"SEO", "Phase 3", "Audit your websites and open fixes as pull requests on your Hugo repositories."}, {"Metrics", "Phase 4", "Pipeline influence, CAC, CLV and NRR from Stripe, EspoCRM and Plausible."}, {"Sites", "Phase 5", "Build pages and sites from a component library and publish them through Gitea."}, } var queued int _ = s.DB.QueryRow(`SELECT count(*) FROM posts`).Scan(&queued) s.render(w, r, "dashboard", page{Title: "Overview", Nav: "home", Data: map[string]any{ "Steps": steps, "Modules": modules, "ImportStatus": s.ImportStatus, "ImportErr": errString(s.ImportErr), "QueuedPosts": queued, }}) } func ifElse(cond bool, a, b string) string { if cond { return a } return b } func errString(err error) string { if err == nil { return "" } return err.Error() } func atOf(c *bridge.Checkin) time.Time { if c == nil { return time.Time{} } return c.At } func coreDomain(c *core.Core) string { if c == nil { return "" } return c.Domain } func inventorySummary(c map[string]int) string { if c[inventory.Partner]+c[inventory.Competitor]+c[inventory.Watch] == 0 { return "Add the partners and competitors you post about" } return plural(c[inventory.Partner], "partner") + ", " + plural(c[inventory.Competitor], "competitor") + ", " + plural(c[inventory.Watch], "watched") } func (s *Server) connectionSummary(c map[string]Connection) string { var parts []string if a := c["x"].Account; a != "" { parts = append(parts, "X @"+a) } else if s.Secrets.Has(secrets.XAccessToken) { parts = append(parts, "X") } if s.Secrets.Has(secrets.LinkedInAccessToken) { parts = append(parts, "LinkedIn") } if len(parts) == 0 { return "Connect X and LinkedIn" } return strings.Join(parts, ", ") } func plural(n int, word string) string { if word == "watched" { return strconv.Itoa(n) + " watched" } if n == 1 { return "1 " + word } return strconv.Itoa(n) + " " + word + "s" } // --- Core & Hermes --- type coreData struct { Core *core.Core User string HubURL string MCPURL string MCPSocket string MCPToken string Last *bridge.Checkin Prompt string HermesConfig string HermesEnv string } func (s *Server) corePage(w http.ResponseWriter, r *http.Request) { last, err := bridge.Last(s.DB) if err != nil { s.serverError(w, err) return } d := coreData{ Core: s.Core, MCPURL: "http://127.0.0.1:" + publicPort(s.PublicURL) + "/mcp", MCPToken: s.MCPToken, MCPSocket: s.MCPSocket, Last: last, Prompt: bridge.CheckinPrompt, } hub := "https://mcphub./sse?as_user=" if s.Core != nil { d.User = s.Core.User() hub = s.Core.MCPHubURL() } d.HubURL = hub d.HermesConfig = `mcp_servers: mcphub: url: "` + hub + `" transport: sse headers: Authorization: "Basic ${MCPHUB_AUTH}" supermarket: command: socat args: ["STDIO", "UNIX-CONNECT:` + d.MCPSocket + `"]` d.HermesEnv = `MCPHUB_AUTH=` s.render(w, r, "core", page{Title: "Core & Hermes", Nav: "core", Data: d}) } func publicPort(u string) string { if i := strings.LastIndex(u, ":"); i > strings.Index(u, "://")+2 { return strings.TrimRight(u[i+1:], "/") } return "8470" } type serviceCheck struct { Name, URL, Status string OK bool } // coreChecks asks each Core service whether it answers. It's an htmx // fragment, loaded after the page so a slow service doesn't hold it up. func (s *Server) coreChecks(w http.ResponseWriter, r *http.Request) { if s.Core == nil { s.fragment(w, "core", "checks", nil) return } services := s.Core.Services() checks := make([]serviceCheck, len(services)) client := &http.Client{ Timeout: 6 * time.Second, // A redirect (e.g. to a login page) means the service is there. CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, } var wg sync.WaitGroup for i, svc := range services { wg.Add(1) go func(i int, svc core.Service) { defer wg.Done() c := serviceCheck{Name: svc.Name, URL: svc.URL} ctx, cancel := context.WithTimeout(r.Context(), 6*time.Second) defer cancel() req, _ := http.NewRequestWithContext(ctx, http.MethodGet, svc.URL, nil) res, err := client.Do(req) switch { case err != nil: c.Status = "doesn't answer" var dnsErr interface{ Timeout() bool } if errors.As(err, &dnsErr) && dnsErr.Timeout() { c.Status = "timed out" } case res.StatusCode >= 500: c.Status = "error " + res.Status res.Body.Close() default: c.OK = true c.Status = "answers (" + res.Status + ")" res.Body.Close() } checks[i] = c }(i, svc) } wg.Wait() s.fragment(w, "core", "checks", checks) } // --- AI servers CoreDesktop found --- // AIServer is an LLM server from CoreDesktop's `configure ai-servers`, as // install.sh found it in opencode's settings. type AIServer struct { Name string `json:"name"` BaseURL string `json:"base_url"` } func (s *Server) aiServers() []AIServer { raw, err := os.ReadFile(filepath.Join(s.DataDir, "ai-servers.json")) if err != nil { return nil } var out []AIServer if err := json.Unmarshal(raw, &out); err != nil { s.Log.Warn("ai-servers.json", "err", err) return nil } return out } // secretState says whether a secret is set, for forms that never show values. func (s *Server) secretState(names ...string) map[string]bool { m := map[string]bool{} for _, n := range names { m[n] = s.Secrets.Has(n) } return m }