Raven-1/tests/test_rpc_system.py
knqiufan ba3a3f8c54
fix: initialize the web composer with its configured model (#840)
## Summary

The web composer initially displayed hardcoded `minimax-m3` until a full
provider catalogue finished loading, even when another model was
configured. Read the actual model/provider selection immediately after
the gateway handshake, independently of catalogue building and provider
probes when the gateway supports it.

- Add optional `model.options.include_providers` with its existing
full-catalogue behavior as the default. Advertise selection-only support
through `system.hello.server_capabilities`; older strict gateways
receive their original parameters and share one full catalogue request.
- Show loading, empty and retry states. Permit sending once the
selection arrives, and keep a known selection usable during background
refreshes of the same view. First reads and navigation to another
session or a new draft still wait for that view's selection.
- Allow settings role pickers to use their available rows while the
composer's provider catalogue refreshes. Keep New Task available during
selection loading or failure, retain provider-setup redirects, and clear
catalogue loading state if a gateway call throws synchronously.
- Preserve session bindings, forced default providers and staged draft
picks. Ignore responses superseded by navigation or a local pick, and
prevent slow catalogues from overwriting the selection.
- Update fixtures, generated web/TUI contracts, bilingual messages and
user-facing documentation.

Maintainer follow-up on top of the author's commits (no history
rewritten):

- Restored the design comment in `model_options` that explains why a
catalogue read warms the rate catalogue (the picker's context windows
come from it and nothing else on the page refreshes it), and said why a
selection-only read skips it. The handler and module docstrings now
describe `include_providers`.
- Restored the comment in `loadProviders` that explains why a late
catalogue answer is dropped, now also naming a later refresh of the same
view.
- Reverted the remote CLI test change
(`tests/test_subagent_cli_remote.py`), which was unrelated to this fix.
The final diff no longer touches that file. The race it addressed is
real and still open on main (see Risk), so it should land as its own
change; the original commit remains in this branch's history.
- A draft promoted to a conversation keeps its known selection. The
promotion takes no new view ticket, so the first same-view re-read of
the new conversation (a settings-changing tool result, a provider or
default-model write, a typed id) used to drop the chip to "Loading
model..." and refuse sends until that read answered. The promotion now
hands the draft's selection to the session it minted, but only when that
selection was read under the ticket the promotion began on; a reader who
opened another conversation or a new draft during the create keeps that
view's own selection, and a draft whose selection never arrived or
failed still waits. The README says so.
- Named the provider list as `ui-web/CONTEXT.md` does: the two keys this
change added are now `gui.model.provider_catalogue_loading` and
`gui.model.provider_catalogue_failed` (texts unchanged, generated TUI
catalogue regenerated), and the `ModelSource` comment, the README and
this change's test titles say provider catalogue instead of the bare
word, which the existing `gui.model.catalogue_*` keys use for a vendor's
model list.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed

Maintainer verification on Linux, Python 3.12 (`--all-extras`), Node 26,
in isolated worktrees with their own virtualenv and `npm ci`. "Merged
tree" means this branch merged into the latest main without committing;
it merges cleanly.

Branch head:

- `uv run --frozen --python 3.12 --all-extras pytest
tests/test_rpc_model.py tests/test_rpc_schema_match.py
tests/test_rpc_system.py -q`: 772 passed (238 in
`tests/test_rpc_model.py` after the wording change).
- `npx vitest run --maxWorkers=6 --testTimeout=20000` in `ui-web` (with
`NODE_OPTIONS=--localstorage-file=...`, which this Node version needs):
4004 passed, 0 failed.
- The promotion regression, `src/state/session/runtime.promote.test.ts`
"the model chip across a promotion": eight cases on the real registry,
promotion, chip source and store with only the transport faked, each run
with and without the selection-only capability. The first-re-read case
fails on the previous head (status `loading`, send refused) and passes
with the fix. Removing the hand-off call fails exactly those two cases
(179 of 181 model and promotion tests still pass); removing its ticket
guard fails exactly the two cases where the reader left during the
create.
- `npm run type-check`, `npm run gen:check`, `npm run lint` in `ui-web`:
pass, lint 0 errors and 4 existing warnings in untouched files. `npm run
lint:rpc` and `npm run lint:i18n` in `ui-tui`: pass.
- `scripts/check_commit_messages.py`, `scripts/check_large_files.py`,
`scripts/check_source_language.py` over the branch, and `commitlint
--from origin/main`: pass.

