# wsl2-windows-chrome-remote-cdp

Adopt this skill: https://proskills.md/skills/other/andytane-wsl2-windows-chrome-remote-cdp-skill-wsl2-windows-chrome-remote-cdp

Page: https://proskills.md/skills/other/andytane-wsl2-windows-chrome-remote-cdp-skill-wsl2-windows-chrome-remote-cdp
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skill-wsl2-windows-chrome-remote-cdp/SKILL.md
size: 8711
sha: 895489033f3305c0eda16879476e5d2f0901d92e
upstream: https://github.com/andytane/wsl2-windows-chrome-remote-cdp/blob/main/skill-wsl2-windows-chrome-remote-cdp/SKILL.md

````text
---
name: wsl2-windows-chrome-remote-cdp
description: Diagnose, configure, and validate OpenClaw browser control when the Gateway runs inside WSL2 but Google Chrome runs on Windows, especially in environments with proxy software, global mode, virtual network adapters, or host/guest split networking. Use when browser control must attach through Remote CDP instead of launching a Linux browser, when WSL can reach Windows only through a forwarded host port, or when users mention portproxy, 9222/9223, virtual NICs, Clash/FClash/Mihomo, or WSL2-to-Windows Chrome automation.
---

Use this skill to make OpenClaw in WSL2 control Windows Chrome through a stable Remote CDP bridge.

## Core rule

Do not change OpenClaw browser config until WSL2 can successfully reach the Windows-side CDP bridge with `curl`.

Working pattern:

```text
OpenClaw (WSL2) -> profile remote -> http://HOST_IP:9223 -> Windows portproxy -> 127.0.0.1:9222 -> Chrome
```

## Minimal workflow

1. Read `references/runbook.md`.
2. Verify Windows Chrome local CDP on `127.0.0.1:9222`.
3. Verify Windows `portproxy` and firewall for `9223`.
4. From WSL2, verify `curl http://HOST_IP:9223/json/version` and `/json/list`.
5. Only then write OpenClaw remote profile config.
6. Restart gateway.
7. Validate with `openclaw browser profiles`, `status`, `tabs`, `open`, `snapshot`, `navigate`.

## Read these references when needed

- `references/runbook.md` — full end-to-end executable procedure with Mermaid diagrams
- `references/config-snippets.md` — OpenClaw JSON, Windows commands, and validation snippets
- `references/troubleshooting.md` — layered failure analysis and fast triage

## Use bundled scripts

### WSL-side recovery

Before running recovery, first enter the skill root directory and run:

```bash
bash ./scripts/self-check.sh
```

Use `bash ./scripts/...` in the default examples to avoid `Permission denied` when execute bits are missing.

- `scripts/update-openclaw-remote-cdp.sh` — detect current WSL host gateway IP, validate the Windows CDP bridge, backup `~/.openclaw/openclaw.json`, update `browser.profiles.remote.cdpUrl`, optionally set `browser.defaultProfile=remote`, restart the gateway, and print verification output
- `scripts/show-openclaw-remote-cdp.sh` — print the currently detected host IP and derived CDP URL and probe `/json/version`

Run the WSL-side scripts from the skill root directory, for example:

```bash
./scripts/update-openclaw-remote-cdp.sh --dry-run
```

Use `update-openclaw-remote-cdp.sh --dry-run` before modifying config when the environment may have changed after Windows or WSL reboot.

### Windows-side recovery

- `scripts/windows-self-check.ps1` — minimal Windows-side checker that verifies Chrome path, local CDP on `127.0.0.1:9222`, `portproxy` bridge, and firewall rule; prints READY / NOT READY with simple line-by-line status output
- `scripts/setup-windows-chrome-cdp.ps1` — minimal Windows setup script that can run with `-DryRun` first, then start Windows Chrome with `--remote-debugging-port=9222`, recreate `portproxy` `9223 -> 127.0.0.1:9222`, add firewall allow rule, and print verification guidance
- `scripts/teardown-windows-chrome-cdp.ps1` — minimal Windows teardown script that can run with `-DryRun` first, then remove the Windows bridge `portproxy` and firewall rule

Preferred pattern on Windows:
1. Enter the skill root directory in Windows PowerShell.
2. Copy the Windows `.ps1` files to a local Windows folder and run `powershell -NoExit -ExecutionPolicy Bypass -File .\windows-self-check.ps1` from an existing Windows PowerShell console.
3. If NOT READY, run `powershell -ExecutionPolicy Bypass -File .\setup-windows-chrome-cdp.ps1`.
4. Then continue the WSL-side recovery flow.

Use these when Windows reboot, proxy software reset, or network stack changes cause the bridge layer to disappear even though WSL-side config remains correct.

## Dependency remediation rule

When a required dependency is missing in WSL, do not stop at printing shell commands.

Preferred agent behavior:

1. Explain the missing dependency in plain language.
2. State which next step is blocked.
3. Ask whether to install it automatically.
4. If the user replies with an explicit confirmation such as `YES`, run the install command directly.
5. After installation, resume the original flow automatically instead of asking the user to restart from scratch.

Examples:

- Missing `jq` blocks automatic OpenClaw JSON updates.
- Missing `ip` blocks default gateway detection.
- Missing `curl` blocks CDP endpoint validation.

Preferred install commands on Ubuntu/WSL:

```bash
sudo apt update
sudo apt install -y jq curl iproute2
```

If `sudo` requires an interactive password that the agent cannot provide, show the exact command and tell the user the next step will continue automatically after installation completes.

## Key invariants

- Prefer `browser.profiles.remote.cdpUrl` for split-host WSL2/Windows setups.
- Use `attachOnly: true` for externally managed Windows Chrome.
- Treat Windows local `9222` and WSL-visible `9223` as separate layers.
- Do not confuse a higher-layer action failure (for example screenshot timeout) with remote CDP transport failure.

## What to avoid

- Do not keep retrying Linux local browser launch when the real target is Windows Chrome.
- Do not write unverified host IPs into OpenClaw config.
- Do not assume proxy software that affects internet traffic automatically solves local WSL2-to-Windows TCP reachability.
- Do not diagnose browser action failures before proving `/json/version` and `/json/list` are reachable from WSL2.
- Do not over-engineer Windows PowerShell helper scripts for end users; prefer parser stability over elegant abstractions.

## Browser interaction best practices

### Ref naming convention

When documenting or scripting browser interactions, use the `@eN` style for clarity:

```bash
# Preferred (clear ref style)
openclaw browser click @e12
openclaw browser type @e23 "username"

# Also valid (raw number)
openclaw browser click 12
openclaw browser type 23 "username"
```

The `@eN` style makes scripts more readable and aligns with agent-browser conventions.

### Snapshot workflow

Recommended pattern for reliable automation:

```bash
# 1. Navigate
openclaw browser --browser-profile remote open https://example.com

# 2. Wait for network idle
openclaw browser wait --load networkidle

# 3. Capture interactive snapshot
openclaw browser --browser-profile remote snapshot --interactive --limit 200

# 4. Parse refs and interact
openclaw browser click @e12
openclaw browser type @e23 "text"

# 5. Re-snapshot after page changes
openclaw browser --browser-profile remote snapshot --interactive --limit 200
```

### Snapshot wrapper script

Use the bundled `snapshot-json.sh` for unified JSON output:

```bash
# Default AI snapshot
bash ./scripts/snapshot-json.sh

# Snapshot specific tab
bash ./scripts/snapshot-json.sh abcd1234

# With additional flags
bash ./scripts/snapshot-json.sh --interactive --limit 200
```

Output format:

```json
{
  "success": true,
  "timestamp": "2026-03-30T19:00:00Z",
  "data": {
    "snapshot": "...",
    "refs": ["@e1", "@e2", "@e3"]
  },
  "command": "snapshot --interactive --limit 200"
}
```

### Wait patterns

See `references/wait-patterns.md` for comprehensive wait patterns:

