Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 2 additions & 0 deletions desktop-app/e2e/tests/mcp-bridge-stdio.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ const EXPECTED_TOOLS = [
'read_page',
'screenshot',
'set_active_devices',
'set_javascript_enabled',
'set_network_scripts_blocked',
'type_text',
];

Expand Down
2 changes: 2 additions & 0 deletions desktop-app/e2e/tests/mcp-server.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ test.describe('MCP server', () => {
'read_page',
'screenshot',
'set_active_devices',
'set_javascript_enabled',
'set_network_scripts_blocked',
'type_text',
]);
});
Expand Down
2 changes: 2 additions & 0 deletions desktop-app/src/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ export const IPC_MAIN_CHANNELS = {
ENABLE_INSPECTOR_OVERLAY: 'enable-inspector-overlay',
DISABLE_INSPECTOR_OVERLAY: 'disable-inspector-overlay',
INSPECT_ELEMENT: 'inspect-element',
SET_JAVASCRIPT_ENABLED: 'set-javascript-enabled',
SET_NETWORK_SCRIPTS_BLOCKED: 'set-network-scripts-blocked',
DELETE_STORAGE: 'delete-storage',
LOAD_URL_IN_WEBVIEW: 'load-url-in-webview',
SET_NATIVE_THEME: 'set-native-theme',
Expand Down
28 changes: 27 additions & 1 deletion desktop-app/src/common/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@ export interface McpBeacon {
}

export type McpBridgeCommand =
'get-app-state' | 'navigate' | 'list-devices' | 'set-active-devices' | 'get-capture-targets';
| 'get-app-state'
| 'navigate'
| 'list-devices'
| 'set-active-devices'
| 'get-capture-targets'
| 'set-javascript-enabled'
| 'set-network-scripts-blocked';

export interface McpBridgeRequest {
requestId: string;
Expand Down Expand Up @@ -99,3 +105,23 @@ export interface McpCaptureTargetsResult {
targets: McpCaptureTarget[];
skipped: McpSkippedCapture[];
}

export interface McpSetJavascriptEnabledPayload {
device: string;
enabled: boolean;
}

export interface McpSetJavascriptEnabledResult {
deviceName: string;
enabled: boolean;
}

export interface McpSetNetworkScriptsBlockedPayload {
device: string;
blocked: boolean;
}

export interface McpSetNetworkScriptsBlockedResult {
deviceName: string;
blocked: boolean;
}
6 changes: 5 additions & 1 deletion desktop-app/src/main/devtools/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,11 @@ const disableInspector = async (
highlightConfig: {},
});

dbg.removeAllListeners().detach();
// Quiet the inspector's own listener only — the debugger session may
// still be owned by another feature (e.g. the JS-disable toggle) on the
// same guest, so it's left attached and torn down centrally when the
// guest is destroyed (see webview-registry.ts), not here.
dbg.removeAllListeners('message');
} catch (err) {
log.warn('Error detaching debugger', err);
}
Expand Down
82 changes: 82 additions & 0 deletions desktop-app/src/main/javascript-toggle/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/* eslint-disable @typescript-eslint/no-explicit-any -- CDP payloads are untyped by Electron */
import {ipcMain, webContents} from 'electron';
import {IPC_MAIN_CHANNELS} from '../../common/constants';
import log from '../logging';
import {isRegisteredWebview} from '../webview-registry';

export interface SetJavascriptEnabledArgs {
webviewId: number;
enabled: boolean;
}

export interface SetJavascriptEnabledResult {
status: boolean;
}

// Emulation.setScriptExecutionDisabled is a per-navigation CDP override, not
// page/document state — Chromium resets it on the next navigation. Track the
// last-requested state per guest so it can be resent before every subsequent
// navigation (reload, link click, address change), not just applied once.
const disabledByWebviewId = new Map<number, boolean>();

const applyScriptExecutionDisabled = async (dbg: Electron.Debugger, disabled: boolean) => {
if (!dbg.isAttached()) {
dbg.attach();
}
await dbg.sendCommand('Page.enable');
await dbg.sendCommand('Emulation.setScriptExecutionDisabled', {value: disabled});
};

