-
-
Notifications
You must be signed in to change notification settings - Fork 195
Expand file tree
/
Copy pathphoenix-builder-boot.js
More file actions
433 lines (394 loc) · 14.5 KB
/
Copy pathphoenix-builder-boot.js
File metadata and controls
433 lines (394 loc) · 14.5 KB
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
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
// Phoenix Builder boot-time script. Loaded synchronously before loggerSetup.js
// to capture ALL console output from the very start of boot.
// No AMD dependencies — only uses window.AppConfig and localStorage.
/*globals AppConfig*/
(function () {
// Gate checks — exit immediately if not enabled or not a dev build
if (localStorage.getItem("phoenixBuilderEnabled") !== "true") {
return;
}
if (!window.AppConfig || AppConfig.config.environment !== "dev") {
return;
}
// Skip MCP in test windows (the embedded Phoenix iframe inside SpecRunner).
// Only the SpecRunner itself and the normal Phoenix app should connect to MCP.
// Phoenix.isTestWindow is true for both SpecRunner and the test iframe,
// but Phoenix.isSpecRunnerWindow is only true for the SpecRunner itself.
if (window.Phoenix && window.Phoenix.isTestWindow && !window.Phoenix.isSpecRunnerWindow) {
return;
}
// --- Constants ---
const LOG_TO_CONSOLE_KEY = "logToConsole";
const INSTANCE_NAME_KEY = "phoenixBuilderInstanceName";
const FLUSH_INTERVAL = 500;
const FLUSH_THRESHOLD = 50;
const MAX_BUFFER_SIZE = 1000;
const MAX_MESSAGE_LENGTH = 2000;
const RECONNECT_BASE_MS = 500;
const RECONNECT_MAX_MS = 5000;
const DEFAULT_WS_URL = "ws://localhost:38571";
// --- Trust ring reference (set later via setKernalModeTrust) ---
let _kernalModeTrust = null;
/**
* Dismantle the trust ring before reload. Awaits up to 5s, ignores errors.
* @return {Promise<void>}
*/
async function _dismantleTrustRing() {
try {
if (_kernalModeTrust && _kernalModeTrust.dismantleKeyring) {
await Promise.race([
_kernalModeTrust.dismantleKeyring(),
new Promise(resolve => setTimeout(resolve, 5000))
]);
}
} catch (e) {
console.error("Error dismantling trust ring before reload:", e);
}
}
// --- State ---
let ws = null;
let logBuffer = [];
const capturedLogs = [];
let totalLogsPushed = 0;
let flushTimer = null;
let reconnectTimer = null;
let reconnectDelay = RECONNECT_BASE_MS;
let currentUrl = null;
let autoReconnect = true;
const handlers = {};
// --- Enable logToConsole so loggerSetup.js preserves console.log ---
localStorage.setItem(LOG_TO_CONSOLE_KEY, "true");
// --- Save original console methods ---
const originalConsoleLog = console.log;
const originalConsoleInfo = console.info;
const originalConsoleWarn = console.warn;
const originalConsoleError = console.error;
// --- Platform / instance helpers ---
function _getPlatformTag() {
if (window.__TAURI__) {
return "tauri";
}
if (window.__ELECTRON__) {
return "electron";
}
const desktop = Phoenix.browser && Phoenix.browser.desktop;
if (desktop) {
if (desktop.isFirefox) { return "firefox"; }
if (desktop.isEdgeChromium) { return "edge"; }
if (desktop.isOperaChromium || desktop.isOpera) { return "opera"; }
if (desktop.isChrome) { return "chrome"; }
if (desktop.isSafari) { return "safari"; }
if (desktop.isChromeBased) { return "chromium"; }
}
return "browser";
}
function _getOrCreateInstanceName() {
let name = sessionStorage.getItem(INSTANCE_NAME_KEY);
if (!name) {
const hex = Math.floor(Math.random() * 0x10000).toString(16).padStart(4, "0");
const prefix = window._phoenixBuilderNamePrefix || "phoenix";
name = prefix + "-" + _getPlatformTag() + "-" + hex;
sessionStorage.setItem(INSTANCE_NAME_KEY, name);
}
return name;
}
// --- Serialization ---
function _serializeArg(arg) {
if (arg === null) { return "null"; }
if (arg === undefined) { return "undefined"; }
if (typeof arg === "string") {
return arg.length > MAX_MESSAGE_LENGTH ? arg.substring(0, MAX_MESSAGE_LENGTH) + "..." : arg;
}
if (typeof arg === "number" || typeof arg === "boolean") {
return String(arg);
}
if (arg instanceof Error) {
return arg.stack || arg.message || String(arg);
}
try {
const seen = new Set();
const json = JSON.stringify(arg, function (key, value) {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) { return "[Circular]"; }
seen.add(value);
}
return value;
});
return json.length > MAX_MESSAGE_LENGTH ? json.substring(0, MAX_MESSAGE_LENGTH) + "..." : json;
} catch (e) {
return String(arg);
}
}
// --- Log buffering ---
function _pushLogEntry(level, args) {
const message = Array.from(args).map(_serializeArg).join(" ");
const entry = {
level: level,
message: message,
timestamp: new Date().toISOString()
};
logBuffer.push(entry);
capturedLogs.push(entry);
totalLogsPushed++;
// Cap buffer size — drop oldest entries to prevent unbounded memory growth
if (logBuffer.length > MAX_BUFFER_SIZE) {
logBuffer = logBuffer.slice(logBuffer.length - MAX_BUFFER_SIZE);
}
if (capturedLogs.length > MAX_BUFFER_SIZE) {
capturedLogs.splice(0, capturedLogs.length - MAX_BUFFER_SIZE);
}
if (logBuffer.length >= FLUSH_THRESHOLD && ws && ws.readyState === WebSocket.OPEN) {
_flushLogs();
}
}
function _flushLogs() {
if (!ws || ws.readyState !== WebSocket.OPEN || logBuffer.length === 0) {
return;
}
const entries = logBuffer;
logBuffer = [];
try {
ws.send(JSON.stringify({
type: "console_log",
entries: entries
}));
} catch (e) {
// Put them back if send failed
logBuffer = entries.concat(logBuffer);
}
}
// --- Console hooks ---
console.log = function () {
_pushLogEntry("log", arguments);
originalConsoleLog.apply(console, arguments);
};
console.info = function () {
_pushLogEntry("info", arguments);
originalConsoleInfo.apply(console, arguments);
};
console.warn = function () {
_pushLogEntry("warn", arguments);
originalConsoleWarn.apply(console, arguments);
};
console.error = function () {
_pushLogEntry("error", arguments);
originalConsoleError.apply(console, arguments);
};
// --- Error listeners ---
window.addEventListener("error", function (event) {
_pushLogEntry("error", ["[Uncaught Error] " + (event.message || "") +
(event.filename ? " at " + event.filename + ":" + event.lineno : "")]);
});
window.addEventListener("unhandledrejection", function (event) {
const reason = event.reason;
const msg = reason instanceof Error ? (reason.stack || reason.message) : String(reason);
_pushLogEntry("error", ["[Unhandled Promise Rejection] " + msg]);
});
// --- Message sending ---
function _sendMessage(msg) {
if (ws && ws.readyState === WebSocket.OPEN) {
try {
ws.send(JSON.stringify(msg));
} catch (e) {
// ignore
}
}
}
// --- Reconnect ---
function _scheduleReconnect() {
if (!autoReconnect || !currentUrl || reconnectTimer) { return; }
reconnectTimer = setTimeout(function () {
reconnectTimer = null;
if (!ws && currentUrl && autoReconnect) {
connect(currentUrl);
}
}, reconnectDelay);
reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
}
// --- Cleanup (does NOT unhook console — keeps buffering for reconnect) ---
function _cleanup() {
if (flushTimer) {
clearInterval(flushTimer);
flushTimer = null;
}
ws = null;
}
// --- Connect / disconnect ---
function connect(url) {
if (ws) {
disconnect();
}
currentUrl = url;
autoReconnect = true;
try {
ws = new WebSocket(url);
} catch (e) {
ws = null;
_scheduleReconnect();
return;
}
ws.onopen = function () {
reconnectDelay = RECONNECT_BASE_MS;
_sendMessage({ type: "hello", version: "1.0.0", name: _getOrCreateInstanceName() });
flushTimer = setInterval(_flushLogs, FLUSH_INTERVAL);
_flushLogs();
};
ws.onmessage = function (event) {
let msg;
try {
msg = JSON.parse(event.data);
} catch (e) {
return;
}
// Dispatch to registered handler, or built-in defaults
if (msg.type && handlers[msg.type]) {
handlers[msg.type](msg);
} else if (msg.type === "ping") {
_sendMessage({ type: "pong" });
}
};
ws.onclose = function () {
_cleanup();
_scheduleReconnect();
};
ws.onerror = function () {
// onclose will be called after this
};
}
function disconnect() {
autoReconnect = false;
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
if (ws) {
try {
ws.close(1000, "Disconnecting");
} catch (e) {
// ignore
}
_cleanup();
}
}
function isConnected() {
return ws !== null && ws.readyState === WebSocket.OPEN;
}
function getInstanceName() {
return _getOrCreateInstanceName();
}
function sendMessage(msg) {
_sendMessage(msg);
}
function registerHandler(type, fn) {
handlers[type] = fn;
}
// --- Register built-in handler for get_logs_request ---
// Returns the full capturedLogs buffer to the MCP server on demand.
registerHandler("get_logs_request", function (msg) {
const tail = typeof msg.tail === "number" ? msg.tail : 50;
const before = typeof msg.before === "number" ? msg.before : null;
const filterStr = msg.filter || null;
let source = capturedLogs;
if (filterStr) {
try {
const re = new RegExp(filterStr, "i");
source = capturedLogs.filter(function (e) { return re.test(e.message); });
} catch (e) {
// invalid regex — skip filtering
source = capturedLogs;
}
}
const matchedEntries = source.length;
const endIdx = before != null ? Math.max(0, Math.min(matchedEntries, before)) : matchedEntries;
let entries;
if (tail === 0) {
entries = source.slice(0, endIdx);
} else {
const startIdx = Math.max(0, endIdx - tail);
entries = source.slice(startIdx, endIdx);
}
_sendMessage({
type: "get_logs_response",
id: msg.id,
entries: entries,
totalEntries: totalLogsPushed,
matchedEntries: matchedEntries,
rangeEnd: endIdx
});
});
// --- Register built-in boot-time handler for reload_request ---
// Simple fallback: just reload. The AMD module upgrades this to FILE_CLOSE_ALL + reload.
registerHandler("reload_request", function (msg) {
_sendMessage({
type: "reload_response",
id: msg.id,
success: true
});
setTimeout(async function () {
await _dismantleTrustRing();
location.reload();
}, 100);
});
// --- Register built-in handler for exec_js_request ---
// Evaluates arbitrary JS in the page context and returns the result.
// `__kernalModeTrust` is available inside exec_js code for dev/test access.
registerHandler("exec_js_request", function (msg) {
const AsyncFunction = (async function () {}).constructor;
const fn = new AsyncFunction("__kernalModeTrust", msg.code);
fn(_kernalModeTrust).then(function (result) {
_sendMessage({
type: "exec_js_response",
id: msg.id,
result: _serializeArg(result)
});
}).catch(function (err) {
_sendMessage({
type: "exec_js_response",
id: msg.id,
error: (err && err.stack) || (err && err.message) || String(err)
});
});
});
// --- Expose API for AMD module ---
// Phoenix builder should never be in prod builds as it exposes the kernal mode trust.
// for prod mcp controls, we need to expose this with another framework that has
// restricted access to the trust framework.
window._phoenixBuilder = {
connect: connect,
disconnect: disconnect,
isConnected: isConnected,
getInstanceName: getInstanceName,
sendMessage: sendMessage,
registerHandler: registerHandler,
getLogBuffer: function () { return capturedLogs.slice(); },
dismantleTrustRing: _dismantleTrustRing,
// Called once by trust_ring.js to pass the trust ring reference
// before it is nuked from window. Set-only, no getter.
setKernalModeTrust: function (trust) {
_kernalModeTrust = trust;
delete window._phoenixBuilder.setKernalModeTrust;
}
};
// --- Auto-connect ---
const wsUrl = localStorage.getItem("phoenixBuilderWsUrl") || DEFAULT_WS_URL;
connect(wsUrl);
}());