Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
5f2abf7
perf: one snapshot per tap; cache idb describe per connection
cryptotavares Oct 29, 2026
c755260
refactor: drop dead try/catch in idb getWindowSize
cryptotavares Nov 6, 2026
4d07f40
chore: drop manual CHANGELOG entries
cryptotavares Nov 10, 2026
bb01e62
fix: keep the cached idb description while getDeviceInfo reads
cryptotavares Nov 10, 2026
693e87c
fix: waitForElement returns an element that appeared once it stops mo…
cryptotavares Nov 10, 2026
f7d09f7
fix: iOS key presses, back and text clearing
cryptotavares Oct 29, 2026
f317c8f
refactor: drop pass-through #exec and restore dropped recovery tests
cryptotavares Nov 6, 2026
0ebd7a6
fix!: scrollToElement succeeds only when the element is in the viewport
cryptotavares Oct 29, 2026
60b6d2f
fix: round the frame in the scroll error message
cryptotavares Oct 30, 2026
02bd986
fix: a zero-height frame is not in the viewport (Android clipped bounds)
cryptotavares Oct 30, 2026
c86dc73
test: complete the SnapshotResult fixture in the scroll tests
cryptotavares Oct 30, 2026
03d9f10
refactor: simplify scrollUntilInViewport and inline the Android scrol…
cryptotavares Nov 6, 2026
c1e8d24
fix: hit-test iOS taps; refuse off-screen Android taps
cryptotavares Oct 30, 2026
90def7b
fix: give the viewport tap error code ELEMENT_NOT_IN_VIEWPORT
cryptotavares Oct 30, 2026
268595e
refactor: simplify iOS tap hit-test plumbing
cryptotavares Nov 6, 2026
dbd6963
feat: add HermesClient, a persistent Hermes CDP connection
cryptotavares Nov 9, 2026
347f626
fix: keep HermesClient dispatching when an event listener throws
cryptotavares Nov 9, 2026
6af5e65
feat: emit contextCreated when the app reloads on the same Hermes socket
cryptotavares Nov 9, 2026
42759be
fix: keep HermesClient reconnecting and open one socket per reconnect
cryptotavares Nov 9, 2026
81961c0
test: assert HERMES_TIMEOUT for a Hermes CDP user-method timeout
cryptotavares Nov 9, 2026
eabd06b
Merge remote-tracking branch 'origin/main' into cryptotavares/mmcli-p…
cryptotavares Nov 16, 2026
329620e
Merge branch 'main' into cryptotavares/mmcli-p2-02-persistent-hermes
cryptotavares Nov 18, 2026
1185c49
Merge branch 'main' into cryptotavares/mmcli-p2-02-persistent-hermes
cryptotavares Nov 19, 2026
5069bf6
fix: emit reconnectFailed and let a caller restart a stopped HermesCl…
cryptotavares Nov 19, 2026
f69a403
fix: bound a HermesClient send's wait for a shared connect by its tim…
cryptotavares Nov 19, 2026
878ac83
fix: export HermesListenerErrorEvent
cryptotavares Nov 19, 2026
36a2e3d
refactor: drop a HermesClient connect guard made redundant by the bou…
cryptotavares Nov 19, 2026
0ca114e
fix: make HermesClient trackContexts opt-in so sessions do not enable…
cryptotavares Nov 19, 2026
71bc1aa
fix: abandon a HermesClient in-flight connect on close so a reopen st…
cryptotavares Nov 19, 2026
c94168d
fix: retry a HermesClient pin mismatch on reconnect; only a missing W…
cryptotavares Nov 19, 2026
8ee1349
fix: do not emit HermesClient disconnected for a socket lost before i…
cryptotavares Nov 19, 2026
f27edf7
fix: treat an empty HermesClient pinnedDeviceId as no pin, as the one…
cryptotavares Nov 19, 2026
de910d0
refactor: remove unreachable guards from HermesClient #attemptReconnect
cryptotavares Nov 19, 2026
368506c
docs: list HermesClient timeout steps, socket lifetime and per-socket…
cryptotavares Nov 19, 2026
07c3d9a
refactor: remove the unreachable same-device branch from HermesClient…
cryptotavares Nov 19, 2026
0aa6e76
test: cover HermesClient close, send and pin-mismatch edge cases on f…
cryptotavares Nov 19, 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
5 changes: 3 additions & 2 deletions src/hermes/hermes-cdp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -729,7 +729,7 @@ describe('runHermesCdp', () => {
expect(result.message).toContain('timed out');
});

