Skip to content

Automate browser based workflows with AI

33.6 KB
Raw Blame
// @vitest-environment jsdom

import { afterEach, describe, expect, test, vi } from "vitest";

import type { AppNode } from "../editor/nodes";
import {
  makeCollapseKey,
  useNodeCollapseStore,
} from "../editor/collapse/useNodeCollapseStore";
import { START_ANCHOR_TOP_PX } from "../editor/paneFit";
import {
  BLOCK_JUMP_DURATION_MS,
  BRANCH_SETTLE_STABLE_FRAMES,
  BRANCH_SETTLE_TIMEOUT_MS,
  beginFocusGeneration,
  blockJumpDuration,
  collectBlockSearchTargets,
  filterBlockSearchTargets,
  focusBlockTarget,
  invalidateFocusGeneration,
  resolveConditionalBranchPath,
  resolveContainerAncestorLabels,
  waitForNodeSettle,
  type FocusBlockDeps,
} from "./blockSearch";

const startNode = {
  id: "start-node",
  type: "start",
  position: { x: 0, y: 0 },
  data: { label: "__start_block__" },
} as AppNode;

const adderNode = {
  id: "adder-node",
  type: "nodeAdder",
  position: { x: 0, y: 900 },
  data: {},
} as AppNode;

const loginNode = {
  id: "login-node",
  type: "task",
  position: { x: 0, y: 100 },
  measured: { width: 400, height: 200 },
  data: { label: "Login" },
} as AppNode;

const loopNode = {
  id: "loop-node",
  type: "loop",
  position: { x: 0, y: 400 },
  data: { label: "Iterate rows", loopKind: "while" },
} as AppNode;

// Nested inside the loop container: `position` is parent-relative.
const nestedNode = {
  id: "nested-node",
  type: "extraction",
  parentId: "loop-node",
  position: { x: 40, y: 80 },
  data: { label: "Extract row data" },
} as AppNode;

const unlabeledNode = {
  id: "unlabeled-node",
  type: "task",
  position: { x: 0, y: 700 },
  data: { label: "   " },
} as AppNode;

const nodes = [
  startNode,
  loginNode,
  loopNode,
  nestedNode,
  unlabeledNode,
  adderNode,
];

// A conditional flow: branch A active, branch B hidden. Branch B holds a task
// plus a loop with a cascaded (affinity-less) child, and a nested conditional
// whose branch Y holds the deepest target.
function makeConditionalNodes(): Array<AppNode> {
  return [
    startNode,
    {
      id: "cond-node",
      type: "conditional",
      position: { x: 0, y: 100 },
      data: { label: "Route by type", activeBranchId: "branch-a" },
    } as AppNode,
    {
      id: "branch-a-block",
      type: "task",
      parentId: "cond-node",
      position: { x: 20, y: 120 },
      data: {
        label: "Handle type A",
        conditionalNodeId: "cond-node",
        conditionalBranchId: "branch-a",
      },
    } as AppNode,
    {
      id: "branch-b-block",
      type: "task",
      parentId: "cond-node",
      position: { x: 20, y: 120 },
      hidden: true,
      data: {
        label: "Handle type B",
        conditionalNodeId: "cond-node",
        conditionalBranchId: "branch-b",
      },
    } as AppNode,
    {
      id: "branch-b-loop",
      type: "loop",
      parentId: "cond-node",
      position: { x: 20, y: 360 },
      hidden: true,
      data: {
        label: "Iterate type B rows",
        conditionalNodeId: "cond-node",
        conditionalBranchId: "branch-b",
      },
    } as AppNode,
    {
      id: "branch-b-loop-child",
      type: "extraction",
      parentId: "branch-b-loop",
      position: { x: 30, y: 60 },
      hidden: true,
      data: { label: "Extract type B row" },
    } as AppNode,
    {
      id: "inner-cond-node",
      type: "conditional",
      parentId: "cond-node",
      position: { x: 20, y: 600 },
      hidden: true,
      data: {
        label: "Route type B result",
        activeBranchId: "branch-x",
        conditionalNodeId: "cond-node",
        conditionalBranchId: "branch-b",
      },
    } as AppNode,
    {
      id: "inner-branch-y-block",
      type: "sendEmail",
      parentId: "inner-cond-node",
      position: { x: 10, y: 80 },
      hidden: true,
      data: {
        label: "Email type B result",
        conditionalNodeId: "inner-cond-node",
        conditionalBranchId: "branch-y",
      },
    } as AppNode,
  ];
}