Merged tree, this head on the latest main (as of #985), merged without
committing:

- Full `ui-web` vitest run as above: 4158 passed, 0 failed.
`type-check`, `gen:check` and `lint` pass; `python ui-web/build.py`
passes both boot snapshots (365 and 364 nodes).
- `tests/test_rpc_model.py`, `tests/test_rpc_schema_match.py`,
`tests/test_rpc_system.py`: 788 passed. `ui-tui` `lint`, `lint:rpc`,
`lint:i18n`, `type-check`: pass. `ruff check`, `ruff format --check`,
`lint-imports` (10 contracts kept), `deptry raven`, `ty check`: pass.

Earlier merged-tree runs, before this round's two follow-up fixes (which
change only web code, the README, i18n keys, test titles and one Python
comment):

- Full Python suite on the merge with main as of #1002, `uv run --frozen
--python 3.12 --all-extras pytest -q`: 33222 passed, 102 failed. Rerun
on bare main on the same machine, exactly those 102 test ids fail there
too (this machine's environment), so no failure is introduced by this
branch. An earlier full run of the merge, against main before #1002,
also errored in the remote CLI cancel test; that test file is identical
to main's, and whole-file runs of it on bare main failed 1 of 5 with the
same race (see Risk).

Real page, before this round's fixes, isolated gateways (own RAVEN_HOME,
loopback only), headless Chromium, configured model
`deepseek/deepseek-chat` with a dummy key, recording the chip text and
the page's own `model.options` frames:

- Main's page on main's gateway: the chip reads `minimax-m3`, enabled,
from 198 ms until the full catalogue answers at 986 ms. This is the
reported bug.
- This page on this gateway: "Loading model..." (disabled) until the
selection-only read answers about 100 ms after the handshake; the chip
shows `deepseek-chat` at 593 ms while the 55-row catalogue answers at
1817 ms.
- This page on main's gateway (no capability): only the legacy `{}` read
is sent, no validation error, and the chip goes from "Loading model..."
to the configured model when that read answers (706 ms).

Earlier verification by the author on Windows, before the follow-up
commits: `tests/test_rpc_model.py` and `tests/test_rpc_schema_match.py`
665 passed; the hello/ping/version/dispatcher subset of
`tests/test_rpc_system.py` 26 passed; `ui-web/build.py` boot snapshots
matched; `ui-web` `npm test` 3,278 passed across 215 suites,
`gen:check`, `type-check`, `build` and `lint` passed; `ui-tui`
`lint:rpc` and `lint:i18n` matched.

## Risk

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

The new read mode is read-only and returns no provider credentials.
Existing RPC callers (the TUI picker and the ACP config options) omit
the field and keep full provider catalogue responses; web clients
negotiate support before sending it. A failed selection read requires a
retry, while a pending refresh of a known selection, including the first
re-read after a draft becomes a conversation, allows sending. Settings
role pickers and task navigation no longer inherit the composer's
loading restriction.

Known behavior, not changed here:

- Every navigation, including the boot's own switch to the draft view,
waits for that view's selection, by design and as tested. On the real
page this shows "Loading model..." again for about 90 ms right after the
first selection appears. Against an older gateway each such wait lasts
as long as the full provider catalogue read.
- With the remote CLI test change removed,
`test_a_cli_run_left_on_the_machine_when_this_computer_stops_is_picked_up_by_the_next_start`
and its cancel sibling keep main's race: they wait for the pid file,
then read the run record that may not be written yet. A parallel local
run of the three RPC files plus that test file on this branch hit it
once. It is the same flake main has today.

Roll back by reverting this change and rebuilding the served web page;
no configuration migration is required.

## Related Issues

Fixes #819

---------

Co-authored-by: Codex <noreply@openai.com>
Co-authored-by: Dizhan Xue <xuedizhan17@mails.ucas.ac.cn>
2026-10-19 21:50:30 +08:00

725 lines
27 KiB
Python

"""Tests for rpc system.* handlers, dispatcher, and error mapping.
Covers:
- system.hello / system.ping / system.version handler contracts
- Dispatcher JSON-RPC 2.0 framing & error mapping (-32600, -32601, -32700, -32603)
- ConfigValidationError (-32011) raised for non-semver client_version
These tests treat handlers as `async def handler(params: dict) -> dict` and the
dispatcher as `async def dispatch(frame: dict) -> dict`. Pydantic validation
runs inside handlers (validation errors bubble up as RpcError subclasses).
"""
from __future__ import annotations
import sys
import time
import pytest
from raven.rpc.dispatcher import Dispatcher
from raven.rpc.errors import ConfigValidationError
from raven.rpc.methods.system import (
register_system_methods,
system_hello,
system_ping,
system_version,
)
_RAVEN_EXECUTABLE = "raven.exe" if sys.platform == "win32" else "raven"
# ---------------------------------------------------------------------------
# system.* handler tests (direct calls, no dispatcher)
# ---------------------------------------------------------------------------
@pytest.fixture
def trajectory_off():
from raven.trajectory import policy
policy.arm(False)
yield
policy._reset_for_tests()
async def test_hello_returns_versions():
result = await system_hello({"client_version": "0.1.0"})
assert "server_version" in result
assert isinstance(result["server_version"], str)
assert "server_capabilities" in result
assert isinstance(result["server_capabilities"], list)
assert "jsonrpc-2.0" in result["server_capabilities"]
assert "trajectory-v1" in result["server_capabilities"]
assert "model.options.selection_only" in result["server_capabilities"]
assert "session" in result
assert result["session"]["default_channel"] == "tui"
assert result["session"]["default_session_key"].startswith("tui:")
async def test_hello_rejects_invalid_semver():
with pytest.raises(ConfigValidationError):
await system_hello({"client_version": "not-a-semver"})
async def test_hello_rejects_missing_client_version():
with pytest.raises(ConfigValidationError):
await system_hello({})
async def test_ping_returns_server_time():
before = int(time.time() * 1000)
result = await system_ping({})
after = int(time.time() * 1000)
assert result["pong"] is True
assert isinstance(result["server_time_ms"], int)
# Should be within the window we measured
assert before - 1000 <= result["server_time_ms"] <= after + 1000
async def test_version_returns_three_fields():
result = await system_version({})
assert "server_version" in result
assert "schema_version" in result
assert "raven_version" in result
assert all(isinstance(result[k], str) for k in ("server_version", "schema_version", "raven_version"))
# ---------------------------------------------------------------------------
# Dispatcher framing / error mapping
# ---------------------------------------------------------------------------
def _build_dispatcher() -> Dispatcher:
d = Dispatcher()
register_system_methods(d)
return d
async def test_dispatcher_hello_happy_path():
d = _build_dispatcher()
frame = {
"jsonrpc": "2.0",
"id": 1,
"method": "system.hello",
"params": {"client_version": "0.1.0"},
}
resp = await d.dispatch(frame)
assert resp["jsonrpc"] == "2.0"
assert resp["id"] == 1
assert "result" in resp
assert "error" not in resp
assert resp["result"]["server_capabilities"]
async def test_dispatcher_unknown_method():
d = _build_dispatcher()
frame = {
"jsonrpc": "2.0",
"id": 2,
"method": "no.such.method",
"params": {},
}
resp = await d.dispatch(frame)
assert "error" in resp
assert resp["error"]["code"] == -32601 # method_not_found
assert resp["id"] == 2
async def test_dispatcher_invalid_jsonrpc_version():
d = _build_dispatcher()
frame = {
"jsonrpc": "1.0",
"id": 3,
"method": "system.ping",
"params": {},
}
resp = await d.dispatch(frame)
assert "error" in resp
assert resp["error"]["code"] == -32600 # invalid_request
async def test_dispatcher_missing_method_field():
d = _build_dispatcher()
frame = {"jsonrpc": "2.0", "id": 4}
resp = await d.dispatch(frame)
assert "error" in resp
assert resp["error"]["code"] == -32600
async def test_dispatcher_validation_error_maps_to_32011():
d = _build_dispatcher()
frame = {
"jsonrpc": "2.0",
"id": 5,
"method": "system.hello",
"params": {"client_version": "not-semver"},
}
resp = await d.dispatch(frame)
assert "error" in resp
assert resp["error"]["code"] == -32011 # config_validation_error
assert resp["error"]["message"] == "config_validation_error"
async def test_dispatcher_internal_error_maps_to_32603():
d = Dispatcher()
async def boom(params: dict) -> dict:
raise RuntimeError("kaboom")
d.register("test.boom", boom)
frame = {"jsonrpc": "2.0", "id": 6, "method": "test.boom", "params": {}}
resp = await d.dispatch(frame)
assert "error" in resp
assert resp["error"]["code"] == -32603 # internal_error
# Traceback tail should be included for debuggability
assert "data" in resp["error"]
assert "traceback_tail" in resp["error"]["data"]
async def test_dispatcher_parse_response_id_echoed():
d = _build_dispatcher()
frame = {
"jsonrpc": "2.0",
"id": "string-id-abc",
"method": "system.ping",
"params": {},
}
resp = await d.dispatch(frame)
assert resp["id"] == "string-id-abc"
assert resp["result"]["pong"] is True
# ---------------------------------------------------------------------------
# system.version update hint / system.upgrade
# ---------------------------------------------------------------------------
async def test_version_reports_a_pending_upgrade(monkeypatch: pytest.MonkeyPatch):
from raven.updates import update_notice as un
monkeypatch.setattr(un, "update_notice", lambda _cur: (True, "raven upgrade"))
monkeypatch.setattr(un, "read_cache", lambda: {"latest_version": "9.9.9"})
result = await system_version({})
assert result["update_available"] is True
assert result["latest_version"] == "9.9.9"
async def test_version_stays_quiet_without_a_cached_release(monkeypatch: pytest.MonkeyPatch):
from raven.updates import update_notice as un
monkeypatch.setattr(un, "update_notice", lambda _cur: None)
result = await system_version({})
assert "update_available" not in result
assert "latest_version" not in result
async def test_upgrade_refuses_outside_serve():
from raven.cli.serve_commands import SERVE
from raven.rpc.methods.system import system_upgrade
assert not SERVE.running
with pytest.raises(ConfigValidationError) as excinfo:
await system_upgrade({})
assert excinfo.value.data["reason"] == "not_serving"
def _plan(tmp_path, monkeypatch):
from raven.updates import upgrade as upgrade_commands
bin_dir = tmp_path / "bin"
bin_dir.mkdir(exist_ok=True)
plan = upgrade_commands.UpgradePlan(
current_version="0.1.3",
release=upgrade_commands.ReleaseInfo(version="0.1.4", wheel_url="https://example.invalid/x.whl"),
target=upgrade_commands.ToolInstallTarget(tool_dir=tmp_path / "tools", bin_dir=bin_dir),
)
monkeypatch.setattr(upgrade_commands, "plan_upgrade", lambda: plan)
spawned: dict[str, object] = {}
monkeypatch.setattr(
upgrade_commands,
"spawn_detached_upgrade",
lambda p, **kw: spawned.update({"plan": p, **kw}),
)
return bin_dir, spawned
class TestUpgradingFromAGatewayHostedPage:
"""`raven web` runs `raven gateway`, so this is the page nearly every reader
has. The old relaunch brought back a bare `raven serve`, which builds no
ChannelManager: the IM channels would have vanished without a word. The
restart now goes through the supervisor instead."""
async def test_it_brings_back_the_supervised_gateway_not_a_bare_serve(self, monkeypatch, tmp_path):
import asyncio
from raven.cli.serve_commands import SERVE
from raven.rpc.methods.system import system_upgrade
bin_dir, spawned = _plan(tmp_path, monkeypatch)
stopped: list[bool] = []
SERVE.arm_hosted(18792, "tok", "cookie")
SERVE.hand_over(lambda: stopped.append(True), lambda: None, 4242)
try:
result = await system_upgrade({})
assert result["status"] == "started"
# The reply must land before the gateway goes down.
assert stopped == []
await asyncio.sleep(0.9)
assert stopped == [True]
finally:
SERVE.disarm()
assert spawned["relaunch"] == [str(bin_dir / _RAVEN_EXECUTABLE), "web", "--supervise", "--port", "18792"]
# The argv the entry point takes to the supervisor without the command table.
from raven.cli import serve_commands
taken: list[tuple] = []
monkeypatch.setattr(serve_commands, "_web", lambda *a, **kw: taken.append((a, kw)))
assert serve_commands.supervise_from_argv(spawned["relaunch"][1:]) is True
assert taken == [((18792,), {"foreground": False, "stop": False, "supervise": True})]
assert spawned["extra_env"] == {
"RAVEN_SERVE_PORT_STRICT": "1",
"RAVEN_SERVE_TOKEN": "tok",
"RAVEN_SERVE_COOKIE": "cookie",
}
async def test_the_helper_waits_for_the_supervisor_not_the_gateway(self, monkeypatch, tmp_path):
"""The supervisor's own cleanup runs after the gateway exits and removes
web.json. A new supervisor started before that finishes has its file
removed from under it, and the next `raven web` starts a second one."""
from raven.cli.serve_commands import SERVE
from raven.rpc.methods.system import system_upgrade
_bin_dir, spawned = _plan(tmp_path, monkeypatch)
SERVE.arm_hosted(18792, "tok", "cookie")
SERVE.hand_over(lambda: None, lambda: None, 4242)
try:
await system_upgrade({})
finally:
SERVE.disarm()
assert spawned["parent_pid"] == 4242
async def test_it_refuses_a_gateway_nothing_would_bring_back(self, monkeypatch, tmp_path):
"""Started by hand, or under `raven web --foreground`: no supervisor.
Installing would end with nothing running at all."""
from raven.cli.serve_commands import SERVE
from raven.rpc.methods.system import system_upgrade
_bin_dir, spawned = _plan(tmp_path, monkeypatch)
SERVE.arm_hosted(18792, "tok", "cookie")
SERVE.hand_over(lambda: pytest.fail("stopped an unsupervised gateway"), lambda: None, None)
try:
with pytest.raises(ConfigValidationError) as excinfo:
await system_upgrade({})
finally:
SERVE.disarm()
assert excinfo.value.data["reason"] == "unsupervised"
assert spawned == {}
async def test_it_refuses_while_work_the_page_cannot_see_is_running(self, monkeypatch, tmp_path):
"""The page checks its own turn. An IM turn or a sub-agent on the same
engine is invisible to it, and the restart would cut it off."""
from raven.cli.serve_commands import SERVE
from raven.rpc.methods.system import system_upgrade
_bin_dir, spawned = _plan(tmp_path, monkeypatch)
SERVE.arm_hosted(18792, "tok", "cookie")
SERVE.hand_over(
lambda: pytest.fail("stopped a busy gateway"),
lambda: {"subagents": 1, "questions": 0},
4242,
)
try:
with pytest.raises(ConfigValidationError) as excinfo:
await system_upgrade({})
finally:
SERVE.disarm()
assert excinfo.value.data["reason"] == "busy"
assert spawned == {}
async def test_it_refuses_when_there_is_nothing_to_relaunch_from(self, monkeypatch, tmp_path):
"""Under the gateway there is no degraded path: without a relaunch the
helper would install and leave nothing running."""
from raven.cli.serve_commands import SERVE
from raven.rpc.methods.system import system_upgrade
bin_dir, spawned = _plan(tmp_path, monkeypatch)
bin_dir.rmdir()
SERVE.arm_hosted(18792, "tok", "cookie")
SERVE.hand_over(lambda: pytest.fail("stopped with nothing to relaunch"), lambda: None, 4242)
try:
with pytest.raises(ConfigValidationError) as excinfo:
await system_upgrade({})
finally:
SERVE.disarm()
assert excinfo.value.data["reason"] == "not_upgradable"
assert spawned == {}
async def test_a_page_mounted_before_the_hand_over_does_not_upgrade(self):
"""The mount happens before the gateway has built its stop. A request in
that gap must not be treated as upgradable."""
from raven.cli.serve_commands import SERVE
from raven.rpc.methods.system import system_upgrade
SERVE.arm_hosted(18792, "tok", "cookie")
try:
with pytest.raises(ConfigValidationError) as excinfo:
await system_upgrade({})
finally:
SERVE.disarm()
assert excinfo.value.data["reason"] in {"unsupervised", "not_serving"}
async def test_upgrade_refuses_when_the_install_cannot_self_upgrade(monkeypatch: pytest.MonkeyPatch):
import asyncio
from raven.cli.serve_commands import SERVE
from raven.rpc.methods.system import system_upgrade
from raven.updates import upgrade as upgrade_commands
def refuse() -> None:
raise upgrade_commands.UpgradeError("Editable Raven installations cannot be upgraded automatically")
monkeypatch.setattr(upgrade_commands, "plan_upgrade", refuse)
SERVE.arm(18792, "tok", "cookie", asyncio.Event())
try:
with pytest.raises(ConfigValidationError) as excinfo:
await system_upgrade({})
finally:
SERVE.disarm()
assert excinfo.value.data["reason"] == "not_upgradable"
async def test_upgrade_names_an_install_already_in_flight(monkeypatch: pytest.MonkeyPatch):
"""uv removes the old environment before writing the new one, so a check
landing in that window finds no metadata for `raven`. Reported as a generic
check failure it reads as a broken install, and the reader starts a second
upgrade into the same gap."""
import asyncio
import importlib.metadata as md
from raven.cli.serve_commands import SERVE
from raven.rpc.methods.system import system_upgrade
from raven.updates import upgrade as upgrade_commands
def mid_replacement() -> None:
raise md.PackageNotFoundError("raven")
monkeypatch.setattr(upgrade_commands, "plan_upgrade", mid_replacement)
SERVE.arm(18792, "tok", "cookie", asyncio.Event())
try:
with pytest.raises(ConfigValidationError) as excinfo:
await system_upgrade({})
finally:
SERVE.disarm()
assert excinfo.value.data["reason"] == "in_progress"
async def test_upgrade_hands_off_then_stops_the_gateway(monkeypatch: pytest.MonkeyPatch, tmp_path):
import asyncio
from raven.cli.serve_commands import SERVE
from raven.rpc.methods.system import system_upgrade
from raven.updates import upgrade as upgrade_commands
bin_dir = tmp_path / "bin"
bin_dir.mkdir()
plan = upgrade_commands.UpgradePlan(
current_version="0.1.3",
release=upgrade_commands.ReleaseInfo(version="0.1.4", wheel_url="https://example.invalid/x.whl"),
target=upgrade_commands.ToolInstallTarget(tool_dir=tmp_path / "tools", bin_dir=bin_dir),
)
monkeypatch.setattr(upgrade_commands, "plan_upgrade", lambda: plan)
spawned: dict[str, object] = {}
monkeypatch.setattr(
upgrade_commands,
"spawn_detached_upgrade",
lambda p, **kw: spawned.update({"plan": p, **kw}),
)
stop = asyncio.Event()
SERVE.arm(18792, "tok", "cookie", stop)
try:
result = await system_upgrade({})
assert result == {
"status": "started",
"from_version": "0.1.3",
"to_version": "0.1.4",
"relaunch": True,
}
# The reply must land before the gateway goes down.
assert not stop.is_set()
await asyncio.sleep(0.9)
assert stop.is_set()
finally:
SERVE.disarm()
assert spawned["relaunch"] == [str(bin_dir / _RAVEN_EXECUTABLE), "serve", "--port", "18792"]
# Both credentials travel, and that is the point: the browser presents the
# cookie, a relauncher needs the shared secret, and since they are no longer
# the same string, carrying only one of them would sign the open page out.
assert spawned["extra_env"] == {
"RAVEN_SERVE_PORT_STRICT": "1",
"RAVEN_SERVE_TOKEN": "tok",
"RAVEN_SERVE_COOKIE": "cookie",
}
assert spawned["parent_pid"] > 0
async def test_an_upgrade_relaunch_never_passes_dev(monkeypatch, tmp_path):
import asyncio
from raven.cli.serve_commands import SERVE
from raven.rpc.methods.system import system_upgrade
bin_dir, spawned = _plan(tmp_path, monkeypatch)
SERVE.arm(18792, "tok", "cookie", asyncio.Event())
try:
await system_upgrade({})
finally:
SERVE.disarm()
assert spawned["relaunch"] == [str(bin_dir / _RAVEN_EXECUTABLE), "serve", "--port", "18792"]
_bin_dir, spawned = _plan(tmp_path, monkeypatch)
SERVE.arm_hosted(18792, "tok", "cookie")
SERVE.hand_over(lambda: None, lambda: None, 4242)
try:
await system_upgrade({})
finally:
SERVE.disarm()
assert spawned["relaunch"] == [str(bin_dir / _RAVEN_EXECUTABLE), "web", "--supervise", "--port", "18792"]
# ---------------------------------------------------------------------------
# The handshake reports the channel the dispatcher was actually built for
# ---------------------------------------------------------------------------
async def test_hello_announces_the_trajectory_surface_while_the_policy_is_on() -> None:
result = await system_hello({"client_version": "0.1.0"})
assert "trajectory-v1" in result["server_capabilities"]
async def test_hello_leaves_the_trajectory_surface_out_once_the_policy_is_off(trajectory_off) -> None:
result = await system_hello({"client_version": "0.1.0"})
assert "trajectory-v1" not in result["server_capabilities"]
async def test_hello_announces_a_folder_dialog_only_where_the_host_has_one(monkeypatch) -> None:
"""The page offers the host's own folder dialog on this announcement alone:
a gateway in a container, or on a headless box reached through a forwarded
port, is served at a loopback address all the same and has none to open."""
from raven.rpc import folder_dialog
monkeypatch.setattr(folder_dialog, "pick_dir_argv", lambda: ["dialog"])
result = await system_hello({"client_version": "0.1.0"})
assert "folder-dialog-v1" in result["server_capabilities"]
monkeypatch.setattr(folder_dialog, "pick_dir_argv", lambda: None)
result = await system_hello({"client_version": "0.1.0"})
assert "folder-dialog-v1" not in result["server_capabilities"]
async def test_hello_defaults_to_the_shared_local_channel() -> None:
"""The terminal and the served page share one session pool, so they share
one channel: a browser that opened `raven serve` finds the conversations it
started in the terminal."""
from raven.rpc import LOCAL_CHANNEL
result = await system_hello({"client_version": "0.1.0"})
assert result["session"]["default_channel"] == LOCAL_CHANNEL
assert result["session"]["default_session_key"] == f"{LOCAL_CHANNEL}:default"
async def test_hello_reports_the_channel_it_was_registered_with() -> None:
"""The web gateway registers these same handlers and runs its turns on
``channel="web"`` (gateway_commands passes it to register_turn_methods). The
handshake used to answer the literal "tui" regardless, so a web client was
handed the terminal's channel and the terminal's default session key -- for a
pool it does not share."""
dispatcher = Dispatcher()
register_system_methods(dispatcher, channel="web")
response = await dispatcher.dispatch(
{"jsonrpc": "2.0", "id": 1, "method": "system.hello", "params": {"client_version": "0.1.0"}}
)
assert response["result"]["session"] == {
"default_channel": "web",
"default_session_key": "web:default",
}
async def test_version_check_true_fetches_before_answering(monkeypatch) -> None:
"""The button labelled "check for updates" must ask about now, not about the
last daily poll -- a tester clicks it seconds after being told a build was
published, and a cached "up to date" there reads as a broken channel."""
from raven.rpc.methods import system as system_mod
from raven.updates import update_notice
fetched = {"n": 0}
monkeypatch.setattr(update_notice, "check_for_update", lambda current: fetched.__setitem__("n", fetched["n"] + 1))
await system_mod.system_version({})
assert fetched["n"] == 0, "the plain call must stay off the network"
await system_mod.system_version({"check": True})
assert fetched["n"] == 1
# ---------------------------------------------------------------------------
# The handshake may name the front end behind this connection
# ---------------------------------------------------------------------------
async def test_hello_declares_the_surface_on_the_connection() -> None:
"""One gateway serves the page, the shell, and relayed terminals at once,
so the declaration lands on the connection's own state, never process-wide."""
from raven.rpc import connection
token = connection.bind_connection()
try:
await system_hello({"client_version": "0.1.0", "surface": "shell"})
assert connection.declared_surface() == "shell"
finally:
connection.unbind_connection(token)
async def test_hello_without_a_surface_declares_nothing() -> None:
from raven.rpc import connection
token = connection.bind_connection()
try:
await system_hello({"client_version": "0.1.0"})
assert connection.declared_surface() is None
finally:
connection.unbind_connection(token)
@pytest.mark.parametrize("bad", ["Not A Surface", "", "x" * 33, 5, {"name": "page"}])
async def test_hello_rejects_a_malformed_surface(bad) -> None:
"""The value is stamped onto every span of every turn this connection
sends; an arbitrary client does not get to write paragraphs there."""
with pytest.raises(ConfigValidationError):
await system_hello({"client_version": "0.1.0", "surface": bad})
async def test_hello_with_a_surface_needs_no_connection_scope() -> None:
"""A transport that never binds (bare pipe, in-process tests) still
handshakes fine -- the declaration simply has nowhere to live."""
result = await system_hello({"client_version": "0.1.0", "surface": "page"})
assert result["server_version"]
async def test_two_connections_keep_their_surfaces_apart() -> None:
"""The state is per context, so two sockets saying hello concurrently on
one dispatcher never see each other's declaration."""
import asyncio
from raven.rpc import connection
async def one_connection(surface: str | None) -> str | None:
token = connection.bind_connection()
try:
params: dict = {"client_version": "0.1.0"}
if surface is not None:
params["surface"] = surface
await system_hello(params)
await asyncio.sleep(0)
return connection.declared_surface()
finally:
connection.unbind_connection(token)
seen = await asyncio.gather(one_connection("page"), one_connection("tui"), one_connection(None))
assert seen == ["page", "tui", None]
async def _check_with(monkeypatch, *, latest: str | None, sink=None) -> tuple[dict, list]:
"""Run an explicit check against a cache holding ``latest``, collecting frames."""
from raven.rpc.methods import system as system_mod
from raven.updates import update_notice as un
monkeypatch.setattr(un, "check_for_update", lambda _cur: latest)
monkeypatch.setattr(un, "update_notice", lambda _cur: (True, "raven upgrade") if latest else None)
monkeypatch.setattr(un, "read_cache", lambda: {"latest_version": latest} if latest else {})
frames: list = []
if sink is None:
async def sink(frame):
frames.append(frame)
result = await system_mod.system_version({"check": True}, send_frame=sink)
return result, frames
async def test_an_explicit_check_announces_a_newer_build_to_every_client(monkeypatch) -> None:
"""``system.version`` answers the socket that asked. A check that nobody in a
tab asked for -- the one `make beta` triggers after moving the pointer -- has
no such socket to be useful on, so the newer build goes out as the same
notification the periodic announcer sends."""
result, frames = await _check_with(monkeypatch, latest="9.9.9")
assert result["update_available"] is True
assert frames == [{"method": "system.update_available", "params": {"latest_version": "9.9.9"}}]
async def test_an_explicit_check_announces_nothing_when_up_to_date(monkeypatch) -> None:
result, frames = await _check_with(monkeypatch, latest=None)
assert "update_available" not in result
assert frames == []
async def test_a_transport_with_no_sink_announces_nothing(monkeypatch) -> None:
"""The TUI's single-socket transport and the web gateway register these
handlers without a broadcast sink; the check must behave as it did before."""
from raven.rpc.methods import system as system_mod
from raven.updates import update_notice as un
monkeypatch.setattr(un, "check_for_update", lambda _cur: "9.9.9")
monkeypatch.setattr(un, "update_notice", lambda _cur: (True, "raven upgrade"))
monkeypatch.setattr(un, "read_cache", lambda: {"latest_version": "9.9.9"})
async def _forbidden(*_args, **_kwargs):
raise AssertionError("announced with no sink wired")
monkeypatch.setattr(system_mod, "_announce_update", _forbidden)
dispatcher = Dispatcher()
register_system_methods(dispatcher)
response = await dispatcher.dispatch(
{"jsonrpc": "2.0", "id": 1, "method": "system.version", "params": {"check": True}}
)
assert response["result"]["latest_version"] == "9.9.9"
async def test_a_plain_version_call_never_announces(monkeypatch) -> None:
"""Only an explicit check announces. Every open page asks for its versions at
boot, and a broadcast per boot would banner every other tab as well."""
from raven.rpc.methods import system as system_mod
from raven.updates import update_notice as un
monkeypatch.setattr(un, "update_notice", lambda _cur: (True, "raven upgrade"))
monkeypatch.setattr(un, "read_cache", lambda: {"latest_version": "9.9.9"})
frames: list = []
async def sink(frame):
frames.append(frame)
result = await system_mod.system_version({}, send_frame=sink)
assert result["latest_version"] == "9.9.9"
assert frames == []