@lynx-js/devtool-connector 0.18.8 → 0.19.1

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.
@@ -2,4 +2,4 @@ import type { Connector } from "../index.js";
2
2
  import type { CommandData, CommandParams } from "./contract.js";
3
3
  import { type CommandResult } from "./result.js";
4
4
  /** The sole production implementation of the open command. */
5
- export declare function openAction(connector: Pick<Connector, "openPage" | "waitForHeadlessReady">, params: CommandParams<"open">, signal?: AbortSignal): Promise<CommandResult<CommandData<"open">>>;
5
+ export declare function openAction(connector: Pick<Connector, "openPage">, params: CommandParams<"open">, signal?: AbortSignal): Promise<CommandResult<CommandData<"open">>>;
@@ -33,7 +33,7 @@ export interface RendererState {
33
33
  export declare function createRendererState(): RendererState;
34
34
  /** Apply one upstream `operation_v2` payload to a renderer tree. */
35
35
  export declare function applyOperationV2(state: RendererState, ops: number[]): void;
36
- /** Replace the renderer's roots vector. */
36
+ /** Replace the renderer's roots vector while preserving live roots omitted from `rootOrder`. */
37
37
  export declare function applyRootOrder(state: RendererState, rootOrder: ID[]): void;
38
38
  /** Short type tag used by the CLI's compact renderer. */
39
39
  export declare function typeTag(type: DevNodeType): string;
@@ -1,3 +1 @@
1
- import type { CommandAction, CommandObject } from "./contract.js";
2
1
  export declare const DEFAULT_COMMAND_TIMEOUT_MS = 30000;
3
- export declare function getDefaultCommandTimeoutMs(action: CommandAction, params: CommandObject): number;
@@ -8,7 +8,7 @@ import "../2.js";
8
8
  import { DevtoolDaemon } from "../t.js";
9
9
  const DEBUG_ROUTER_DIR = node_path.join(node_os.homedir(), ".DebugRouterConnector");
10
10
  const PIDFILE = node_path.join(DEBUG_ROUTER_DIR, "daemon.pid");
11
- const { values: values } = parseArgs({
11
+ const { values } = parseArgs({
12
12
  options: {
13
13
  port: {
14
14
  type: "string",
@@ -65,6 +65,7 @@ export interface ControlResponse {
65
65
  id: number;
66
66
  result?: unknown;
67
67
  error?: string;
68
+ transports?: string[];
68
69
  };
69
70
  }
70
71
  export type DaemonIncomingMessage = RegisterEvent | ListClientsRequest | PingEvent | ControlRequest | CustomizedMessage;
@@ -1,5 +1,5 @@
1
1
  import { ActionCore } from "../command/core.js";
2
- import type { Transport } from "../transport/transport.js";
2
+ import { type Transport } from "../transport/transport.js";
3
3
  import { type DaemonIdentity } from "./protocol.js";
4
4
  import { StaticServer } from "./static-server.js";
5
5
  /**
package/dist/f.js CHANGED
@@ -2073,17 +2073,32 @@ function result_fail(action, message, options = {}) {
2073
2073
  error
2074
2074
  };
2075
2075
  }
2076
- const NO_CLIENTS_FOUND_MESSAGE = "No Lynx DevTool clients were found.\n\nTry these steps:\n1. Make sure the target device/simulator and app are running.\n2. If the app just launched, wait a moment and rerun `list-clients`.\n3. If this is unexpected, rerun with `DEBUG='devtool-mcp-server:connector*'` or try `--no-daemon`.\n\nRun `agent-lynx skills get lynx-devtool`, then read `references/troubleshooting/symptoms.md#list-clients-returns-` relative to the reported Skill directory.";
2076
+ const noClientsSummary = "No Lynx DevTool clients were found.";
2077
+ const noClientsHelp = "Try these steps:\n1. Make sure the target device/simulator and app are running.\n2. If the app just launched, wait a moment and rerun `list-clients`.\n3. If this is unexpected, rerun with `DEBUG='devtool-mcp-server:connector*'` or try `--no-daemon` (HDT/Aiden discovery still takes precedence).\n\nRun `agent-lynx skills get lynx-devtool`, then read `references/troubleshooting/symptoms.md#list-clients-returns-` relative to the reported Skill directory.";
2078
+ const NO_CLIENTS_FOUND_MESSAGE = [
2079
+ noClientsSummary,
2080
+ noClientsHelp
2081
+ ].join("\n\n");
2077
2082
  async function listClientsAction(connector) {
2078
2083
  const clients = await connector.listClients();
2079
- if (0 === clients.length) return result_fail("list-clients", NO_CLIENTS_FOUND_MESSAGE, {
2080
- reason: "no-clients",
2081
- recoverable: true,
2082
- nextActions: [
2083
- "Make sure the target device/simulator and app are running, then retry.",
2084
- "Retry with `--no-daemon` to use direct device discovery."
2085
- ]
2086
- });
2084
+ if (0 === clients.length) {
2085
+ const transports = clients.transports ?? [];
2086
+ const message = [
2087
+ noClientsSummary,
2088
+ ...transports.length > 0 ? [
2089
+ `Discovery path: ${transports.join(", ")}`
2090
+ ] : [],
2091
+ noClientsHelp
2092
+ ].join("\n\n");
2093
+ return result_fail("list-clients", message, {
2094
+ reason: "no-clients",
2095
+ recoverable: true,
2096
+ nextActions: [
2097
+ "Make sure the target device/simulator and app are running, then retry.",
2098
+ "Retry with `--no-daemon` to run discovery in-process; HDT/Aiden still takes precedence over direct discovery."
2099
+ ]
2100
+ });
2101
+ }
2087
2102
  return ok("list-clients", {
2088
2103
  clients
2089
2104
  });
@@ -2099,9 +2114,6 @@ async function listSessionsAction(connector, params) {
2099
2114
  sessions
2100
2115
  });
2101
2116
  }
2102
- function isHeadlessClientId(clientId) {
2103
- return clientId.startsWith("headless:");
2104
- }
2105
2117
  async function openAction(connector, params, signal) {
2106
2118
  const clientId = params.clientId;
2107
2119
  if (!clientId) return result_fail("open", "clientId is required after target resolution.", {
@@ -2111,10 +2123,6 @@ async function openAction(connector, params, signal) {
2111
2123
  reason: "bad-params"
2112
2124
  });
2113
2125
  signal?.throwIfAborted();
2114
- if (isHeadlessClientId(clientId)) await connector.waitForHeadlessReady(clientId, signal ? {
2115
- signal
2116
- } : {});
2117
- signal?.throwIfAborted();
2118
2126
  const response = await connector.openPage(clientId, params.url, signal);
2119
2127
  return ok("open", {
2120
2128
  clientId,
@@ -2280,9 +2288,12 @@ function applyOperationV2(state, ops) {
2280
2288
  }
2281
2289
  }
2282
2290
  function applyRootOrder(state, rootOrder) {
2283
- state.roots = [
2284
- ...rootOrder
2285
- ];
2291
+ const ordered = rootOrder.filter((id)=>state.tree.has(id));
2292
+ for (const id of state.roots)if (state.tree.has(id) && !ordered.includes(id)) ordered.push(id);
2293
+ if (0 === ordered.length) {
2294
+ for (const [id, node] of state.tree)if (-1 === node.parent) ordered.push(id);
2295
+ }
2296
+ state.roots = ordered;
2286
2297
  }
2287
2298
  function typeTag(type) {
2288
2299
  switch(type){
@@ -2698,11 +2709,20 @@ async function runReactLynxSession(options) {
2698
2709
  let rootOrderFrames = 0;
2699
2710
  const envelopeTypes = new Set();
2700
2711
  let snapshotPending = void 0 !== afterSnapshot;
2712
+ const wantsTree = outbound.some((frame)=>{
2713
+ try {
2714
+ const parsed = JSON.parse(frame.params.data);
2715
+ return "refresh" === parsed.type;
2716
+ } catch {
2717
+ return false;
2718
+ }
2719
+ });
2701
2720
  try {
2702
2721
  for await (const value of readUntilIdle(stream, {
2703
2722
  idleMs: ()=>snapshotPending ? snapshotIdleMs : idleMs,
2704
2723
  maxMs,
2705
2724
  onIdle: ()=>{
2725
+ if (wantsTree && 0 === state.tree.size && (operationFrames > 0 || envelopeTypes.has("attach"))) return true;
2706
2726
  if (!snapshotPending || !afterSnapshot) return awaitEnvelope;
2707
2727
  snapshotPending = false;
2708
2728
  assertInputWritable();
@@ -2731,7 +2751,10 @@ async function runReactLynxSession(options) {
2731
2751
  framesSeen += 1;
2732
2752
  envelopeTypes.add(envelope.type);
2733
2753
  debug("frame %d: type=%s dataSize=%s", framesSeen, envelope.type, Array.isArray(envelope.data) ? envelope.data.length : typeof envelope.data);
2734
- if ("operation_v2" === envelope.type && Array.isArray(envelope.data)) {
2754
+ if ("init" === envelope.type) {
2755
+ state.tree.clear();
2756
+ state.roots.length = 0;
2757
+ } else if ("operation_v2" === envelope.type && Array.isArray(envelope.data)) {
2735
2758
  operationFrames += 1;
2736
2759
  applyOperationV2(state, envelope.data);
2737
2760
  } else if ("root-order" === envelope.type && Array.isArray(envelope.data)) {
@@ -4667,9 +4690,6 @@ function numberParam(params, key) {
4667
4690
  if (Number.isFinite(parsed)) return parsed;
4668
4691
  }
4669
4692
  }
4670
- function targets_isHeadlessClientId(clientId) {
4671
- return clientId.startsWith("headless:");
4672
- }
4673
4693
  function targetFailure(action, message, nextActions) {
4674
4694
  return result_fail(action, message, {
4675
4695
  reason: "target-not-found",
@@ -4691,19 +4711,14 @@ async function resolveTarget(action, params, connector, requirement) {
4691
4711
  };
4692
4712
  if (!clientId) {
4693
4713
  const clients = await connector.listClients();
4694
- const firstClient = clients.find((client)=>!targets_isHeadlessClientId(client.id));
4695
- if (!firstClient) {
4696
- const headlessAvailable = clients.some((client)=>targets_isHeadlessClientId(client.id));
4697
- return {
4698
- ok: false,
4699
- result: targetFailure(action, headlessAvailable ? "No real-device clients found. The built-in headless runtime is available but is never auto-selected." : "No available clients found.", headlessAvailable ? [
4700
- "Retry with an explicit headless client, for example `--client headless:0`."
4701
- ] : [
4702
- "Connect a Lynx client, then retry the command.",
4703
- "Run `agent-lynx list-clients` to verify discovery."
4704
- ])
4705
- };
4706
- }
4714
+ const firstClient = clients[0];
4715
+ if (!firstClient) return {
4716
+ ok: false,
4717
+ result: targetFailure(action, "No available clients found.", [
4718
+ "Connect a Lynx client, then retry the command.",
4719
+ "Run `agent-lynx list-clients` to verify discovery."
4720
+ ])
4721
+ };
4707
4722
  clientId = firstClient.id;
4708
4723
  }
4709
4724
  const withClient = {
@@ -4725,9 +4740,7 @@ async function resolveTarget(action, params, connector, requirement) {
4725
4740
  const sessions = await connector.sendListSessionMessage(clientId);
4726
4741
  if (0 === sessions.length) return {
4727
4742
  ok: false,
4728
- result: targetFailure(action, targets_isHeadlessClientId(clientId) ? `No sessions found for headless client ${clientId}. The headless runtime has no page open yet.` : `No available sessions found for client: ${clientId}`, targets_isHeadlessClientId(clientId) ? [
4729
- `Open a page first with \`agent-lynx open --client ${clientId} <url>\`.`
4730
- ] : [
4743
+ result: targetFailure(action, `No available sessions found for client: ${clientId}`, [
4731
4744
  `Open or reload a Lynx page on ${clientId}.`,
4732
4745
  `Run \`agent-lynx list-sessions --client ${clientId}\`.`
4733
4746
  ])
@@ -4746,9 +4759,6 @@ async function resolveTarget(action, params, connector, requirement) {
4746
4759
  const DEFAULT_TIMEOUT_MS = 30000;
4747
4760
  const DEFAULT_INTERVAL_MS = 1000;
4748
4761
  const DISCOVERY_DEADLINE = Symbol("discoveryDeadline");
4749
- function wait_for_client_isHeadlessClientId(clientId) {
4750
- return clientId.startsWith("headless:");
4751
- }
4752
4762
  function finiteNumber(value) {
4753
4763
  if ("number" == typeof value && Number.isFinite(value)) return value;
4754
4764
  if ("string" == typeof value && "" !== value.trim()) {
@@ -4773,16 +4783,14 @@ function formatClientForError(client) {
4773
4783
  return ` ${client.id}${suffix}`;
4774
4784
  }
4775
4785
  function selectClients(clients, clientName) {
4776
- const realClients = clients.filter((client)=>!wait_for_client_isHeadlessClientId(client.id));
4777
- if (void 0 === clientName) return realClients.slice(0, 1);
4778
- return realClients.filter((client)=>getClientNames(client).includes(clientName));
4786
+ if (void 0 === clientName) return clients.slice(0, 1);
4787
+ return clients.filter((client)=>getClientNames(client).includes(clientName));
4779
4788
  }
4780
4789
  function timeoutMessage(clientName, clients) {
4781
4790
  if (void 0 !== clientName) {
4782
- const availableClients = clients.filter((client)=>!wait_for_client_isHeadlessClientId(client.id)).map(formatClientForError).join("\n");
4783
- return `No client found matching --client-name "${clientName}".` + (availableClients ? `\nAvailable clients:\n${availableClients}` : "\nNo real-device clients are available.");
4791
+ const availableClients = clients.map(formatClientForError).join("\n");
4792
+ return `No client found matching --client-name "${clientName}".` + (availableClients ? `\nAvailable clients:\n${availableClients}` : "\nNo clients are available.");
4784
4793
  }
4785
- if (clients.some((client)=>wait_for_client_isHeadlessClientId(client.id))) return "Only headless Lynx DevTool clients were found before timeout; waiting without --client-name requires a non-headless client.";
4786
4794
  return "No Lynx DevTool clients were found before timeout.";
4787
4795
  }
4788
4796
  async function discoverBeforeDeadline(connector, deadline, signal) {
@@ -4835,7 +4843,7 @@ async function* waitForClientStream(connector, params, signal) {
4835
4843
  }));
4836
4844
  lastClients = discovery;
4837
4845
  attempts += 1;
4838
- const availableClients = lastClients.filter((client)=>!wait_for_client_isHeadlessClientId(client.id));
4846
+ const availableClients = lastClients;
4839
4847
  const clients = selectClients(lastClients, clientName);
4840
4848
  const elapsedMs = Date.now() - startedAt;
4841
4849
  if (clients.length > 0) return void (yield ok("wait-for-client", {
package/dist/f1.js CHANGED
@@ -11,23 +11,44 @@ __webpack_require__.add({
11
11
  module.exports = require("utf-8-validate");
12
12
  }
13
13
  });
14
+ function requireNumericPort(port) {
15
+ if ("number" == typeof port) return port;
16
+ if (/^\d+$/.test(port)) return Number(port);
17
+ throw new TypeError(`Transport requires a numeric port, received target: ${port}`);
18
+ }
19
+ function withTransports(clients, transports) {
20
+ if (void 0 !== transports) Object.defineProperty(clients, "transports", {
21
+ value: transports,
22
+ configurable: true
23
+ });
24
+ return clients;
25
+ }
14
26
  class ClientId {
15
- static serialize(deviceId, target) {
27
+ transportId;
28
+ deviceId;
29
+ port;
30
+ constructor(transportId, deviceId, port){
31
+ this.transportId = transportId;
32
+ this.deviceId = deviceId;
33
+ this.port = port;
34
+ }
35
+ static serialize(transportId, deviceId, target) {
36
+ const encodedTransportId = encodeURIComponent(transportId);
37
+ const encodedDeviceId = encodeURIComponent(deviceId);
16
38
  const encodedTarget = "string" == typeof target ? encodeURIComponent(target) : target;
17
- return `${encodeURIComponent(deviceId)}:${encodedTarget}`;
39
+ return `${encodedTransportId}:${encodedDeviceId}:${encodedTarget}`;
18
40
  }
19
41
  static deserialize(clientId) {
20
42
  try {
21
- const lastColonIndex = clientId.lastIndexOf(":");
22
- if (-1 === lastColonIndex) return null;
23
- const target = decodeURIComponent(clientId.substring(lastColonIndex + 1));
24
- if (!target) return null;
43
+ const [rawTransportId, rawDeviceId, rawTarget, ...rest] = clientId.split(":");
44
+ if (void 0 === rawTransportId || void 0 === rawDeviceId || void 0 === rawTarget || rest.length > 0) return null;
45
+ const transportId = decodeURIComponent(rawTransportId);
46
+ const deviceId = decodeURIComponent(rawDeviceId);
47
+ const target = decodeURIComponent(rawTarget);
48
+ if (!transportId || !deviceId || !target) return null;
25
49
  const port = /^-?\d+$/.test(target) ? Number(target) : target;
26
50
  if ("number" == typeof port && !Number.isSafeInteger(port)) return null;
27
- return {
28
- deviceId: decodeURIComponent(clientId.substring(0, lastColonIndex)),
29
- port
30
- };
51
+ return new ClientId(transportId, deviceId, port);
31
52
  } catch {
32
53
  return null;
33
54
  }
@@ -170,6 +191,7 @@ function urlToDeviceId(url) {
170
191
  return `HDT-${url}`;
171
192
  }
172
193
  class HDTTransport {
194
+ id;
173
195
  #url;
174
196
  static DEFAULT_PORT = 19783;
175
197
  static createTransports(port = HDTTransport.DEFAULT_PORT, backoff = 10) {
@@ -182,6 +204,7 @@ class HDTTransport {
182
204
  constructor(urlOrPort){
183
205
  const url = "number" == typeof urlOrPort ? `ws://127.0.0.1:${urlOrPort}/mdevices/page/android` : urlOrPort;
184
206
  this.#url = url;
207
+ this.id = urlToDeviceId(url);
185
208
  }
186
209
  close() {
187
210
  return Promise.resolve();
@@ -214,7 +237,7 @@ class HDTTransport {
214
237
  const clients = msg.data;
215
238
  debug("Received client list from HDT transport: %o", clients);
216
239
  return clients.filter(({ info })=>"ws://127.0.0.1:3005/ws" !== this.#url || "unknown" !== info.osType).map(({ info, id })=>({
217
- id: ClientId.serialize(urlToDeviceId(this.#url), info.debugRouterId || Number(id)),
240
+ id: ClientId.serialize(this.id, urlToDeviceId(this.#url), info.debugRouterId || Number(id)),
218
241
  info
219
242
  }));
220
243
  }
@@ -459,6 +482,7 @@ async function withAbortSignal(promise, signal) {
459
482
  }
460
483
  const daemon_debug = ansi_createDebug("devtool-mcp-server:daemon:transport");
461
484
  class DaemonTransport {
485
+ id = "daemon";
462
486
  #endpoint;
463
487
  constructor(endpoint = 21783){
464
488
  if ("string" == typeof endpoint) {
@@ -490,15 +514,24 @@ class DaemonTransport {
490
514
  }, options?.signal);
491
515
  }
492
516
  async listClients() {
493
- const entries = await this.#controlRequest("listClients");
494
- daemon_debug("received ClientList with %d entries", entries.length);
495
- return entries.map(({ id, info })=>({
496
- id,
497
- info
498
- }));
517
+ const conn = await this.#createWebSocketConnection();
518
+ try {
519
+ const response = await this.#controlRequestOnConn(conn, "listClients");
520
+ const entries = response.result ?? [];
521
+ daemon_debug("received ClientList with %d entries", entries.length);
522
+ return withTransports(entries.map(({ id, info })=>({
523
+ id,
524
+ info
525
+ })), [
526
+ this.id,
527
+ ...response.transports ?? []
528
+ ]);
529
+ } finally{
530
+ await conn[Symbol.asyncDispose]();
531
+ }
499
532
  }
500
533
  async connect(options) {
501
- const { deviceId, signal } = options;
534
+ const { transportId, deviceId, signal } = options;
502
535
  const { port } = options;
503
536
  daemon_debug("connect to %s:%o via daemon", deviceId, port);
504
537
  const conn = await this.#createWebSocketConnection(signal);
@@ -508,6 +541,7 @@ class DaemonTransport {
508
541
  AbortSignal.timeout(10000)
509
542
  ]) : void 0;
510
543
  await this.#controlRequestOnConn(conn, "subscribe", {
544
+ transportId,
511
545
  deviceId,
512
546
  port
513
547
  }, subscribeSignal);
@@ -538,7 +572,7 @@ class DaemonTransport {
538
572
  async #controlRequest(method, params, signal) {
539
573
  const conn = await this.#createWebSocketConnection(signal);
540
574
  try {
541
- return await this.#controlRequestOnConn(conn, method, params, signal);
575
+ return (await this.#controlRequestOnConn(conn, method, params, signal)).result;
542
576
  } finally{
543
577
  await conn[Symbol.asyncDispose]();
544
578
  }
@@ -568,7 +602,7 @@ class DaemonTransport {
568
602
  const resp = msg.data;
569
603
  if (resp.id === id) {
570
604
  if (resp.error) throw new Error(resp.error);
571
- return resp.result;
605
+ return resp;
572
606
  }
573
607
  }
574
608
  }
@@ -723,4 +757,4 @@ class daemon_JSONStringToObjectStream extends TransformStream {
723
757
  });
724
758
  }
725
759
  }
726
- export { ClientId, DaemonTransport, HDTTransport };
760
+ export { ClientId, DaemonTransport, HDTTransport, requireNumericPort, withTransports };