describe("collectBlockSearchTargets", () => {
  test("keeps workflow blocks (including nested ones) in canvas order and maps block types", () => {
    expect(collectBlockSearchTargets(nodes)).toEqual([
      { nodeId: "login-node", label: "Login", blockType: "task" },
      { nodeId: "loop-node", label: "Iterate rows", blockType: "while_loop" },
      {
        nodeId: "nested-node",
        label: "Extract row data",
        blockType: "extraction",
      },
    ]);
  });

  test("skips utility nodes and blank labels", () => {
    const targets = collectBlockSearchTargets(nodes);
    const ids = targets.map((target) => target.nodeId);
    expect(ids).not.toContain("start-node");
    expect(ids).not.toContain("adder-node");
    expect(ids).not.toContain("unlabeled-node");
  });

  test("includes blocks hidden inside inactive conditional branches", () => {
    const ids = collectBlockSearchTargets(makeConditionalNodes()).map(
      (target) => target.nodeId,
    );
    expect(ids).toContain("branch-b-block");
    expect(ids).toContain("branch-b-loop-child");
    expect(ids).toContain("inner-branch-y-block");
  });
});

describe("filterBlockSearchTargets", () => {
  const targets = collectBlockSearchTargets(nodes);

  test("returns every target for an empty or whitespace query", () => {
    expect(filterBlockSearchTargets(targets, "")).toEqual(targets);
    expect(filterBlockSearchTargets(targets, "   ")).toEqual(targets);
  });

  test("matches case-insensitive substrings", () => {
    expect(
      filterBlockSearchTargets(targets, "ROW").map((t) => t.nodeId),
    ).toEqual(["loop-node", "nested-node"]);
    expect(
      filterBlockSearchTargets(targets, "login").map((t) => t.nodeId),
    ).toEqual(["login-node"]);
  });

  test("trims the query before matching", () => {
    expect(
      filterBlockSearchTargets(targets, "  login  ").map((t) => t.nodeId),
    ).toEqual(["login-node"]);
  });

  test("returns nothing when no label matches", () => {
    expect(filterBlockSearchTargets(targets, "does-not-exist")).toEqual([]);
  });
});

describe("blockJumpDuration", () => {
  afterEach(() => {
    vi.unstubAllGlobals();
  });

  test("is instant when matchMedia is unavailable (jsdom default)", () => {
    expect(blockJumpDuration()).toBe(0);
  });

  test("is instant under prefers-reduced-motion", () => {
    vi.stubGlobal("matchMedia", () => ({ matches: true }));
    expect(blockJumpDuration()).toBe(0);
  });

  test("animates otherwise", () => {
    vi.stubGlobal("matchMedia", () => ({ matches: false }));
    expect(blockJumpDuration()).toBe(BLOCK_JUMP_DURATION_MS);
  });
});

describe("resolveConditionalBranchPath", () => {
  test("is empty for targets outside conditionals or in the active branch", () => {
    expect(resolveConditionalBranchPath(nodes, "nested-node")).toEqual([]);
    expect(
      resolveConditionalBranchPath(makeConditionalNodes(), "branch-a-block"),
    ).toEqual([]);
  });

  test("resolves a direct child of an inactive branch", () => {
    expect(
      resolveConditionalBranchPath(makeConditionalNodes(), "branch-b-block"),
    ).toEqual([
      {
        conditionalId: "cond-node",
        conditionalLabel: "Route by type",
        branchId: "branch-b",
      },
    ]);
  });

  test("reaches the branch chain through parentId nesting (block in a loop)", () => {
    expect(
      resolveConditionalBranchPath(
        makeConditionalNodes(),
        "branch-b-loop-child",
      ),
    ).toEqual([
      {
        conditionalId: "cond-node",
        conditionalLabel: "Route by type",
        branchId: "branch-b",
      },
    ]);
  });

  test("orders nested conditional switches root→leaf", () => {
    expect(
      resolveConditionalBranchPath(
        makeConditionalNodes(),
        "inner-branch-y-block",
      ),
    ).toEqual([
      {
        conditionalId: "cond-node",
        conditionalLabel: "Route by type",
        branchId: "branch-b",
      },
      {
        conditionalId: "inner-cond-node",
        conditionalLabel: "Route type B result",
        branchId: "branch-y",
      },
    ]);
  });

  test("skips levels whose branch is already active", () => {
    const alreadySwitched = makeConditionalNodes().map((node) =>
      node.id === "cond-node"
        ? ({
            ...node,
            data: { ...node.data, activeBranchId: "branch-b" },
          } as AppNode)
        : node,
    );
    expect(
      resolveConditionalBranchPath(alreadySwitched, "inner-branch-y-block"),
    ).toEqual([
      {
        conditionalId: "inner-cond-node",
        conditionalLabel: "Route type B result",
        branchId: "branch-y",
      },
    ]);
  });

  test("stops at a dangling conditional reference", () => {
    const orphan = {
      id: "orphan-node",
      type: "task",
      position: { x: 0, y: 0 },
      data: {
        label: "Orphan",
        conditionalNodeId: "gone-node",
        conditionalBranchId: "branch-z",
      },
    } as AppNode;
    expect(resolveConditionalBranchPath([orphan], "orphan-node")).toEqual([]);
  });
});