| Pattern | Example |
|---------|---------|
| Wait for text | `openclaw browser wait --text "Welcome"` |
| Wait for network | `openclaw browser wait --load networkidle` |
| Wait for URL | `openclaw browser wait --url "**/dashboard"` |
| Wait for JS condition | `openclaw browser wait --fn "window.ready === true"` |
| Wait for time | `openclaw browser wait 3000` |

**Rule**: Wait for conditions, not just time.

### Comparison with agent-browser

| Feature | agent-browser | Current OpenClaw |
|---------|---------------|------------------|
| Ref style | `@e2` | `@e2` or `12` |
| Snapshot | `snapshot -i --json` | `snapshot --interactive --format ai` |
| Wait for element | `wait @e2` | `wait --selector "[ref=e2]"` |
| Wait for text | `wait --text "..."` | `wait --text "..."` |
| Wait for network | `wait --load networkidle` | `wait --load networkidle` |
| Wait for JS | `wait --fn "..."` | `wait --fn "..."` |
| Session isolation | `--session` flag | Single Chrome, multi-tab |
| State persistence | `state save/load` | Native Chrome persistence |

**Design choice**: We prioritize reusing the user's daily Chrome (with native login state) over isolated browser instances. This is lighter and more aligned with the WSL2 → Windows Chrome remote CDP scenario.

## Additional references

- `references/wait-patterns.md` — Comprehensive wait patterns and best practices
````

## File: skill-wsl2-windows-chrome-remote-cdp/scripts/self-check.sh
size: 1248
sha: ba6fcecd51687c7bbfcfbd87c5eabe042d82230e
upstream: https://github.com/andytane/wsl2-windows-chrome-remote-cdp/blob/main/skill-wsl2-windows-chrome-remote-cdp/scripts/self-check.sh

```text
#!/usr/bin/env bash
set -euo pipefail

missing=0

check_cmd() {
  local cmd="$1"
  if command -v "$cmd" >/dev/null 2>&1; then
    echo "OK   command: $cmd -> $(command -v "$cmd")"
  else
    echo "MISS command: $cmd"
    missing=1
  fi
}

echo "Current directory: $(pwd)"

echo
if [[ -f "./SKILL.md" && -d "./scripts" && -d "./references" ]]; then
  echo "OK   current directory looks like the skill root"
else
  echo "MISS current directory is not the expected skill root"
  echo "Expected to see: ./SKILL.md ./scripts ./references"
  missing=1
fi

echo
echo "Checking required commands..."
check_cmd ip
check_cmd awk
check_cmd curl
check_cmd jq
check_cmd openclaw

echo
if [[ $missing -ne 0 ]]; then
  echo "Preflight check failed."
  echo
  echo "If jq is missing on Ubuntu/WSL, install it with:"
  echo "  sudo apt update"
  echo "  sudo apt install -y jq"
  echo
  echo "Common base tools if needed:"
  echo "  sudo apt update"
  echo "  sudo apt install -y jq curl iproute2"
  echo
  echo "Then re-run:"
  echo "  ./scripts/self-check.sh"
  exit 1
fi

echo "Preflight check passed."
echo "Suggested next steps:"
echo "  ./scripts/update-openclaw-remote-cdp.sh --dry-run"
echo "  ./scripts/update-openclaw-remote-cdp.sh --apply --set-default"
```

## File: skill-wsl2-windows-chrome-remote-cdp/scripts/setup-windows-chrome-cdp.ps1
size: 2697
sha: 83001d1292646cd9d37259d795b9fe373c34d0b9
upstream: https://github.com/andytane/wsl2-windows-chrome-remote-cdp/blob/main/skill-wsl2-windows-chrome-remote-cdp/scripts/setup-windows-chrome-cdp.ps1

```text
param(
  [int]$ChromePort = 9222,
  [int]$BridgePort = 9223,
  [string]$ChromePath = 'C:\Program Files\Google\Chrome\Application\chrome.exe',
  [switch]$DryRun
)

$ErrorActionPreference = 'Continue'
$RuleName = 'ChromeCDP' + $BridgePort

Write-Host ''
Write-Host '==== Windows setup for Chrome CDP (minimal) ===='
Write-Host ('ChromePath  : ' + $ChromePath)
Write-Host ('ChromePort  : ' + $ChromePort)
Write-Host ('BridgePort  : ' + $BridgePort)
Write-Host ('RuleName    : ' + $RuleName)
Write-Host ('DryRun      : ' + $DryRun)
Write-Host ''

if (-not (Test-Path $ChromePath)) {
  Write-Host 'ERROR: Chrome executable not found.'
  Write-Host ('Expected path: ' + $ChromePath)
  exit 1
}

if ($DryRun) {
  Write-Host 'DRY RUN - no changes will be made.'
  Write-Host ('Would start Chrome with: ' + $ChromePath + ' --remote-debugging-port=' + $ChromePort)
  Write-Host ('Would run: netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=' + $BridgePort)
  Write-Host ('Would run: netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=' + $BridgePort + ' connectaddress=127.0.0.1 connectport=' + $ChromePort)
  Write-Host ('Would run: netsh advfirewall firewall delete rule name=' + $RuleName)
  Write-Host ('Would run: netsh advfirewall firewall add rule name=' + $RuleName + ' dir=in action=allow protocol=TCP localport=' + $BridgePort)
  exit 0
}

Write-Host 'Starting Chrome with remote debugging...'
Start-Process -FilePath $ChromePath -ArgumentList ('--remote-debugging-port=' + $ChromePort) | Out-Null
Start-Sleep -Seconds 2

try {
  $uri = 'http://127.0.0.1:' + $ChromePort + '/json/version'
  $null = Invoke-RestMethod -Uri $uri -TimeoutSec 5
  Write-Host 'OK - Chrome local CDP /json/version'
} catch {
  Write-Host 'MISS - Chrome local CDP /json/version after start'
}

Write-Host 'Resetting portproxy rule...'
& netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=$BridgePort | Out-Null
& netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=$BridgePort connectaddress=127.0.0.1 connectport=$ChromePort | Out-Null

Write-Host 'Resetting firewall rule...'
& netsh advfirewall firewall delete rule name=$RuleName | Out-Null
& netsh advfirewall firewall add rule name=$RuleName dir=in action=allow protocol=TCP localport=$BridgePort | Out-Null

Write-Host ''
Write-Host 'Current portproxy:'
& netsh interface portproxy show all
Write-Host ''
Write-Host 'Current firewall rule:'
& netsh advfirewall firewall show rule name=$RuleName
Write-Host ''
Write-Host 'Done.'
Write-Host 'Now verify from WSL with:'
Write-Host ('  curl --connect-timeout 3 --max-time 5 http://<WSL_HOST_GATEWAY>:' + $BridgePort + '/json/version')
```

## File: skill-wsl2-windows-chrome-remote-cdp/scripts/show-openclaw-remote-cdp.sh
size: 347
sha: c8ec70d517a4e7bc1043655394c3c0ee6ba94111
upstream: https://github.com/andytane/wsl2-windows-chrome-remote-cdp/blob/main/skill-wsl2-windows-chrome-remote-cdp/scripts/show-openclaw-remote-cdp.sh

```text
#!/usr/bin/env bash
set -euo pipefail
HOST_IP="$(ip route | awk '/default/ {print $3; exit}')"
if [[ -z "${HOST_IP}" ]]; then
  echo "ERROR: failed to detect WSL default gateway IP" >&2
  exit 1
fi
CDP_URL="http://${HOST_IP}:9223"
echo "HOST_IP=${HOST_IP}"
echo "CDP_URL=${CDP_URL}"
curl --connect-timeout 3 --max-time 5 "${CDP_URL}/json/version"
```

## File: skill-wsl2-windows-chrome-remote-cdp/scripts/snapshot-json.sh
size: 1356
sha: fd9662c3f87c05ff0e3a02d87ca070476723aeb4
upstream: https://github.com/andytane/wsl2-windows-chrome-remote-cdp/blob/main/skill-wsl2-windows-chrome-remote-cdp/scripts/snapshot-json.sh

