Spaces:
Sleeping
Sleeping
File size: 35,945 Bytes
1305386 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 | 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 };
});
}
|