describe("waitForNodeSettle", () => {
  function makeFrameQueue() {
    const queue: Array<() => void> = [];
    return {
      requestFrame: (callback: () => void) => {
        queue.push(callback);
      },
      async tick() {
        queue.splice(0).forEach((callback) => callback());
        await Promise.resolve();
      },
    };
  }

  test("resolves once the node is visible and its position holds still", async () => {
    const frames = makeFrameQueue();
    const node = {
      id: "n",
      type: "task",
      hidden: true,
      position: { x: 0, y: 0 },
      data: { label: "N" },
    } as AppNode;
    let resolved = false;
    void waitForNodeSettle("n", {
      getNodes: () => [node],
      getInternalNode: () => undefined,
      requestFrame: frames.requestFrame,
      now: () => 0,
    }).then(() => {
      resolved = true;
    });

    await frames.tick(); // hidden
    (node as { hidden?: boolean }).hidden = false;
    node.position = { x: 10, y: 10 };
    await frames.tick(); // visible, but the position just moved
    for (let i = 0; i < BRANCH_SETTLE_STABLE_FRAMES; i++) {
      expect(resolved).toBe(false);
      await frames.tick(); // stable frames accumulate
    }
    expect(resolved).toBe(true);
  });

  test("times out instead of hanging when the node never becomes visible", async () => {
    const frames = makeFrameQueue();
    let clock = 0;
    let resolved = false;
    void waitForNodeSettle("missing", {
      getNodes: () => [],
      getInternalNode: () => undefined,
      requestFrame: frames.requestFrame,
      now: () => {
        clock += BRANCH_SETTLE_TIMEOUT_MS / 2;
        return clock;
      },
    }).then(() => {
      resolved = true;
    });

    await frames.tick();
    await frames.tick();
    expect(resolved).toBe(true);
  });

  test("does not settle while a relayout is pending, even if position already looks stable", async () => {
    // Reproduces the race behind SKY-12050: a batched ancestor expand fires
    // an async debounced Dagre relayout (10ms handler delay + use-debounce
    // wait/maxWait) that hasn't landed yet when this starts polling. Position
    // looks unchanged in that dead window, so stability alone would resolve
    // on stale geometry.
    const frames = makeFrameQueue();
    const node = {
      id: "n",
      type: "task",
      hidden: false,
      position: { x: 10, y: 10 },
      data: { label: "N" },
    } as AppNode;
    let pending = true;
    let resolved = false;
    void waitForNodeSettle("n", {
      getNodes: () => [node],
      getInternalNode: () => undefined,
      requestFrame: frames.requestFrame,
      now: () => 0,
      isRelayoutPending: () => pending,
    }).then(() => {
      resolved = true;
    });

    for (let i = 0; i < BRANCH_SETTLE_STABLE_FRAMES + 2; i++) {
      await frames.tick();
      expect(resolved).toBe(false);
    }

    pending = false;
    for (let i = 0; i < BRANCH_SETTLE_STABLE_FRAMES; i++) {
      expect(resolved).toBe(false);
      await frames.tick();
    }
    expect(resolved).toBe(true);
  });

  test("resets the stable-frame counter when a relayout arms mid-streak", async () => {
    // The race this guards against isn't "pending from the start" (covered
    // above) but the relayout arming *after* polling has already begun
    // accumulating stable frames on pre-relayout geometry — the
    // header-resized -> 10ms handler delay -> debounce hop described in
    // FlowRenderer. Pins that the counter resets on that transition rather
    // than resuming from its pre-relayout value once the relayout clears.
    const frames = makeFrameQueue();
    const node = {
      id: "n",
      type: "task",
      hidden: false,
      position: { x: 10, y: 10 },
      data: { label: "N" },
    } as AppNode;
    let pending = false;
    let resolved = false;
    void waitForNodeSettle("n", {
      getNodes: () => [node],
      getInternalNode: () => undefined,
      requestFrame: frames.requestFrame,
      now: () => 0,
      isRelayoutPending: () => pending,
    }).then(() => {
      resolved = true;
    });

    for (let i = 0; i < BRANCH_SETTLE_STABLE_FRAMES - 1; i++) {
      await frames.tick();
      expect(resolved).toBe(false);
    }

    pending = true;
    for (let i = 0; i < BRANCH_SETTLE_STABLE_FRAMES; i++) {
      await frames.tick();
      expect(resolved).toBe(false);
    }

    pending = false;
    for (let i = 0; i < BRANCH_SETTLE_STABLE_FRAMES; i++) {
      expect(resolved).toBe(false);
      await frames.tick();
    }
    expect(resolved).toBe(true);
  });
});

