# ADR-0002: Runtime.evaluate Result Structure

## Status

Accepted

## Context

Chrome DevTools Protocol's `Runtime.evaluate` returns results in a nested structure:

```json
// CDP response for Runtime.evaluate
{
  "result": {
    "result": {
      "type": "string",
      "value": "actual value here"
    }
  }
}
```

The double nesting (`result.result.value`) is confusing. Early in development, we assumed the simpler structure:

```json
// WRONG assumption
{
  "result": {
    "value": "actual value here"
  }
}
```

## Decision

We handle the full CDP response structure explicitly:

```python
# browser_hybrid/browser.py
def evaluate(self, script: str) -> Any:
    result = self._send_cdp("Runtime.evaluate", {
        "expression": script,
        "returnByValue": True,
    })
    
    # Extract value from nested structure
    # result = {"result": {"result": {"value": ...}}}
    if "exceptionDetails" in result:
        raise CDPError(...)
    
    inner = result.get("result", {})
    value = inner.get("result", {}).get("value")
    return value
```

## Consequences

### Positive

- **Correct behavior** — Matches CDP specification
- **Clear error handling** — Check for `exceptionDetails` at correct level
- **Type safety** — `result.result.type` indicates JS type

### Negative

- **Confusing API** — Users expect `result.value`, not `result.result.value`
- **Documentation complexity** — Need to explain CDP quirks

## Examples

### CDP Response Structure

```javascript
// JavaScript: "hello"
// CDP Response:
{
  "id": 1,
  "result": {
    "result": {
      "type": "string",
      "value": "hello",
      "className": "String",
      "description": "hello"
    }
  }
}
```

### Python Implementation

```python
# Correct extraction
response = await ws.send("Runtime.evaluate", {"expression": "1 + 1"})
# response = {"result": {"result": {"type": "number", "value": 2}}}
value = response["result"]["result"]["value"]  # = 2

# Common mistake (handled by try/except)
# value = response["result"]["value"]  # KeyError!
```

## References

- [CDP Runtime.evaluate](https://chromedevtools.github.io/devtools-protocol/tot/Runtime/#method-evaluate)
- CODE_REVIEW_0.2.6.md — Bug discovery