3 Commits

50 changed files with 272 additions and 1084 deletions

View File

@@ -55,10 +55,10 @@ curl -fsSL https://raw.githubusercontent.com/YspCoder/clawgo/main/install.sh | b
clawgo onboard
```
### 3) 配置模型
### 3) 配置 Provider
```bash
clawgo login
clawgo provider
```
### 4) 看状态
@@ -118,7 +118,7 @@ http://<host>:<port>/webui?token=<gateway.token>
```text
clawgo onboard
clawgo login
clawgo provider
clawgo status
clawgo agent [-m "..."]
clawgo gateway [run|start|stop|restart|status]

View File

@@ -55,10 +55,10 @@ curl -fsSL https://raw.githubusercontent.com/YspCoder/clawgo/main/install.sh | b
clawgo onboard
```
### 3) Configure model/proxy
### 3) Configure provider
```bash
clawgo login
clawgo provider
```
### 4) Check status
@@ -118,7 +118,7 @@ Main pages:
```text
clawgo onboard
clawgo login
clawgo provider
clawgo status
clawgo agent [-m "..."]
clawgo gateway [run|start|stop|restart|status]

View File

@@ -92,6 +92,7 @@ func printHelp() {
fmt.Println(" agent Interact with the agent directly")
fmt.Println(" gateway Register/manage gateway service")
fmt.Println(" status Show clawgo status")
fmt.Println(" provider Configure provider credentials")
fmt.Println(" config Get/set config values")
fmt.Println(" cron Manage scheduled tasks")
fmt.Println(" channel Test and manage messaging channels")

View File

@@ -5,6 +5,8 @@ import (
"encoding/json"
"fmt"
"os"
"sort"
"strconv"
"strings"
"clawgo/pkg/config"
@@ -26,8 +28,6 @@ func configCmd() {
configCheckCmd()
case "reload":
configReloadCmd()
case "login":
configLoginCmd()
default:
fmt.Printf("Unknown config command: %s\n", os.Args[2])
configHelp()
@@ -171,35 +171,216 @@ func configCheckCmd() {
}
}
func configLoginCmd() {
func providerCmd() {
cfg, err := loadConfig()
if err != nil {
fmt.Printf("Error loading config: %v\n", err)
os.Exit(1)
}
fmt.Println("Configuring CLIProxyAPI...")
fmt.Printf("Current Base: %s\n", cfg.Providers.Proxy.APIBase)
fmt.Print("Enter CLIProxyAPI Base URL (e.g. http://localhost:8080/v1): ")
reader := bufio.NewReader(os.Stdin)
line, _ := reader.ReadString('\n')
apiBase := strings.TrimSpace(line)
if apiBase != "" {
cfg.Providers.Proxy.APIBase = apiBase
defaultProxy := strings.TrimSpace(cfg.Agents.Defaults.Proxy)
if defaultProxy == "" {
defaultProxy = "proxy"
}
available := providerNames(cfg)
fmt.Printf("Current default provider: %s\n", defaultProxy)
fmt.Printf("Available providers: %s\n", strings.Join(available, ", "))
argName := ""
if len(os.Args) >= 3 {
argName = strings.TrimSpace(os.Args[2])
}
if argName == "" || strings.HasPrefix(argName, "-") {
argName = defaultProxy
}
providerName := promptLine(reader, "Provider name to configure", argName)
if providerName == "" {
providerName = defaultProxy
}
fmt.Print("Enter API Key (optional): ")
fmt.Scanln(&cfg.Providers.Proxy.APIKey)
pc := providerConfigByName(cfg, providerName)
if pc.TimeoutSec <= 0 {
pc.TimeoutSec = 90
}
if strings.TrimSpace(pc.Auth) == "" {
pc.Auth = "bearer"
}
if len(pc.Models) == 0 {
pc.Models = append([]string{}, cfg.Providers.Proxy.Models...)
}
if len(pc.Models) == 0 {
pc.Models = []string{"glm-4.7"}
}
pc.APIBase = promptLine(reader, "api_base", pc.APIBase)
apiKey := promptLine(reader, "api_key (leave empty to keep current)", "")
if apiKey != "" {
pc.APIKey = apiKey
}
modelsRaw := promptLine(reader, "models (comma-separated)", strings.Join(pc.Models, ","))
if models := parseCSV(modelsRaw); len(models) > 0 {
pc.Models = models
}
pc.Auth = promptLine(reader, "auth (bearer/oauth/none)", pc.Auth)
timeoutRaw := promptLine(reader, "timeout_sec", fmt.Sprintf("%d", pc.TimeoutSec))
pc.TimeoutSec = parseIntOrDefault(timeoutRaw, pc.TimeoutSec)
pc.SupportsResponsesCompact = promptBool(reader, "supports_responses_compact", pc.SupportsResponsesCompact)
setProviderConfigByName(cfg, providerName, pc)
makeDefault := promptBool(reader, fmt.Sprintf("Set %s as agents.defaults.proxy", providerName), providerName == defaultProxy)
if makeDefault {
cfg.Agents.Defaults.Proxy = providerName
}
currentFallbacks := strings.Join(cfg.Agents.Defaults.ProxyFallbacks, ",")
fallbackRaw := promptLine(reader, "agents.defaults.proxy_fallbacks (comma-separated names)", currentFallbacks)
fallbacks := parseCSV(fallbackRaw)
valid := map[string]struct{}{}
for _, name := range providerNames(cfg) {
valid[name] = struct{}{}
}
filteredFallbacks := make([]string, 0, len(fallbacks))
seen := map[string]struct{}{}
defaultName := strings.TrimSpace(cfg.Agents.Defaults.Proxy)
for _, fb := range fallbacks {
if fb == "" || fb == defaultName {
continue
}
if _, ok := valid[fb]; !ok {
fmt.Printf("Skip unknown fallback provider: %s\n", fb)
continue
}
if _, ok := seen[fb]; ok {
continue
}
seen[fb] = struct{}{}
filteredFallbacks = append(filteredFallbacks, fb)
}
cfg.Agents.Defaults.ProxyFallbacks = filteredFallbacks
if err := config.SaveConfig(getConfigPath(), cfg); err != nil {
fmt.Printf("Error saving config: %v\n", err)
os.Exit(1)
}
fmt.Println("✓ CLIProxyAPI configuration saved.")
fmt.Println("✓ Provider configuration saved.")
running, err := triggerGatewayReload()
if err != nil {
if running {
fmt.Printf("Hot reload not applied: %v\n", err)
return
}
fmt.Printf("Gateway not running, reload skipped: %v\n", err)
return
}
fmt.Println("✓ Gateway hot reload signal sent")
}
func providerNames(cfg *config.Config) []string {
names := []string{"proxy"}
for k := range cfg.Providers.Proxies {
k = strings.TrimSpace(k)
if k == "" {
continue
}
names = append(names, k)
}
sort.Strings(names)
return names
}
func providerConfigByName(cfg *config.Config, name string) config.ProviderConfig {
name = strings.TrimSpace(name)
if name == "" || name == "proxy" {
return cfg.Providers.Proxy
}
if cfg.Providers.Proxies != nil {
if pc, ok := cfg.Providers.Proxies[name]; ok {
return pc
}
}
return config.ProviderConfig{
APIBase: cfg.Providers.Proxy.APIBase,
TimeoutSec: cfg.Providers.Proxy.TimeoutSec,
Auth: cfg.Providers.Proxy.Auth,
Models: append([]string{}, cfg.Providers.Proxy.Models...),
}
}
func setProviderConfigByName(cfg *config.Config, name string, pc config.ProviderConfig) {
name = strings.TrimSpace(name)
if name == "" || name == "proxy" {
cfg.Providers.Proxy = pc
return
}
if cfg.Providers.Proxies == nil {
cfg.Providers.Proxies = map[string]config.ProviderConfig{}
}
cfg.Providers.Proxies[name] = pc
}
func promptLine(reader *bufio.Reader, label, defaultValue string) string {
label = strings.TrimSpace(label)
if defaultValue != "" {
fmt.Printf("%s [%s]: ", label, defaultValue)
} else {
fmt.Printf("%s: ", label)
}
line, _ := reader.ReadString('\n')
line = strings.TrimSpace(line)
if line == "" {
return defaultValue
}
return line
}
func promptBool(reader *bufio.Reader, label string, defaultValue bool) bool {
def := "N"
if defaultValue {
def = "Y"
}
raw := promptLine(reader, label+" (y/n)", def)
switch strings.ToLower(strings.TrimSpace(raw)) {
case "y", "yes", "true", "1":
return true
case "n", "no", "false", "0":
return false
default:
return defaultValue
}
}
func parseCSV(raw string) []string {
parts := strings.Split(raw, ",")
out := make([]string, 0, len(parts))
seen := map[string]struct{}{}
for _, p := range parts {
v := strings.TrimSpace(p)
if v == "" {
continue
}
if _, ok := seen[v]; ok {
continue
}
seen[v] = struct{}{}
out = append(out, v)
}
return out
}
func parseIntOrDefault(raw string, def int) int {
raw = strings.TrimSpace(raw)
if raw == "" {
return def
}
v, err := strconv.Atoi(raw)
if err != nil || v <= 0 {
return def
}
return v
}
func loadConfigAsMap(path string) (map[string]interface{}, error) {
return configops.LoadConfigAsMap(path)

View File

@@ -14,6 +14,7 @@ import (
"time"
"clawgo/pkg/agent"
"clawgo/pkg/api"
"clawgo/pkg/autonomy"
"clawgo/pkg/bus"
"clawgo/pkg/channels"
@@ -140,7 +141,7 @@ func gatewayCmd() {
fmt.Printf("Error starting channels: %v\n", err)
}
registryServer := nodes.NewRegistryServer(cfg.Gateway.Host, cfg.Gateway.Port, cfg.Gateway.Token, nodes.DefaultManager())
registryServer := api.NewServer(cfg.Gateway.Host, cfg.Gateway.Port, cfg.Gateway.Token, nodes.DefaultManager())
registryServer.SetConfigPath(getConfigPath())
registryServer.SetWorkspacePath(cfg.WorkspacePath())
registryServer.SetLogFilePath(cfg.LogFilePath())

View File

@@ -59,6 +59,8 @@ func main() {
gatewayCmd()
case "status":
statusCmd()
case "provider":
providerCmd()
case "config":
configCmd()
case "cron":

12
pkg/api/reload_unix.go Normal file
View File

@@ -0,0 +1,12 @@
//go:build !windows
package api
import (
"os"
"syscall"
)
func requestSelfReloadSignal() error {
return syscall.Kill(os.Getpid(), syscall.SIGHUP)
}

View File

@@ -0,0 +1,8 @@
//go:build windows
package api
// requestSelfReloadSignal is a no-op on Windows (no SIGHUP semantics).
func requestSelfReloadSignal() error {
return nil
}

View File

@@ -1,4 +1,4 @@
package nodes
package api
import (
"archive/tar"
@@ -27,12 +27,13 @@ import (
"time"
cfgpkg "clawgo/pkg/config"
"clawgo/pkg/nodes"
)
type RegistryServer struct {
type Server struct {
addr string
token string
mgr *Manager
mgr *nodes.Manager
server *http.Server
configPath string
workspacePath string
@@ -49,7 +50,7 @@ type RegistryServer struct {
ekgCacheRows []map[string]interface{}
}
func NewRegistryServer(host string, port int, token string, mgr *Manager) *RegistryServer {
func NewServer(host string, port int, token string, mgr *nodes.Manager) *Server {
addr := strings.TrimSpace(host)
if addr == "" {
addr = "0.0.0.0"
@@ -57,25 +58,25 @@ func NewRegistryServer(host string, port int, token string, mgr *Manager) *Regis
if port <= 0 {
port = 7788
}
return &RegistryServer{addr: fmt.Sprintf("%s:%d", addr, port), token: strings.TrimSpace(token), mgr: mgr}
return &Server{addr: fmt.Sprintf("%s:%d", addr, port), token: strings.TrimSpace(token), mgr: mgr}
}
func (s *RegistryServer) SetConfigPath(path string) { s.configPath = strings.TrimSpace(path) }
func (s *RegistryServer) SetWorkspacePath(path string) { s.workspacePath = strings.TrimSpace(path) }
func (s *RegistryServer) SetLogFilePath(path string) { s.logFilePath = strings.TrimSpace(path) }
func (s *RegistryServer) SetChatHandler(fn func(ctx context.Context, sessionKey, content string) (string, error)) {
func (s *Server) SetConfigPath(path string) { s.configPath = strings.TrimSpace(path) }
func (s *Server) SetWorkspacePath(path string) { s.workspacePath = strings.TrimSpace(path) }
func (s *Server) SetLogFilePath(path string) { s.logFilePath = strings.TrimSpace(path) }
func (s *Server) SetChatHandler(fn func(ctx context.Context, sessionKey, content string) (string, error)) {
s.onChat = fn
}
func (s *RegistryServer) SetChatHistoryHandler(fn func(sessionKey string) []map[string]interface{}) {
func (s *Server) SetChatHistoryHandler(fn func(sessionKey string) []map[string]interface{}) {
s.onChatHistory = fn
}
func (s *RegistryServer) SetConfigAfterHook(fn func()) { s.onConfigAfter = fn }
func (s *RegistryServer) SetCronHandler(fn func(action string, args map[string]interface{}) (interface{}, error)) {
func (s *Server) SetConfigAfterHook(fn func()) { s.onConfigAfter = fn }
func (s *Server) SetCronHandler(fn func(action string, args map[string]interface{}) (interface{}, error)) {
s.onCron = fn
}
func (s *RegistryServer) SetWebUIDir(dir string) { s.webUIDir = strings.TrimSpace(dir) }
func (s *Server) SetWebUIDir(dir string) { s.webUIDir = strings.TrimSpace(dir) }
func (s *RegistryServer) Start(ctx context.Context) error {
func (s *Server) Start(ctx context.Context) error {
if s.mgr == nil {
return nil
}
@@ -104,7 +105,6 @@ func (s *RegistryServer) Start(ctx context.Context) error {
mux.HandleFunc("/webui/api/tasks", s.handleWebUITasks)
mux.HandleFunc("/webui/api/task_daily_summary", s.handleWebUITaskDailySummary)
mux.HandleFunc("/webui/api/ekg_stats", s.handleWebUIEKGStats)
mux.HandleFunc("/webui/api/office_state", s.handleWebUIOfficeState)
mux.HandleFunc("/webui/api/exec_approvals", s.handleWebUIExecApprovals)
mux.HandleFunc("/webui/api/logs/stream", s.handleWebUILogsStream)
mux.HandleFunc("/webui/api/logs/recent", s.handleWebUILogsRecent)
@@ -119,7 +119,7 @@ func (s *RegistryServer) Start(ctx context.Context) error {
return nil
}
func (s *RegistryServer) handleRegister(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
@@ -128,7 +128,7 @@ func (s *RegistryServer) handleRegister(w http.ResponseWriter, r *http.Request)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
var n NodeInfo
var n nodes.NodeInfo
if err := json.NewDecoder(r.Body).Decode(&n); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
@@ -142,7 +142,7 @@ func (s *RegistryServer) handleRegister(w http.ResponseWriter, r *http.Request)
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "id": n.ID})
}
func (s *RegistryServer) handleHeartbeat(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleHeartbeat(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
@@ -170,7 +170,7 @@ func (s *RegistryServer) handleHeartbeat(w http.ResponseWriter, r *http.Request)
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "id": body.ID})
}
func (s *RegistryServer) handleWebUI(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUI(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
@@ -196,7 +196,7 @@ func (s *RegistryServer) handleWebUI(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(webUIHTML))
}
func (s *RegistryServer) handleWebUIAsset(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUIAsset(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
@@ -215,7 +215,7 @@ func (s *RegistryServer) handleWebUIAsset(w http.ResponseWriter, r *http.Request
http.NotFound(w, r)
}
func (s *RegistryServer) tryServeWebUIDist(w http.ResponseWriter, r *http.Request, reqPath string) bool {
func (s *Server) tryServeWebUIDist(w http.ResponseWriter, r *http.Request, reqPath string) bool {
dir := strings.TrimSpace(s.webUIDir)
if dir == "" {
return false
@@ -237,7 +237,7 @@ func (s *RegistryServer) tryServeWebUIDist(w http.ResponseWriter, r *http.Reques
return true
}
func (s *RegistryServer) handleWebUIConfig(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUIConfig(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -404,7 +404,7 @@ func getPathValue(m map[string]interface{}, path string) interface{} {
return cur
}
func (s *RegistryServer) handleWebUIUpload(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUIUpload(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -440,7 +440,7 @@ func (s *RegistryServer) handleWebUIUpload(w http.ResponseWriter, r *http.Reques
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "path": path, "name": h.Filename})
}
func (s *RegistryServer) handleWebUIChat(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUIChat(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -484,7 +484,7 @@ func (s *RegistryServer) handleWebUIChat(w http.ResponseWriter, r *http.Request)
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "reply": resp, "session": session})
}
func (s *RegistryServer) handleWebUIChatHistory(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUIChatHistory(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -504,7 +504,7 @@ func (s *RegistryServer) handleWebUIChatHistory(w http.ResponseWriter, r *http.R
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "session": session, "messages": s.onChatHistory(session)})
}
func (s *RegistryServer) handleWebUIChatStream(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUIChatStream(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -566,7 +566,7 @@ func (s *RegistryServer) handleWebUIChatStream(w http.ResponseWriter, r *http.Re
}
}
func (s *RegistryServer) handleWebUIVersion(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUIVersion(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -582,19 +582,19 @@ func (s *RegistryServer) handleWebUIVersion(w http.ResponseWriter, r *http.Reque
})
}
func (s *RegistryServer) handleWebUINodes(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUINodes(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
switch r.Method {
case http.MethodGet:
list := []NodeInfo{}
list := []nodes.NodeInfo{}
if s.mgr != nil {
list = s.mgr.List()
}
host, _ := os.Hostname()
local := NodeInfo{ID: "local", Name: "local", Endpoint: "gateway", Version: gatewayBuildVersion(), LastSeenAt: time.Now(), Online: true}
local := nodes.NodeInfo{ID: "local", Name: "local", Endpoint: "gateway", Version: gatewayBuildVersion(), LastSeenAt: time.Now(), Online: true}
if strings.TrimSpace(host) != "" {
local.Name = host
}
@@ -623,7 +623,7 @@ func (s *RegistryServer) handleWebUINodes(w http.ResponseWriter, r *http.Request
}
}
if !matched {
list = append([]NodeInfo{local}, list...)
list = append([]nodes.NodeInfo{local}, list...)
}
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "nodes": list})
case http.MethodPost:
@@ -652,7 +652,7 @@ func (s *RegistryServer) handleWebUINodes(w http.ResponseWriter, r *http.Request
}
}
func (s *RegistryServer) handleWebUICron(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUICron(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -702,7 +702,7 @@ func (s *RegistryServer) handleWebUICron(w http.ResponseWriter, r *http.Request)
}
}
func (s *RegistryServer) handleWebUISkills(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUISkills(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -1802,7 +1802,7 @@ func anyToString(v interface{}) string {
}
}
func (s *RegistryServer) handleWebUISessions(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUISessions(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -1850,7 +1850,7 @@ func (s *RegistryServer) handleWebUISessions(w http.ResponseWriter, r *http.Requ
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "sessions": out})
}
func (s *RegistryServer) handleWebUIMemory(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUIMemory(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -1925,7 +1925,7 @@ func (s *RegistryServer) handleWebUIMemory(w http.ResponseWriter, r *http.Reques
}
}
func (s *RegistryServer) handleWebUITaskAudit(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUITaskAudit(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -2041,7 +2041,7 @@ func (s *RegistryServer) handleWebUITaskAudit(w http.ResponseWriter, r *http.Req
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "items": items})
}
func (s *RegistryServer) handleWebUITaskQueue(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUITaskQueue(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -2258,7 +2258,7 @@ func (s *RegistryServer) handleWebUITaskQueue(w http.ResponseWriter, r *http.Req
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "running": running, "items": items, "stats": stats})
}
func (s *RegistryServer) handleWebUITaskDailySummary(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUITaskDailySummary(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -2290,7 +2290,7 @@ func (s *RegistryServer) handleWebUITaskDailySummary(w http.ResponseWriter, r *h
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "date": date, "report": report})
}
func (s *RegistryServer) loadEKGRowsCached(path string, maxLines int) []map[string]interface{} {
func (s *Server) loadEKGRowsCached(path string, maxLines int) []map[string]interface{} {
path = strings.TrimSpace(path)
if path == "" {
return nil
@@ -2332,7 +2332,7 @@ func (s *RegistryServer) loadEKGRowsCached(path string, maxLines int) []map[stri
return rows
}
func (s *RegistryServer) handleWebUIEKGStats(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUIEKGStats(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -2470,389 +2470,7 @@ func (s *RegistryServer) handleWebUIEKGStats(w http.ResponseWriter, r *http.Requ
})
}
func (s *RegistryServer) handleWebUIOfficeState(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
workspace := strings.TrimSpace(s.workspacePath)
auditPath := filepath.Join(workspace, "memory", "task-audit.jsonl")
tasksPath := filepath.Join(workspace, "memory", "tasks.json")
ekgPath := filepath.Join(workspace, "memory", "ekg-events.jsonl")
now := time.Now().UTC()
parseTime := func(raw string) time.Time {
raw = strings.TrimSpace(raw)
if raw == "" {
return time.Time{}
}
if t, err := time.Parse(time.RFC3339, raw); err == nil {
return t
}
return time.Time{}
}
ipv4Pattern := regexp.MustCompile(`\b(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\b`)
maskIPv4 := func(text string) string {
if strings.TrimSpace(text) == "" {
return text
}
return ipv4Pattern.ReplaceAllStringFunc(text, func(ip string) string {
parts := strings.Split(ip, ".")
if len(parts) != 4 {
return ip
}
for _, p := range parts {
n, err := strconv.Atoi(p)
if err != nil || n < 0 || n > 255 {
return ip
}
}
return parts[0] + "." + parts[1] + ".**.**"
})
}
latestByTask := map[string]map[string]interface{}{}
latestTimeByTask := map[string]time.Time{}
if b, err := os.ReadFile(auditPath); err == nil {
lines := strings.Split(string(b), "\n")
for _, ln := range lines {
if strings.TrimSpace(ln) == "" {
continue
}
var row map[string]interface{}
if json.Unmarshal([]byte(ln), &row) != nil {
continue
}
source := strings.ToLower(strings.TrimSpace(fmt.Sprintf("%v", row["source"])))
if source == "heartbeat" {
continue
}
taskID := strings.TrimSpace(fmt.Sprintf("%v", row["task_id"]))
if taskID == "" {
continue
}
t := parseTime(fmt.Sprintf("%v", row["time"]))
prev, ok := latestTimeByTask[taskID]
if ok && !t.IsZero() && t.Before(prev) {
continue
}
latestByTask[taskID] = row
if !t.IsZero() {
latestTimeByTask[taskID] = t
}
}
}
if b, err := os.ReadFile(tasksPath); err == nil {
var tasks []map[string]interface{}
if json.Unmarshal(b, &tasks) == nil {
for _, t := range tasks {
id := strings.TrimSpace(fmt.Sprintf("%v", t["id"]))
if id == "" {
continue
}
row := map[string]interface{}{
"task_id": id,
"time": fmt.Sprintf("%v", t["updated_at"]),
"status": fmt.Sprintf("%v", t["status"]),
"source": fmt.Sprintf("%v", t["source"]),
"input_preview": fmt.Sprintf("%v", t["content"]),
"log": fmt.Sprintf("%v", t["block_reason"]),
}
tm := parseTime(fmt.Sprintf("%v", row["time"]))
prev, ok := latestTimeByTask[id]
if !ok || prev.IsZero() || (!tm.IsZero() && tm.After(prev)) {
latestByTask[id] = row
if !tm.IsZero() {
latestTimeByTask[id] = tm
}
}
}
}
}
items := make([]map[string]interface{}, 0, len(latestByTask))
for _, row := range latestByTask {
items = append(items, row)
}
sort.Slice(items, func(i, j int) bool {
ti := parseTime(fmt.Sprintf("%v", items[i]["time"]))
tj := parseTime(fmt.Sprintf("%v", items[j]["time"]))
if ti.IsZero() && tj.IsZero() {
return fmt.Sprintf("%v", items[i]["task_id"]) > fmt.Sprintf("%v", items[j]["task_id"])
}
if ti.IsZero() {
return false
}
if tj.IsZero() {
return true
}
return ti.After(tj)
})
stats := map[string]int{
"running": 0,
"waiting": 0,
"blocked": 0,
"error": 0,
"success": 0,
"suppressed": 0,
}
for _, row := range items {
st := strings.ToLower(strings.TrimSpace(fmt.Sprintf("%v", row["status"])))
if _, ok := stats[st]; ok {
stats[st]++
}
}
mainState := "idle"
mainZone := "breakroom"
switch {
case stats["running"] > 0:
mainState = "executing"
mainZone = "work"
case stats["error"] > 0 || stats["blocked"] > 0:
mainState = "error"
mainZone = "bug"
case stats["suppressed"] > 0:
mainState = "syncing"
mainZone = "server"
case stats["waiting"] > 0:
mainState = "idle"
mainZone = "breakroom"
case stats["success"] > 0:
mainState = "writing"
mainZone = "work"
default:
mainState = "idle"
mainZone = "breakroom"
}
mainTaskID := ""
mainDetail := "No active task"
isMainStatus := func(st string) bool {
st = strings.ToLower(strings.TrimSpace(st))
switch mainState {
case "executing":
return st == "running"
case "error":
return st == "error" || st == "blocked"
case "syncing":
return st == "suppressed"
case "writing":
return st == "success"
default:
return st == "waiting" || st == "idle"
}
}
for _, row := range items {
st := strings.ToLower(strings.TrimSpace(fmt.Sprintf("%v", row["status"])))
if isMainStatus(st) {
mainTaskID = strings.TrimSpace(fmt.Sprintf("%v", row["task_id"]))
mainDetail = strings.TrimSpace(fmt.Sprintf("%v", row["input_preview"]))
if mainDetail == "" {
mainDetail = strings.TrimSpace(fmt.Sprintf("%v", row["log"]))
}
if mainDetail == "" {
mainDetail = "Task " + mainTaskID
}
break
}
}
if mainTaskID == "" && len(items) > 0 {
mainTaskID = strings.TrimSpace(fmt.Sprintf("%v", items[0]["task_id"]))
mainDetail = strings.TrimSpace(fmt.Sprintf("%v", items[0]["input_preview"]))
if mainDetail == "" {
mainDetail = strings.TrimSpace(fmt.Sprintf("%v", items[0]["log"]))
}
if mainDetail == "" {
mainDetail = "Task " + mainTaskID
}
}
nodeState := func(n NodeInfo) string {
if !n.Online {
return "offline"
}
// A node that is still online but hasn't heartbeat recently is treated as syncing.
if !n.LastSeenAt.IsZero() && now.Sub(n.LastSeenAt) > 20*time.Second {
return "syncing"
}
return "online"
}
nodeZone := func(n NodeInfo) string {
if !n.Online {
return "bug"
}
if n.Capabilities.Model || n.Capabilities.Run {
return "work"
}
if n.Capabilities.Invoke || n.Capabilities.Camera || n.Capabilities.Screen || n.Capabilities.Canvas || n.Capabilities.Location {
return "server"
}
return "breakroom"
}
nodeDetail := func(n NodeInfo) string {
parts := make([]string, 0, 4)
if ep := strings.TrimSpace(n.Endpoint); ep != "" {
parts = append(parts, maskIPv4(ep))
}
switch {
case strings.TrimSpace(n.OS) != "" && strings.TrimSpace(n.Arch) != "":
parts = append(parts, fmt.Sprintf("%s/%s", strings.TrimSpace(n.OS), strings.TrimSpace(n.Arch)))
case strings.TrimSpace(n.OS) != "":
parts = append(parts, strings.TrimSpace(n.OS))
case strings.TrimSpace(n.Arch) != "":
parts = append(parts, strings.TrimSpace(n.Arch))
}
if m := len(n.Models); m > 0 {
parts = append(parts, fmt.Sprintf("models:%d", m))
}
if !n.LastSeenAt.IsZero() {
parts = append(parts, "seen:"+n.LastSeenAt.UTC().Format(time.RFC3339))
}
if len(parts) == 0 {
return maskIPv4("node " + strings.TrimSpace(n.ID))
}
return maskIPv4(strings.Join(parts, " · "))
}
allNodes := []NodeInfo{}
if s.mgr != nil {
allNodes = s.mgr.List()
}
host, _ := os.Hostname()
localNode := NodeInfo{ID: "local", Name: "local", Endpoint: "gateway", Version: gatewayBuildVersion(), LastSeenAt: now, Online: true}
if strings.TrimSpace(host) != "" {
localNode.Name = strings.TrimSpace(host)
}
if ip := detectLocalIP(); ip != "" {
localNode.Endpoint = ip
}
hostLower := strings.ToLower(strings.TrimSpace(host))
mainNode := localNode
otherNodes := make([]NodeInfo, 0, len(allNodes))
for _, n := range allNodes {
idLower := strings.ToLower(strings.TrimSpace(n.ID))
nameLower := strings.ToLower(strings.TrimSpace(n.Name))
isLocal := idLower == "local" || nameLower == "local" || (hostLower != "" && nameLower == hostLower)
if isLocal {
if strings.TrimSpace(n.Name) != "" {
mainNode.Name = strings.TrimSpace(n.Name)
}
if strings.TrimSpace(localNode.Name) != "" {
mainNode.Name = strings.TrimSpace(localNode.Name)
}
if strings.TrimSpace(n.Endpoint) != "" {
mainNode.Endpoint = strings.TrimSpace(n.Endpoint)
}
if strings.TrimSpace(localNode.Endpoint) != "" {
mainNode.Endpoint = strings.TrimSpace(localNode.Endpoint)
}
if strings.TrimSpace(n.OS) != "" {
mainNode.OS = strings.TrimSpace(n.OS)
}
if strings.TrimSpace(n.Arch) != "" {
mainNode.Arch = strings.TrimSpace(n.Arch)
}
if len(n.Models) > 0 {
mainNode.Models = append([]string(nil), n.Models...)
}
mainNode.Online = true
mainNode.LastSeenAt = now
mainNode.Version = localNode.Version
continue
}
otherNodes = append(otherNodes, n)
}
onlineNodes := 1 // main(local) is always considered online.
nodesPayload := make([]map[string]interface{}, 0, 24)
for _, n := range otherNodes {
if n.Online {
onlineNodes++
}
id := strings.TrimSpace(n.ID)
if id == "" {
continue
}
name := strings.TrimSpace(n.Name)
if name == "" {
name = id
}
name = maskIPv4(name)
updatedAt := ""
if !n.LastSeenAt.IsZero() {
updatedAt = n.LastSeenAt.UTC().Format(time.RFC3339)
}
nodesPayload = append(nodesPayload, map[string]interface{}{
"id": id,
"name": name,
"state": nodeState(n),
"zone": nodeZone(n),
"detail": nodeDetail(n),
"updated_at": updatedAt,
})
if len(nodesPayload) >= 24 {
break
}
}
mainDetailOut := mainDetail
if nodeInfo := nodeDetail(mainNode); strings.TrimSpace(nodeInfo) != "" {
if strings.TrimSpace(mainDetailOut) == "" || strings.EqualFold(strings.TrimSpace(mainDetailOut), "No active task") {
mainDetailOut = nodeInfo
} else {
mainDetailOut = mainDetailOut + " · " + nodeInfo
}
}
mainDetailOut = maskIPv4(mainDetailOut)
ekgErr5m := 0
cutoff := now.Add(-5 * time.Minute)
for _, row := range s.loadEKGRowsCached(ekgPath, 2000) {
status := strings.ToLower(strings.TrimSpace(fmt.Sprintf("%v", row["status"])))
if status != "error" {
continue
}
ts := parseTime(fmt.Sprintf("%v", row["time"]))
if !ts.IsZero() && ts.Before(cutoff) {
continue
}
ekgErr5m++
}
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"ok": true,
"time": now.Format(time.RFC3339),
"main": map[string]interface{}{
"id": mainNode.ID,
"name": maskIPv4(mainNode.Name),
"state": mainState,
"detail": mainDetailOut,
"zone": mainZone,
"task_id": mainTaskID,
},
"nodes": nodesPayload,
"stats": map[string]interface{}{
"running": stats["running"],
"waiting": stats["waiting"],
"blocked": stats["blocked"],
"error": stats["error"],
"success": stats["success"],
"suppressed": stats["suppressed"],
"online_nodes": onlineNodes,
"ekg_error_5m": ekgErr5m,
},
})
}
func (s *RegistryServer) handleWebUITasks(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUITasks(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -2959,7 +2577,7 @@ func (s *RegistryServer) handleWebUITasks(w http.ResponseWriter, r *http.Request
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true})
}
func (s *RegistryServer) handleWebUIExecApprovals(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUIExecApprovals(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -3022,7 +2640,7 @@ func (s *RegistryServer) handleWebUIExecApprovals(w http.ResponseWriter, r *http
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
func (s *RegistryServer) handleWebUILogsRecent(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUILogsRecent(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -3073,7 +2691,7 @@ func (s *RegistryServer) handleWebUILogsRecent(w http.ResponseWriter, r *http.Re
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "logs": out})
}
func (s *RegistryServer) handleWebUILogsStream(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleWebUILogsStream(w http.ResponseWriter, r *http.Request) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
@@ -3132,7 +2750,7 @@ func (s *RegistryServer) handleWebUILogsStream(w http.ResponseWriter, r *http.Re
}
}
func (s *RegistryServer) checkAuth(r *http.Request) bool {
func (s *Server) checkAuth(r *http.Request) bool {
if s.token == "" {
return true
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 599 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 589 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 726 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 503 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 568 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 341 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 468 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 464 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 306 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 322 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 364 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 364 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 781 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 944 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 838 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 914 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1007 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 204 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 580 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 996 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

View File

@@ -15,7 +15,6 @@ import TaskAudit from './pages/TaskAudit';
import EKG from './pages/EKG';
import Tasks from './pages/Tasks';
import LogCodes from './pages/LogCodes';
import Office from './pages/Office';
export default function App() {
return (
@@ -36,7 +35,6 @@ export default function App() {
<Route path="task-audit" element={<TaskAudit />} />
<Route path="ekg" element={<EKG />} />
<Route path="tasks" element={<Tasks />} />
<Route path="office" element={<Office />} />
</Route>
</Routes>
</BrowserRouter>

View File

@@ -1,5 +1,5 @@
import React from 'react';
import { LayoutDashboard, MessageSquare, Settings, Clock, Server, Terminal, Zap, FolderOpen, ClipboardList, ListTodo, BrainCircuit, Hash, Map } from 'lucide-react';
import { LayoutDashboard, MessageSquare, Settings, Clock, Server, Terminal, Zap, FolderOpen, ClipboardList, ListTodo, BrainCircuit, Hash } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useAppContext } from '../context/AppContext';
import NavItem from './NavItem';
@@ -38,7 +38,6 @@ const Sidebar: React.FC = () => {
{
title: t('sidebarInsights'),
items: [
{ icon: <Map className="w-5 h-5" />, label: t('office'), to: '/office' },
{ icon: <BrainCircuit className="w-5 h-5" />, label: t('ekg'), to: '/ekg' },
],
},

View File

@@ -1,408 +0,0 @@
import React, { useEffect, useMemo, useState } from 'react';
import { OFFICE_CANVAS, OFFICE_ZONE_POINT, OFFICE_ZONE_SLOTS, OfficeZone } from './officeLayout';
export type OfficeMainState = {
id?: string;
name?: string;
state?: string;
detail?: string;
zone?: string;
task_id?: string;
};
export type OfficeNodeState = {
id?: string;
name?: string;
state?: string;
zone?: string;
detail?: string;
updated_at?: string;
};
type OfficeSceneProps = {
main: OfficeMainState;
nodes: OfficeNodeState[];
};
type SpriteSpec = {
src: string;
frameW: number;
frameH: number;
cols: number;
start: number;
end: number;
fps: number;
scale: number;
};
type ImageSpec = {
src: string;
width: number;
height: number;
scale: number;
};
const TICK_FPS = 12;
const MAIN_SPRITES: Record<'idle' | 'working' | 'syncing' | 'error', SpriteSpec> = {
idle: {
src: '/webui/office/star-idle-v5.png',
frameW: 256,
frameH: 256,
cols: 8,
start: 0,
end: 47,
fps: 12,
scale: 0.62,
},
working: {
src: '/webui/office/star-working-spritesheet-grid.webp',
frameW: 300,
frameH: 300,
cols: 8,
start: 0,
end: 37,
fps: 12,
scale: 0.56,
},
syncing: {
src: '/webui/office/sync-animation-v3-grid.webp',
frameW: 256,
frameH: 256,
cols: 7,
start: 1,
end: 47,
fps: 12,
scale: 0.54,
},
error: {
src: '/webui/office/error-bug-spritesheet-grid.webp',
frameW: 220,
frameH: 220,
cols: 8,
start: 0,
end: 71,
fps: 12,
scale: 0.66,
},
};
const NODE_SPRITES: SpriteSpec[] = Array.from({ length: 6 }, (_, i) => ({
src: `/webui/office/guest_anim_${i + 1}.webp`,
frameW: 32,
frameH: 32,
cols: 8,
start: 0,
end: 7,
fps: 8,
scale: 1.55,
}));
const DECOR_SPRITES = {
plants: {
src: '/webui/office/plants-spritesheet.webp',
frameW: 160,
frameH: 160,
cols: 4,
start: 0,
end: 15,
fps: 0,
scale: 1,
} as SpriteSpec,
posters: {
src: '/webui/office/posters-spritesheet.webp',
frameW: 160,
frameH: 160,
cols: 4,
start: 0,
end: 31,
fps: 0,
scale: 1,
} as SpriteSpec,
flowers: {
src: '/webui/office/flowers-bloom-v2.webp',
frameW: 128,
frameH: 128,
cols: 4,
start: 0,
end: 15,
fps: 0,
scale: 0.8,
} as SpriteSpec,
cats: {
src: '/webui/office/cats-spritesheet.webp',
frameW: 160,
frameH: 160,
cols: 4,
start: 0,
end: 15,
fps: 0,
scale: 1,
} as SpriteSpec,
coffeeMachine: {
src: '/webui/office/coffee-machine-v3-grid.webp',
frameW: 230,
frameH: 230,
cols: 12,
start: 0,
end: 94,
fps: 10,
scale: 1,
} as SpriteSpec,
serverroom: {
src: '/webui/office/serverroom-spritesheet.webp',
frameW: 180,
frameH: 251,
cols: 40,
start: 0,
end: 38,
fps: 6,
scale: 1,
} as SpriteSpec,
};
const DECOR_IMAGES = {
sofaIdle: {
src: '/webui/office/sofa-idle-v3.png',
width: 212,
height: 143,
scale: 1,
} as ImageSpec,
sofaShadow: {
src: '/webui/office/sofa-shadow-v1.png',
width: 233,
height: 81,
scale: 1,
} as ImageSpec,
desk: {
src: '/webui/office/desk-v3.webp',
width: 304,
height: 264,
scale: 1,
} as ImageSpec,
coffeeShadow: {
src: '/webui/office/coffee-machine-shadow-v1.png',
width: 245,
height: 111,
scale: 1,
} as ImageSpec,
};
function normalizeZone(z: string | undefined): OfficeZone {
const v = (z || '').trim().toLowerCase();
if (v === 'work' || v === 'server' || v === 'bug' || v === 'breakroom') return v;
return 'breakroom';
}
function normalizeMainSpriteState(s: string | undefined): keyof typeof MAIN_SPRITES {
const v = (s || '').trim().toLowerCase();
if (v.includes('error') || v.includes('blocked')) return 'error';
if (v.includes('sync') || v.includes('suppressed')) return 'syncing';
if (v.includes('run') || v.includes('execut') || v.includes('writing') || v.includes('research') || v.includes('success')) return 'working';
return 'idle';
}
function textHash(input: string): number {
let h = 0;
for (let i = 0; i < input.length; i += 1) {
h = (h * 31 + input.charCodeAt(i)) >>> 0;
}
return h;
}
function frameAtTick(spec: SpriteSpec, tick: number, seed = 0): number {
const frameCount = Math.max(1, spec.end - spec.start + 1);
const absoluteMs = tick * (1000 / TICK_FPS);
const frame = Math.floor((absoluteMs + seed) / (1000 / Math.max(1, spec.fps)));
return spec.start + (frame % frameCount);
}
function frameFromSeed(spec: SpriteSpec, seedText: string): number {
const frameCount = Math.max(1, spec.end - spec.start + 1);
return spec.start + (textHash(seedText) % frameCount);
}
function posStyle(x: number, y: number, zIndex: number): React.CSSProperties {
return {
left: `${(x / OFFICE_CANVAS.width) * 100}%`,
top: `${(y / OFFICE_CANVAS.height) * 100}%`,
zIndex,
};
}
type SpriteProps = {
spec: SpriteSpec;
frame: number;
className?: string;
};
const SpriteSheet: React.FC<SpriteProps> = ({ spec, frame, className }) => {
const col = frame % spec.cols;
const row = Math.floor(frame / spec.cols);
return (
<div
className={className}
style={{
width: spec.frameW,
height: spec.frameH,
backgroundImage: `url(${spec.src})`,
backgroundRepeat: 'no-repeat',
backgroundPosition: `-${col * spec.frameW}px -${row * spec.frameH}px`,
imageRendering: 'pixelated',
transform: `translate(-50%, -50%) scale(${spec.scale})`,
transformOrigin: 'center center',
}}
/>
);
};
type PlacedSpriteProps = {
spec: SpriteSpec;
frame: number;
x: number;
y: number;
zIndex: number;
title?: string;
};
const PlacedSprite: React.FC<PlacedSpriteProps> = ({ spec, frame, x, y, zIndex, title }) => (
<div className="absolute -translate-x-1/2 -translate-y-1/2 pointer-events-none" style={posStyle(x, y, zIndex)} title={title || ''}>
<div className="relative">
<SpriteSheet spec={spec} frame={frame} className="absolute left-1/2 top-1/2" />
</div>
</div>
);
type PlacedImageProps = {
spec: ImageSpec;
x: number;
y: number;
zIndex: number;
title?: string;
};
const PlacedImage: React.FC<PlacedImageProps> = ({ spec, x, y, zIndex, title }) => (
<div className="absolute -translate-x-1/2 -translate-y-1/2 pointer-events-none" style={posStyle(x, y, zIndex)} title={title || ''}>
<img
src={spec.src}
alt=""
className="absolute left-1/2 top-1/2"
style={{
width: spec.width,
height: spec.height,
imageRendering: 'pixelated',
transform: `translate(-50%, -50%) scale(${spec.scale})`,
transformOrigin: 'center center',
}}
/>
</div>
);
const OfficeScene: React.FC<OfficeSceneProps> = ({ main, nodes }) => {
const [tick, setTick] = useState(0);
useEffect(() => {
const timer = window.setInterval(() => {
setTick((v) => (v + 1) % 10000000);
}, Math.round(1000 / TICK_FPS));
return () => window.clearInterval(timer);
}, []);
const bgSrc = '/webui/office/office_bg_small.webp';
const placedNodes = useMemo(() => {
const counters: Record<OfficeZone, number> = { breakroom: 0, work: 0, server: 0, bug: 0 };
return nodes.slice(0, 24).map((n) => {
const zone = normalizeZone(n.zone);
const slots = OFFICE_ZONE_SLOTS[zone];
const idx = counters[zone] % slots.length;
counters[zone] += 1;
const stableKey = `${n.id || ''}|${n.name || ''}|${idx}`;
const avatarSeed = textHash(stableKey);
const spriteIndex = avatarSeed % NODE_SPRITES.length;
return { ...n, zone, point: slots[idx], spriteIndex, avatarSeed };
});
}, [nodes]);
const mainZone = normalizeZone(main.zone);
const mainPoint = OFFICE_ZONE_POINT[mainZone];
const mainSprite = MAIN_SPRITES[normalizeMainSpriteState(main.state)];
const mainFrame = frameAtTick(mainSprite, tick);
const mainSpriteState = normalizeMainSpriteState(main.state);
const decorSeedBase = `${main.id || 'main'}|${main.name || ''}`;
const plantFrameA = frameFromSeed(DECOR_SPRITES.plants, `${decorSeedBase}|plantA`);
const plantFrameB = frameFromSeed(DECOR_SPRITES.plants, `${decorSeedBase}|plantB`);
const plantFrameC = frameFromSeed(DECOR_SPRITES.plants, `${decorSeedBase}|plantC`);
const posterFrame = frameFromSeed(DECOR_SPRITES.posters, `${decorSeedBase}|poster`);
const flowerFrame = frameFromSeed(DECOR_SPRITES.flowers, `${decorSeedBase}|flower`);
const catFrame = frameFromSeed(DECOR_SPRITES.cats, `${decorSeedBase}|cat`);
const coffeeFrame = frameAtTick(DECOR_SPRITES.coffeeMachine, tick, 300);
const serverFrame = mainSpriteState === 'idle' ? 0 : frameAtTick(DECOR_SPRITES.serverroom, tick, 700);
return (
<div className="relative w-full overflow-hidden rounded-2xl border border-zinc-800 bg-zinc-950/60">
<div className="relative aspect-[16/9]">
<img src={bgSrc} alt="office" className="absolute inset-0 h-full w-full object-cover" />
<div className="absolute inset-0">
<PlacedSprite spec={DECOR_SPRITES.serverroom} frame={serverFrame} x={1021} y={142} zIndex={10} title="serverroom" />
<PlacedSprite spec={DECOR_SPRITES.posters} frame={posterFrame} x={252} y={66} zIndex={20} title="poster" />
<PlacedSprite spec={DECOR_SPRITES.plants} frame={plantFrameA} x={565} y={178} zIndex={21} title="plant" />
<PlacedSprite spec={DECOR_SPRITES.plants} frame={plantFrameB} x={230} y={185} zIndex={21} title="plant" />
<PlacedSprite spec={DECOR_SPRITES.plants} frame={plantFrameC} x={977} y={496} zIndex={21} title="plant" />
<PlacedImage spec={DECOR_IMAGES.sofaShadow} x={1070} y={610} zIndex={25} title="sofa-shadow" />
<PlacedImage spec={DECOR_IMAGES.sofaIdle} x={1070} y={610} zIndex={26} title="sofa" />
<PlacedImage spec={DECOR_IMAGES.coffeeShadow} x={659} y={397} zIndex={30} title="coffee-shadow" />
<PlacedSprite spec={DECOR_SPRITES.coffeeMachine} frame={coffeeFrame} x={659} y={397} zIndex={31} title="coffee-machine" />
<PlacedImage spec={DECOR_IMAGES.desk} x={218} y={417} zIndex={35} title="desk" />
<PlacedSprite spec={DECOR_SPRITES.flowers} frame={flowerFrame} x={310} y={390} zIndex={36} title="flower" />
<div
className="absolute -translate-x-1/2 -translate-y-1/2"
style={{
left: `${(mainPoint.x / OFFICE_CANVAS.width) * 100}%`,
top: `${(mainPoint.y / OFFICE_CANVAS.height) * 100}%`,
zIndex: 50,
}}
title={`${main.state || 'idle'} ${main.detail || ''}`.trim()}
>
<div className="relative">
<SpriteSheet spec={mainSprite} frame={mainFrame} className="absolute left-1/2 top-1/2" />
<div className="absolute left-1/2 top-1/2 -translate-x-1/2 translate-y-[62px] rounded bg-black/75 px-2 py-0.5 text-[10px] font-semibold tracking-wide text-zinc-100">
{main.name || main.id || 'main'}
</div>
</div>
</div>
{placedNodes.map((n, i) => (
<div
key={`${n.id || 'node'}-${i}`}
className="absolute -translate-x-1/2 -translate-y-1/2"
style={{
left: `${(n.point.x / OFFICE_CANVAS.width) * 100}%`,
top: `${(n.point.y / OFFICE_CANVAS.height) * 100}%`,
zIndex: 51,
}}
title={`${n.name || n.id || 'node'} · ${n.state || 'idle'}${n.detail ? ` · ${n.detail}` : ''}`}
>
<div className="relative">
<SpriteSheet
spec={NODE_SPRITES[n.spriteIndex]}
frame={frameAtTick(NODE_SPRITES[n.spriteIndex], tick, n.avatarSeed % 1000)}
className="absolute left-1/2 top-1/2"
/>
</div>
</div>
))}
<PlacedSprite spec={DECOR_SPRITES.cats} frame={catFrame} x={94} y={557} zIndex={80} title="cat" />
</div>
</div>
</div>
);
};
export default OfficeScene;

View File

@@ -1,48 +0,0 @@
export type OfficeZone = 'breakroom' | 'work' | 'server' | 'bug';
export const OFFICE_CANVAS = {
width: 1280,
height: 720,
};
export const OFFICE_ZONE_POINT: Record<OfficeZone, { x: number; y: number }> = {
breakroom: { x: 1070, y: 610 },
work: { x: 300, y: 365 },
server: { x: 1010, y: 235 },
bug: { x: 1125, y: 245 },
};
export const OFFICE_ZONE_SLOTS: Record<OfficeZone, Array<{ x: number; y: number }>> = {
breakroom: [
{ x: 1020, y: 620 },
{ x: 1090, y: 620 },
{ x: 1150, y: 620 },
{ x: 1040, y: 670 },
{ x: 1110, y: 670 },
{ x: 1180, y: 670 },
],
work: [
{ x: 240, y: 350 },
{ x: 300, y: 345 },
{ x: 360, y: 350 },
{ x: 420, y: 360 },
{ x: 260, y: 420 },
{ x: 320, y: 425 },
{ x: 380, y: 425 },
{ x: 440, y: 430 },
],
server: [
{ x: 950, y: 225 },
{ x: 1000, y: 220 },
{ x: 1055, y: 220 },
{ x: 930, y: 285 },
{ x: 990, y: 285 },
],
bug: [
{ x: 1100, y: 230 },
{ x: 1160, y: 230 },
{ x: 1210, y: 235 },
{ x: 1085, y: 290 },
{ x: 1145, y: 295 },
],
};

View File

@@ -20,13 +20,6 @@ const resources = {
sidebarSystem: 'System',
sidebarOps: 'Operations',
sidebarInsights: 'Insights',
office: 'Office',
officeMainState: 'Main State',
officeNoDetail: 'No active detail',
officeSceneStats: 'Scene Stats',
officeNodeList: 'Node List',
officeNoNodes: 'No nodes',
officeEkgErr5m: 'EKG Errors (5m)',
ekg: 'EKG',
ekgEscalations: 'Escalations',
ekgSourceStats: 'Source Stats',
@@ -451,13 +444,6 @@ const resources = {
sidebarSystem: '系统',
sidebarOps: '运维',
sidebarInsights: '洞察',
office: '办公室',
officeMainState: '主状态',
officeNoDetail: '暂无活动详情',
officeSceneStats: '场景统计',
officeNodeList: '节点列表',
officeNoNodes: '暂无节点',
officeEkgErr5m: 'EKG 近5分钟错误',
ekg: 'EKG',
ekgEscalations: '升级拦截次数',
ekgSourceStats: '来源统计',

View File

@@ -1,162 +0,0 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { RefreshCw } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useAppContext } from '../context/AppContext';
import OfficeScene, { OfficeMainState, OfficeNodeState } from '../components/office/OfficeScene';
const IPV4_PATTERN = /\b(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\b/g;
function maskIPv4(text: string | undefined): string {
const raw = String(text || '');
return raw.replace(IPV4_PATTERN, (ip) => {
const parts = ip.split('.');
if (parts.length !== 4) return ip;
const valid = parts.every((p) => {
const n = Number(p);
return Number.isInteger(n) && n >= 0 && n <= 255;
});
if (!valid) return ip;
return `${parts[0]}.${parts[1]}.**.**`;
});
}
type OfficeStats = {
running?: number;
waiting?: number;
blocked?: number;
error?: number;
success?: number;
suppressed?: number;
online_nodes?: number;
ekg_error_5m?: number;
};
type OfficePayload = {
ok?: boolean;
time?: string;
main?: OfficeMainState;
nodes?: OfficeNodeState[];
stats?: OfficeStats;
};
const Office: React.FC = () => {
const { t } = useTranslation();
const { q } = useAppContext();
const [loading, setLoading] = useState(false);
const [payload, setPayload] = useState<OfficePayload>({});
const fetchState = useCallback(async () => {
setLoading(true);
try {
const r = await fetch(`/webui/api/office_state${q}`);
if (!r.ok) throw new Error(await r.text());
const j = (await r.json()) as OfficePayload;
setPayload(j || {});
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
}, [q]);
useEffect(() => {
fetchState();
const timer = setInterval(fetchState, 5000);
return () => clearInterval(timer);
}, [fetchState]);
const main = payload.main || {};
const nodes = Array.isArray(payload.nodes) ? payload.nodes : [];
const stats = payload.stats || {};
const safeMain = useMemo(
() => ({
...main,
id: maskIPv4(main.id),
name: maskIPv4(main.name),
detail: maskIPv4(main.detail),
task_id: maskIPv4(main.task_id),
}),
[main]
);
const safeNodes = useMemo(
() =>
nodes.map((n) => ({
...n,
id: maskIPv4(n.id),
name: maskIPv4(n.name),
detail: maskIPv4(n.detail),
})),
[nodes]
);
const cards = useMemo(
() => [
{ label: t('statusRunning'), value: Number(stats.running || 0) },
{ label: t('statusWaiting'), value: Number(stats.waiting || 0) },
{ label: t('statusBlocked'), value: Number(stats.blocked || 0) },
{ label: t('statusError'), value: Number(stats.error || 0) },
{ label: t('nodesOnline'), value: Number(stats.online_nodes || 0) },
{ label: t('officeEkgErr5m'), value: Number(stats.ekg_error_5m || 0) },
],
[stats, t]
);
return (
<div className="p-4 md:p-6 space-y-4">
<div className="flex items-center justify-between gap-2 flex-wrap">
<div>
<h1 className="text-xl md:text-2xl font-semibold">{t('office')}</h1>
<div className="text-xs text-zinc-500 mt-1">
{t('officeMainState')}: {safeMain.state || 'idle'} {safeMain.task_id ? `· ${safeMain.task_id}` : ''}
</div>
</div>
<button onClick={fetchState} className="px-3 py-1.5 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-sm flex items-center gap-2">
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
{loading ? t('loading') : t('refresh')}
</button>
</div>
<div className="grid grid-cols-1 xl:grid-cols-3 gap-4">
<div className="xl:col-span-2">
<OfficeScene main={safeMain} nodes={safeNodes} />
<div className="mt-2 text-xs text-zinc-400 bg-zinc-900/40 border border-zinc-800 rounded-lg px-3 py-2">
{safeMain.detail || t('officeNoDetail')}
</div>
</div>
<div className="space-y-3">
<div className="rounded-xl border border-zinc-800 bg-zinc-900/40 p-3">
<div className="text-zinc-500 text-xs mb-2">{t('officeSceneStats')}</div>
<div className="grid grid-cols-2 gap-2">
{cards.map((c) => (
<div key={c.label} className="rounded-lg bg-zinc-950/70 border border-zinc-800 px-2 py-2">
<div className="text-[10px] text-zinc-500">{c.label}</div>
<div className="text-sm font-semibold text-zinc-100">{c.value}</div>
</div>
))}
</div>
</div>
<div className="rounded-xl border border-zinc-800 bg-zinc-900/40 p-3">
<div className="text-zinc-500 text-xs mb-2">{t('officeNodeList')}</div>
<div className="max-h-64 overflow-auto space-y-1.5">
{safeNodes.length === 0 ? (
<div className="text-zinc-500 text-sm">{t('officeNoNodes')}</div>
) : (
safeNodes.slice(0, 20).map((n, i) => (
<div key={`${n.id || 'node'}-${i}`} className="rounded-md bg-zinc-950/70 border border-zinc-800 px-2 py-1.5">
<div className="text-xs text-zinc-200 truncate">{n.name || n.id || 'node'}</div>
<div className="text-[11px] text-zinc-500 truncate">
{n.state || 'idle'} · {n.zone || 'breakroom'}
</div>
</div>
))
)}
</div>
</div>
</div>
</div>
</div>
);
};
export default Office;