From d426ea1bea476576d4b8db48e91bcf736d25b5b2 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Wed, 11 Nov 2026 15:33:23 -0500 Subject: [PATCH] test(antigravity): exercise the adapter offline through the daemon --- robot-docs/testing.md | 8 + test/e2e/albedo_antigravity_offline.erl | 25 +++ test/e2e/antigravity_support.py | 158 ++++++++++++++ test/e2e/antigravity_test.py | 266 +++++++++++++++++++++++ test/e2e/areas.toml | 7 + test/e2e/fake_provider.py | 24 +- test/e2e/harness.py | 10 +- test/e2e/provider_events.py | 22 ++ test/harness/antigravity_offline_test.py | 78 +++++++ 9 files changed, 587 insertions(+), 11 deletions(-) create mode 100644 test/e2e/albedo_antigravity_offline.erl create mode 100644 test/e2e/antigravity_support.py create mode 100644 test/e2e/antigravity_test.py create mode 100644 test/harness/antigravity_offline_test.py diff --git a/robot-docs/testing.md b/robot-docs/testing.md index 1b446a8ee..bcc109a0c 100644 --- a/robot-docs/testing.md +++ b/robot-docs/testing.md @@ -12,6 +12,14 @@ [test/e2e/harness.py](../test/e2e/harness.py) owns test daemons and fixtures. `peer_daemon(name, prepare=None)` starts a separate daemon for a test. `finish_test` cleans up peers and registered resources. Use the shared harness for daemon scenarios. See [storage migrations](migrations.md) for upgrade coverage. +## Offline Antigravity scenarios + +[`antigravity_test.py`](../test/e2e/antigravity_test.py) drives the real adapter through a private copy of the runner's sealed daemon. The [fixture](../test/e2e/antigravity_support.py) replaces native transport modules in that copy and reseals it before boot. Production endpoints and profile settings remain unchanged. + +The [route guard](../test/e2e/albedo_antigravity_offline.erl) accepts only the exact inference URL, the dummy bearer token, and the fixture's marked home. The compiled destination is a numeric route on the loopback fake provider. Other streaming destinations and non-streaming provider HTTP calls are refused. The [safety probe](../test/harness/antigravity_offline_test.py) checks refusals before socket acquisition, including malformed headers. + +Run `nix develop -c python3 test/e2e/run.py antigravity_test.py` for adapter scenarios. They cover tool execution, title-request separation, usage, restart replay, cancellation, and conditional signature fallback. Fixture signatures check preservation, not Google's cryptographic validation. OAuth, Google TLS, live quotas and acceptance of genuine signatures require separate live checks. + ## Related pages - [All topics](README.md) diff --git a/test/e2e/albedo_antigravity_offline.erl b/test/e2e/albedo_antigravity_offline.erl new file mode 100644 index 000000000..396ef7717 --- /dev/null +++ b/test/e2e/albedo_antigravity_offline.erl @@ -0,0 +1,25 @@ +-module(albedo_antigravity_offline). +-export([route/4]). + +%% Only the private snapshot calls this module. Neither the destination nor +%% the permitted home is supplied by a provider profile or environment flag. +route(<<"https://daily-cloudcode-pa.googleapis.com/v1internal:streamGenerateContent?alt=sse">>, + Headers, Target, Home) -> + Tokens = [Value || {Name, Value} <- Headers, string:lowercase(Name) =:= <<"authorization">>], + case Tokens =:= [<<"Bearer fixture-antigravity">>] andalso valid_target(Target) + andalso os:getenv("ALBEDO_HOME") =:= binary_to_list(Home) + andalso file:read_file(filename:join(binary_to_list(Home), ".antigravity-offline")) + =:= {ok, <<"offline fixture\n">>} of + true -> <>; + false -> <<>> + end; +route(_, _, _, _) -> <<>>. + +valid_target(Target) -> + try uri_string:parse(Target) of + #{scheme := <<"http">>, host := <<"127.0.0.1">>, port := Port, path := Path} = Parts -> + lists:sort(maps:keys(Parts)) =:= [host, path, port, scheme] + andalso Port > 0 andalso Port < 65536 + andalso re:run(Path, <<"^/t/[0-9]+$">>, [{capture, none}]) =:= match; + _ -> false + catch _:_ -> false end. diff --git a/test/e2e/antigravity_support.py b/test/e2e/antigravity_support.py new file mode 100644 index 000000000..f73e0f7b6 --- /dev/null +++ b/test/e2e/antigravity_support.py @@ -0,0 +1,158 @@ +"""Private, fail-closed transport build for real Antigravity adapter scenarios. + +The runner still owns startup and teardown. Only its copied native transport +is redirected; production source, profiles and endpoint policy are unchanged. +""" + +import json +from pathlib import Path +import re +import shlex +import shutil +import subprocess + +from harness import Albedo, Provider, ROOT + +ENDPOINT = "https://daily-cloudcode-pa.googleapis.com" +INFERENCE = ENDPOINT + "/v1internal:streamGenerateContent?alt=sse" +TOKEN = "fixture-antigravity" +SIGNATURE = "Zml4dHVyZS1zaWduYXR1cmU=" +GEMINI = "gemini-3-flash" +CLAUDE = "claude-opus-5-5" +GUARD = Path(__file__).with_name("albedo_antigravity_offline.erl") + +# No inets entry point in the private build can contact a provider. Retain +# the production exports so an added front door fails fixture setup. +HTTP_STUB = """-module(albedo_http). +-export([get/4, post/6, request/6, fetch/4, failure/3, tls_options/1, locations/2]). +get(U, H, T, C) -> request(get, U, H, none, T, C). +post(U, H, K, B, T, C) -> request(post, U, H, {K, B}, T, C). +request(_, _, _, _, _, _) -> {error, offline_fixture}. +fetch(_, _, _, _) -> {error, <<"offline fixture">>}. +failure(_, _, _) -> <<"offline fixture">>. +tls_options(_) -> error(offline_fixture). +locations(Urls, _) -> Urls. +""" + + +def compile_offline(ebin: Path, source: Path, home: Path, target: str) -> None: + """Compile replacements without touching the checkout or a running VM.""" + route = re.fullmatch(r"http://127\.0\.0\.1:([0-9]+)/t/[0-9]+", target) + if not home.is_absolute() or route is None or not 0 < int(route[1]) < 65536: + raise ValueError("offline fixture requires an absolute home and loopback route") + transport = (ROOT / "src/albedo/openai_api/albedo_openai_transport.erl").read_text() + marker = "open_valid_headers(Method, URL, Headers, Body, Timeout) ->\n case parse_url(URL) of" + if transport.count(marker) != 1: + raise AssertionError("stream transport interception point changed") + + def literal(value: str) -> str: + return "<<" + ",".join(str(byte) for byte in value.encode()) + ">>" + + routed = f"albedo_antigravity_offline:route(URL, Headers, {literal(target)}, {literal(str(home))})" + source.mkdir() + (source / "albedo_openai_transport.erl").write_text( + transport.replace( + marker, marker.replace("parse_url(URL)", f"parse_url({routed})") + ) + ) + original = (ROOT / "src/albedo/harness/albedo_http.erl").read_text() + + def exports(text: str) -> set[str]: + return set( + re.findall( + r"\b[a-z_]+/[0-9]+", text.split("-export([", 1)[1].split("]).", 1)[0] + ) + ) + + if exports(original) != exports(HTTP_STUB): + raise AssertionError("non-streaming HTTP exports changed") + (source / "albedo_http.erl").write_text(HTTP_STUB) + subprocess.run( + [ + "erlc", + "-Wall", + "-Werror", + "-o", + str(ebin), + str(GUARD), + *map(str, source.glob("*.erl")), + ], + check=True, + text=True, + ) + + +def prepare(app: Albedo, provider: Provider) -> None: + """Install a sealed private build and dummy accounts before exclusive boot.""" + if app.daemon.concurrent or app.daemon.booted: + raise AssertionError("Antigravity fixture requires a fresh exclusive daemon") + original = Path(app.env["ALBEDO_DAEMON"]).parent + for module in ["albedo_openai_transport", "albedo_http"]: + built = ROOT / f"build/dev/erlang/albedo/ebin/{module}.beam" + if (original / f"albedo/ebin/{module}.beam").read_bytes() != built.read_bytes(): + raise AssertionError("snapshot differs from the current daemon build") + snapshot = app.root / "antigravity-daemon" + shutil.copytree(original, snapshot) + ebin = snapshot / "albedo/ebin" + ebin.chmod(ebin.stat().st_mode | 0o200) + for module in ["albedo_openai_transport", "albedo_http"]: + (ebin / f"{module}.beam").unlink() + (app.home / ".antigravity-offline").write_text("offline fixture\n") + compile_offline(ebin, app.root / "offline-source", app.home, provider.url) + subprocess.run( + [ + str(ROOT / "priv/bin/albedo-daemon"), + "erl", + "-pa", + *map(str, snapshot.glob("*/ebin")), + "-noshell", + "-eval", + 'application:ensure_all_started(crypto), ok = albedo_daemon:seal_build(unicode:characters_to_binary(os:getenv("ALBEDO_BUILD_APP"))), halt().', + ], + check=True, + capture_output=True, + text=True, + env={**app.env, "ALBEDO_BUILD_APP": str(snapshot / "albedo")}, + ) + launcher = snapshot / "albedo-daemon" + launcher.write_text( + "#!/bin/sh\nset -eu\n" + f'test "${{ALBEDO_HOME-}}" = {shlex.quote(str(app.home))}\n' + f"exec {shlex.quote(str(ROOT / 'priv/bin/albedo-daemon'))} erl -pa {shlex.quote(str(snapshot))}/*/ebin -eval 'albedo@@main:run(albedo)' -noshell -extra \"$@\"\n" + ) + launcher.chmod(0o700) + app.env.update(ALBEDO_DAEMON=str(launcher), ALBEDO_STANDBY="0") + app.write_extensions({"quota": {"enabled": False}}) + app.store_secrets( + "accounts", + { + "google-antigravity": [ + { + "type": "oauth", + "access": TOKEN, + "refresh": "fixture-refresh", + "expires": 9999999999999, + "projectId": "fixture-project", + "email": "fixture@example.invalid", + } + ] + }, + ) + (app.home / "antigravity.json").write_text( + json.dumps( + { + "version": "2.16.0", + "models": [ + { + "id": name, + "name": name, + "context": 200000, + "output": 8192, + "images": True, + } + for name in [GEMINI, CLAUDE + "-low", CLAUDE + "-high"] + ], + "renamed": {}, + } + ) + ) diff --git a/test/e2e/antigravity_test.py b/test/e2e/antigravity_test.py new file mode 100644 index 000000000..020dd0084 --- /dev/null +++ b/test/e2e/antigravity_test.py @@ -0,0 +1,266 @@ +"""Drive Antigravity's real adapter, signed replay and conditional HTTP resend. + +Only native network destinations change in a private sealed test snapshot. +Fake signatures check preservation, not Google's signature validation or OAuth. +""" + +from contextlib import closing +import json +import sqlite3 +import unittest +from typing import Any + +import antigravity_support as offline +from harness import Albedo, Provider, Reply, error, exclusive, python, text, wait_until +from provider_events import antigravity_events + +CODE = "print(6 * 7)" + + +def parts(record: dict[str, Any]) -> list[dict[str, Any]]: + return [ + part + for content in record["request"]["request"]["contents"] + for part in content["parts"] + ] + + +@exclusive +class AntigravityTests(unittest.TestCase): + def start( + self, replies: list[Reply], *, model: str = offline.CLAUDE + ) -> tuple[Albedo, Provider]: + provider = Provider(lambda _: replies) + provider.title_script = lambda request: text("Arithmetic") + self.addCleanup(provider.close) + app = Albedo( + provider, + providers={ + "ag": { + "extension": "antigravity", + "model": model, + "protocol": "chat_completions", + **({"effort": "low"} if model == offline.CLAUDE else {}), + } + }, + prepare=lambda app: offline.prepare(app, provider), + ) + app.__enter__() + self.addCleanup(app.__exit__, None, None, None) + return app, provider + + def turn( + self, app: Albedo, session: str, message: str = "calculate" + ) -> dict[str, Any]: + app.prompt(session, message).close() + state = app.idle(session) + self.assertFalse( + [line for line in state["activity"]["lines"] if line["kind"] == "error"], + state, + ) + return state + + def high_effort(self, app: Albedo, session: str) -> None: + route = f"/sessions/{session}?view=configuration" + with app.api(route) as response: + response.read() + etag = response.headers["ETag"] + with app.api( + route, {"effort": "high"}, method="PATCH", headers={"If-Match": etag} + ) as response: + response.read() + + def test_tool_turn_replays_signed_parts_after_restart(self) -> None: + events = list(antigravity_events(text("the answer is 42"), "{}", "unused", 20)) + events[-1]["response"]["usageMetadata"] = { + "promptTokenCount": 1200, + "candidatesTokenCount": 34, + "thoughtsTokenCount": 7, + "cachedContentTokenCount": 900, + "totalTokenCount": 1241, + "cost": 999, + } + app, provider = self.start( + [ + python(CODE, reasoning="multiply first"), + Reply("text", events=events), + text("still 42"), + ], + model=offline.GEMINI, + ) + session = app.session() + state = self.turn(app, session) + shown = [(line["kind"], line["text"]) for line in state["activity"]["lines"]] + self.assertIn(("thinking", "multiply first"), shown) + self.assertIn(("assistant", "the answer is 42"), shown) + self.assertFalse( + any( + kind == "assistant" and "multiply first" in value + for kind, value in shown + ) + ) + wait_until( + lambda: len(provider.title_requests) == 1, 10, "title request missing" + ) + wait_until( + lambda: self.session_name(app, session) == "Arithmetic", + 10, + "title not applied", + ) + self.assertEqual(len(provider.requests), 2) + first = provider.requests[0] + self.assertEqual(first["model"], offline.GEMINI) + self.assertEqual(first["authorization"], "Bearer " + offline.TOKEN) + self.assertTrue( + first["path"].endswith("/v1internal:streamGenerateContent?alt=sse") + ) + self.assertEqual(first["request"]["project"], "fixture-project") + self.assertEqual(first["request"]["requestType"], "agent") + declarations = first["request"]["request"]["tools"][0]["functionDeclarations"] + self.assertIn("python", [tool["name"] for tool in declarations]) + replay = parts(provider.requests[1]) + signed = [part for part in replay if "functionCall" in part] + self.assertEqual(signed[0]["thoughtSignature"], offline.SIGNATURE) + self.assertTrue( + any("42" in json.dumps(part.get("functionResponse", {})) for part in replay) + ) + history = app.history(session) + self.assertIn("multiply first", json.dumps(history)) + self.assertIn("the answer is 42", json.dumps(history)) + with app.api(f"/sessions/{session}/context?view=requests") as response: + rows = [ + row for row in json.load(response)["items"] if row["kind"] == "turn" + ] + final = rows[-1] + self.assertEqual(final["provider_profile"], "ag") + self.assertEqual(final["account_id"], "fixture@example.invalid") + self.assertEqual(final["provider"], "chat_completions:" + offline.ENDPOINT) + for field, expected in [ + ("prompt_tokens", 1200), + ("completion_tokens", 41), + ("cached_tokens", 900), + ("reasoning_tokens", 7), + ("total_tokens", 1241), + ]: + self.assertEqual(final[field]["observed"], expected, field) + self.assertEqual( + (final["response_id"], final["model_version"], final["trace_id"]), + ("fixture-response", "fixture-served", "fixture-trace"), + ) + with closing( + sqlite3.connect(f"file:{app.home / 'albedo.sqlite'}?mode=ro", uri=True) + ) as db: + self.assertEqual( + db.execute( + "SELECT DISTINCT cost FROM provider_requests WHERE session=?", + (session,), + ).fetchall(), + [(None,)], + ) + app.restart() + self.turn(app, session, "again") + self.assertEqual(len(provider.requests), 3) + replayed = [ + part for part in parts(provider.requests[2]) if "functionCall" in part + ] + self.assertEqual(replayed, signed) + self.assertEqual(len(provider.title_requests), 1) + + def session_name(self, app: Albedo, session: str) -> str: + with app.api(f"/sessions/{session}?tail=0") as response: + return json.load(response)["name"] + + def test_cross_effort_signature_refusal_resends_once_portably(self) -> None: + app, provider = self.start( + [ + python(CODE, reasoning="signed thought"), + text("42"), + error(400, "invalid thought signature"), + text("portable retry accepted"), + ] + ) + session = app.session(name="signature fallback") + self.turn(app, session) + self.high_effort(app, session) + self.turn(app, session, "use high effort") + self.assertEqual(len(provider.requests), 4) + first, retry = provider.requests[2:] + self.assertEqual(first["model"], offline.CLAUDE + "-high") + self.assertEqual(retry["model"], first["model"]) + self.assertTrue( + any( + part.get("thoughtSignature") == offline.SIGNATURE + for part in parts(first) + ) + ) + self.assertFalse(any("thoughtSignature" in part for part in parts(retry))) + self.assertTrue(any("functionCall" in part for part in parts(retry))) + self.assertTrue( + any( + "42" in json.dumps(part.get("functionResponse", {})) + for part in parts(retry) + ) + ) + self.assertEqual(retry["authorization"], first["authorization"]) + + def test_same_variant_signature_refusal_does_not_resend(self) -> None: + app, provider = self.start( + [python(CODE), text("42"), error(400, "invalid thought signature")] + ) + session = app.session(name="same variant") + self.turn(app, session) + app.prompt(session, "refuse this request").close() + state = app.idle(session) + self.assertEqual(len(provider.requests), 3) + self.assertIn("invalid thought signature", json.dumps(state)) + + def test_unrelated_refusal_does_not_resend(self) -> None: + app, provider = self.start( + [python(CODE), text("42"), error(400, "invalid request")] + ) + session = app.session(name="unrelated refusal") + self.turn(app, session) + self.high_effort(app, session) + app.prompt(session, "refuse this request").close() + state = app.idle(session) + self.assertEqual(len(provider.requests), 3) + self.assertIn("invalid request", json.dumps(state)) + + def test_portable_retry_refusal_stops_after_two_attempts(self) -> None: + app, provider = self.start( + [ + python(CODE), + text("42"), + error(400, "invalid thought signature"), + error(400, "invalid thought signature"), + ] + ) + session = app.session(name="refused retry") + self.turn(app, session) + self.high_effort(app, session) + app.prompt(session, "refuse both attempts").close() + state = app.idle(session) + self.assertEqual(len(provider.requests), 4) + self.assertIn("invalid thought signature", json.dumps(state)) + + def test_interrupt_cancels_the_provider_request(self) -> None: + app, provider = self.start([Reply("text", hang=True)]) + session = app.session(name="cancel streaming") + app.prompt(session, "wait for a reply").close() + wait_until(lambda: len(provider.requests) == 1, 10, "provider request missing") + with app.api(f"/sessions/{session}?tail=0") as response: + state = json.load(response) + with app.api( + f"/sessions/{session}/interrupt", + { + "run_id": state["status"]["run_id"], + "through_input_order": state["input_order"], + }, + ): + pass + app.idle(session) + with app.api(f"/sessions/{session}/context?view=requests") as response: + rows = json.load(response)["items"] + self.assertEqual(rows[-1]["outcome"], "failed") + self.assertEqual(rows[-1]["failure"]["detail"], "Cancelled") + self.assertEqual(len(provider.requests), 1) diff --git a/test/e2e/areas.toml b/test/e2e/areas.toml index 8d47af86d..3ef776297 100644 --- a/test/e2e/areas.toml +++ b/test/e2e/areas.toml @@ -55,5 +55,12 @@ "src/albedo/anthropic_api/**" = ["github_copilot_test.py", "output_ceiling_test.py", "provider_protocols_test.py"] "src/albedo/gemini_api/**" = ["integration_test.py", "context_test.py", "prompt_test.py", "provider_protocols_test.py"] "src/albedo/openai_api/bridge.gleam" = ["github_copilot_test.py", "provider_protocols_test.py"] +"src/albedo/harness/extensions/antigravity/**" = ["antigravity_test.py", "integration_test.py", "context_test.py", "prompt_test.py"] +"src/albedo/openai_api/albedo_openai_transport.erl" = ["antigravity_test.py", "provider_protocols_test.py", "integration_test.py", "context_test.py", "prompt_test.py"] +"src/albedo/harness/albedo_http.erl" = ["antigravity_test.py", "integration_test.py", "context_test.py", "prompt_test.py"] "src/albedo/harness/**" = ["integration_test.py", "context_test.py", "prompt_test.py"] +"test/e2e/antigravity*" = ["antigravity_test.py"] +"test/e2e/albedo_antigravity_offline.erl" = ["antigravity_test.py"] +"test/e2e/fake_provider.py" = ["antigravity_test.py", "provider_protocols_test.py", "integration_test.py", "context_test.py", "prompt_test.py", "output_ceiling_test.py", "key_endpoints_test.py"] +"test/e2e/provider_events.py" = ["antigravity_test.py", "provider_protocols_test.py", "integration_test.py", "context_test.py", "prompt_test.py", "output_ceiling_test.py", "key_endpoints_test.py"] "test/e2e/*.py" = [] diff --git a/test/e2e/fake_provider.py b/test/e2e/fake_provider.py index e2c1266a3..9b5112878 100644 --- a/test/e2e/fake_provider.py +++ b/test/e2e/fake_provider.py @@ -1,4 +1,4 @@ -"""A scripted fake model provider that serves four streaming wire formats. +"""A scripted fake model provider for real-daemon tests. A provider's script receives each decoded request and returns ``text(...)``, ``python(...)``, ``error(...)``, or a custom ``Reply``; ``Provider(catalog=...)`` @@ -16,8 +16,9 @@ review):: python3 test/e2e/fake_provider.py script.py [--port N] ``script.py`` defines ``script(request)`` and may define ``catalog``. The base -URL printed is what the daemon's provider ``baseUrl`` takes. Cloud Code Assist -envelopes, Bedrock binary streams, and Mistral thinking chunks are unsupported. +URL printed is what the daemon's provider ``baseUrl`` takes. Antigravity Cloud +Code Assist envelopes are also supported. Bedrock binary streams and Mistral +thinking chunks are unsupported. """ from __future__ import annotations @@ -35,6 +36,7 @@ import time from typing import Literal from provider_events import ( + antigravity_events, chat_events, gemini_events, messages_events, @@ -46,6 +48,7 @@ from provider_events import ( # format: its chunks are wrapped in a service envelope. GEMINI_PATH = re.compile(r"/models/([^/:]+):streamGenerateContent$") EVENTS = { + "antigravity": antigravity_events, "chat": chat_events, "responses": responses_events, "messages": messages_events, @@ -63,9 +66,16 @@ def gemini_model(path: str) -> str | None: return match.group(1) if match else None -def wire_format(path: str) -> Literal["chat", "messages", "gemini", "responses"]: +def wire_format( + path: str, +) -> Literal["chat", "messages", "gemini", "responses", "antigravity"]: """The stream format of the endpoint a request reached.""" - route = path.partition("?")[0] + route, _, query = path.partition("?") + if ( + re.fullmatch(r"/t/[0-9]+/v1internal:streamGenerateContent", route) + and query == "alt=sse" + ): + return "antigravity" if route.endswith("chat/completions"): return "chat" if route.endswith("/messages"): @@ -236,7 +246,9 @@ class Provider: "model": gemini_model(self.path) or request.get("model"), "request": request, } - title = title_input(request) + title = title_input( + request.get("request", {}) if wire == "antigravity" else request + ) with owner._lock: recorded = owner.title_requests if title is not None else owner.requests recorded.append(record) diff --git a/test/e2e/harness.py b/test/e2e/harness.py index 0cd469f3a..90770359d 100644 --- a/test/e2e/harness.py +++ b/test/e2e/harness.py @@ -2,12 +2,12 @@ A provider is a scripted model (``fake_provider.py``, re-exported here): its callback receives each decoded request and returns ``text(...)``, -``python(...)``, ``error(...)``, or a custom ``Reply``. Four streaming wire +``python(...)``, ``error(...)``, or a custom ``Reply``. Streaming wire formats are served, picked by the request path: Chat Completions, OpenAI -Responses, Anthropic Messages, and Gemini ``generateContent``. That covers -the shared wire formats, not provider-specific authentication or service -behaviour. ``Provider(catalog=...)`` also serves -a local models catalog. ``Albedo`` gives each fixture a separate workspace and +Responses, Anthropic Messages, Gemini ``generateContent`` and Cloud Code Assist. +The Antigravity scenarios use a guarded private transport snapshot. Shared +protocol tests do not establish provider authentication or service behaviour. +``Provider(catalog=...)`` also serves a local models catalog. ``Albedo`` gives each fixture a separate workspace and provider route on one shared HTTP server, on the daemon the runner gave its test. Tests share one daemon and keep to their own profile; an ``@exclusive`` test, which may change global settings or restart the daemon, gets a fresh one diff --git a/test/e2e/provider_events.py b/test/e2e/provider_events.py index 1c3374fc9..6d2307ede 100644 --- a/test/e2e/provider_events.py +++ b/test/e2e/provider_events.py @@ -1,6 +1,13 @@ """Scripted upstream events for real-daemon workflows. No daemon wire fixtures.""" +from __future__ import annotations + +from collections.abc import Iterator import json +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from fake_provider import Reply def chat_events(reply, arguments, call_id, chunk_size): @@ -264,3 +271,18 @@ def gemini_events(reply, arguments, call_id, chunk_size): "totalTokenCount": prompt + answer, } yield last + + +def antigravity_events( + reply: Reply, arguments: str, call_id: str, chunk_size: int +) -> Iterator[dict[str, Any]]: + """Cloud Code Assist wraps Gemini chunks and carries service identity.""" + for chunk in gemini_events(reply, arguments, call_id, chunk_size): + yield { + "response": { + **chunk, + "responseId": "fixture-response", + "modelVersion": "fixture-served", + }, + "traceId": "fixture-trace", + } diff --git a/test/harness/antigravity_offline_test.py b/test/harness/antigravity_offline_test.py new file mode 100644 index 000000000..514e2b70c --- /dev/null +++ b/test/harness/antigravity_offline_test.py @@ -0,0 +1,78 @@ +"""The private transport must refuse credentials and destinations before I/O. + +Daemon scenarios only send valid fixture requests. These probes exercise the +replacement transport itself, including unchanged production header validation. +""" + +import json +from pathlib import Path +import socket +import subprocess +import sys +import tempfile +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "e2e")) +from antigravity_support import INFERENCE, compile_offline + + +class AntigravityOfflineTests(unittest.TestCase): + def test_only_the_dummy_token_exact_route_and_private_home_are_allowed( + self, + ) -> None: + with tempfile.TemporaryDirectory() as temporary, socket.socket() as listener: + root = Path(temporary) + home = root / "home" + home.mkdir() + (home / ".antigravity-offline").write_text("offline fixture\n") + listener.bind(("127.0.0.1", 0)) + listener.listen() + listener.setblocking(False) + target = f"http://127.0.0.1:{listener.getsockname()[1]}/t/1" + compile_offline(root, root / "source", home, target) + + def literal(value: str) -> str: + return f"<<{json.dumps(value)}>>" + + probe = f""" + URL = {literal(INFERENCE)}, Target = {literal(target)}, Home = {literal(str(home))}, + Good = [{{<<"authorization">>, <<"Bearer fixture-antigravity">>}}], + true = os:putenv("ALBEDO_HOME", binary_to_list(Home)), + Expected = <>, + Expected = albedo_antigravity_offline:route(URL, Good, Target, Home), + Wrong = [{{<<"authorization">>, <<"Bearer not-a-credential">>}}], + Duplicate = Good ++ Wrong, + lists:foreach(fun(Headers) -> + <<>> = albedo_antigravity_offline:route(URL, Headers, Target, Home), + {{error, invalid_url}} = albedo_openai_transport:open(URL, Headers, <<>>, 100) + end, [[], Wrong, Duplicate]), + {{error, invalid_headers}} = albedo_openai_transport:open(URL, + [{{<<"x-test">>, <<"bad", 13, 10, "header">>}} | Good], <<>>, 100), + {{error, invalid_url}} = albedo_openai_transport:open(<<"https://example.invalid/">>, Good, <<>>, 100), + lists:foreach(fun(Bad) -> + <<>> = albedo_antigravity_offline:route(URL, Good, Bad, Home) + end, [<<"https://127.0.0.1:80/t/1">>, <<"http://localhost:80/t/1">>, + <<"http://127.0.0.1:0/t/1">>, <<"http://127.0.0.1:65536/t/1">>, + <<"http://user@127.0.0.1:80/t/1">>, <>, + <>, <>]), + true = os:putenv("ALBEDO_HOME", "not-the-fixture-home"), + <<>> = albedo_antigravity_offline:route(URL, Good, Target, Home), + true = os:putenv("ALBEDO_HOME", binary_to_list(Home)), + ok = file:delete(filename:join(binary_to_list(Home), ".antigravity-offline")), + <<>> = albedo_antigravity_offline:route(URL, Good, Target, Home), + {{error, offline_fixture}} = albedo_http:request(get, URL, [], none, 100, 100), + halt(). + """ + result = subprocess.run( + ["erl", "+S", "2:2", "-pa", str(root), "-noshell", "-eval", probe], + capture_output=True, + text=True, + timeout=20, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + with self.assertRaises(BlockingIOError): + listener.accept() + + +if __name__ == "__main__": + unittest.main() -- knotmirror 0.0.1