```text
#!/bin/bash
# snapshot-json.sh - Wrapper for OpenClaw browser snapshot with unified JSON envelope
#
# Usage:
#   ./snapshot-json.sh [target-id] [format]
#
# Examples:
#   ./snapshot-json.sh                              # Default AI snapshot
#   ./snapshot-json.sh abcd1234                     # Snapshot specific tab
#   ./snapshot-json.sh abcd1234 aria                # Aria format
#   ./snapshot-json.sh --interactive --limit 200    # Pass-through flags

set -e

SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Check if first arg is a target-id or a flag
if [[ "${1:-}" == --* ]]; then
  # All args are flags, pass through
  EXTRA_ARGS=("$@")
  TARGET_ID=""
else
  TARGET_ID="${1:-}"
  FORMAT="${2:-ai}"
  EXTRA_ARGS=("${@:3}")
fi

# Build command
CMD=(openclaw browser --browser-profile remote snapshot)

if [[ -n "$TARGET_ID" && "$TARGET_ID" != --* ]]; then
  CMD+=(--target-id "$TARGET_ID")
fi

if [[ -n "${FORMAT:-}" && "$FORMAT" != --* ]]; then
  CMD+=(--format "$FORMAT")
fi

# Add extra flags
if [[ ${#EXTRA_ARGS[@]} -gt 0 ]]; then
  CMD+=("${EXTRA_ARGS[@]}")
fi

# Execute and wrap in unified envelope
"${CMD[@]}" | jq --slurp '{
  success: true,
  timestamp: (now | strftime("%Y-%m-%dT%H:%M:%SZ")),
  data: {
    snapshot: (.[0] // ""),
    refs: (.[0] | scan("@e[0-9]+") | unique)
  },
  command: ($ARGS.positional | join(" "))
}'
```

## File: skill-wsl2-windows-chrome-remote-cdp/scripts/teardown-windows-chrome-cdp.ps1
size: 999
sha: 8687d680898c7aac7ed386150f8a8f92658f984f
upstream: https://github.com/andytane/wsl2-windows-chrome-remote-cdp/blob/main/skill-wsl2-windows-chrome-remote-cdp/scripts/teardown-windows-chrome-cdp.ps1

```text
param(
  [int]$BridgePort = 9223,
  [switch]$DryRun
)

$ErrorActionPreference = 'Continue'
$RuleName = 'ChromeCDP' + $BridgePort

Write-Host ''
Write-Host '==== Windows teardown for Chrome CDP bridge (minimal) ===='
Write-Host ('BridgePort  : ' + $BridgePort)
Write-Host ('RuleName    : ' + $RuleName)
Write-Host ('DryRun      : ' + $DryRun)
Write-Host ''

if ($DryRun) {
  Write-Host 'DRY RUN - no changes will be made.'
  Write-Host ('Would run: netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=' + $BridgePort)
  Write-Host ('Would run: netsh advfirewall firewall delete rule name=' + $RuleName)
  exit 0
}

Write-Host 'Removing portproxy rule...'
& netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=$BridgePort | Out-Null

Write-Host 'Removing firewall rule...'
& netsh advfirewall firewall delete rule name=$RuleName | Out-Null

Write-Host ''
Write-Host 'Remaining portproxy:'
& netsh interface portproxy show all
Write-Host ''
Write-Host 'Done.'
```

## File: skill-wsl2-windows-chrome-remote-cdp/scripts/update-openclaw-remote-cdp.sh
size: 4236
sha: 842916394c9a95dc805ae0b02d5668f00d97b509
upstream: https://github.com/andytane/wsl2-windows-chrome-remote-cdp/blob/main/skill-wsl2-windows-chrome-remote-cdp/scripts/update-openclaw-remote-cdp.sh

```text
#!/usr/bin/env bash
set -euo pipefail

CONFIG_FILE="${HOME}/.openclaw/openclaw.json"
BACKUP_DIR="${HOME}/.openclaw/backups"
PROFILE_NAME="remote"
CDP_PORT="9223"
SET_DEFAULT="false"
MODE="apply"

usage() {
  cat <<'EOF'
Usage:
  update-openclaw-remote-cdp.sh [--dry-run|--apply] [--set-default] [--port <port>]

Options:
  --dry-run      Detect and validate only; do not modify config
  --apply        Detect, validate, backup, update config, restart gateway, validate
  --set-default  Also set browser.defaultProfile=remote
  --port <port>  Override CDP bridge port (default: 9223)
EOF
}

need_cmd() {
  local cmd="$1"
  command -v "$cmd" >/dev/null 2>&1 || {
    echo "ERROR: missing command: $cmd" >&2
    case "$cmd" in
      jq)
        echo "Install it with:" >&2
        echo "  sudo apt update" >&2
        echo "  sudo apt install -y jq" >&2
        ;;
      ip)
        echo "Install it with:" >&2
        echo "  sudo apt update" >&2
        echo "  sudo apt install -y iproute2" >&2
        ;;
      curl)
        echo "Install it with:" >&2
        echo "  sudo apt update" >&2
        echo "  sudo apt install -y curl" >&2
        ;;
      openclaw)
        echo "Ensure OpenClaw CLI is installed and available in PATH." >&2
        ;;
    esac
    exit 1
  }
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --dry-run) MODE="dry-run"; shift ;;
    --apply) MODE="apply"; shift ;;
    --set-default) SET_DEFAULT="true"; shift ;;
    --port)
      [[ $# -ge 2 ]] || { echo "ERROR: --port requires a value" >&2; exit 1; }
      CDP_PORT="$2"; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "ERROR: unknown argument: $1" >&2; usage; exit 1 ;;
  esac
done

need_cmd ip
need_cmd awk
need_cmd curl
need_cmd jq
need_cmd cp
need_cmd mkdir
need_cmd date
need_cmd mktemp
need_cmd mv

if [[ ! -f "$CONFIG_FILE" ]]; then
  echo "ERROR: OpenClaw config not found: $CONFIG_FILE" >&2
  exit 1
fi

HOST_IP="$(ip route | awk '/default/ {print $3; exit}')"
if [[ -z "${HOST_IP}" ]]; then
  echo "ERROR: failed to detect WSL default gateway IP" >&2
  exit 1
fi

CDP_URL="http://${HOST_IP}:${CDP_PORT}"

echo "Detected Windows host IP : ${HOST_IP}"
echo "Target CDP URL          : ${CDP_URL}"

echo "Checking CDP endpoint: ${CDP_URL}/json/version"
curl --connect-timeout 3 --max-time 5 -fsS "${CDP_URL}/json/version" >/dev/null

echo "Checking CDP target list: ${CDP_URL}/json/list"
curl --connect-timeout 3 --max-time 5 -fsS "${CDP_URL}/json/list" >/dev/null

if [[ "$MODE" == "dry-run" ]]; then
  echo
  echo "Dry run only. No config changes made."
  echo "Suggested profile : ${PROFILE_NAME}"
  echo "Suggested cdpUrl  : ${CDP_URL}"
  echo "Suggested default : ${SET_DEFAULT}"
  exit 0
fi

mkdir -p "$BACKUP_DIR"
BACKUP_FILE="${BACKUP_DIR}/openclaw.json.$(date +%Y%m%d-%H%M%S).bak"
cp "$CONFIG_FILE" "$BACKUP_FILE"
echo "Backup created: $BACKUP_FILE"

TMP_FILE="$(mktemp)"
if [[ "$SET_DEFAULT" == "true" ]]; then
  jq --arg profile "$PROFILE_NAME" --arg cdpUrl "$CDP_URL" '
    .browser = (.browser // {}) |
    .browser.defaultProfile = $profile |
    .browser.profiles = (.browser.profiles // {}) |
    .browser.profiles[$profile] = ((.browser.profiles[$profile] // {}) + {
      "cdpUrl": $cdpUrl,
      "attachOnly": true,
      "color": "#00AA00"
    })
  ' "$CONFIG_FILE" > "$TMP_FILE"
else
  jq --arg profile "$PROFILE_NAME" --arg cdpUrl "$CDP_URL" '
    .browser = (.browser // {}) |
    .browser.profiles = (.browser.profiles // {}) |
    .browser.profiles[$profile] = ((.browser.profiles[$profile] // {}) + {
      "cdpUrl": $cdpUrl,
      "attachOnly": true,
      "color": "#00AA00"
    })
  ' "$CONFIG_FILE" > "$TMP_FILE"
fi

mv "$TMP_FILE" "$CONFIG_FILE"

echo "Updated: $CONFIG_FILE"
echo "Profile : $PROFILE_NAME"
echo "cdpUrl  : $CDP_URL"
if [[ "$SET_DEFAULT" == "true" ]]; then
  echo "defaultProfile set to: $PROFILE_NAME"
fi

echo "Restarting OpenClaw gateway..."
if command -v openclaw >/dev/null 2>&1; then
  openclaw gateway restart || true
elif command -v systemctl >/dev/null 2>&1; then
  systemctl --user restart openclaw-gateway.service || true
fi

sleep 2

echo
echo "Validation:"
openclaw browser profiles || true
echo
openclaw browser --browser-profile "$PROFILE_NAME" status || true

echo
echo "Done."
```

