Raven-1/tests/test_cli_tui_bootstrap.py
Handsome-wzw 7b45527b5b fix(tools): an array sent as its own JSON is still an array
## Summary

Reported as "deliver_files is broken". It is not: **the tool never ran.**

Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered:

```
Error: Invalid parameters for tool 'deliver_files': files should be array
```

What the model sent was the array, spelled as a string:

```json
{"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."}
```

`cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify.

## Type

- [x] Fix
- [ ] Feature

## The edge of the forgiving is the design

When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error.

**Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through.

**A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage.

## Not just deliver_files

Six built-in tools declare an array or object parameter and were all exposed:

| tool | parameter |
|---|---|
| `deliver_files` | `files` |
| `ask_user` | `questions` |
| `image_generate` | `images` |
| `message` | `media` |
| `create_playbook` | `skills` |
| `video_generate` | `params` |

The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch.

## Verification

```
make lint-python    ruff check + ruff format --check, 1850 files
make lint-imports   9 contracts kept, 0 broken
pytest tests/       19,699 passed, 7 failed (all pre-existing, see below)
```

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots -- no user-facing string

**End to end, through the real tool**, with the exact payload that failed five times in production:

```
files sent as:            str -> [{"path": ".../poster.png", "title": "..."}]
returned:                 Delivered 1 file(s): poster.png (72 B).
still "should be array":  False
registered in the store:  True
```

Twelve cases, five mutations, each killing at least one:

| mutation | red |
|---|---|
| drop the whole branch (the old behaviour) | 3 |
| raise instead of falling through on a parse failure | 5 |
| accept the parse whatever type it yielded | 1 |
| do not re-cast the parsed value, so items are not cast | 1 |
| widen the tuple to include `string` | **survived -- unreachable** |

The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so.

**Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own.

## Risk

- [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before
- [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed
- [x] Rollback path is clear -- single-commit revert

## Related Issues

N/A

## Swept

`mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`.

- **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects.
- **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`.
- **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case).
- **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts.
- **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none.
- **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value.
- **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed.

Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text).

## Deliberately not fixed

The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument.

## Moved from !594

Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name.

Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00

540 lines
19 KiB
Python

