@acertijosapps/electron-viewer 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AcertijosApps
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,227 @@
1
- # Temporary Holding Version
1
+ # @acertijosapps/electron-viewer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Live viewer for Electron apps in the browser, plus an MCP server so an AI agent can drive them.
4
+ Built for the browser pane of AI coding tools (such as Claude Code): you and the agent watch and
5
+ control the same app window, in real time.
6
+
7
+ <img src="https://unpkg.com/@acertijosapps/electron-viewer/media/viewer.jpg" width="560" alt="Electron Viewer showing the example app: window selector and launch button on top, the live window in the middle, and the reload, DevTools, window size, frame and screenshot controls at the bottom" />
8
+
9
+ - **Live video**: `Page.startScreencast` from the Chrome DevTools Protocol (CDP) over WebSocket. It keeps
10
+ streaming while the app window is covered or minimized.
11
+ - **Real input**: mouse move and hover, click, double click, right click, drag, wheel and full keyboard
12
+ passthrough (including ⌘C/⌘V/⌘A on macOS, IME and dictation).
13
+ - **Every app and window**: launch your project with `electron .` from the viewer, or attach to any app
14
+ started with `--remote-debugging-port`. Apps on ports 9222–9231 are found automatically.
15
+ - **Main process too**: launched apps also expose their main process (Node inspector), so the agent can
16
+ run code there, resize the real window, open DevTools and capture the native frame.
17
+ - **Native frame capture**: title bar, context menus and dialogs on top of the window.
18
+ - **MCP server**: the same actions as tools, plus JavaScript in the renderer and main process, the
19
+ accessibility tree with click-ready coordinates, and console logs.
20
+ - **Nothing to add to your app**: no preload, no dependency, no code changes.
21
+
22
+ ## Requirements
23
+
24
+ - Node.js 18 or later.
25
+ - An Electron app. To launch it from the viewer, the project must have `electron` in its
26
+ `node_modules` (`npm install --save-dev electron`); if its binary hasn't been downloaded yet, the
27
+ viewer downloads it on the first launch.
28
+ - Works on macOS, Linux and Windows.
29
+
30
+ ## Quick start
31
+
32
+ From your Electron project folder:
33
+
34
+ ```sh
35
+ npx @acertijosapps/electron-viewer
36
+ ```
37
+
38
+ Open <http://localhost:8094> and click **Launch**. The viewer runs `electron .` on free debugging
39
+ ports (CDP from 9222, Node inspector from 9229). Deep link to a window: `?window=<target id>`.
40
+
41
+ If your app is started by another tool (Electron Forge, electron-vite, a custom script), pass the flags
42
+ yourself and the viewer finds it:
43
+
44
+ ```sh
45
+ electron --remote-debugging-port=9222 --inspect=9229 .
46
+ ```
47
+
48
+ `--inspect` is optional; without it you get everything except the main-process features
49
+ (`evaluate_main`, frame capture, real window resizing and in-app DevTools). To attach on another
50
+ port, use the form in the viewer or `--attach`.
51
+
52
+ ```text
53
+ electron-viewer [options] Start the viewer
54
+ electron-viewer mcp [options] Start the MCP server on stdio
55
+
56
+ --project <dir> Project to launch with "electron ." (default: current folder)
57
+ -p, --port <port> Viewer port (default 8094, env PORT)
58
+ --host <host> Interface to bind (default 127.0.0.1, env HOST)
59
+ --attach <port> Attach at startup to an app on this CDP port
60
+ --inspect <port> With --attach: the app's main process inspector port
61
+ --viewer-url <url> Viewer the MCP talks to (default http://localhost:8094)
62
+ ```
63
+
64
+ Other environment variables: `MAX_DIM` (longest side of the streamed frames, default 1920), `QUALITY`
65
+ (JPEG quality, default 80), `SCREENSHOT_MAX` (longest side of MCP screenshots, default 1024),
66
+ `CDP_PORT` / `INSPECT_PORT` (first ports to scan and launch on, default 9222 / 9229) and
67
+ `ELECTRON_VIEWER_STATE_DIR` (where launched and attached apps are remembered, default
68
+ `~/.cache/electron-viewer`).
69
+
70
+ ## Use it with an AI agent (MCP)
71
+
72
+ Claude Code:
73
+
74
+ ```sh
75
+ claude mcp add electron-viewer -- npx -y @acertijosapps/electron-viewer mcp
76
+ ```
77
+
78
+ Any other MCP client:
79
+
80
+ ```json
81
+ {
82
+ "mcpServers": {
83
+ "electron-viewer": {
84
+ "command": "npx",
85
+ "args": ["-y", "@acertijosapps/electron-viewer", "mcp"]
86
+ }
87
+ }
88
+ }
89
+ ```
90
+
91
+ Also listed in the [official MCP Registry](https://registry.modelcontextprotocol.io) as
92
+ `io.github.acertijosapps/electron-viewer`.
93
+
94
+ Keep the viewer running (`npx @acertijosapps/electron-viewer`) to watch what the agent does. Without
95
+ it, the MCP drives the app over CDP directly. Apps launched by either one are visible to the other.
96
+
97
+ | Tool | What it does |
98
+ | --- | --- |
99
+ | `list_windows` | Running apps (with `main` when the main process is reachable) and their windows |
100
+ | `launch_app` | Run `electron .` in the project on free debugging ports and wait for the first window |
101
+ | `attach` | Attach to an app on a CDP port, optionally with its inspector port |
102
+ | `screenshot` | PNG of the window content, longest side ≤ 1024 px; `frame: true` adds the native frame, menus and dialogs |
103
+ | `click` | Left, right or middle click; `count: 2` for a double click; optional modifiers |
104
+ | `drag` | Press, move in steps and release: a real drag |
105
+ | `hover` | Move the mouse without clicking |
106
+ | `scroll` | Mouse wheel at a point, deltas in CSS px |
107
+ | `type_text` | Insert text into the focused element (any Unicode) |
108
+ | `press_key` | Enter, Tab, Escape, arrows, F1–F12… or any character, with modifiers |
109
+ | `resize_window` | Resize the content area (the real window with the main process, emulated without it) |
110
+ | `reload` | Reload the window's page |
111
+ | `evaluate` | Run JavaScript in the window's page and return the value |
112
+ | `evaluate_main` | Run JavaScript in the main process, with `require('electron')` available |
113
+ | `get_accessibility_tree` | Roles, names, values and states; interactive elements carry their normalized center |
114
+ | `get_console_logs` | Console messages and exceptions from renderer windows and the main process, or the raw stdout |
115
+
116
+ Coordinates are normalized to `0–1` over the content screenshot (`x = pixel_x / image_width`), so they
117
+ hold at any window size. `window` is optional when only one window is open; it takes the target id
118
+ from `list_windows` or part of the window title.
119
+
120
+ ### In the Claude Code browser pane
121
+
122
+ Add the viewer to `.claude/launch.json` and open it with `preview_start electron-viewer`:
123
+
124
+ ```json
125
+ {
126
+ "version": "0.0.1",
127
+ "configurations": [
128
+ {
129
+ "name": "electron-viewer",
130
+ "runtimeExecutable": "npx",
131
+ "runtimeArgs": ["-y", "@acertijosapps/electron-viewer"],
132
+ "port": 8094,
133
+ "autoPort": false
134
+ }
135
+ ]
136
+ }
137
+ ```
138
+
139
+ ## Native frame capture
140
+
141
+ The **frame** button (and `screenshot` with `frame: true`) captures the screen area of the window from
142
+ the main process with `desktopCapturer`: the title bar, native context menus and dialogs on top of the
143
+ window show up, at a few frames per second. Anything else covering the window shows up too, and the
144
+ macOS menu bar at the top of the screen is not included. In frame mode, clicks on the content still
145
+ work; the title bar and native menus can't be clicked from the viewer.
146
+
147
+ On macOS the app needs the **Screen Recording** permission (System Settings › Privacy & Security ›
148
+ Screen & System Audio Recording). For an app run with `electron .`, that is the `Electron.app` inside
149
+ the project's `node_modules/electron/dist`; the error message gives the exact path. Restart the app
150
+ after allowing it.
151
+
152
+ ## HTTP API
153
+
154
+ The MCP uses the viewer's API; you can call it too. `window` (target id or part of the title) goes in
155
+ the query string or the body and is optional with a single window. The server only listens on
156
+ 127.0.0.1, only accepts a local `Host` and origin, and `POST` requests require
157
+ `content-type: application/json`, so other websites can't drive your apps.
158
+
159
+ | Endpoint | |
160
+ | --- | --- |
161
+ | `GET /api/windows` | `[{ id, name, cdpPort, inspectPort, main, windows: [{ id, title, url }] }]` |
162
+ | `GET /api/project` | The project the viewer launches and whether it has Electron installed |
163
+ | `GET /api/screenshot?max=<px>&frame=1` | PNG; viewport size in `X-Viewport-Width` / `X-Viewport-Height` |
164
+ | `GET /api/ax-tree?interactiveOnly=true` | `{ tree }` |
165
+ | `GET /api/logs?level=&source=&limit=` | `{ logs }` or `{ stdout }` |
166
+ | `POST /api/launch` | `{ project? }` |
167
+ | `POST /api/attach` | `{ port, inspectPort? }` |
168
+ | `POST /api/click` | `{ x, y, button?, count?, modifiers? }` |
169
+ | `POST /api/drag` | `{ x1, y1, x2, y2, ms? }` |
170
+ | `POST /api/hover` | `{ x, y }` |
171
+ | `POST /api/scroll` | `{ x, y, dx, dy }` |
172
+ | `POST /api/text` | `{ text }` |
173
+ | `POST /api/key` | `{ key, modifiers? }` |
174
+ | `POST /api/resize` | `{ width, height }` (0 × 0 restores the window size) |
175
+ | `POST /api/reload` | `{ ignoreCache? }` |
176
+ | `POST /api/evaluate` | `{ expression }` |
177
+ | `POST /api/evaluate-main` | `{ expression, app? }` |
178
+ | `POST /api/devtools` | Toggles DevTools; without the main process returns the DevTools `url` |
179
+
180
+ ## How it works
181
+
182
+ - Everything goes through CDP with `ws`: no Playwright, no Puppeteer, nothing injected into the app.
183
+ The renderer is reached through `--remote-debugging-port` (one `page` target per window) and the
184
+ main process through the Node inspector (`--inspect`), where the console API provides `require`.
185
+ - One screencast session per window, shared by every viewer tab and stopped when the last one closes.
186
+ The last frame is kept for late joiners. Focus and page lifecycle are emulated while someone is
187
+ watching, so a covered or minimized window keeps painting.
188
+ - Viewer input is queued in order and mouse moves are coalesced to one per animation frame. A hidden
189
+ textarea holds the focus: keys are sent with `Input.dispatchKeyEvent`, and text that arrives without
190
+ key events (IME, dictation) with `Input.insertText`. On macOS, ⌘A, ⌘C, ⌘V, ⌘X and ⌘Z are sent as
191
+ editing commands, because the native menu that normally handles them never sees CDP events.
192
+ - Each process keeps one connection per window and per main process, which also collects console
193
+ messages and exceptions (the last 1000 per app).
194
+ - Launched and attached apps are remembered in `~/.cache/electron-viewer`, so the viewer and the MCP see
195
+ the same apps. Launched apps write their output to a log file there and keep running if the viewer
196
+ or MCP exits.
197
+
198
+ ## Limitations
199
+
200
+ - CDP only sees web content. Native UI (title bar, menus, dialogs, tray, notifications) is visible only
201
+ in frame mode and can't be clicked; use `evaluate_main` to drive it from the main process.
202
+ - Synchronous dialogs (`dialog.showMessageBoxSync`) block the main process: `evaluate_main` and frame
203
+ capture wait until the dialog is closed.
204
+ - Each `WebContentsView` is a separate CDP target, so it is listed as its own window. `<webview>` tags are
205
+ not listed.
206
+ - No audio.
207
+ - Frame mode runs at a few frames per second and, on macOS, needs the Screen Recording permission.
208
+ - Apps that build before starting (Forge, electron-vite) can't be launched from the viewer; start them
209
+ with the debugging flags and they are picked up.
210
+
211
+ ## Contributing
212
+
213
+ Branching model (`main` · `beta`), Conventional Commits and releases are described in
214
+ [CONTRIBUTING.md](./CONTRIBUTING.md); changes are listed in [CHANGELOG.md](./CHANGELOG.md). The
215
+ example app in [`example/`](./example) is there to try changes.
216
+
217
+ ## Author
218
+
219
+ Made by [AcertijosApps](https://acertijosapps.com/librerias). See the rest of our libraries at
220
+ [acertijosapps.com/librerias](https://acertijosapps.com/librerias).
221
+
222
+ Questions or proposals: [acertijos.contacto@gmail.com](mailto:acertijos.contacto@gmail.com) or open an
223
+ [issue](https://github.com/acertijosapps/electron-viewer/issues).
224
+
225
+ ## License
226
+
227
+ MIT
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+ // CLI del paquete: `electron-viewer` arranca el visor; `electron-viewer mcp`, el MCP por stdio.
3
+
4
+ import path from 'node:path';
5
+ import { readFileSync } from 'node:fs';
6
+
7
+ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
8
+
9
+ const HELP = `electron-viewer ${version}
10
+
11
+ Live viewer for Electron apps in the browser, plus an MCP server to drive them.
12
+
13
+ Usage:
14
+ electron-viewer [options] Start the viewer (http://localhost:8094)
15
+ electron-viewer mcp [options] Start the MCP server on stdio
16
+
17
+ Common options:
18
+ --project <dir> Electron project to launch with "electron ." (default:
19
+ current folder, env ELECTRON_VIEWER_PROJECT)
20
+
21
+ Viewer options:
22
+ -p, --port <port> Port to listen on (default: 8094, env PORT)
23
+ --host <host> Interface to bind (default: 127.0.0.1, env HOST)
24
+ --attach <port> Attach at startup to an app already running with
25
+ --remote-debugging-port=<port>
26
+ --inspect <port> With --attach: the app's main process inspector
27
+ (--inspect=<port>), for evaluate_main, frame capture,
28
+ DevTools and real window resizing
29
+
30
+ MCP options:
31
+ --viewer-url <url> Viewer to talk to (default: http://localhost:8094,
32
+ env ELECTRON_VIEWER_URL). Without a running viewer the
33
+ MCP drives the app over CDP directly.
34
+
35
+ -h, --help Show this help
36
+ -v, --version Show the version
37
+
38
+ Apps are found on CDP ports 9222-9231. Launched apps get the first free CDP port
39
+ from 9222 and inspector port from 9229.
40
+ `;
41
+
42
+ function fail(message) {
43
+ console.error(`electron-viewer: ${message}\nRun "electron-viewer --help" for usage.`);
44
+ process.exit(2);
45
+ }
46
+
47
+ const args = process.argv.slice(2);
48
+ const command = args[0] && !args[0].startsWith('-') ? args.shift() : 'viewer';
49
+ if (!['viewer', 'mcp'].includes(command)) fail(`unknown command "${command}"`);
50
+
51
+ const portValue = (flag, v) => {
52
+ if (!/^\d+$/.test(v) || Number(v) < 1 || Number(v) > 65535) fail(`invalid port "${v}" for ${flag}`);
53
+ return v;
54
+ };
55
+
56
+ for (let i = 0; i < args.length; i++) {
57
+ const arg = args[i];
58
+ const [flag, inline] = arg.includes('=') ? arg.split(/=(.*)/s) : [arg];
59
+ const value = () => {
60
+ const v = inline ?? args[++i];
61
+ if (v === undefined || v.startsWith('-')) fail(`${flag} needs a value`);
62
+ return v;
63
+ };
64
+ switch (flag) {
65
+ case '-h':
66
+ case '--help':
67
+ process.stdout.write(HELP);
68
+ process.exit(0);
69
+ break;
70
+ case '-v':
71
+ case '--version':
72
+ console.log(version);
73
+ process.exit(0);
74
+ break;
75
+ case '-p':
76
+ case '--port':
77
+ process.env.PORT = portValue(flag, value());
78
+ break;
79
+ case '--host':
80
+ process.env.HOST = value();
81
+ break;
82
+ case '--project':
83
+ process.env.ELECTRON_VIEWER_PROJECT = path.resolve(value());
84
+ break;
85
+ case '--attach':
86
+ process.env.ELECTRON_VIEWER_ATTACH = portValue(flag, value());
87
+ break;
88
+ case '--inspect':
89
+ process.env.ELECTRON_VIEWER_INSPECT = portValue(flag, value());
90
+ break;
91
+ case '--viewer-url':
92
+ process.env.ELECTRON_VIEWER_URL = value();
93
+ break;
94
+ default:
95
+ fail(`unknown option "${arg}"`);
96
+ }
97
+ }
98
+
99
+ if (process.env.ELECTRON_VIEWER_INSPECT && !process.env.ELECTRON_VIEWER_ATTACH) fail('--inspect needs --attach');
100
+
101
+ // Los módulos arrancan al importarse; las opciones ya quedaron en process.env.
102
+ await import(command === 'mcp' ? '../mcp/server.js' : '../server.js');
package/lib/cdp.js ADDED
@@ -0,0 +1,112 @@
1
+ // Cliente mínimo de Chrome DevTools Protocol sobre WebSocket. Sirve igual para un target del
2
+ // renderer (`--remote-debugging-port`) que para el inspector de Node del proceso main (`--inspect`).
3
+
4
+ import { EventEmitter } from 'node:events';
5
+ import WebSocket from 'ws';
6
+
7
+ const CONNECT_TIMEOUT_MS = 5000;
8
+ const COMMAND_TIMEOUT_MS = 30000;
9
+
10
+ export class CdpError extends Error {}
11
+
12
+ export class CdpClient extends EventEmitter {
13
+ static connect(wsUrl, { timeout = CONNECT_TIMEOUT_MS } = {}) {
14
+ return new Promise((resolve, reject) => {
15
+ // Sin Origin: Chromium rechaza orígenes que no estén en --remote-allow-origins.
16
+ const ws = new WebSocket(wsUrl, { perMessageDeflate: false, maxPayload: 256 * 1024 * 1024 });
17
+ const timer = setTimeout(() => {
18
+ ws.terminate();
19
+ reject(new CdpError(`Timed out connecting to ${wsUrl}`));
20
+ }, timeout);
21
+ ws.once('open', () => {
22
+ clearTimeout(timer);
23
+ resolve(new CdpClient(ws));
24
+ });
25
+ ws.once('error', (err) => {
26
+ clearTimeout(timer);
27
+ reject(new CdpError(`Could not connect to ${wsUrl}: ${err.message}`));
28
+ });
29
+ });
30
+ }
31
+
32
+ constructor(ws) {
33
+ super();
34
+ this.ws = ws;
35
+ this.nextId = 1;
36
+ this.pending = new Map();
37
+ this.closed = false;
38
+ ws.on('message', (data) => this.onMessage(data));
39
+ ws.on('close', () => this.onClose());
40
+ ws.on('error', () => {}); // el cierre llega después por 'close'
41
+ }
42
+
43
+ onMessage(data) {
44
+ let msg;
45
+ try {
46
+ msg = JSON.parse(data.toString());
47
+ } catch {
48
+ return;
49
+ }
50
+ if (msg.id) {
51
+ const p = this.pending.get(msg.id);
52
+ if (!p) return;
53
+ this.pending.delete(msg.id);
54
+ clearTimeout(p.timer);
55
+ if (msg.error) p.reject(new CdpError(`${p.method}: ${msg.error.message}`));
56
+ else p.resolve(msg.result);
57
+ } else if (msg.method) {
58
+ this.emit(msg.method, msg.params);
59
+ this.emit('event', msg.method, msg.params);
60
+ }
61
+ }
62
+
63
+ onClose() {
64
+ this.closed = true;
65
+ for (const p of this.pending.values()) {
66
+ clearTimeout(p.timer);
67
+ p.reject(new CdpError(`${p.method}: connection closed`));
68
+ }
69
+ this.pending.clear();
70
+ this.emit('close');
71
+ }
72
+
73
+ send(method, params = {}, { timeout = COMMAND_TIMEOUT_MS } = {}) {
74
+ if (this.closed) return Promise.reject(new CdpError(`${method}: connection closed`));
75
+ const id = this.nextId++;
76
+ return new Promise((resolve, reject) => {
77
+ const timer = setTimeout(() => {
78
+ this.pending.delete(id);
79
+ reject(new CdpError(`${method}: no answer within ${timeout / 1000} s`));
80
+ }, timeout);
81
+ this.pending.set(id, { resolve, reject, timer, method });
82
+ this.ws.send(JSON.stringify({ id, method, params }));
83
+ });
84
+ }
85
+
86
+ close() {
87
+ if (!this.closed) this.ws.close();
88
+ }
89
+ }
90
+
91
+ // GET a un endpoint HTTP del depurador (/json/list, /json/version).
92
+ export async function fetchJson(port, route, { timeout = 1500 } = {}) {
93
+ const res = await fetch(`http://127.0.0.1:${port}${route}`, { signal: AbortSignal.timeout(timeout) });
94
+ if (!res.ok) throw new CdpError(`HTTP ${res.status} from port ${port}${route}`);
95
+ return res.json();
96
+ }
97
+
98
+ // Evalúa una expresión y devuelve su valor, o lanza con el mensaje de la excepción.
99
+ export async function evaluate(client, expression, { awaitPromise = true, commandLineAPI = false, timeout } = {}) {
100
+ const { result, exceptionDetails } = await client.send(
101
+ 'Runtime.evaluate',
102
+ { expression, awaitPromise, returnByValue: true, includeCommandLineAPI: commandLineAPI, userGesture: true },
103
+ { timeout },
104
+ );
105
+ if (exceptionDetails) {
106
+ const ex = exceptionDetails.exception;
107
+ // Un `throw 'texto'` o un rechazo con string no trae description, solo value.
108
+ const message = ex?.description || (ex && 'value' in ex ? String(ex.value) : exceptionDetails.text) || 'Evaluation failed';
109
+ throw Object.assign(new CdpError(message.split('\n')[0].replace(/^Error: /, '')), { status: 400, stack: message });
110
+ }
111
+ return result.type === 'undefined' ? undefined : result.value ?? result.description ?? null;
112
+ }