Spaces:
Sleeping
Sleeping
Download src/classes/core/ControlServer.ts from lamsaoganh/teamta: direct link, hf CLI and curl.
- Browser
- Download file 35.9 kB
-
https://huggingface.co/spaces/lamsaoganh/teamta/resolve/main/src/classes/core/ControlServer.ts
- Command line
-
hf download hf://spaces/lamsaoganh/teamta/src/classes/core/ControlServer.ts
-
curl -L -o ControlServer.ts https://huggingface.co/spaces/lamsaoganh/teamta/resolve/main/src/classes/core/ControlServer.ts
35.9 kB
| import express, { Request, Response } from 'express'; | |
| import type { Server } from 'http'; | |
| import os from 'os'; | |
| import { WorkerProfileConfig } from '../../config/WorkerProfile'; | |
| import { IWorkerRegistry } from '../../interfaces/core/IWorkerRegistry'; | |
| export type RunMode = 'start' | 'pause'; | |
| export interface WorkerControlSnapshot { | |
| runMode: RunMode; | |
| startedAt: string; | |
| uptimeSec: number; | |
| isProcessing: boolean; | |
| noah: { | |
| apiBaseUrl: string; | |
| }; | |
| currentMessage?: { | |
| messageId?: string; | |
| messageType?: string; | |
| startedAt?: string; | |
| }; | |
| profile: { | |
| profileName: string; | |
| workerRole: string; | |
| platform: IWorkerRegistry['platform']; | |
| coder: string; | |
| enabledMessageTypes: string[]; | |
| }; | |
| pendingProfileUpdate?: { | |
| profileName?: string; | |
| requestedAt: string; | |
| }; | |
| pendingNoahApiBaseUrlUpdate?: { | |
| apiBaseUrl: string; | |
| requestedAt: string; | |
| }; | |
| system: { | |
| nodeVersion: string; | |
| platform: string; | |
| arch: string; | |
| cpus: number; | |
| loadavg: number[]; | |
| totalmem: number; | |
| freemem: number; | |
| }; | |
| process: { | |
| pid: number; | |
| memoryUsage: ReturnType<typeof process.memoryUsage>; | |
| cpuUsage: ReturnType<typeof process.cpuUsage>; | |
| }; | |
| } | |
| export interface ControlServerDeps { | |
| getSnapshot: () => WorkerControlSnapshot; | |
| setRunMode: (mode: RunMode) => void; | |
| requestApplyProfileByName: (profileName: string) => Promise<void>; | |
| requestApplyProfileObject: (profile: WorkerProfileConfig, opts?: { persist?: boolean }) => Promise<void>; | |
| requestResetToStartupProfile: () => Promise<void>; | |
| requestSetNoahApiBaseUrl: (apiBaseUrl: string) => Promise<void>; | |
| } | |
| export function buildSnapshot(params: { | |
| runMode: RunMode; | |
| startedAt: Date; | |
| isProcessing: boolean; | |
| noahApiBaseUrl: string; | |
| currentMessage?: { messageId?: string; messageType?: string; startedAt?: Date }; | |
| profile: WorkerProfileConfig; | |
| enabledMessageTypes: string[]; | |
| pendingProfileUpdate?: { profileName?: string; requestedAt: Date }; | |
| pendingNoahApiBaseUrlUpdate?: { apiBaseUrl: string; requestedAt: Date }; | |
| }): WorkerControlSnapshot { | |
| const currentMessage = params.currentMessage | |
| ? { | |
| ...(params.currentMessage.messageId !== undefined && { messageId: params.currentMessage.messageId }), | |
| ...(params.currentMessage.messageType !== undefined && { messageType: params.currentMessage.messageType }), | |
| ...(params.currentMessage.startedAt !== undefined && { startedAt: params.currentMessage.startedAt.toISOString() }), | |
| } | |
| : undefined; | |
| return { | |
| runMode: params.runMode, | |
| startedAt: params.startedAt.toISOString(), | |
| uptimeSec: Math.floor(process.uptime()), | |
| isProcessing: params.isProcessing, | |
| noah: { | |
| apiBaseUrl: params.noahApiBaseUrl, | |
| }, | |
| ...(currentMessage && { currentMessage }), | |
| profile: { | |
| profileName: params.profile.profileName, | |
| workerRole: params.profile.workerRole, | |
| platform: params.profile.platform, | |
| coder: params.profile.coder, | |
| enabledMessageTypes: params.enabledMessageTypes, | |
| }, | |
| ...(params.pendingProfileUpdate && { | |
| pendingProfileUpdate: { | |
| ...(params.pendingProfileUpdate.profileName !== undefined && { | |
| profileName: params.pendingProfileUpdate.profileName, | |
| }), | |
| requestedAt: params.pendingProfileUpdate.requestedAt.toISOString(), | |
| }, | |
| }), | |
| ...(params.pendingNoahApiBaseUrlUpdate && { | |
| pendingNoahApiBaseUrlUpdate: { | |
| apiBaseUrl: params.pendingNoahApiBaseUrlUpdate.apiBaseUrl, | |
| requestedAt: params.pendingNoahApiBaseUrlUpdate.requestedAt.toISOString(), | |
| }, | |
| }), | |
| system: { | |
| nodeVersion: process.version, | |
| platform: os.platform(), | |
| arch: os.arch(), | |
| cpus: os.cpus()?.length || 0, | |
| loadavg: os.loadavg(), | |
| totalmem: os.totalmem(), | |
| freemem: os.freemem(), | |
| }, | |
| process: { | |
| pid: process.pid, | |
| memoryUsage: process.memoryUsage(), | |
| cpuUsage: process.cpuUsage(), | |
| }, | |
| }; | |
| } | |
| export function startControlServer(params: { | |
| port: number; | |
| deps: ControlServerDeps; | |
| host?: string; | |
| // How many ports to try starting from `port` before falling back to an ephemeral port (0) | |
| maxPortTries?: number; | |
| }): Promise<{ port: number }> { | |
| const app = express(); | |
| const host = params.host || '0.0.0.0'; | |
| const maxPortTries = params.maxPortTries ?? 50; | |
| const listenOnce = (port: number) => | |
| new Promise<{ server: Server; port: number }>((resolve, reject) => { | |
| const server = app.listen(port, host, () => { | |
| const addr = server.address(); | |
| const resolvedPort = typeof addr === 'object' && addr ? addr.port : port; | |
| resolve({ server, port: resolvedPort }); | |
| }); | |
| server.once('error', reject); | |
| }); | |
| const listenWithFallback = async (preferredPort: number) => { | |
| const portsToTry: number[] = []; | |
| if (preferredPort === 0) { | |
| portsToTry.push(0); | |
| } else { | |
| for (let i = 0; i < maxPortTries; i++) { | |
| portsToTry.push(preferredPort + i); | |
| } | |
| // If all else fails, ask OS to pick an available ephemeral port. | |
| portsToTry.push(0); | |
| } | |
| let lastError: any = null; | |
| for (const port of portsToTry) { | |
| try { | |
| return await listenOnce(port); | |
| } catch (error: any) { | |
| lastError = error; | |
| const code = error?.code; | |
| // Try next port for common bind errors | |
| if (code === 'EADDRINUSE' || code === 'EACCES') { | |
| continue; | |
| } | |
| break; | |
| } | |
| } | |
| throw lastError || new Error('Failed to start control server'); | |
| }; | |
| const handleConfigUpdate = async (req: Request, res: Response) => { | |
| try { | |
| const body = req.body || {}; | |
| if (typeof body.profileName === 'string' && body.profileName.trim()) { | |
| await params.deps.requestApplyProfileByName(body.profileName.trim()); | |
| res.json({ ok: true, applied: { profileName: body.profileName.trim() } }); | |
| return; | |
| } | |
| if (body.profile && typeof body.profile === 'object') { | |
| const persist = Boolean(body.persist); | |
| await params.deps.requestApplyProfileObject(body.profile as WorkerProfileConfig, { persist }); | |
| res.json({ ok: true, applied: { profileName: (body.profile as any).profileName, persist } }); | |
| return; | |
| } | |
| res.status(400).json({ | |
| ok: false, | |
| error: "Body must include either { profileName: string } or { profile: object }", | |
| }); | |
| } catch (error: any) { | |
| res.status(500).json({ ok: false, error: error?.message || String(error) }); | |
| } | |
| }; | |
| app.use(express.json({ limit: '2mb' })); | |
| app.get('/monitor', (_req: Request, res: Response) => { | |
| const html = `<!doctype html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="utf-8" /> | |
| <meta name="viewport" content="width=device-width, initial-scale=1" /> | |
| <title>Snake Worker Monitor</title> | |
| <style> | |
| :root { | |
| --bg-primary: #f8fafc; | |
| --bg-secondary: #ffffff; | |
| --bg-card: #ffffff; | |
| --bg-card-hover: #f1f5f9; | |
| --border: #e2e8f0; | |
| --border-hover: #cbd5e1; | |
| --text-primary: #0f172a; | |
| --text-secondary: #475569; | |
| --text-muted: #94a3b8; | |
| --accent: #6366f1; | |
| --accent-glow: rgba(99, 102, 241, 0.15); | |
| --success: #10b981; | |
| --success-bg: #d1fae5; | |
| --warning: #f59e0b; | |
| --warning-bg: #fef3c7; | |
| --danger: #ef4444; | |
| --danger-bg: #fee2e2; | |
| --info: #3b82f6; | |
| --info-bg: #dbeafe; | |
| } | |
| * { box-sizing: border-box; } | |
| body { | |
| font-family: 'Inter', ui-sans-serif, system-ui, -apple-system, sans-serif; | |
| margin: 0; padding: 0; | |
| background: var(--bg-primary); | |
| color: var(--text-primary); | |
| min-height: 100vh; | |
| } | |
| .wrap { max-width: 1280px; margin: 0 auto; padding: 24px; } | |
| /* Header */ | |
| .header { | |
| display: flex; align-items: center; justify-content: space-between; | |
| padding: 20px 0 28px; border-bottom: 1px solid var(--border); | |
| margin-bottom: 24px; flex-wrap: wrap; gap: 16px; | |
| } | |
| .header-left { display: flex; align-items: center; gap: 16px; } | |
| .logo { | |
| width: 48px; height: 48px; border-radius: 14px; | |
| background: linear-gradient(135deg, var(--accent) 0%, #8b5cf6 100%); | |
| display: flex; align-items: center; justify-content: center; | |
| font-size: 24px; font-weight: 800; color: white; | |
| box-shadow: 0 2px 10px var(--accent-glow); | |
| } | |
| .header-title { font-size: 24px; font-weight: 700; letter-spacing: -0.5px; } | |
| .header-subtitle { font-size: 13px; color: var(--text-muted); margin-top: 2px; } | |
| .header-right { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; } | |
| /* Badges */ | |
| .badge { | |
| display: inline-flex; align-items: center; gap: 6px; | |
| padding: 6px 12px; border-radius: 20px; | |
| font-weight: 600; font-size: 11px; text-transform: uppercase; | |
| letter-spacing: 0.5px; border: 1px solid; | |
| transition: all 0.2s ease; | |
| } | |
| .badge::before { content: ''; width: 6px; height: 6px; border-radius: 50%; } | |
| .badge.ok { background: var(--success-bg); border-color: var(--success); color: var(--success); } | |
| .badge.ok::before { background: var(--success); } | |
| .badge.warn { background: var(--warning-bg); border-color: var(--warning); color: #b45309; } | |
| .badge.warn::before { background: var(--warning); } | |
| .badge.bad { background: var(--danger-bg); border-color: var(--danger); color: var(--danger); } | |
| .badge.bad::before { background: var(--danger); } | |
| .badge.info { background: var(--info-bg); border-color: var(--info); color: var(--info); } | |
| .badge.info::before { background: var(--info); } | |
| /* Buttons */ | |
| .btn { | |
| cursor: pointer; border-radius: 10px; border: 1px solid var(--border); | |
| padding: 10px 18px; background: var(--bg-card); color: var(--text-primary); | |
| font-weight: 600; font-size: 13px; transition: all 0.2s ease; | |
| display: inline-flex; align-items: center; gap: 8px; | |
| } | |
| .btn:hover { background: var(--bg-card-hover); border-color: var(--border-hover); transform: translateY(-1px); } | |
| .btn:active { transform: translateY(0); } | |
| .btn-primary { background: var(--accent); border-color: var(--accent); } | |
| .btn-primary:hover { background: #4f46e5; box-shadow: 0 4px 12px var(--accent-glow); } | |
| .btn-success { background: var(--success); border-color: var(--success); } | |
| .btn-success:hover { background: #059669; box-shadow: 0 4px 12px rgba(16,185,129,0.4); } | |
| .btn-warning { background: rgba(245,158,11,0.2); border-color: rgba(245,158,11,0.4); color: #fcd34d; } | |
| .btn-warning:hover { background: rgba(245,158,11,0.3); } | |
| .btn-danger { background: rgba(239,68,68,0.2); border-color: rgba(239,68,68,0.4); color: #fca5a5; } | |
| .btn-danger:hover { background: rgba(239,68,68,0.3); } | |
| .btn-sm { padding: 6px 12px; font-size: 12px; } | |
| .btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; } | |
| .btns { display: flex; gap: 8px; flex-wrap: wrap; } | |
| /* Grid */ | |
| .grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; } | |
| @media (max-width: 900px) { .grid { grid-template-columns: 1fr; } } | |
| /* Cards */ | |
| .card { | |
| background: var(--bg-card); border: 1px solid var(--border); | |
| border-radius: 16px; padding: 20px; | |
| transition: all 0.3s ease; position: relative; overflow: hidden; | |
| box-shadow: 0 1px 3px rgba(0,0,0,0.05); | |
| } | |
| .card:hover { border-color: var(--border-hover); box-shadow: 0 4px 12px rgba(0,0,0,0.08); } | |
| .card-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; } | |
| .card-title { font-size: 16px; font-weight: 700; display: flex; align-items: center; gap: 10px; } | |
| .card-title-icon { font-size: 18px; } | |
| .card-subtitle { font-size: 12px; color: var(--text-muted); } | |
| .card-full { grid-column: 1 / -1; } | |
| /* Collapsible */ | |
| .collapsible-toggle { | |
| cursor: pointer; display: flex; align-items: center; gap: 8px; | |
| user-select: none; padding: 8px 0; | |
| } | |
| .collapsible-toggle::before { content: 'βΆ'; font-size: 10px; transition: transform 0.2s; } | |
| .collapsible-toggle.open::before { transform: rotate(90deg); } | |
| .collapsible-content { display: none; animation: slideDown 0.2s ease; } | |
| .collapsible-content.open { display: block; } | |
| @keyframes slideDown { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } } | |
| /* Pre / Code */ | |
| pre { | |
| margin: 0; padding: 14px; border-radius: 10px; | |
| background: #f8fafc; overflow: auto; | |
| border: 1px solid var(--border); | |
| font-size: 12px; line-height: 1.5; max-height: 300px; | |
| } | |
| code { font-family: 'JetBrains Mono', 'Fira Code', monospace; } | |
| /* Inputs */ | |
| input, select { | |
| border-radius: 10px; border: 1px solid var(--border); | |
| padding: 10px 14px; background: var(--bg-secondary); | |
| color: var(--text-primary); font-size: 13px; | |
| transition: all 0.2s ease; width: 100%; | |
| } | |
| input:focus, select:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-glow); } | |
| input::placeholder { color: var(--text-muted); } | |
| /* Error / Toast */ | |
| .error { color: var(--danger); font-weight: 600; font-size: 12px; margin-top: 8px; } | |
| .toast-container { position: fixed; bottom: 24px; right: 24px; z-index: 9999; display: flex; flex-direction: column; gap: 8px; } | |
| .toast { | |
| padding: 14px 20px; border-radius: 12px; font-size: 13px; font-weight: 600; | |
| display: flex; align-items: center; gap: 10px; animation: toastIn 0.3s ease; | |
| box-shadow: 0 8px 30px rgba(0,0,0,0.4); | |
| } | |
| .toast.success { background: var(--success); color: white; } | |
| .toast.error { background: var(--danger); color: white; } | |
| .toast.info { background: var(--info); color: white; } | |
| @keyframes toastIn { from { opacity: 0; transform: translateX(100%); } to { opacity: 1; transform: translateX(0); } } | |
| @keyframes toastOut { from { opacity: 1; transform: translateX(0); } to { opacity: 0; transform: translateX(100%); } } | |
| /* Env Editor */ | |
| .env-table { width: 100%; margin-top: 12px; } | |
| .env-row { display: grid; grid-template-columns: minmax(120px, 1fr) minmax(150px, 2fr) auto auto; gap: 10px; align-items: center; padding: 8px 0; border-bottom: 1px solid var(--border); } | |
| .env-row:last-child { border-bottom: none; } | |
| .env-key { font-family: 'JetBrains Mono', monospace; font-weight: 700; font-size: 12px; color: var(--accent); word-break: break-all; } | |
| .env-row input { min-width: 0; } | |
| @media (max-width: 640px) { .env-row { grid-template-columns: 1fr; gap: 8px; } } | |
| /* Stats */ | |
| .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); gap: 12px; margin-top: 12px; } | |
| .stat-item { text-align: center; padding: 12px; background: var(--bg-primary); border-radius: 10px; border: 1px solid var(--border); } | |
| .stat-value { font-size: 20px; font-weight: 800; color: var(--accent); } | |
| .stat-label { font-size: 10px; color: var(--text-muted); text-transform: uppercase; margin-top: 4px; } | |
| /* Progress bar */ | |
| .progress-bar { height: 6px; background: var(--border); border-radius: 3px; overflow: hidden; margin-top: 8px; } | |
| .progress-fill { height: 100%; border-radius: 3px; transition: width 0.3s ease; } | |
| .progress-fill.ok { background: linear-gradient(90deg, var(--success), #34d399); } | |
| .progress-fill.warn { background: linear-gradient(90deg, var(--warning), #fbbf24); } | |
| .progress-fill.bad { background: linear-gradient(90deg, var(--danger), #f87171); } | |
| /* Loading spinner */ | |
| .spinner { width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin 0.8s linear infinite; } | |
| @keyframes spin { to { transform: rotate(360deg); } } | |
| /* Kbd */ | |
| kbd { background: var(--bg-primary); border: 1px solid var(--border); border-radius: 4px; padding: 2px 6px; font-size: 11px; font-family: monospace; } | |
| /* Meta info bar */ | |
| .meta-bar { display: flex; align-items: center; justify-content: space-between; padding: 12px 0; margin-top: 20px; border-top: 1px solid var(--border); color: var(--text-muted); font-size: 12px; flex-wrap: wrap; gap: 12px; } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="wrap"> | |
| <!-- Header --> | |
| <header class="header"> | |
| <div class="header-left"> | |
| <div class="logo">S</div> | |
| <div> | |
| <div class="header-title">Snake Worker Monitor</div> | |
| <div class="header-subtitle">Real-time worker status & control panel</div> | |
| </div> | |
| </div> | |
| <div class="header-right"> | |
| <div id="statusBadge"></div> | |
| <div class="btns"> | |
| <button id="btnToggle" class="btn" type="button"></button> | |
| <button id="btnRefresh" class="btn" type="button" title="Refresh now (R)"><span id="refreshIcon">β»</span> Refresh</button> | |
| </div> | |
| </div> | |
| </header> | |
| <!-- Main Grid --> | |
| <div class="grid"> | |
| <!-- Status Card --> | |
| <div class="card"> | |
| <div class="card-header"> | |
| <div class="card-title"><span class="card-title-icon">π</span> Status</div> | |
| <div class="card-subtitle" id="uptimeDisplay">--</div> | |
| </div> | |
| <div class="stats-grid"> | |
| <div class="stat-item"><div class="stat-value" id="statUptime">--</div><div class="stat-label">Uptime (m)</div></div> | |
| <div class="stat-item"><div class="stat-value" id="statMode">--</div><div class="stat-label">Mode</div></div> | |
| <div class="stat-item"><div class="stat-value" id="statProcessing">--</div><div class="stat-label">Processing</div></div> | |
| </div> | |
| <div class="collapsible-toggle" onclick="toggleCollapse(this)">Details</div> | |
| <div class="collapsible-content"><pre id="statusJson"></pre></div> | |
| </div> | |
| <!-- Noah API Card --> | |
| <div class="card"> | |
| <div class="card-header"> | |
| <div class="card-title"><span class="card-title-icon">π</span> Noah API</div> | |
| <div class="card-subtitle">Runtime base URL</div> | |
| </div> | |
| <div style="display: flex; gap: 10px; flex-wrap: wrap; align-items: center;"> | |
| <input id="noahUrl" placeholder="http://localhost:3000" style="flex: 1; min-width: 200px;" /> | |
| <button id="btnSetNoah" class="btn btn-primary" type="button">Apply</button> | |
| </div> | |
| <div id="noahError" class="error"></div> | |
| <div class="collapsible-toggle" onclick="toggleCollapse(this)">Details</div> | |
| <div class="collapsible-content"><pre id="noahJson"></pre></div> | |
| </div> | |
| <!-- Current Message Card --> | |
| <div class="card"> | |
| <div class="card-header"> | |
| <div class="card-title"><span class="card-title-icon">π¨</span> Current Message</div> | |
| <div class="card-subtitle">Active task</div> | |
| </div> | |
| <div id="messageDisplay" style="padding: 16px; text-align: center; color: var(--text-muted);">No active message</div> | |
| <div class="collapsible-toggle" onclick="toggleCollapse(this)">Raw JSON</div> | |
| <div class="collapsible-content"><pre id="messageJson"></pre></div> | |
| </div> | |
| <!-- Profile Card --> | |
| <div class="card"> | |
| <div class="card-header"> | |
| <div class="card-title"><span class="card-title-icon">βοΈ</span> Profile</div> | |
| <div class="card-subtitle" id="profileName">--</div> | |
| </div> | |
| <div id="enabledTypes" style="display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 12px;"></div> | |
| <div class="collapsible-toggle" onclick="toggleCollapse(this)">Full Profile</div> | |
| <div class="collapsible-content"><pre id="profileJson"></pre></div> | |
| </div> | |
| <!-- System Stats Card --> | |
| <div class="card"> | |
| <div class="card-header"> | |
| <div class="card-title"><span class="card-title-icon">π₯οΈ</span> System</div> | |
| <div class="card-subtitle" id="nodeVersion">--</div> | |
| </div> | |
| <div style="margin-top: 8px;"> | |
| <div style="display: flex; justify-content: space-between; font-size: 12px;"><span>Memory</span><span id="memoryText">--</span></div> | |
| <div class="progress-bar"><div class="progress-fill ok" id="memoryBar" style="width: 0%;"></div></div> | |
| </div> | |
| <div style="margin-top: 12px;"> | |
| <div style="display: flex; justify-content: space-between; font-size: 12px;"><span>CPU Load</span><span id="cpuText">--</span></div> | |
| <div class="progress-bar"><div class="progress-fill ok" id="cpuBar" style="width: 0%;"></div></div> | |
| </div> | |
| <div class="stats-grid" style="margin-top: 16px;"> | |
| <div class="stat-item"><div class="stat-value" id="statCpus">--</div><div class="stat-label">CPUs</div></div> | |
| <div class="stat-item"><div class="stat-value" id="statPid">--</div><div class="stat-label">PID</div></div> | |
| </div> | |
| </div> | |
| <!-- Raw Snapshot Card --> | |
| <div class="card card-full"> | |
| <div class="card-header"> | |
| <div class="card-title"><span class="card-title-icon">π</span> Raw Snapshot</div> | |
| <div class="card-subtitle" id="lastUpdated">--</div> | |
| </div> | |
| <div class="collapsible-toggle open" onclick="toggleCollapse(this)">Toggle JSON</div> | |
| <div class="collapsible-content open"><pre id="rawJson" style="max-height: 400px;"></pre></div> | |
| </div> | |
| </div> | |
| <!-- Meta Bar --> | |
| <div class="meta-bar"> | |
| <div>Keyboard: <kbd>R</kbd> Refresh <kbd>S</kbd> or <kbd>P</kbd> Toggle Start/Pause</div> | |
| <div>Auto-refresh every 2s</div> | |
| </div> | |
| </div> | |
| <!-- Toast Container --> | |
| <div id="toastContainer" class="toast-container"></div> | |
| <script> | |
| const $ = (id) => document.getElementById(id); | |
| function toggleCollapse(el) { | |
| el.classList.toggle('open'); | |
| const content = el.nextElementSibling; | |
| if (content) content.classList.toggle('open'); | |
| } | |
| function showToast(message, type = 'info') { | |
| const container = $('toastContainer'); | |
| const toast = document.createElement('div'); | |
| toast.className = 'toast ' + type; | |
| toast.innerHTML = (type === 'success' ? 'β' : type === 'error' ? 'β' : 'βΉ') + ' ' + message; | |
| container.appendChild(toast); | |
| setTimeout(() => { toast.style.animation = 'toastOut 0.3s ease forwards'; setTimeout(() => toast.remove(), 300); }, 3000); | |
| } | |
| function badge(text, kind) { | |
| const el = document.createElement('span'); | |
| el.className = 'badge ' + kind; | |
| el.textContent = text; | |
| return el; | |
| } | |
| function pretty(obj) { return JSON.stringify(obj, null, 2); } | |
| function formatBytes(bytes) { | |
| if (bytes < 1024) return bytes + ' B'; | |
| if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB'; | |
| if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB'; | |
| return (bytes / 1073741824).toFixed(2) + ' GB'; | |
| } | |
| function formatUptime(sec) { | |
| const h = Math.floor(sec / 3600); | |
| const m = Math.floor((sec % 3600) / 60); | |
| const s = sec % 60; | |
| if (h > 0) return h + 'h ' + m + 'm'; | |
| if (m > 0) return m + 'm ' + s + 's'; | |
| return s + 's'; | |
| } | |
| async function api(path, opts) { | |
| const res = await fetch(path, opts); | |
| const text = await res.text(); | |
| let json; | |
| try { json = JSON.parse(text); } catch { json = { raw: text }; } | |
| if (!res.ok) { | |
| const msg = json?.error || json?.message || text || ('HTTP ' + res.status); | |
| const e = new Error(msg); e.status = res.status; e.body = json; | |
| throw e; | |
| } | |
| return json; | |
| } | |
| function render(snapshot) { | |
| // Status badge | |
| const statusBadge = $('statusBadge'); | |
| statusBadge.innerHTML = ''; | |
| const isRunning = snapshot.runMode === 'start'; | |
| const badgeEl = badge(isRunning ? 'RUNNING' : 'PAUSED', isRunning ? 'ok' : 'warn'); | |
| statusBadge.appendChild(badgeEl); | |
| // Toggle button | |
| const btnToggle = $('btnToggle'); | |
| if (isRunning) { | |
| btnToggle.textContent = 'βΈ Pause'; | |
| btnToggle.className = 'btn btn-warning'; | |
| btnToggle.title = 'Pause worker (P)'; | |
| } else { | |
| btnToggle.textContent = 'βΆ Start'; | |
| btnToggle.className = 'btn btn-success'; | |
| btnToggle.title = 'Start worker (S)'; | |
| } | |
| // Status stats | |
| $('statUptime').textContent = Math.floor(snapshot.uptimeSec / 60); | |
| $('statMode').textContent = snapshot.runMode.toUpperCase(); | |
| $('statProcessing').textContent = snapshot.isProcessing ? 'YES' : 'NO'; | |
| $('uptimeDisplay').textContent = 'Uptime: ' + formatUptime(snapshot.uptimeSec); | |
| $('statusJson').textContent = pretty({ runMode: snapshot.runMode, isProcessing: snapshot.isProcessing, uptimeSec: snapshot.uptimeSec, startedAt: snapshot.startedAt }); | |
| // Noah | |
| $('noahUrl').value = snapshot.noah?.apiBaseUrl || ''; | |
| $('noahJson').textContent = pretty({ apiBaseUrl: snapshot.noah?.apiBaseUrl, pending: snapshot.pendingNoahApiBaseUrlUpdate || null }); | |
| // Message | |
| const msg = snapshot.currentMessage; | |
| if (msg && msg.messageType) { | |
| $('messageDisplay').innerHTML = '<div style="font-size:14px;font-weight:700;color:var(--accent);">' + (msg.messageType || '') + '</div><div style="font-size:12px;margin-top:4px;color:var(--text-secondary);">ID: ' + (msg.messageId || 'N/A') + '</div>'; | |
| } else { | |
| $('messageDisplay').innerHTML = '<div style="color:var(--text-muted);">No active message</div>'; | |
| } | |
| $('messageJson').textContent = pretty(msg || null); | |
| // Profile | |
| $('profileName').textContent = snapshot.profile?.profileName || '--'; | |
| const typesEl = $('enabledTypes'); | |
| typesEl.innerHTML = ''; | |
| (snapshot.profile?.enabledMessageTypes || []).forEach(t => { const b = badge(t, 'info'); typesEl.appendChild(b); }); | |
| $('profileJson').textContent = pretty(snapshot.profile); | |
| // System | |
| const sys = snapshot.system || {}; | |
| const proc = snapshot.process || {}; | |
| $('nodeVersion').textContent = sys.nodeVersion || '--'; | |
| $('statCpus').textContent = sys.cpus || '--'; | |
| $('statPid').textContent = proc.pid || '--'; | |
| const memUsed = sys.totalmem - sys.freemem; | |
| const memPct = sys.totalmem ? Math.round((memUsed / sys.totalmem) * 100) : 0; | |
| $('memoryText').textContent = formatBytes(memUsed) + ' / ' + formatBytes(sys.totalmem) + ' (' + memPct + '%)'; | |
| const memBar = $('memoryBar'); | |
| memBar.style.width = memPct + '%'; | |
| memBar.className = 'progress-fill ' + (memPct > 90 ? 'bad' : memPct > 70 ? 'warn' : 'ok'); | |
| const loadPct = sys.loadavg && sys.cpus ? Math.min(100, Math.round((sys.loadavg[0] / sys.cpus) * 100)) : 0; | |
| $('cpuText').textContent = 'Load avg: ' + (sys.loadavg ? sys.loadavg.map(l => l.toFixed(2)).join(', ') : '--'); | |
| const cpuBar = $('cpuBar'); | |
| cpuBar.style.width = loadPct + '%'; | |
| cpuBar.className = 'progress-fill ' + (loadPct > 90 ? 'bad' : loadPct > 70 ? 'warn' : 'ok'); | |
| // Raw | |
| $('rawJson').textContent = pretty(snapshot); | |
| $('lastUpdated').textContent = 'Updated: ' + new Date().toLocaleTimeString(); | |
| } | |
| let inFlight = false; | |
| async function refresh() { | |
| if (inFlight) return; | |
| inFlight = true; | |
| $('refreshIcon').className = 'spinner'; | |
| $('refreshIcon').textContent = ''; | |
| try { | |
| const snapshot = await api('/health'); | |
| $('noahError').textContent = ''; | |
| render(snapshot); | |
| } catch (e) { | |
| $('noahError').textContent = String(e?.message || e); | |
| } finally { | |
| inFlight = false; | |
| $('refreshIcon').className = ''; | |
| $('refreshIcon').textContent = 'β»'; | |
| } | |
| } | |
| $('btnRefresh').addEventListener('click', refresh); | |
| $('btnToggle').addEventListener('click', async () => { | |
| const snapshot = await api('/health'); | |
| const isRunning = snapshot.runMode === 'start'; | |
| if (isRunning) { | |
| await api('/pause', { method: 'POST' }); | |
| showToast('Worker paused', 'info'); | |
| } else { | |
| await api('/start', { method: 'POST' }); | |
| showToast('Worker started', 'success'); | |
| } | |
| await refresh(); | |
| }); | |
| $('btnSetNoah').addEventListener('click', async () => { | |
| const apiBaseUrl = $('noahUrl').value; | |
| try { | |
| $('noahError').textContent = ''; | |
| await api('/noah', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ apiBaseUrl }) }); | |
| showToast('Noah URL updated', 'success'); | |
| await refresh(); | |
| } catch (e) { $('noahError').textContent = String(e?.message || e); showToast('Failed: ' + e?.message, 'error'); } | |
| }); | |
| // Keyboard shortcuts | |
| document.addEventListener('keydown', (e) => { | |
| if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return; | |
| if (e.key.toLowerCase() === 'r') { e.preventDefault(); refresh(); } | |
| if (e.key.toLowerCase() === 's' || e.key.toLowerCase() === 'p') { | |
| e.preventDefault(); | |
| $('btnToggle').click(); | |
| } | |
| }); | |
| refresh(); | |
| setInterval(refresh, 2000); | |
| </script> | |
| </body> | |
| </html>`; | |
| res.setHeader('Content-Type', 'text/html; charset=utf-8'); | |
| res.status(200).send(html); | |
| }); | |
| app.get('/health', (_req: Request, res: Response) => { | |
| res.json(params.deps.getSnapshot()); | |
| }); | |
| app.get('/config', (_req: Request, res: Response) => { | |
| res.json(params.deps.getSnapshot()); | |
| }); | |
| // Update config by profileName (load from worker/*.json) | |
| app.post('/config', handleConfigUpdate); | |
| app.put('/config', handleConfigUpdate); | |
| app.delete('/config', async (_req: Request, res: Response) => { | |
| try { | |
| await params.deps.requestResetToStartupProfile(); | |
| res.json({ ok: true, reset: true }); | |
| } catch (error: any) { | |
| res.status(500).json({ ok: false, error: error?.message || String(error) }); | |
| } | |
| }); | |
| app.post('/start', (_req: Request, res: Response) => { | |
| params.deps.setRunMode('start'); | |
| res.json({ ok: true, runMode: 'start' }); | |
| }); | |
| app.post('/pause', (_req: Request, res: Response) => { | |
| params.deps.setRunMode('pause'); | |
| res.json({ ok: true, runMode: 'pause' }); | |
| }); | |
| app.get('/noah', (_req: Request, res: Response) => { | |
| const snapshot = params.deps.getSnapshot(); | |
| res.json({ ok: true, apiBaseUrl: snapshot.noah.apiBaseUrl }); | |
| }); | |
| const handleNoahUpdate = async (req: Request, res: Response) => { | |
| try { | |
| const body = req.body || {}; | |
| const apiBaseUrl = | |
| typeof body.apiBaseUrl === 'string' | |
| ? body.apiBaseUrl | |
| : typeof body.noahApiBaseUrl === 'string' | |
| ? body.noahApiBaseUrl | |
| : ''; | |
| if (!String(apiBaseUrl || '').trim()) { | |
| res.status(400).json({ ok: false, error: 'Body must include { apiBaseUrl: string }' }); | |
| return; | |
| } | |
| const requestedApiBaseUrl = String(apiBaseUrl).trim(); | |
| await params.deps.requestSetNoahApiBaseUrl(requestedApiBaseUrl); | |
| const snapshot = params.deps.getSnapshot(); | |
| res.json({ ok: true, requestedApiBaseUrl, apiBaseUrl: snapshot.noah.apiBaseUrl }); | |
| } catch (error: any) { | |
| res.status(500).json({ ok: false, error: error?.message || String(error) }); | |
| } | |
| }; | |
| app.put('/noah', handleNoahUpdate); | |
| app.post('/noah', handleNoahUpdate); | |
| return listenWithFallback(params.port).then(({ port }) => { | |
| console.log(`π§ Control server listening on http://${host}:${port}`); | |
| return { port }; | |
| }); | |
| } | |