@lynx-js/devtool-connector 0.19.1 → 0.20.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.
@@ -231,5 +231,5 @@ class InProcessCommandClient {
231
231
  }
232
232
  var command_DEFAULT_REACTLYNX_IDLE_MS = 700;
233
233
  var command_DEFAULT_REACTLYNX_MAX_MS = 5000;
234
- export { ActionCore, DevNodeType, NO_CLIENTS_FOUND_MESSAGE, ScreenshotAnnotationError, ScreenshotTimeoutError, annotateScreenshot, applyOperationV2, applyRootOrder, buildReactLynxOutboundFrame, buildReactLynxUpdatePath, buildRefs, buildRegexMatcher, buildSnapshot, buildSubstringMatcher, captureScreenshot, captureScreenshotFrame, centerOfQuad, createRendererState, deserializeRendererState, fail, fetchDebugMetadata, findReactLynxComponents, formatReactLynxTree, getOriginalNodeSourceInfo, listClientsAction, listSessionsAction, normalizeRef, ok, openAction, parseReactLynxComponentRef, parseReactLynxLinkRef, reactLynxEmptyTreeDiagnostic, remapOriginalNodeSourceInfo, runReactLynxSession, serializeRendererState, touchTap, typeTag, validateRef, waitForClientStream } from "../f.js";
234
+ export { ActionCore, DevNodeType, NO_CLIENTS_FOUND_MESSAGE, ScreenshotAnnotationError, ScreenshotTimeoutError, annotateScreenshot, applyOperationV2, applyRootOrder, buildReactLynxOutboundFrame, buildReactLynxPageHookFrame, buildReactLynxUpdatePath, buildRefs, buildRegexMatcher, buildSnapshot, buildSubstringMatcher, captureScreenshot, captureScreenshotFrame, centerOfQuad, createRendererState, deserializeRendererState, fail, fetchDebugMetadata, findReactLynxComponents, formatReactLynxTree, getOriginalNodeSourceInfo, listClientsAction, listSessionsAction, normalizeRef, ok, openAction, parseReactLynxComponentRef, parseReactLynxLinkRef, reactLynxEmptyTreeDiagnostic, remapOriginalNodeSourceInfo, runReactLynxSession, serializeRendererState, touchTap, typeTag, validateRef, waitForClientStream } from "../f.js";
235
235
  export { HttpCommandClient, InProcessCommandClient, callCommand, callRawCommand, command_DEFAULT_REACTLYNX_IDLE_MS as DEFAULT_REACTLYNX_IDLE_MS, command_DEFAULT_REACTLYNX_MAX_MS as DEFAULT_REACTLYNX_MAX_MS, streamCommand, streamRawCommand };
@@ -50,7 +50,7 @@ export declare class ReactLynxController {
50
50
  refresh: boolean;
51
51
  }, signal: AbortSignal): Promise<ReactLynxComponentData>;
52
52
  componentForElement(connector: Connector, target: Target, options: {
53
- uniqueId: number;
53
+ uniqueIds: readonly number[];
54
54
  showShells: boolean;
55
55
  refresh: boolean;
56
56
  }, signal: AbortSignal): Promise<ReactLynxElementToComponentMapping>;
@@ -8,6 +8,7 @@ export interface PreactEnvelope<T = unknown> {
8
8
  data: T;
9
9
  }