## File: skill-wsl2-windows-chrome-remote-cdp/scripts/windows-self-check.ps1
size: 3022
sha: 41874c548dde3f77ce0468dd6feed3567cc55a6d
upstream: https://github.com/andytane/wsl2-windows-chrome-remote-cdp/blob/main/skill-wsl2-windows-chrome-remote-cdp/scripts/windows-self-check.ps1

```text
# Windows self-check script for Chrome CDP setup
param(
  [int]$ChromePort = 9222,
  [int]$BridgePort = 9223,
  [string]$ChromePath = 'C:\Program Files\Google\Chrome\Application\chrome.exe'
)

$ErrorActionPreference = 'Continue'
$RuleName = 'ChromeCDP' + $BridgePort

Write-Host ""
Write-Host "==== Windows self-check (minimal) ===="
Write-Host "ChromePath  : $ChromePath"
Write-Host "ChromePort  : $ChromePort"
Write-Host "BridgePort  : $BridgePort"
Write-Host "RuleName    : $RuleName"
Write-Host ""
Write-Host "Run this from an existing Windows PowerShell console."
Write-Host "Recommended: copy this .ps1 file to a local Windows folder before executing it."
Write-Host ""

$ChromePathOk = Test-Path $ChromePath
if ($ChromePathOk) {
  Write-Host "OK - Chrome executable path"
} else {
  Write-Host "MISS - Chrome executable path"
}

try {
  $uri = "http://127.0.0.1:$ChromePort/json/version"
  $null = Invoke-RestMethod -Uri $uri -TimeoutSec 5
  Write-Host "OK - Chrome local CDP /json/version"
  $ChromeVersionOk = $true
} catch {
  Write-Host "MISS - Chrome local CDP /json/version"
  $ChromeVersionOk = $false
}

try {
  $uri = "http://127.0.0.1:$ChromePort/json/list"
  $null = Invoke-RestMethod -Uri $uri -TimeoutSec 5
  Write-Host "OK - Chrome local CDP /json/list"
  $ChromeListOk = $true
} catch {
  Write-Host "MISS - Chrome local CDP /json/list"
  $ChromeListOk = $false
}

$PortproxyText = (& netsh interface portproxy show all | Out-String)
$PortproxyOk = $false
if ($PortproxyText -match '127.0.0.1') {
  if ($PortproxyText -match $BridgePort) {
    if ($PortproxyText -match $ChromePort) {
      $PortproxyOk = $true
    }
  }
}
if ($PortproxyOk) {
  Write-Host "OK - portproxy bridge"
} else {
  Write-Host "MISS - portproxy bridge"
}

$FirewallText = (& netsh advfirewall firewall show rule name=$RuleName 2>&1 | Out-String)
$FirewallOk = $false
if ($FirewallText -like "*$RuleName*" -and $FirewallText -notlike "*No rules match*" -and $FirewallText -notlike "*没有与指定条件匹配的规则*" -and $FirewallText -notlike "*指定的值无效*") {
  $FirewallOk = $true
}
if ($FirewallOk) {
  Write-Host "OK - firewall rule"
} else {
  Write-Host "MISS - firewall rule"
}

Write-Host ""
$AllOk = $ChromePathOk -and $ChromeVersionOk -and $ChromeListOk -and $PortproxyOk -and $FirewallOk
if ($AllOk) {
  Write-Host "OVERALL: READY"
} else {
  Write-Host "OVERALL: NOT READY"
  Write-Host "Recommended next step:"
  Write-Host "  powershell -ExecutionPolicy Bypass -File .\setup-windows-chrome-cdp.ps1"
}

Write-Host ""
Write-Host "Useful manual checks:"
Write-Host "  Test-Path '$ChromePath'"
Write-Host "  curl http://127.0.0.1:$ChromePort/json/version"
Write-Host "  curl http://127.0.0.1:$ChromePort/json/list"
Write-Host "  netsh interface portproxy show all"
Write-Host "  netsh advfirewall firewall show rule name=$RuleName"
Write-Host ""
Write-Host "If needed, keep the window open with:"
Write-Host "  powershell -NoExit -ExecutionPolicy Bypass -File .\windows-self-check.ps1"
Write-Host ""
```

## File: skill-wsl2-windows-chrome-remote-cdp/references/config-snippets.md
size: 2630
sha: 506483cde0f3dec016d224337d321c1e705a2522
upstream: https://github.com/andytane/wsl2-windows-chrome-remote-cdp/blob/main/skill-wsl2-windows-chrome-remote-cdp/references/config-snippets.md

````text
# Config snippets

## OpenClaw browser config

```json
{
  "browser": {
    "enabled": true,
    "defaultProfile": "remote",
    "profiles": {
      "remote": {
        "cdpUrl": "http://172.17.32.1:9223",
        "attachOnly": true,
        "color": "#00AA00"
      }
    }
  }
}
```

## Windows Chrome start command

```powershell
& 'C:\Program Files\Google\Chrome\Application\chrome.exe' --remote-debugging-port=9222
```

## Windows recovery script

Recommended: copy the `.ps1` files to a local Windows folder first, then run:

This Windows self-check is intentionally minimal and line-oriented for parser stability.

```powershell
powershell -NoExit -ExecutionPolicy Bypass -File .\windows-self-check.ps1
powershell -ExecutionPolicy Bypass -File .\setup-windows-chrome-cdp.ps1 -DryRun
powershell -ExecutionPolicy Bypass -File .\setup-windows-chrome-cdp.ps1
powershell -ExecutionPolicy Bypass -File .\teardown-windows-chrome-cdp.ps1 -DryRun
powershell -ExecutionPolicy Bypass -File .\teardown-windows-chrome-cdp.ps1
```

## Windows portproxy commands

```powershell
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=9223 connectaddress=127.0.0.1 connectport=9222
netsh interface portproxy show all
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=9223
```

## Windows firewall commands

```powershell
netsh advfirewall firewall add rule name="ChromeCDP9223" dir=in action=allow protocol=TCP localport=9223
netsh advfirewall firewall show rule name="ChromeCDP9223"
netsh advfirewall firewall delete rule name="ChromeCDP9223"
```

## WSL validation commands

```bash
curl --connect-timeout 3 --max-time 5 http://172.17.32.1:9223/json/version
curl --connect-timeout 3 --max-time 5 http://172.17.32.1:9223/json/list
```

## Preflight

Run this first from the skill root directory:

```bash
bash ./scripts/self-check.sh
```

If dependencies are missing and the user confirms installation, use:

```bash
sudo apt update
sudo apt install -y jq curl iproute2
```

## Recovery scripts

Run these **from the skill root directory**:

```bash
bash ./scripts/update-openclaw-remote-cdp.sh --dry-run
bash ./scripts/update-openclaw-remote-cdp.sh --apply --set-default
bash ./scripts/show-openclaw-remote-cdp.sh
```