describe("focusBlockTarget", () => {
  function makeDeps(
    depsNodes: Array<AppNode> = nodes,
    overrides?: Partial<FocusBlockDeps>,
  ): FocusBlockDeps {
    return {
      getNodes: () => depsNodes,
      getInternalNode: () => undefined,
      getPaneWidth: () => 1000,
      viewportZoom: 0.75,
      duration: 300,
      setViewport: vi.fn(),
      selectBlock: vi.fn(),
      expandBlock: vi.fn(),
      switchBranch: vi.fn(),
      waitForSettle: vi.fn().mockResolvedValue(undefined),
      ...overrides,
    };
  }

  test("selects the block (feeding the selected-block URL sync) and expands it", async () => {
    const deps = makeDeps();
    await expect(focusBlockTarget("login-node", deps)).resolves.toBe(true);
    expect(deps.selectBlock).toHaveBeenCalledWith("login-node");
    expect(deps.expandBlock).toHaveBeenCalledWith("Login");
  });

  test("does not arm the relayout gate while opening an ordinary target", async () => {
    const beforeExpand = vi.fn();
    const deps = makeDeps(nodes, { beforeExpand });

    await expect(focusBlockTarget("login-node", deps)).resolves.toBe(true);

    expect(beforeExpand).not.toHaveBeenCalled();
  });

  test("visible targets never switch branches or wait", async () => {
    const deps = makeDeps();
    await focusBlockTarget("login-node", deps);
    expect(deps.switchBranch).not.toHaveBeenCalled();
    expect(deps.waitForSettle).not.toHaveBeenCalled();
    expect(deps.selectBlock).toHaveBeenCalledTimes(1);
    expect(deps.setViewport).toHaveBeenCalledTimes(1);
  });

  test("top-anchors the block at its absolute position, horizontally centered, at the current zoom", async () => {
    const deps = makeDeps(nodes, {
      getInternalNode: (nodeId) =>
        nodeId === "nested-node"
          ? {
              internals: { positionAbsolute: { x: 140, y: 480 } },
              measured: { width: 300, height: 120 },
            }
          : undefined,
    });
    await focusBlockTarget("nested-node", deps);
    expect(deps.setViewport).toHaveBeenCalledWith(
      {
        x: 1000 / 2 - (140 + 150) * 0.75,
        y: START_ANCHOR_TOP_PX - 480 * 0.75,
        zoom: 0.75,
      },
      { duration: 300 },
    );
  });

  test("falls back to the node's own position and measurements", async () => {
    const deps = makeDeps();
    await focusBlockTarget("login-node", deps);
    expect(deps.setViewport).toHaveBeenCalledWith(
      {
        x: 1000 / 2 - (0 + 200) * 0.75,
        y: START_ANCHOR_TOP_PX - 100 * 0.75,
        zoom: 0.75,
      },
      { duration: 300 },
    );
  });

  describe("centered framing", () => {
    // loginNode sits at y=100 and is 200 tall, so its center is at flow y=200.
    function centeredDeps(overrides?: Partial<FocusBlockDeps>) {
      return makeDeps(nodes, {
        framing: "centered",
        getPaneHeight: () => 800,
        getPaneTopInset: () => 112,
        ...overrides,
      });
    }

    test("centers the block in the band below the floating header and zooms in", async () => {
      const deps = centeredDeps();
      await focusBlockTarget("login-node", deps);
      expect(deps.setViewport).toHaveBeenCalledWith(
        { x: 500 - 200, y: 112 + (800 - 112) / 2 - 200, zoom: 1 },
        { duration: 300 },
      );
    });

    test("the landed block clears the header instead of hiding under it", async () => {
      const deps = centeredDeps();
      await focusBlockTarget("login-node", deps);
      const [viewport] = vi.mocked(deps.setViewport).mock.calls[0]!;
      // Screen-space top edge of the block after the pan.
      const screenTop = 100 * viewport.zoom + viewport.y;
      expect(screenTop).toBeGreaterThan(112);
    });

    test("only ever zooms in, so an already-close view is not yanked back", async () => {
      const deps = centeredDeps({ viewportZoom: 1.5 });
      await focusBlockTarget("login-node", deps);
      expect(deps.setViewport).toHaveBeenCalledWith(
        { x: 500 - 300, y: 112 + (800 - 112) / 2 - 300, zoom: 1.5 },
        { duration: 300 },
      );
    });

    test("reads the inset at landing time, so a collapsed header reclaims the band", async () => {
      const deps = centeredDeps({ getPaneTopInset: () => 0 });
      await focusBlockTarget("login-node", deps);
      expect(deps.setViewport).toHaveBeenCalledWith(
        { x: 500 - 200, y: 400 - 200, zoom: 1 },
        { duration: 300 },
      );
    });

    test("measures the block after its expansion settles, not while collapsed", async () => {
      // 76 collapsed -> 400 expanded, the shape "Collapse all blocks" produces.
      let height = 76;
      const deps = centeredDeps({
        getInternalNode: () => ({
          internals: { positionAbsolute: { x: 0, y: 100 } },
          measured: { width: 400, height },
        }),
        waitForSettle: vi.fn().mockImplementation(async () => {
          height = 400;
        }),
      });
      await focusBlockTarget("login-node", deps);
      expect(deps.waitForSettle).toHaveBeenCalledWith("login-node");
      const calls = vi.mocked(deps.setViewport).mock.calls;
      const [viewport] = calls[calls.length - 1]!;
      // Centered on the EXPANDED box: 456 - (100 + 400/2) = 156.
      expect(viewport.y).toBe(156);
      const screenCenter = (100 + 400 / 2) * viewport.zoom + viewport.y;
      expect(screenCenter).toBe(112 + (800 - 112) / 2);
    });

    test("top-anchored framing skips the settle wait", async () => {
      const deps = makeDeps(nodes, { getPaneHeight: () => 800 });
      await focusBlockTarget("login-node", deps);
      expect(deps.waitForSettle).not.toHaveBeenCalled();
    });

    test("falls back to the top anchor when the pane height is unknown", async () => {
      const deps = centeredDeps({ getPaneHeight: () => 0 });
      await focusBlockTarget("login-node", deps);
      expect(deps.setViewport).toHaveBeenCalledWith(
        {
          x: 1000 / 2 - (0 + 200) * 0.75,
          y: START_ANCHOR_TOP_PX - 100 * 0.75,
          zoom: 0.75,
        },
        { duration: 300 },
      );
    });

    test("leaves the default (studio search) framing top-anchored", async () => {
      const deps = makeDeps(nodes, {
        getPaneHeight: () => 800,
        getPaneTopInset: () => 112,
      });
      await focusBlockTarget("login-node", deps);
      expect(deps.setViewport).toHaveBeenCalledWith(
        {
          x: 1000 / 2 - (0 + 200) * 0.75,
          y: START_ANCHOR_TOP_PX - 100 * 0.75,
          zoom: 0.75,
        },
        { duration: 300 },
      );
    });
  });

  test("refuses unknown ids and utility nodes without side effects", async () => {
    const deps = makeDeps();
    await expect(focusBlockTarget("missing-node", deps)).resolves.toBe(false);
    await expect(focusBlockTarget("start-node", deps)).resolves.toBe(false);
    expect(deps.selectBlock).not.toHaveBeenCalled();
    expect(deps.setViewport).not.toHaveBeenCalled();
    expect(deps.switchBranch).not.toHaveBeenCalled();
  });

  test("hidden-branch target: focuses the conditional, switches the branch, settles, then centers the target on fresh geometry", async () => {
    const conditionalNodes = makeConditionalNodes();
    const calls: Array<string> = [];
    const deps = makeDeps(conditionalNodes, {
      getInternalNode: (nodeId) =>
        nodeId === "cond-node"
          ? {
              internals: { positionAbsolute: { x: 0, y: 100 } },
              measured: { width: 480, height: 300 },
            }
          : undefined,
      selectBlock: vi.fn((id) => calls.push(`select:${id}`)),
      expandBlock: vi.fn((label) => calls.push(`expand:${label}`)),
      setViewport: vi.fn((viewport) =>
        calls.push(`anchor:${viewport.x},${viewport.y}`),
      ),
      switchBranch: vi.fn((conditionalId, branchId) =>
        calls.push(`switch:${conditionalId}:${branchId}`),
      ),
      waitForSettle: vi.fn(async () => {
        calls.push("settle");
        // Simulate the visibility cascade + re-layout moving the target.
        const target = conditionalNodes.find(
          (node) => node.id === "branch-b-block",
        )!;
        (target as { hidden?: boolean }).hidden = false;
        target.position = { x: 500, y: 700 };
        (target as { measured?: { width: number; height: number } }).measured =
          { width: 400, height: 100 };
      }),
    });

    await expect(focusBlockTarget("branch-b-block", deps)).resolves.toBe(true);
    // Conditional: internal (0,100) 480 wide -> x=500-240*0.75, y=24-100*0.75.
    // Target post-settle (500,700) 400 wide -> x=500-700*0.75, y=24-700*0.75.
    expect(calls).toEqual([
      "select:cond-node",
      "expand:Route by type",
      `anchor:320,${START_ANCHOR_TOP_PX - 75}`,
      "switch:cond-node:branch-b",
      "settle",
      "select:branch-b-block",
      "expand:Handle type B",
      // Post-settle geometry, not the stale pre-switch position.
      `anchor:-25,${START_ANCHOR_TOP_PX - 525}`,
    ]);
  });

  test("nested conditionals switch every level root→leaf with a settle between", async () => {
    const conditionalNodes = makeConditionalNodes();
    const calls: Array<string> = [];
    const deps = makeDeps(conditionalNodes, {
      selectBlock: vi.fn((id) => calls.push(`select:${id}`)),
      switchBranch: vi.fn((conditionalId, branchId) =>
        calls.push(`switch:${conditionalId}:${branchId}`),
      ),
      waitForSettle: vi.fn(async () => {
        calls.push("settle");
        // Simulate the visibility cascade: after each settle, the target
        // becomes visible so the collapsed-ancestor expansion path is not
        // triggered.
        const target = conditionalNodes.find(
          (node) => node.id === "inner-branch-y-block",
        )!;
        (target as { hidden?: boolean }).hidden = false;
      }),
    });

    await expect(focusBlockTarget("inner-branch-y-block", deps)).resolves.toBe(
      true,
    );
    expect(
      calls.filter(
        (entry) => entry.startsWith("switch:") || entry === "settle",
      ),
    ).toEqual([
      "switch:cond-node:branch-b",
      "settle",
      "switch:inner-cond-node:branch-y",
      "settle",
    ]);
    expect(calls[calls.length - 1]).toBe("select:inner-branch-y-block");
  });
});

