Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

12.9 KB
Raw Blame
#!/bin/bash
# HTTP/API helpers for curl-based E2E tests.

wait_for_orchestrator_instance_status() {
  local base_url="$1"
  local instance_id="$2"
  local wanted_status="${3:-running}"
  local timeout_sec="${4:-60}"
  local started_at
  started_at=$(date +%s)

  while true; do
    local now
    now=$(date +%s)
    if [ $((now - started_at)) -ge "$timeout_sec" ]; then
      echo -e "  ${RED}✗${NC} instance ${instance_id} at ${base_url} did not reach ${wanted_status} within ${timeout_sec}s"
      return 1
    fi

    local inst_json
    inst_json=$(e2e_curl -sf "${base_url}/instances/${instance_id}" 2>/dev/null || true)
    if [ -n "$inst_json" ]; then
      local inst_status
      inst_status=$(echo "$inst_json" | jq -r '.status // empty' 2>/dev/null || true)
      if [ "$inst_status" = "$wanted_status" ]; then
        echo -e "  ${GREEN}✓${NC} instance ${instance_id} is ${wanted_status}"
        return 0
      fi
      if [ "$inst_status" = "stopped" ] || [ "$inst_status" = "error" ]; then
        echo -e "  ${RED}✗${NC} instance ${instance_id} reached terminal status ${inst_status} before ${wanted_status}"
        return 1
      fi
    fi

    sleep 1
  done
}

wait_for_instances_gone() {
  local base_url="$1"
  local timeout_sec="${2:-10}"
  shift 2
  local -a instance_ids=("$@")
  local started_at
  started_at=$(date +%s)

  while true; do
    local remaining=0
    for instance_id in "${instance_ids[@]}"; do
      local inst_json
      inst_json=$(e2e_curl -sf "${base_url}/instances/${instance_id}" 2>/dev/null || true)
      if [ -n "$inst_json" ]; then
        local inst_status
        inst_status=$(echo "$inst_json" | jq -r '.status // empty' 2>/dev/null || true)
        if [ "$inst_status" != "stopped" ] && [ "$inst_status" != "" ] && [ "$inst_status" != "null" ]; then
          ((remaining++)) || true
        fi
      fi
    done

    if [ "$remaining" -eq 0 ]; then
      return 0
    fi

    local now
    now=$(date +%s)
    if [ $((now - started_at)) -ge "$timeout_sec" ]; then
      return 1
    fi

    sleep 1
  done
}

wait_for_instances_running() {
  local base_url="$1"
  local timeout_sec="${2:-30}"
  shift 2
  local -a instance_ids=("$@")
  local started_at
  started_at=$(date +%s)

  while true; do
    local ready=0
    for instance_id in "${instance_ids[@]}"; do
      local inst_json
      inst_json=$(e2e_curl -sf "${base_url}/instances/${instance_id}" 2>/dev/null || true)
      if [ -n "$inst_json" ]; then
        local inst_status
        inst_status=$(echo "$inst_json" | jq -r '.status // empty' 2>/dev/null || true)
        if [ "$inst_status" = "running" ]; then
          ((ready++)) || true
        fi
      fi
    done

    if [ "$ready" -eq "${#instance_ids[@]}" ]; then
      return 0
    fi

    local now
    now=$(date +%s)
    if [ $((now - started_at)) -ge "$timeout_sec" ]; then
      return 1
    fi

    sleep 1
  done
}

RESULT=""
HTTP_STATUS=""

split_pinchtab_response() {
  local response="$1"
  HTTP_STATUS="${response##*$'\n'}"
  if [[ "$response" == *$'\n'* ]]; then
    RESULT="${response%$'\n'*}"
  else
    RESULT=""
  fi
}

pinchtab() {
  local method="$1"
  local path="$2"
  shift 2

  echo -e "${BLUE}→ curl -X $method ${E2E_SERVER}$path $(printf "%q " "$@")${NC}" >&2

  local response
  response=$(e2e_curl -s -w "\n%{http_code}" \
    -X "$method" \
    "${E2E_SERVER}$path" \
    -H "Content-Type: application/json" \
    "$@")

  split_pinchtab_response "$response"

  if [[ ! "$HTTP_STATUS" =~ ^2 ]]; then
    echo -e "${ERROR}  HTTP $HTTP_STATUS: $RESULT${NC}" >&2
  fi
}