it('user-method timeout → HERMES_CONNECTION_FAILED via finally close', async () => {
it('user-method timeout → HERMES_TIMEOUT and closes the socket', async () => {
vi.useFakeTimers();
MockWebSocket.responseFactory = (request) =>
request.id === 1 ? defaultResponseFactory(request) : undefined;
Expand All @@ -740,7 +740,8 @@ describe('runHermesCdp', () => {
await vi.advanceTimersByTimeAsync(1_000);
const result = await resultPromise;

expect(result.ok).toBe(false);
expectError(result, HERMES_TIMEOUT);
expect(result.message).toContain('timed out');
expect(socketAt(0).readyState).toBe(MockWebSocket.closed);
});

Expand Down
193 changes: 107 additions & 86 deletions src/hermes/hermes-cdp.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
// `hermes-client.ts` imports this module's discovery and socket helpers, so the
// two modules import each other. The cycle is safe: `hermes-client.ts` reads
// those bindings only while connecting, never during module evaluation.
import { HermesClient } from './hermes-client.js';

/**
* Pure Hermes Chrome DevTools Protocol (CDP) core for `@metamask/device-mcp`.
*
Expand Down Expand Up @@ -105,20 +110,33 @@ type CdpSuccessResponse = {
result?: unknown;
};

/**
* A CDP-level error payload.
*/
export type HermesCdpErrorInfo = {
/** The CDP error message. */
message?: string;
/** The CDP error code. */
code?: number;
/** Optional structured error details. */
data?: unknown;
};

type CdpErrorResponse = {
id: number;
error: {
message?: string;
code?: number;
data?: unknown;
};
error: HermesCdpErrorInfo;
};

type TargetSelection =
| { ok: true; target: HermesTarget }
| { ok: false; code: string; message: string };

type ProbeResult = { ok: true } | { ok: false; code: string; message: string };
/**
* Result of the Hermes identity probe.
*/
export type HermesIdentityProbeResult =
| { ok: true }
| { ok: false; code: string; message: string };

/**
* No Hermes debug target matched the expected appId (after synthetic-title and
Expand Down Expand Up @@ -174,6 +192,12 @@ export const HERMES_CDP_FAILED = 'HERMES_CDP_FAILED';
*/
export const HERMES_WEBSOCKET_UNAVAILABLE = 'HERMES_WEBSOCKET_UNAVAILABLE';

/**
* A pending CDP call was aborted through its `AbortSignal`. The pending entry is
* removed, so a late response is ignored.
*/
export const HERMES_ABORTED = 'HERMES_ABORTED';

/**
* CDP methods blocked for safety. Ported VERBATIM from the reference — do not
* weaken.
Expand Down Expand Up @@ -216,6 +240,46 @@ export const IDENTITY_PROBE_EXPR = `(function () {
}
})();`;

/**
* Returns the fail-closed result for a CDP method in the blocked set.
*
* @param method - The requested CDP method.
* @returns The `HERMES_BLOCKED_METHOD` failure, or undefined when not blocked.
*/
export function createBlockedMethodResult(
method: string,
): HermesCdpResult | undefined {
if (!HERMES_BLOCKED_METHODS.has(method)) {
return undefined;
}
return {
ok: false,
code: HERMES_BLOCKED_METHOD,
message:
`CDP method "${method}" is blocked for safety. ` +
`Blocked methods: ${[...HERMES_BLOCKED_METHODS].join(', ')}`,
};
}

/**
* Returns the failure result for a runtime without a global `WebSocket`.
*
* @returns The `HERMES_WEBSOCKET_UNAVAILABLE` failure.
*/
export function websocketUnavailableResult(): {
ok: false;
code: string;
message: string;
} {
return {
ok: false,
code: HERMES_WEBSOCKET_UNAVAILABLE,
message:
'Global WebSocket is unavailable. On Node 20 launch device-mcp with ' +
'NODE_OPTIONS="--experimental-websocket" (or use Node 22+).',
};
}

/**
* Orchestrates a single verified Hermes CDP command end to end.
*
Expand All @@ -225,72 +289,34 @@ export const IDENTITY_PROBE_EXPR = `(function () {
* supplies the resolved port/appId/pin and persists the pin — this function is
* pure with respect to session state.
*
* Implemented on {@link HermesClient}: one client, one connect, one send, then
* close. Auto-reconnect is disabled because a one-shot call owns the socket.
*
* @param input - Method, params, timeout, resolved port/appId/pin, and the pin
* persistence callback. See {@link RunHermesCdpInput}.
* @returns A discriminated {@link HermesCdpResult}.
*/
export async function runHermesCdp(
input: RunHermesCdpInput,
): Promise<HermesCdpResult> {
if (HERMES_BLOCKED_METHODS.has(input.method)) {
return {
ok: false,
code: HERMES_BLOCKED_METHOD,
message:
`CDP method "${input.method}" is blocked for safety. ` +
`Blocked methods: ${[...HERMES_BLOCKED_METHODS].join(', ')}`,
};
}

if (typeof WebSocket !== 'function') {
return {
ok: false,
code: HERMES_WEBSOCKET_UNAVAILABLE,
message:
'Global WebSocket is unavailable. On Node 20 launch device-mcp with ' +
'NODE_OPTIONS="--experimental-websocket" (or use Node 22+).',
};
}
const client = new HermesClient({
metroPort: input.metroPort,
appId: input.appId,
origin: input.origin,
pinnedDeviceId: input.pinnedDeviceId,
onPin: input.onPin,
reconnect: { maxAttempts: 0 },
// The one-shot path must not pay for (or expose) context tracking, and its
// wire traffic stays probe + one method.
trackContexts: false,
});

try {
const targets = await fetchDiscoveryTargets(
input.metroPort,
input.timeoutMs,
);
const selection = selectHermesTarget(
targets,
input.appId,
input.pinnedDeviceId,
);
if (!selection.ok) {
return { ok: false, code: selection.code, message: selection.message };
}

const validation = validateWebSocketUrl(
selection.target.webSocketDebuggerUrl,
input.metroPort,
);
if (!validation.ok) {
return {
ok: false,
code: HERMES_INVALID_WS_URL,
message: validation.message,
};
}

return await executeVerifiedCdpCommand(
selection.target,
input,
input.pinnedDeviceId,
input.onPin,
);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return {
ok: false,
code: HERMES_CONNECTION_FAILED,
message: `Hermes CDP connection failed: ${message}`,
};
return await client.send(input.method, input.params, {
timeoutMs: input.timeoutMs,
});
} finally {
client.close();
}
}

Expand Down Expand Up @@ -501,8 +527,9 @@ export function validateWebSocketUrl(
* @param webSocketUrl - The target's WebSocket URL.
* @param override - An explicit HTTP(S) origin, if configured.
* @returns The HTTP(S) origin to send in the handshake.
* @throws When the explicit override is not a bare HTTP(S) origin.
*/
function resolveWebSocketOrigin(
export function resolveWebSocketOrigin(
webSocketUrl: string,
override: string | undefined,
): string {
Expand Down Expand Up @@ -562,13 +589,7 @@ export async function executeVerifiedCdpCommand(
};
}
if (typeof WebSocket !== 'function') {
return {
ok: false,
code: HERMES_WEBSOCKET_UNAVAILABLE,
message:
'Global WebSocket is unavailable. On Node 20 launch device-mcp with ' +
'NODE_OPTIONS="--experimental-websocket" (or use Node 22+).',
};
return websocketUnavailableResult();
}

// Node's WebSocket supports this headers overload on Node 20 (with the
Expand Down Expand Up @@ -616,7 +637,7 @@ export async function executeVerifiedCdpCommand(
ok: false,
code: HERMES_CDP_FAILED,
message: `Hermes CDP "${input.method}" failed: ${formatCdpError(
response,
response.error,
)}`,
};
}
Expand All @@ -635,13 +656,13 @@ export async function executeVerifiedCdpCommand(
* @param socket - The open target WebSocket.
* @param timeoutMs - Round-trip timeout in milliseconds.
* @param id - The CDP message id to use for this probe.
* @returns A {@link ProbeResult}.
* @returns A {@link HermesIdentityProbeResult}.
*/
async function runIdentityProbe(
export async function runIdentityProbe(
socket: WebSocket,
timeoutMs: number,
id: number,
): Promise<ProbeResult> {
): Promise<HermesIdentityProbeResult> {
socket.send(
JSON.stringify({
id,
Expand Down Expand Up @@ -673,7 +694,7 @@ async function runIdentityProbe(
return {
ok: false,
code: HERMES_NOT_VERIFIED,
message: `Identity probe failed: ${formatCdpError(response)}`,
message: `Identity probe failed: ${formatCdpError(response.error)}`,
};
}

Expand Down Expand Up @@ -786,7 +807,7 @@ async function sendUserMethod(
* @param timeoutMs - Connection timeout in milliseconds.
* @returns A promise that resolves when the socket is open.
*/
async function waitForSocketOpen(
export async function waitForSocketOpen(
socket: WebSocket,
timeoutMs: number,
): Promise<void> {
Expand Down Expand Up @@ -925,18 +946,18 @@ function isCdpErrorResponse(
}

/**
* Formats a CDP error response into a single human-readable line.
* Formats a CDP error payload into a single human-readable line.
*
* @param response - The CDP error response.
* @param error - The CDP error payload.
* @returns A combined message including code and data when present.
*/
function formatCdpError(response: CdpErrorResponse): string {
const parts = [response.error.message ?? 'Unknown CDP error'];
if (typeof response.error.code === 'number') {
parts.push(`code ${response.error.code}`);
export function formatCdpError(error: HermesCdpErrorInfo): string {
const parts = [error.message ?? 'Unknown CDP error'];
if (typeof error.code === 'number') {
parts.push(`code ${error.code}`);
}
if (response.error.data !== undefined) {
parts.push(JSON.stringify(response.error.data));
if (error.data !== undefined) {
parts.push(JSON.stringify(error.data));
}
return parts.join(' - ');
}
Expand All @@ -946,7 +967,7 @@ function formatCdpError(response: CdpErrorResponse): string {
*
* @param socket - The target WebSocket.
*/
function closeSocket(socket: WebSocket): void {
export function closeSocket(socket: WebSocket): void {
if (
socket.readyState === WebSocket.CONNECTING ||
socket.readyState === WebSocket.OPEN
Expand Down
Loading
Loading