From 921bf3ab5a0b6f92a5beb8c7082bb597172157e1 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:17:51 +0800 Subject: [PATCH] fix(release): repair dsh closeout test, antigravity failover alias, and release download retry Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../workflows/desktop-release-artifacts.yml | 36 ++++-- .github/workflows/desktop-updater.yml | 11 +- loopx/capabilities/configuration_ui.py | 9 +- .../native_chat/antigravity_adapter.py | 84 ++++++++------ loopx/chat_manager.py | 9 +- .../admission-closeout.integration.spec.ts | 45 +++++--- scripts/chat_bundle.py | 99 ++++++++++++----- .../test_capability_configuration_ui.py | 52 +++++++++ tests/presentation/test_chat_bundle.py | 89 +++++++++++++++ tests/test_antigravity_steward_adapter.py | 60 ++++++++++ tests/test_chat_machine_configuration_api.py | 65 +++++++++++ tests/test_chat_manager_model_adoption.py | 104 ++++++++++++++++++ 12 files changed, 574 insertions(+), 89 deletions(-) diff --git a/.github/workflows/desktop-release-artifacts.yml b/.github/workflows/desktop-release-artifacts.yml index 565a09265e..3d0b489f69 100644 --- a/.github/workflows/desktop-release-artifacts.yml +++ b/.github/workflows/desktop-release-artifacts.yml @@ -340,10 +340,20 @@ jobs: --jq '.assets[].name | select(. == "DESKTOP-SHA256SUMS" or (startswith("LoopX") and (endswith(".dmg") or endswith(".zip") or endswith(".exe") or endswith(".msi"))))' ) for asset in "${assets[@]}"; do - gh release download "${RELEASE_TAG}" \ - --repo "${GITHUB_REPOSITORY}" \ - --pattern "${asset}" \ - --dir dist/previous-desktop + for attempt in 1 2 3 4; do + rm -f "dist/previous-desktop/${asset}" + if gh release download "${RELEASE_TAG}" \ + --repo "${GITHUB_REPOSITORY}" \ + --pattern "${asset}" \ + --dir dist/previous-desktop + then + break + fi + if [[ "${attempt}" -eq 4 ]]; then + exit 1 + fi + sleep "$((1 << (attempt - 1)))" + done done { echo "release_tag=${RELEASE_TAG}" @@ -434,10 +444,20 @@ jobs: "LoopX_${RELEASE_VERSION}_x64_en-US.msi" \ DESKTOP-SHA256SUMS do - gh release download "${RELEASE_TAG}" \ - --repo "${GITHUB_REPOSITORY}" \ - --pattern "${asset}" \ - --dir dist/published-desktop + for attempt in 1 2 3 4; do + rm -f "dist/published-desktop/${asset}" + if gh release download "${RELEASE_TAG}" \ + --repo "${GITHUB_REPOSITORY}" \ + --pattern "${asset}" \ + --dir dist/published-desktop + then + break + fi + if [[ "${attempt}" -eq 4 ]]; then + exit 1 + fi + sleep "$((1 << (attempt - 1)))" + done done python scripts/desktop_release_artifacts.py verify-checksums \ --dist-dir dist/published-desktop \ diff --git a/.github/workflows/desktop-updater.yml b/.github/workflows/desktop-updater.yml index a6eaa65f18..ab1b6dde90 100644 --- a/.github/workflows/desktop-updater.yml +++ b/.github/workflows/desktop-updater.yml @@ -272,7 +272,16 @@ jobs: decision=advance if grep -Fxq desktop-updater.json <<<"$pointer_assets"; then mkdir -p dist/current-pointer - gh release download "$pointer" --pattern desktop-updater.json --dir dist/current-pointer + for attempt in 1 2 3 4; do + rm -f dist/current-pointer/desktop-updater.json + if gh release download "$pointer" --pattern desktop-updater.json --dir dist/current-pointer; then + break + fi + if [ "$attempt" -eq 4 ]; then + exit 1 + fi + sleep "$((1 << (attempt - 1)))" + done decision="$(python scripts/desktop_update_feed.py \ --channel-pointer-decision "$CHANNEL" \ --current-feed dist/current-pointer/desktop-updater.json \ diff --git a/loopx/capabilities/configuration_ui.py b/loopx/capabilities/configuration_ui.py index d6803d4cb0..77ac8dac60 100644 --- a/loopx/capabilities/configuration_ui.py +++ b/loopx/capabilities/configuration_ui.py @@ -242,7 +242,10 @@ def capability_configuration_editor( "string_list", description=( "One authorized executor id per line. Required only for " - "flexible selection; include the primary executor." + "flexible selection; include the primary executor. " + "Optional per-endpoint model and reasoning effort overrides " + "(endpoint_models) are authored in JSON mode and preserved " + "by guided saves." ), ), _field( @@ -252,7 +255,9 @@ def capability_configuration_editor( nullable=True, description=( "Optional model for the selected executor. Leave blank to keep " - "the executor's own default." + "the executor's own default. Configure per-endpoint overrides " + "(endpoint_models: {\"\": {\"model\": ..., " + "\"reasoning_effort\": ...}}) in JSON mode." ), ), _field( diff --git a/loopx/capabilities/native_chat/antigravity_adapter.py b/loopx/capabilities/native_chat/antigravity_adapter.py index f5d989f069..4311d965ca 100644 --- a/loopx/capabilities/native_chat/antigravity_adapter.py +++ b/loopx/capabilities/native_chat/antigravity_adapter.py @@ -474,6 +474,39 @@ def _matching_antigravity_model_config(rows: list[Any], model_id: str) -> list[d ] +def _extract_user_model_quota( + user: Any, + model_id: str, + *, + fallback_rows: list[Any] | None = None, +) -> tuple[str, float, str] | None: + """Validate and extract `(account_ref, remaining_fraction, reset_time)` for one canonical model.""" + if not isinstance(user, Mapping): + return None + account = user.get("email") + if not isinstance(account, str) or not account.strip(): + return None + rows = (user.get("cascadeModelConfigData") or {}).get("clientModelConfigs") + if not isinstance(rows, list): + if fallback_rows is None: + return None + rows = fallback_rows + matching = _matching_antigravity_model_config(rows, model_id) + if len(matching) != 1: + return None + quota = matching[0]["quotaInfo"] + fraction, reset = quota.get("remainingFraction", 0), quota.get("resetTime") + if (type(fraction) not in (int, float) or not math.isfinite(fraction) + or not 0 <= fraction <= 1 or not isinstance(reset, str) + or datetime.fromisoformat(reset).tzinfo is None): + return None + return ( + hashlib.sha256(account.strip().casefold().encode()).hexdigest(), + fraction, + reset, + ) + + def _native_user_input_text(step: dict[str, Any]) -> str | None: """Read the one native text item; any redundant response must agree.""" content = step.get("userInput") @@ -683,6 +716,7 @@ def metadata_review_capacity(*, cascade_id: str, model_id: str) -> dict[str, Any native failure alongside the exact model's quota epoch. """ try: + canonical_model_id, _ = resolve_antigravity_model_placeholder(model_id) found = discover_antigravity_language_server() if found is None: return None @@ -717,25 +751,15 @@ def read(method: str, payload: dict[str, Any]) -> dict[str, Any]: if not normal and not exhausted: return None # An unknown native failure is not capacity evidence. status = read("GetUserStatus", {}) - user = status["userStatus"] - account = user.get("email") - if not isinstance(account, str) or not account.strip(): - return None - rows = user["cascadeModelConfigData"]["clientModelConfigs"] - matching = _matching_antigravity_model_config(rows, model_id) - if len(matching) != 1: - return None - quota = matching[0]["quotaInfo"] - fraction, reset = quota.get("remainingFraction", 0), quota.get("resetTime") - if (type(fraction) not in (int, float) or not math.isfinite(fraction) - or not 0 <= fraction <= 1 or not isinstance(reset, str) - or datetime.fromisoformat(reset).tzinfo is None): + extracted = _extract_user_model_quota(status.get("userStatus"), canonical_model_id) + if extracted is None: return None + account_ref, fraction, reset = extracted after = read("GetCascadeTrajectory", {"cascadeId": cascade_id}) if (after.get("status") != before["status"] or after.get("numTotalSteps") != total or (after.get("trajectory") or {}).get("cascadeId") != cascade_id): return None - return {"model_id": model_id, "account_ref": hashlib.sha256(account.strip().casefold().encode()).hexdigest(), + return {"model_id": canonical_model_id, "account_ref": account_ref, "remaining_fraction": fraction, "reset_time": reset, "execution_id": (latest[0].get("metadata") or {}).get("executionId"), "observed_at": time.time(), "quota_exhausted": exhausted, "normal_completion": normal} @@ -746,35 +770,33 @@ def read(method: str, payload: dict[str, Any]) -> dict[str, Any]: def endpoint_model_capacity( *, model_id: str, + reasoning_effort: str | None = None, env: Mapping[str, str] | None = None, discovered: Mapping[str, Any] | None = None, ) -> dict[str, Any] | None: """Observe the live LS account's quota for one offered model without opening a cascade.""" try: + canonical_model_id, _ = resolve_antigravity_model_placeholder( + model_id, + reasoning_effort, + ) found = discovered or discover_antigravity_language_server(env=env, include_model_config=True) if found is None: return None status = _rpc_post(str(found["url"]), str(found["csrf_token"]), "GetUserStatus", {}, timeout=5.0) - user = status["userStatus"] - account = user.get("email") - if not isinstance(account, str) or not account.strip(): - return None - rows = (user.get("cascadeModelConfigData") or {}).get("clientModelConfigs") - if not isinstance(rows, list): - rows = (found.get("model_config_data") or {}).get("clientModelConfigs") or [] - matching = _matching_antigravity_model_config(rows, model_id) - if len(matching) != 1: - return None - quota = matching[0]["quotaInfo"] - fraction, reset = quota.get("remainingFraction", 0), quota.get("resetTime") - if (type(fraction) not in (int, float) or not math.isfinite(fraction) - or not 0 <= fraction <= 1 or not isinstance(reset, str) - or datetime.fromisoformat(reset).tzinfo is None): + fallback_rows = (found.get("model_config_data") or {}).get("clientModelConfigs") or [] + extracted = _extract_user_model_quota( + status.get("userStatus"), + canonical_model_id, + fallback_rows=fallback_rows if isinstance(fallback_rows, list) else [], + ) + if extracted is None: return None + account_ref, fraction, reset = extracted exhausted = fraction <= 0 return { - "model_id": model_id, - "account_ref": hashlib.sha256(account.strip().casefold().encode()).hexdigest(), + "model_id": canonical_model_id, + "account_ref": account_ref, "remaining_fraction": fraction, "reset_time": reset, "execution_id": f"endpoint-probe:{uuid.uuid4().hex}", diff --git a/loopx/chat_manager.py b/loopx/chat_manager.py index f6214b2e68..0d877ef9d2 100644 --- a/loopx/chat_manager.py +++ b/loopx/chat_manager.py @@ -1008,10 +1008,13 @@ def manager_session_quota_route(controller: Any, session: Mapping[str, Any]) -> else: route = accounts.steward_route(**route_inputs, primary_capacity=None, fallback_capacity=None) if route.get("endpoint") is None: - target_ag_model = manager_model_resolution( + target_ag_config = manager_model_config( clean_environment, endpoint="antigravity", machine_defaults=defaults, - )[0] - capacity = AntigravityAdapter.endpoint_model_capacity(model_id=target_ag_model) + ) + capacity = AntigravityAdapter.endpoint_model_capacity( + model_id=target_ag_config["model"], + reasoning_effort=target_ag_config["reasoning_effort"], + ) if capacity is not None: route = accounts.steward_route( **route_inputs, primary_capacity=None, fallback_capacity=capacity, diff --git a/packages/dsh-loopx-plugin/tests/admission-closeout.integration.spec.ts b/packages/dsh-loopx-plugin/tests/admission-closeout.integration.spec.ts index cd178b7c02..c999adf9de 100644 --- a/packages/dsh-loopx-plugin/tests/admission-closeout.integration.spec.ts +++ b/packages/dsh-loopx-plugin/tests/admission-closeout.integration.spec.ts @@ -283,12 +283,13 @@ function receiptEffectIds(payload: Record): string[] { function executablePlanArgs( steps: readonly Record[], - kind: 'durable_writeback' | 'quota_spend', + kind: 'durable_writeback', replacements: Readonly> = {}, ): string[] { const command = String( steps.find(step => step.kind === kind)?.command_template ?? '', ) + expect(command).not.toBe('') const tokens = command.match(/'[^']*'|"[^"]*"|\S+/gu) ?? [] expect(tokens.shift()).toBe('loopx') const args = tokens.map(token => replacements[token] ?? token.replace(/^(['"])(.*)\1$/u, '$2')) @@ -522,6 +523,7 @@ describe('DSH admission-to-closeout integration', () => { expect(heartbeatReceipt.turn_instance_id).toBe(turnInstanceId) const cliChannel = record(record(guard.payload.interaction_contract).cli_channel) const rawPlan = record(cliChannel.settlement_plan) + expect(rawPlan.schema_version).toBe('quota_settlement_plan_v2') const identity = record(rawPlan.identity) const replayChannel = record(record(guardReplay.payload.interaction_contract).cli_channel) expect(record(record(replayChannel.settlement_plan).identity)).toEqual(identity) @@ -530,16 +532,15 @@ describe('DSH admission-to-closeout integration', () => { expect(identity.todo_id).toBe(todoId) expect(JSON.stringify(rawPlan)).not.toContain('${LOOPX_TURN:?}') const steps = array(rawPlan.ordered_steps).map(record) - const writebackTemplate = String( - steps.find(step => step.kind === 'durable_writeback')?.command_template, - ) - const spendTemplate = String( - steps.find(step => step.kind === 'quota_spend')?.command_template, - ) - for (const command of [writebackTemplate, spendTemplate]) { - expect(command).toContain(`--turn-instance-id ${turnInstanceId}`) - expect(command).toContain(`--todo-id ${todoId}`) - } + const writebackStep = steps.find(step => step.kind === 'durable_writeback') + const spendStep = steps.find(step => step.kind === 'quota_spend') + const writebackTemplate = String(writebackStep?.command_template) + expect(writebackStep?.owner).toBe('agent') + expect(writebackTemplate).toContain(`--turn-instance-id ${turnInstanceId}`) + expect(writebackTemplate).toContain(`--todo-id ${todoId}`) + expect(writebackTemplate).toContain('--settle-turn') + expect(spendStep?.owner).toBe('runtime') + expect(spendStep?.command_template).toBeUndefined() const writeback = await runCli(testFixture, [ ...executablePlanArgs(steps, 'durable_writeback', { @@ -552,15 +553,25 @@ describe('DSH admission-to-closeout integration', () => { ]) expect(writeback.exitCode, JSON.stringify(writeback.payload)).toBe(0) expect(new Set(receiptEffectIds(writeback.payload))).toEqual(new Set([effectId])) + expect( + array(record(writeback.payload.settlement_result).receipts) + .map(receipt => String(record(receipt).step_kind)), + ).toEqual(['validation', 'durable_writeback', 'quota_spend']) - const spendArgs = executablePlanArgs(steps, 'quota_spend') - const spend = await runCli(testFixture, spendArgs) - const spendReplay = await runCli(testFixture, spendArgs) - expect(spend.exitCode).toBe(0) - expect(spendReplay.exitCode).toBe(0) + const spendReplay = await runCli(testFixture, [ + 'quota', 'spend-slot', + '--goal-id', goalId, + '--slots', '1', + '--source', 'heartbeat', + '--execute', + '--todo-id', todoId, + '--agent-id', agentId, + '--turn-instance-id', turnInstanceId, + ]) + expect(spendReplay.exitCode, JSON.stringify(spendReplay.payload)).toBe(0) expect(spendReplay.payload.idempotent_replay).toBe(true) expect(spendReplay.payload.appended).toBe(false) - expect(new Set(receiptEffectIds(spend.payload))).toEqual(new Set([effectId])) + expect(new Set(receiptEffectIds(spendReplay.payload))).toEqual(new Set([effectId])) const closeout = await runCli(testFixture, [ 'todo', 'complete', diff --git a/scripts/chat_bundle.py b/scripts/chat_bundle.py index bb8d881f5d..acb7def125 100644 --- a/scripts/chat_bundle.py +++ b/scripts/chat_bundle.py @@ -14,6 +14,8 @@ import subprocess import sys import tempfile +import time +from typing import Callable, TypeVar import zipfile ROOT = Path(__file__).resolve().parents[1] @@ -224,19 +226,52 @@ def _ensure(previous: Path | None) -> None: ) +_T = TypeVar("_T") + + +def _retry_gh( + operation: Callable[[], _T], + *, + label: str, + attempts: int = 4, + base_delay: float = 1.0, + before_attempt: Callable[[], None] | None = None, +) -> _T: + """Retry transient GitHub CLI failures with bounded exponential backoff.""" + for attempt in range(1, attempts + 1): + if before_attempt is not None: + before_attempt() + try: + return operation() + except subprocess.CalledProcessError as exc: + if attempt >= attempts: + raise + delay = base_delay * (2 ** (attempt - 1)) + print( + f"Retrying {label} after gh exit {exc.returncode} " + f"(attempt {attempt}/{attempts}, sleep {delay:.1f}s)", + file=sys.stderr, + ) + time.sleep(delay) + raise AssertionError("unreachable") + + def release_build(tag: str, repository: str) -> None: # Use the preceding published version, never the latest desktop prerelease # or a future release when rebuilding an older tag. pages = json.loads( - subprocess.check_output( - [ - "gh", - "api", - "--paginate", - "--slurp", - f"repos/{repository}/releases?per_page=100", - ], - text=True, + _retry_gh( + lambda: subprocess.check_output( + [ + "gh", + "api", + "--paginate", + "--slurp", + f"repos/{repository}/releases?per_page=100", + ], + text=True, + ), + label=f"gh release listing for {repository}", ) ) versions = [ @@ -278,23 +313,33 @@ def number(value: str) -> tuple[int, ...]: if len(wheels) != 1: raise RuntimeError("preceding release must contain exactly one LoopX wheel") with tempfile.TemporaryDirectory(prefix="loopx-previous-release-") as temporary: - directory = Path(temporary) - subprocess.run( - [ - "gh", - "release", - "download", - previous["tag_name"], - "--repo", - repository, - "--pattern", - wheels[0], - "--pattern", - "SHA256SUMS", - "--dir", - str(directory), - ], - check=True, + root = Path(temporary) + directory = root / "download" + + def reset_download_dir() -> None: + shutil.rmtree(directory, ignore_errors=True) + directory.mkdir(parents=True, exist_ok=True) + + _retry_gh( + lambda: subprocess.run( + [ + "gh", + "release", + "download", + previous["tag_name"], + "--repo", + repository, + "--pattern", + wheels[0], + "--pattern", + "SHA256SUMS", + "--dir", + str(directory), + ], + check=True, + ), + label=f"gh release download {previous['tag_name']}", + before_attempt=reset_download_dir, ) checksums = (directory / "SHA256SUMS").read_text().splitlines() matches = [ @@ -305,7 +350,7 @@ def number(value: str) -> tuple[int, ...]: ] if matches != [contract.digest(directory / wheels[0])]: raise RuntimeError("previous release wheel checksum mismatch") - old_bundle = directory / "chat" + old_bundle = root / "chat" extract_wheel(directory / wheels[0], old_bundle) build(old_bundle, install=True) diff --git a/tests/capabilities/test_capability_configuration_ui.py b/tests/capabilities/test_capability_configuration_ui.py index ab045c6bd1..3b4dac0d53 100644 --- a/tests/capabilities/test_capability_configuration_ui.py +++ b/tests/capabilities/test_capability_configuration_ui.py @@ -313,6 +313,58 @@ def test_steward_executor_editor_is_machine_only_and_typed() -> None: ) +def test_steward_executor_editor_documents_json_endpoint_models_and_preserves_catalog_values() -> None: + editor = capability_configuration_editor("steward_executor") + fields = {field["key"]: field for field in editor["fields"]} + assert "endpoint_models" not in fields + assert {field["input_kind"] for field in editor["fields"]} <= { + "boolean", + "number", + "select", + "string_list", + "text", + "periodic_report_schedule", + } + assert "endpoint_models" in fields["eligible_endpoints"]["description"] + assert "JSON mode" in fields["eligible_endpoints"]["description"] + assert "endpoint_models" in fields["executor_model"]["description"] + assert "JSON mode" in fields["executor_model"]["description"] + + configured = { + "schema_version": "steward_executor_machine_defaults_v1", + "selection_policy": "flexible", + "executor_endpoint": "codex", + "eligible_endpoints": ["codex", "antigravity"], + "executor_model": "gpt-6.2-sol", + "executor_reasoning_effort": "xhigh", + "endpoint_models": { + "antigravity": {"model": "carbon", "reasoning_effort": "medium"}, + }, + } + catalog = build_capability_configuration_catalog( + machine_namespaces=[ + { + "namespace": "steward_executor", + "title": "Steward executor", + "current": configured, + "configuration_template": { + "schema_version": "steward_executor_machine_defaults_v1", + "selection_policy": "preferred", + "executor_endpoint": "codex", + "eligible_endpoints": [], + "executor_model": None, + "executor_reasoning_effort": None, + }, + } + ] + ) + capability = catalog["capabilities"][0] + assert capability["machine_current"]["endpoint_models"] == { + "antigravity": {"model": "carbon", "reasoning_effort": "medium"}, + } + assert capability["effective_configuration"]["configuration"] == configured + + def test_catalog_merges_machine_and_goal_descriptors_without_losing_scope() -> None: catalog = build_capability_configuration_catalog( machine_namespaces=[ diff --git a/tests/presentation/test_chat_bundle.py b/tests/presentation/test_chat_bundle.py index e1df5858e0..d4b5f0a2b3 100644 --- a/tests/presentation/test_chat_bundle.py +++ b/tests/presentation/test_chat_bundle.py @@ -456,3 +456,92 @@ def test_runtime_source_root_fails_closed_without_valid_release_manifest(tmp_pat (tmp_path / "release.json").write_text(release_json, encoding="utf-8") assert runtime_source_root(tmp_path) == tmp_path.resolve() + + +def test_release_build_retries_transient_gh_errors_with_clean_download_dir(monkeypatch): + releases = [[{ + "tag_name": "v2.3.0", + "draft": False, + "prerelease": False, + "assets": [{"name": "loopx-2.3.0-py3-none-any.whl"}], + }]] + sleeps = [] + monkeypatch.setattr(builder.time, "sleep", sleeps.append) + + api_attempts = 0 + + def flaky_check_output(command, **kwargs): + nonlocal api_attempts + api_attempts += 1 + if api_attempts < 2: + raise subprocess.CalledProcessError(1, command, stderr="HTTP 500") + return json.dumps(releases) + + monkeypatch.setattr(builder.subprocess, "check_output", flaky_check_output) + + download_attempts = 0 + saw_partial_marker = [] + + def flaky_download(command, **kwargs): + nonlocal download_attempts + download_attempts += 1 + directory = Path(command[command.index("--dir") + 1]) + saw_partial_marker.append((directory / "partial.tmp").exists()) + if download_attempts < 4: + (directory / "partial.tmp").write_bytes(b"corrupt partial download") + raise subprocess.CalledProcessError(1, command) + wheel = directory / "loopx-2.3.0-py3-none-any.whl" + with zipfile.ZipFile(wheel, "w") as archive: + archive.writestr( + "loopx/web/chat/index.html", + '', + ) + archive.writestr("loopx/web/chat/assets/prev.js", "prev code") + (directory / "SHA256SUMS").write_text( + f"{builder.contract.digest(wheel)} {wheel.name}\n" + ) + + monkeypatch.setattr(builder.subprocess, "run", flaky_download) + builds = [] + monkeypatch.setattr( + builder, + "build", + lambda previous, **kwargs: builds.append((previous / "assets/prev.js").read_text()), + ) + + builder.release_build("v2.4.0", "fixture/repository") + + assert api_attempts == 2 + assert download_attempts == 4 + assert saw_partial_marker == [False, False, False, False] + assert sleeps == [1.0, 1.0, 2.0, 4.0] + assert builds == ["prev code"] + + +def test_release_build_exhausts_bounded_gh_download_retries(monkeypatch): + releases = [[{ + "tag_name": "v2.3.0", + "draft": False, + "prerelease": False, + "assets": [{"name": "loopx-2.3.0-py3-none-any.whl"}], + }]] + sleeps = [] + monkeypatch.setattr(builder.time, "sleep", sleeps.append) + monkeypatch.setattr( + builder.subprocess, "check_output", lambda *a, **k: json.dumps(releases) + ) + + download_attempts = 0 + + def always_fail(command, **kwargs): + nonlocal download_attempts + download_attempts += 1 + raise subprocess.CalledProcessError(1, command) + + monkeypatch.setattr(builder.subprocess, "run", always_fail) + + with pytest.raises(subprocess.CalledProcessError): + builder.release_build("v2.4.0", "fixture/repository") + + assert download_attempts == 4 + assert sleeps == [1.0, 2.0, 4.0] diff --git a/tests/test_antigravity_steward_adapter.py b/tests/test_antigravity_steward_adapter.py index c9623fb339..8e56ccad56 100644 --- a/tests/test_antigravity_steward_adapter.py +++ b/tests/test_antigravity_steward_adapter.py @@ -1753,3 +1753,63 @@ def guard(): result = adapter.start_turn("guarded turn") assert result["message"] == "Argon answer 1" assert events == [("guard_enter", 0), ("guard_exit", 1)] + + +def test_antigravity_endpoint_model_capacity_resolves_short_aliases_and_rejects_mismatches( + language_server, +) -> None: + from datetime import timedelta + + reset = (datetime.now(timezone.utc) + timedelta(days=7)).isoformat() + language_server["user_status_response"] = { + "userStatus": { + "email": "synthetic@invalid.example", + "cascadeModelConfigData": { + "clientModelConfigs": [ + { + "label": "Gemini 4 Argon (High)", + "modelOrAlias": {"model": "MODEL_PLACEHOLDER_M417"}, + "quotaInfo": {"remainingFraction": 0.42, "resetTime": reset}, + }, + { + "label": "Gemini 4 Carbon (High)", + "modelOrAlias": {"model": "MODEL_PLACEHOLDER_M427"}, + "quotaInfo": {"remainingFraction": 0.85, "resetTime": reset}, + }, + { + "label": "Gemini 4 Carbon (Medium)", + "modelOrAlias": {"model": "MODEL_PLACEHOLDER_M437"}, + "quotaInfo": {"remainingFraction": 0.0, "resetTime": reset}, + }, + ] + }, + } + } + + for alias, effort, expected_canonical, expected_fraction, expected_exhausted in [ + ("carbon", None, "gemini-4-carbon-high", 0.85, False), + ("CARBON", None, "gemini-4-carbon-high", 0.85, False), + ("gemini-4-carbon", None, "gemini-4-carbon-high", 0.85, False), + ("argon", None, "gemini-4-argon-high", 0.42, False), + ("gemini-4-argon", None, "gemini-4-argon-high", 0.42, False), + ("carbon", "medium", "gemini-4-carbon-medium", 0.0, True), + ]: + observed = AntigravityAdapter.endpoint_model_capacity( + model_id=alias, + reasoning_effort=effort, + ) + assert observed is not None, (alias, effort) + assert observed["model_id"] == expected_canonical + assert observed["remaining_fraction"] == expected_fraction + assert observed["quota_exhausted"] is expected_exhausted + assert observed["normal_completion"] is (not expected_exhausted) + + calls_before = len(language_server["calls"]) + assert AntigravityAdapter.endpoint_model_capacity(model_id="unknown-model") is None + assert AntigravityAdapter.endpoint_model_capacity( + model_id="gemini-4-carbon-high", reasoning_effort="medium", + ) is None + assert AntigravityAdapter.endpoint_model_capacity( + model_id="carbon", reasoning_effort="xhigh", + ) is None + assert len(language_server["calls"]) == calls_before diff --git a/tests/test_chat_machine_configuration_api.py b/tests/test_chat_machine_configuration_api.py index 6b903e1ced..3380e5a689 100644 --- a/tests/test_chat_machine_configuration_api.py +++ b/tests/test_chat_machine_configuration_api.py @@ -975,3 +975,68 @@ def request(method, path, body=None): server.shutdown() thread.join(timeout=5) server.server_close() + + +def test_steward_executor_endpoint_models_round_trip_through_machine_api(tmp_path: Path) -> None: + from loopx.chat_server import ChatHTTPServer, ChatRequestHandler + + server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler) + server.runtime_root = tmp_path + server.verbose = False + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + connection = http.client.HTTPConnection(*server.server_address, timeout=10) + + def request(method: str, path: str, body: dict[str, Any] | None = None) -> tuple[int, dict[str, Any]]: + connection.request( + method, + path, + body=json.dumps(body) if body is not None else None, + headers={"Content-Type": "application/json"}, + ) + response = connection.getresponse() + return response.status, json.loads(response.read()) + + try: + desired = { + "namespace": "steward_executor", + "namespace_configuration": { + "schema_version": "steward_executor_machine_defaults_v1", + "selection_policy": "flexible", + "executor_endpoint": "codex", + "eligible_endpoints": ["codex", "antigravity"], + "executor_model": "gpt-6.2-sol", + "executor_reasoning_effort": "xhigh", + "endpoint_models": { + "antigravity": {"model": "carbon", "reasoning_effort": "medium"}, + }, + }, + } + status, preview = request("POST", CHAT_MACHINE_CONFIGURATION_PREVIEW_PATH, desired) + assert status == 201, preview + status, applied = request( + "POST", + CHAT_MACHINE_CONFIGURATION_APPLY_PATH, + {**desired, "expected_plan_revision": preview["plan_revision"]}, + ) + assert status == 200 and applied["ok"] is True, applied + status, inspection = request("GET", CHAT_MACHINE_CONFIGURATION_PATH) + assert status == 200 + saved = inspection["machine_configuration"]["namespaces"]["steward_executor"] + assert saved["endpoint_models"] == { + "antigravity": {"model": "carbon", "reasoning_effort": "medium"}, + } + steward_cap = next( + item + for item in inspection["capability_catalog"]["capabilities"] + if item["capability_id"] == "steward_executor" + ) + assert steward_cap["configuration_editor"]["editable"] is True + fields = {field["key"]: field for field in steward_cap["configuration_editor"]["fields"]} + assert "endpoint_models" in fields["executor_model"]["description"] + assert applied["machine_configuration"]["namespaces"]["steward_executor"]["endpoint_models"] == saved["endpoint_models"] + finally: + connection.close() + server.shutdown() + thread.join(timeout=5) + server.server_close() diff --git a/tests/test_chat_manager_model_adoption.py b/tests/test_chat_manager_model_adoption.py index 6a603990d6..003be4f7c1 100644 --- a/tests/test_chat_manager_model_adoption.py +++ b/tests/test_chat_manager_model_adoption.py @@ -891,3 +891,107 @@ def steward_route(self, *, codex_home, primary, pool, current, primary_capacity, ], ) assert store.load_session(session["session_id"])["agent_id"] == "codex" + + +def test_codex_to_antigravity_failover_resolves_short_alias_endpoint_model(conversation, monkeypatch): + import sys + from datetime import datetime, timedelta, timezone + from types import ModuleType + from loopx.capabilities.native_chat import antigravity_adapter + from loopx.chat_manager import manager_session_quota_route + + root, store, runtime, session, _starts = conversation + store.update_session( + session["session_id"], + upstream_thread_id="codex-thread-1", + agent_model_id="gpt-6.2-sol", + agent_reasoning_effort="xhigh", + ) + + parent = ModuleType("loopx_codex_provider_routing") + module = ModuleType("loopx_codex_provider_routing.native") + + class Accounts: + def __init__(self, path): + assert path == runtime.coordination_runtime_root + + def model_transport(self, **_parameters): + return None + + def steward_route(self, *, codex_home, primary, pool, current, primary_capacity, + fallback_capacity=None, blocked_primary=None, model=None): + if fallback_capacity is None: + return {"endpoint": None, "blocked_primary": blocked_primary} + return {"endpoint": "antigravity", "blocked_primary": blocked_primary} + + module.NativeAccounts = Accounts + monkeypatch.setitem(sys.modules, parent.__name__, parent) + monkeypatch.setitem(sys.modules, module.__name__, module) + monkeypatch.setattr(runtime, "capabilities", lambda: [ + {"agent_id": "codex", "available": True}, + {"agent_id": "antigravity", "available": True}, + ]) + reset = (datetime.now(timezone.utc) + timedelta(days=1)).isoformat() + monkeypatch.setattr( + antigravity_adapter, + "discover_antigravity_language_server", + lambda **_kw: {"url": "http://127.0.0.1:4321", "csrf_token": "tok"}, + ) + monkeypatch.setattr( + antigravity_adapter, + "_rpc_post", + lambda _url, _tok, method, _payload, **_kw: { + "userStatus": { + "email": "synthetic@invalid.example", + "cascadeModelConfigData": { + "clientModelConfigs": [ + { + "label": "Gemini 4 Carbon (High)", + "modelOrAlias": {"model": "MODEL_PLACEHOLDER_M427"}, + "quotaInfo": {"remainingFraction": 0.91, "resetTime": reset}, + }, + { + "label": "Gemini 4 Carbon (Medium)", + "modelOrAlias": {"model": "MODEL_PLACEHOLDER_M437"}, + "quotaInfo": {"remainingFraction": 0.77, "resetTime": reset}, + }, + ] + }, + } + } if method == "GetUserStatus" else {}, + ) + + loaded = store.load_session(session["session_id"]) + + # Alias with explicit effort resolves to gemini-4-carbon-medium and passes quota route. + configure( + root, + model="gpt-6.2-sol", + effort="xhigh", + endpoint="codex", + policy="flexible", + endpoint_models={"antigravity": {"model": "carbon", "reasoning_effort": "medium"}}, + ) + routed_medium = manager_session_quota_route(runtime, loaded) + assert routed_medium is not None + alloc_medium = routed_medium["allocation"] + assert alloc_medium["executor_endpoint"] == "antigravity" + assert alloc_medium["allocation_reason"] == "flexible_availability_fallback" + assert alloc_medium["model"] == "carbon" + assert alloc_medium["reasoning_effort"] == "medium" + + # Alias without explicit effort defaults to high (gemini-4-carbon-high). + configure( + root, + model="gpt-6.2-sol", + effort="xhigh", + endpoint="codex", + policy="flexible", + endpoint_models={"antigravity": {"model": "carbon"}}, + ) + routed_high = manager_session_quota_route(runtime, loaded) + assert routed_high is not None + alloc_high = routed_high["allocation"] + assert alloc_high["executor_endpoint"] == "antigravity" + assert alloc_high["model"] == "carbon" + assert alloc_high["reasoning_effort"] == "high"