describe("resolveContainerAncestorLabels", () => {
  test("returns empty for a top-level target with no parentId", () => {
    expect(resolveContainerAncestorLabels(nodes, "login-node")).toEqual([]);
  });

  test("returns empty for a target that is itself a container (parentId traversal starts from parent)", () => {
    expect(resolveContainerAncestorLabels(nodes, "loop-node")).toEqual([]);
  });

  test("returns the direct loop ancestor label for a node nested in a loop", () => {
    expect(resolveContainerAncestorLabels(nodes, "nested-node")).toEqual([
      "Iterate rows",
    ]);
  });

  test("returns the direct conditional ancestor label for a node nested in a conditional", () => {
    const conditionalNodes = makeConditionalNodes();
    expect(
      resolveContainerAncestorLabels(conditionalNodes, "branch-b-block"),
    ).toEqual(["Route by type"]);
  });

  test("returns ancestor labels root→leaf when a loop is nested inside a conditional", () => {
    const conditionalNodes = makeConditionalNodes();
    expect(
      resolveContainerAncestorLabels(conditionalNodes, "branch-b-loop-child"),
    ).toEqual(["Route by type", "Iterate type B rows"]);
  });

  test("stops gracefully for a dangling parentId", () => {
    const orphan = {
      id: "orphan-node",
      type: "task",
      parentId: "gone-container",
      position: { x: 0, y: 0 },
      data: { label: "Orphan" },
    } as AppNode;
    expect(resolveContainerAncestorLabels([orphan], "orphan-node")).toEqual([]);
  });
});