## OpenClaw validation commands

```bash
openclaw gateway restart
openclaw browser profiles
openclaw browser --browser-profile remote status
openclaw browser --browser-profile remote tabs
openclaw browser --browser-profile remote open https://example.com
openclaw browser --browser-profile remote snapshot
openclaw browser --browser-profile remote navigate https://example.org
```
````

## File: skill-wsl2-windows-chrome-remote-cdp/references/promo.pptx
size: 43877
sha: 5f6cae4f668d1cb24f7e532be38c7be06766521d
upstream: https://github.com/andytane/wsl2-windows-chrome-remote-cdp/blob/main/skill-wsl2-windows-chrome-remote-cdp/references/promo.pptx

Content is not inlined in the catalog. Read the upstream file: https://github.com/andytane/wsl2-windows-chrome-remote-cdp/blob/main/skill-wsl2-windows-chrome-remote-cdp/references/promo.pptx

## File: skill-wsl2-windows-chrome-remote-cdp/references/runbook.md
size: 11626
sha: 1422dbc21f9aca69eb35c9364ac006c13ba942a4
upstream: https://github.com/andytane/wsl2-windows-chrome-remote-cdp/blob/main/skill-wsl2-windows-chrome-remote-cdp/references/runbook.md

````text
# Runbook

See the packaged executable procedure below.

---

# OpenClaw WSL2 → Windows Chrome Remote CDP Runbook（脱敏版，可执行）

## 1. 目标

本说明用于让其他维护者或 Agent **快速理解、复现并维护**如下工作链路：

- OpenClaw Gateway 运行在 **WSL2 Ubuntu** 中
- 被控制的浏览器运行在 **Windows Chrome** 中
- OpenClaw 不直接控制 Linux 本地浏览器
- OpenClaw 通过 **Remote CDP** 控制 Windows Chrome

本文强调：
- 明确配置
- 明确步骤
- 明确命令
- 明确验证点
- 明确排障顺序

## 2. 最终工作链路（一句话）

```text
OpenClaw (WSL2) -> browser profile: remote -> http://172.17.32.1:9223
-> Windows portproxy -> 127.0.0.1:9222 -> Windows Chrome (CDP)
```

关键固定点：

```text
profile = remote
cdpUrl  = http://172.17.32.1:9223
```

## 3. Mermaid 链路图

```mermaid
flowchart LR
    A[WSL2 Ubuntu\nOpenClaw Gateway / CLI] --> B[Browser Profile: remote]
    B --> C[CDP URL\nhttp://172.17.32.1:9223]
    C --> D[Windows portproxy\n0.0.0.0:9223 -> 127.0.0.1:9222]
    D --> E[Windows Chrome\n--remote-debugging-port=9222]
    E --> F[Chrome DevTools Protocol\nTabs / Pages / DOM / JS / Network]
```

## 4. Mermaid 分层结构图

```mermaid
flowchart TB
    subgraph L1[WSL2 Linux侧]
        A1[openclaw CLI]
        A2[openclaw gateway]
        A3[browser profile: remote]
    end

    subgraph L2[WSL2 -> Windows 宿主机访问层]
        B1[Host gateway IP\n172.17.32.1]
        B2[访问端口 9223]
    end

    subgraph L3[Windows 转发层]
        C1[netsh portproxy]
        C2[listen 0.0.0.0:9223]
        C3[forward to 127.0.0.1:9222]
        C4[Windows firewall allow 9223]
    end

    subgraph L4[Windows 浏览器层]
        D1[Chrome]
        D2[remote debugging port 9222]
        D3[DevTools HTTP + WebSocket]
    end

    A1 --> A2 --> A3 --> B1 --> B2 --> C1 --> C2 --> C3 --> C4 --> D1 --> D2 --> D3
```

## 5. Mermaid 数据流图

```mermaid
sequenceDiagram
    participant OC as OpenClaw in WSL2
    participant RP as remote profile
    participant GW as 172.17.32.1:9223
    participant PP as Windows portproxy
    participant CH as Chrome 127.0.0.1:9222

    OC->>RP: 选择 profile=remote
    RP->>GW: GET /json/version
    GW->>PP: 命中 9223 转发口
    PP->>CH: 转发到 127.0.0.1:9222
    CH-->>PP: 返回 Browser / webSocketDebuggerUrl
    PP-->>GW: 回传
    GW-->>RP: 回传
    RP->>GW: WebSocket /devtools/browser/<id>
    GW->>PP: 转发 WebSocket
    PP->>CH: 进入 Chrome DevTools Protocol
    CH-->>PP: 返回 tabs / pages / DOM / JS / navigation 结果
    PP-->>GW: 回传
    GW-->>RP: 回传
    RP-->>OC: 浏览器控制成功
```

## 6. 关键配置

### 6.1 OpenClaw JSON 配置片段

文件：

```text
~/.openclaw/openclaw.json
```

关键配置片段：

```json
{
  "browser": {
    "enabled": true,
    "defaultProfile": "remote",
    "profiles": {
      "remote": {
        "cdpUrl": "http://172.17.32.1:9223",
        "attachOnly": true,
        "color": "#00AA00"
      }
    }
  }
}
```

## 7. 可执行步骤（按顺序）

### Step 0：[WSL Terminal] 定位 skill 根目录

WSL 默认终端起点可能是：

```bash
pwd
```

很多情况下会看到类似：

```text
/mnt/c/Windows/system32
```

不要在这个目录直接运行 skill 脚本。先定位 skill：

```bash
find ~ -type d -name 'wsl2-windows-chrome-remote-cdp' 2>/dev/null
```

进入其中一个结果：

```bash
cd "$(find ~ -type d -name 'wsl2-windows-chrome-remote-cdp' 2>/dev/null | head -n 1)"
```

确认当前目录：

```bash
pwd
ls
```

预期至少能看到：

```text
SKILL.md
references/
scripts/
```

### Step 0.5：[WSL Terminal] 执行前置自检

在 **skill 根目录** 执行：

```bash
bash ./scripts/self-check.sh
```

说明：
- 文档默认使用 `bash ./scripts/...`，避免脚本执行位丢失时出现 `Permission denied`
- 如果你已经确认脚本有执行权限，也可以直接用 `./scripts/...`

它会检查：
- 当前目录是否真的是 skill 根目录
- `ip` / `awk` / `curl` / `jq` / `openclaw` 是否可用
- 如果缺 `jq` 等依赖，会直接打印安装命令

### Step 0.6：[WSL Terminal] 缺依赖时的推荐交互（面向小白用户）

如果前置检查发现缺依赖，不要只把安装命令丢给用户就结束。

推荐的 Agent 交互应该是：

1. 用通俗语言解释缺了什么
2. 说明这会阻塞哪一步
3. 问用户是否要代装
4. 如果用户回复 `YES`，直接执行安装
5. 安装完成后，自动继续 `self-check` 和后续恢复流程

Ubuntu / WSL 常用安装命令：

```bash
sudo apt update
sudo apt install -y jq curl iproute2
```

如果只有 `jq` 缺失，也可以更小粒度安装：

```bash
sudo apt update
sudo apt install -y jq
```

### Windows Step W0：[Windows PowerShell] 定位 skill 根目录

在 Windows PowerShell 中，先确认当前目录：

```powershell
Get-Location
```

注意：如果 skill 实际放在 WSL Linux 文件系统里，直接用下面这条命令在 Windows 用户目录下递归搜索，**通常找不到**：

```powershell
Get-ChildItem -Path $HOME -Recurse -Directory -Filter wsl2-windows-chrome-remote-cdp -ErrorAction SilentlyContinue
```

因为它只会搜 Windows 用户目录，不会自动枚举 `\\wsl$\...` 下的 Linux 文件系统。

更稳的做法：

#### 方式 A：先在 WSL 里输出 skill 路径，再切到对应的 `\\wsl$` 路径

