feat(webui): add office main+nodes scene with Star assets

This commit is contained in:
lpf
2026-03-05 14:27:27 +08:00
parent 8df91df91c
commit 7cbb28eec8
25 changed files with 785 additions and 1 deletions

View File

@@ -104,6 +104,7 @@ 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)
@@ -2469,6 +2470,349 @@ 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{}
}
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["error"] > 0 || stats["blocked"] > 0:
mainState = "error"
mainZone = "bug"
case stats["running"] > 0:
mainState = "executing"
mainZone = "work"
case stats["suppressed"] > 0:
mainState = "syncing"
mainZone = "server"
case stats["success"] > 0:
mainState = "writing"
mainZone = "work"
default:
mainState = "idle"
mainZone = "breakroom"
}
mainTaskID := ""
mainDetail := "No active task"
for _, row := range items {
st := strings.ToLower(strings.TrimSpace(fmt.Sprintf("%v", row["status"])))
if st == "running" || st == "error" || st == "blocked" || st == "waiting" {
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, 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 "node " + strings.TrimSpace(n.ID)
}
return 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
}
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
}
}
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": 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) {
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 468 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 464 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 306 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 322 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 364 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 364 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 781 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 944 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 838 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 914 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1007 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 204 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

View File

@@ -15,6 +15,7 @@ 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 (
@@ -35,6 +36,7 @@ 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 } from 'lucide-react';
import { LayoutDashboard, MessageSquare, Settings, Clock, Server, Terminal, Zap, FolderOpen, ClipboardList, ListTodo, BrainCircuit, Hash, Map } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useAppContext } from '../context/AppContext';
import NavItem from './NavItem';
@@ -38,6 +38,7 @@ 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

@@ -0,0 +1,248 @@
import React, { useEffect, useMemo, useState } from 'react';
import { OFFICE_CANVAS, OFFICE_ZONE_POINT, OFFICE_ZONE_SLOTS, OfficeZone } from './officeLayout';
export type OfficeMainState = {
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;
};
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,
}));
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 stateTone(s: string | undefined): string {
const v = (s || '').trim().toLowerCase();
switch (v) {
case 'running':
case 'executing':
case 'writing':
return 'bg-cyan-400';
case 'online':
return 'bg-emerald-400';
case 'error':
case 'blocked':
case 'offline':
return 'bg-red-400';
case 'syncing':
case 'suppressed':
return 'bg-violet-400';
case 'success':
return 'bg-emerald-400';
default:
return 'bg-zinc-300';
}
}
function normalizeMainSpriteState(s: string | undefined): keyof typeof MAIN_SPRITES {
const v = (s || '').trim().toLowerCase();
if (v === 'error' || v === 'blocked') return 'error';
if (v === 'syncing' || v === 'suppressed' || v === 'sync') return 'syncing';
if (v === 'running' || v === 'executing' || v === 'writing' || v === 'researching' || v === '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);
}
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',
}}
/>
);
};
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);
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">
<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}%`,
}}
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-[145%] h-2.5 w-2.5 rounded-full ring-2 ring-white/80 ${stateTone(main.state)} shadow-lg shadow-black/50`} />
<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">
clawgo
</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}%`,
}}
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 className={`absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-[68%] h-2 w-2 rounded-full ring-1 ring-black/50 ${stateTone(n.state)}`} />
</div>
</div>
))}
</div>
</div>
</div>
);
};
export default OfficeScene;

View File

@@ -0,0 +1,49 @@
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: 640, y: 470 },
server: { x: 820, y: 220 },
bug: { x: 230, y: 210 },
};
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: 520, y: 470 },
{ x: 600, y: 470 },
{ x: 680, y: 470 },
{ x: 760, y: 470 },
{ x: 560, y: 530 },
{ x: 640, y: 530 },
{ x: 720, y: 530 },
{ x: 800, y: 530 },
],
server: [
{ x: 760, y: 240 },
{ x: 830, y: 240 },
{ x: 900, y: 240 },
{ x: 780, y: 290 },
{ x: 850, y: 290 },
],
bug: [
{ x: 180, y: 230 },
{ x: 240, y: 230 },
{ x: 300, y: 230 },
{ x: 210, y: 280 },
{ x: 270, y: 280 },
],
};

View File

@@ -20,6 +20,13 @@ 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',
@@ -444,6 +451,13 @@ const resources = {
sidebarSystem: '系统',
sidebarOps: '运维',
sidebarInsights: '洞察',
office: '办公室',
officeMainState: '主状态',
officeNoDetail: '暂无活动详情',
officeSceneStats: '场景统计',
officeNodeList: '节点列表',
officeNoNodes: '暂无节点',
officeEkgErr5m: 'EKG 近5分钟错误',
ekg: 'EKG',
ekgEscalations: '升级拦截次数',
ekgSourceStats: '来源统计',

126
webui/src/pages/Office.tsx Normal file
View File

@@ -0,0 +1,126 @@
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';
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 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')}: {main.state || 'idle'} {main.task_id ? `· ${main.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={main} nodes={nodes} />
<div className="mt-2 text-xs text-zinc-400 bg-zinc-900/40 border border-zinc-800 rounded-lg px-3 py-2">
{main.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">
{nodes.length === 0 ? (
<div className="text-zinc-500 text-sm">{t('officeNoNodes')}</div>
) : (
nodes.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;