"""Tests for `raven tui` Typer subcommand."""
from __future__ import annotations
import os
import stat
import sys
from pathlib import Path
import pytest
from typer.testing import CliRunner
from raven.cli.commands import app
runner = CliRunner()
def test_tui_check_node_ok(monkeypatch):
"""When node is on PATH and version >= 22, --check exits 0."""
monkeypatch.setattr(
"raven.cli.tui_commands.find_node",
lambda: ("/usr/bin/node", (22, 5, 0)),
)
monkeypatch.setattr(
"raven.cli.tui_commands.run_subprocess",
lambda *_args, **_kw: 0,
)
result = runner.invoke(app, ["tui", "--check"])
assert result.exit_code == 0, result.output
def test_tui_check_node_missing(monkeypatch):
"""When node not found, --check exits 1 with friendly error."""
monkeypatch.setattr(
"raven.cli.tui_commands.find_node",
lambda: (None, None),
)
result = runner.invoke(app, ["tui", "--check"])
assert result.exit_code == 1
assert "Node" in result.output
assert "raven agent -m" in result.output
def test_tui_check_node_too_old(monkeypatch):
"""When node < 22, --check exits 1."""
monkeypatch.setattr(
"raven.cli.tui_commands.find_node",
lambda: ("/usr/bin/node", (18, 0, 0)),
)
result = runner.invoke(app, ["tui", "--check"])
assert result.exit_code == 1
assert "22" in result.output
def test_tui_color_flag_forwards_to_child_env(monkeypatch):
"""`--color` exports RAVEN_TUI_COLOR for the Node child (read by
colorTier.ts)."""
import os
monkeypatch.delenv("RAVEN_TUI_COLOR", raising=False)
monkeypatch.setattr(
"raven.cli.tui_commands.find_node",
lambda: ("/usr/bin/node", (22, 5, 0)),
)
captured: dict[str, str | None] = {}
monkeypatch.setattr(
"raven.cli.tui_commands.run_subprocess",
lambda *_a, **_k: captured.setdefault("color", os.environ.get("RAVEN_TUI_COLOR")) or 0,
)
result = runner.invoke(app, ["tui", "--check", "--color", "256"])
assert result.exit_code == 0, result.output
assert captured["color"] == "256"
def test_tui_print_colors_uses_no_rpc_spawn(monkeypatch, tmp_path):
"""`--print-colors` is a no-RPC stdio spawn: it must use run_subprocess
(not run_subprocess_with_rpc) and set RAVEN_TUI_PRINT_COLORS."""
import os
dist = tmp_path / "dist"
dist.mkdir()
(dist / "entry.js").write_text("", encoding="utf-8")
monkeypatch.delenv("RAVEN_TUI_PRINT_COLORS", raising=False)
monkeypatch.setattr("raven.cli.tui_commands._UI_TUI_DIR", tmp_path)
monkeypatch.setattr(
"raven.cli.tui_commands.find_node",
lambda: ("/usr/bin/node", (22, 5, 0)),
)
calls = {"plain": False, "rpc": False, "print_colors": None}
def fake_plain(*_a, **_k):
calls["plain"] = True
calls["print_colors"] = os.environ.get("RAVEN_TUI_PRINT_COLORS")
return 0
def fake_rpc(*_a, **_k):
calls["rpc"] = True
return 3
monkeypatch.setattr("raven.cli.tui_commands.run_subprocess", fake_plain)
monkeypatch.setattr("raven.cli.tui_commands.run_subprocess_with_rpc", fake_rpc)
result = runner.invoke(app, ["tui", "--print-colors"])
assert result.exit_code == 0, result.output
assert calls["plain"] is True
assert calls["rpc"] is False
assert calls["print_colors"] == "1"
def test_tui_preview_colors_uses_no_rpc_spawn(monkeypatch, tmp_path):
"""`--preview-colors` is a no-RPC stdio spawn that sets
RAVEN_TUI_COLOR_PREVIEW."""
import os
dist = tmp_path / "dist"
dist.mkdir()
(dist / "entry.js").write_text("", encoding="utf-8")
monkeypatch.delenv("RAVEN_TUI_COLOR_PREVIEW", raising=False)
monkeypatch.setattr("raven.cli.tui_commands._UI_TUI_DIR", tmp_path)
monkeypatch.setattr(
"raven.cli.tui_commands.find_node",
lambda: ("/usr/bin/node", (22, 5, 0)),
)
calls = {"plain": False, "rpc": False, "preview": None}
def fake_plain(*_a, **_k):
calls["plain"] = True
calls["preview"] = os.environ.get("RAVEN_TUI_COLOR_PREVIEW")
return 0
monkeypatch.setattr("raven.cli.tui_commands.run_subprocess", fake_plain)
monkeypatch.setattr(
"raven.cli.tui_commands.run_subprocess_with_rpc",
lambda *_a, **_k: calls.__setitem__("rpc", True) or 3,
)
result = runner.invoke(app, ["tui", "--preview-colors"])
assert result.exit_code == 0, result.output
assert calls["plain"] is True
assert calls["rpc"] is False
assert calls["preview"] == "1"
def test_raven_node_override_no_fallback(monkeypatch, tmp_path):
"""When RAVEN_NODE is set but path missing, find_node returns (None, None)
— must NOT fall back to venv/PATH."""
from raven.cli.tui_commands import find_node
monkeypatch.setenv("RAVEN_NODE", str(tmp_path / "nonexistent-node"))
# Even if VIRTUAL_ENV / PATH would otherwise resolve a working node,
# the explicit override must take precedence and fail closed.
node_path, version = find_node()
assert node_path is None, "RAVEN_NODE override must not fall back to venv/PATH"
assert version is None
def test_find_node_discovers_windows_private_runtime(monkeypatch, tmp_path):
"""The Windows installer unpacks Node from the official zip, whose binary
lives at ``node-v22.x.y-win-x64/node.exe`` rather than ``bin/node``."""
if sys.platform == "win32":
pytest.skip("uses a POSIX fake node executable")
from raven.cli import tui_commands
node_dir = tmp_path / "runtime" / "node-v22.20.0-win-x64"
node_dir.mkdir(parents=True)
node = node_dir / "node.exe"
node.write_text("#!/bin/sh\necho v22.20.0\n", encoding="utf-8")
node.chmod(node.stat().st_mode | stat.S_IXUSR)
monkeypatch.setattr(tui_commands, "_is_windows", lambda: True)
monkeypatch.setenv("RAVEN_HOME", str(tmp_path))
monkeypatch.delenv("RAVEN_NODE", raising=False)
monkeypatch.delenv("VIRTUAL_ENV", raising=False)
monkeypatch.setenv("PATH", "")
node_path, version = tui_commands.find_node()
assert node_path == str(node)
assert version == (22, 20, 0)
def test_find_node_skips_below_min_and_scans_all_path(monkeypatch, tmp_path):
"""A stale < 22 node earlier on PATH must not shadow a newer node later on
PATH: find_node enumerates every PATH entry and returns the first that
meets the minimum, rather than shutil.which's single first hit."""
if sys.platform == "win32":
pytest.skip("uses POSIX fake node executables")
from raven.cli import tui_commands
def make_node(d: Path, ver: str) -> Path:
d.mkdir(parents=True)
p = d / "node"
p.write_text(f"#!/bin/sh\necho v{ver}\n", encoding="utf-8")
p.chmod(p.stat().st_mode | stat.S_IXUSR)
return p
old = make_node(tmp_path / "old", "20.20.1") # earlier on PATH
new = make_node(tmp_path / "new", "26.5.0") # later on PATH
monkeypatch.delenv("RAVEN_NODE", raising=False)
monkeypatch.delenv("VIRTUAL_ENV", raising=False)
monkeypatch.setenv("RAVEN_HOME", str(tmp_path / "no-runtime"))
monkeypatch.setenv("PATH", f"{old.parent}{os.pathsep}{new.parent}")
node_path, version = tui_commands.find_node()
assert node_path == str(new)
assert version == (26, 5, 0)
def test_find_node_reports_below_min_when_nothing_qualifies(monkeypatch, tmp_path):
"""When only a < 22 node exists, find_node returns it (not None) so the
caller can report the real version ('found 20.20.1, need >= 22') instead
of a bare 'not found'."""
if sys.platform == "win32":
pytest.skip("uses a POSIX fake node executable")
from raven.cli import tui_commands
old_dir = tmp_path / "old"
old_dir.mkdir()
old = old_dir / "node"
old.write_text("#!/bin/sh\necho v20.20.1\n", encoding="utf-8")
old.chmod(old.stat().st_mode | stat.S_IXUSR)
monkeypatch.delenv("RAVEN_NODE", raising=False)
monkeypatch.delenv("VIRTUAL_ENV", raising=False)
monkeypatch.setenv("RAVEN_HOME", str(tmp_path / "no-runtime"))
monkeypatch.setenv("PATH", str(old_dir))
node_path, version = tui_commands.find_node()
assert node_path == str(old)
assert version == (20, 20, 1)
def test_dev_npx_derived_from_node_path(monkeypatch, tmp_path):
"""`--dev` mode must derive npx from the validated node_path,
not from PATH — so RAVEN_NODE's version-pin semantics are honored."""
# Lay out a fake node tree: /tmp.../fake-node/bin/{node,npx}
fake_bin = tmp_path / "fake-node" / "bin"
fake_bin.mkdir(parents=True)
fake_node = fake_bin / "node"
fake_npx = fake_bin / "npx"
fake_node.write_text("#!/bin/sh\necho ok\n")
fake_npx.write_text("#!/bin/sh\necho ok\n")
monkeypatch.setattr(
"raven.cli.tui_commands.find_node",
lambda: (str(fake_node), (22, 5, 0)),
)
captured: dict[str, object] = {}
# Interactive `--dev` spawns through run_subprocess_with_rpc; the npx
# derivation logic is shared, so assert the derived binary here.
def fake_run_subprocess_with_rpc(node_path, args, cwd, **_kw):
captured["node_path"] = node_path
captured["args"] = args
captured["cwd"] = cwd
return 0
monkeypatch.setattr(
"raven.cli.tui_commands.run_subprocess_with_rpc",
fake_run_subprocess_with_rpc,
)
# Even if PATH has a different npx, the derived one must win.
monkeypatch.setattr(
"raven.cli.tui_commands.shutil.which",
lambda _name: "/usr/bin/npx",
)
result = runner.invoke(app, ["tui", "--dev"])
assert result.exit_code == 0, result.output
assert captured["node_path"] == str(fake_npx), (
f"Expected --dev to spawn derived npx {fake_npx}, got {captured['node_path']!r}"
)
def test_run_subprocess_returns_child_exit_code(monkeypatch):
"""Verify run_subprocess transparently returns child's exit code."""
from raven.cli.tui_commands import run_subprocess
class FakeProc:
def __init__(self, exit_code):
self._exit_code = exit_code
def wait(self, timeout=None):
return self._exit_code
def send_signal(self, sig):
pass
def fake_popen(*_args, **_kw):
return FakeProc(42)
monkeypatch.setattr("subprocess.Popen", fake_popen)
monkeypatch.setattr("signal.signal", lambda *_a, **_kw: None)
result = run_subprocess("/usr/bin/node", ["dist/entry.js"], Path("/tmp"))
assert result == 42
# ---------------------------------------------------------------------------
# RPC handshake integration
# ---------------------------------------------------------------------------
def test_rpc_handshake_timeout(monkeypatch, tmp_path):
"""When the Node child never sends `system.hello`, the parent must
abort with exit code 3 and a diagnostic stderr message.
We replace `find_node` with a stub so the existing Node discovery path
is bypassed, and replace `run_subprocess_with_rpc` with a stub that
simulates "child spawned, never sent hello → handshake_timeout()".
"""
# Fake dist/entry.js so the build-artifact check passes
fake_ui_dir = tmp_path / "ui-tui"
(fake_ui_dir / "dist").mkdir(parents=True)
(fake_ui_dir / "dist" / "entry.js").write_text("// stub")
monkeypatch.setattr("raven.cli.tui_commands._UI_TUI_DIR", fake_ui_dir)
monkeypatch.setattr(
"raven.cli.tui_commands.find_node",
lambda: ("/usr/bin/node", (22, 5, 0)),
)
# The new helper must return exit_code 3 when the handshake times out.
monkeypatch.setattr(
"raven.cli.tui_commands.run_subprocess_with_rpc",
lambda *_a, **_kw: 3,
)
result = runner.invoke(app, ["tui"])
assert result.exit_code == 3, result.output
def test_rpc_handshake_timeout_helper_real(tmp_path, monkeypatch):
"""End-to-end: invoke the actual `run_subprocess_with_rpc` helper with a
child that exits immediately without ever sending `system.hello` —
the helper must return exit code 3.
Uses `sh -c 'sleep 6'` as a stand-in child: it inherits stdio + FDs but
never writes anything to the request pipe → handshake timeout fires
(we configure a 1s timeout in the test for speed).
"""
from raven.cli import tui_commands
# Override default handshake timeout for fast test
monkeypatch.setattr(tui_commands, "_RPC_HANDSHAKE_TIMEOUT_S", 0.1)
# Child that just sleeps without writing anything.
exit_code = tui_commands.run_subprocess_with_rpc(
"/bin/sh",
["-c", "sleep 6"],
cwd=tmp_path,
forward_signals=False,
)
assert exit_code == 3
# ---------------------------------------------------------------------------
# Unix-socket transport
# ---------------------------------------------------------------------------
#
# These exercise the production-path helper `_spawn_with_rpc_socket` which
# replaces `pass_fds=(3,4)` for the real `raven tui` invocation. The
# `pass_fds` variant is kept for `--check` smoke compat + existing
# Python-only tests above; do NOT remove those.
def test_rpc_socket_env_constants_exposed():
"""Sanity: the production transport exposes the env var names the Node
child reads -- the TCP-loopback address and the auth token."""
from raven.cli import tui_commands
assert tui_commands._RPC_SOCKET_ENV == "RAVEN_RPC_SOCKET"
assert tui_commands._RPC_TOKEN_ENV == "RAVEN_RPC_TOKEN"
def test_production_dispatcher_includes_all_umbrella_methods():
"""Regression: prevent drift between the umbrella registrar and the
production ``run_subprocess_with_rpc`` spawn path.
Bug pattern: a new ``register_*_methods`` helper was added
to the umbrella ``register_aligned_methods``, but ``tui_commands.py``
hand-expanded the umbrella inline and forgot to add the new helper —
so the demo runner had ``slash.exec`` / ``session.status`` /
``complete.{slash,path}`` registered while ``raven tui`` returned
-32601 for the exact same methods.
This test asserts that every method the umbrella registers is also
registered by the production path. Future additions to the umbrella
automatically extend this test.
"""
from raven.rpc.dispatcher import Dispatcher
from raven.rpc.methods import (
register_aligned_methods,
register_aligned_methods_except_system,
)
from raven.rpc.methods.system import (
system_hello,
system_ping,
system_upgrade,
system_version,
)
umbrella = Dispatcher()
register_aligned_methods(umbrella)
umbrella_methods = set(umbrella.methods())
# Mirrors the hand-expanded system.* block in tui_commands.py — keep the two
# in step when either gains a method.
production = Dispatcher()
production.register("system.hello", system_hello)
production.register("system.ping", system_ping)
production.register("system.version", system_version)
production.register("system.upgrade", system_upgrade)
register_aligned_methods_except_system(production)
production_methods = set(production.methods())
assert umbrella_methods == production_methods, (
f"production dispatcher drifted from umbrella; "
f"missing in production: {umbrella_methods - production_methods}; "
f"extra in production: {production_methods - umbrella_methods}"
)
# Explicit sanity: these four methods MUST be present in
# production. These are the ones the dogfood bug surfaced.
for required in ("slash.exec", "session.status", "complete.slash", "complete.path"):
assert required in production_methods, (
f"{required} missing from production dispatcher — `raven tui` will return -32601 for it"
)
def test_confirm_registered_when_broker_present():
"""``confirm.respond`` registers only when a ConfirmBroker is supplied
(mirrors the emitter/turn gate). Without a broker neither the umbrella nor
the production path registers it, so the drift test above stays balanced.
"""
from raven.rpc.confirm_broker import ConfirmBroker
from raven.rpc.dispatcher import Dispatcher
from raven.rpc.methods import register_aligned_methods_except_system
async def _send(_frame):
return None
broker = ConfirmBroker(_send)
without_broker = Dispatcher()
register_aligned_methods_except_system(without_broker)
assert "confirm.respond" not in without_broker.methods()
with_broker = Dispatcher()
register_aligned_methods_except_system(with_broker, confirm_broker=broker)
assert "confirm.respond" in with_broker.methods()
def test_rpc_socket_transport_handshake_ok(tmp_path, monkeypatch):
"""End-to-end: spawn a tiny Python child that connects to the TCP-loopback
address in `RAVEN_RPC_SOCKET`, sends the `RAVEN_RPC_TOKEN` auth line, then
``system.hello`` — the parent helper must complete the handshake and the
child must exit 0.
We use a Python child rather than the real Node demo here so the test
doesn't depend on the ui-tui build artifact; the wire protocol (an auth
line then newline JSON over the socket) is identical regardless of language.
"""
from raven.cli import tui_commands
# Short handshake timeout for fast feedback.
monkeypatch.setattr(tui_commands, "_RPC_HANDSHAKE_TIMEOUT_S", 3.0)
child_src = """
import json, os, socket, sys
host, port = os.environ["RAVEN_RPC_SOCKET"].rsplit(":", 1)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, int(port)))
tok = os.environ.get("RAVEN_RPC_TOKEN")
if tok:
s.sendall((tok + "\\n").encode("utf-8"))
req = {"jsonrpc": "2.0", "id": 1, "method": "system.hello",
"params": {"client_version": "0.1.0"}}
s.sendall((json.dumps(req) + "\\n").encode("utf-8"))
# Read one response frame.
buf = b""
while b"\\n" not in buf:
chunk = s.recv(4096)
if not chunk:
sys.exit(2)
buf += chunk
resp = json.loads(buf.decode("utf-8").splitlines()[0])
assert resp.get("result", {}).get("server_version"), resp
s.close()
sys.exit(0)
"""
exit_code = tui_commands.run_subprocess_with_rpc(
sys.executable,
["-c", child_src],
cwd=tmp_path,
forward_signals=False,
)
assert exit_code == 0, f"expected child to exit 0, got {exit_code}"
def test_rpc_socket_handshake_timeout_when_child_never_connects(tmp_path, monkeypatch):
"""If the spawned child never connects to the unix socket within the
handshake deadline, parent must return exit code 3."""
from raven.cli import tui_commands
monkeypatch.setattr(tui_commands, "_RPC_HANDSHAKE_TIMEOUT_S", 0.1)
# `sleep` ignores the RAVEN_RPC_SOCKET env var — pure timeout path.
exit_code = tui_commands.run_subprocess_with_rpc(
"/bin/sh",
["-c", "sleep 6"],
cwd=tmp_path,
forward_signals=False,
)
assert exit_code == 3
# ---------------------------------------------------------------------------
# Imports for the socket tests above
# ---------------------------------------------------------------------------
import sys # noqa: E402 (kept at file bottom for the late-added tests)