在 **WSL Terminal** 中执行：

```bash
pwd
find ~ -type d -name 'wsl2-windows-chrome-remote-cdp' 2>/dev/null | head -n 1
```

然后在 **Windows PowerShell** 中手动进入类似这样的路径：

```powershell
Set-Location "\\wsl$\Ubuntu-24.04\home\<linux-user>\.openclaw\workspace\skills\wsl2-windows-chrome-remote-cdp"
```

#### 方式 B：如果你已经在 `\\wsl$` 里打开了 skill 目录，直接继续

进入 skill 根目录后，再确认：

```powershell
Get-Location
Get-ChildItem
```

预期至少能看到：
- `SKILL.md`
- `references`
- `scripts`

### Windows Step W0.5：[Windows PowerShell] 执行 Windows 前置自检

优先建议：**先把 Windows 侧 `.ps1` 脚本复制到 Windows 本地目录，再执行。**

原因：
- 在部分环境里，直接从 `\\wsl$\...` 路径执行 PowerShell 脚本，可能出现解析/缓存/路径兼容性异常
- 将脚本放到 Windows 本地目录（例如桌面或 `C:\temp\wsl2-windows-chrome-remote-cdp`）后再执行，更稳

例如先把下面两个文件复制到 Windows 本地目录：
- `windows-self-check.ps1`
- `setup-windows-chrome-cdp.ps1`

然后在 **已有的 Windows PowerShell 控制台** 中，`Set-Location` 到那个 Windows 本地目录，再执行：

```powershell
powershell -NoExit -ExecutionPolicy Bypass -File .\windows-self-check.ps1
```

它会检查：
- Chrome 路径是否存在
- `127.0.0.1:9222/json/version` 是否可达
- `127.0.0.1:9222/json/list` 是否可达
- `portproxy` 是否存在
- `firewall` 规则是否存在
- 最终输出 `READY` 或 `NOT READY`

这版脚本故意保持极简：
- 不做复杂对象组装
- 不做复杂格式化
- 优先保证在 Windows PowerShell 中可解析、可执行、可读输出

注意：
- 不要依赖双击 `.ps1` 文件或从 `\\wsl$` 路径直接点开脚本来观察输出
- 这类方式经常会出现“窗口瞬间打开又关闭”的体验，看起来像“闪退”
- 应在一个已经打开的 Windows PowerShell 控制台里执行，并加 `-NoExit` 保持窗口不自动关闭

### Step 1：在 Windows 启动 Chrome 调试端口 9222

```powershell
& 'C:\Program Files\Google\Chrome\Application\chrome.exe' --remote-debugging-port=9222
```

### Step 2：在 Windows 本机确认 9222 确实可用

```powershell
curl http://127.0.0.1:9222/json/version
curl http://127.0.0.1:9222/json/list
netstat -ano | findstr 9222
```

### Step 3：在 Windows 建立 9223 → 9222 的 bridge（两种方式）

#### 方式 A：手工执行 netsh（最直接）

```powershell
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=9223 connectaddress=127.0.0.1 connectport=9222
```

查看：

```powershell
netsh interface portproxy show all
```

删除：

```powershell
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=9223
```

#### 方式 B：执行 skill 自带 PowerShell 脚本（推荐给重启后恢复）

```powershell
powershell -ExecutionPolicy Bypass -File .\scripts\setup-windows-chrome-cdp.ps1
```

这个脚本会自动：
- 启动 Chrome 9222
- 验证 `127.0.0.1:9222/json/version`
- 建立 `9223 -> 127.0.0.1:9222`
- 增加 firewall 规则

推荐顺序（在 Windows 本地目录中执行）：

```powershell
powershell -ExecutionPolicy Bypass -File .\windows-self-check.ps1
powershell -ExecutionPolicy Bypass -File .\setup-windows-chrome-cdp.ps1 -DryRun
powershell -ExecutionPolicy Bypass -File .\setup-windows-chrome-cdp.ps1
powershell -ExecutionPolicy Bypass -File .\windows-self-check.ps1
```

如果只想看 teardown 将执行什么，而不真正删除：

```powershell
powershell -ExecutionPolicy Bypass -File .\teardown-windows-chrome-cdp.ps1 -DryRun
```

### Step 4：在 Windows 放行 9223 防火墙规则

```powershell
netsh advfirewall firewall add rule name="ChromeCDP9223" dir=in action=allow protocol=TCP localport=9223
```

查看：

```powershell
netsh advfirewall firewall show rule name='ChromeCDP9223'
```

删除：

```powershell
netsh advfirewall firewall delete rule name="ChromeCDP9223"
```

如需整体回收 bridge，可执行：

```powershell
powershell -ExecutionPolicy Bypass -File .\scripts\teardown-windows-chrome-cdp.ps1
```

### Step 5：[WSL Terminal] 验证 9223 是否已打通

```bash
curl --connect-timeout 3 --max-time 5 http://172.17.32.1:9223/json/version
curl --connect-timeout 3 --max-time 5 http://172.17.32.1:9223/json/list
```

### Step 6：[WSL Terminal] 重启后自动恢复 remote CDP（推荐）

**前提：你已经完成 Step 0 和 Step 0.5，并且当前就在 skill 根目录。**

也就是说，下面这些命令都默认假设你的当前目录是：

```text
wsl2-windows-chrome-remote-cdp/
```

在这个前提下，优先使用 skill 自带脚本，而不是每次手工改 JSON：

```bash
bash ./scripts/update-openclaw-remote-cdp.sh --dry-run
bash ./scripts/update-openclaw-remote-cdp.sh --apply --set-default
```

如果你只是想快速看当前宿主机 IP 与推导出来的 CDP URL：

```bash
bash ./scripts/show-openclaw-remote-cdp.sh
```

说明：
- 文档默认使用“**在 skill 目录下执行**”这一约定
- 这样不依赖具体用户名、家目录或安装路径
- 无论 skill 被放在 `~/skills/...`、工作区目录、仓库目录，还是别的位置，只要进入 skill 根目录，命令都成立

`~/bin` 复制方式只是一种可选的长期使用优化，不是默认步骤，也不是功能前提。

### Step 7：[WSL Terminal] 确认 OpenClaw 配置已指向 remote CDP

```bash
grep -n 'defaultProfile\|cdpUrl\|attachOnly' ~/.openclaw/openclaw.json
```

### Step 8：[WSL Terminal] 重启 OpenClaw Gateway

```bash
openclaw gateway restart
```

### Step 9：[WSL Terminal] 验证 OpenClaw 已接上 remote profile

```bash
openclaw browser profiles
openclaw browser --browser-profile remote status
```

### Step 10：[WSL Terminal] 验证 OpenClaw 对 Windows Chrome 的控制能力

```bash
openclaw browser --browser-profile remote tabs
openclaw browser --browser-profile remote open https://example.com
openclaw browser --browser-profile remote snapshot
openclaw browser --browser-profile remote navigate https://example.org
```
````

## File: skill-wsl2-windows-chrome-remote-cdp/references/troubleshooting.md
size: 4316
sha: 5d27e134e20968eb81b50f8dd46411fc48ea3002
upstream: https://github.com/andytane/wsl2-windows-chrome-remote-cdp/blob/main/skill-wsl2-windows-chrome-remote-cdp/references/troubleshooting.md

````text
# Troubleshooting

## Fast triage order

0. Run `bash ./scripts/self-check.sh` from the skill root directory.
1. If dependencies are missing, explain the block in plain language, ask whether to install them, and continue automatically after explicit confirmation such as `YES`.
2. Verify Windows local Chrome CDP on `127.0.0.1:9222`.
3. Verify Windows portproxy and firewall for `9223`.
4. Verify WSL2 can reach `http://172.17.32.1:9223/json/version`.
5. Verify OpenClaw remote profile config.
6. Verify OpenClaw browser actions.

## If Windows `9222` fails

Problem is in Windows Chrome startup or local listener state.

Commands:

```powershell
curl http://127.0.0.1:9222/json/version
netstat -ano | findstr 9222
```

