@lynx-js/devtool-connector 0.18.7 → 0.19.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/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @lynx-js/devtool-connector
2
2
 
3
+ ## 0.19.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Remove the built-in `agent-lynx --client headless:0` path, replaced by Lynx Simulator, including SpawnTransport and headless runtime preparation. EmbeddedLynx and NodeLynx test runtimes remain available.
8
+ - Include the transport ID in client IDs to route requests directly to the matching transport and isolate daemon connections across transports. Client IDs now use `transportId:deviceId:target`; rediscover clients instead of reusing IDs from older versions.
9
+
10
+ ### Patch Changes
11
+
12
+ - Updated dependency `@yume-chan/adb-server-node-tcp` to `3.0.0-beta.5`.
13
+ - Updated dependency `@yume-chan/adb` to `3.0.0-beta.5`.
14
+ - Updated dependency `@yume-chan/stream-extra` to `3.0.0-beta.5`.
15
+ - Updated dependency `plist` to `^5.1.0`.
16
+ - Updated dependency `@rslib/core` to `^1.0.6`.
17
+ - Reuse a known target's transport when reconnecting after a disconnect, allowing its connection setup to wait for the device instead of failing on a temporarily empty device scan.
18
+ - Include the actual discovery path in empty `list-clients` errors, including responding HDT/Aiden endpoints and whether they bypassed direct device discovery. Preserve this information through the daemon and clarify that `--no-daemon` still prioritizes HDT/Aiden.
19
+ - Load the Inspector Preact DevTools plugin from the configured network mirror so the panel is reachable in restricted network environments.
20
+
21
+ ## 0.18.8
22
+
23
+ No changes in this release.
24
+
3
25
  ## 0.18.7
4
26
 
5
27
  ### Patch Changes
package/dist/2.js CHANGED
@@ -1781,7 +1781,7 @@ function log(...args) {
1781
1781
  }
