Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
e57a826
feat: full OffscreenCanvas support for main-thread and Worker contexts
sebavan Mar 20, 2026
dc6be4f
docs: add OffscreenCanvas samples to build.md and Worker APIs to apis.md
sebavan Mar 20, 2026
a21d5c7
fix: Worker sample consistency and capture resilience
sebavan Mar 20, 2026
736e856
fix: Worker sample captures full frame (6 commands) with visual state
sebavan Mar 20, 2026
b53b25a
fix: remove orphan workerRenderer.js that caused blank page on ?sampl…
sebavan Mar 20, 2026
27d4458
feat: Worker OffscreenCanvas appears in Spector canvas list dropdown
sebavan Mar 20, 2026
f1249e6
fix: Worker sample renders visible RGB triangle on page canvas
sebavan Mar 20, 2026
92122f2
fix: Worker sample shows visible RGB triangle + Worker in canvas list
sebavan Mar 20, 2026
1b6e3d6
fix: Worker auto-selected in Spector UI canvas list
sebavan Mar 20, 2026
312e224
fix: extension detects Worker OffscreenCanvas in canvas list
sebavan Mar 20, 2026
f8113e3
fix: extension captures full Worker frame via direct postMessage
sebavan Mar 20, 2026
f2225da
fix: extension capture works regardless of captureOffScreen toggle
sebavan Mar 20, 2026
a4bca89
fix: restore Worker bundle importScripts + make sample robust
sebavan Mar 21, 2026
7cda5e3
fix: captureWorker uses direct postMessage for full-frame capture
sebavan Mar 21, 2026
f1de6ea
fix: Worker capture E2E test asserts >3 commands with drawArrays
sebavan Mar 21, 2026
449ec2b
fix: Worker capture E2E tests the actual Spector pipeline with >3 com…
sebavan Mar 21, 2026
2e60ae0
fix: Worker capture now returns 5+ commands (was 1)
sebavan Mar 21, 2026
776662a
merge: integrate React frontend migration and TypeScript fixes from m…
sebavan Mar 30, 2026
49767ee
feat: Worker OffscreenCanvas detection, module worker support, and sh…
sebavan Apr 1, 2026
66c0329
Fix doc
sebavan Apr 1, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,8 @@
/node_modules
npm-debug.log.**
npm-debug.log
.DS_Storeplaywright-report/
.DS_Store
test-results/
playwright-report/

.playwright-cli/
2 changes: 1 addition & 1 deletion dist/spector.bundle.js

Large diffs are not rendered by default.