pt() { pinchtab "$@"; }

_echo_truncated() {
  if [ ${#RESULT} -gt 1000 ]; then
    echo "${RESULT:0:200}...[truncated ${#RESULT} chars]"
  else
    echo "$RESULT"
  fi
}

pt_get() { pinchtab GET "$1"; _echo_truncated; }

pt_post() {
  local path="$1"
  shift
  if [ "$1" = "-d" ]; then
    shift
  fi
  pinchtab POST "$path" -d "$1"
  _echo_truncated
}

pt_patch() {
  local path="$1"
  local body="$2"
  echo -e "${BLUE}→ curl -X PATCH ${E2E_SERVER}$path${NC}" >&2
  local response
  response=$(e2e_curl -s -w "\n%{http_code}" \
    -X PATCH \
    "${E2E_SERVER}$path" \
    -H "Content-Type: application/json" \
    -d "$body")
  split_pinchtab_response "$response"
  _echo_truncated
}

pt_delete() {
  local path="$1"
  echo -e "${BLUE}→ curl -X DELETE ${E2E_SERVER}$path${NC}" >&2
  local response
  response=$(e2e_curl -s -w "\n%{http_code}" \
    -X DELETE \
    "${E2E_SERVER}$path")
  split_pinchtab_response "$response"
  _echo_truncated
}

pt_post_raw() {
  local path="$1"
  local body="$2"
  echo -e "${BLUE}→ curl -X POST ${E2E_SERVER}$path -d '$body'${NC}" >&2
  local response
  response=$(e2e_curl -s -w "\n%{http_code}" \
    -X POST \
    "${E2E_SERVER}$path" \
    -H "Content-Type: application/json" \
    -d "$body")
  split_pinchtab_response "$response"
  _echo_truncated
}

assert_url_accessible() {
  local url="$1"
  local label="${2:-$url}"

  if curl -sf "$url" >/dev/null 2>&1; then
    pass_assert "GET $label"
  else
    fail_assert "GET $label (not accessible)"
  fi
}

assert_fixtures_accessible() {
  assert_url_accessible "${FIXTURES_URL}/" "fixtures/"
  assert_url_accessible "${FIXTURES_URL}/form.html" "fixtures/form.html"
  assert_url_accessible "${FIXTURES_URL}/table.html" "fixtures/table.html"
  assert_url_accessible "${FIXTURES_URL}/buttons.html" "fixtures/buttons.html"
  assert_url_accessible "${FIXTURES_URL}/mouse-events.html" "fixtures/mouse-events.html"
}

assert_ok() {
  local label="${1:-request}"

  if [ "$HTTP_STATUS" = "200" ] || [ "$HTTP_STATUS" = "201" ]; then
    pass_assert "$label → $HTTP_STATUS"
  else
    fail_assert "$label failed (status: $HTTP_STATUS)"
  fi
}

assert_http_status() {
  local expected="$1"
  local label="${2:-request}"

  if [ "$HTTP_STATUS" = "$expected" ]; then
    pass_assert "$label → $HTTP_STATUS"
  else
    fail_assert "$label: expected $expected, got $HTTP_STATUS"
  fi
}

assert_not_ok() {
  local label="${1:-request}"

  if [ "$HTTP_STATUS" != "200" ] && [ "$HTTP_STATUS" != "201" ]; then
    pass_assert "$label → $HTTP_STATUS (error expected)"
  else
    fail_assert "$label: expected error, got $HTTP_STATUS"
  fi
}

click_button() {
  local name="$1"
  local ref
  ref=$(echo "$RESULT" | jq -r "[.nodes[] | select(.name == \"$name\") | .ref] | first // empty")

  if [ -n "$ref" ] && [ "$ref" != "null" ]; then
    pt_post /action "{\"kind\":\"click\",\"ref\":\"${ref}\"}" >/dev/null
    pass_assert "clicked '$name' (ref: $ref)"
  else
    fail_assert "button '$name' not found"
  fi
}

type_into() {
  local name="$1"
  local text="$2"
  local ref
  ref=$(echo "$RESULT" | jq -r "[.nodes[] | select(.name == \"$name\") | .ref] | first // empty")

  if [ -z "$ref" ] || [ "$ref" = "null" ]; then
    ref=$(echo "$RESULT" | jq -r '[.nodes[] | select(.role == "textbox") | .ref] | first // empty')
  fi

  if [ -n "$ref" ] && [ "$ref" != "null" ]; then
    pt_post /action "{\"kind\":\"type\",\"ref\":\"${ref}\",\"text\":\"${text}\"}" >/dev/null
    pass_assert "typed '$text' into '$name' (ref: $ref)"
  else
    fail_assert "input '$name' not found"
  fi
}

press_key() {
  local key="$1"
  pt_post /action -d "{\"kind\":\"press\",\"key\":\"${key}\"}" >/dev/null
  pass_assert "pressed '$key'"
}

get_tab_count() {
  e2e_curl -s "${E2E_SERVER}/tabs" | jq '.tabs | length'
}

_e2e_snapshot_tab_ids() {
  e2e_curl -s --max-time 5 "${E2E_SERVER}/tabs" 2>/dev/null | jq -r '.tabs[].id // empty' 2>/dev/null || true
}

# Records the scenario's starting tab set and, separately, whether the snapshot
# succeeded. A successful empty baseline (0 tabs) and a failed snapshot both leave
# an empty id set, but cleanup must treat them oppositely, so the success flag is
# tracked on its own rather than inferred from the contents.
_e2e_record_tab_baseline() {
  SCENARIO_TAB_BASELINE=""
  SCENARIO_TAB_BASELINE_OK=0
  local body status
  body=$(e2e_curl -s --max-time 5 -w $'\n%{http_code}' "${E2E_SERVER}/tabs" 2>/dev/null) || return 0
  status="${body##*$'\n'}"
  [ "$status" = "200" ] || return 0
  SCENARIO_TAB_BASELINE_OK=1
  SCENARIO_TAB_BASELINE="$(printf '%s' "${body%$'\n'*}" | jq -r '.tabs[].id // empty' 2>/dev/null | tr '\n' ' ')"
}

_e2e_close_leaked_tabs() {
  local id
  # Skip only when the start-of-scenario snapshot FAILED: an unknown baseline cannot
  # say which tabs the scenario opened. A successful empty baseline means the
  # scenario began with no tabs, so every tab present now is one it opened.
  [ "${SCENARIO_TAB_BASELINE_OK:-0}" = "1" ] || return 0
  while read -r id; do
    [ -n "$id" ] || continue
    case " ${SCENARIO_TAB_BASELINE} " in
      *" ${id} "*) continue ;;
    esac
    e2e_curl -s --max-time 5 -X POST "${E2E_SERVER}/close" \
      -H "Content-Type: application/json" \
      -d "{\"tabId\":\"$id\"}" >/dev/null 2>&1 || true
  done < <(_e2e_snapshot_tab_ids)
}

get_tab_id() {
  echo "$RESULT" | jq -r '.tabId'
}

normalize_default_port_url() {
  local raw="${1:-}"
  raw="${raw/http:\/\/127.0.0.1:80\//http:\/\/127.0.0.1/}"
  raw="${raw/http:\/\/localhost:80\//http:\/\/localhost/}"
  raw="${raw/https:\/\/127.0.0.1:443\//https:\/\/127.0.0.1/}"
  raw="${raw/https:\/\/localhost:443\//https:\/\/localhost/}"
  printf '%s' "$raw" | sed -E \
    -e 's#^http://([^/:]+):80(/|$)#http://\1\2#' \
    -e 's#^https://([^/:]+):443(/|$)#https://\1\2#'
}

poll_instance_tab_id_by_url() {
  local instance_id="$1"
  local url="$2"
  local attempts="${3:-20}"
  local delay="${4:-0.5}"
  local base_url="${5:-$E2E_SERVER}"
  local normalized_url
  normalized_url=$(normalize_default_port_url "$url")

  for i in $(seq 1 "$attempts"); do
    local tabs_json
    tabs_json=$(e2e_curl -sf "${base_url}/instances/${instance_id}/tabs" 2>/dev/null || true)
    if [ -n "$tabs_json" ]; then
      local tab_id
      tab_id=$(echo "$tabs_json" | jq -r --arg url "$url" --arg normalized_url "$normalized_url" '[.[] | select(.url == $url or .url == $normalized_url) | .id] | first // empty' 2>/dev/null || true)
      if [ -n "$tab_id" ] && [ "$tab_id" != "null" ]; then
        printf '%s' "$tab_id"
        return 0
      fi
    fi
    sleep "$delay"
  done

  return 1
}

assert_tab_id() {
  local desc="${1:-tabId returned}"
  TAB_ID=$(echo "$RESULT" | jq -r '.tabId')
  if [ -n "$TAB_ID" ] && [ "$TAB_ID" != "null" ]; then
    pass_assert "$desc: ${TAB_ID:0:12}..."
  else
    fail_assert "no tabId in response"
  fi
}

assert_instance_list_contains() {
  local instance_id="$1"
  local present_msg="$2"
  local missing_msg="$3"
  local found
  found=$(echo "$RESULT" | jq -r ".[] | select(.id == \"$instance_id\") | .id")
  if [ "$found" = "$instance_id" ]; then
    pass_assert "$present_msg"
  else
    fail_assert "$missing_msg"
  fi
}

assert_instance_list_absent() {
  local instance_id="$1"
  local absent_msg="$2"
  local present_msg="$3"
  local found
  found=$(echo "$RESULT" | jq -r ".[] | select(.id == \"$instance_id\") | .id")
  if [ -z "$found" ] || [ "$found" = "null" ]; then
    pass_assert "$absent_msg"
  else
    fail_assert "$present_msg"
  fi
}

assert_instance_id_prefix() {
  local instance_id="$1"
  if grep -q -- "^inst_" <<<"$instance_id"; then
    pass_assert "instance ID has inst_ prefix: $instance_id"
  else
    fail_assert "bad ID format: $instance_id"
  fi
}

get_first_tab() {
  echo "$RESULT" | jq -r '.tabs[0].id'
}

show_tab() {
  local label="$1"
  local id="$2"
  echo -e "  ${MUTED}$label: ${id:0:12}...${NC}"
}

assert_tab_count() {
  local expected="$1"
  local actual
  actual=$(get_tab_count)

  if [ "$actual" -eq "$expected" ]; then
    pass_assert "tab count = $actual"
  else
    fail_assert "tab count: expected $expected, got $actual"
  fi
}

assert_tab_count_gte() {
  local min="$1"
  local actual
  actual=$(get_tab_count)

  if [ "$actual" -ge "$min" ]; then
    pass_assert "tab count $actual >= $min"
  else
    fail_assert "tab count: expected >= $min, got $actual"
  fi
}

assert_tab_closed() {
  local before="$1"
  local actual
  actual=$(get_tab_count)

  if [ "$actual" -lt "$before" ]; then
    pass_assert "tab closed (before: $before, after: $actual)"
  else
    fail_assert "tab not closed (before: $before, after: $actual)"
  fi
}

assert_eval_poll() {
  local expr="$1"
  local expected="$2"
  local desc="${3:-eval poll}"
  local attempts="${4:-5}"
  local delay="${5:-0.4}"
  local tab_id="${6:-}"

  local ok=false
  local actual=""
  for i in $(seq 1 "$attempts"); do
    local json_body
    if [ -n "$tab_id" ]; then
      json_body=$(jq -n --arg expr "$expr" '{"expression": $expr}')
      pt_post "/tabs/${tab_id}/evaluate" "$json_body"
    else
      json_body=$(jq -n --arg expr "$expr" '{"expression": $expr}')
      pt_post /evaluate "$json_body"
    fi
    actual=$(echo "$RESULT" | jq -r '
      if has("result") then
        .result | if . == null then "null" else tostring end
      else
        empty
      end
    ' 2>/dev/null)
    if [ "$actual" = "$expected" ]; then
      ok=true
      break
    fi
    sleep "$delay"
  done

  if [ "$ok" = "true" ]; then
    pass_assert "$desc"
    return 0
  fi

  fail_assert "$desc (got: $actual, expected: $expected)"
  return 1
}