diff --git a/AGENTS.md b/AGENTS.md index 027b4e643..11e86e859 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -476,6 +476,7 @@ Fields live in `~/.codex/ucode.config.toml` and `/etc/codex/managed_config.toml` | `mcp_servers` | Ignore | Merge | Managed file; add/update the config's MCP server entries, other entries left alone. A same-name entry in `~/.codex/config.toml` of the other transport (stdio vs HTTP) is removed, since Codex would merge the two into an invalid entry | | Smart Router and Smart Router Orchestrator hooks | Merge | Merge | Launch-only `PreToolUse`, plus `UserPromptSubmit` and compact `SessionStart` with `ENABLE_SMART_ROUTER_ORCHESTRATOR=1`; Codex combines them with its native hook sources and applies project trust; `features.hooks` is enabled for a smart-routed launch | | Native v2 collaboration | Launch-only (-c), never written | Launch-only (-c), never written | `features.multi_agent_v2.non_code_mode_only=false` and matching `root_agent_usage_hint_text` / `subagent_usage_hint_text` override saved values for the session; only for smart routing on Codex 0.171.0 or newer. User config files, general developer instructions, and native delegation-mode controls are preserved | +| Smart Router footer | Launch-only (-c), never written | Launch-only (-c), never written | On routed Codex 0.171.0 or newer, enable `features.tui_extensions_statusline`, select `tui.status_line_provider`, and add only `mcp_servers.ug-smart-router-statusline`. The app-server owns the session-local stdio provider; the terminal client receives the feature and selection overrides. Routed launches require stable 0.171.0 or newer through the existing upgrade gate. Saved footer settings and unrelated MCP servers are preserved. The footer relies on that launch gate; do not add a second version probe | | Smart Router native metadata | Launch-only (-c), never written | Launch-only (-c), never written | `responses_api_metadata.smart_router_recipe_name` records the configured recipe. The app-server interposer updates `smart_router_state` per main turn; spawn hooks stamp child task names. Reserve the state key for the interposer; a static config value would override turn updates | diff --git a/README.md b/README.md index 537860782..a85d058eb 100644 --- a/README.md +++ b/README.md @@ -778,6 +778,23 @@ bypass `spawn_agent` have no guaranteed marker. Reserve `smart_router_state` for per-turn metadata; a static Codex `responses_api_metadata` entry with that name would override dynamic values. +Routed Codex terminal sessions show `smart router` with a green `ON` or gray `OFF` +badge beside the current model, directory, and remaining context. The indicator +stays visible when routing is off, as Claude's prompt hint does. The MCP status-line +provider API ships in stable Codex 0.171.0 and still requires its experimental +feature flag, which UG supplies for that launch. + +The indicator reads the same session controls as routing on each refresh, including +after `$smart-router off` and `$smart-router on`. Unreadable controls show +`smart router UNKNOWN` until a later refresh succeeds. Each launch has its own +local provider and controls file. UG enables and selects its footer for that launch +only; saved status-line settings and other MCP servers are preserved. The selected +footer replaces the normal footer's item layout for that session. This does not add +an indicator to the Codex desktop app or other app-server clients. + +For validation and upgrade behavior, see +[Codex Smart Router footer](docs/codex-smart-router-statusline.md). + ### Smart Router Orchestrator Use `SMART_ROUTER_CONFIG_VERSION` at launch to select a smart-routing configuration. diff --git a/docs/codex-smart-router-statusline.md b/docs/codex-smart-router-statusline.md new file mode 100644 index 000000000..1a1033d7a --- /dev/null +++ b/docs/codex-smart-router-statusline.md @@ -0,0 +1,90 @@ +# Codex Smart Router footer + +The terminal footer uses the experimental MCP status-line provider API first +shipped in stable Codex `0.171.0`. UG registers a local stdio provider for each +routed launch and selects it in the terminal client. Both configurations are +launch-only. The provider needs no gateway credentials or network access. +Its MCP tool is visible only to the app, so it is excluded from model-facing tool declarations. + +The indicator reflects the latest session controls, rather than a turn's original +routing attribution. Existing children and an ongoing main turn keep their original +attribution after a toggle. A failed controls read shows `UNKNOWN` without stopping +Codex's polling, so the next successful read can recover. + +The state badge matches Claude's Smart Router banner: bold black `ON` on green, +or bold black `OFF` on gray. Claude keeps an ON/OFF hint below the prompt after its +temporary banner disappears; disabling routing does not hide that hint. Codex keeps +the badge in its persistent footer, since this API only controls the footer. + +## Validation + +Install the checkout in an isolated Python environment and use Codex +`0.171.0` on that environment's PATH. Do not replace the user's +installation as part of automated tests. Check both `codex --version` and `ug --version`. + +Run the offline checks: + +```bash +uv run pytest tests/test_codex_statusline.py tests/test_codex_smart_routing_v2.py \ + tests/test_codex_metadata.py tests/test_agent_codex.py tests/test_smart_router.py \ + tests/test_smart_routing_config.py tests/test_integration_contract.py +just lint +``` + +For a configured test workspace and an explicitly selected profile: + +1. Launch `SMART_ROUTER_CONFIG_VERSION=subagent_only_v0 ug codex`. Check the + native footer shows `smart router` with a green `ON` badge alongside model and project directory. +2. Ask Codex to read a file containing an unpredictable value. Require the correct + value in its completed answer, rather than accepting a startup banner as inference. +3. Submit `$smart-router off`. After the command succeeds, require a gray `OFF` + badge in the footer without restarting the conversation. The indicator stays visible. +4. Submit `$smart-router on` and require `smart router ON` again. Complete another + file task in the same conversation. +5. Open a second session. Toggle one and check the other session's footer is unchanged. +6. Repeat with `first_prompt_and_subagent_no_orch_v0` and complete an initial prompt. +7. Repeat on Windows. Confirm both the app-server and remote terminal receive the + correct configuration, including when paths contain spaces. +8. Compare saved footer preferences and MCP registrations before and after. + Codex may add its own trust and onboarding records, such as + `tui.screen_reader_detection_done`; compare `tui.status_line` and + `tui.status_line_provider` independently of that bookkeeping. +9. With an older client and explicit routing selected, verify the upgrade gate blocks + routed launch until the upgrade succeeds. With managed routing and no explicit + selection, decline the upgrade and require a warning, a completed task, and no footer. + `--disable-smart-routing` retains ordinary launch behavior. + +Existing native routing journeys can be run with pinned stable Codex through +`scripts/run_integration.py --ug-version checkout --codex-version 0.171.0 +--profile --workspace -- -k routing_toggle`. +Those journeys verify inference and session continuity; the footer assertions above +are additional manual UI checks. + +## Stable validation + +On 2026-11-20, native Linux Codex `0.171.0` passed ON/OFF/ON badge rendering and +UNKNOWN/read recovery. An isolated-wheel Arclet run against the supplied workspace +completed five hidden-file tasks across two concurrent sessions and a first-prompt +launch, with installed-skill toggles, unchanged conversation identity, independent +controls, and unchanged saved footer settings and UG profile. GPT-6-Luna was selected +through ordinary user settings. Seven installation checks passed. + +The initial first-prompt routing check returned HTTP 400/downstream 422 and fell +back; its delegated file tasks completed without a recorded routing decision. +Later live Arclet ON/OFF/ON and managed-routing journeys passed with correlated +child-model selection. A separate native plaintext journey verified the exact +assignment and digest at the hook and child. Native Linux and Windows routing CI +subsequently passed. Manual badge-rendering validation remains Linux-only. + +## Required upgrade + +Routed launches require stable Codex `0.171.0` or newer. Earlier builds, including +`0.171.0-alpha.*`, must pass the existing native upgrade flow before starting. +Declining or failing the upgrade blocks routed launch; `--disable-smart-routing` +keeps ordinary launch behavior. `UG_AUTO_UPGRADE_AGENT=1` selects automatic upgrade. +When routing comes from the managed default, an unsuccessful upgrade instead warns +and continues without routing or the footer, with no extra launch flag required. +The footer is registered after that launch gate, without a second version probe. + +Upstream contract and starter: +[create-statusline](https://github.com/openai/codex/blob/rust-v0.171.0/codex-rs/skills/src/assets/samples/create-statusline/SKILL.md). diff --git a/src/ucode/smart_routing/codex_statusline.py b/src/ucode/smart_routing/codex_statusline.py new file mode 100644 index 000000000..513ce06a7 --- /dev/null +++ b/src/ucode/smart_routing/codex_statusline.py @@ -0,0 +1,174 @@ +"""Session-local MCP footer for Codex's experimental status line providers.""" + +from __future__ import annotations + +import json +import os +import sys +from pathlib import Path, PurePosixPath, PureWindowsPath +from typing import Any, TextIO + +from ucode.smart_routing.session_env import SESSION_ENV_VAR, session_routing_enabled + +SERVER_NAME = "ug-smart-router-statusline" +TOOL_NAME = "statusline" +RESOURCE_URI = "ui://ug-smart-router/footer" +STATE_META_KEY = "com.openai/codex-statusline-state" +TOOL = { + "name": TOOL_NAME, + "title": "Unity Gateway Smart Router", + "description": "Show this session's Smart Router state in the Codex footer.", + "inputSchema": {"type": "object", "properties": {}}, + "annotations": {"readOnlyHint": True}, + "_meta": { + "ui": {"visibility": ["app"]}, + "openai/ui": {"entrypoints": [{"type": "statusline", "resourceUri": RESOURCE_URI}]}, + }, +} + + +def launch_config(controls: Path) -> dict: + return { + "features.tui_extensions_statusline": True, + "tui.status_line_provider": {"server": SERVER_NAME, "tool": TOOL_NAME}, + "mcp_servers": { + SERVER_NAME: { + "command": sys.executable, + "args": ["-P", "-X", "utf8", "-m", __name__], + "env": {SESSION_ENV_VAR: str(controls)}, + "enabled": True, + } + }, + } + + +def tui_config(config: dict) -> dict: + return { + key: config[key] + for key in ("features.tui_extensions_statusline", "tui.status_line_provider") + if key in config + } + + +def _object(value: Any) -> dict: + return value if isinstance(value, dict) else {} + + +def _text(value: str, color: str) -> dict: + return {"type": "text", "props": {"color": color}, "children": [value]} + + +def _router_indicator(label: str) -> dict: + if label == "UNKNOWN": + return _text("smart router UNKNOWN", "yellow") + badge = { + "type": "row", + "props": {"gap": 0, "background": "green" if label == "ON" else "#808080"}, + "children": [ + { + "type": "text", + "props": {"color": "black", "weight": "bold"}, + "children": [f" {label} "], + } + ], + } + return { + "type": "row", + "props": {"gap": 1}, + "children": [_text("smart router", "primary"), badge], + } + + +def render(state: dict[str, Any]) -> dict: + controls = os.environ.get(SESSION_ENV_VAR) + try: + if not controls: + raise ValueError("No session controls") + enabled = session_routing_enabled(Path(controls), retry=False) + label = "ON" if enabled else "OFF" + except (OSError, UnicodeError, ValueError): + label = "UNKNOWN" + + thread = _object(_object(state).get("thread")) + model = _object(thread.get("model")) + model_name = model.get("display_name") or model.get("id") or "Codex" + if model.get("reasoning_level"): + model_name += " " + model["reasoning_level"] + children = [_router_indicator(label), _text(model_name, "status-model")] + cwd = _object(thread.get("workspace")).get("cwd") + if cwd: + path = PureWindowsPath(cwd) if "\\" in cwd else PurePosixPath(cwd) + children.append(_text(path.name or str(path), "status-path")) + used = _object(_object(thread.get("usage")).get("context")).get("used_percentage") + if isinstance(used, (int, float)) and not isinstance(used, bool): + remaining = max(0, min(100, round(100 - used))) + children.append(_text(f"{remaining}% context left", "status-usage")) + separated: list = [] + for child in children: + if separated: + separated.append("·") + separated.append(child) + return {"type": "row", "props": {"gap": 1, "wrap": "wrap"}, "children": separated} + + +def respond(method: str, params: dict) -> dict: + if method == "initialize": + return { + "protocolVersion": "2025-06-18", + "capabilities": {"tools": {}, "resources": {}}, + "serverInfo": {"name": SERVER_NAME, "version": "1.0.0"}, + } + if method == "ping": + return {} + if method == "tools/list": + return {"tools": [TOOL]} + if method == "tools/call": + if params.get("name") != TOOL_NAME: + raise ValueError("Unknown tool") + return {"content": [{"type": "text", "text": f"Footer resource: {RESOURCE_URI}"}]} + if method == "resources/list": + return { + "resources": [{"name": "footer", "uri": RESOURCE_URI, "mimeType": "application/json"}] + } + if method == "resources/templates/list": + return {"resourceTemplates": []} + if method == "resources/read": + if params.get("uri") != RESOURCE_URI: + raise ValueError("Unknown resource") + state = params.get("_meta", {}).get(STATE_META_KEY, {}) + return { + "contents": [ + { + "uri": RESOURCE_URI, + "mimeType": "application/json", + "text": json.dumps(render(state)), + } + ] + } + raise KeyError(method) + + +def serve(stdin: TextIO, stdout: TextIO) -> None: + for line in stdin: + reply: dict = {"jsonrpc": "2.0", "id": None} + try: + request = json.loads(line) + if not isinstance(request, dict) or not isinstance(request.get("method"), str): + reply["error"] = {"code": -32600, "message": "Invalid request"} + elif "id" not in request: + continue + else: + reply["id"] = request["id"] + reply["result"] = respond(request["method"], request.get("params", {})) + except json.JSONDecodeError: + reply["error"] = {"code": -32700, "message": "Parse error"} + except KeyError: + reply["error"] = {"code": -32601, "message": "Method not found"} + except (TypeError, ValueError, AttributeError): + reply["error"] = {"code": -32602, "message": "Invalid parameters"} + stdout.write(json.dumps(reply) + "\n") + stdout.flush() + + +if __name__ == "__main__": + serve(sys.stdin, sys.stdout) diff --git a/src/ucode/smart_routing/session_env.py b/src/ucode/smart_routing/session_env.py index 25484ed2b..75343c204 100644 --- a/src/ucode/smart_routing/session_env.py +++ b/src/ucode/smart_routing/session_env.py @@ -73,8 +73,8 @@ def _read_with_retry(path: Path) -> dict[str, str]: time.sleep(CONTROLS_READ_RETRY_SECONDS) -def session_routing_enabled(path: Path) -> bool: - overrides = _read_with_retry(path) +def session_routing_enabled(path: Path, *, retry: bool = True) -> bool: + overrides = _read_with_retry(path) if retry else _read(path) return not all( overrides.get(key) == "0" for key in (ENABLE_SMART_ROUTING_ENV_VAR, ENABLE_SUBAGENT_ROUTING_ENV_VAR) diff --git a/src/ucode/smart_routing/v2.py b/src/ucode/smart_routing/v2.py index 338c80875..d7672ad66 100644 --- a/src/ucode/smart_routing/v2.py +++ b/src/ucode/smart_routing/v2.py @@ -62,7 +62,7 @@ install_skill, uninstall_agent_skill, ) -from ucode.smart_routing import claude_routing, orchestrator, routing, session_log +from ucode.smart_routing import claude_routing, codex_statusline, orchestrator, routing, session_log from ucode.smart_routing.claude_hooks import ( FIRST_PROMPT_SOCKET_ENV, ROUTE_SUBAGENT_MOD_EVENT, @@ -1151,6 +1151,8 @@ def launch_codex( overlay[f"shell_environment_policy.set.{SESSION_PYTHON_ENV_VAR}"] = os.environ[ SESSION_PYTHON_ENV_VAR ] + statusline_config = codex_statusline.launch_config(session_env_path) + config_io.deep_merge_dict(overlay, statusline_config) config_args = codex_config_args(overlay) if app_server_launch: # The caller owns this app-server's address, model and clients, so run its command as is. @@ -1206,7 +1208,15 @@ def launch_codex( ) model_args = [] if has_explicit_model_arg(tool_args) else ["--model", start_model] tui = subprocess_cross_os.popen( - [binary, *provider_args, "--remote", tui_url, *model_args, *tool_args] + [ + binary, + *provider_args, + *codex_config_args(codex_statusline.tui_config(statusline_config)), + "--remote", + tui_url, + *model_args, + *tool_args, + ] ) try: returncode = tui.wait() diff --git a/tests/README.md b/tests/README.md index 29bac0709..576f18a5f 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,5 +1,13 @@ # Test suites and user journeys +`test_codex_statusline.py` covers live control-file reads, Claude-style green ON/gray +OFF badges, ON/OFF/UNKNOWN recovery, nullable snapshots, MCP advertisement and +protocol errors, and two real stdio providers using Python's `-P` flag. +`test_codex_smart_routing_v2.py` also checks the footer's POSIX/Windows app-server +registration, terminal selection, and preservation of unrelated MCP entries. +Native UI and credentialed gateway validation are separate, as described in the +[validation guide](../docs/codex-smart-router-statusline.md). + The Codex smart-routing floor is stable 0.171.0. `test_agent_codex.py` covers the stable boundary, prerelease rejection at the minimum, and slow-probe recovery. `test_codex_smart_routing_v2.py` and `test_cli.py` cover explicit/managed upgrade diff --git a/tests/integration/README.md b/tests/integration/README.md index 8466bf8d7..75a56e676 100644 --- a/tests/integration/README.md +++ b/tests/integration/README.md @@ -1,5 +1,14 @@ # Integration tests +The Codex footer has offline protocol, process-isolation, and launcher coverage in +`../test_codex_statusline.py` and `../test_codex_smart_routing_v2.py`. Those component +checks cover green ON/gray OFF badges, nullable snapshots, Python's `-P` provider +launch flag, and terminal config isolation. Native checks must verify badge colors +and ON/OFF text; OFF stays visible, matching Claude's persistent hint. See the +[footer validation steps](../../docs/codex-smart-router-statusline.md). A native +footer or resource read alone does not establish gateway inference or routed-child +coverage. Windows native footer rendering remains untested. + Routing CI pins stable Codex 0.171.0. Component checks in `../test_agent_codex.py`, `../test_codex_smart_routing_v2.py`, and `../test_cli.py` cover the required version, explicit/managed upgrades, refusal/failure, and routing disable. The managed-default diff --git a/tests/test_codex_smart_routing_v2.py b/tests/test_codex_smart_routing_v2.py index 948794816..849362b69 100644 --- a/tests/test_codex_smart_routing_v2.py +++ b/tests/test_codex_smart_routing_v2.py @@ -3,6 +3,7 @@ import json import os import subprocess +import sys import tomllib from pathlib import Path from types import SimpleNamespace @@ -358,6 +359,11 @@ def start_interposer(*args, **kwargs): monkeypatch.setattr(codex_interposer, "start_interposer_thread", start_interposer) + def render_overlay(*args, **kwargs): + overlay = codex.render_overlay(*args, **kwargs) + overlay["mcp_servers"] = {"other-server": {"command": "other-helper"}} + return overlay + with pytest.raises(SystemExit) as exc: v2.launch_codex( { @@ -369,7 +375,7 @@ def start_interposer(*args, **kwargs): ["--search", *model_args], binary="codex", start_model="gpt-start", - render_overlay=codex.render_overlay, + render_overlay=render_overlay, ) assert exc.value.code == 7 @@ -383,9 +389,9 @@ def start_interposer(*args, **kwargs): "--config", ] assert processes[0].argv[7].startswith("model_providers.Databricks={") - assert processes[0].argv[8] == "--config" - hook_override = processes[0].argv[9] - assert hook_override.startswith("hooks.PreToolUse=[{") + hook_override = next( + arg for arg in processes[0].argv if arg.startswith("hooks.PreToolUse=[{") + ) assert 'matcher = "Agent|.*spawn_agent$"' in hook_override assert "codex-router-hook route-subagent" in hook_override assert f"--host {WS}" in hook_override @@ -394,6 +400,7 @@ def start_interposer(*args, **kwargs): assert "--model system.ai.glm-5-2" in hook_override config_values = processes[0].argv[3:-2:2] config = tomllib.loads("\n".join(config_values)) + assert config["mcp_servers"]["other-server"] == {"command": "other-helper"} assert config["responses_api_metadata"]["smart_router_recipe_name"] == ( v2.routing.configured_router_name() ) @@ -434,6 +441,26 @@ def start_interposer(*args, **kwargs): "--search", *model_args, ] + statusline_args = [ + "--config", + "features.tui_extensions_statusline=true", + "--config", + 'tui.status_line_provider={server = "ug-smart-router-statusline", tool = "statusline"}', + ] + expected_tui_args = [*statusline_args, *expected_tui_args] + assert statusline_args[1] in config_values + assert statusline_args[3] in config_values + server_config = next( + value + for value in config_values + if value.startswith("mcp_servers.ug-smart-router-statusline=") + ) + assert json.dumps(sys.executable) in server_config + assert ( + 'args = ["-P", "-X", "utf8", "-m", "ucode.smart_routing.codex_statusline"]' + in server_config + ) + assert json.dumps(os.environ["UCODE_SESSION_ENV_FILE"]) in server_config if platform_name == "nt": assert tui_argv[:4] == [ "codex", @@ -446,6 +473,8 @@ def start_interposer(*args, **kwargs): else: assert tui_argv == ["codex", *expected_tui_args] assert not any(arg.startswith("hooks.") for arg in tui_argv) + assert not any(arg.startswith("mcp_servers.") for arg in tui_argv) + assert user_config.read_bytes() == saved_config assert interposer_args["args"] == (v2.LOOPBACK_HOST, "ws://127.0.0.1:41001") assert interposer_args["kwargs"]["available_models"] == [ "system.ai.gpt-5-6-sol", diff --git a/tests/test_codex_statusline.py b/tests/test_codex_statusline.py new file mode 100644 index 000000000..c48f80216 --- /dev/null +++ b/tests/test_codex_statusline.py @@ -0,0 +1,275 @@ +"""Offline protocol and session isolation checks for the experimental Codex footer.""" + +import io +import json +import os +import queue +import subprocess +import sys +import threading + +import pytest + +from ucode.constants import ENABLE_SMART_ROUTING_ENV_VAR, ENABLE_SUBAGENT_ROUTING_ENV_VAR +from ucode.smart_routing import codex_statusline as statusline +from ucode.smart_routing.session_env import SESSION_ENV_VAR, set_session_environment, start_session + + +def _labels(tree): + if isinstance(tree, str): + return tree + return " ".join(" ".join(_labels(child) for child in tree.get("children", [])).split()) + + +def _read_lines(stream, replies): + for line in stream: + replies.put(line) + + +def test_launch_config_pins_session_without_credentials(tmp_path): + controls = tmp_path / "controls with spaces.json" + config = statusline.launch_config(controls) + server = config["mcp_servers"][statusline.SERVER_NAME] + assert server["command"] == sys.executable + assert server["args"] == ["-P", "-X", "utf8", "-m", "ucode.smart_routing.codex_statusline"] + assert server["env"] == {SESSION_ENV_VAR: str(controls)} + assert config["features.tui_extensions_statusline"] is True + assert config["tui.status_line_provider"] == { + "server": statusline.SERVER_NAME, + "tool": statusline.TOOL_NAME, + } + + +def test_terminal_config_contains_only_feature_and_selection(tmp_path): + config = statusline.launch_config(tmp_path / "controls.json") + config["server_only"] = "private" + assert statusline.tui_config(config) == { + "features.tui_extensions_statusline": True, + "tui.status_line_provider": { + "server": statusline.SERVER_NAME, + "tool": statusline.TOOL_NAME, + }, + } + assert statusline.tui_config({}) == {} + + +def test_statusline_tool_is_visible_to_the_app_only(): + (tool,) = statusline.respond("tools/list", {})["tools"] + assert tool["_meta"]["ui"]["visibility"] == ["app"] + assert tool["_meta"]["openai/ui"]["entrypoints"] == [ + {"type": "statusline", "resourceUri": statusline.RESOURCE_URI} + ] + + +@pytest.mark.parametrize( + "state", + [ + None, + {"thread": None}, + {"thread": []}, + {"thread": {"model": None}}, + {"thread": {"model": []}}, + {"thread": {"workspace": None}}, + {"thread": {"usage": None}}, + {"thread": {"usage": {"context": None}}}, + ], +) +def test_nullable_snapshots_keep_footer_available(tmp_path, monkeypatch, state): + controls = tmp_path / "controls.json" + controls.write_text("{}") + monkeypatch.setenv(SESSION_ENV_VAR, str(controls)) + reply = statusline.respond( + "resources/read", + {"uri": statusline.RESOURCE_URI, "_meta": {statusline.STATE_META_KEY: state}}, + ) + labels = _labels(json.loads(reply["contents"][0]["text"])) + assert "smart router ON" in labels + assert "Codex" in labels + + +def test_footer_tracks_session_toggles_and_current_thread(tmp_path, monkeypatch): + monkeypatch.setenv(SESSION_ENV_VAR, str(tmp_path / "controls.json")) + (tmp_path / "controls.json").write_text("{}") + state = { + "thread": { + "model": {"display_name": "GPT Test", "reasoning_level": "high"}, + "workspace": {"cwd": "/projects/my-app"}, + "usage": {"context": {"used_percentage": 25}}, + } + } + labels = _labels(statusline.render(state)) + assert "smart router ON" in labels + assert "GPT Test high" in labels + assert "my-app" in labels + assert "75% context left" in labels + set_session_environment( + {ENABLE_SMART_ROUTING_ENV_VAR: "0", ENABLE_SUBAGENT_ROUTING_ENV_VAR: "0"} + ) + assert "smart router OFF" in _labels(statusline.render(state)) + set_session_environment( + {ENABLE_SMART_ROUTING_ENV_VAR: "0", ENABLE_SUBAGENT_ROUTING_ENV_VAR: "1"} + ) + state["thread"]["model"] = {"display_name": "Other thread"} + assert "smart router ON" in _labels(statusline.render(state)) + assert "Other thread" in _labels(statusline.render(state)) + assert "GPT Test" not in _labels(statusline.render(state)) + + +def test_footer_handles_missing_snapshot_and_windows_paths(tmp_path, monkeypatch): + controls = tmp_path / "controls.json" + controls.write_text("{}") + monkeypatch.setenv(SESSION_ENV_VAR, str(controls)) + assert "Codex" in _labels(statusline.render({})) + assert "my-app" in _labels( + statusline.render({"thread": {"workspace": {"cwd": r"C:\projects\my-app"}}}) + ) + + +@pytest.mark.parametrize( + ("enabled", "label", "background"), [(True, "ON", "green"), (False, "OFF", "#808080")] +) +def test_footer_matches_claude_badges(tmp_path, monkeypatch, enabled, label, background): + controls = tmp_path / "controls.json" + controls.write_text( + json.dumps( + { + ENABLE_SMART_ROUTING_ENV_VAR: "0", + ENABLE_SUBAGENT_ROUTING_ENV_VAR: "1" if enabled else "0", + } + ) + ) + monkeypatch.setenv(SESSION_ENV_VAR, str(controls)) + indicator = statusline.render({})["children"][0] + assert _labels(indicator) == f"smart router {label}" + badge = indicator["children"][1] + assert badge["props"] == {"gap": 0, "background": background} + assert badge["children"] == [ + {"type": "text", "props": {"color": "black", "weight": "bold"}, "children": [f" {label} "]} + ] + + +@pytest.mark.parametrize("contents", [None, "not-json", "[]", '{"unrecognized": "1"}']) +def test_unreadable_controls_show_unknown_and_recover(tmp_path, monkeypatch, contents): + controls = tmp_path / "controls.json" + monkeypatch.setenv(SESSION_ENV_VAR, str(controls)) + if contents is not None: + controls.write_text(contents) + assert "smart router UNKNOWN" in _labels(statusline.render({})) + controls.write_text("{}") + assert "smart router ON" in _labels(statusline.render({})) + + +def test_footer_does_not_retry_blocked_file_reads(tmp_path, monkeypatch): + def blocked(*_args, **_kwargs): + raise PermissionError("locked") + + monkeypatch.setenv(SESSION_ENV_VAR, str(tmp_path / "controls.json")) + monkeypatch.setattr(statusline.Path, "read_text", blocked) + monkeypatch.setattr( + "ucode.smart_routing.session_env.time.sleep", lambda _: pytest.fail("slept") + ) + assert "smart router UNKNOWN" in _labels(statusline.render({})) + + +def test_missing_session_controls_never_uses_inherited_on_state(monkeypatch): + monkeypatch.delenv(SESSION_ENV_VAR, raising=False) + monkeypatch.setenv(ENABLE_SMART_ROUTING_ENV_VAR, "1") + assert "smart router UNKNOWN" in _labels(statusline.render({})) + + +def test_stdio_errors_leave_provider_available(): + requests = [ + "not-json", + "[]", + json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}), + json.dumps({"jsonrpc": "2.0", "id": 1, "method": "unknown"}), + json.dumps( + {"jsonrpc": "2.0", "id": 2, "method": "resources/read", "params": {"uri": "other"}} + ), + json.dumps({"jsonrpc": "2.0", "id": 3, "method": "tools/list"}), + ] + output = io.StringIO() + statusline.serve(io.StringIO("\n".join(requests) + "\n"), output) + replies = [json.loads(line) for line in output.getvalue().splitlines()] + assert [reply["error"]["code"] for reply in replies[:-1]] == [-32700, -32600, -32601, -32602] + assert replies[-1]["result"]["tools"][0]["_meta"]["openai/ui"]["entrypoints"] == [ + {"type": "statusline", "resourceUri": statusline.RESOURCE_URI} + ] + + +def test_real_stdio_process_keeps_sessions_separate_and_polls_live_controls(): + processes = [] + try: + for enabled in (True, False): + env = os.environ.copy() + controls = start_session(env) + if not enabled: + controls.write_text( + json.dumps( + {ENABLE_SMART_ROUTING_ENV_VAR: "0", ENABLE_SUBAGENT_ROUTING_ENV_VAR: "0"} + ) + ) + server = statusline.launch_config(controls)["mcp_servers"][statusline.SERVER_NAME] + process = subprocess.Popen( + [server["command"], *server["args"]], + env=env, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + encoding="utf-8", + ) + replies = queue.Queue() + threading.Thread( + target=_read_lines, args=(process.stdout, replies), daemon=True + ).start() + processes.append((process, controls, replies)) + for process, _controls, replies in processes: + process.stdin.write( + json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize"}) + "\n" + ) + process.stdin.flush() + assert json.loads(replies.get(timeout=10))["result"]["capabilities"] == { + "tools": {}, + "resources": {}, + } + for expected in (("ON", "OFF"), ("OFF", "OFF"), ("ON", "OFF")): + for (process, controls, replies), label in zip(processes, expected, strict=True): + if controls == processes[0][1]: + controls.write_text( + json.dumps( + { + ENABLE_SMART_ROUTING_ENV_VAR: "0", + ENABLE_SUBAGENT_ROUTING_ENV_VAR: "1" if label == "ON" else "0", + } + ) + ) + process.stdin.write( + json.dumps( + { + "jsonrpc": "2.0", + "id": 2, + "method": "resources/read", + "params": { + "uri": statusline.RESOURCE_URI, + "_meta": { + statusline.STATE_META_KEY: { + "thread": {"workspace": {"cwd": r"C:\projects\项目目录"}} + } + }, + }, + }, + ensure_ascii=False, + ) + + "\n" + ) + process.stdin.flush() + resource = json.loads(replies.get(timeout=10))["result"]["contents"][0] + assert f"smart router {label}" in _labels(json.loads(resource["text"])) + assert "项目目录" in _labels(json.loads(resource["text"])) + finally: + for process, controls, _replies in processes: + process.terminate() + process.communicate(timeout=5) + controls.unlink() + controls.parent.rmdir()