describe("focusBlockTarget — collapsed container ancestors", () => {
  function makeDeps(
    depsNodes: Array<AppNode> = nodes,
    overrides?: Partial<FocusBlockDeps>,
  ): FocusBlockDeps {
    return {
      getNodes: () => depsNodes,
      getInternalNode: () => undefined,
      getPaneWidth: () => 1000,
      viewportZoom: 0.75,
      duration: 300,
      setViewport: vi.fn(),
      selectBlock: vi.fn(),
      expandBlock: vi.fn(),
      switchBranch: vi.fn(),
      waitForSettle: vi.fn().mockResolvedValue(undefined),
      ...overrides,
    };
  }

  test("top-level target: no ancestor expand, no extra settle (sequence identical to pre-fix)", async () => {
    const deps = makeDeps();
    await expect(focusBlockTarget("login-node", deps)).resolves.toBe(true);
    expect(deps.waitForSettle).not.toHaveBeenCalled();
    expect(deps.expandBlock).toHaveBeenCalledTimes(1);
    expect(deps.expandBlock).toHaveBeenCalledWith("Login");
  });

  test("visible nested target (not hidden): no ancestor expand, no extra settle", async () => {
    // nestedNode has parentId=loop-node but is not hidden — already visible.
    const deps = makeDeps();
    await expect(focusBlockTarget("nested-node", deps)).resolves.toBe(true);
    expect(deps.waitForSettle).not.toHaveBeenCalled();
    expect(deps.expandBlock).toHaveBeenCalledTimes(1);
    expect(deps.expandBlock).toHaveBeenCalledWith("Extract row data");
  });

  test("target inside collapsed loop: expands the loop ancestor and re-settles before anchoring", async () => {
    const collapsedNestedNodes = nodes.map((node) =>
      node.id === "nested-node" ? { ...node, hidden: true } : node,
    );
    const calls: Array<string> = [];
    const deps = makeDeps(collapsedNestedNodes, {
      getNodes: () => collapsedNestedNodes,
      expandBlock: vi.fn((label) => calls.push(`expand:${label}`)),
      waitForSettle: vi.fn(async () => {
        calls.push("settle");
        // Simulate expand revealing the node.
        (
          collapsedNestedNodes.find((n) => n.id === "nested-node") as {
            hidden?: boolean;
          }
        ).hidden = false;
      }),
      selectBlock: vi.fn((id) => calls.push(`select:${id}`)),
      setViewport: vi.fn(() => calls.push("anchor")),
    });

    await expect(focusBlockTarget("nested-node", deps)).resolves.toBe(true);
    // The ancestor "Iterate rows" must be expanded, then settle, then target-expand and anchor.
    expect(calls).toContain("expand:Iterate rows");
    expect(calls).toContain("settle");
    expect(calls.indexOf("expand:Iterate rows")).toBeLessThan(
      calls.indexOf("settle"),
    );
    expect(calls.indexOf("settle")).toBeLessThan(
      calls.indexOf("expand:Extract row data"),
    );
    expect(calls.indexOf("expand:Extract row data")).toBeLessThan(
      calls.indexOf("anchor"),
    );
  });

  test("arms the relayout gate before expanding a collapsed ancestor", async () => {
    const collapsedNestedNodes = nodes.map((node) =>
      node.id === "nested-node" ? { ...node, hidden: true } : node,
    );
    const calls: Array<string> = [];
    const deps = makeDeps(collapsedNestedNodes, {
      beforeExpand: vi.fn((label) => calls.push(`arm:${label}`)),
      expandBlock: vi.fn((label) => calls.push(`expand:${label}`)),
      waitForSettle: vi.fn(async () => {
        calls.push("settle");
        (
          collapsedNestedNodes.find((node) => node.id === "nested-node") as {
            hidden?: boolean;
          }
        ).hidden = false;
      }),
    });

    await focusBlockTarget("nested-node", deps);

    expect(calls).toContain("arm:Iterate rows");
    expect(calls.indexOf("arm:Iterate rows")).toBeLessThan(
      calls.indexOf("expand:Iterate rows"),
    );
  });

  test("loop-inside-conditional (active branch, but loop collapsed): both ancestors expanded root→leaf", async () => {
    // Build a node set where the conditional branch is already active (no
    // branch switch needed) but the loop inside is collapsed, keeping the
    // nested target hidden.
    const innerLoop = {
      id: "inner-loop",
      type: "loop",
      parentId: "cond-node-b",
      position: { x: 20, y: 200 },
      data: { label: "Rows loop" },
    } as AppNode;
    const innerTarget = {
      id: "inner-target",
      type: "task",
      parentId: "inner-loop",
      position: { x: 10, y: 60 },
      hidden: true,
      data: { label: "Row task" },
    } as AppNode;
    const outerCond = {
      id: "cond-node-b",
      type: "conditional",
      position: { x: 0, y: 100 },
      data: { label: "Outer cond", activeBranchId: "branch-a" },
    } as AppNode;
    // Loop's conditionalBranchId matches the active branch, so no branch switch
    // is needed — but the loop itself is collapsed (inner-target is hidden).
    const innerLoopWithBranch = {
      ...innerLoop,
      data: {
        ...innerLoop.data,
        conditionalNodeId: "cond-node-b",
        conditionalBranchId: "branch-a",
      },
    } as AppNode;
    const nestedHiddenNodes = [
      startNode,
      outerCond,
      innerLoopWithBranch,
      innerTarget,
    ];
    const expandCalls: Array<string> = [];
    const deps = makeDeps(nestedHiddenNodes, {
      getNodes: () => nestedHiddenNodes,
      expandBlock: vi.fn((label) => expandCalls.push(label)),
      switchBranch: vi.fn(),
      waitForSettle: vi.fn().mockResolvedValue(undefined),
    });

    await focusBlockTarget("inner-target", deps);
    // No branch switches (branch already active).
    expect(deps.switchBranch).not.toHaveBeenCalled();
    // Ancestor expands in root→leaf order before the target's own expand.
    expect(expandCalls).toEqual(["Outer cond", "Rows loop", "Row task"]);
  });

  test("hidden node with dangling parentId: no expand, no extra settle (no 2s timeout reintroduced)", async () => {
    // A node hidden for a reason other than a collapsed container (dangling
    // parentId → resolveContainerAncestorLabels returns []). waitForSettle
    // must NOT be called — calling it with nothing expanded re-introduces the
    // 2s timeout the fix set out to remove.
    const orphanNode = {
      id: "orphan-node",
      type: "task",
      parentId: "gone-container",
      position: { x: 0, y: 0 },
      hidden: true,
      data: { label: "Orphan" },
    } as AppNode;
    const deps = makeDeps([startNode, orphanNode]);
    await focusBlockTarget("orphan-node", deps);
    expect(deps.expandBlock).toHaveBeenCalledTimes(1);
    expect(deps.expandBlock).toHaveBeenCalledWith("Orphan");
    expect(deps.waitForSettle).not.toHaveBeenCalled();
  });
});

