-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
490 lines (443 loc) · 17.8 KB
/
index.html
File metadata and controls
490 lines (443 loc) · 17.8 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
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Raybox</title>
<style>
body {
margin: 0;
background: #1a1a1a;
width: 100vw;
height: 100vh;
overflow: hidden;
}
canvas {
display: block;
width: 100vw;
height: 100vh;
}
#overlay {
position: absolute;
top: 10px;
left: 10px;
color: #fff;
font-family: monospace;
font-size: 14px;
background: rgba(0, 0, 0, 0.5);
padding: 10px;
border-radius: 4px;
white-space: pre;
pointer-events: none;
}
#reload-indicator {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0, 0, 0, 0.8);
color: #0f0;
padding: 20px 40px;
border-radius: 8px;
font-family: monospace;
font-size: 18px;
display: none;
z-index: 1000;
}
#startup-error {
position: fixed;
inset: 24px;
display: none;
z-index: 1100;
padding: 20px 24px;
background: rgba(18, 18, 20, 0.96);
color: #f3f4f6;
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: 10px;
font-family: monospace;
overflow: auto;
white-space: pre-wrap;
}
#startup-error h2 {
margin: 0 0 12px;
font-size: 20px;
}
#startup-error pre {
margin: 12px 0 0;
padding: 12px;
background: rgba(255, 255, 255, 0.06);
border-radius: 6px;
overflow: auto;
}
#runtime-error {
position: fixed;
right: 16px;
bottom: 16px;
max-width: min(560px, calc(100vw - 32px));
max-height: min(40vh, calc(100vh - 32px));
display: none;
z-index: 1200;
padding: 12px 14px;
background: rgba(60, 12, 12, 0.94);
color: #fff3f3;
border: 1px solid rgba(255, 190, 190, 0.35);
border-radius: 8px;
font-family: monospace;
font-size: 12px;
overflow: auto;
white-space: pre-wrap;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="600"></canvas>
<div id="overlay"></div>
<div id="reload-indicator">Reloading...</div>
<div id="startup-error"></div>
<div id="runtime-error"></div>
<script type="module">
// Parse URL parameters
const params = new URLSearchParams(window.location.search);
const initialDemo = parseInt(params.get('demo') || '1');
const controlEnabled = params.get('control') === '1' || params.get('control') === 'true';
const hotReloadEnabled = params.get('hotreload') === '1' || params.get('hotreload') === 'true';
const controlUrl = params.get('control_url') || 'ws://127.0.0.1:9300';
// State for hot-reload
let wasmModule = null;
let savedStateJson = null;
let hotReloadWs = null;
const debugEvents = [];
const DEBUG_LOG_STORAGE_KEY = 'raybox_last_debug_log';
const DEBUG_LOG_LIMIT = 200;
function formatDebugArg(value) {
if (value instanceof Error) {
return `${value.name}: ${value.message}${value.stack ? `\n${value.stack}` : ''}`;
}
if (typeof value === 'string') {
return value;
}
try {
return JSON.stringify(value);
} catch (_) {
return String(value);
}
}
function recordDebugEvent(level, message, detail = null) {
debugEvents.push({
timestamp: new Date().toISOString(),
level,
message: String(message),
detail,
});
if (debugEvents.length > DEBUG_LOG_LIMIT) {
debugEvents.shift();
}
persistDebugLog();
}
function persistDebugLog() {
try {
localStorage.setItem(DEBUG_LOG_STORAGE_KEY, JSON.stringify(debugEvents));
} catch (_) {
}
}
function loadPersistedDebugLog() {
try {
const raw = localStorage.getItem(DEBUG_LOG_STORAGE_KEY);
if (!raw) {
return;
}
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) {
return;
}
debugEvents.length = 0;
for (const item of parsed.slice(-DEBUG_LOG_LIMIT)) {
debugEvents.push(item);
}
} catch (_) {
}
}
const originalConsole = {
log: console.log.bind(console),
info: console.info.bind(console),
warn: console.warn.bind(console),
error: console.error.bind(console),
};
console.log = (...args) => {
recordDebugEvent('log', args.map(formatDebugArg).join(' '));
originalConsole.log(...args);
};
console.info = (...args) => {
recordDebugEvent('info', args.map(formatDebugArg).join(' '));
originalConsole.info(...args);
};
console.warn = (...args) => {
recordDebugEvent('warn', args.map(formatDebugArg).join(' '));
originalConsole.warn(...args);
};
console.error = (...args) => {
recordDebugEvent('error', args.map(formatDebugArg).join(' '));
originalConsole.error(...args);
};
function showRuntimeError(title, detail) {
const element = document.getElementById('runtime-error');
element.textContent = `${title}\n\n${detail}`;
element.style.display = 'block';
}
function clearRuntimeError() {
const element = document.getElementById('runtime-error');
element.style.display = 'none';
element.textContent = '';
}
window.rayboxGetDebugLog = () => JSON.stringify(debugEvents, null, 2);
window.rayboxClearDebugLog = () => {
debugEvents.length = 0;
persistDebugLog();
clearRuntimeError();
return true;
};
window.rayboxReportRuntimeError = (title, detail) => {
recordDebugEvent('runtime-error', title, detail);
showRuntimeError(title, detail);
};
window.rayboxDebugControlState = () => {
if (!wasmModule || typeof wasmModule.debug_control_state !== 'function') {
return '{"hasWasmModule":false}';
}
return wasmModule.debug_control_state();
};
window.addEventListener('error', (event) => {
const detail = [
`message: ${event.message || '(no message)'}`,
event.filename ? `file: ${event.filename}:${event.lineno || 0}:${event.colno || 0}` : '',
event.error && event.error.stack ? `stack:\n${event.error.stack}` : '',
].filter(Boolean).join('\n');
recordDebugEvent('window-error', event.message || 'Unhandled error', detail);
showRuntimeError('Raybox runtime error', detail);
});
window.addEventListener('unhandledrejection', (event) => {
const detail = formatDebugArg(event.reason);
recordDebugEvent('unhandledrejection', 'Unhandled promise rejection', detail);
showRuntimeError('Raybox unhandled promise rejection', detail);
});
// Show/hide reload indicator
function showReloadIndicator(show) {
document.getElementById('reload-indicator').style.display = show ? 'block' : 'none';
}
function startupCommandsText() {
const justCommand = hotReloadEnabled ? 'just open-browser-hotreload' : 'just open-browser';
const ctlFlags = [
'cargo run --bin raybox-ctl --features control -- web-open',
controlEnabled ? '--control' : '',
hotReloadEnabled ? '--hotreload' : '',
].filter(Boolean).join(' ');
return `${justCommand}\n${ctlFlags}`;
}
function startupFlagsText() {
return [
'--no-first-run',
'--no-default-browser-check',
'--disable-extensions',
'--disable-component-extensions-with-background-pages',
'--disable-background-networking',
'--disable-sync',
'--disable-default-apps',
'--disable-component-update',
'--metrics-recording-only',
'--no-service-autorun',
'--enable-unsafe-webgpu',
'--enable-webgpu-developer-features',
'--force-webgpu',
'--ignore-gpu-blocklist',
'--enable-vulkan',
'--use-angle=vulkan',
'--disable-software-rasterizer',
'--ozone-platform=x11',
'--enable-features=UnsafeWebGPU,SharedArrayBufferOnDesktop,Vulkan,VulkanFromANGLE,DefaultANGLEVulkan,UseSkiaRenderer',
'--remote-debugging-port=9222',
].join('\n');
}
function clearStartupError() {
const element = document.getElementById('startup-error');
element.style.display = 'none';
element.innerHTML = '';
}
function escapeHtml(value) {
return String(value)
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>');
}
function showStartupError(title, detail, rawError) {
const element = document.getElementById('startup-error');
const raw = rawError ? `\n\nRaw error:\n${String(rawError)}` : '';
element.innerHTML = `
<h2>${escapeHtml(title)}</h2>
<div>${escapeHtml(detail)}</div>
<pre>${escapeHtml(`Supported Chromium/WebGPU flags:
${startupFlagsText()}
Recommended launch commands:
${startupCommandsText()}
If Chromium is already running on another profile, use the commands above so Raybox launches an isolated profile with the correct flags.${raw}`)}</pre>
`;
element.style.display = 'block';
}
async function preflightWebGpu() {
const canvas = document.getElementById('canvas');
if (!navigator.gpu) {
throw new Error('WebGPU unavailable: navigator.gpu is undefined in this browser session.');
}
const context = canvas.getContext('webgpu');
if (!context) {
throw new Error('WebGPU canvas context unavailable: canvas.getContext("webgpu") returned null.');
}
let adapter = null;
try {
adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
} catch (_) {
adapter = null;
}
if (!adapter) {
try {
adapter = await navigator.gpu.requestAdapter();
} catch (_) {
adapter = null;
}
}
if (!adapter) {
throw new Error('No WebGPU adapter found: requestAdapter() returned null.');
}
}
// Load and initialize WASM module
async function loadWasm() {
// Add cache-busting timestamp for hot-reload
const timestamp = hotReloadEnabled ? `?t=${Date.now()}` : '';
const module = await import(`./pkg/raybox.js${timestamp}`);
await module.default();
return module;
}
// Main initialization
async function init() {
try {
loadPersistedDebugLog();
clearStartupError();
clearRuntimeError();
await preflightWebGpu();
wasmModule = await loadWasm();
// Restore state if we have saved state from a previous reload
if (savedStateJson && savedStateJson !== '{}') {
wasmModule.restore_state(savedStateJson);
savedStateJson = null;
}
await wasmModule.start_with_demo(initialDemo);
console.log('Raybox initialized, demo:', initialDemo);
} catch (e) {
console.error('Failed to initialize WASM:', e);
wasmModule = null;
showStartupError(
'Raybox WebGPU startup failed',
'Raybox requires a Chromium/WebGPU session launched with the supported flags. The page reached the bootstrap path, but WebGPU startup did not complete.',
e
);
persistDebugLog();
}
}
// Hot-reload: save state, reload WASM, restore state
async function performHotReload() {
if (!wasmModule) {
console.warn('No WASM module loaded, skipping hot-reload');
return;
}
console.log('Hot-reload triggered');
showReloadIndicator(true);
clearRuntimeError();
try {
// Save current state
savedStateJson = wasmModule.save_state_for_reload();
console.log('Saved state:', savedStateJson);
// Clean up current module
wasmModule.cleanup_for_reload();
// Brief delay to allow GPU resources to be released
await new Promise(resolve => setTimeout(resolve, 100));
// Reload WASM module (with cache-busting)
wasmModule = await loadWasm();
// Restore state
if (savedStateJson && savedStateJson !== '{}') {
wasmModule.restore_state(savedStateJson);
savedStateJson = null;
}
await wasmModule.start_with_demo(initialDemo);
console.log('Hot-reload completed');
} catch (e) {
console.error('Hot-reload failed:', e);
showStartupError(
'Raybox WebGPU hot-reload failed',
'The WASM bundle reloaded, but the browser session did not complete WebGPU startup again. Relaunch Chromium with the supported Raybox flags.',
e
);
} finally {
showReloadIndicator(false);
}
}
// Set up WebSocket for hot-reload notifications
function setupHotReloadWebSocket() {
if (!hotReloadEnabled) return;
const wsUrl = params.get('reload_url') || controlUrl;
console.log('Connecting to hot-reload WebSocket:', wsUrl);
try {
hotReloadWs = new WebSocket(wsUrl);
hotReloadWs.onopen = () => {
console.log('Hot-reload WebSocket connected');
};
hotReloadWs.onmessage = async (event) => {
try {
const data = JSON.parse(event.data);
// Check for reload command (either direct or via control protocol)
if (data.command?.type === 'reload' ||
data.command?.type === 'reloadWasm' ||
data.type === 'reload') {
await performHotReload();
// Send success response if it was a command with an ID
if (data.id !== undefined) {
hotReloadWs.send(JSON.stringify({
id: data.id,
response: { type: 'success', data: { message: 'reload_complete' } }
}));
}
}
// Check for WasmReload event from dev server
else if (data.event?.type === 'wasmReload') {
console.log('Received wasmReload event from dev server');
await performHotReload();
}
// Check for BuildCompleted event (as fallback)
else if (data.event?.type === 'buildCompleted' && data.event?.success) {
console.log('Build completed, reloading WASM...');
await performHotReload();
}
} catch (e) {
// Might be a plain text message
if (event.data === 'reload') {
await performHotReload();
}
}
};
hotReloadWs.onclose = () => {
console.log('Hot-reload WebSocket disconnected, reconnecting...');
setTimeout(setupHotReloadWebSocket, 2000);
};
hotReloadWs.onerror = (e) => {
console.error('Hot-reload WebSocket error:', e);
};
} catch (e) {
console.error('Failed to setup hot-reload WebSocket:', e);
setTimeout(setupHotReloadWebSocket, 2000);
}
}
// Expose performHotReload globally for manual triggering
window.rayboxHotReload = performHotReload;
// Initialize
await init();
setupHotReloadWebSocket();
</script>
</body>
</html>