feat: RHS panel initial fetch, floating widget, session cleanup (#5)

Phase 1: Fix RHS panel to fetch existing sessions on mount
- Add initial API fetch in useAllStatusUpdates() hook
- Allow GET /sessions endpoint without shared secret auth
- RHS panel now shows sessions after page refresh

Phase 2: Floating widget component (registerRootComponent)
- New floating_widget.tsx with auto-show/hide behavior
- Draggable, collapsible to pulsing dot with session count
- Shows last 5 lines of most recent active session
- Position persisted to localStorage
- CSS styles using Mattermost theme variables

Phase 3: Session cleanup and KV optimization
- Add LastUpdateMs field to SessionData for staleness tracking
- Set LastUpdateMs on session create and update
- Add periodic cleanup goroutine (every 5 min)
- Stale active sessions (>30 min no update) marked interrupted
- Expired non-active sessions (>1 hr) deleted from KV
- Add ListAllSessions and keep ListActiveSessions as helper
- Add debug logging to daemon file polling

Closes #5
This commit is contained in:
sol
2026-03-09 14:15:04 +00:00
parent 9ec52a418d
commit 79d5e82803
10 changed files with 520 additions and 32 deletions

View File

@@ -6,6 +6,7 @@ import (
"io"
"net/http"
"strings"
"time"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/plugin"
@@ -13,7 +14,13 @@ import (
// ServeHTTP handles HTTP requests to the plugin.
func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request) {
// Auth middleware: validate shared secret
path := r.URL.Path
// Auth middleware: validate shared secret for write operations.
// Read-only endpoints (GET /sessions, GET /health) are accessible to any
// authenticated Mattermost user — no shared secret required.
isReadOnly := r.Method == http.MethodGet && (path == "/api/v1/sessions" || path == "/api/v1/health")
if !isReadOnly {
config := p.getConfiguration()
if config.SharedSecret != "" {
auth := r.Header.Get("Authorization")
@@ -23,8 +30,7 @@ func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Req
return
}
}
path := r.URL.Path
}
switch {
case path == "/api/v1/health" && r.Method == http.MethodGet:
@@ -46,10 +52,14 @@ func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Req
// handleHealth returns plugin health status.
func (p *Plugin) handleHealth(w http.ResponseWriter, r *http.Request) {
sessions, err := p.store.ListActiveSessions()
sessions, err := p.store.ListAllSessions()
count := 0
if err == nil {
count = len(sessions)
for _, s := range sessions {
if s.Status == "active" {
count++
}
}
}
writeJSON(w, http.StatusOK, map[string]interface{}{
@@ -59,9 +69,9 @@ func (p *Plugin) handleHealth(w http.ResponseWriter, r *http.Request) {
})
}
// handleListSessions returns all active sessions.
// handleListSessions returns all sessions (active and non-active).
func (p *Plugin) handleListSessions(w http.ResponseWriter, r *http.Request) {
sessions, err := p.store.ListActiveSessions()
sessions, err := p.store.ListAllSessions()
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
return
@@ -93,8 +103,14 @@ func (p *Plugin) handleCreateSession(w http.ResponseWriter, r *http.Request) {
// Check max active sessions
config := p.getConfiguration()
sessions, _ := p.store.ListActiveSessions()
if len(sessions) >= config.MaxActiveSessions {
allSessions, _ := p.store.ListAllSessions()
activeCount := 0
for _, s := range allSessions {
if s.Status == "active" {
activeCount++
}
}
if activeCount >= config.MaxActiveSessions {
writeJSON(w, http.StatusTooManyRequests, map[string]string{"error": "max active sessions reached"})
return
}
@@ -133,6 +149,7 @@ func (p *Plugin) handleCreateSession(w http.ResponseWriter, r *http.Request) {
}
// Store session data
now := time.Now().UnixMilli()
sessionData := SessionData{
SessionKey: req.SessionKey,
PostID: createdPost.Id,
@@ -141,6 +158,8 @@ func (p *Plugin) handleCreateSession(w http.ResponseWriter, r *http.Request) {
AgentID: req.AgentID,
Status: "active",
Lines: []string{},
StartTimeMs: now,
LastUpdateMs: now,
}
if err := p.store.SaveSession(req.SessionKey, sessionData); err != nil {
p.API.LogWarn("Failed to save session", "error", err.Error())
@@ -187,6 +206,7 @@ func (p *Plugin) handleUpdateSession(w http.ResponseWriter, r *http.Request, ses
existing.ElapsedMs = req.ElapsedMs
existing.TokenCount = req.TokenCount
existing.Children = req.Children
existing.LastUpdateMs = time.Now().UnixMilli()
if req.StartTimeMs > 0 {
existing.StartTimeMs = req.StartTimeMs
}

View File

@@ -2,6 +2,7 @@ package main
import (
"sync"
"time"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/plugin"
@@ -22,6 +23,9 @@ type Plugin struct {
// botUserID is the plugin's bot user ID (created on activation).
botUserID string
// stopCleanup signals the cleanup goroutine to stop.
stopCleanup chan struct{}
}
// OnActivate is called when the plugin is activated.
@@ -41,10 +45,36 @@ func (p *Plugin) OnActivate() error {
p.API.LogInfo("Plugin bot user ensured", "botUserID", botID)
}
// Start session cleanup goroutine
p.stopCleanup = make(chan struct{})
go p.sessionCleanupLoop()
p.API.LogInfo("OpenClaw Live Status plugin activated")
return nil
}
// sessionCleanupLoop runs periodically to clean up stale and expired sessions.
func (p *Plugin) sessionCleanupLoop() {
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ticker.C:
staleThreshold := int64(30 * 60 * 1000) // 30 minutes — active sessions with no update
expireThreshold := int64(60 * 60 * 1000) // 1 hour — completed/interrupted sessions
cleaned, expired, err := p.store.CleanStaleSessions(staleThreshold, expireThreshold)
if err != nil {
p.API.LogWarn("Session cleanup error", "error", err.Error())
} else if cleaned > 0 || expired > 0 {
p.API.LogInfo("Session cleanup completed", "stale_marked", cleaned, "expired_deleted", expired)
}
case <-p.stopCleanup:
return
}
}
}
// getBotUserID returns the plugin's bot user ID.
func (p *Plugin) getBotUserID() string {
return p.botUserID
@@ -52,8 +82,13 @@ func (p *Plugin) getBotUserID() string {
// OnDeactivate is called when the plugin is deactivated.
func (p *Plugin) OnDeactivate() error {
// Stop cleanup goroutine
if p.stopCleanup != nil {
close(p.stopCleanup)
}
// Mark all active sessions as interrupted
sessions, err := p.store.ListActiveSessions()
sessions, err := p.store.ListAllSessions()
if err != nil {
p.API.LogWarn("Failed to list sessions on deactivate", "error", err.Error())
} else {

View File

@@ -5,6 +5,7 @@ import (
"fmt"
"net/url"
"strings"
"time"
"github.com/mattermost/mattermost/server/public/plugin"
)
@@ -24,6 +25,7 @@ type SessionData struct {
TokenCount int `json:"token_count"`
Children []SessionData `json:"children,omitempty"`
StartTimeMs int64 `json:"start_time_ms"`
LastUpdateMs int64 `json:"last_update_ms"`
}
// Store wraps Mattermost KV store operations for session persistence.
@@ -79,8 +81,8 @@ func (s *Store) DeleteSession(sessionKey string) error {
return nil
}
// ListActiveSessions returns all active sessions from the KV store.
func (s *Store) ListActiveSessions() ([]SessionData, error) {
// ListAllSessions returns all sessions from the KV store (active and non-active).
func (s *Store) ListAllSessions() ([]SessionData, error) {
var sessions []SessionData
page := 0
perPage := 100
@@ -106,12 +108,59 @@ func (s *Store) ListActiveSessions() ([]SessionData, error) {
if err := json.Unmarshal(b, &data); err != nil {
continue
}
if data.Status == "active" {
sessions = append(sessions, data)
}
}
page++
}
return sessions, nil
}
// ListActiveSessions returns only active sessions from the KV store.
func (s *Store) ListActiveSessions() ([]SessionData, error) {
all, err := s.ListAllSessions()
if err != nil {
return nil, err
}
var active []SessionData
for _, sess := range all {
if sess.Status == "active" {
active = append(active, sess)
}
}
return active, nil
}
// CleanStaleSessions marks stale active sessions as interrupted and deletes expired completed sessions.
// staleThresholdMs: active sessions with no update for this long are marked interrupted.
// expireThresholdMs: non-active sessions older than this are deleted from KV.
func (s *Store) CleanStaleSessions(staleThresholdMs, expireThresholdMs int64) (cleaned int, expired int, err error) {
now := time.Now().UnixMilli()
all, err := s.ListAllSessions()
if err != nil {
return 0, 0, err
}
for _, session := range all {
lastUpdate := session.LastUpdateMs
if lastUpdate == 0 {
lastUpdate = session.StartTimeMs
}
if lastUpdate == 0 {
continue
}
age := now - lastUpdate
if session.Status == "active" && age > staleThresholdMs {
// Mark stale sessions as interrupted
session.Status = "interrupted"
session.LastUpdateMs = now
_ = s.SaveSession(session.SessionKey, session)
cleaned++
} else if session.Status != "active" && age > expireThresholdMs {
// Delete expired completed/interrupted sessions
_ = s.DeleteSession(session.SessionKey)
expired++
}
}
return cleaned, expired, nil
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,197 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { LiveStatusData } from '../types';
import StatusLine from './status_line';
const STORAGE_KEY = 'livestatus_widget_pos';
const AUTO_HIDE_DELAY = 5000; // 5s after all sessions complete
const FloatingWidget: React.FC = () => {
const [sessions, setSessions] = useState<Record<string, LiveStatusData>>({});
const [collapsed, setCollapsed] = useState(true);
const [visible, setVisible] = useState(false);
const [position, setPosition] = useState(() => {
try {
const saved = localStorage.getItem(STORAGE_KEY);
if (saved) return JSON.parse(saved);
} catch {}
return { right: 20, bottom: 80 };
});
const [dragging, setDragging] = useState(false);
const dragRef = useRef<{ startX: number; startY: number; startRight: number; startBottom: number } | null>(null);
const hideTimerRef = useRef<number | null>(null);
const widgetRef = useRef<HTMLDivElement>(null);
// Subscribe to updates (same pattern as RHS panel)
useEffect(() => {
const key = '__floating_widget__';
if (!window.__livestatus_listeners[key]) {
window.__livestatus_listeners[key] = [];
}
const listener = () => {
setSessions({ ...(window.__livestatus_updates || {}) });
};
window.__livestatus_listeners[key].push(listener);
// Polling fallback
const interval = setInterval(() => {
setSessions(prev => {
const current = window.__livestatus_updates || {};
const prevKeys = Object.keys(prev).sort().join(',');
const currKeys = Object.keys(current).sort().join(',');
if (prevKeys !== currKeys) return { ...current };
for (const k of Object.keys(current)) {
if (current[k] !== prev[k]) return { ...current };
}
return prev;
});
}, 2000);
return () => {
clearInterval(interval);
const listeners = window.__livestatus_listeners[key];
if (listeners) {
const idx = listeners.indexOf(listener);
if (idx >= 0) listeners.splice(idx, 1);
}
};
}, []);
// Auto-show/hide logic
useEffect(() => {
const entries = Object.values(sessions);
const hasActive = entries.some(s => s.status === 'active');
if (hasActive) {
// Clear any pending hide timer
if (hideTimerRef.current) {
clearTimeout(hideTimerRef.current);
hideTimerRef.current = null;
}
setVisible(true);
} else if (visible && entries.length > 0) {
// All done - hide after delay
if (!hideTimerRef.current) {
hideTimerRef.current = window.setTimeout(() => {
setVisible(false);
setCollapsed(true);
hideTimerRef.current = null;
}, AUTO_HIDE_DELAY);
}
}
}, [sessions, visible]);
// Save position to localStorage
useEffect(() => {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(position));
} catch {}
}, [position]);
// Drag handlers
const onMouseDown = useCallback((e: React.MouseEvent) => {
e.preventDefault();
dragRef.current = {
startX: e.clientX,
startY: e.clientY,
startRight: position.right,
startBottom: position.bottom,
};
setDragging(true);
}, [position]);
useEffect(() => {
if (!dragging) return;
const onMouseMove = (e: MouseEvent) => {
if (!dragRef.current) return;
const dx = dragRef.current.startX - e.clientX;
const dy = dragRef.current.startY - e.clientY;
setPosition({
right: Math.max(0, dragRef.current.startRight + dx),
bottom: Math.max(0, dragRef.current.startBottom + dy),
});
};
const onMouseUp = () => {
setDragging(false);
dragRef.current = null;
};
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
return () => {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
};
}, [dragging]);
if (!visible) return null;
const entries = Object.values(sessions);
const activeSessions = entries.filter(s => s.status === 'active');
const displaySession = activeSessions[0] || entries[entries.length - 1];
const activeCount = activeSessions.length;
// Collapsed = pulsing dot with count
if (collapsed) {
return (
<div
ref={widgetRef}
className="ls-widget-collapsed"
style={{ right: position.right, bottom: position.bottom }}
onClick={() => setCollapsed(false)}
title={`${activeCount} active agent session${activeCount !== 1 ? 's' : ''}`}
>
<span className="ls-live-dot" />
{activeCount > 0 && <span className="ls-widget-count">{activeCount}</span>}
</div>
);
}
// Expanded view
return (
<div
ref={widgetRef}
className="ls-widget-expanded"
style={{ right: position.right, bottom: position.bottom }}
>
<div className="ls-widget-header" onMouseDown={onMouseDown}>
<span className="ls-widget-title">
{activeCount > 0 && <span className="ls-live-dot" />}
Agent Status
{activeCount > 0 && ` (${activeCount})`}
</span>
<button className="ls-widget-collapse-btn" onClick={() => setCollapsed(true)}>_</button>
<button className="ls-widget-close-btn" onClick={() => setVisible(false)}>×</button>
</div>
<div className="ls-widget-body">
{displaySession ? (
<div className="ls-widget-session">
<div className="ls-widget-session-header">
<span className="ls-agent-badge">{displaySession.agent_id}</span>
<span className={`ls-status-badge ls-status-${displaySession.status}`}>
{displaySession.status.toUpperCase()}
</span>
</div>
<div className="ls-widget-lines">
{displaySession.lines.slice(-5).map((line, i) => (
<StatusLine key={i} line={line} />
))}
</div>
</div>
) : (
<div className="ls-widget-empty">No sessions</div>
)}
{activeSessions.length > 1 && (
<div className="ls-widget-more">
+{activeSessions.length - 1} more active
</div>
)}
</div>
</div>
);
};
export default FloatingWidget;

View File

@@ -12,6 +12,30 @@ function useAllStatusUpdates(): Record<string, LiveStatusData> {
});
useEffect(() => {
// Initial fetch of existing sessions from the plugin API.
// Uses credentials: 'include' so Mattermost session cookies are forwarded.
// The server allows unauthenticated GET /sessions for MM-authenticated users.
fetch('/plugins/com.openclaw.livestatus/api/v1/sessions', {
credentials: 'include',
})
.then((res) => res.json())
.then((fetchedSessions: LiveStatusData[]) => {
if (Array.isArray(fetchedSessions)) {
const updates: Record<string, LiveStatusData> = {};
fetchedSessions.forEach((s) => {
const key = s.post_id || s.session_key;
updates[key] = s;
});
// Merge: WebSocket data (already in window) takes precedence over fetched data
window.__livestatus_updates = {
...updates,
...window.__livestatus_updates,
};
setSessions({ ...window.__livestatus_updates });
}
})
.catch((err) => console.warn('[LiveStatus] Failed to fetch initial sessions:', err));
// Register a global listener that catches all updates
const globalKey = '__rhs_panel__';
if (!window.__livestatus_listeners[globalKey]) {

View File

@@ -2,6 +2,7 @@ import React from 'react';
import { PluginRegistry, WebSocketPayload, LiveStatusData } from './types';
import LiveStatusPost from './components/live_status_post';
import RHSPanel from './components/rhs_panel';
import FloatingWidget from './components/floating_widget';
import './styles/live_status.css';
const PLUGIN_ID = 'com.openclaw.livestatus';
@@ -37,6 +38,9 @@ class LiveStatusPlugin {
tooltipText: 'Toggle Agent Status panel',
});
// Register floating widget as root component (always rendered)
registry.registerRootComponent(FloatingWidget);
// Register WebSocket event handler
registry.registerWebSocketEventHandler(WS_EVENT, (msg: any) => {
const data = msg.data as WebSocketPayload;
@@ -68,6 +72,12 @@ class LiveStatusPlugin {
if (rhsListeners) {
rhsListeners.forEach((fn) => fn(update));
}
// Notify floating widget listener
const widgetListeners = window.__livestatus_listeners['__floating_widget__'];
if (widgetListeners) {
widgetListeners.forEach((fn) => fn(update));
}
});
}

View File

@@ -305,3 +305,141 @@
letter-spacing: 0.5px;
color: var(--center-channel-color-48, rgba(0, 0, 0, 0.48));
}
/* ========= Floating Widget Styles ========= */
.ls-widget-collapsed {
position: fixed;
z-index: 9999;
cursor: pointer;
display: flex;
align-items: center;
gap: 4px;
padding: 8px;
background: var(--center-channel-bg, #fff);
border: 1px solid var(--center-channel-color-16, rgba(0, 0, 0, 0.16));
border-radius: 50%;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
transition: transform 0.2s;
}
.ls-widget-collapsed:hover {
transform: scale(1.1);
}
.ls-widget-collapsed .ls-live-dot {
width: 12px;
height: 12px;
}
.ls-widget-count {
position: absolute;
top: -4px;
right: -4px;
background: #f44336;
color: #fff;
font-size: 10px;
font-weight: 700;
width: 16px;
height: 16px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
}
.ls-widget-expanded {
position: fixed;
z-index: 9999;
width: 320px;
max-height: 300px;
background: var(--center-channel-bg, #fff);
border: 1px solid var(--center-channel-color-16, rgba(0, 0, 0, 0.16));
border-radius: 8px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
display: flex;
flex-direction: column;
overflow: hidden;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
.ls-widget-header {
display: flex;
align-items: center;
padding: 8px 10px;
background: var(--center-channel-color-04, rgba(0, 0, 0, 0.04));
border-bottom: 1px solid var(--center-channel-color-08, rgba(0, 0, 0, 0.08));
cursor: grab;
user-select: none;
}
.ls-widget-header:active {
cursor: grabbing;
}
.ls-widget-title {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
font-weight: 600;
flex: 1;
}
.ls-widget-collapse-btn,
.ls-widget-close-btn {
background: none;
border: none;
cursor: pointer;
font-size: 14px;
color: var(--center-channel-color-56, rgba(0, 0, 0, 0.56));
padding: 2px 6px;
border-radius: 3px;
}
.ls-widget-collapse-btn:hover,
.ls-widget-close-btn:hover {
background: var(--center-channel-color-08, rgba(0, 0, 0, 0.08));
}
.ls-widget-body {
padding: 8px;
overflow-y: auto;
flex: 1;
}
.ls-widget-session {
margin-bottom: 4px;
}
.ls-widget-session-header {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 6px;
}
.ls-widget-lines {
font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
font-size: 11px;
line-height: 1.5;
background: var(--center-channel-color-04, rgba(0, 0, 0, 0.04));
border-radius: 4px;
padding: 6px 8px;
max-height: 150px;
overflow-y: auto;
}
.ls-widget-empty {
color: var(--center-channel-color-48, rgba(0, 0, 0, 0.48));
font-size: 12px;
text-align: center;
padding: 12px;
}
.ls-widget-more {
font-size: 11px;
color: var(--center-channel-color-48, rgba(0, 0, 0, 0.48));
text-align: center;
padding: 4px;
}

View File

@@ -47,6 +47,7 @@ export interface PluginRegistry {
dropdownText: string;
tooltipText: string;
}): string;
registerRootComponent(component: React.ComponentType): string;
}
export interface Post {

View File

@@ -107,16 +107,27 @@ class StatusWatcher extends EventEmitter {
_startFilePoll(sessionKey, state) {
var self = this;
var pollInterval = 500; // 500ms poll
var pollCount = 0;
state._filePollTimer = setInterval(function () {
try {
var stat = fs.statSync(state.transcriptFile);
pollCount++;
if (stat.size > state.lastOffset) {
if (self.logger) {
self.logger.info(
{ sessionKey, fileSize: stat.size, lastOffset: state.lastOffset, delta: stat.size - state.lastOffset, pollCount },
'File poll: new data detected — reading',
);
}
self._readFile(sessionKey, state);
}
} catch (_e) {
// File might not exist yet or was deleted
}
}, pollInterval);
if (self.logger) {
self.logger.info({ sessionKey, pollInterval }, 'File poll timer started');
}
}
/**
@@ -214,6 +225,9 @@ class StatusWatcher extends EventEmitter {
const state = this.sessions.get(sessionKey);
if (!state) return;
if (this.logger) {
this.logger.info({ sessionKey, fullPath: path.basename(fullPath) }, 'fs.watch: file change detected');
}
this._readFile(sessionKey, state);
}