describe("beginFocusGeneration", () => {
  afterEach(() => {
    useNodeCollapseStore.setState({ collapsed: {} });
    localStorage.clear();
  });

  test("the current run stays current until a newer one begins", () => {
    const counter = { current: 0 };
    const first = beginFocusGeneration(counter);
    expect(first()).toBe(true);

    const second = beginFocusGeneration(counter);
    // A rapid second Locate supersedes the first, whichever resolves last.
    expect(first()).toBe(false);
    expect(second()).toBe(true);

    const third = beginFocusGeneration(counter);
    expect(second()).toBe(false);
    expect(third()).toBe(true);
  });

  test("does not write persisted collapse state after unmount settles a locate", async () => {
    const workflowId = "workflow";
    const container = {
      id: "container",
      type: "loop",
      position: { x: 0, y: 0 },
      data: { label: "Container" },
    } as AppNode;
    const target = {
      id: "target",
      type: "task",
      parentId: container.id,
      position: { x: 0, y: 100 },
      hidden: true,
      data: { label: "Target" },
    } as AppNode;
    useNodeCollapseStore.setState({
      collapsed: {
        [makeCollapseKey(workflowId, container.data.label)]: true,
        [makeCollapseKey(workflowId, target.data.label)]: true,
      },
    });
    let settle: () => void = () => undefined;
    const settled = new Promise<void>((resolve) => {
      settle = resolve;
    });
    const generation = { current: 0 };
    const isCurrent = beginFocusGeneration(generation);
    const focus = focusBlockTarget(target.id, {
      getNodes: () => [container, target],
      getInternalNode: () => undefined,
      getPaneWidth: () => 1000,
      viewportZoom: 1,
      duration: 0,
      setViewport: vi.fn(),
      selectBlock: vi.fn(),
      expandBlock: (label) => {
        if (isCurrent()) {
          useNodeCollapseStore.getState().expandBlock(workflowId, label);
        }
      },
      waitForSettle: () => settled,
      switchBranch: vi.fn(),
    });

    await Promise.resolve();
    const beforeUnmount = useNodeCollapseStore.getState().collapsed;
    const persistedBeforeUnmount = localStorage.getItem(
      "skyvern:node-collapse",
    );
    invalidateFocusGeneration(generation);
    settle();
    await focus;

    expect(useNodeCollapseStore.getState().collapsed).toEqual(beforeUnmount);
    expect(localStorage.getItem("skyvern:node-collapse")).toBe(
      persistedBeforeUnmount,
    );
  });
});