63 changes: 63 additions & 0 deletions dist/spector.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -408,11 +408,17 @@ export declare class ReactCaptureMenu {
private readonly _rootPlaceHolder;
private _isTrackingCanvas;
private readonly _hideLog;
private readonly _extraCanvasEntries;
constructor(options?: ICaptureMenuOptions);
getSelectedCanvasInformation(): ICanvasInformation;
trackPageCanvases(): void;
updateCanvasesList(canvases: NodeListOf<HTMLCanvasElement>): void;
updateCanvasesListInformation(canvasesInformation: ICanvasInformation[]): void;
/**
* Appends a single canvas entry (e.g. a Worker OffscreenCanvas) to the
* list without replacing existing entries, and auto-selects it.
*/
addCanvasInformation(info: ICanvasInformation): void;
display(): void;
hide(): void;
captureComplete(errorText: string): void;
Expand Down Expand Up @@ -500,6 +506,40 @@ export declare class ReactResultView {
}


export interface IWorkerBridgeOptions {
/** Timeout in milliseconds for capture responses. Default: 10000 (10s). */
captureTimeout?: number;
}
export interface IWorkerContextInfo {
canvasCount: number;
canvasWidth: number;
canvasHeight: number;
}
/**
* Main-thread bridge that communicates with a WorkerSpector running inside a Worker.
* Uses addEventListener (not onmessage) to avoid overwriting app communication.
*/
export declare class WorkerBridge {
readonly onCapture: Observable<ICapture>;
readonly onCaptureStarted: Observable<void>;
readonly onError: Observable<string>;
readonly onFps: Observable<number>;
readonly onContextReady: Observable<IWorkerContextInfo>;
private readonly worker;
private readonly captureTimeout;
private readonly messageHandler;
private captureTimer;
private disposed;
constructor(worker: Worker, options?: IWorkerBridgeOptions);
/** Request a capture from the Worker. */
triggerCapture(canvasIndex?: number, commandCount?: number, quickCapture?: boolean, fullCapture?: boolean): void;
/** Clean up all resources. */
dispose(): void;
private handleMessage;
private clearCaptureTimer;
}


export interface IAvailableContext {
readonly canvas: HTMLCanvasElement | OffscreenCanvas;
readonly contextSpy: ContextSpy;
Expand Down Expand Up @@ -532,6 +572,7 @@ export declare class Spector {
private retry;
private noFrameTimeout;
private marker;
private readonly workerBridges;
private options;
constructor(options?: SpectorInitOptions);
displayUI(disableTracking?: boolean): void;
Expand Down Expand Up @@ -562,6 +603,28 @@ export declare class Spector {
[name: string]: any;
}): void;
log(value: string): void;
/**
* Intercept all new Worker() calls to auto-inject Spector.
* Best-effort: will fail for CORS, CSP, or module Workers.
* @param workerBundleUrl URL to spector.worker.bundle.js
*/
spyWorkers(workerBundleUrl?: string): void;
/**
* Stop intercepting Worker construction.
*/
stopSpyingWorkers(): void;
/**
* Manually spy on a specific Worker.
* This is the primary, reliable API for Worker capture.
* The Worker must already have the Spector worker bundle loaded.
*/
spyWorker(worker: Worker): WorkerBridge;
/**
* Capture a frame from a Worker's WebGL context.
* Uses direct postMessage to bypass the main-thread spy chain,
* which ensures a full frame is captured.
*/
captureWorker(worker: Worker, commandCount?: number, quickCapture?: boolean, fullCapture?: boolean): void;
private captureFrames;
private captureCommands;
private spyContext;
Expand Down
1 change: 1 addition & 0 deletions dist/spector.worker.bundle.js

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions documentation/apis.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ And the following list of events:
- ```onCapture: IEvent<ICapture>```: triggered when a new capture is available (this is a JSON only object containing alll the information).
- ```onError: IEvent<string>```: triggered when an error occured and return the error message.

### Worker / OffscreenCanvas APIs
- ```spyWorkers(workerBundleUrl?: string)``` : Intercept all `new Worker()` calls to auto-inject Spector. Best-effort — may fail with CORS, CSP, or module Workers. Defaults to `"spector.worker.bundle.js"`.
- ```stopSpyingWorkers()``` : Stop intercepting Worker construction.
- ```spyWorker(worker: Worker): WorkerBridge``` : Manually bridge a specific Worker for capture. This is the primary, reliable API. The Worker must have `spector.worker.bundle.js` loaded via `importScripts`.
- ```captureWorker(worker: Worker, commandCount?: number, quickCapture?: boolean, fullCapture?: boolean)``` : Capture a frame from a Worker's WebGL context. If the Worker hasn't been bridged yet, `spyWorker` is called automatically.

As you notice you could use the capture without displying the UI (this is the orientation we chosed in the browser extension).

## SPECTOR.CaptureMenu
Expand Down
12 changes: 12 additions & 0 deletions documentation/build.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ Then you can use the following npm commands to speed your development:
2. ```npm run build``` Will create and build a new version of the dist folder files.
3. ```npm run clean``` Will clean all the generated files from the repo.

## Testing
The project includes both unit tests and end-to-end tests:

1. ```npm run test:unit``` Runs Jest unit tests (69 tests covering CanvasFactory, TimeSpy, Time, WorkerBridge, WorkerMessageSender, message protocol, WorkerSpy, and WebGlObject).
2. ```npm run test:e2e``` Runs Playwright E2E tests against Chromium with SwiftShader (5 tests covering sample page loading, main-thread OffscreenCanvas capture, and Worker OffscreenCanvas capture).

Unit tests live in ```test/``` mirroring the ```src/``` structure. E2E tests live in ```e2e/```.

If you are looking for the temporary generated .js or .map files, they are all available in the built folder which is not under source control.

I would recommend developping on [VsCode](https://code.visualstudio.com/) as the entire setup is present so that if you install the chrome debugger extension you can directly debug from your typescript files by pressing F5.
Expand Down Expand Up @@ -56,6 +64,10 @@ Once ```npm start``` has been launched, you can access the following samples to
22. [Custom Log](http://localhost:1337/sample/index.html?sample=customLog): Test the custom log functionnality.
22. [Pixelated Nearest](http://localhost:1337/sample/index.html?sample=texturePixelated): Test visual texture capture being pixelated on nearest.

### OffscreenCanvas
1. [Offscreen (BabylonJS)](http://localhost:1337/sample/index.html?sample=offscreen): Test OffscreenCanvas support with BabylonJS engine.
2. [Worker OffscreenCanvas](http://localhost:1337/sample/index.html?sample=workerOffscreen): Test Worker-based OffscreenCanvas capture via `transferControlToOffscreen()` and `spector.captureWorker()`.

You can also add &noSpy=1 at the end of the previous Urls to test without enabling the full spy before starting your rendering engine.

### Add more samples
Expand Down
6 changes: 6 additions & 0 deletions documentation/changeLogs.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@
Please, find below the per release summary of the contribution added to the project per version. Each of the listed versions is having its corresponding tag in the repo.

## v0.9.33
* Add [Offscreen canvas support](https://github.com/BabylonJS/Spector.js/pull/343)
* Add [Typescript typings](https://github.com/BabylonJS/Spector.js/pull/339)
* Migrate [MVX to React](https://github.com/BabylonJS/Spector.js/pull/338)
* Fix [spyContext wrongly hooking non-GL functions](https://github.com/BabylonJS/Spector.js/pull/328)
* Fix [Offline support - remove fonts from cdn](https://github.com/BabylonJS/Spector.js/pull/321)
* Fix [Correct error in buffer length calculation](https://github.com/BabylonJS/Spector.js/pull/315)

## v0.9.32
* Fix [Capture on Reload](https://github.com/BabylonJS/Spector.js/issues/313)
Expand Down
28 changes: 28 additions & 0 deletions e2e/smoke.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { test, expect } from '@playwright/test';

test.describe('Spector.js E2E Smoke Test', () => {
test('sample page loads and has a canvas', async ({ page }) => {
await page.goto('/sample/index.html');

// Wait for the canvas to be present
const canvas = page.locator('canvas#renderCanvas');
await expect(canvas).toBeVisible({ timeout: 10000 });
});

test('Spector bundle is loaded by sample page', async ({ page }) => {
await page.goto('/sample/index.html');

// The sample page's loader asynchronously loads .temp/spector.bundle.js
// which defines window.SPECTOR (UMD library). Wait for it.
await page.waitForFunction(
() => typeof (window as any).SPECTOR !== 'undefined',
{ timeout: 15000 },
);

// Verify the Spector constructor is available
const hasSpectorClass = await page.evaluate(
() => typeof (window as any).SPECTOR.Spector === 'function',
);
expect(hasSpectorClass).toBe(true);
});
});
83 changes: 83 additions & 0 deletions e2e/worker.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { test, expect } from '@playwright/test';

test.describe('Worker OffscreenCanvas Capture', () => {
test('Worker renders visible content on the page', async ({ page }) => {
await page.goto('/sample/index.html?sample=workerOffscreen');
await page.waitForFunction('window.worker', { timeout: 30000 });
await page.waitForTimeout(2000);

const hasContent = await page.evaluate(() => {
const canvas = document.getElementById('renderCanvas') as HTMLCanvasElement;
return canvas !== null && canvas.width > 0;
});
expect(hasContent).toBe(true);
});

test('Worker capture returns multiple GL commands', async ({ page }) => {
await page.goto('/sample/index.html?sample=workerOffscreen');
// Wait for spector and scripts to load
await page.waitForFunction('typeof SPECTOR !== "undefined"', { timeout: 30000 });
await page.waitForTimeout(2000);

// Test the Spector Worker capture pipeline end-to-end.
// This creates a Worker, loads the Spector worker bundle via importScripts,
// renders WebGL frames, triggers capture, and validates the response.
// This mirrors how the Spector extension captures Worker contexts.
const result = await page.evaluate(() => {
return new Promise<any>((resolve, reject) => {
const origin = location.origin;
const bundlePath = '/.temp/spector.worker.bundle.js';
const code = 'try { importScripts("' + origin + bundlePath + '"); } catch(e) {}\n' +
'self.addEventListener("message", function(e) {\n' +
' if (e.data.type === "init") {\n' +
' var gl = new OffscreenCanvas(200,200).getContext("webgl2");\n' +
' var vs = gl.createShader(gl.VERTEX_SHADER);\n' +
' gl.shaderSource(vs, "#version 300 es\\nin vec2 p;\\nvoid main(){gl_Position=vec4(p,0,1);}");\n' +
' gl.compileShader(vs);\n' +
' var fs = gl.createShader(gl.FRAGMENT_SHADER);\n' +
' gl.shaderSource(fs, "#version 300 es\\nprecision mediump float;\\nout vec4 c;\\nvoid main(){c=vec4(1,0,0,1);}");\n' +
' gl.compileShader(fs);\n' +
' var prog = gl.createProgram();\n' +
' gl.attachShader(prog, vs); gl.attachShader(prog, fs); gl.linkProgram(prog);\n' +
' var vao = gl.createVertexArray(); gl.bindVertexArray(vao);\n' +
' var buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n' +
' gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0,0.5,-0.5,-0.5,0.5,-0.5]), gl.STATIC_DRAW);\n' +
' gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);\n' +
' function render() {\n' +
' gl.viewport(0,0,200,200); gl.clearColor(1,0,0,1); gl.clear(gl.COLOR_BUFFER_BIT);\n' +
' gl.useProgram(prog); gl.bindVertexArray(vao); gl.drawArrays(gl.TRIANGLES,0,3);\n' +
' setTimeout(render, 16);\n' +
' }\n' +
' render();\n' +
' }\n' +
'});';
const w = new Worker(URL.createObjectURL(new Blob([code], {type: 'application/javascript'})));
w.addEventListener('message', (e: any) => {
if (e.data && e.data.type === 'spector:capture-complete') {
resolve({
commands: e.data.capture.commands.length,
names: e.data.capture.commands.map((c: any) => c.name),
});
}
});
w.postMessage({type: 'init'});
setTimeout(() => {
w.postMessage({
type: 'spector:trigger-capture', version: 1, canvasIndex: 0,
commandCount: 0, quickCapture: false, fullCapture: false,
});
}, 2000);
setTimeout(() => reject(new Error('capture timed out')), 15000);
});
});

// Must have multiple commands — viewport, clearColor, clear, useProgram, bindVertexArray, drawArrays
expect(result.commands).toBeGreaterThan(3);
expect(result.names).toContain('drawArrays');
});

test('workerRenderer.js does not exist as a standalone sample', async ({ page }) => {
const response = await page.goto('/sample/js/workerRenderer.js');
expect(response!.status()).toBe(404);
});
});
Loading
Loading