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
|
// module-servermon.js — Server monitoring + self-optimization telemetry
// Commands: server, servers, server-check, server-remove, monitor, system-health
class ServerMonitorModule {
constructor() {
this.commands = {}; this.terminal = null;
this.servers = this.loadServers(); this.monitorInterval = null;
this._latencyLog = [];
this._maxLatencyEntries = 200;
}
getHelpInfo() {
return {
'server': 'server <name> <url> — Add a server to monitor',
'servers': 'servers — List all monitored servers',
'server-check': 'server-check <name-or-index> — Check a server status',
'server-remove': 'server-remove <name-or-index> — Remove a server',
'monitor': 'monitor — Toggle auto-monitoring (checks every 60s)',
'system-health': 'system-health — Show tool latency, module load times, VFS size, and error rates',
'test-net': 'test-net — Check proxy API, Ollama, and internet connectivity',
};
}
registerCommands() {
this.commands['server'] = (args) => this.addServer(args);
this.commands['servers'] = () => this.listServers();
this.commands['server-check'] = (args) => this.checkServer(args);
this.commands['server-remove'] = (args) => this.removeServer(args);
this.commands['monitor'] = (args) => this.toggleMonitor(args);
this.commands['system-health'] = () => this.showSystemHealth();
// v4.5.43: test-net — check proxy/ollama/internet connectivity
this.commands['test-net'] = () => this.testNetwork();
}
async testNetwork() {
this.terminal.print('🌐 Network Test', 'header');
// 1. Browser online
const online = navigator.onLine;
this.terminal.print(` ${online ? '✅' : '🔴'} Browser: ${online ? 'online' : 'offline'}`, online ? 'success' : 'error');
// 2. Proxy API
try {
const t0 = Date.now();
const resp = await fetch('/api/stats', { signal: AbortSignal.timeout(5000) });
const ms = Date.now() - t0;
if (resp.ok) {
const data = await resp.json();
this.terminal.print(` ✅ Proxy: ok (${ms}ms, uptime ${data.uptime_seconds || '?'}s)`, 'success');
} else {
this.terminal.print(` 🔴 Proxy: HTTP ${resp.status}`, 'error');
}
} catch (e) {
this.terminal.print(` 🔴 Proxy: ${e.message || 'unreachable'}`, 'error');
}
// 3. Ollama
const ollamaOk = this.terminal.ollamaManager && this.terminal.ollamaManager.connected;
this.terminal.print(` ${ollamaOk ? '✅' : '🟡'} Ollama: ${ollamaOk ? 'connected' : 'disconnected'}`, ollamaOk ? 'success' : 'warning');
// 4. Internet (test by fetching a small file)
try {
const t0 = Date.now();
const resp = await fetch('https://duckduckgo.com/?q=test', { method: 'HEAD', signal: AbortSignal.timeout(5000), mode: 'no-cors' });
const ms = Date.now() - t0;
this.terminal.print(` ✅ Internet: reachable (${ms}ms)`, 'success');
} catch (e) {
this.terminal.print(` 🔴 Internet: ${e.message || 'unreachable'}`, 'error');
}
}
logToolCall(name, durationMs, error) {
this._latencyLog.push({
name,
duration: durationMs,
error: !!error,
time: Date.now()
});
if (this._latencyLog.length > this._maxLatencyEntries) {
this._latencyLog = this._latencyLog.slice(-this._maxLatencyEntries);
}
// Persist every 20 calls
if (this._latencyLog.length % 20 === 0) {
this._persistLatency();
}
}
_persistLatency() {
try {
this.terminal.fs.fsWriteJSON('/system/metrics/tool-latency.json', this._latencyLog.slice(-100));
} catch (e) {}
}
_loadLatency() {
try {
const data = this.terminal.fs.fsReadJSON('/system/metrics/tool-latency.json');
if (data) this._latencyLog = data;
} catch (e) {}
}
showSystemHealth() {
this._loadLatency();
const fs = this.terminal.fs;
// Tool latency stats
const toolStats = {};
for (const entry of this._latencyLog) {
if (!toolStats[entry.name]) toolStats[entry.name] = { calls: 0, totalMs: 0, errors: 0, maxMs: 0 };
toolStats[entry.name].calls++;
toolStats[entry.name].totalMs += entry.duration;
toolStats[entry.name].errors += entry.error ? 1 : 0;
toolStats[entry.name].maxMs = Math.max(toolStats[entry.name].maxMs, entry.duration);
}
this.terminal.print('📊 System Health', 'header');
// Tool latency table (sorted by avg desc)
this.terminal.print('── Tool Latency ──', 'info');
const sorted = Object.entries(toolStats)
.map(([name, s]) => ({ name, avg: (s.totalMs / s.calls).toFixed(0), ...s }))
.sort((a, b) => b.avg - a.avg);
for (const t of sorted.slice(0, 10)) {
const avgMs = t.avg.padStart(5);
const maxMs = String(t.maxMs).padStart(5);
const err = t.errors > 0 ? ` ⚠️${t.errors}` : '';
this.terminal.print(` ${avgMs}ms avg / ${maxMs}ms max — ${t.name} (${t.calls} calls)${err}`, t.errors > 0 ? 'warning' : '');
}
if (sorted.length > 10) this.terminal.print(` ... and ${sorted.length - 10} more tools`, 'info');
// VFS stats
this.terminal.print('── VFS Stats ──', 'info');
try {
const totalSize = this._vfsSize(fs.root);
const fileCount = this._vfsCount(fs.root, 'file');
const dirCount = this._vfsCount(fs.root, 'dir');
this.terminal.print(` ${fileCount} files, ${dirCount} dirs, ${(totalSize / 1024).toFixed(0)} KB total`, '');
} catch (e) { this.terminal.print(' VFS stats unavailable', 'warning'); }
// Module stats
this.terminal.print('── Module Stats ──', 'info');
const mm = this.terminal.moduleManager;
const loaded = Object.keys(mm.modules).length;
const reg = (mm.moduleRegistry || []).length;
this.terminal.print(` ${loaded} modules loaded, ${reg} in registry`, '');
// Memory
this.terminal.print('── Memory ──', 'info');
if (performance.memory) {
const heap = (performance.memory.usedJSHeapSize / 1048576).toFixed(1);
const total = (performance.memory.jsHeapSizeLimit / 1048576).toFixed(0);
this.terminal.print(` ${heap} MB used / ${total} MB limit`, heap > 100 ? 'warning' : '');
} else {
this.terminal.print(' Memory info not available (non-Chrome browser)', '');
}
// Total tool call count
const totalCalls = this._latencyLog.length;
const totalErrors = this._latencyLog.filter(e => e.error).length;
this.terminal.print(` ${totalCalls} tool calls logged, ${totalErrors} errors (${totalCalls > 0 ? (totalErrors / totalCalls * 100).toFixed(1) : 0}% error rate)`, totalErrors > 0 ? 'warning' : '');
}
_vfsSize(node) {
if (!node) return 0;
if (node.type === 'file') return (node.content || '').length;
let s = 0;
for (const k in (node.content || {})) s += this._vfsSize(node.content[k]);
return s;
}
_vfsCount(node, type) {
if (!node) return 0;
let c = 0;
for (const k in (node.content || {})) {
const child = node.content[k];
if (child.type === type) c++;
c += this._vfsCount(child, type);
}
return c;
}
loadServers() {
try {
const saved = localStorage.getItem('webx11_servers');
return saved ? JSON.parse(saved) : [];
} catch (e) { return []; }
}
saveServers() {
localStorage.setItem('webx11_servers', JSON.stringify(this.servers));
}
addServer(args) {
if (args.length < 2) {
this.terminal.print("Usage: server <name> <url>", "warning"); return;
}
const name = args[0], url = args[1];
this.servers.push({ name, url, status: 'unknown', lastCheck: null });
this.saveServers();
this.terminal.print(`Server '${name}' added`, "success");
}
listServers() {
if (this.servers.length === 0) {
this.terminal.print("No servers configured", "info"); return;
}
this.terminal.print("=== Monitored Servers ===", "info");
this.servers.forEach((s, i) => {
const statusIcon = s.status === 'online' ? '🟢' : s.status === 'offline' ? '🔴' : '⚪';
this.terminal.print(`${i + 1}. ${statusIcon} ${s.name} - ${s.url}`);
if (s.lastCheck) { this.terminal.print(` Last check: ${s.lastCheck}`, "info"); }
});
}
async checkServer(args) {
if (!args[0]) {
this.terminal.print("Usage: server-check <name-or-index>", "warning"); return;
}
const server = this.findServer(args[0]);
if (!server) {
this.terminal.print("Server not found", "error"); return;
}
this.terminal.print(`Checking ${server.name}...`, "info");
try {
const start = Date.now();
const response = await fetch(server.url, { method: 'HEAD', mode: 'no-cors' });
const latency = Date.now() - start;
server.status = 'online'; server.lastCheck = new Date().toLocaleString(); server.latency = latency;
this.saveServers();
this.terminal.print(`✅ ${server.name} is online (${latency}ms)`, "success");
} catch (e) {
server.status = 'offline'; server.lastCheck = new Date().toLocaleString();
this.saveServers();
this.terminal.print(`❌ ${server.name} is offline`, "error");
}
}
removeServer(args) {
if (!args[0]) {
this.terminal.print("Usage: server-remove <name-or-index>", "warning"); return;
}
const index = this.findServerIndex(args[0]);
if (index === -1) {
this.terminal.print("Server not found", "error"); return;
}
this.servers.splice(index, 1);
this.saveServers();
this.terminal.print("Server removed", "success");
}
toggleMonitor(args) {
if (this.monitorInterval) {
clearInterval(this.monitorInterval);
this.monitorInterval = null;
this.terminal.print("Auto-monitor stopped", "warning");
} else {
this.terminal.print("Auto-monitor started (every 60s)", "success");
this.monitorInterval = setInterval(() => {
this.servers.forEach((s, i) => { this.checkServer([String(i + 1)]); });
}, 60000);
}
}
findServer(identifier) {
const index = this.findServerIndex(identifier);
return index !== -1 ? this.servers[index] : null;
}
findServerIndex(identifier) {
const idx = parseInt(identifier) - 1;
if (!isNaN(idx) && idx >= 0 && idx < this.servers.length) { return idx; }
return this.servers.findIndex(s => s.name.toLowerCase() === identifier.toLowerCase());
}
}
|