## If dependencies are missing in WSL

Do not end with raw install commands only. Preferred handling for an agent:

1. Explain what is missing and why it matters.
2. Ask whether to install it automatically.
3. On explicit confirmation like `YES`, run the install command.
4. Re-run `bash ./scripts/self-check.sh`.
5. Resume the blocked recovery step automatically.

Typical install command:

```bash
sudo apt update
sudo apt install -y jq curl iproute2
```

## If Windows-side state is unknown

Note: earlier versions of the Windows self-check script became too complex and regressed from “runnable but imperfect” to `ParserError`. The current version intentionally follows a much simpler structure validated against a known-good user-tested variant: straight-line checks, simple string matching, and minimal formatting. Parsing stability takes priority over pretty output.

### Windows PowerShell scripting rules learned from this incident

When writing Windows-side helper scripts for end users, especially on Windows PowerShell 5.x and localized systems:

1. Prefer the smallest syntax subset that gets the job done.
2. Prefer straight-line checks over helper-heavy abstractions.
3. Avoid decorative status markers such as `[OK]` / `[MISS]` in output strings.
4. Avoid complex inline expressions and nested `$(if (...) { ... })` inside output objects.
5. Avoid complicated quote nesting and aggressive string composition.
6. Prefer simple double-quoted strings with direct variable interpolation when they remain readable.
7. Prefer “ugly but stable” over “elegant but parser-fragile”.
8. If a script fails with parser errors twice in a row, stop patching incrementally and rewrite it in a more minimal style.

Start with Windows local self-check from the skill root directory:

Before making Windows-side changes, prefer a dry run first:

```powershell
powershell -ExecutionPolicy Bypass -File .\setup-windows-chrome-cdp.ps1 -DryRun
powershell -ExecutionPolicy Bypass -File .\teardown-windows-chrome-cdp.ps1 -DryRun
```

```powershell
powershell -ExecutionPolicy Bypass -File .\scripts\windows-self-check.ps1
```

If it prints `NOT READY`, run:

```powershell
powershell -ExecutionPolicy Bypass -File .\scripts\setup-windows-chrome-cdp.ps1
powershell -ExecutionPolicy Bypass -File .\scripts\windows-self-check.ps1
```

## If Windows `9222` works but WSL `9223` fails

Problem is in portproxy, firewall, or WSL-to-host path.

Preferred recovery:

```powershell
powershell -ExecutionPolicy Bypass -File .\scripts\setup-windows-chrome-cdp.ps1
powershell -ExecutionPolicy Bypass -File .\scripts\windows-self-check.ps1
```

Commands:

```powershell
netsh interface portproxy show all
netsh advfirewall firewall show rule name="ChromeCDP9223"
```

```bash
curl --connect-timeout 3 --max-time 5 http://172.17.32.1:9223/json/version
```

## If WSL `9223` works but OpenClaw remote fails

From the skill root directory, first run the recovery script in dry-run mode, then apply mode if the derived host IP/CDP URL are correct.

```bash
bash ./scripts/update-openclaw-remote-cdp.sh --dry-run
bash ./scripts/update-openclaw-remote-cdp.sh --apply --set-default
```

Problem is in OpenClaw browser config or wrong profile usage.

Commands:

```bash
openclaw browser profiles
openclaw browser --browser-profile remote status
grep -n 'defaultProfile\|cdpUrl\|attachOnly' ~/.openclaw/openclaw.json
```

## If remote is connected but one action fails

Do not confuse action failure with transport failure.

Example: screenshot timeout can happen even when remote CDP transport is already healthy.
````

## File: skill-wsl2-windows-chrome-remote-cdp/references/wait-patterns.md
size: 4057
sha: 35e0b9e34c99921b12ae3ff7b0a27186cb5601a6
upstream: https://github.com/andytane/wsl2-windows-chrome-remote-cdp/blob/main/skill-wsl2-windows-chrome-remote-cdp/references/wait-patterns.md

````text
# Wait Patterns for Browser Automation

本文档整理 OpenClaw browser 等待模式，借鉴 agent-browser 的分类方式，适配当前 remote CDP 链路。

---

## 等待模式分类

### 1. 等待元素出现

```bash
# 等待特定文本出现
openclaw browser wait --text "Welcome"

# 等待 CSS 选择器匹配的元素
openclaw browser wait --selector ".dashboard-loaded"

# 等待 ref 对应的元素（先用 snapshot 查看 refs）
openclaw browser wait --selector "[ref=e12]"
```

---

### 2. 等待时间

```bash
# 等待固定毫秒
openclaw browser wait 3000
```

**适用场景**：
- 简单的动画/过渡
- 不确定其他条件时的兜底

**不推荐**作为首选，因为不够精确。

---

### 3. 等待 URL 变化

```bash
# 等待 URL 包含特定路径
openclaw browser wait --url "**/dashboard"

# 等待 URL 完全匹配
openclaw browser wait --url "https://example.com/home"
```

**适用场景**：
- 导航完成后继续
- 登录跳转后继续

---

### 4. 等待网络空闲

```bash
# 等待网络空闲（推荐）
openclaw browser wait --load networkidle

# 等待 DOM 加载完成
openclaw browser wait --load domcontentloaded

# 等待 load 事件
openclaw browser wait --load load
```

**推荐**：`networkidle` 最稳定，适合大多数 SPA。

---

### 5. 等待 JS 条件

```bash
# 等待全局变量
openclaw browser wait --fn "window.appReady === true"

# 等待元素存在
openclaw browser wait --fn "document.querySelector('.loaded') !== null"

# 等待复杂条件
openclaw browser wait --fn "window.data && window.data.length > 0"
```

**适用场景**：
- 应用自定义就绪信号
- 复杂异步加载完成

---

## 组合等待模式

### 推荐组合

```bash
# 1. 导航后等待网络空闲
openclaw browser navigate https://example.com
openclaw browser wait --load networkidle

# 2. 点击后等待文本出现
openclaw browser click @e12
openclaw browser wait --text "Success"

# 3. 提交后等待 URL 跳转
openclaw browser type @e1 "username"
openclaw browser press Enter
openclaw browser wait --url "**/dashboard"
```

---

## 等待超时处理

默认超时是 30 秒。如需调整：

```bash
openclaw browser --timeout 60000 wait --text "Welcome"
```

---

## 调试技巧

### 1. 先用 snapshot 查看当前状态

```bash
openclaw browser --browser-profile remote snapshot --interactive --limit 100
```

### 2. 检查页面是否已加载

```bash
openclaw browser --browser-profile remote evaluate --fn "document.readyState"
# 应返回 "complete"
```

### 3. 查看当前 URL

```bash
openclaw browser --browser-profile remote evaluate --fn "window.location.href"
```

---

## 常见陷阱

### ❌ 只等待固定时间

```bash
# 不推荐：不够精确，容易失败
openclaw browser wait 5000
openclaw browser click @e12
```

### ✅ 等待明确条件

```bash
# 推荐：等待元素出现后再操作
openclaw browser wait --text "Welcome"
openclaw browser click @e12
```

---

### ❌ 等待不存在的元素

```bash
# 如果选择器错了，会一直超时
openclaw browser wait --selector ".non-existent"
```

### ✅ 先用 snapshot 验证 refs

```bash
openclaw browser snapshot --interactive --limit 100
# 确认元素存在后再等待
```

---

## 最佳实践总结

1. **优先等待条件，而不是时间**
2. **导航后先等 `networkidle`**
3. **操作前先用 snapshot 验证元素存在**
4. **复杂场景用 JS 条件等待**
5. **超时时间根据场景调整（默认 30s）**

---

## 与 agent-browser 对比

| 模式 | agent-browser | 当前 OpenClaw |
|------|---------------|---------------|
| 等待元素 | `wait @e2` | `wait --selector "[ref=e2]"` |
| 等待时间 | `wait 1000` | `wait 1000` |
| 等待文本 | `wait --text "Welcome"` | `wait --text "Welcome"` |
| 等待 URL | `wait --url "**/dashboard"` | `wait --url "**/dashboard"` |
| 等待网络 | `wait --load networkidle` | `wait --load networkidle` |
| 等待 JS | `wait --fn "..."` | `wait --fn "..."` |