10
10
  export interface ReactLynxOutboundFrame {
11
+ id?: number;
11
12
  method: string;
12
13
  params: {
13
14
  vmType: string;
@@ -16,6 +17,8 @@ export interface ReactLynxOutboundFrame {
16
17
  };
17
18
  }
18
19
  export declare function buildReactLynxOutboundFrame<T = null>(type: string, data?: T): ReactLynxOutboundFrame;
20
+ /** Build a `preact-page-hook` frame (e.g. `root-order-page` FIFO sentinel). */
21
+ export declare function buildReactLynxPageHookFrame<T = null>(type: string, data?: T): ReactLynxOutboundFrame;
19
22
  export interface ReactLynxSessionResult {
20
23
  state: RendererState;
21
24
  framesSeen: number;
@@ -2,10 +2,11 @@ import promises from "node:fs/promises";
2
2
  import node_os from "node:os";
3
3
  import node_path from "node:path";
4
4
  import { parseArgs } from "node:util";
5
- import { AndroidTransport, DesktopTransport, iOSTransport } from "../h.js";
5
+ import { AndroidTransport, iOSTransport } from "../a.js";
6
+ import { DesktopTransport, LynxSimulatorTransport } from "../h6.js";
6
7
  import { HDTTransport } from "../f1.js";
7
8
  import "../2.js";
8
- import { DevtoolDaemon } from "../t.js";
9
+ import { DevtoolDaemon } from "../tw.js";
9
10
  const DEBUG_ROUTER_DIR = node_path.join(node_os.homedir(), ".DebugRouterConnector");
10
11
  const PIDFILE = node_path.join(DEBUG_ROUTER_DIR, "daemon.pid");
11
12
  const { values } = parseArgs({
@@ -22,7 +23,8 @@ const daemon = new DevtoolDaemon([
22
23
  new AndroidTransport(),
23
24
  new iOSTransport(),
24
25
  new DesktopTransport(),
25
- ...HDTTransport.createTransports()
26
+ ...HDTTransport.createTransports(),
27
+ new LynxSimulatorTransport()
26
28
  ], {
27
29
  onIdle: ()=>{
28
30
  daemon.close().then(()=>{
@@ -4,5 +4,5 @@ var daemon_DAEMON_CONVERGENCE_TIMEOUT_MS = 15000;
4
4
  var daemon_DAEMON_LIFECYCLE_PROTOCOL_VERSION = 1;
5
5
  var daemon_DEFAULT_DAEMON_PORT = 21783;
6
6
  export { DAEMON_COMMAND_PATH_PREFIX, DAEMON_INSPECTOR_PATH, DAEMON_PRODUCT, DAEMON_SHUTDOWN_PATH, DAEMON_VERSION_PATH, DAEMON_WS_PATH, DaemonLifecycle, DaemonLifecycleError, DaemonManager, createDaemonProcessEnvironment, isControlRequest, isCustomizedMessage, isDaemonLifecycleError, isListClientsRequest, isPingEvent, isRegisterEvent, resolveDaemonEntryPath } from "../2.js";
7
- export { DeviceConnection, DevtoolDaemon, HDT_RES_PATH_PREFIX, InspectorAssets, StaticServer, TarballCache } from "../t.js";
7
+ export { DeviceConnection, DevtoolDaemon, HDT_RES_PATH_PREFIX, InspectorAssets, StaticServer, TarballCache } from "../tw.js";
8
8
  export { daemon_DAEMON_BROWSER_PREVIEW_PROTOCOL_VERSION as DAEMON_BROWSER_PREVIEW_PROTOCOL_VERSION, daemon_DAEMON_COMMAND_PROTOCOL_VERSION as DAEMON_COMMAND_PROTOCOL_VERSION, daemon_DAEMON_CONVERGENCE_TIMEOUT_MS as DAEMON_CONVERGENCE_TIMEOUT_MS, daemon_DAEMON_LIFECYCLE_PROTOCOL_VERSION as DAEMON_LIFECYCLE_PROTOCOL_VERSION, daemon_DEFAULT_DAEMON_PORT as DEFAULT_DAEMON_PORT };
package/dist/f.js CHANGED
@@ -1,12 +1,12 @@
1
+ import { rspackRequire, moduleFactories } from "./rslib-runtime.js";
1
2
  import { setTimeout as promises_setTimeout } from "node:timers/promises";
2
- import { ReadableStream } from "node:stream/web";
3
+ import { ReadableStream, TransformStream } from "node:stream/web";
3
4
  import { remapUiTree } from "@lynx-js/debug-metadata";
4
- import { __webpack_require__ } from "./rslib-runtime.js";
5
- import { ansi_createDebug } from "./2.js";
6
5
  import { nextRequestId } from "./3.js";
7
- __webpack_require__.add({
8
- "../../../node_modules/.pnpm/jpeg-js@0.4.4/node_modules/jpeg-js/index.js" (module, __unused_rspack_exports, __webpack_require__) {
9
- var encode = __webpack_require__("../../../node_modules/.pnpm/jpeg-js@0.4.4/node_modules/jpeg-js/lib/encoder.js"), decode = __webpack_require__("../../../node_modules/.pnpm/jpeg-js@0.4.4/node_modules/jpeg-js/lib/decoder.js");
6
+ import { ansi_createDebug } from "./2.js";
7
+ moduleFactories.add({
8
+ "../../../node_modules/.pnpm/jpeg-js@0.4.4/node_modules/jpeg-js/index.js" (module) {
9
+ var encode = rspackRequire("../../../node_modules/.pnpm/jpeg-js@0.4.4/node_modules/jpeg-js/lib/encoder.js"), decode = rspackRequire("../../../node_modules/.pnpm/jpeg-js@0.4.4/node_modules/jpeg-js/lib/decoder.js");
10
10
  module.exports = {
11
11
  encode: encode,
12
12
  decode: decode
@@ -2074,7 +2074,7 @@ function result_fail(action, message, options = {}) {
2074
2074
  };
2075
2075
  }
2076
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.";
2077
+ const noClientsHelp = "Try these steps:\n1. Make sure the target device/simulator and app are running.\n2. If the app is still launching, run `agent-lynx wait-for-client` instead of polling `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
2078
  const NO_CLIENTS_FOUND_MESSAGE = [
2079
2079
  noClientsSummary,
2080
2080
  noClientsHelp
@@ -2094,7 +2094,7 @@ async function listClientsAction(connector) {
2094
2094
  reason: "no-clients",
2095
2095
  recoverable: true,
2096
2096
  nextActions: [
2097
- "Make sure the target device/simulator and app are running, then retry.",
2097
+ "Make sure the target device/simulator and app are running, or run `agent-lynx wait-for-client` while launching.",
2098
2098
  "Retry with `--no-daemon` to run discovery in-process; HDT/Aiden still takes precedence over direct discovery."
2099
2099
  ]
2100
2100
  });
@@ -2578,20 +2578,70 @@ const SOURCE_PAGE_HOOK = "preact-page-hook";
2578
2578
  const SOURCE_DEVTOOLS_TO_CLIENT = "preact-devtools-to-client";
2579
2579
  const DEFAULT_REACTLYNX_IDLE_MS = 700;
2580
2580
  const DEFAULT_REACTLYNX_MAX_MS = 5000;
2581
- function buildReactLynxOutboundFrame(type, data) {
2581
+ const INITIAL_TREE_IDLE_MS = 2500;
2582
+ function buildVMEventFrame(source, type, data) {
2582
2583
  return {
2583
2584
  method: "Lynx.sendVMEvent",
2584
2585
  params: {
2585
2586
  vmType: "JSContext",
2586
2587
  event: PREACT_EVENT,
2587
2588
  data: JSON.stringify({
2588
- source: SOURCE_DEVTOOLS_TO_CLIENT,
2589
+ source,
2589
2590
  type,
2590
2591
  data: data ?? null
2591
2592
  })
2592
2593
  }
2593
2594
  };
2594
2595
  }
2596
+ function buildReactLynxOutboundFrame(type, data) {
2597
+ return buildVMEventFrame(SOURCE_DEVTOOLS_TO_CLIENT, type, data);
2598
+ }
2599
+ function buildReactLynxPageHookFrame(type, data) {
2600
+ return buildVMEventFrame(SOURCE_PAGE_HOOK, type, data);
2601
+ }
2602
+ const CONTEXT_CLEARED_METHODS = new Set([
2603
+ "Runtime.executionContextsCleared",
2604
+ "Runtime.executionContextDestroyed",
2605
+ "Target.targetDestroyed"
2606
+ ]);
2607
+ const CONTEXT_CREATED_METHODS = new Set([
2608
+ "Runtime.executionContextCreated",
2609
+ "Target.targetCreated"
2610
+ ]);
2611
+ function isMainTargetEvent(value) {
2612
+ const params = value.params;
2613
+ return (params?.targetId ?? params?.targetInfo?.targetId) === "Main";
2614
+ }
2615
+ function parseSessionStreamEvent(value, pendingAckIds) {
2616
+ if ("object" != typeof value || null === value) return null;
2617
+ const responseId = value.id;
2618
+ if ("number" == typeof responseId && pendingAckIds.delete(responseId)) return 0 === pendingAckIds.size ? {
2619
+ kind: "outbound-acked"
2620
+ } : null;
2621
+ const method = value.method;
2622
+ if ("string" != typeof method) return null;
2623
+ if (CONTEXT_CLEARED_METHODS.has(method)) return isMainTargetEvent(value) ? null : {
2624
+ kind: "context-cleared"
2625
+ };
2626
+ if (CONTEXT_CREATED_METHODS.has(method)) return isMainTargetEvent(value) ? null : {
2627
+ kind: "context-created"
2628
+ };
2629
+ if ("Lynx.onVMEvent" !== method) return null;
2630
+ const params = value.params ?? {};
2631
+ if (params.event !== PREACT_EVENT) return null;
2632
+ try {
2633
+ const parsed = JSON.parse(params.data ?? "null");
2634
+ if ("object" != typeof parsed || null === parsed) return null;
2635
+ const envelope = parsed;
2636
+ if (envelope.source !== SOURCE_PAGE_HOOK) return null;
2637
+ return {
2638
+ kind: "envelope",
2639
+ envelope
2640
+ };
2641
+ } catch {
2642
+ return null;
2643
+ }
2644
+ }
2595
2645
  async function raceRead(read, timeoutMs) {
2596
2646
  let timer;
2597
2647
  const timeout = new Promise((resolve)=>{
@@ -2656,6 +2706,7 @@ async function runReactLynxSession(options) {
2656
2706
  };
2657
2707
  try {
2658
2708
  const { connector, clientId, sessionId, outbound, sendInit = true, onEnvelope = ()=>"continue", afterSnapshot, awaitEnvelope = false, snapshotIdleMs = DEFAULT_REACTLYNX_IDLE_MS, idleMs = DEFAULT_REACTLYNX_IDLE_MS, maxMs = DEFAULT_REACTLYNX_MAX_MS, signal } = options;
2709
+ const initialTreeIdleMs = options.idleMs ?? INITIAL_TREE_IDLE_MS;
2659
2710
  let stopRequested = false;
2660
2711
  let cancelInput = ()=>{};
2661
2712
  let inputTerminated = false;
@@ -2666,10 +2717,19 @@ async function runReactLynxSession(options) {
2666
2717
  let sendInput = ()=>{
2667
2718
  throw new Error("ReactLynx input stream is not ready");
2668
2719
  };
2720
+ const pendingAckIds = new Set();
2721
+ const trackOutbound = (frame)=>{
2722
+ const id = frame.id ?? nextRequestId();
2723
+ pendingAckIds.add(id);
2724
+ return {
2725
+ ...frame,
2726
+ id
2727
+ };
2728
+ };
2669
2729
  const input = new ReadableStream({
2670
2730
  start (controller) {
2671
- if (sendInit) controller.enqueue(buildReactLynxOutboundFrame("init"));
2672
- for (const frame of outbound)controller.enqueue(frame);
2731
+ if (sendInit) controller.enqueue(trackOutbound(buildReactLynxOutboundFrame("init")));
2732
+ for (const frame of outbound)controller.enqueue(trackOutbound(frame));
2673
2733
  assertInputWritable = ()=>{
2674
2734
  if (!inputTerminated) return;
2675
2735
  if (void 0 !== inputTerminalReason) throw inputTerminalReason;
@@ -2677,9 +2737,11 @@ async function runReactLynxSession(options) {
2677
2737
  };
2678
2738
  sendInput = (frame)=>{
2679
2739
  assertInputWritable();
2740
+ const tracked = trackOutbound(frame);
2680
2741
  try {
2681
- controller.enqueue(frame);
2742
+ controller.enqueue(tracked);
2682
2743
  } catch (error) {
2744
+ pendingAckIds.delete(tracked.id);
2683
2745
  inputTerminated = true;
2684
2746
  inputTerminalReason = error;
2685
2747
  throw error;
@@ -2709,6 +2771,7 @@ async function runReactLynxSession(options) {
2709
2771
  let rootOrderFrames = 0;
2710
2772
  const envelopeTypes = new Set();
2711
2773
  let snapshotPending = void 0 !== afterSnapshot;
2774
+ let awaitingNewContext = false;
2712
2775
  const wantsTree = outbound.some((frame)=>{
2713
2776
  try {
2714
2777
  const parsed = JSON.parse(frame.params.data);
@@ -2717,12 +2780,23 @@ async function runReactLynxSession(options) {
2717
2780
  return false;
2718
2781
  }
2719
2782
  });
2783
+ const filteredStream = stream.pipeThrough(new TransformStream({
2784
+ transform (chunk, controller) {
2785
+ const event = parseSessionStreamEvent(chunk, pendingAckIds);
2786
+ if (null !== event) controller.enqueue(event);
2787
+ }
2788
+ }));
2720
2789
  try {
2721
- for await (const value of readUntilIdle(stream, {
2722
- idleMs: ()=>snapshotPending ? snapshotIdleMs : idleMs,
2790
+ for await (const event of readUntilIdle(filteredStream, {
2791
+ idleMs: ()=>{
2792
+ if (snapshotPending) return snapshotIdleMs;
2793
+ if (0 === framesSeen && wantsTree) return initialTreeIdleMs;
2794
+ return idleMs;
2795
+ },
2723
2796
  maxMs,
2724
2797
  onIdle: ()=>{
2725
- if (wantsTree && 0 === state.tree.size && (operationFrames > 0 || envelopeTypes.has("attach"))) return true;
2798
+ if (awaitingNewContext) return true;
2799
+ if (wantsTree && (operationFrames > 0 ? 0 === state.tree.size || 0 === rootOrderFrames : envelopeTypes.has("attach") || envelopeTypes.has("init") ? 0 === rootOrderFrames : !snapshotPending && 0 === framesSeen && pendingAckIds.size > 0)) return true;
2726
2800
  if (!snapshotPending || !afterSnapshot) return awaitEnvelope;
2727
2801
  snapshotPending = false;
2728
2802
  assertInputWritable();
@@ -2735,36 +2809,47 @@ async function runReactLynxSession(options) {
2735
2809
  return true;
2736
2810
  }
2737
2811
  })){
2738
- if ("object" != typeof value || null === value) continue;
2739
- if ("Lynx.onVMEvent" !== value.method) continue;
2740
- const params = value.params ?? {};
2741
- if (params.event !== PREACT_EVENT) continue;
2742
- let envelope;
2743
- try {
2744
- const parsed = JSON.parse(params.data ?? "null");
2745
- if ("object" != typeof parsed || null === parsed) continue;
2746
- envelope = parsed;
2747
- } catch {
2812
+ if ("outbound-acked" === event.kind) continue;
2813
+ if ("context-cleared" === event.kind) {
2814
+ debug("execution context cleared mid-session; discarding pre-reload state");
2815
+ state.tree.clear();
2816
+ state.roots.length = 0;
2817
+ framesSeen = 0;
2818
+ operationFrames = 0;
2819
+ rootOrderFrames = 0;
2820
+ envelopeTypes.clear();
2821
+ pendingAckIds.clear();
2822
+ awaitingNewContext = true;
2748
2823
  continue;
2749
2824
  }
2750
- if (envelope.source === SOURCE_PAGE_HOOK) {
2751
- framesSeen += 1;
2752
- envelopeTypes.add(envelope.type);
2753
- debug("frame %d: type=%s dataSize=%s", framesSeen, envelope.type, Array.isArray(envelope.data) ? envelope.data.length : typeof 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)) {
2758
- operationFrames += 1;
2759
- applyOperationV2(state, envelope.data);
2760
- } else if ("root-order" === envelope.type && Array.isArray(envelope.data)) {
2761
- rootOrderFrames += 1;
2762
- applyRootOrder(state, envelope.data);
2763
- }
2764
- if ("stop" === onEnvelope(envelope)) {
2765
- stopRequested = true;
2766
- break;
2825
+ if ("context-created" === event.kind) {
2826
+ const shouldReplay = awaitingNewContext || 0 === framesSeen;
2827
+ awaitingNewContext = false;
2828
+ if (shouldReplay && !inputTerminated) {
2829
+ debug("execution context created mid-session; re-sending outbound frames");
2830
+ if (sendInit) sendInput(buildReactLynxOutboundFrame("init"));
2831
+ for (const frame of outbound)sendInput(frame);
2767
2832
  }
2833
+ continue;
2834
+ }
2835
+ awaitingNewContext = false;
2836
+ const { envelope } = event;
2837
+ framesSeen += 1;
2838
+ envelopeTypes.add(envelope.type);
2839
+ debug("frame %d: type=%s dataSize=%s", framesSeen, envelope.type, Array.isArray(envelope.data) ? envelope.data.length : typeof envelope.data);
2840
+ if ("init" === envelope.type) {
2841
+ state.tree.clear();
2842
+ state.roots.length = 0;
2843
+ } else if ("operation_v2" === envelope.type && Array.isArray(envelope.data)) {
2844
+ operationFrames += 1;
2845
+ applyOperationV2(state, envelope.data);
2846
+ } else if ("root-order" === envelope.type && Array.isArray(envelope.data)) {
2847
+ rootOrderFrames += 1;
2848
+ applyRootOrder(state, envelope.data);
2849
+ }
2850
+ if ("stop" === onEnvelope(envelope)) {
2851
+ stopRequested = true;
2852
+ break;
2768
2853
  }
2769
2854
  }
2770
2855
  } finally{
@@ -2790,7 +2875,11 @@ async function runReactLynxSession(options) {
2790
2875
  }
2791
2876
  function reactLynxEmptyTreeDiagnostic(result) {
2792
2877
  if (0 === result.framesSeen) return "saw 0 frames -- the App is silent on the PreactDevtools channel. Most likely `@lynx-js/preact-devtools` is not installed, the bundle is a production build, or `setupReactLynx()` has not run yet. Look for `[PREACT DEVTOOLS] Devtools initialized successfully` in the device console.";
2793
- if (0 === result.operationFrames) return `saw ${result.framesSeen} frame(s) but no \`operation_v2\` -- \`@lynx-js/preact-devtools\` is loaded but does not honor \`refresh\`. Upgrade to a build with the \`document.body\` and \`preactDevtoolsCtx.Node\` fixes.`;
2878
+ if (0 === result.operationFrames) {
2879
+ if (result.rootOrderFrames > 0 && 0 === result.state.roots.length) return `saw ${result.framesSeen} frame(s) with an empty \`root-order\` and no \`operation_v2\` -- \`@lynx-js/preact-devtools\` responded, but no active ReactLynx roots are currently tracked (the JS runtime may have been restarted or no root is mounted).`;
2880
+ return `saw ${result.framesSeen} frame(s) but no \`operation_v2\` -- \`@lynx-js/preact-devtools\` is loaded but does not honor \`refresh\`. Upgrade to a build with the \`document.body\` and \`preactDevtoolsCtx.Node\` fixes.`;
2881
+ }
2882
+ if (result.state.tree.size > 0 && 0 === result.state.roots.length) return `saw ${result.framesSeen} frame(s) (${result.state.tree.size} node(s)) without \`root-order\` -- the component tree stream ended before the root list arrived.`;
2794
2883
  return `saw ${result.framesSeen} frame(s) including ${result.operationFrames} \`operation_v2\` but the resulting tree is empty (every node was unmounted).`;
2795
2884
  }
2796
2885
  class ReactLynxActionError extends Error {
@@ -2883,9 +2972,10 @@ class ReactLynxController {
2883
2972
  outbound: [
2884
2973
  buildReactLynxOutboundFrame("refresh")
2885
2974
  ],
2975
+ maxMs: 15000,
2886
2976
  signal
2887
2977
  });
2888
- if (0 === result.state.tree.size) throw new ReactLynxActionError(reactLynxEmptyTreeDiagnostic(result), {
2978
+ if (0 === result.state.tree.size || 0 === result.state.roots.length) throw new ReactLynxActionError(reactLynxEmptyTreeDiagnostic(result), {
2889
2979
  reason: "reactlynx-empty-tree",
2890
2980
  nextActions: [
2891
2981
  "Verify that this is a ReactLynx development build with @lynx-js/preact-devtools enabled.",
@@ -3054,7 +3144,7 @@ class ReactLynxController {
3054
3144
  componentForElement(connector, target, options, signal) {
3055
3145
  return this.#withSession(target, signal, async ()=>{
3056
3146
  let cached = await this.#cachedTarget(connector, target, options.refresh, signal);
3057
- const id = await this.#componentIdForUniqueId(connector, target, options.uniqueId, signal);
3147
+ const id = await this.#componentIdForUniqueIds(connector, target, options.uniqueIds, signal);
3058
3148
  if (!cached.entry.state.tree.has(id) && "reused" === cached.status) cached = {
3059
3149
  ...target,
3060
3150
  entry: await this.#capture(connector, target, signal),
@@ -3180,59 +3270,64 @@ class ReactLynxController {
3180
3270
  ]
3181
3271
  });
3182
3272
  }
3183
- async #componentIdForUniqueId(connector, target, uniqueId, signal) {
3184
- let id;
3185
- const result = await runReactLynxSession({
3186
- connector,
3187
- clientId: target.clientId,
3188
- sessionId: target.sessionId,
3189
- outbound: [
3190
- buildReactLynxOutboundFrame("element-picked", {
3191
- uniqueId
3192
- })
3193
- ],
3194
- awaitEnvelope: true,
3195
- idleMs: 1000,
3196
- maxMs: 5000,
3197
- signal,
3198
- onEnvelope: (envelope)=>{
3199
- if ("element-picked-vnode-id" !== envelope.type) return "continue";
3200
- const candidate = envelope.data?.id;
3201
- if ("number" != typeof candidate || !Number.isFinite(candidate)) return "continue";
3202
- id = candidate;
3203
- return "stop";
3204
- }
3205
- });
3206
- if (void 0 !== id) return id;
3207
- throw new ReactLynxActionError(`No ReactLynx component mapping was returned for DOM uniqueId ${uniqueId} after ${result.framesSeen} frame(s) (types=${controller_envelopeTypes(result)}). The element may not be React-owned, or the App-side identity mapping may not be ready.`, {
3273
+ async #runLookupSession(connector, target, outbound, extract, signal) {
3274
+ for(let attempt = 0;; attempt += 1){
3275
+ let value;
3276
+ const result = await runReactLynxSession({
3277
+ connector,
3278
+ clientId: target.clientId,
3279
+ sessionId: target.sessionId,
3280
+ outbound: [
3281
+ ...outbound,
3282
+ buildReactLynxPageHookFrame("root-order-page")
3283
+ ],
3284
+ awaitEnvelope: true,
3285
+ idleMs: 1000,
3286
+ maxMs: 5000,
3287
+ signal,
3288
+ onEnvelope: (envelope)=>{
3289
+ const matched = extract(envelope);
3290
+ if (void 0 !== matched) {
3291
+ value = matched;
3292
+ return "stop";
3293
+ }
3294
+ return "root-order" === envelope.type ? "stop" : "continue";
3295
+ }
3296
+ });
3297
+ if (void 0 !== value || attempt > 0 || !result.envelopeTypes.has("root-order")) return {
3298
+ value,
3299
+ result
3300
+ };
3301
+ await promises_setTimeout(75, void 0, {
3302
+ signal
3303
+ });
3304
+ }
3305
+ }
3306
+ async #componentIdForUniqueIds(connector, target, uniqueIds, signal) {
3307
+ const { value, result } = await this.#runLookupSession(connector, target, uniqueIds.map((uniqueId)=>buildReactLynxOutboundFrame("element-picked", {
3308
+ uniqueId
3309
+ })), (envelope)=>{
3310
+ if ("element-picked-vnode-id" !== envelope.type) return;
3311
+ const candidate = envelope.data?.id;
3312
+ return "number" == typeof candidate && Number.isFinite(candidate) ? candidate : void 0;
3313
+ }, signal);
3314
+ if (void 0 !== value) return value;
3315
+ throw new ReactLynxActionError(`No ReactLynx component mapping was returned for DOM uniqueId ${uniqueIds[0]} after ${result.framesSeen} frame(s) (types=${controller_envelopeTypes(result)}). The element may not be React-owned, or the App-side identity mapping may not be ready.`, {
3208
3316
  reason: "reactlynx-component-not-found",
3209
3317
  nextActions: [
3210
- "Retry after the page has settled, or run `agent-lynx reactlynx tree --refresh`."
3318
+ "Retry after the page has settled, or run `agent-lynx reactlynx tree`."
3211
3319
  ]
3212
3320
  });
3213
3321
  }
3214
3322
  async #uniqueIdForComponent(connector, target, id, signal) {
3215
- let uniqueId;
3216
- const result = await runReactLynxSession({
3217
- connector,
3218
- clientId: target.clientId,
3219
- sessionId: target.sessionId,
3220
- outbound: [
3221
- buildReactLynxOutboundFrame("highlight", id)
3222
- ],
3223
- awaitEnvelope: true,
3224
- idleMs: 1000,
3225
- maxMs: 5000,
3226
- signal,
3227
- onEnvelope: (envelope)=>{
3228
- if ("preact-devtools-highlight" !== envelope.type) return "continue";
3229
- const candidate = envelope.data?.uniqueId;
3230
- if ("number" != typeof candidate || !Number.isFinite(candidate)) return "continue";
3231
- uniqueId = candidate;
3232
- return "stop";
3233
- }
3234
- });
3235
- if (void 0 !== uniqueId) return uniqueId;
3323
+ const { value, result } = await this.#runLookupSession(connector, target, [
3324
+ buildReactLynxOutboundFrame("highlight", id)
3325
+ ], (envelope)=>{
3326
+ if ("preact-devtools-highlight" !== envelope.type) return;
3327
+ const candidate = envelope.data?.uniqueId;
3328
+ return "number" == typeof candidate && Number.isFinite(candidate) ? candidate : void 0;
3329
+ }, signal);
3330
+ if (void 0 !== value) return value;
3236
3331
  throw new ReactLynxActionError(`No host element mapping was returned for component id ${id} after ${result.framesSeen} frame(s) (types=${controller_envelopeTypes(result)}). The component may render null or a Fragment, or its host element may be offscreen in a virtual list.`, {
3237
3332
  reason: "reactlynx-element-not-found",
3238
3333
  nextActions: [
@@ -3581,7 +3676,7 @@ async function isPaintedRef(connector, clientId, sessionId, ref, signal) {
3581
3676
  signal?.throwIfAborted();
3582
3677
  let located;
3583
3678
  try {
3584
- located = await connector.sendCDPMessage(clientId, sessionId, "DOM.getNodeForLocation", point);
3679
+ located = await connector.sendCDPMessage(clientId, sessionId, "DOM.getNodeForLocation", point, false, signal);
3585
3680
  } catch {
3586
3681
  signal?.throwIfAborted();
3587
3682
  return;
@@ -3622,7 +3717,7 @@ async function enrichEditableValues(connector, clientId, sessionId, refs, signal
3622
3717
  const editableRefs = refs.filter((ref)=>ref.flags.visible && ref.flags.editable && !ref.attributes["type"]?.toLowerCase().includes("password"));
3623
3718
  if (0 === editableRefs.length) return;
3624
3719
  try {
3625
- await connector.sendCDPMessage(clientId, sessionId, "UITree.enable");
3720
+ await connector.sendCDPMessage(clientId, sessionId, "UITree.enable", void 0, false, signal);
3626
3721
  } catch {
3627
3722
  signal?.throwIfAborted();
3628
3723
  return;
@@ -3633,7 +3728,7 @@ async function enrichEditableValues(connector, clientId, sessionId, refs, signal
3633
3728
  try {
3634
3729
  info = await connector.sendCDPMessage(clientId, sessionId, "UITree.getUIInfoForNode", {
3635
3730
  UINodeId: ref.nodeId
3636
- });
3731
+ }, false, signal);
3637
3732
  } catch {
3638
3733
  signal?.throwIfAborted();
3639
3734
  continue;
@@ -3690,9 +3785,9 @@ async function buildSnapshotStructure(connector, clientId, sessionId, signal) {
3690
3785
  signal?.throwIfAborted();
3691
3786
  await connector.sendCDPMessage(clientId, sessionId, "DOM.enable", {
3692
3787
  useCompression: false
3693
- });
3788
+ }, false, signal);
3694
3789
  signal?.throwIfAborted();
3695
- const result = await connector.sendCDPMessage(clientId, sessionId, "DOM.getDocumentWithBoxModel");
3790
+ const result = await connector.sendCDPMessage(clientId, sessionId, "DOM.getDocumentWithBoxModel", void 0, false, signal);
3696
3791
  signal?.throwIfAborted();
3697
3792
  if ("string" == typeof result.root) throw new Error("DOM.getDocumentWithBoxModel returned a compressed tree. Retry after DOM.enable with useCompression:false.");
3698
3793
  const viewport = deriveViewport(result.root);
@@ -3875,7 +3970,7 @@ async function setValue(connector, clientId, sessionId, nodeId, value, signal, c
3875
3970
  });
3876
3971
  signal.throwIfAborted();
3877
3972
  }
3878
- const jpeg_js = __webpack_require__("../../../node_modules/.pnpm/jpeg-js@0.4.4/node_modules/jpeg-js/index.js");
3973
+ const jpeg_js = rspackRequire("../../../node_modules/.pnpm/jpeg-js@0.4.4/node_modules/jpeg-js/index.js");
3879
3974
  class ScreenshotAnnotationError extends Error {
3880
3975
  constructor(message, options){
3881
3976
  super(message, options);
@@ -4339,7 +4434,7 @@ function annotateScreenshot(options) {
4339
4434
  occupiedLabels.push(labelBox);
4340
4435
  }
4341
4436
  try {
4342
- const encoded = jpeg_js.encode(image, options.quality ?? 90);
4437
+ const encoded = jpeg_js.encode(image, options.quality ?? 80);
4343
4438
  return {
4344
4439
  jpeg: Buffer.from(encoded.data),
4345
4440
  width: image.width,
@@ -4407,7 +4502,7 @@ function screenshot_ts_dispose_resources(env) {
4407
4502
  }
4408
4503
  return next();
4409
4504
  }
4410
- function deferred() {
4505
+ function screenshot_deferred() {
4411
4506
  let resolve;
4412
4507
  const promise = new Promise((done)=>{
4413
4508
  resolve = done;
@@ -4460,8 +4555,8 @@ async function captureScreenshotFrame(connector, clientId, sessionId, options =
4460
4555
  timeoutController.abort(new ScreenshotTimeoutError(timeoutMs, timeoutPhase));
4461
4556
  }, timeoutMs);
4462
4557
  timeout.unref();
4463
- let frame = deferred();
4464
- let ack = deferred();
4558
+ let frame = screenshot_deferred();
4559
+ let ack = screenshot_deferred();
4465
4560
  const acknowledgements = new Map();
4466
4561
  let usableFrameReceived = false;
4467
4562
  let result;
@@ -4506,8 +4601,8 @@ async function captureScreenshotFrame(connector, clientId, sessionId, options =
4506
4601
  });
4507
4602
  ack.resolve(id);
4508
4603
  if (usable) break;
4509
- frame = deferred();
4510
- ack = deferred();
4604
+ frame = screenshot_deferred();
4605
+ ack = screenshot_deferred();
4511
4606
  }
4512
4607
  } finally{
4513
4608
  controller.close();
@@ -4715,7 +4810,7 @@ async function resolveTarget(action, params, connector, requirement) {
4715
4810
  if (!firstClient) return {
4716
4811
  ok: false,
4717
4812
  result: targetFailure(action, "No available clients found.", [
4718
- "Connect a Lynx client, then retry the command.",
4813
+ "Connect a Lynx client or run `agent-lynx wait-for-client` while launching.",
4719
4814
  "Run `agent-lynx list-clients` to verify discovery."
4720
4815
  ])
4721
4816
  };
@@ -5270,8 +5365,21 @@ class ActionCore {
5270
5365
  if ("element" === ref.kind) {
5271
5366
  const resolved = this.#resolveRef("reactlynx-link", clientId, sessionId, ref.ref);
5272
5367
  if ("ok" in resolved) return resolved;
5368
+ const refsByName = new Map(resolved.snapshot.refs.map((candidate)=>[
5369
+ candidate.ref,
5370
+ candidate
5371
+ ]));
5372
+ const uniqueIds = new Set();
5373
+ const visited = new Set();
5374
+ for(let current = resolved.ref; current && !visited.has(current.ref);){
5375
+ visited.add(current.ref);
5376
+ uniqueIds.add(current.backendNodeId ?? current.nodeId);
5377
+ current = current.parentRef ? refsByName.get(current.parentRef) : void 0;
5378
+ }
5273
5379
  const mapping = await this.#reactLynx.componentForElement(ctx.connector, target, {
5274
- uniqueId: resolved.ref.backendNodeId ?? resolved.ref.nodeId,
5380
+ uniqueIds: [
5381
+ ...uniqueIds
5382
+ ],
5275
5383
  showShells,
5276
5384
  refresh
5277
5385
  }, signal);
@@ -5426,7 +5534,7 @@ class ActionCore {
5426
5534
  try {
5427
5535
  const capturedFrame = await captureScreenshotFrame(ctx.connector, clientId, sessionId, {
5428
5536
  fullscreen,
5429
- quality: annotate ? 100 : 80,
5537
+ quality: 80,
5430
5538
  signal
5431
5539
  });
5432
5540
  const jpegBase64 = capturedFrame.data;
@@ -5856,4 +5964,4 @@ function decodeCommandQuery(params) {
5856
5964
  }
5857
5965
  return result;
5858
5966
  }
5859
- export { ActionCore, DevNodeType, NO_CLIENTS_FOUND_MESSAGE, ScreenshotAnnotationError, ScreenshotTimeoutError, annotateScreenshot, appendCommandQueryParam, applyOperationV2, applyRootOrder, buildReactLynxOutboundFrame, buildReactLynxUpdatePath, buildRefs, buildRegexMatcher, buildSnapshot, buildSubstringMatcher, captureScreenshot, captureScreenshotFrame, centerOfQuad, createRendererState, decodeCommandQuery, deserializeRendererState, fetchDebugMetadata, findReactLynxComponents, formatReactLynxTree, getOriginalNodeSourceInfo, listClientsAction, listSessionsAction, normalizeRef, ok, openAction, parseReactLynxComponentRef, parseReactLynxLinkRef, reactLynxEmptyTreeDiagnostic, remapOriginalNodeSourceInfo, result_fail as fail, runReactLynxSession, serializeRendererState, touchTap, typeTag, validateRef, waitForClientStream };
5967
+ export { ActionCore, DevNodeType, NO_CLIENTS_FOUND_MESSAGE, ScreenshotAnnotationError, ScreenshotTimeoutError, annotateScreenshot, appendCommandQueryParam, applyOperationV2, applyRootOrder, buildReactLynxOutboundFrame, buildReactLynxPageHookFrame, buildReactLynxUpdatePath, buildRefs, buildRegexMatcher, buildSnapshot, buildSubstringMatcher, captureScreenshot, captureScreenshotFrame, centerOfQuad, createRendererState, decodeCommandQuery, deserializeRendererState, fetchDebugMetadata, findReactLynxComponents, formatReactLynxTree, getOriginalNodeSourceInfo, listClientsAction, listSessionsAction, normalizeRef, ok, openAction, parseReactLynxComponentRef, parseReactLynxLinkRef, reactLynxEmptyTreeDiagnostic, remapOriginalNodeSourceInfo, result_fail as fail, runReactLynxSession, serializeRendererState, touchTap, typeTag, validateRef, waitForClientStream };