1782
1782
  const defaultOptions = {
1783
1783
  useColors: ansi_useColors(),
1784
- formatArgs: formatArgs,
1784
+ formatArgs,
1785
1785
  formatters: {
1786
1786
  o (v) {
1787
1787
  this.inspectOpts.colors = this.useColors;
@@ -1792,8 +1792,8 @@ const defaultOptions = {
1792
1792
  return inspect(v, this.inspectOpts);
1793
1793
  }
1794
1794
  },
1795
- inspectOpts: inspectOpts,
1796
- log: log,
1795
+ inspectOpts,
1796
+ log,
1797
1797
  humanize: humanize
1798
1798
  };
1799
1799
  function ansi_createDebug(namespace, options) {
@@ -1826,7 +1826,7 @@ const DAEMON_SHUTDOWN_PATH = `${DAEMON_WS_PATH}/shutdown`;
1826
1826
  const DAEMON_INSPECTOR_PATH = `${DAEMON_WS_PATH}/inspector`;
1827
1827
  const DAEMON_COMMAND_PATH_PREFIX = "/command/";
1828
1828
  var package_namespaceObject = {
1829
- rE: "0.18.7"
1829
+ rE: "0.19.0"
1830
1830
  };
1831
1831
  const CONNECTOR_VERSION = package_namespaceObject.rE;
1832
1832
  const node_modules_semver = __webpack_require__("../../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/index.js");
package/dist/a.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { ReadableStream } from "node:stream/web";
2
- import { isGetGlobalSwitchResponse, isInitializeResponse, AppResponseTransformStream, GlobalSwitchRequestTransformStream, isListSessionResponse, isHeadlessPrepareResponse, createCorrelatedFilter, isSetGlobalSwitchResponse, CDPResponseTransformStream, CDPOutputTransformStream, CustomizedResponseTransformStream, CDPRequestTransformStream, CustomizedRequestTransformStream, SessionGuardTransformStream, FilterTransformStream, InspectStream, CustomizedClientIdTransformStream } from "./hb.js";
2
+ import { isGetGlobalSwitchResponse, isInitializeResponse, AppResponseTransformStream, GlobalSwitchRequestTransformStream, isListSessionResponse, createCorrelatedFilter, isSetGlobalSwitchResponse, CDPResponseTransformStream, CDPOutputTransformStream, CustomizedResponseTransformStream, CDPRequestTransformStream, CustomizedRequestTransformStream, SessionGuardTransformStream, FilterTransformStream, InspectStream, CustomizedClientIdTransformStream } from "./hb.js";
3
3
  import { ansi_createDebug, isDaemonLifecycleError } from "./2.js";
4
4
  import { nextRequestId } from "./3.js";
5
- import { DaemonTransport, HDTTransport, ClientId } from "./f1.js";
5
+ import { DaemonTransport, HDTTransport, ClientId, withTransports } from "./f1.js";
6
6
  function throwClientDiscoveryFailures(failures) {
7
7
  if (1 === failures.length) throw failures[0];
8
8
  const details = failures.map((failure)=>failure instanceof Error ? failure.message : String(failure)).join("; ");
@@ -113,39 +113,69 @@ class Connector {
113
113
  const daemonClients = fulfilledDaemonClientResults.flatMap((r)=>r.value);
114
114
  if (fulfilledDaemonClientResults.length > 0) {
115
115
  debug("Using clients from daemon transport: %o", daemonClients);
116
- return daemonClients;
116
+ return withTransports(daemonClients, fulfilledDaemonClientResults.flatMap((r)=>r.value.transports ?? [
117
+ "daemon"
118
+ ]));
117
119
  }
118
120
  const daemonLifecycleFailure = daemonClientResults.filter((result)=>"rejected" === result.status).map((result)=>result.reason).find(isDaemonLifecycleError);
119
121
  if (daemonLifecycleFailure) throw daemonLifecycleFailure;
120
122
  const hdtClientResults = await Promise.allSettled(this.#hdtTransports.map(async (transport)=>{
121
123
  const clients = await transport.listClients();
122
124
  await Promise.allSettled(clients.flatMap(({ id })=>this.#setupClient(transport, id)));
123
- return clients;
125
+ return {
126
+ clients,
127
+ id: transport.id
128
+ };
124
129
  }));
125
130
  const fulfilledHDTClientResults = hdtClientResults.filter((r)=>"fulfilled" === r.status);
126
131
  discoveryFailures.push(...hdtClientResults.filter((r)=>"rejected" === r.status).map((r)=>r.reason));
127
- const hdtClients = fulfilledHDTClientResults.flatMap((r)=>r.value);
132
+ const hdtClients = fulfilledHDTClientResults.flatMap((r)=>r.value.clients);
128
133
  if (fulfilledHDTClientResults.length > 0) {
129
134
  debug("Using clients from HDT transport: %o", hdtClients);
130
- return hdtClients;
135
+ return withTransports(hdtClients, fulfilledHDTClientResults.map((r)=>r.value.id));
136
+ }
137
+ const directTransports = this.#transports.filter((t)=>!(t instanceof DaemonTransport));
138
+ const clientListTransports = directTransports.filter((t)=>!(t instanceof HDTTransport)).filter(hasClientList);
139
+ const deviceProbeTransports = directTransports.filter((t)=>!hasClientList(t));
140
+ const [clientListResults, transportDevices] = await Promise.all([
141
+ Promise.allSettled(clientListTransports.map(async (transport)=>{
142
+ const clients = await transport.listClients();
143
+ await Promise.allSettled(clients.flatMap(({ id })=>this.#setupClient(transport, id)));
144
+ return {
145
+ clients,
146
+ id: transport.id
147
+ };
148
+ })),
149
+ Promise.allSettled(deviceProbeTransports.map(async (transport)=>({
150
+ transport,
151
+ devices: await transport.listDevices()
152
+ })))
153
+ ]);
154
+ for (const result of clientListResults)if ("rejected" === result.status) {
155
+ discoveryFailures.push(result.reason);
156
+ debug("listClients: listClients failed on one transport: %O", result.reason);
131
157
  }
132
- const transportDevices = await Promise.allSettled(this.#transports.filter((t)=>!(t instanceof HDTTransport)).filter((t)=>!(t instanceof DaemonTransport)).map(async (transport)=>({
133
- transport,
134
- devices: await transport.listDevices()
135
- })));
136
158
  for (const result of transportDevices)if ("rejected" === result.status) {
137
159
  discoveryFailures.push(result.reason);
138
160
  debug("listClients: listDevices failed on one transport: %O", result.reason);
139
161
  }
162
+ const fulfilledClientListResults = clientListResults.filter((result)=>"fulfilled" === result.status);
140
163
  const fulfilledTransportDevices = transportDevices.filter((result)=>"fulfilled" === result.status);
141
- if (0 === fulfilledTransportDevices.length && discoveryFailures.length > 0) throwClientDiscoveryFailures(discoveryFailures);
164
+ if (0 === fulfilledClientListResults.length && 0 === fulfilledTransportDevices.length && discoveryFailures.length > 0) throwClientDiscoveryFailures(discoveryFailures);
142
165
  const results = await Promise.allSettled(fulfilledTransportDevices.map((r)=>r.value).flatMap(({ transport, devices })=>devices.flatMap(({ id })=>this.#listClientsForDevice(transport, id))));
143
166
  const fulfilledClientResults = results.filter((r)=>"fulfilled" === r.status);
144
- if (0 === fulfilledClientResults.length && results.length > 0) throwClientDiscoveryFailures([
167
+ if (0 === fulfilledClientListResults.length && 0 === fulfilledClientResults.length && results.length > 0) throwClientDiscoveryFailures([
145
168
  ...discoveryFailures,
146
169
  ...results.filter((result)=>"rejected" === result.status).map((result)=>result.reason)
147
170
  ]);
148
- return fulfilledClientResults.flatMap((r)=>r.value);
171
+ const fulfilledTransports = [
172
+ ...fulfilledClientListResults.map((r)=>r.value.id),
173
+ ...fulfilledTransportDevices.map((r)=>r.value.transport.id)
174
+ ];
175
+ return withTransports([
176
+ ...fulfilledClientListResults.flatMap((r)=>r.value.clients),
177
+ ...fulfilledClientResults.flatMap((r)=>r.value)
178
+ ], fulfilledTransports.length > 0 ? fulfilledTransports : void 0);
149
179
  }
150
180
  async listDevices() {
151
181
  const results = await Promise.allSettled(this.#transports.map((t)=>t.listDevices()));
@@ -256,39 +286,6 @@ class Connector {
256
286
  async sendListSessionMessage(clientId) {
257
287
  return await this.#sendListSessionMessage(clientId);
258
288
  }
259
- async prepareHeadless(clientId) {
260
- const { data: { data: state } } = await this.#sendMessage(clientId, {
261
- event: "Customized",
262
- data: {
263
- type: "HeadlessPrepare",
264
- data: {}
265
- }
266
- }, {
267
- input: [],
268
- output: [
269
- new FilterTransformStream(isHeadlessPrepareResponse)
270
- ]
271
- });
272
- return state;
273
- }
274
- async waitForHeadlessReady(clientId, options = {}) {
275
- const timeoutMs = options.timeoutMs ?? 300000;
276
- const pollIntervalMs = options.pollIntervalMs ?? 1000;
277
- const { setTimeout: delay } = await import("node:timers/promises");
278
- const deadline = Date.now() + timeoutMs;
279
- let lastError;
280
- for(;;){
281
- options.signal?.throwIfAborted();
282
- const state = await this.prepareHeadless(clientId);
283
- options.signal?.throwIfAborted();
284
- if ("ready" === state.status) return;
285
- if ("error" === state.status) lastError = state.message ?? "unknown error";
286
- if (Date.now() >= deadline) throw new Error(void 0 !== lastError ? `Failed to prepare headless runtime: ${lastError}` : `Timed out preparing headless runtime after ${timeoutMs}ms`);
287
- await delay(pollIntervalMs, void 0, options.signal ? {
288
- signal: options.signal
289
- } : {});
290
- }
291
- }
292
289
  async #sendListSessionMessage(clientId) {
293
290
  const id = nextRequestId();
294
291
  const { data: { data: sessions } } = await this.#sendMessage(clientId, {
@@ -337,9 +334,10 @@ class Connector {
337
334
  });
338
335
  }
339
336
  async sendStream(clientId, inputStream, { signal, pipeline } = {}) {
340
- const { deviceId, port } = this.#resolveClientId(clientId);
341
- const transport = await this.#findTransportWithDeviceId(deviceId);
337
+ const { transportId, deviceId, port } = this.#resolveClientId(clientId);
338
+ const transport = await this.#findTransportWithDeviceId(deviceId, transportId);
342
339
  return await this.#connect(transport, {
340
+ transportId,
343
341
  deviceId,
344
342
  port,
345
343
  signal
@@ -367,12 +365,18 @@ class Connector {
367
365
  if (!parsed) throw new Error(`Invalid clientId: ${clientId}`);
368
366
  return parsed;
369
367
  }
370
- async #findTransportWithDeviceId(deviceId) {
368
+ async #findTransportWithDeviceId(deviceId, transportId) {
371
369
  const [onlyTransport] = this.#transports;
372
370
  if (1 === this.#transports.length && onlyTransport instanceof DaemonTransport) return onlyTransport;
373
371
  const daemonTransport = await this.#findTransportWithDeviceIdInPool(this.#daemonTransports, deviceId);
374
372
  if (daemonTransport) return daemonTransport;
375
- const transport = await this.#findTransportWithDeviceIdInPool(this.#transports.filter((t)=>!(t instanceof DaemonTransport)), deviceId);
373
+ const nonDaemonTransports = this.#transports.filter((t)=>!(t instanceof DaemonTransport));
374
+ if (void 0 !== transportId) {
375
+ const matchedById = nonDaemonTransports.find((t)=>t.id === transportId);
376
+ if (matchedById) return matchedById;
377
+ throw new Error(`Transport with id: ${transportId} not found`);
378
+ }
379
+ const transport = await this.#findTransportWithDeviceIdInPool(nonDaemonTransports, deviceId);
376
380
  if (transport) return transport;
377
381
  throw new Error(`Device with id: ${deviceId} not found`);
378
382
  }
@@ -393,7 +397,11 @@ class Connector {
393
397
  }
394
398
  async #connect(transport, options, inputStream, pipeline) {
395
399
  const { deviceId, port } = options;
396
- const conn = await transport.connect(options);
400
+ const conn = transport instanceof DaemonTransport ? await transport.connect(options) : await transport.connect({
401
+ deviceId,
402
+ port,
403
+ signal: options.signal
404
+ });
397
405
  const inputAbortController = new AbortController();
398
406
  const inputAbortReason = new Error("Connector input stream disposed");
399
407
  const inputClosed = [
@@ -429,9 +437,10 @@ class Connector {
429
437
  input: [],
430
438
  output: []
431
439
  }, signal) {
432
- const { deviceId, port } = this.#resolveClientId(clientId);
433
- const transport = await this.#findTransportWithDeviceId(deviceId);
440
+ const { transportId, deviceId, port } = this.#resolveClientId(clientId);
441
+ const transport = await this.#findTransportWithDeviceId(deviceId, transportId);
434
442
  return this.#sendMessageWithTransport(transport, {
443
+ transportId,
435
444
  deviceId,
436
445
  port,
437
446
  signal: signal ?? AbortSignal.timeout(10000)
@@ -455,7 +464,7 @@ class Connector {
455
464
  await outputStream.inputClosed;
456
465
  if (response.done) {
457
466
  options.signal?.throwIfAborted();
458
- const clientId = ClientId.serialize(options.deviceId, options.port);
467
+ const clientId = ClientId.serialize(transport.id, options.deviceId, options.port);
459
468
  throw new Error(`Transport ${transport.constructor.name} ended cleanly (EOF) while waiting for a response to ${request} on clientId: ${clientId}.`);
460
469
  } else result = response.value;
461
470
  } catch (err) {
@@ -486,7 +495,7 @@ class Connector {
486
495
  const results = await Promise.allSettled(PORTS.map(async (port)=>{
487
496
  const info = await this.#discoverAndSetupClient(transport, deviceId, port, discoverySignal);
488
497
  return {
489
- id: ClientId.serialize(deviceId, port),
498
+ id: ClientId.serialize(transport.id, deviceId, port),
490
499
  info,
491
500
  port
492
501
  };
@@ -581,9 +590,10 @@ class Connector {
581
590
  }
582
591
  }
583
592
  async #setupClient(transport, clientId) {
584
- const { deviceId, port } = this.#resolveClientId(clientId);
593
+ const { transportId, deviceId, port } = this.#resolveClientId(clientId);
585
594
  for (const { key, value } of clientSetupSwitches)try {
586
595
  await this.#sendMessageWithTransport(transport, {
596
+ transportId,
587
597
  deviceId,
588
598
  port,
589
599
  signal: AbortSignal.timeout(3000)
@@ -1,8 +1,9 @@
1
1
  export type ClientTarget = number | string;
2
2
  export declare class ClientId {
3
- static serialize(deviceId: string, target: ClientTarget): string;
4
- static deserialize(clientId: string): {
5
- deviceId: string;
6
- port: ClientTarget;
7
- } | null;
3
+ readonly transportId: string;
4
+ readonly deviceId: string;
5
+ readonly port: ClientTarget;
6
+ constructor(transportId: string, deviceId: string, port: ClientTarget);
7
+ static serialize(transportId: string, deviceId: string, target: ClientTarget): string;
8
+ static deserialize(clientId: string): ClientId | null;
8
9
  }
@@ -26,14 +26,14 @@ export interface OpenData {
26
26
  export interface WaitForClientData {
27
27
  matched: true;
28
28
  clients: Client[];
29
- /** Non-headless clients returned by the latest successful discovery attempt. */
29
+ /** Clients returned by the latest successful discovery attempt. */
30
30
  availableClients: Client[];
31
31
  attempts: number;
32
32
  elapsedMs: number;
33
33
  }
34
34
  export interface WaitForClientProgressData {
35
35
  matched: false;
36
- /** Non-headless clients returned by the latest successful discovery attempt. */
36
+ /** Clients returned by the latest successful discovery attempt. */
37
37
  availableClients: Client[];
38
38
  attempts: number;
39
39
  elapsedMs: number;
@@ -1,12 +1,5 @@
1
1
  import { DaemonManager } from "../2.js";
2
2
  import { fail as result_fail, appendCommandQueryParam, ActionCore } from "../f.js";
3
- const DEFAULT_COMMAND_TIMEOUT_MS = 30000;
4
- const HEADLESS_OPEN_TIMEOUT_MS = 360000;
5
- function getDefaultCommandTimeoutMs(action, params) {
6
- const clientId = params["clientId"];
7
- if ("open" === action && "string" == typeof clientId && clientId.trim().startsWith("headless:")) return HEADLESS_OPEN_TIMEOUT_MS;
8
- return DEFAULT_COMMAND_TIMEOUT_MS;
9
- }
10
3
  const MAX_SSE_BUFFER_LENGTH = 1048576;
11
4
  async function responseText(response) {
12
5
  try {
@@ -66,7 +59,7 @@ function callRawCommand(action, params, options = {}) {
66
59
  function callCommand(action, params, options = {}) {
67
60
  return callRawCommand(action, params, {
68
61
  ...options,
69
- timeoutMs: options.timeoutMs ?? getDefaultCommandTimeoutMs(action, params)
62
+ timeoutMs: options.timeoutMs ?? 30000
70
63
  });
71
64
  }
72
65
  function getStreamUrl(port, action, params) {
@@ -91,7 +84,7 @@ class HttpCommandClient {
91
84
  execute(action, params, options = {}) {
92
85
  return this.executeRaw(action, params, {
93
86
  ...options,
94
- timeoutMs: options.timeoutMs ?? getDefaultCommandTimeoutMs(action, params)
87
+ timeoutMs: options.timeoutMs ?? 30000
95
88
  });
96
89
  }
97
90
  stream(action, params, options = {}) {
@@ -224,7 +217,7 @@ class InProcessCommandClient {
224
217
  }
225
218
  execute(action, params, options = {}) {
226
219
  const commandParams = params;
227
- const signal = AbortSignal.timeout(options.timeoutMs ?? getDefaultCommandTimeoutMs(action, commandParams));
220
+ const signal = AbortSignal.timeout(options.timeoutMs ?? 30000);
228
221
  return this.#core.execute(action, commandParams, {
229
222
  connector: this.#connector
230
223
  }, signal);
@@ -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", {