// <webview> exposes no post-mount "javascript enabled" attribute, so this
// goes through CDP instead. Emulation.setScriptExecutionDisabled only stops
// *future* script execution, so a reload is required for the toggle to be
// visibly consistent with the page already on screen.
const setJavascriptEnabled = async (
_: any,
args: SetJavascriptEnabledArgs
): Promise<SetJavascriptEnabledResult> => {
const {webviewId, enabled} = args;
if (!isRegisteredWebview(webviewId)) {
return {status: false};
}
const webViewContents = webContents.fromId(webviewId);
if (webViewContents === undefined) {
return {status: false};
}

const isFirstToggle = !disabledByWebviewId.has(webviewId);
disabledByWebviewId.set(webviewId, !enabled);

try {
await applyScriptExecutionDisabled(webViewContents.debugger, !enabled);
} catch (err) {
log.warn('Error toggling JavaScript execution', err);
disabledByWebviewId.delete(webviewId);
return {status: false};
}

if (isFirstToggle) {
// The debugger itself is detached centrally on guest teardown (see
// webview-registry.ts) — here we only need to forget our own bookkeeping.
webViewContents.on('did-start-navigation', () => {
const stillDisabled = disabledByWebviewId.get(webviewId);
if (stillDisabled === undefined) {
return;
}
applyScriptExecutionDisabled(webViewContents.debugger, stillDisabled).catch((err) => {
log.warn('Error reapplying JavaScript execution state on navigation', err);
});
});
webViewContents.once('destroyed', () => {
disabledByWebviewId.delete(webviewId);
});
}

webViewContents.reload();
return {status: true};
};

export const initJavascriptToggleHandlers = () => {
ipcMain.removeHandler(IPC_MAIN_CHANNELS.SET_JAVASCRIPT_ENABLED);
ipcMain.handle(IPC_MAIN_CHANNELS.SET_JAVASCRIPT_ENABLED, setJavascriptEnabled);
};
4 changes: 4 additions & 0 deletions desktop-app/src/main/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import store from '../store';
import {initWebviewContextMenu} from './webview-context-menu/register';
import {initScreenshotHandlers} from './screenshot';
import {initDevtoolsHandlers} from './devtools';
import {initJavascriptToggleHandlers} from './javascript-toggle';
import {initNetworkScriptBlockerHandlers} from './network-script-blocker';
import {initWebviewStorageManagerHandlers} from './webview-storage-manager';
import {initNativeFunctionHandlers} from './native-functions';
import {WebPermissionHandlers} from './web-permissions';
Expand Down Expand Up @@ -278,6 +280,8 @@ const createWindow = async () => {
}
trackWindowState(mainWindow);
initDevtoolsHandlers(mainWindow);
initJavascriptToggleHandlers();
initNetworkScriptBlockerHandlers();
wireWebviewSecurity(mainWindow.webContents, {
openInPreview: (url) => openUrl(url, getMainWindow()),
openExternal: (url) => shell.openExternal(url),
Expand Down
24 changes: 24 additions & 0 deletions desktop-app/src/main/mcp/toolDefs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,30 @@ export const toolDefs = {
.describe('Optional device id or exact name; omit to type in the primary device'),
},
},
set_javascript_enabled: {
description:
'Enable or disable JavaScript execution for one Responsively App device preview. ' +
'Reloads that preview so the change takes effect; the state persists across further ' +
'reloads and navigation until changed again or the device is removed from the preview.',
inputSchema: {
device: z.string().min(1).describe('Device id or exact name (use list_devices)'),
enabled: z.boolean().describe('true to enable JavaScript, false to disable it'),
},
},
set_network_scripts_blocked: {
description:
'Block or unblock JavaScript network requests for one Responsively App device preview, ' +
'without disabling the JavaScript engine itself. Distinct from set_javascript_enabled: ' +
'the page can still execute inline or already-loaded scripts, but any request Chromium ' +
'classifies as a script (any <script src>, any source) is cancelled at the network layer ' +
'— closer to an ad-blocker, corporate firewall, or a dead CDN than a no-JS browser. ' +
'Reloads that preview so the change takes effect; the state persists across further ' +
'reloads and navigation until changed again or the device is removed from the preview.',
inputSchema: {
device: z.string().min(1).describe('Device id or exact name (use list_devices)'),
blocked: z.boolean().describe('true to block script network requests, false to allow them'),
},
},
screenshot: {
description:
'Capture screenshots of Responsively App device previews rendering the current page. ' +
Expand Down
36 changes: 36 additions & 0 deletions desktop-app/src/main/mcp/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {
McpDeviceInfo,
McpNavigateResult,
McpSetActiveDevicesResult,
McpSetJavascriptEnabledResult,
McpSetNetworkScriptsBlockedResult,
McpSkippedCapture,
} from '../../common/mcp';
import {captureImage} from '../screenshot';
Expand Down Expand Up @@ -160,6 +162,40 @@ export const registerTools = (server: McpServer, getMainWindow: GetMainWindow) =
}
);

server.registerTool(
'set_javascript_enabled',
toolDefs.set_javascript_enabled,
async ({device, enabled}) => {
try {
const result = await sendBridgeCommand<McpSetJavascriptEnabledResult>(
getMainWindow,
'set-javascript-enabled',
{device, enabled}
);
return textResult(result);
} catch (error) {
return errorResult(error);
}
}
);

server.registerTool(
'set_network_scripts_blocked',
toolDefs.set_network_scripts_blocked,
async ({device, blocked}) => {
try {
const result = await sendBridgeCommand<McpSetNetworkScriptsBlockedResult>(
getMainWindow,
'set-network-scripts-blocked',
{device, blocked}
);
return textResult(result);
} catch (error) {
return errorResult(error);
}
}
);