**结论**：功能基本对齐，语法略有差异。
````

## File: README.md
upstream: https://github.com/andytane/wsl2-windows-chrome-remote-cdp/blob/main/README.md

````text
# 🧩 wsl2-windows-chrome-remote-cdp

> **OpenClaw skill for controlling Windows Chrome from WSL2 via Remote CDP**  
> **面向 WSL2 + Windows Chrome + OpenClaw 的远程 CDP 控制技能**

![Release](https://img.shields.io/badge/release-v0.1.0-blue)
![Platform](https://img.shields.io/badge/platform-WSL2%20%2B%20Windows-4c8bf5)
![Chrome](https://img.shields.io/badge/browser-Windows%20Chrome-34a853)
![OpenClaw](https://img.shields.io/badge/OpenClaw-skill-orange)
![Status](https://img.shields.io/badge/status-user--validated-success)

---

## 🇨🇳 中文简介

这是一个给 **OpenClaw** 使用的技能仓库，解决的是下面这类真实环境问题：

- OpenClaw Gateway 跑在 **WSL2 Ubuntu** 里
- 真正要控制的浏览器是 **Windows 上的 Chrome**
- 本地环境还可能叠加：
  - 代理软件
  - 全局模式
  - 虚拟网卡
  - WSL / Windows 分离网络栈

这个技能把可用链路沉淀成了：

- WSL 侧恢复脚本
- Windows 侧 setup / teardown / self-check
- Mermaid 架构图
- dry-run 检查流程
- 面向小白的执行引导
- 真机踩坑后的排障经验

---

## 🇺🇸 English Overview

This repository contains an **OpenClaw skill** for a real-world split-host browser control scenario:

- OpenClaw Gateway runs inside **WSL2 Ubuntu**
- The actual browser to control is **Google Chrome on Windows**
- The environment may also include:
  - proxy software
  - global proxy mode
  - virtual network adapters
  - split WSL / Windows networking behavior

The skill turns that into a repeatable workflow with:

- WSL-side recovery scripts
- Windows-side setup / teardown / self-check
- Mermaid architecture diagrams
- dry-run flow before mutation
- novice-friendly execution guidance
- troubleshooting notes learned from real debugging

---

## ✨ Key Features / 核心能力

- 🐧 **WSL-side recovery**: refresh OpenClaw remote CDP profile automatically
- 🪟 **Windows-side setup**: create `portproxy` + firewall + Chrome debug port workflow
- 🔍 **Windows self-check**: verify local CDP / bridge / firewall state
- 🧪 **Dry-run support**: preview Windows setup/teardown commands before mutation
- 🧭 **Dual-terminal guidance**: explicitly separates WSL Terminal and Windows PowerShell steps
- 🧯 **Troubleshooting-first design**: optimized for environments with proxy/global-mode/virtual-NIC complexity

---

## 🏗️ Architecture / 架构图

```mermaid
flowchart LR
    A[WSL2 Ubuntu\nOpenClaw Gateway / CLI] --> B[Browser Profile: remote]
    B --> C[CDP URL\nhttp://HOST_IP:9223]
    C --> D[Windows portproxy\n0.0.0.0:9223 -> 127.0.0.1:9222]
    D --> E[Windows Chrome\n--remote-debugging-port=9222]
    E --> F[Chrome DevTools Protocol]
```

---

## 📦 Repository Layout / 仓库结构

```text
repo-root/
├── README.md
└── skill-wsl2-windows-chrome-remote-cdp/
    ├── SKILL.md
    ├── references/
    │   ├── runbook.md
    │   ├── config-snippets.md
    │   └── troubleshooting.md
    └── scripts/
        ├── self-check.sh
        ├── show-openclaw-remote-cdp.sh
        ├── update-openclaw-remote-cdp.sh
        ├── windows-self-check.ps1
        ├── setup-windows-chrome-cdp.ps1
        └── teardown-windows-chrome-cdp.ps1
```

### Why this layout? / 为什么这样组织？

**中文：**
- `README.md` 给人看
- `SKILL.md` 给 OpenClaw / Agent 触发和执行
- 把 skill 放进 `skill-.../` 子目录后，避免 README 和 SKILL 混在一起，减少误读和误加载风险

**English:**
- `README.md` is for humans
- `SKILL.md` is for OpenClaw / agents
- placing the skill under a dedicated `skill-.../` directory reduces accidental mixing between human docs and agent instructions

---

## 🚀 Quick Start / 快速开始

### 1) WSL side / WSL 侧

Enter the skill directory / 进入 skill 目录：

```bash
cd skill-wsl2-windows-chrome-remote-cdp
```

Run preflight / 先跑前置检查：

```bash
bash ./scripts/self-check.sh
```

Refresh remote profile / 刷新 remote 配置：

```bash
bash ./scripts/update-openclaw-remote-cdp.sh --dry-run
bash ./scripts/update-openclaw-remote-cdp.sh --apply --set-default
```

---

### 2) Windows side / Windows 侧

> Recommended: copy `.ps1` files to a local Windows folder first.  
> 建议先把 `.ps1` 文件复制到 Windows 本地目录再执行。

Run self-check / 先做自检：

```powershell
powershell -NoExit -ExecutionPolicy Bypass -File .\windows-self-check.ps1
```

Preview setup / 先 dry-run 看 setup 会做什么：

```powershell
powershell -ExecutionPolicy Bypass -File .\setup-windows-chrome-cdp.ps1 -DryRun
```

Execute setup / 真正执行 setup：

```powershell
powershell -ExecutionPolicy Bypass -File .\setup-windows-chrome-cdp.ps1
```

Preview teardown / 如需回收，先看 teardown dry-run：

```powershell
powershell -ExecutionPolicy Bypass -File .\teardown-windows-chrome-cdp.ps1 -DryRun
```

---

## ✅ Verification Targets / 验证目标

A healthy environment should eventually confirm / 一个健康环境最终应满足：

- Chrome executable exists / Chrome 路径存在
- `127.0.0.1:9222/json/version` reachable
- `127.0.0.1:9222/json/list` reachable
- `portproxy` bridge exists for `9223 -> 127.0.0.1:9222`
- firewall rule exists for `ChromeCDP9223`
- WSL can reach `http://HOST_IP:9223/json/version`
- OpenClaw browser profile `remote` becomes healthy

---

## 🧠 Design Notes / 设计备注

### 中文
- Windows PowerShell 脚本最终采用了**极简、保守、稳定优先**的风格
- 这是经过真实环境反复踩坑后收敛出的结果
- 结论是：**parser stability > elegant abstractions**

### English
- The Windows PowerShell helpers intentionally use a **minimal, parser-stable style**
- This was learned from real debugging iterations
- Final rule: **parser stability > elegant abstractions**

---

## ⚠️ Current Scope / 当前边界

**中文：**
- 当前仓库重点是“让链路跑通并可恢复”
- 不是通用浏览器自动化框架
- 对 Windows 侧，优先保证“能跑、能查、能恢复”，而不是脚本写法漂亮

**English:**
- The repository focuses on making the chain work and recover reliably
- It is not a general browser automation framework
- On the Windows side, operational stability takes precedence over elegant scripting

---

## 🔖 Installation Hint / 安装提示

If OpenClaw installs skills from a folder path, point it to:

```text
skill-wsl2-windows-chrome-remote-cdp/
```

如果 OpenClaw 支持按目录安装 skill，请直接指向：

```text
skill-wsl2-windows-chrome-remote-cdp/
```

---

## 📌 Release Status / 发布状态

- Public repository prepared
- `v0.1.0` tag created
- Windows self-check validated through real user feedback loop

---

## 📄 License

No explicit LICENSE file yet. Add one if you want reuse terms to be explicit.
````