server.registerTool('screenshot', toolDefs.screenshot, async ({device}) => {
try {
const {targets, skipped} = await sendBridgeCommand<McpCaptureTargetsResult>(
Expand Down
119 changes: 119 additions & 0 deletions desktop-app/src/main/network-script-blocker/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import {ipcMain, session, webContents} from 'electron';
import {IPC_MAIN_CHANNELS} from '../../common/constants';
import {getBrowserSyncHost} from '../browser-sync';
import {isRegisteredWebview} from '../webview-registry';

export interface SetNetworkScriptsBlockedArgs {
webviewId: number;
blocked: boolean;
}

export interface SetNetworkScriptsBlockedResult {
status: boolean;
}

// Distinct from the CDP-based JS-disable toggle: the script *engine* stays
// on here, only requests Chromium classifies as resourceType 'script' are
// cancelled at the network layer — closer to an ad-blocker, corporate
// firewall, or a dead CDN than to a browser with JavaScript turned off.
// Unlike the CDP override, blocking here isn't tied to a single document —
// once a webContents id is in the set it stays blocked across every future
// navigation, so no per-navigation reapply listener is needed.
const blockedWebviewIds = new Set<number>();
const watchedForDestroy = new Set<number>();

const registerRequestFilter = () => {
session.defaultSession.webRequest.onBeforeRequest((details, callback) => {
// The BrowserSync client script is the app's own event-mirroring
// transport, injected into every preview regardless of this toggle —
// it's indistinguishable from a page's own script by resourceType alone,
// but blocking it would silently drop a device out of scroll/click
// mirroring instead of just blocking the site's scripts as intended.
if (
details.resourceType === 'script' &&
blockedWebviewIds.has(details.webContentsId ?? -1) &&
!details.url.includes(getBrowserSyncHost())
) {
callback({cancel: true});
return;
}
callback({});
});
};

const RELOAD_SETTLE_TIMEOUT_MS = 15_000;

// reloadIgnoringCache() is fire-and-forget — it returns before the reload
// actually starts or commits. Resolving this handler right after calling it
// (as it used to) let a caller's very next action (e.g. an MCP navigate()
// call) race the in-flight reload on the same webContents: two competing
// navigations, and whichever happens to commit last — not necessarily the
// one requested last — wins. Waiting for the reload to genuinely settle
// before resolving closes that window, so callers can rely on this device
// being idle again by the time the promise resolves.
const waitForReloadToSettle = (contents: Electron.WebContents): Promise<void> =>
new Promise((resolve) => {
let settled = false;
const finish = () => {
if (settled) return;
settled = true;
clearTimeout(timer);
contents.removeListener('did-stop-loading', onStopLoading);
contents.removeListener('did-fail-load', onFailLoad);
contents.removeListener('destroyed', finish);
resolve();
};
const onStopLoading = () => finish();
const onFailLoad = (_event: Electron.Event, errorCode: number) => {
// -3 (ERR_ABORTED) fires for in-page interruptions (e.g. a follow-up
// navigation superseding this reload) — something else committed, so
// that's a settle too, not a failure worth surfacing here.
if (errorCode !== -3) finish();
};
contents.once('did-stop-loading', onStopLoading);
contents.once('did-fail-load', onFailLoad);
contents.once('destroyed', finish);
const timer = setTimeout(finish, RELOAD_SETTLE_TIMEOUT_MS);
contents.reloadIgnoringCache();
});

const setNetworkScriptsBlocked = async (
_: unknown,
args: SetNetworkScriptsBlockedArgs
): Promise<SetNetworkScriptsBlockedResult> => {
const {webviewId, blocked} = args;
if (!isRegisteredWebview(webviewId)) {
return {status: false};
}
const webViewContents = webContents.fromId(webviewId);
if (webViewContents === undefined) {
return {status: false};
}

if (blocked) {
blockedWebviewIds.add(webviewId);
} else {
blockedWebviewIds.delete(webviewId);
}

if (!watchedForDestroy.has(webviewId)) {
watchedForDestroy.add(webviewId);
webViewContents.once('destroyed', () => {
blockedWebviewIds.delete(webviewId);
watchedForDestroy.delete(webviewId);
});
}

// A plain reload() can be satisfied entirely from the HTTP cache, in which
// case Chromium never issues a fresh network request for the script and
// this filter never gets a chance to see it — bypassing the cache is what
// makes toggling this reliably observable, on a first visit or a hundredth.
await waitForReloadToSettle(webViewContents);
return {status: true};
};

export const initNetworkScriptBlockerHandlers = () => {
registerRequestFilter();
ipcMain.removeHandler(IPC_MAIN_CHANNELS.SET_NETWORK_SCRIPTS_BLOCKED);
ipcMain.handle(IPC_MAIN_CHANNELS.SET_NETWORK_SCRIPTS_BLOCKED, setNetworkScriptsBlocked);
};
Loading
Loading